-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
57 lines (46 loc) · 1.55 KB
/
main.py
File metadata and controls
57 lines (46 loc) · 1.55 KB
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
50
51
52
53
54
55
56
57
import paho.mqtt.client as mqtt
import sys
import credentials
# MQTT Connection definitions:
broker = credentials.MQTTBroker
PortaBroker = credentials.MQTTPort
KeepAliveBroker = 60
username = credentials.MQTTUsername
password = credentials.MQTTPassword
# MQTT Topics definitions:
MQTT_TOPIC = [("ledStatus", 1), ("temperature", 1)]
topicSubscribe = "ledStatus"
topicSender = "confirmationLedStatus"
# MQTT Connect to broker function
def on_connect(client, userdata, flags, rc):
print("[STATUS] Connecting to broker: " + str(rc))
client.subscribe(MQTT_TOPIC)
# Reception callback function
def on_message(client, userdata, msg):
MensagemRecebida = str(msg.payload)
if msg.topic == 'temperature':
temperatureReceived(MensagemRecebida)
if msg.topic == 'ledStatus':
LEDStatusReceived(MensagemRecebida)
sendMessage(topicSender, "OK")
def temperatureReceived(temperature):
print("[Temperature reading] " + temperature + "°C")
def LEDStatusReceived(ledStatus):
print("[LED status reading] " + ledStatus)
# Send function
def sendMessage(topic, msg):
client.publish(topic, msg)
print("[MSG SENT] Topic: " + topic + " / Message: " + msg)
# Main:
try:
print("[STATUS] Inicializando MQTT...")
# inicializa MQTT:
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username, password)
client.connect(broker, PortaBroker, KeepAliveBroker)
client.loop_forever()
except KeyboardInterrupt:
print("\nClosing application and exiting.")
sys.exit(0)