我正在尝试监视mqtt代理,以便在连接中断时触发通知。
我的方法是创建一个除了监控代理之外什么都不做的云客户端。 “on_disconnect”似乎是合适的方法,但我不能让它触发。 (我一直在不同的终端上加载和卸载代理服务)。
该方法是一个骨架:
import random
import time
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
def on_message(client, userdata, message):
print message
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
mqttc.subscribe('control/iterate',qos=0)
def on_disconnect(client, userdata, rc):
print("Disconnected")
mqttc = mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect('10.147.17.234', port=1883, keepalive=1)
print("test")
mqttc.loop_forever()
显然有很简单的方法可以做到这一点,但我觉得这个问题有一个优雅的解决方案,我只是缺少。
答案 0 :(得分:1)
您实际上并未在代码中添加on_disconnect回调:
import random
import time
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
def on_message(client, userdata, message):
print message
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
mqttc.subscribe('control/iterate',qos=0)
def on_disconnect(client, userdata, rc):
print("Disconnected")
mqttc = mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
#added the following line
mqttc.on_disconnect = on_disconnect
mqttc.connect('10.147.17.234', port=1883, keepalive=1)
print("test")
mqttc.loop_forever()