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
95 lines (69 sloc) 3.15 KB
import paho.mqtt.client as mqtt #necessary imports
import json, os
from datetime import date, datetime
import time
import sys
import sqlite3 as sql
print("Hello, Visual Studio")
""" 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
def on_disconnect(client, userdata, rc):
print("client disconnected ok")
#def on_publish(client, userdata, mid):
# print("In on_pub callback mid= " + str(mid))
def on_subscribe(client,userdata,mid,qos):
print("in on subscribe callback result "+str(mid))
#for t in topic_ack:
# if t[1]==mid:
# t[2]=1 #set acknowledged flag
# print("subscription acknowledged "+t[0])
# client.suback_flag=True
# client.loop_stop()
""" callback function for messages received """
def on_message( client, userdata, msg ): #client method to get messages from topic
topic = msg.topic #for use when we can't decode
try:
data = json.loads(msg.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)))
#print device, latitude and longitude from the message; add time data
print(str(data), 0) #print the entire message just for fun
except:
print ("Cannot decode data on topic {0}".format(topic)) #cannot decode; print the topic for the non-decodable message
mqtt.Client.connected_flag=False#create flag in class
client = mqtt.Client()
client.on_connect = on_connect
client.connect("broker.hivemq.com", 1883)
#client.on_subscribe=on_subscribe
client.on_disconnect = on_disconnect
#client.on_publish = on_publish
client.on_message = on_message
topic="house/lights/bulb1"
print("Connecting to broker ","broker.hivemq.com")
try:
client.connect("broker.hivemq.com") #connect to broker
except:
print("can't connect")
sys.exit(1)
client.loop_start() #Start loop
while not client.connected_flag: #wait in loop
print("In wait loop")
time.sleep(1)
print("subscribing to topic ",topic)
ret= client.subscribe(topic,0)
print("subscribed returned ",ret)
time.sleep(4)
#####
msg="closed"
time.sleep(4)
client.loop_stop() #Stop loop
client.disconnect() # disconnect