Как обращаться с loop_stop () Paho MQTT - PullRequest
0 голосов
/ 05 апреля 2020

Я пытаюсь подключить маленькие модели автомобилей через MQTT к брокеру. Каждый раз, когда они проходят определенный участок (здесь кусок == 20), они подключаются к брокеру, подписываются, отправляют сообщение с текущей позицией. После того, как они получили сообщение от брокера, они должны отключиться от брокера. Пока это работает довольно хорошо, но только в первый раз, когда они пересекают кусок == 20. Как только клиент (машина) отключается и l oop завершается loop_stop (), ничего не происходит, если они пересекают раздел снова. Если я не отключу и не остановлю l oop, все будет нормально, но я хочу, чтобы они отключились и остановили l oop. У вас есть идея, в чем здесь проблема?

from overdrive import Overdrive
import time
import paho.mqtt.client as mqtt

класс Auto:

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()

1 Ответ

0 голосов
/ 05 апреля 2020

Я наконец нашел проблему. Функция остановки l oop не называется loop_stop (), она называется l oop .stop ().

Поэтому сегмент кода должен быть изменен на следующее:

def on_message(self, mqttc, obj, msg):
    print("received message" + " " + str(msg.payload))
    self.client.disconnect()
    self.client.loop.stop() 

спасибо в любом случае

...