Skip to content

Commit e41a5af

Browse files
committed
Enhanced hub
Signed-off-by: Vishal Rana <vr@labstack.com>
1 parent 8dc4cb6 commit e41a5af

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

labstack/hub.py

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,47 @@
22
import paho.mqtt.client as mqtt
33

44
class Hub():
5-
def __init__(self, account_id, api_key, client_id=None):
5+
def __init__(self, account_id, api_key, device_id=None, message_handler=None):
66
self.account_id = account_id
7-
self.client = mqtt.Client(client_id=client_id, clean_session=True)
7+
self.client = mqtt.Client(client_id=device_id, clean_session=True)
88
self.client.username_pw_set(account_id, api_key)
99
# self.client.tls_set(ca_certs='labstack.com/cert.pem')
1010
self.handlers = {}
1111
def handler(client, userdata, msg):
12-
self.handlers[msg.topic](msg.payload)
12+
topic = self._denormalize_topic(msg.topic)
13+
if message_handler:
14+
message_handler(topic, msg.payload)
15+
h = self.handlers.get(topic)
16+
if h:
17+
h(topic, msg.payload)
1318
self.client.on_message = handler
19+
20+
def _normalize_topic(self, topic):
21+
return '{}/{}'.format(self.account_id, topic)
22+
23+
def _denormalize_topic(self, topic):
24+
return topic.lstrip(self.account_id + '/')
1425

1526
def connect(self, handler=None):
1627
self.client.connect("hub.labstack.com", 1883)
1728
self.client.loop_start()
1829
def on_connect(client, userdata, flags, rc):
19-
if handler is not None:
30+
if handler:
2031
handler()
2132
self.client.on_connect = on_connect
2233

2334
def publish(self, topic, message):
24-
self.client.publish('{}/{}'.format(self.account_id, topic), message)
35+
self.client.publish(self._normalize_topic(topic), message)
2536

2637
# def subscribe(self, topic, handler, shared=False):
27-
def subscribe(self, topic, handler):
28-
topic = '{}/{}'.format(self.account_id, topic)
38+
def subscribe(self, topic, handler=None):
2939
# if shared:
3040
# topic = '$queue/' + topic
31-
self.client.subscribe(topic)
41+
self.client.subscribe(self._normalize_topic(topic))
3242
self.handlers[topic] = handler
3343

3444
def unsubscribe(self, topic):
35-
self.client.unsubscribe('{}/{}'.format(self.account_id, topic))
45+
self.client.unsubscribe(self._normalize_topic(topic))
3646

3747
def disconnect(self):
3848
self.client.loop_stop()

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
setup(
44
name='labstack',
5-
version='0.31.6',
5+
version='0.32.0',
66
description='Official Python client library for the LabStack platform',
77
long_description='`<https://github.com/labstack/labstack-python>`_',
88
keywords='image compress, image resize, text summary, barcode generate, barcode scan',

0 commit comments

Comments
 (0)