made reconnect actually start receiving again
This commit is contained in:
parent
30c418b8d4
commit
1f61719768
15
relay.py
15
relay.py
@ -26,6 +26,7 @@ gpio.setup(sensor_pin,gpio.IN,pull_up_down=gpio.PUD_DOWN)
|
||||
def mqtt_on_message(client, userdata, msg):
|
||||
data=str(msg.payload.decode("utf-8"))
|
||||
print("message received " ,data)
|
||||
sys.stdout.flush()
|
||||
if data=="set_low":
|
||||
set_relay(0)
|
||||
if data=="set_high":
|
||||
@ -39,15 +40,18 @@ def mqtt_on_message(client, userdata, msg):
|
||||
def mqtt_on_disconnect(client, userdata, rc):
|
||||
global CONNECTED
|
||||
print("RELAY: LOST CONNECTION")
|
||||
sys.stdout.flush()
|
||||
CONNECTED=0
|
||||
|
||||
def mqtt_on_connect(client, userdata, flags, rc):
|
||||
global CONNECTED
|
||||
if rc == 0:
|
||||
print("Connected to MQTT Broker")
|
||||
sys.stdout.flush()
|
||||
CONNECTED=1
|
||||
else:
|
||||
print("Failed to Connect MQTT")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def mqtt_setup():
|
||||
@ -56,17 +60,19 @@ def mqtt_setup():
|
||||
#client.username_pw_set(uname,pw)
|
||||
client.on_connect = mqtt_on_connect
|
||||
client.on_disconnect = mqtt_on_disconnect
|
||||
client.on_message = mqtt_on_message
|
||||
while(1): # keep trying until the network is up
|
||||
try:
|
||||
client.connect(broker,port,keepalive=60)
|
||||
break
|
||||
except:
|
||||
print("RELAY:Cant connect. waiting 1s")
|
||||
sys.stdout.flush()
|
||||
time.sleep(1)
|
||||
print("RELAY: Subscribed")
|
||||
sys.stdout.flush()
|
||||
#Subscribe
|
||||
client.subscribe(topic_control)
|
||||
client.on_message = mqtt_on_message
|
||||
return client
|
||||
|
||||
def publish_status(client):
|
||||
@ -89,10 +95,12 @@ def press_button(client):
|
||||
|
||||
def end():
|
||||
print("stop")
|
||||
sys.stdout.flush()
|
||||
RUN=0
|
||||
|
||||
def main():
|
||||
print("Start Relay Contorl")
|
||||
sys.stdout.flush()
|
||||
client=mqtt_setup()
|
||||
client.loop_start()
|
||||
publish_status(client)
|
||||
@ -102,10 +110,15 @@ def main():
|
||||
publish_status(client)
|
||||
if CONNECTED==0:
|
||||
print("RELAY: Attempting reconnect")
|
||||
sys.stdout.flush()
|
||||
try:
|
||||
client.loop_stop()
|
||||
client.reconnect()
|
||||
client.subscribe(topic_control)
|
||||
client.loop_start()
|
||||
except:
|
||||
print("Failed to reconnect")
|
||||
sys.stdout.flush()
|
||||
gpio.cleanup()
|
||||
exit()
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user