123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- import paho.mqtt.client as mqtt
- import time
- import json
- class Client(mqtt.Client):
- def __init__(self, host='127.0.0.1', port=41883):
- super().__init__()
- self.connect(host=host, port=port, keepalive=60)
- self.casper_info = {}
- # if subscribe_topic:
- # def on_message(client, userdata, message):
- # # print(f"#userdata: {userdata}")
- # # print(f"#message.payload: {str(message.payload.decode())}")
- # print(f"#message.payload: {json.loads(message.payload)}")
- # print(f"#message.topic: {message.topic}")
- #
- # self.on_message = on_message
- # self.subscribe(subscribe_topic)
- # self.loop_forever()
- def start_subscribe_loop(self, decorate_method, subscribe_topic):
- """启动订阅循环"""
- self.on_message = decorate_method
- self.subscribe(subscribe_topic)
- self.loop_forever()
- def publish_message(self, publish_topic, message):
- """发布消息"""
- try:
- results = self.publish(publish_topic, message)
- result_code, message_id = results
- """
- result_code: 错误码
- result_code.0: 成功
- result_code.1: 失败
- result_code.4: 无法连接到 MQTT 代理
- result_code.7: QoS错误
- """
- print(f"#result_code: {result_code}, #message_id: {message_id}")
- except Exception as e:
- print(f'#Exception: {e.__class__.__name__}')
- if __name__ == '__main__':
- """
- cd /home/sri/repositories/repositories/SRI-DINO.Server-py/sri-pysdk/xclient && python3 xmqtt.py
-
- pip3 install paho-mqtt==1.6.1
-
- python3 xmqtt-a1.py
- python3 xmqtt-a2.py
- python3 xmqtt.py
-
- pip3 install paho-mqtt==1.6.1 -i hhttps://mirror.baidu.com/pypi/simple
-
-
- """
- # --- init ---
- # c1 = Client(host='192.168.131.23', port=41883)
- # c1 = Client(host='127.0.0.1', port=41883)
- # c1 = Client(host='10.10.10.116', port=41883)
- c1 = Client(host='10.10.60.237', port=41883)
- # --- test subscribe ---
- # def m1(_, __, p3):
- # # print(f'#message: {p3.payload}')
- # print(f"#message.payload: {p3.payload}")
- # # print(f"#message.payload: {json.loads(p3.payload)}")
- # subscribe_topic = 'bg/log'
- # subscribe_topic = 'qtmqtt'
- # subscribe_topic = 'client'
- # subscribe_topic = 'Vehicle/ControlVehicle/Veh001'
- # subscribe_topic = 'Cockpit/CanBus/CanId001/Cop001'
- # c1.start_subscribe_loop(decorate_method=m1, subscribe_topic=subscribe_topic)
- # --- test publish ---
- while True:
- data = {
- 'code': 1001,
- }
- # topic = 'hs/vehicle/state'
- # topic = 'Vehicle/ControlVehicle/Veh0533'
- topic = 'Cockpit/CanBus/CanId001/Cop001'
- c1.publish_message(topic, json.dumps(data))
- time.sleep(3)
- # --- test publish ---
- # while True:
- # data = {
- # 'address': "192.168.131.180",
- # 'state': 2,
- # 'direction': 22,
- # }
- # c1.publish_message('hs/vehicle/state', json.dumps(data))
- # time.sleep(3)
|