-
Notifications
You must be signed in to change notification settings - Fork 0
/
MQTT.py
49 lines (36 loc) · 1.81 KB
/
MQTT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
Python MQTT Subscription client - No Username/Password
Thomas Varnish (https://github.com/tvarnish), (https://www.instructables.com/member/Tango172)
Written for my Instructable - "How to use MQTT with the Raspberry Pi and ESP8266"
"""
import paho.mqtt.client as mqtt
from db import sensor_Data_Handler
# Don't forget to change the variables for the MQTT broker!
mqtt_topic = "/sunway/level1/toilet1/#"
mqtt_broker_ip = "192.168.0.170"
client = mqtt.Client()
# These functions handle what happens when the MQTT client connects
# to the broker, and what happens then the topic receives a message
def on_connect(client, userdata, flags, rc):
# rc is the error code returned when connecting to the broker
print "Connected!", str(rc)
# Once the client has connected to the broker, subscribe to the topic
client.subscribe(mqtt_topic)
def on_message(client, userdata, msg):
# This function is called everytime the topic is published to.
# If you want to check each message, and do something depending on
# the content, the code to do this should be run in this function
print "Topic: ", msg.topic + "\nMessage: " + str(msg.payload)
sensor_Data_Handler(msg.topic, msg.payload)
# The message itself is stored in the msg variable
# and details about who sent it are stored in userdata
# Here, we are telling the client which functions are to be run
# on connecting, and on receiving a message
client.on_connect = on_connect
client.on_message = on_message
# Once everything has been set up, we can (finally) connect to the broker
# 1883 is the listener port that the MQTT broker is using
client.connect(mqtt_broker_ip, 1883)
# Once we have told the client to connect, let the client object run itself
client.loop_forever()
client.disconnect()