From 96073ac022653f176a5f40f165fc6a61f454f6eb Mon Sep 17 00:00:00 2001 From: Monster1025 Date: Sun, 29 Jan 2017 02:20:43 +0300 Subject: [PATCH] Now we are polling(reading state) of motion sensors in manual mode, because sometimes messages from sensors were lost. Now it works much better. Need somthing like that for buttons. --- config/config-sample.yaml | 1 + src/main.py | 29 ++++++++++++++++++++++++++++- src/xiaomihub.py | 3 +++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/config/config-sample.yaml b/config/config-sample.yaml index 8f4c316..39b3faf 100644 --- a/config/config-sample.yaml +++ b/config/config-sample.yaml @@ -7,6 +7,7 @@ mqtt: gateway: password: passw0rd + polling_interval: 2 sids: # motion diff --git a/src/main.py b/src/main.py index 1117e68..77775f9 100644 --- a/src/main.py +++ b/src/main.py @@ -29,6 +29,28 @@ def process_gateway_messages(gateway, client): except Exception as e: _LOGGER.error('Error while sending from gateway to mqtt: ', str(e)) +def read_motion_data(gateway, client, polling_interval): + first = True + while True: + try: + for device in gateway.XIAOMI_DEVICES['binary_sensor']: + model = device.get("model", "") + if (model!="motion"): + continue + sid = device['sid'] + + sensor_resp = gateway.get_from_hub(sid) + data = json.loads(sensor_resp['data']) + state = data.get("status", None) + short_id = sensor_resp['short_id'] + if (device['data'] != data or first): + device['data'] = data + client.publish(model, sid, data) + first = False + except Exception as e: + _LOGGER.error('Error while sending from mqtt to gateway: ', str(e)) + time.sleep(polling_interval) + def process_mqtt_messages(gateway, client): while True: try: @@ -48,6 +70,7 @@ if __name__ == "__main__": _LOGGER.info("Loading config file...") config=yamlparser.load_yaml('config/config.yaml') gateway_pass = yamlparser.get_gateway_password(config) + polling_interval = config['gateway'].get("polling_interval", 2) _LOGGER.info("Init mqtt client.") client = mqtt.Mqtt(config) @@ -65,5 +88,9 @@ if __name__ == "__main__": t2.daemon = True t2.start() + t3 = threading.Thread(target=read_motion_data, args=[gateway, client, polling_interval]) + t3.daemon = True + t3.start() + while True: - time.sleep(10) + time.sleep(10) \ No newline at end of file diff --git a/src/xiaomihub.py b/src/xiaomihub.py index 352fac8..26830d2 100644 --- a/src/xiaomihub.py +++ b/src/xiaomihub.py @@ -231,6 +231,7 @@ class XiaomiDevice(): self._sid = device['sid'] self._name = '{}_{}'.format(name, self._sid) self.parse_data(device['data']) + self._last_event_id = -1 self.xiaomi_hub = xiaomi_hub xiaomi_hub.XIAOMI_HA_DEVICES[self._sid].append(self) @@ -248,4 +249,6 @@ class XiaomiDevice(): return True def parse_data(self, data): + print(data) + # self._last_event_id = data return True \ No newline at end of file