Python 脚本 mqtt 失败后重新连接

时间:2021-05-19 21:12:09

标签: python bluetooth mqtt

您好,我需要有关我用于家庭自动化的 python 脚本的帮助,有时会发生 mqtt 不可用我的脚本停止我希望它重试连接并重新启动操作 - 这可能吗?

我的剧本

#!/usr/bin/python
import bluetooth
from time import sleep
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish

phones = [
    {'name': 'person1', 'state': 'not home', 'mac': '<mac address>'}
    {'name': 'person2', 'state': 'not home', 'mac': '<mac address>'}
]

client = mqtt.Client("hass-client")
client.tls_set('/home/pi/certs/ca-certificates.crt')
client.username_pw_set('<username>', '<password>')
client.connect('<mqtt broker>', 8883)
client.loop_start()

while True:
    for phone in phones:
        key = "bluetooth/presence/" + phone['name']
        result = bluetooth.lookup_name(phone['mac'], timeout=3)
        if result != None:
            detected_state = 'home'
        else:
            detected_state = 'not home'

        if phone['state'] != detected_state:
            phone['state'] = detected_state
            client.publish(key, detected_state, retain=False)
    sleep(15)

client.disconnect()

0 个答案:

没有答案