物美物联自己记录

设备上线发布

topic /{productId}/{deviceNum}/info/post # 客户端发布设备信息-上线-下线-
# 描述:设备上电后发布设备信息
#device_name:       "产品SN"码
#product_id:	     "产品编号灭蚊器是1”
#product_name:      "产品名称 驱蚊器"
#user_id:	    	 "用户id 用户创建会有一个id 出厂id 0"
#user_name:	         "用户注册名”
#tenant_id:	         "租户id"
#tenant_name:	     "租户名"
#serial_number	     "产品SN"
#firmware_version	 "固件版本"
# status             设备状态,1:未激活,2:禁用,3:在线,4:离线
# rssi               设备强度(信号极好[-55— 0],信号好[-70— -55],信号一般[-85— -70],信号差[-100— -85])
things_model_value   "物理模型”

{
     "device_name":"sn码",
     "product_name":"树莓派",
     "tenant_id":"1",
     "rssi": -20,
     "firmwareVersion": 1.10,
     "status": 1,
     "userId": 1
    
}

物美物联自己记录_第1张图片

 开关信息发布

topic /{productId}/{deviceNum}/function/post  #方法发布
[{"id":"mos_key","value":"1"}]

开关信息订阅

topic /{productId}/{deviceNum}/function/get #方法订阅
[{"id":"mos_key","value":"1"}]

属性发布

topic /{productId}/{deviceNum}/property/post #属性订阅

[    
    {
         "id": "mos_switch", 
         "value": "1", 
         "shadow": ""
     }, 
     {
          "id": "mos_num",
          "value": "2", 
          "shadow": ""
     }
]

属性订阅

topic /{productId}/{deviceNum}/property/get #属性订阅

[    
    {
         "id": "mos_switch", 
         "value": "1", 
         "shadow": ""
     }, 
     {
          "id": "mos_num",
          "value": "2", 
          "shadow": ""
     }
]

 树莓派代码

#!/usr/bin/env python
#coding:utf-8

import time
import json
import psutil
import random
from paho.mqtt import client as mqtt_client
import uuid
broker = '192.168.0.214'  # mqtt代理服务器地址
port = 1883				# 端口
keepalive = 60     		# 与代理通信之间允许的最长时间段(以秒为单位)

def get_mac_address():
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:].upper()
    return '%s:%s:%s:%s:%s:%s' % (mac[0:2],mac[2:4],mac[4:6],mac[6:8],mac[8:10],mac[10:])
macAddress = get_mac_address()
client_id = f'python-mqtt-pub-{macAddress}'  # 客户端id不能重复

def device_info():
    info = {
     "device_name":macAddress,
     "product_name":"智能灭蚊器",
     "tenant_id":"1",
     "rssi": -20,
     "firmwareVersion": 1.0,
     "status": 3,
     "userId": 1,
     "things_model_value": [{"id": "mos_switch", "value": "", "shadow": ""}, {"id": "mos_num", "value": "", "shadow": ""}],
    }
    # mqtt只能传输字符串数据
    return json.dumps(info)
#遗嘱消息
def device_willinfo():
    info = {
     "device_name":macAddress,
     "product_name":"智能灭蚊器",
     "tenant_id":"1",
     "rssi": -20,
     "firmwareVersion": 1.0,
     "status": 4,
     "userId": 1,
     "things_model_value": [{"id": "mos_switch", "value": "", "shadow": ""}, {"id": "mos_num", "value": "", "shadow": ""}],
    }
    # mqtt只能传输字符串数据
    return json.dumps(info)
#订阅开关消息
def on_connect(client, userdata, flags, rc):
    '''连接回调函数'''
    # 响应状态码为0表示连接成功
    print("Connected with result code " + str(rc))

    client.subscribe("/1/" + macAddress + "/function/post")  # 订阅消息
    client.subscribe("/1/" + macAddress + "/function/get")  # 订阅消息
    client.subscribe("/1/" + macAddress + "/property/post")  # 订阅消息
    client.subscribe("/1/" + macAddress + "/property/get")  # 订阅消息
    client.subscribe("/1/" + macAddress + "/function-online/post")  # 订阅消息
    client.subscribe("/1/" + macAddress + "/function-online/get")  # 订阅消息
    client.subscribe("/1/" + macAddress + "/property-online/post")  # 订阅消息
    client.subscribe("/1/" + macAddress + "/property-online/get")  # 订阅消息

def connect_mqtt():
    '''连接mqtt代理服务器'''

    # 连接mqtt代理服务器,并获取连接引用
    client = mqtt_client.Client(client_id)
    client.username_pw_set("wumei-smart", "wumei-smart")		# 连接MQTT的账户和密码
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_subscribe = on_subscribe
    client.on_disconnect = on_disconnect
    client.will_set("/1/" + macAddress + "/info/post",device_willinfo(), 0, False)#设置遗嘱消息
    client.connect(broker, port, keepalive)
    return client

def factory_publish(client):
    '''发布上线消息'''
    msg = device_info()
    topic = "/1/" + macAddress + "/info/post"  # 设备上线
    print(topic)
    result = client.publish(topic, msg)
    status = result[0]
    if status == 0:
        print(f"Send `{msg}` to topic `{topic}`")
    else:
        print(f"Failed to send message to topic {topic}")




def on_message(client, userdata, msg):
    print("主题:"+msg.topic+" 消息:"+str(msg.payload.decode('utf-8')))
    #解析json
    data = json.loads(msg.payload.decode('utf-8'))
    print(data)
    # 解析字典数据
    print("key = "+data[0]['id'])
    print(data[0]['value'])
    if str(data[0]['id'])=="mos_key":
        print("灭蚊器")
        if int(data[0]['value']) == 1:
            print("灭蚊器开始工作")
        if int(data[0]['value']) == 0:
            print("灭蚊器停止工作")






def on_subscribe(client, userdata, mid, granted_qos):
    print("On Subscribed: qos = %d" % granted_qos)


def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection %s" % rc)

def run():
    '''运行发布者'''
    client = connect_mqtt()
    # 运行一个线程来自动调用loop()处理网络事件, 非阻塞
   # client.loop_start()
    factory_publish(client)
    client.loop_forever()

if __name__ == '__main__':
    run()

你可能感兴趣的:(python,mqtt)