Skip to content

Commit 9f3316f

Browse files
committed
Overriding method wait_msg() in MQTTClient class to avoid infinite waiting of broker response. Works on all micropython boards but needs improvement because it adds timeout to MESSAGE_RATE.
1 parent 8fb2d8a commit 9f3316f

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

LiveObjects/Connection.py

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,47 @@ def __init__(self, board, deviceID, port, apiKey, debug=True):
5959
self.__mqtt = paho.Client(deviceID)
6060
elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON:
6161
self.ssl = port == 8883
62-
self.__mqtt = MQTTClient(deviceID, self.__server, self.__port, "json+device",
63-
self.__apiKey, 0, self.ssl, {'server_hostname': self.__server})
62+
63+
class MQTTClient2(MQTTClient): # overriding original method wait_msg due to infinite waiting
64+
def wait_msg(self):
65+
import select
66+
poller = select.poll()
67+
poller.register(self.sock, select.POLLIN)
68+
res = poller.poll(1000)
69+
if not res:
70+
res = None
71+
self.sock.setblocking(True)
72+
if res is None:
73+
return None
74+
if res == b"":
75+
raise OSError(-1)
76+
if res == b"\xd0": # PINGRESP
77+
sz = self.sock.read(1)[0]
78+
assert sz == 0
79+
return None
80+
op = res[0]
81+
if op & 0xf0 != 0x30:
82+
return op
83+
sz = self._recv_len()
84+
topic_len = self.sock.read(2)
85+
topic_len = (topic_len[0] << 8) | topic_len[1]
86+
topic = self.sock.read(topic_len)
87+
sz -= topic_len + 2
88+
if op & 6:
89+
pid = self.sock.read(2)
90+
pid = pid[0] << 8 | pid[1]
91+
sz -= 2
92+
msg = self.sock.read(sz)
93+
self.cb(topic, msg)
94+
if op & 6 == 2:
95+
pkt = bytearray(b"\x40\x02\0\0")
96+
struct.pack_into("!H", pkt, 2, pid)
97+
self.sock.write(pkt)
98+
elif op & 6 == 4:
99+
assert 0
100+
101+
self.__mqtt = MQTTClient2(deviceID, self.__server, self.__port, "json+device",
102+
self.__apiKey, 0, self.ssl, {'server_hostname': self.__server})
64103

65104
def loop(self):
66105
if self.mode == LiveObjects.BoardsInterface.MICROPYTHON:

0 commit comments

Comments
 (0)