Skip to content
Permalink
1b342361ed
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
35 lines (31 sloc) 1.67 KB
import paho.mqtt.client as mqtt #necessary imports
import json, os
from datetime import date, datetime
import time
""" callback function for connection """
def on_connect(client, userdata, flags, rc): #client method to connect
if rc==0:
client.connected_flag = True #set flag
print("connected OK Returned code=",rc) #let us know 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) #if we can't connect
""" callback function for messages received """
def on_message(client, userdata, msg):
topic=msg.topic
try:
data=json.loads(msg.payload.decode("utf8")) #decode the message
day=date.today() #time function
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)))
#print device, latitude and longitude from the message; add time data
print(str(data), 0) #print the entire message just for fun
except:
print("can not decode datat on topic(0)")
client=mqtt.Client() #define the client class
client.on_connect=on_connect
client.on_message=on_message
client.connect("broker.hivemq.com", 1883)
client.loop_forever()