2020-11-04 04:26:39 +01:00
|
|
|
import logging
|
2020-11-04 13:28:07 +01:00
|
|
|
import threading
|
2020-11-01 15:06:15 +01:00
|
|
|
|
2020-11-04 13:31:25 +01:00
|
|
|
import paho.mqtt.client as mqtt
|
|
|
|
|
2020-11-03 15:15:58 +01:00
|
|
|
from frigate.config import MqttConfig
|
|
|
|
|
2020-11-04 04:26:39 +01:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2020-11-03 15:15:58 +01:00
|
|
|
def create_mqtt_client(config: MqttConfig):
|
|
|
|
client = mqtt.Client(client_id=config.client_id)
|
2020-11-01 15:06:15 +01:00
|
|
|
def on_connect(client, userdata, flags, rc):
|
2020-11-04 13:28:07 +01:00
|
|
|
threading.current_thread().name = "mqtt"
|
2020-11-01 15:06:15 +01:00
|
|
|
if rc != 0:
|
|
|
|
if rc == 3:
|
2020-11-04 04:26:39 +01:00
|
|
|
logger.error("MQTT Server unavailable")
|
2020-11-01 15:06:15 +01:00
|
|
|
elif rc == 4:
|
2020-11-04 04:26:39 +01:00
|
|
|
logger.error("MQTT Bad username or password")
|
2020-11-01 15:06:15 +01:00
|
|
|
elif rc == 5:
|
2020-11-04 04:26:39 +01:00
|
|
|
logger.error("MQTT Not authorized")
|
2020-11-01 15:06:15 +01:00
|
|
|
else:
|
2020-11-04 04:26:39 +01:00
|
|
|
logger.error("Unable to connect to MQTT: Connection refused. Error code: " + str(rc))
|
2020-11-04 13:28:07 +01:00
|
|
|
|
|
|
|
logger.info("MQTT connected")
|
2020-11-03 15:15:58 +01:00
|
|
|
client.publish(config.topic_prefix+'/available', 'online', retain=True)
|
2020-11-01 15:06:15 +01:00
|
|
|
client.on_connect = on_connect
|
2020-11-03 15:15:58 +01:00
|
|
|
client.will_set(config.topic_prefix+'/available', payload='offline', qos=1, retain=True)
|
|
|
|
if not config.user is None:
|
|
|
|
client.username_pw_set(config.user, password=config.password)
|
|
|
|
client.connect(config.host, config.port, 60)
|
2020-11-01 15:06:15 +01:00
|
|
|
client.loop_start()
|
2020-11-04 13:31:25 +01:00
|
|
|
return client
|