Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Cartrax/Security_Sensor.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
54 lines (41 sloc)
1.81 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import paho.mqtt.client as mqtt | |
import json, os | |
from random import uniform | |
from datetime import date, datetime | |
import time | |
from time import strftime | |
def logging(client_id): # logs | |
f = open("systemlog.txt", "a") | |
x = datetime.datetime.now() | |
string = f"{x} | {client_id}" | |
f.write(string) | |
f.close() | |
#open and read the file after the appending: | |
f = open("demofile2.txt", "r") | |
print(f.read()) | |
def on_log(client, userdata, level, buf): #log the subscriber considering the buffer | |
print("Log: ",buf) | |
def on_publish(client, userdata, mid): | |
print("Data published \n") | |
print("Published ", mid) #print the message id of the publisher | |
pass | |
# The callback for when the client receives a CONNACK response from the server. | |
def on_connect(client, userdata, flags, rc): | |
if rc == 0: | |
client.connected_flag = True #set the flag to true once connected | |
print("Connected with result code "+str(rc)) #check to know if we are connected to broker | |
else: | |
print("Bad connection, returned code= ", rc) #if connection failed | |
print("client disconnected ok") | |
def on_disconnect(client, userdata, rc): | |
print("Client disconnected") | |
client.connected_flag = False #set flag to false if disconnected | |
time.sleep(1) #wait before retrying connection | |
client.reconnect() #attempt reconnection | |
client1 = mqtt.Client("Thermometer") # Create an MQTT client object | |
client1.connect("broker.hivemq.com", 1883) | |
client1.on_publish = on_publish | |
client1.on_log = on_log #set log function to print the messages | |
#client1.on_message = on_message #assign the on_messsage function | |
client1.on_connect = on_connect #assign the on_connect function to the callback attribute | |
client1.on_disconnect = on_disconnect |