from Tank import Tank from paho.mqtt import client as mqtt_Client from paho.mqtt.properties import Properties from paho.mqtt.packettypes import PacketTypes tank = Tank() tank.setSpeed(40) def on_message(client, userdata, msg): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") cmd = msg.payload.decode() if cmd == 'f': tank.forward() elif cmd == 'p': tank.stop() elif cmd == 'b': tank.backward() elif cmd == 'l': tank.left() elif cmd == 'r': tank.right() elif cmd == 'u': tank.speedUp() elif cmd == 'd': tank.speedDown() def on_disconnect(client, userdata, rc): tank.stop() client = mqtt_Client.Client(client_id="RaspiCar", protocol=5) connectProperties = Properties(PacketTypes.CONNECT) publishProperties = Properties(PacketTypes.PUBLISH) # 添加断开连接的回调(可选) client.on_disconnect = on_disconnect client.connect("192.168.31.98",1883,0,properties=connectProperties) client.subscribe("carcontrol") client.on_message = on_message client.loop_forever()