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)
63 address = subtopic.split('/')
65 channel = int(address[0])
69 channel = int(address[0])
76 command = command.lower()
77 print("%s: %s (%s)" % (command,channel,id))
80 mtrf_command = { "mode": 2, "ch": channel, "cmd": 2 }
82 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 mtrf_command = { "mode": 0, "ch": channel, "cmd": 2 }
85 elif command == "off":
87 mtrf_command = { "mode": 2, "ch": channel, "cmd": 0 }
89 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 mtrf_command = { "mode": 0, "ch": channel, "cmd": 0 }
92 elif command == "brightness":
93 brightness = int(payload)
95 mtrf_command = { "mode": 2, "ch": channel, "cmd": 6, "d0": brightness }
97 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 mtrf_command = { "mode": 0, "ch": channel, "cmd": 6, "d0": brightness }
100 elif command == "state":
102 mtrf_command = { "mode": 2, "ch": channel, "cmd": 128 }
104 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 }
105 elif command == "load_preset":
107 mtrf_command = { "mode": 2, "ch": channel, "cmd": 7 }
109 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 mtrf_command = { "mode": 0, "ch": channel, "cmd": 7 }
112 elif command == "save_preset":
114 mtrf_command = { "mode": 2, "ch": channel, "cmd": 8 }
116 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 mtrf_command = { "mode": 0, "ch": channel, "cmd": 8 }
119 elif command == "temp_on":
120 delay = (int(payload) + 3)//5
124 mtrf_command = { "mode": 2, "ch": channel, "cmd": 25, "fmt": 6, "d0": d0, "d1": d1 }
126 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 mtrf_command = { "mode": 0, "ch": channel, "cmd": 25, "fmt": 6, "d0": d0, "d1": d1 }
129 except Exception as e:
132 await self.commands_to_send_queue.put(mtrf_command)
135 async def send_command_to_noolite(self):
136 last_command_send_time = 0
138 logger.info('Waiting commands to send...')
139 payload = await self.commands_to_send_queue.get()
140 logger.info('Get command from queue: {}'.format(payload))
142 # Формируем и отправляем команду к noolite
143 noolite_cmd = self.payload_to_noolite_command(payload)
145 if time.time() - last_command_send_time < self.commands_delay:
146 logger.info('Wait before send next command: {}'.format(
147 self.commands_delay - (time.time() - last_command_send_time)))
148 await asyncio.sleep(self.commands_delay - (time.time() - last_command_send_time))
151 await self.noolite_serial.send_command(**noolite_cmd)
152 except TypeError as e:
153 logger.exception(str(e))
154 last_command_send_time = time.time()
156 async def input_serial_data(self, command):
157 logger.info('Pub command: {}'.format(command))
158 command = self.noolite_response_to_payload(command.to_list())
160 topic = "%s/%s/%s" % (self.write_topic, command['ch'], command['id'])
162 topic = "%s/%s" % (self.write_topic, command['ch'])
163 await self.mqtt_client.publish(topic=topic, message=json.dumps(command).encode())
166 def payload_to_noolite_command(payload):
170 def noolite_response_to_payload(payload):
175 mode = [ 'TX', 'RX', 'TX-F', 'RX-F', 'SERVICE', 'FIRMWARE' ] [payload[1]]
176 message['mode'] = mode
181 message['ctr'] = [ 'OK', 'NORESP', 'ERROR', 'BOUND' ] [payload[2]]
195 message['data'] = data
198 message['id'] = '%0.2X%0.2X%0.2X%0.2X' % (payload[11], payload[12], payload[13], payload[14])
201 message['command'] = 'OFF'
203 message['command'] = 'BRIGHT_DOWN'
205 message['command'] = 'ON'
207 message['command'] = 'BRIGHT_UP'
209 message['command'] = 'SWITCH'
211 message['command'] = 'SWITCH'
213 message['command'] = 'BRIGHT_BACK'
215 message['command'] = 'BRIGHT_BACK'
217 message['command'] = 'SET_BRIGHTNESS'
219 message['command'] = 'LOAD_PRESET'
221 message['command'] = 'SAVE_PRESET'
223 message['command'] = 'UNBIND'
225 message['command'] = 'STOP_REG'
227 # message['command'] = 'BRIGHTNESS_STEP_DOWN'
229 # message['command'] = 'BRIGHTNESS_STEP_UP'
231 # message['command'] = 'BRIGHT_REG'
233 message['command'] = 'BIND'
235 message['command'] = 'ROLL_COLOUR'
237 message['command'] = 'SWITCH_COLOUR'
239 message['command'] = 'SWITCH_MODE'
241 message['command'] = 'SPEED_MODE_BACK'
243 message['command'] = 'BATTERY_LOW'
245 message['command'] = 'SENS_TEMP_HUMI'
246 t = data[0] + 256*(data[1] % 16)
247 if (data[1] % 16) // 8:
251 dev_type = (data[1] // 16) % 8
253 message['dev_type'] = [ 'RESERVED', 'PT112', 'PT111' ][dev_type]
256 message['dev_battery_low'] = (data[1] // 128)
260 message['aux'] = data[3]
262 message['command'] = 'TEMPORARY_ON'
264 message['delay'] = data[0] * 5
266 message['delay'] = data[0] * 5 + data[1]*5*256
268 message['command'] = 'MODES'
270 message['command'] = 'READ_STATE'
272 message['command'] = 'WRITE_STATE'
274 message['command'] = 'SEND_STATE'
277 message['dev_type'] = 'SLU-1-300'
278 message['dev_firmware'] = data[1]
280 dev_state = data[2] % 16
282 message['dev_state'] = [ 'OFF', 'ON', 'TEMPORARY_ON' ][dev_state]
285 dev_mode = data[2] // 128
287 message['dev_binding'] = 'ON'
288 message['brightness'] = data[3]
290 message['dev_aux'] = data[2]
291 message['dev_legacy'] = data[3]
293 message['dev_free'] = data[3]
294 message['dev_free_legacy'] = data[2]
296 message['command'] = 'SERVICE'
298 message['command'] = 'CLEAR_MEMORY'