Add MQTT authentication

This commit is contained in:
Correl Roush 2024-01-31 22:45:14 -05:00
parent 51a5028ea9
commit 0bd6f5e818
2 changed files with 25 additions and 6 deletions

16
main.py
View file

@ -64,8 +64,20 @@ last_mqtt_attempt = 0
def mqtt_init(): def mqtt_init():
print("Starting MQTT client") print(f"Connecting MQTT client (host: {mqtt_broker}, prefix: {mqtt_prefix})")
mqtt = MQTTClient(mqtt_client_id, mqtt_broker, keepalive=MQTT_KEEPALIVE) username = settings["mqtt"].get("username")
password = settings["mqtt"].get("password")
if username and password:
print(f"Authenticating with MQTT as user '{username}")
mqtt = MQTTClient(
mqtt_client_id,
mqtt_broker,
keepalive=MQTT_KEEPALIVE,
user=username,
password=password,
)
else:
mqtt = MQTTClient(mqtt_client_id, mqtt_broker, keepalive=MQTT_KEEPALIVE)
mqtt.set_callback(on_message) mqtt.set_callback(on_message)
mqtt.set_last_will(f"{mqtt_prefix}/status", b"offline", retain=True) mqtt.set_last_will(f"{mqtt_prefix}/status", b"offline", retain=True)
mqtt.connect() mqtt.connect()

View file

@ -4,11 +4,18 @@
"password": "job5638pit5614iced" "password": "job5638pit5614iced"
}, },
"mqtt": { "mqtt": {
"broker": "192.168.1.183", "broker": "192.168.1.13",
"prefix": "desk-controls" "prefix": "desk-controls",
"username": "desk-controls",
"password": "r9Yh]sKPa2Hw|d0G"
}, },
"home-assistant": { "home-assistant": {
"url": "http://192.168.1.183:8123", "url": "http://192.168.1.13:8123",
"api_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI3MGIyZjk0MzZkZDk0ZjNlYTRhMWVlZGRlZWMzMTU5NCIsImlhdCI6MTY5NDUzNjY3NywiZXhwIjoyMDA5ODk2Njc3fQ.uetwuZ9_Szbnuf3vbKTLclBiF24YXLHOiDBswgT8drA" "api_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI3MGIyZjk0MzZkZDk0ZjNlYTRhMWVlZGRlZWMzMTU5NCIsImlhdCI6MTY5NDUzNjY3NywiZXhwIjoyMDA5ODk2Njc3fQ.uetwuZ9_Szbnuf3vbKTLclBiF24YXLHOiDBswgT8drA"
} },
"scenes": [
"scene.morning_office",
"scene.relaxed_office",
"scene.bi_office"
]
} }