6 from hbmqtt.client import MQTTClient
7 from hbmqtt.mqtt.constants import QOS_0, QOS_1, QOS_2
9 from .nl_serial import NooliteSerial
10 from .utils import Singleton
12 from uuid import uuid1
13 from socket import gethostname
15 logger = logging.getLogger(__name__)
17 client_id = gethostname()+'-'+str(uuid1())
19 INPUT_TOPIC = '%s/send'
20 OUTPUT_TOPIC = '%s/receive'
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),
34 self.write_topic = OUTPUT_TOPIC % mqtt_topic
35 loop.create_task(self.send_command_to_noolite())
38 await self.mqtt_client.connect(self.mqtt_uri)
39 await self.mqtt_client.subscribe(self.subscriptions)
42 logger.info('Waiting messages from mqtt...')
43 message = await self.mqtt_client.deliver_message()
46 payload = message.publish_packet.payload.data
48 logger.info('In message: {}\n{}'.format(topic, payload))
50 if topic.startswith(self.read_topic):
51 subtopic = topic[len(self.read_topic)+1:]
56 payload = json.loads(payload.decode())
57 except Exception as e:
60 await self.commands_to_send_queue.put(payload)
64 address = subtopic.split('/')
66 channel = int(address[0])
70 channel = int(address[0])
77 command = command.lower()
78 print("%s: %s (%s)" % (command,channel,id))
81 mtrf_command = { "mode": 2, "ch": channel, "cmd": 2, "ctr": 1 }
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 }
85 mtrf_command = { "mode": 0, "ch": channel, "cmd": 2 }
86 elif command == "off":
88 mtrf_command = { "mode": 2, "ch": channel, "cmd": 0, "ctr": 1 }
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 }
92 mtrf_command = { "mode": 0, "ch": channel, "cmd": 0 }
93 elif command == "brightness":
94 brightness = int(payload)
96 mtrf_command = { "mode": 2, "ch": channel, "cmd": 6, "d0": brightness, "ctr": 1 }
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 }
100 mtrf_command = { "mode": 0, "ch": channel, "cmd": 6, "d0": brightness }
101 elif command == "state":
103 mtrf_command = { "mode": 2, "ch": channel, "cmd": 128, "ctr": 1 }
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":
108 mtrf_command = { "mode": 2, "ch": channel, "cmd": 7, "ctr": 1 }
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 }
112 mtrf_command = { "mode": 0, "ch": channel, "cmd": 7 }
113 elif command == "save_preset":
115 mtrf_command = { "mode": 2, "ch": channel, "cmd": 8, "ctr": 1 }
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 }
119 mtrf_command = { "mode": 0, "ch": channel, "cmd": 8 }
120 elif command == "temp_on":
121 delay = (int(payload) + 3)//5
125 mtrf_command = { "mode": 2, "ch": channel, "cmd": 25, "fmt": 6, "d0": d0, "d1": d1, "ctr": 1 }
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 }
129 mtrf_command = { "mode": 0, "ch": channel, "cmd": 25, "fmt": 6, "d0": d0, "d1": d1 }
130 elif command == "bind":
132 mtrf_command = { "mode": 2, "ch": channel, "cmd": 15 }
134 mtrf_command = { "mode": 0, "ch": channel, "cmd": 15 }
136 mtrf_command = { "mode": 1, "ch": channel, "cmd": 15 }
138 mtrf_command = { "mode": 3, "ch": channel, "cmd": 15 }
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 }
145 mtrf_command = { "mode": 0, "ch": channel, "cmd": 9 }
147 mtrf_command = { "mode": 1, "ch": channel, "cmd": 9, "ctr": 5 }
149 mtrf_command = { "mode": 3, "ch": channel, "cmd": 9, "ctr": 5 }
151 mtrf_command = { "mode": 0, "ch": channel, "cmd": 9 }
152 elif command == "service":
154 mtrf_command = { "mode": 2, "ch": channel, "cmd": 131, "d0": 1 }
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 }
159 await self.commands_to_send_queue.put(mtrf_command)
161 except Exception as e:
166 async def send_command_to_noolite(self):
167 last_command_send_time = 0
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))
173 # Формируем и отправляем команду к noolite
174 noolite_cmd = self.payload_to_noolite_command(payload)
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))
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()
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())
191 topic = "%s/%s/%s" % (self.write_topic, command['ch'], command['id'])
193 topic = "%s/%s" % (self.write_topic, command['ch'])
194 await self.mqtt_client.publish(topic=topic, message=json.dumps(command).encode())
197 def payload_to_noolite_command(payload):
201 def noolite_response_to_payload(payload):
206 mode = [ 'TX', 'RX', 'TX-F', 'RX-F', 'SERVICE', 'FIRMWARE' ] [payload[1]]
207 message['mode'] = mode
212 message['ctr'] = [ 'OK', 'NORESP', 'ERROR', 'BOUND' ] [payload[2]]
226 message['data'] = data
229 message['id'] = '%0.2X%0.2X%0.2X%0.2X' % (payload[11], payload[12], payload[13], payload[14])
232 message['command'] = 'OFF'
234 message['command'] = 'BRIGHT_DOWN'
236 message['command'] = 'ON'
238 message['command'] = 'BRIGHT_UP'
240 message['command'] = 'SWITCH'
242 message['command'] = 'SWITCH'
244 message['command'] = 'BRIGHT_BACK'
246 message['command'] = 'BRIGHT_BACK'
248 message['command'] = 'SET_BRIGHTNESS'
250 message['command'] = 'LOAD_PRESET'
252 message['command'] = 'SAVE_PRESET'
254 message['command'] = 'UNBIND'
256 message['command'] = 'STOP_REG'
258 # message['command'] = 'BRIGHTNESS_STEP_DOWN'
260 # message['command'] = 'BRIGHTNESS_STEP_UP'
262 # message['command'] = 'BRIGHT_REG'
264 message['command'] = 'BIND'
266 message['command'] = 'ROLL_COLOUR'
268 message['command'] = 'SWITCH_COLOUR'
270 message['command'] = 'SWITCH_MODE'
272 message['command'] = 'SPEED_MODE_BACK'
274 message['command'] = 'BATTERY_LOW'
276 message['command'] = 'SENS_TEMP_HUMI'
277 t = data[0] + 256*(data[1] % 16)
278 if (data[1] % 16) // 8:
282 dev_type = (data[1] // 16) % 8
284 message['dev_type'] = [ 'RESERVED', 'PT112', 'PT111' ][dev_type]
287 message['dev_battery_low'] = (data[1] // 128)
291 message['aux'] = data[3]
293 message['command'] = 'TEMPORARY_ON'
295 message['delay'] = data[0] * 5
297 message['delay'] = data[0] * 5 + data[1]*5*256
299 message['command'] = 'MODES'
301 message['command'] = 'READ_STATE'
303 message['command'] = 'WRITE_STATE'
305 message['command'] = 'SEND_STATE'
308 message['dev_type'] = 'SLU-1-300'
309 message['dev_firmware'] = data[1]
311 dev_state = data[2] % 16
313 message['dev_state'] = [ 'OFF', 'ON', 'TEMPORARY_ON' ][dev_state]
316 dev_mode = data[2] // 128
318 message['dev_binding'] = 'ON'
319 message['brightness'] = data[3]
321 message['dev_aux'] = data[2]
322 message['dev_legacy'] = data[3]
324 message['dev_free'] = data[3]
325 message['dev_free_legacy'] = data[2]
327 message['command'] = 'SERVICE'
329 message['command'] = 'CLEAR_MEMORY'