diff --git a/get_data.py b/get_data.py index a6bd457..d631730 100644 --- a/get_data.py +++ b/get_data.py @@ -2,7 +2,6 @@ Read Xiaomi LYWSD03MMC advertised packets and send them to MQTT """ import os -from datetime import datetime from socket import gaierror from typing import TypedDict @@ -26,7 +25,6 @@ class MQTTdata(TypedDict): TypedDict ([type]): timestamp, MAC addr, temp, humidity %, battery % """ - timestamp: str mac: str temperature: float humidity: int @@ -40,28 +38,34 @@ def send_to_mqtt(data: MQTTdata) -> None: Args: data (MQTTdata): [description] """ + msgs = [ { - 'topic': f'sensors/home/{data["mac"]}/temperature', - 'payload': data['temperature'], + "topic": f"sensors/home/{data['mac']}/temperature", + "payload": data["temperature"], }, { - 'topic': f'sensors/home/{data["mac"]}/humidity', - 'payload': data['humidity'], + "topic": f"sensors/home/{data['mac']}/humidity", + "payload": data["humidity"], }, { - 'topic': f'sensors/home/{data["mac"]}/battery', - 'payload': data['battery'], + "topic": f"sensors/home/{data['mac']}/battery", + "payload": data["battery"], + }, + { + "topic": "sensors/home/{data['mac']}/tele/SENSOR", + "payload": data, }, ] - publish.multiple(msgs, hostname=os.environ.get('MQTT_HOST', 'mqtt')) + + publish.multiple(msgs, hostname=os.environ.get("MQTT_HOST", "mqtt")) def le_advertise_packet_handler( # pylint: disable=unused-argument mac: str, adv_type: int, data: bytes, - rssi: int, + rssi: int, # pylint: disable=unused-argument ) -> None: """ Handle new Xiaomi LYWSD03MMC BTLE advertise packet @@ -75,24 +79,23 @@ def le_advertise_packet_handler( # pylint: disable=unused-argument data_str = raw_packet_to_str(data) # Check for ATC preamble - if data_str[0:2] == '11' and data_str[6:10] == '1a18': + if data_str[0:2] == "11" and data_str[6:10] == "1a18": temp = int(data_str[22:26], 16) / 10 hum = int(data_str[26:28], 16) batt = int(data_str[28:30], 16) mqtt_data: MQTTdata = { - 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"), - 'mac': mac, - 'temperature': temp, - 'humidity': hum, - 'battery': batt, + "mac": mac, + "temperature": temp, + "humidity": hum, + "battery": batt, } try: send_to_mqtt(mqtt_data) except gaierror as error: - print(f'[ERROR] {error}') + print(f"[ERROR] {error}") -if __name__ == '__main__': +if __name__ == "__main__": def main() -> None: """ @@ -106,7 +109,7 @@ if __name__ == '__main__': try: sock = bluez.hci_open_dev(dev_id) # pylint: disable=c-extension-no-member except: - print(f'Cannot open bluetooth device {dev_id}') + print(f"Cannot open bluetooth device {dev_id}") raise # Set filter to "True" to see only one packet per device @@ -123,5 +126,4 @@ if __name__ == '__main__': except KeyboardInterrupt: disable_le_scan(sock) - -main() + main()