Skip to content
Permalink
main
Switch branches/tags

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?
Go to file
 
 
Cannot retrieve contributors at this time
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
def on_message(client, userdata, msg): #callback function for message recieved
# 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):
if rc== 0:
client.connected_flag = true #set flag to true once connected
print("Connected with result code "+str(rc) ) #check for connection
client.subscribe("cartrax/location/data") #subscribe to desired topics
client.subscribe("cartrax/moisture_sensor/data")
client.subscribe("cartrax/temperature_sensor/data")
client.subscribe("cartrax/security/data")
client.subscribe("cartrax/speedometer/data")
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 dosconnected
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
client1.loop_start() #start MQTT loop
#example of publishing a message
while true:
data = {"temperature": 25.5, "humidity": 60} #sample data to be published
client1.publish ("cartrax/temperature_sensor/data" json.dumps(data)) #publish data to specified topic
time.sleep(5) #publish data every 5 seconds (for demonstration purposes)