25f96da05b21e419fabe42eb63a857eb304c4c9f
[mqtt-noolite.git] / nmd / nl_mqtt.py
1 import time
2 import json
3 import logging
4 import asyncio
5
6 from hbmqtt.client import MQTTClient
7 from hbmqtt.mqtt.constants import QOS_0, QOS_1, QOS_2
8
9 from .nl_serial import NooliteSerial
10 from .utils import Singleton
11
12 from uuid import uuid1
13 from socket import gethostname
14
15 logger = logging.getLogger(__name__)
16
17 client_id = gethostname()+'-'+str(uuid1())
18
19 INPUT_TOPIC = '%s/send'
20 OUTPUT_TOPIC = '%s/receive'
21
22 class MqttDriver(metaclass=Singleton):
23     def __init__(self, mtrf_tty_name, loop, mqtt_uri='mqtt://127.0.0.1/', mqtt_topic='noolite', commands_delay=0.1):
24         self.mqtt_client = MQTTClient(client_id=client_id,config={'auto_reconnect': True})
25         self.mqtt_uri = mqtt_uri
26         self.commands_delay = commands_delay
27         self.noolite_serial = NooliteSerial(loop=loop, tty_name=mtrf_tty_name,
28                                             input_command_callback_method=self.input_serial_data)
29         self.commands_to_send_queue = asyncio.Queue()
30         self.read_topic = INPUT_TOPIC % mqtt_topic
31         self.subscriptions = [
32             ( self.read_topic+'/#', QOS_0),
33         ]
34         self.write_topic = OUTPUT_TOPIC % mqtt_topic
35         loop.create_task(self.send_command_to_noolite())
36
37     async def run(self):
38         await self.mqtt_client.connect(self.mqtt_uri)
39         await self.mqtt_client.subscribe(self.subscriptions)
40
41         while True:
42             logger.info('Waiting messages from mqtt...')
43             message = await self.mqtt_client.deliver_message()
44
45             topic = message.topic
46             payload = message.publish_packet.payload.data
47
48             logger.info('In message: {}\n{}'.format(topic, payload))
49
50             if topic.startswith(self.read_topic):
51               subtopic = topic[len(self.read_topic)+1:]
52               print(subtopic)
53
54               if subtopic == '':
55                 try:
56                   payload = json.loads(payload.decode())
57                 except Exception as e:
58                   logger.exception(e)
59                   continue
60                 await self.commands_to_send_queue.put(payload)
61               else:
62                 try:
63                   mtrf_command = None
64                   address = subtopic.split('/')
65                   if len(address)==2:
66                     channel = int(address[0])
67                     command = address[1]
68                     id = None
69                   elif len(address)==3:
70                     channel = int(address[0])
71                     command = address[2]
72                     id = address[1]
73                   elif len(address)==1:
74                     command = address[0]
75                     channel = None
76                     id = None
77                   command = command.lower()  
78                   print("%s: %s (%s)" % (command,channel,id))
79                   if command == "on":
80                     if id == '.':
81                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 2, "ctr": 1 }
82                     elif id:
83                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 2, "id0": int(id[0:2],16), "id1": int(id[2:4],16), "id2": int(id[4:6],16), "id3": int(id[6:8],16), "ctr": 8 }
84                     else:
85                       mtrf_command = { "mode": 0, "ch": channel, "cmd": 2 }
86                   elif command == "off":
87                     if id == '.':
88                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 0, "ctr": 1 }
89                     elif id:
90                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 0, "id0": int(id[0:2],16), "id1": int(id[2:4],16), "id2": int(id[4:6],16), "id3": int(id[6:8],16), "ctr": 8 }
91                     else:
92                       mtrf_command = { "mode": 0, "ch": channel, "cmd": 0 }
93                   elif command == "brightness":
94                     brightness = int(payload)
95                     if id == '.':
96                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 6, "d0": brightness, "ctr": 1 }
97                     elif id:
98                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 6, "d0": brightness, "id0": int(id[0:2],16), "id1": int(id[2:4],16), "id2": int(id[4:6],16), "id3": int(id[6:8],16), "ctr": 8 }
99                     else:
100                       mtrf_command = { "mode": 0, "ch": channel, "cmd": 6, "d0": brightness }
101                   elif command == "state":
102                     if id == '.':
103                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 128, "ctr": 1 }
104                     elif id:
105                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 128, "id0": int(id[0:2],16), "id1": int(id[2:4],16), "id2": int(id[4:6],16), "id3": int(id[6:8],16), "ctr": 8 }
106                   elif command == "load_preset":
107                     if id == '.':
108                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 7, "ctr": 1 }
109                     elif id:
110                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 7, "id0": int(id[0:2],16), "id1": int(id[2:4],16), "id2": int(id[4:6],16), "id3": int(id[6:8],16), "ctr": 8 }
111                     else:
112                       mtrf_command = { "mode": 0, "ch": channel, "cmd": 7 }
113                   elif command == "save_preset":
114                     if id == '.':
115                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 8, "ctr": 1 }
116                     elif id:
117                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 8, "id0": int(id[0:2],16), "id1": int(id[2:4],16), "id2": int(id[4:6],16), "id3": int(id[6:8],16), "ctr": 8 }
118                     else:
119                       mtrf_command = { "mode": 0, "ch": channel, "cmd": 8 }
120                   elif command == "temp_on":
121                     delay = (int(payload) + 3)//5
122                     d0 = delay % 256
123                     d1 = delay // 256
124                     if id == '.':
125                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 25, "fmt": 6, "d0": d0, "d1": d1, "ctr": 1 }
126                     elif id:
127                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 25, "fmt": 6, "d0": d0, "d1": d1, "id0": int(id[0:2],16), "id1": int(id[2:4],16), "id2": int(id[4:6],16), "id3": int(id[6:8],16), "ctr": 8 }
128                     else:
129                       mtrf_command = { "mode": 0, "ch": channel, "cmd": 25, "fmt": 6, "d0": d0, "d1": d1 }
130                   elif command == "bind":
131                     if id == 'tx-f':
132                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 15 }
133                     elif id == 'tx':
134                       mtrf_command = { "mode": 0, "ch": channel, "cmd": 15 }
135                     elif id == 'rx':
136                       mtrf_command = { "mode": 1, "ch": channel, "cmd": 15 }
137                     elif id == 'rx-f':
138                       mtrf_command = { "mode": 3, "ch": channel, "cmd": 15 }
139                     else:
140                       mtrf_command = { "mode": 0, "ch": channel, "cmd": 15 }
141                   elif command == "unbind":
142                     if id == '.' or id == 'tx-f':
143                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 9 }
144                     elif id == 'tx':
145                       mtrf_command = { "mode": 0, "ch": channel, "cmd": 9 }
146                     elif id == 'rx':
147                       mtrf_command = { "mode": 1, "ch": channel, "cmd": 9, "ctr": 5 }
148                     elif id == 'rx-f':
149                       mtrf_command = { "mode": 3, "ch": channel, "cmd": 9, "ctr": 5 }
150                     else:
151                       mtrf_command = { "mode": 0, "ch": channel, "cmd": 9 }
152                   elif command == "service":
153                     if id == '.':
154                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 131, "d0": 1 }
155                     elif id:
156                       mtrf_command = { "mode": 2, "ch": channel, "cmd": 131, "d0": 1, "id0": int(id[0:2],16), "id1": int(id[2:4],16), "id2": int(id[4:6],16), "id3": int(id[6:8],16), "ctr": 8 }
157
158                   if mtrf_command:
159                     await self.commands_to_send_queue.put(mtrf_command)
160
161                 except Exception as e:
162                   logger.exception(e)
163                   continue
164                  
165
166     async def send_command_to_noolite(self):
167         last_command_send_time = 0
168         while True:
169             logger.info('Waiting commands to send...')
170             payload = await self.commands_to_send_queue.get()
171             logger.info('Get command from queue: {}'.format(payload))
172
173             # Формируем и отправляем команду к noolite
174             noolite_cmd = self.payload_to_noolite_command(payload)
175
176             if time.time() - last_command_send_time < self.commands_delay:
177                 logger.info('Wait before send next command: {}'.format(
178                     self.commands_delay - (time.time() - last_command_send_time)))
179                 await asyncio.sleep(self.commands_delay - (time.time() - last_command_send_time))
180
181             try:
182                 await self.noolite_serial.send_command(**noolite_cmd)
183             except TypeError as e:
184                 logger.exception(str(e))
185             last_command_send_time = time.time()
186
187     async def input_serial_data(self, command):
188         logger.info('Pub command: {}'.format(command))
189         command = self.noolite_response_to_payload(command.to_list())
190         try:
191           topic = "%s/%s/%s" % (self.write_topic, command['ch'], command['id'])
192         except:
193           topic = "%s/%s" % (self.write_topic, command['ch'])  
194         await self.mqtt_client.publish(topic=topic, message=json.dumps(command).encode())
195
196     @staticmethod        
197     def payload_to_noolite_command(payload):
198         return payload
199
200     @staticmethod
201     def noolite_response_to_payload(payload):
202
203         message = {}
204
205         try:
206           mode = [ 'TX', 'RX', 'TX-F', 'RX-F', 'SERVICE', 'FIRMWARE' ] [payload[1]]
207           message['mode'] = mode
208         finally:
209           None  
210
211         try:
212           message['ctr'] = [ 'OK', 'NORESP', 'ERROR', 'BOUND' ] [payload[2]]
213         finally:
214           None  
215
216         ch = payload[4]
217         message['ch'] = ch
218
219         cmd = payload[5]
220         message['cmd'] = cmd
221
222         fmt = payload[6]
223         message['fmt'] = fmt
224
225         data = payload[7:11]
226         message['data'] = data
227
228         if payload[1] >= 2:
229           message['id'] = '%0.2X%0.2X%0.2X%0.2X' % (payload[11], payload[12], payload[13], payload[14])
230
231         if cmd == 0:
232           message['command'] = 'OFF'
233         elif cmd == 1: 
234           message['command'] = 'BRIGHT_DOWN'
235         elif cmd == 2: 
236           message['command'] = 'ON'
237         elif cmd == 3: 
238           message['command'] = 'BRIGHT_UP'
239         elif cmd == 4: 
240           message['command'] = 'SWITCH'
241         elif cmd == 5: 
242           message['command'] = 'SWITCH'
243         elif cmd == 5: 
244           message['command'] = 'BRIGHT_BACK'
245         elif cmd == 5: 
246           message['command'] = 'BRIGHT_BACK'
247         elif cmd == 6: 
248           message['command'] = 'SET_BRIGHTNESS'
249         elif cmd == 7: 
250           message['command'] = 'LOAD_PRESET'
251         elif cmd == 8: 
252           message['command'] = 'SAVE_PRESET'
253         elif cmd == 9: 
254           message['command'] = 'UNBIND'
255         elif cmd == 10: 
256           message['command'] = 'STOP_REG'
257 #        elif cmd == 11: 
258 #          message['command'] = 'BRIGHTNESS_STEP_DOWN'
259 #        elif cmd == 12: 
260 #          message['command'] = 'BRIGHTNESS_STEP_UP'
261 #        elif cmd == 13: 
262 #          message['command'] = 'BRIGHT_REG'
263         elif cmd == 15: 
264           message['command'] = 'BIND'
265         elif cmd == 16: 
266           message['command'] = 'ROLL_COLOUR'
267         elif cmd == 17: 
268           message['command'] = 'SWITCH_COLOUR'
269         elif cmd == 18: 
270           message['command'] = 'SWITCH_MODE'
271         elif cmd == 19: 
272           message['command'] = 'SPEED_MODE_BACK'
273         elif cmd == 20: 
274           message['command'] = 'BATTERY_LOW'
275         elif cmd == 21: 
276           message['command'] = 'SENS_TEMP_HUMI'
277           t = data[0] + 256*(data[1] % 16)
278           if (data[1] % 16) // 8:
279             t = -(4096 - t )
280           t = t / 10  
281           message['t'] = t
282           dev_type = (data[1] // 16) % 8
283           try:
284             message['dev_type'] = [ 'RESERVED', 'PT112', 'PT111' ][dev_type]
285           finally:
286             None  
287           message['dev_battery_low'] = (data[1] // 128)
288           if dev_type == 2:
289             h = data[2]
290             message['h'] = h
291           message['aux'] = data[3]  
292         elif cmd == 25: 
293           message['command'] = 'TEMPORARY_ON'
294           if fmt == 5:
295             message['delay'] = data[0] * 5
296           elif fmt == 6:
297             message['delay'] = data[0] * 5 + data[1]*5*256
298         elif cmd == 26: 
299           message['command'] = 'MODES'
300         elif cmd == 128: 
301           message['command'] = 'READ_STATE'
302         elif cmd == 129: 
303           message['command'] = 'WRITE_STATE'
304         elif cmd == 130: 
305           message['command'] = 'SEND_STATE'
306           dev_type = data[0]
307           if dev_type == 5:
308             message['dev_type'] = 'SLU-1-300'
309           message['dev_firmware'] = data[1]
310           if fmt == 0:
311             dev_state = data[2] % 16
312             try:
313               message['dev_state'] = [ 'OFF', 'ON', 'TEMPORARY_ON' ][dev_state]
314             finally:
315               None
316             dev_mode = data[2] // 128
317             if dev_mode:
318               message['dev_binding'] = 'ON'
319             message['brightness'] = data[3]
320           elif fmt == 1:
321             message['dev_aux'] = data[2]
322             message['dev_legacy'] = data[3]
323           elif fmt == 2:
324             message['dev_free'] = data[3]
325             message['dev_free_legacy'] = data[2]    
326         elif cmd == 131: 
327           message['command'] = 'SERVICE'
328         elif cmd == 132: 
329           message['command'] = 'CLEAR_MEMORY'
330           
331         return message
332