Contoller.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. from Tank import Tank
  2. from paho.mqtt import client as mqtt_Client
  3. from paho.mqtt.properties import Properties
  4. from paho.mqtt.packettypes import PacketTypes
  5. tank = Tank()
  6. tank.setSpeed(40)
  7. def on_message(client, userdata, msg):
  8. print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
  9. cmd = msg.payload.decode()
  10. if cmd == 'f':
  11. tank.forward()
  12. elif cmd == 'p':
  13. tank.stop()
  14. elif cmd == 'b':
  15. tank.backward()
  16. elif cmd == 'l':
  17. tank.left()
  18. elif cmd == 'r':
  19. tank.right()
  20. elif cmd == 'u':
  21. tank.speedUp()
  22. elif cmd == 'd':
  23. tank.speedDown()
  24. def on_disconnect(client, userdata, rc):
  25. tank.stop()
  26. client = mqtt_Client.Client(client_id="RaspiCar", protocol=5)
  27. connectProperties = Properties(PacketTypes.CONNECT)
  28. publishProperties = Properties(PacketTypes.PUBLISH)
  29. # 添加断开连接的回调(可选)
  30. client.on_disconnect = on_disconnect
  31. client.connect("192.168.31.98",1883,0,properties=connectProperties)
  32. client.subscribe("carcontrol")
  33. client.on_message = on_message
  34. client.loop_forever()