You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

can2mqtt.py 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python3
  2. from __future__ import absolute_import, print_function
  3. import sys
  4. import argparse
  5. import socket
  6. from datetime import datetime
  7. import can
  8. from can import Bus, BusState, Logger
  9. import paho.mqtt.client as mqtt
  10. def decon(msg_id):
  11. msg_prio=msg_id>>26
  12. msg_type=(msg_id>>24) & 0x03
  13. msg_dst=(msg_id>>16) & 0xFF
  14. msg_src=(msg_id>>8) & 0xFF
  15. msg_cmd=msg_id & 0xFF
  16. print("prio: ", hex(msg_prio),"type: ", hex(msg_type)," dst: ", hex(msg_dst)," src: ", hex(msg_src)," cmd: ",hex(msg_cmd))
  17. return [msg_prio, msg_type, msg_dst, msg_src, msg_cmd]
  18. def on_connect(mcp_mqtt, userdata, flags, rc):
  19. print("Connected with result code "+str(rc))
  20. # Subscribing in on_connect() means that if we lose the connection and
  21. # reconnect then subscriptions will be renewed.
  22. mcp_mqtt.subscribe("can/raw")
  23. mcp_mqtt.subscribe("ctest/#")
  24. def on_message(mcp_mqtt, userdata, msg):
  25. local_bus=userdata
  26. topic=msg.topic
  27. print("data Received topic: ", topic)
  28. m_decode=str(msg.payload.decode("utf-8","ignore"))
  29. print("data Received",m_decode)
  30. msg_id=int(m_decode.split('#')[0],16)
  31. msg_data=int(m_decode.split('#')[1],16)
  32. print(msg_data)
  33. m = can.Message(arbitration_id=msg_id,
  34. data=[msg_data],
  35. extended_id=True)
  36. try:
  37. local_bus.send(m)
  38. except BaseException as e:
  39. logging.error("Error sending can message {%s}: %s" % (m, e))
  40. print("data sent to CAN",m)
  41. def main():
  42. verbosity = 2
  43. logging_level_name = ['critical', 'error', 'warning', 'info', 'debug', 'subdebug'][min(5, verbosity)]
  44. can.set_logging_level(logging_level_name)
  45. can_filters = []
  46. config = {"can_filters": can_filters, "single_handle": True}
  47. config["interface"] = "socketcan"
  48. config["bitrate"] = 125000
  49. bus = Bus("can1", **config)
  50. print('Connected to {}: {}'.format(bus.__class__.__name__, bus.channel_info))
  51. print('Can Logger (Started on {})\n'.format(datetime.now()))
  52. mcp_mqtt = mqtt.Client()
  53. mcp_mqtt.on_connect = on_connect
  54. mcp_mqtt.on_message = on_message
  55. mcp_mqtt.user_data_set(bus)
  56. mcp_mqtt.connect("mcp", 1883, 60)
  57. try:
  58. while True:
  59. mcp_mqtt.loop_start()
  60. msg = bus.recv(1)
  61. if msg is not None:
  62. de=decon(msg.arbitration_id)
  63. m= { "prio": hex(de[0]), "type": hex(de[1]), "dst": hex(de[2]), "src": hex(de[3]), "cmd": hex(de[4]), "data": "".join("%02x" % b for b in msg.data) }
  64. print(m)
  65. mcp_mqtt.publish("can/rx", str(m))
  66. except KeyboardInterrupt:
  67. pass
  68. finally:
  69. bus.shutdown()
  70. if __name__ == "__main__":
  71. main()