diff --git a/main.py b/main.py index cd47a7f..343dfd5 100644 --- a/main.py +++ b/main.py @@ -9,6 +9,7 @@ import dht import urequests import wifi_config import mqtt_config +import ha_mqtt_config # Change this GPIO PIN where your DHT22 sensor is connected DHT_22_GPIO_PIN = 3 @@ -120,6 +121,15 @@ def main(): server = mqtt_config.MQTT_HOST_NAME, ) + # Create Home Assistant MQTT Client + ha_mqtt_client = MQTTClient( + client_id = ha_mqtt_config.MQTT_CLIENT_ID, + server = ha_mqtt_config.MQTT_HOST_NAME, + keepalive = ha_mqtt_config.MQTT_KEEP, + user = ha_mqtt_config.MQTT_USERNAME, + password = ha_mqtt_config.MQTT_PASSWORD, + ) + # Create DHT22 sensor = dht.DHT22(Pin(DHT_22_GPIO_PIN)) @@ -177,22 +187,39 @@ def main(): except: continue - # MQTT Conneciton. + # MQTT Connection to Primary Broker. try: + mqtt_client.connect(clean_session = False) + mqtt_ready = True + mqtt = 'mosquitto' + if DEBUG: + print(f'Connected to Mosquitto MQTT broker.') + + except Exception as e: + if DEBUG: + print("Trouble to connecting to Mosquitto MQTT: {}".format(e)) + + + # MQTT Connection to Back Up Broker. + if not mqtt_ready: try: - mqtt_client.connect(clean_session = False) - mqtt_ready = True - if DEBUG: - print(f'MQTT Connected.') - - except Exception as e: - if DEBUG: - print("Trouble to connecting to MQTT: {}".format(e)) - led_error_code(led, 2) - time.sleep(5) - continue # Start back at the top of the While Loop - except: - continue + try: + ha_mqtt_client.connect(clean_session = False) + mqtt_ready = True + mqtt = 'ha' + if DEBUG: + print(f'Connected to the back up, Home Assistant, MQTT broker.') + + except Exception as f: + if DEBUG: + print("Trouble to connecting to Home Assistant MQTT: {}".format(f)) + led_error_code(led, 2) + time.sleep(5) + continue # Start back at the top of the While Loop + + except: + continue + # Ready to Publish? try: @@ -216,15 +243,27 @@ def main(): 'WiFi Information':ifconfig, } hw_payload = json.dumps(hw_data) - - # Publish - mqtt_client.publish("home/{}".format(mqtt_config.MQTT_ZONE_ID),dht_payload, retain=True) - mqtt_client.publish("hw/{}".format(mqtt_config.MQTT_HW_ID),hw_payload, retain=True) - - mqtt_client.disconnect() - if DEBUG: - print(f'MQTT Disconnected.') + if DEBUG: + print(f'Trying to publish...') + + + if mqtt == 'mosquitto': + # Publish + mqtt_client.publish("home/{}".format(mqtt_config.MQTT_ZONE_ID),dht_payload, retain=True) + mqtt_client.publish("hw/{}".format(mqtt_config.MQTT_HW_ID),hw_payload, retain=True) + mqtt_client.disconnect() + if DEBUG: + print(f'MQTT Disconnected.') + + if mqtt == 'ha': + # Publish + ha_mqtt_client.publish("home/{}".format(mqtt_config.MQTT_ZONE_ID),dht_payload, retain=True) + ha_mqtt_client.publish("hw/{}".format(mqtt_config.MQTT_HW_ID),hw_payload, retain=True) + ha_mqtt_client.disconnect() + if DEBUG: + print(f'MQTT Disconnected.') + except: continue