123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- 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)
-
-
-
-
-
-
-
-
-
-
- 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
-
-
- """
-
-
-
-
- c1 = Client(host='10.10.60.237', port=41883)
-
-
-
-
-
-
-
-
-
-
-
-
- while True:
- data = {
- 'code': 1001,
- }
-
-
- topic = 'Cockpit/CanBus/CanId001/Cop001'
- c1.publish_message(topic, json.dumps(data))
- time.sleep(3)
-
-
-
-
-
-
-
-
-
|