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
from datetime import date, datetime
import json
# function to connect with topic
def on_connect(client, userdata, flags, rc): # client method to connect
if rc == 0:
print("connected OK Returned code=", rc) # let us know we connected to the broker
# TOPICS MUST BE ADDED HERE
client.subscribe("smarthouse/sensors/data")
# topic
# topic
# topic
# topic
# topic
else:
print("Bad connection Returned code=", rc) # if we can't connect
#dsfhjfehgfgdsfgsafgeghasdf
#fnsdfbhfgvvgs
#dfm,fdbhsdhfghsdfvgsdf
# function to receive messages
def on_message(client, userdata, msg,): # client method to get messages from topic
topic = msg.topic # for use when we can't decode
try:
day = date.today() # date function call
clock = datetime.now() # time function calls
time_time = datetime.time(clock)
# DECODING CODE GOES HERE FOR EACH SEPARATE TOPIC
if topic == "smarthouse/sensors/data": # decodes message from specific topic (sensors)
data = json.loads(msg.payload.decode("utf-8")) # decode message, turns it back into array 'data'
# stores data from arrays to variables
Id = data[0] # example: database.Id = data[0]
location = data[1]
temperature = data[2]
# print message with data, time and date to check if it is received and decoded
print("Received message at : date-" + str(day) + " time-" + str(time_time) + " / data: topic: " + topic + "; value: "
+ str(data))
# shows that data is stored from array to variables (JUST FOR TESTING)
print("Data stored at: 'Id'=" + str(Id) + "; 'location'=" + location + "; temperature=" + str(temperature))
except:
print("Cannot decode data on topic:" + topic) # cannot decode; print the topic for the non-decodable message
# define client
client = mqtt.Client()
# callback functions
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com", 1883) # connect to the broker on an appropriate port
client.loop_forever() # keep looping forever (allows realtime subscription)