setup auto reconnect to mqtt broker
This commit is contained in:
parent
36b3d4626e
commit
30c418b8d4
21
relay.py
21
relay.py
@ -10,9 +10,10 @@ port = 1883
|
||||
topic_sensor = 'garage/door_sensor'
|
||||
topic_control = 'garage/door_control'
|
||||
client_id = str(210)
|
||||
BUTTON_TIME=1 #seconds
|
||||
BUTTON_TIME=0.75 #seconds
|
||||
|
||||
RUN=1
|
||||
CONNECTED = 0
|
||||
|
||||
#GPIO settings
|
||||
relay_pin = 15
|
||||
@ -35,9 +36,16 @@ def mqtt_on_message(client, userdata, msg):
|
||||
# end()
|
||||
# client.loop_stop()
|
||||
|
||||
def mqtt_on_disconnect(client, userdata, rc):
|
||||
global CONNECTED
|
||||
print("RELAY: LOST CONNECTION")
|
||||
CONNECTED=0
|
||||
|
||||
def mqtt_on_connect(client, userdata, flags, rc):
|
||||
global CONNECTED
|
||||
if rc == 0:
|
||||
print("Connected to MQTT Broker")
|
||||
CONNECTED=1
|
||||
else:
|
||||
print("Failed to Connect MQTT")
|
||||
|
||||
@ -47,6 +55,7 @@ def mqtt_setup():
|
||||
client = mqtt_client.Client(client_id)
|
||||
#client.username_pw_set(uname,pw)
|
||||
client.on_connect = mqtt_on_connect
|
||||
client.on_disconnect = mqtt_on_disconnect
|
||||
while(1): # keep trying until the network is up
|
||||
try:
|
||||
client.connect(broker,port,keepalive=60)
|
||||
@ -61,7 +70,8 @@ def mqtt_setup():
|
||||
return client
|
||||
|
||||
def publish_status(client):
|
||||
client.publish(topic_sensor,str(get_sensor()),retain=True)
|
||||
#client.publish(topic_sensor,str(get_sensor()),retain=True)
|
||||
client.publish(topic_sensor,str(get_sensor()))
|
||||
|
||||
def set_relay(value):
|
||||
if value==1:
|
||||
@ -88,7 +98,14 @@ def main():
|
||||
publish_status(client)
|
||||
while(RUN):
|
||||
time.sleep(5)
|
||||
#print("CONNECTED:",CONNECTED)
|
||||
publish_status(client)
|
||||
if CONNECTED==0:
|
||||
print("RELAY: Attempting reconnect")
|
||||
try:
|
||||
client.reconnect()
|
||||
except:
|
||||
print("Failed to reconnect")
|
||||
gpio.cleanup()
|
||||
exit()
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user