mqtt 组成
1、mqtt 服务器 2、mqtt 订阅者 sub 3、mqtt 发送者 pub
搭建mqtt 使用emqx,我的本地机器是centos 8 云服务是 centos 7.8,搭建大同小异
搭建服务的话,看官网最好
然后就是测试啥的了,用python 测试 订阅 发送
先写订阅 建立 sub_car.py
class MqttSub(object):
def __init__(self, topic):
self.client = mqtt.Client()
self.topic = topic
self.username = 'caoyong'
self.password = 'admin123'
def on_connect(self, client_driver, userdata, flags, rc):
logger.info("Connected with result code: " + str(rc))
print("Connected with result code: " + str(rc))
print(rc)
if rc == 0:
client_driver.subscribe(self.topic, qos=0)
@classmethod
def on_message(cls, client_driver, userdata, msg):
logger.info(f'{msg.topic} {msg.payload}')
print(f'{msg.topic} {msg.payload}')
sub_data = json.loads(msg.payload.decode('utf-8'))
logger.info(f'{get_now()}{sub_data}')
print(sub_data)
start_time = sub_data['time']
end_time = time.time() - start_time
print('消息从发送到接收的时间', end_time)
logger.info(f'{get_now()}消息从发送到接收的时间{end_time}')
if 'open_door' in sub_data.keys():
open_door()
end_time = time.time() - start_time
print(end_time)
logger.info(f'{get_now()}最终时间{end_time}')
def mqtt_main(self):
self.client.username_pw_set(username=self.username, password=self.password)
self.client.connect('192.168.22.70', 61883, 600)
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.loop_forever(retry_first_connection=True) # 保持连接
if __name__ == '__main__':
now_topic = 'door'
MqttSub(topic=now_topic).mqtt_main()
然后 发布 pub_car.py
import json
import time
import paho.mqtt.client as mqtt
if __name__ == '__main__':
control_topic = 'control'
client = mqtt.Client()
client.username_pw_set(username='caoyong', password='admin123')
client.connect('192.168.22.70', 61883, 600) # 600为keepalive的时间间隔
push_new = {'0': 1, 'time': time.time(),
'push_rtmp': 0,
'camera_up_down': {'angle': 45},
'camera_left_right': {'angle': 90},
'car_left_right': {'angle': 45},
'car_up_down': {'car_status': 1, 'speed': 'high'},
'cat_stop': 1
}
client.publish(control_topic, payload=json.dumps(push_new), qos=0)
然后发现一个问题,mqtt 使用本地电脑 查看时间 要 0.015s 使用其他电脑 订阅 居然要 2s+ 不知道为啥,计划用mqtt 控制,但是 实际操作起来 不太可行 延迟太大