diff --git a/main.py b/main.py index 4a5f008..db71f08 100644 --- a/main.py +++ b/main.py @@ -7,6 +7,7 @@ from machine import Pin from umqtt.robust import MQTTClient import wifi_config import mqtt_config +import ha_mqtt_config from pico_funcs import read_cpu_temp, wlan_up, led_error_code from hcsr04_funcs import read_hc_sr04 @@ -39,6 +40,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 HC-SR04 trig = Pin(TRIG_PIN, Pin.OUT) echo = Pin(ECHO_PIN, Pin.IN, Pin.PULL_DOWN) @@ -104,22 +114,38 @@ 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: @@ -142,14 +168,27 @@ def main(): 'WiFi Information':ifconfig, } hw_payload = json.dumps(hw_data) - - # Publish - mqtt_client.publish("home/{}".format(mqtt_config.MQTT_ZONE_ID),hc_sr04_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.') + print(f'Trying to publish...') + + if mqtt == 'mosquitto': + # Publish + mqtt_client.publish("home/{}".format(mqtt_config.MQTT_ZONE_ID),hc_sr04_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),hc_sr04_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