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