-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt.py
74 lines (61 loc) · 2.14 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from threading import Thread
from time import sleep
from uuid import uuid4
import paho.mqtt.client as mqtt
from parser import get_messages, Message
MESSAGE_EVENT = "<<MessageGenerated>>"
UPDATE_EVENT = "<<UpdateCounters>>"
class QClient(mqtt.Client):
def __init__(self, config, communicator, root, topic):
id = "psy-crow-{}-{}".format(
config.mqtt_connection.get("topic").replace("/", "-"),
str(uuid4())[:8]
)
mqtt.Client.__init__(self, client_id=id)
self.config = config
self.communicator = communicator
self.root = root
self.topic = topic
class MqttThread(Thread):
def __init__(self, config, root, communicator):
Thread.__init__(self)
self.config = config
self.root = root
self.client = QClient(
config=config,
communicator=communicator,
root=self.root,
topic=self.config.mqtt_connection["topic"]
)
self.client.on_connect = self._on_connect
self.client.on_message = self._on_message
@staticmethod
def _on_connect(client, userdata, flags, rc):
if rc:
raise Exception("MQTT connected with error")
client.subscribe(client.topic)
@staticmethod
def _on_message(client, userdata, msg):
client.root.event_generate(UPDATE_EVENT)
for message in get_messages(client.config, msg.payload.decode("utf-8")):
client.communicator.put_message(message)
client.root.event_generate(MESSAGE_EVENT)
def run(self):
sleep(2)
try:
self.client.connect(
host=self.config.mqtt_connection["host"],
port=self.config.mqtt_connection["port"],
keepalive=60,
)
sleep(1)
self.client.loop_forever()
except Exception as e:
self.client.communicator.put_message(
Message(
title="System",
text=str(e),
color=self.config.get_color("system")
)
)
self.client.root.event_generate(MESSAGE_EVENT)