|
1 | 1 | import time
|
| 2 | +import requests |
2 | 3 | import paho.mqtt.client as mqtt
|
3 | 4 |
|
4 |
| -class Hub(): |
5 |
| - def __init__(self, account_id, api_key, device_id, message_handler=None): |
6 |
| - self.account_id = account_id |
7 |
| - self.client = mqtt.Client(client_id=self._normalize_device_id(device_id), clean_session=True) |
8 |
| - self.client.username_pw_set(account_id, api_key) |
9 |
| - # self.client.tls_set(ca_certs='labstack.com/cert.pem') |
| 5 | +class Axis(): |
| 6 | + def __init__(self, api_key, client_id, message_handler=None): |
| 7 | + self.api_key = api_key |
| 8 | + self.client_id = client_id |
| 9 | + self.message_handler = message_handler |
10 | 10 | self.handlers = {}
|
11 |
| - def handler(client, userdata, msg): |
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) |
18 |
| - self.client.on_message = handler |
19 | 11 |
|
20 | 12 | def _normalize_device_id(self, id):
|
21 |
| - return '{}:{}'.format(self.account_id, id) |
| 13 | + return '{}:{}'.format(self.project_id, id) |
22 | 14 |
|
23 | 15 | def _normalize_topic(self, name):
|
24 |
| - return '{}/{}'.format(self.account_id, name) |
| 16 | + return '{}/{}'.format(self.project_id, name) |
25 | 17 |
|
26 | 18 | def _denormalize_topic(self, name):
|
27 |
| - return name.lstrip(self.account_id + '/') |
| 19 | + return name.lstrip(self.project_id + '/') |
| 20 | + |
| 21 | + def _find_project_id(self): |
| 22 | + headers = { |
| 23 | + 'Authorization': 'Bearer ' + self.api_key |
| 24 | + } |
| 25 | + r = requests.get('https://api.labstack.com/axis/key', headers=headers) |
| 26 | + if not 200 <= r.status_code < 300: |
| 27 | + pass |
| 28 | + # raise APIError(data['code'], data['message']) |
| 29 | + data = r.json() |
| 30 | + self.project_id = data['project_id'] |
28 | 31 |
|
29 | 32 | def connect(self, handler=None):
|
30 |
| - self.client.connect("hub.labstack.com", 1883) |
| 33 | + # Find project id |
| 34 | + self._find_project_id() |
| 35 | + |
| 36 | + # Connect |
| 37 | + self.client = mqtt.Client(client_id=self._normalize_device_id(self.client_id), |
| 38 | + clean_session=True) |
| 39 | + self.client.username_pw_set(self.project_id, self.api_key) |
| 40 | + # self.client.tls_set(ca_certs='labstack.com/cert.pem') |
| 41 | + def message_handler(client, userdata, msg): |
| 42 | + topic = self._denormalize_topic(msg.topic) |
| 43 | + if self.message_handler: |
| 44 | + self.message_handler(topic, msg.payload) |
| 45 | + h = self.handlers.get(topic) |
| 46 | + if h: |
| 47 | + h(topic, msg.payload) |
| 48 | + self.client.on_message = message_handler |
| 49 | + self.client.connect("axis.labstack.com", 1883) |
31 | 50 | self.client.loop_start()
|
| 51 | + |
32 | 52 | def on_connect(client, userdata, flags, rc):
|
33 | 53 | if handler:
|
34 | 54 | handler()
|
|
0 commit comments