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])
77 command = command.lower()
79 print("%s: %s (%s)" % (command,channel,id))
81 mtrf_command = { "ch": channel }
82 if id == '.' or id == 'TX-F':
83 mtrf_command["mode"] = 2
85 mtrf_command["mode"] = 0
87 mtrf_command["mode"] = 1
89 mtrf_command["mode"] = 3
91 mtrf_command["mode"] = 2
92 mtrf_command["ctr"] = 8
93 mtrf_command["id0"] = int(id[0:2],16)
94 mtrf_command["id1"] = int(id[2:4],16)
95 mtrf_command["id2"] = int(id[4:6],16)
96 mtrf_command["id3"] = int(id[6:8],16)
98 mtrf_command["mode"] = 0
100 if command == "power":
101 payload = payload.decode('utf-8').lower()
102 print( "command: POWER " + payload )
104 mtrf_command["cmd"] = 0
106 mtrf_command["cmd"] = 2
108 elif command == "on":
109 mtrf_command["cmd"] = 2
111 elif command == "off":
112 mtrf_command["cmd"] = 0
114 elif command == "brightness":
115 mtrf_command["cmd"] = 6
116 mtrf_command["d0"] = int(float(payload))
118 elif command == "dimmer":
119 mtrf_command["cmd"] = 6
120 mtrf_command["d0"] = int(round(float(payload)*255/100))
122 elif command == "state":
123 mtrf_command["cmd"] = 128
125 elif command == "load_preset":
126 mtrf_command["cmd"] = 7
128 elif command == "save_preset":
129 mtrf_command["cmd"] = 8
131 elif command == "temp_on":
132 delay = (int(payload) + 3)//5
133 mtrf_command["cmd"] = 25
134 mtrf_command["d0"] = delay % 256
135 mtrf_command["d1"] = delay // 256
136 mtfr_command["fmt"] = 6
138 elif command == "bind":
139 mtrf_command["cmd"] = 15
141 elif command == "unbind":
142 mtrf_command["cmd"] = 9
144 elif command == "service":
145 mtrf_command["cmd"] = 131
147 except Exception as e:
150 await self.commands_to_send_queue.put(mtrf_command)
153 async def send_command_to_noolite(self):
154 last_command_send_time = 0
156 logger.info('Waiting commands to send...')
157 payload = await self.commands_to_send_queue.get()
158 logger.info('Get command from queue: {}'.format(payload))
160 # Формируем и отправляем команду к noolite
161 noolite_cmd = self.payload_to_noolite_command(payload)
163 if time.time() - last_command_send_time < self.commands_delay:
164 logger.info('Wait before send next command: {}'.format(
165 self.commands_delay - (time.time() - last_command_send_time)))
166 await asyncio.sleep(self.commands_delay - (time.time() - last_command_send_time))
169 await self.noolite_serial.send_command(**noolite_cmd)
170 except TypeError as e:
171 logger.exception(str(e))
172 last_command_send_time = time.time()
174 async def input_serial_data(self, command):
175 logger.info('Pub command: {}'.format(command))
176 command = self.noolite_response_to_payload(command.to_list())
178 topic = "%s/%s/%s" % (self.write_topic, command['ch'], command['id'])
180 topic = "%s/%s" % (self.write_topic, command['ch'])
181 await self.mqtt_client.publish(topic=topic, message=json.dumps(command).encode())
184 def payload_to_noolite_command(payload):
188 def noolite_response_to_payload(payload):
193 mode = [ 'TX', 'RX', 'TX-F', 'RX-F', 'SERVICE', 'FIRMWARE' ] [payload[1]]
194 message['mode'] = mode
199 message['ctr'] = [ 'OK', 'NORESP', 'ERROR', 'BOUND' ] [payload[2]]
213 message['data'] = data
216 message['id'] = '%0.2X%0.2X%0.2X%0.2X' % (payload[11], payload[12], payload[13], payload[14])
219 message['command'] = 'OFF'
221 message['command'] = 'BRIGHT_DOWN'
223 message['command'] = 'ON'
225 message['command'] = 'BRIGHT_UP'
227 message['command'] = 'SWITCH'
229 message['command'] = 'SWITCH'
231 message['command'] = 'BRIGHT_BACK'
233 message['command'] = 'BRIGHT_BACK'
235 message['command'] = 'SET_BRIGHTNESS'
237 message['command'] = 'LOAD_PRESET'
239 message['command'] = 'SAVE_PRESET'
241 message['command'] = 'UNBIND'
243 message['command'] = 'STOP_REG'
245 # message['command'] = 'BRIGHTNESS_STEP_DOWN'
247 # message['command'] = 'BRIGHTNESS_STEP_UP'
249 # message['command'] = 'BRIGHT_REG'
251 message['command'] = 'BIND'
253 message['command'] = 'ROLL_COLOUR'
255 message['command'] = 'SWITCH_COLOUR'
257 message['command'] = 'SWITCH_MODE'
259 message['command'] = 'SPEED_MODE_BACK'
261 message['command'] = 'BATTERY_LOW'
263 message['command'] = 'SENS_TEMP_HUMI'
264 t = data[0] + 256*(data[1] % 16)
265 if (data[1] % 16) // 8:
269 dev_type = (data[1] // 16) % 8
271 message['dev_type'] = [ 'RESERVED', 'PT112', 'PT111' ][dev_type]
274 message['dev_battery_low'] = (data[1] // 128)
278 message['aux'] = data[3]
280 message['command'] = 'TEMPORARY_ON'
282 message['delay'] = data[0] * 5
284 message['delay'] = data[0] * 5 + data[1]*5*256
286 message['command'] = 'MODES'
288 message['command'] = 'READ_STATE'
290 message['command'] = 'WRITE_STATE'
292 message['command'] = 'SEND_STATE'
295 message['dev_type'] = 'SLU-1-300'
296 message['dev_firmware'] = data[1]
298 dev_state = data[2] % 16
300 message['dev_state'] = [ 'OFF', 'ON', 'TEMPORARY_ON' ][dev_state]
301 message['POWER'] = message['dev_state']
304 dev_mode = data[2] // 128
306 message['dev_binding'] = 'ON'
307 message['brightness'] = data[3]
308 message['DIMMER'] = int(round(data[3]*100/255))
310 message['dev_aux'] = data[2]
311 message['dev_legacy'] = data[3]
313 message['dev_free'] = data[3]
314 message['dev_free_legacy'] = data[2]
316 message['command'] = 'SERVICE'
318 message['command'] = 'CLEAR_MEMORY'