-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmqtt_gateway.py
58 lines (45 loc) · 1.47 KB
/
mqtt_gateway.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
50
51
52
53
54
55
56
57
58
import serial
from datetime import datetime
import paho.mqtt.client as mqtt
import msgpack
from ebyte import EbyteRaspberryPi
PIN_M0 = 27
PIN_M1 = 17
PIN_AUX = 22
# ser = serial.Serial('/dev/serial0')
ser = serial.Serial('/dev/ttyAMA0')
client = mqtt.Client()
ebyte = EbyteRaspberryPi(ser, PIN_M0, PIN_M1, PIN_AUX)
# client.username_pw_set('tulpe', 'HKUabc98')
def publish(topic, payload):
# return
client.connect('localhost', 1884)
client.publish(topic, payload, 0, True)
# print(topic, payload)
client.loop()
client.disconnect()
# unpacker = msgpack.Unpacker(strict_map_key=False)
unpacker = msgpack.Unpacker()
last_payloads = {}
while True:
unpacker.feed(ser.read(1))
for arr_ in unpacker:
if arr_:
try:
client_id, counter, name, payload = arr_
topic = f'{client_id}/{name}'
# if client_id == 'greenhouse': # and name in ['temp_inside', 'temp_outside':
# try:
# payload = float(payload)
# except Exception:
# pass
if True or last_payloads.get(topic) != payload:
last_payloads[topic] = payload
print(
datetime.now().strftime("%H:%M:%S"),
topic,
payload
)
publish(topic, payload)
except Exception:
print('.')