我尝试通过MQTT将小型模型车连接到经纪人。每当他们通过轨道的某个部分(此处== 20)时,他们就连接到代理,订阅并发送具有当前位置的消息。从经纪人收到消息后,他们应该与经纪人断开连接。到目前为止,这种方法效果很好,但是只有在他们第一次越过片段== 20时。一旦客户端(汽车)断开连接并使用loop_stop()终止循环,如果他们再次越过该部分,就什么也不会发生。如果我不断开连接并停止循环,则一切正常-但我希望它们断开连接并停止循环。您知道这里有什么问题吗?
from overdrive import Overdrive
import time
import paho.mqtt.client as mqtt
自动班级:
def __init__(self, macaddr):
self.car = Overdrive(macaddr)
self.client = CarClient(macaddr)
self.check = 0
def startEngine(self):
self.car.changeSpeed(300, 1000)
self.car.setLocationChangeCallback(self.locationChangeCallback) # Set location change callback to function above
def locationChangeCallback(self, addr, location, piece, speed, clockwise):
if piece == 20 :
self.client.run(piece)
CarClient类:
def __init__(self, id):
self.client = mqtt.Client(id)
self.id = id
def on_connect(self, mqttc, obj, flags, rc):
print("connected" + str(rc))
def on_message(self, mqttc, obj, msg):
print("received message" + " " + str(msg.payload))
self.client.disconnect() #if i remove this and the following line, everything works fine
self.client.loop_stop() #but i have to disconnect and stop the loop after they received a message
def on_publish(self, mqttc, obj, mid):
print("Data published " + str(mid))
def on_subscribe(self, mqttc, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(self, mqttc, obj, level, string):
print(string)
def run(self, position):
self.position = position
self.client.on_message = self.on_message
self.client.connect("localhost", 1883, 60) # connect to broker
time.sleep(0.1)
self.client.subscribe("test_channel") # subscribe topic
self.client.loop_start()
self.client.publish("test_channel1", "ID:" + str(self.id) + " Position: " + str(position))
Main()
def main():
bmw = Auto("D8:4E:11:7C:25:BD")
bmw.startEngine()
if __name__ == '__main__' :
main()
我终于找到了问题。停止循环的函数不称为loop_stop(),其称为loop.stop()。
因此代码段必须更改为以下内容:
def on_message(self, mqttc, obj, msg):
print("received message" + " " + str(msg.payload))
self.client.disconnect()
self.client.loop.stop()
仍然感谢