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 #necessary imports
import json, os
from datetime import date, datetime
import time
def on_log(client, userdata,level, buf): #log the subscriber considering the buffer
print(buf)
""" Connect callback function """
def on_connect(client, userdata, flags,rc):
if rc==0
client.connected_flag=True #set the flag
print("connected OK Returned code =",rc) #let us know that we connected to the broker
client.subscribe("owntracks/KS/#) #we are connected, so subscribe to the topic, wildcard means any device
print("rc")
else:
print("Bad connection Returned code=", rc)
print("client disconnected ok")
""" callback function for messaged published """
def on_publish(client, userdata, mid):
print("in on_pub callback = ", mid)
""" callback function for Subscribing """
def on_subscribe(client, userdata, mid, granted_qos):
print("subscribed")
""" callback function for client disconnected """
def on_disconnect(client, userdata, rc):
print("client disconnected OK")
""" callback function for messages received """
def on_message(client, userdata, msg, mid) #client method to get messages from topic
topic=msg.topic #to be used when we can't decode
try:
data=json.loads.payload.decode("utf8") #decode message
day=date.today() #time functions
clock=datetime.now()
time=datetime.time(clock)
print("TID={0} is currently at {1}. {2}. {3}, {4}", format(data['tid'], data['lat'], data['lon'], str(day), str(time)), mid)
#print device, latitude and longtitude from the message, add time data
print(str(data))
except:
print("Cannot decode data on topic(0)".format(topic))
def reset():
ret=publish("house/temperature1", "", 0, True)
mqtt.Client.connected_flag=False #create the flag in the class
client=mqtt.Client()
cliet.on_log=on_log
client.on_connect=on_connect
client.on_disconnect=on_disconnect
client.on_publish=on_publish
client.connect("boker.hivemq.com", 1883) #connect to the broker on the appropriate port
client.on_loop_start()
while not client.connected_flag #wait in loop
print("in wait loop")
time.sleep(1)
print("publishing")
ret=client.publish("house/temperature1", "Test Message 0", 0)
print("publish return=", ret)
time.sleep(3)
ret=client.publish("house/temperature1", "Test Message 1", 1)
print("publish return=", ret)
time.sleep(3)
ret=client.publish("house/temperature1", "Test Message 2", 2)
print("publish return=", ret)
time.sleep(3)
client.subscribe("house/temperature1",2)
time.sleep(10)
client.loop_stop()
client.disconnect()