Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the simply-static domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/html/wp-includes/functions.php on line 6121
树莓派配置自定义域名的mqtt服务器

树莓派配置自定义域名的mqtt服务器

几个注意事项:

1、在cpolor后台建立tcp通道,得到带有端口的tcp地址

2、在cpolar.yml配置文件里设置带端口的tcp地址,如下图:

3、在域名的后台(如阿里云)解析二级域名,地址填入以上不带端口的tcp地址,如下图:

4、完成后可以在树莓派上运行mqtt服务器程序,如下:

import sys
import os
import time
import paho.mqtt.client as mqtt

sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
sys.path.append("..")

REPORT_TOPIC = 'mqtt/myhome'  # 主题


def on_connect(client, userdata, flags, rc):
    print('connected to mqtt with resurt code ', rc)
    client.subscribe(REPORT_TOPIC)  # 订阅主题


def on_message(client, userdata, msg):

    message = msg.payload.decode()
    print(message)

def server_conenet(client):
    client.on_connect = on_connect  # 启用订阅模式
    client.on_message = on_message  # 接收消息
    client.connect("mqtt.ihand.work", 20246, 60)  # 链接
    # client.loop_start()   # 以start方式运行,需要启动一个守护线程,让服务端运行,否则会随主线程死亡
    client.loop_forever()  # 以forever方式阻塞运行。


def server_stop(client):
    client.loop_stop()  # 停止服务端
    sys.exit(0)


def server_main():
    client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    client = mqtt.Client(client_id, transport='tcp')
    server_conenet(client)


if __name__ == '__main__':
    # 启动监听
    server_main()

5、此时运行mqtt客户端即可实现通讯,如下:

import paho.mqtt.client as mqtt

client = mqtt.Client()
# 参数有 Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
#client.connect("tcp://1.tcp.hk.cpolar.io", 20246, 60)  # 连接服务器,端口为1883,维持心跳为60秒
client.connect("mqtt.ihand.work", 20246, 60)
client.publish('mqtt/myhome', '温度',1)