-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadorable_qtpi.py
48 lines (38 loc) · 1.52 KB
/
adorable_qtpi.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
import paho.mqtt.client as mqtt
import json
import requests
import os
LOCALWOOD_TOKEN = os.environ["LOCALWOOD_TOKEN"]
MQTT_HOST = os.environ["MQTT_HOST"]
MQTT_USERNAME = os.environ["MQTT_USERNAME"]
MQTT_TOPIC = os.environ["MQTT_TOPIC"]
# Optional envs
MQTT_CLIENT_ID = os.getenv("MQTT_CLIENT_ID")
MQTT_PASSWORD = os.getenv("MQTT_PASSWORD")
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
if rc != 0:
print("Failed to connect to broker :'(")
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(MQTT_TOPIC)
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print('Got message %s', msg.payload)
localwood_payload = json.loads(msg.payload.decode('utf-8'))
localwood_payload['token'] = LOCALWOOD_TOKEN
try:
requests.post('http://localhost:8080/sockets', data = localwood_payload)
except Exception as err:
print(err)
client = mqtt.Client(client_id = MQTT_CLIENT_ID)
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
client.connect(MQTT_HOST)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()