annotate lib/mqtt_client/mqtt_client.py @ 1382:f883166f7ca1

big rewrite. now probably works for multiple subscriptions and over reconnects Ignore-this: 301b82746e517d2a6ff212677f23ca8e darcs-hash:c3badf7258cd931afa0f9b0507482d0c6a702407
author drewp <drewp@bigasterisk.com>
date Wed, 08 May 2019 00:55:58 -0700
parents 3cf19717cb6f
children c887b1cc5e83
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
1 import logging
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
2 from mqtt.client.factory import MQTTFactory
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
3 from rx import Observable
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
4 from rx.subjects import Subject
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
5 from rx.concurrency import TwistedScheduler
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
6 from twisted.application.internet import ClientService
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
7 from twisted.internet import reactor
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
8 from twisted.internet.defer import inlineCallbacks, Deferred
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
9 from twisted.internet.endpoints import clientFromString
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
10
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
11 log = logging.getLogger('mqtt_client')
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
12
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
13 class MQTTService(ClientService):
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
14
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
15 def __init__(self, endpoint, factory, observersByTopic):
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
16 self.endpoint = endpoint
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
17 self.observersByTopic = observersByTopic
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
18 ClientService.__init__(self, endpoint, factory, retryPolicy=lambda _: 5)
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
19
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
20 def startService(self):
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
21 self.whenConnected().addCallback(self.connectToBroker)
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
22 ClientService.startService(self)
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
23
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
24 def ensureSubscribed(self, topic: bytes):
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
25 self.whenConnected().addCallback(self._subscribeToLatestTopic, topic)
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
26
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
27 def _subscribeToLatestTopic(self, protocol, topic: bytes):
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
28 if protocol.state == protocol.CONNECTED:
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
29 self.protocol.subscribe(topics=[(topic.decode('utf8'), 2)])
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
30 # else it'll get done in the next connectToBroker.
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
31
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
32 def _subscribeAll(self):
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
33 topics = list(self.observersByTopic)
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
34 log.info('subscribing %r', topics)
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
35 self.protocol.subscribe(topics=[(topic.decode('utf8'), 2) for topic in topics])
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
36
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
37
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
38 @inlineCallbacks
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
39 def connectToBroker(self, protocol):
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
40 self.protocol = protocol
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
41 self.protocol.onDisconnection = self._onProtocolDisconnection
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
42
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
43 # Publish requests beyond window size are enqueued
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
44 self.protocol.setWindowSize(1)
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
45
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
46 try:
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
47 yield self.protocol.connect("TwistedMQTT-pub", keepalive=60)
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
48 except Exception as e:
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
49 log.error(f"Connecting to {self.endpoint} raised {e!s}")
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
50 return
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
51
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
52 log.info(f"Connected to {self.endpoint}")
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
53
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
54 self.protocol.onPublish = self._onProtocolMessage
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
55 self._subscribeAll()
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
56
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
57 def _onProtocolMessage(self, topic, payload, qos, dup, retain, msgId):
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
58 topic = topic.encode('ascii')
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
59 observers = self.observersByTopic.get(topic, [])
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
60 log.debug(f'received {topic} payload {payload} ({len(observers)} obs)')
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
61 for obs in observers:
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
62 obs.on_next(payload)
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
63
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
64 def _onProtocolDisconnection(self, reason):
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
65 log.warn("Connection to broker lost: %r", reason)
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
66 self.whenConnected().addCallback(self.connectToBroker)
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
67
1359
8fb419235dc9 some py3 compatibility
drewp <drewp@bigasterisk.com>
parents: 1357
diff changeset
68 def publish(self, topic: bytes, msg: bytes):
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
69 def _logFailure(failure):
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
70 log.warn("publish failed: %s", failure.getErrorMessage())
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
71 return failure
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
72
1363
3cf19717cb6f also pass topic as str at publish
drewp <drewp@bigasterisk.com>
parents: 1361
diff changeset
73 return self.protocol.publish(topic=topic.decode('utf-8'), qos=0,
1359
8fb419235dc9 some py3 compatibility
drewp <drewp@bigasterisk.com>
parents: 1357
diff changeset
74 message=bytearray(msg)).addErrback(_logFailure)
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
75
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
76
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
77 class MqttClient(object):
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
78 def __init__(self, brokerHost='bang', brokerPort=1883):
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
79
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
80 self.observersByTopic = {} # bytes: Set(observer)
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
81
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
82 factory = MQTTFactory(profile=MQTTFactory.PUBLISHER | MQTTFactory.SUBSCRIBER)
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
83 myEndpoint = clientFromString(reactor, 'tcp:%s:%s' % (brokerHost, brokerPort))
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
84 myEndpoint.__class__.__repr__ = lambda self: repr('%s:%s' % (self._host, self._port))
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
85 self.serv = MQTTService(myEndpoint, factory, self.observersByTopic)
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
86 self.serv.startService()
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
87
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
88 def publish(self, topic: bytes, msg: bytes):
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
89 return self.serv.publish(topic, msg)
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
90
1359
8fb419235dc9 some py3 compatibility
drewp <drewp@bigasterisk.com>
parents: 1357
diff changeset
91 def subscribe(self, topic: bytes):
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
92 """returns rx.Observable of payload strings"""
1382
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
93 ret = Subject()
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
94 self.observersByTopic.setdefault(topic, set()).add(ret)
f883166f7ca1 big rewrite. now probably works for multiple subscriptions and over reconnects
drewp <drewp@bigasterisk.com>
parents: 1363
diff changeset
95 self.serv.ensureSubscribed(topic)
1357
f99fe03803d4 mqtt_client into a distributable
drewp <drewp@bigasterisk.com>
parents:
diff changeset
96 return ret