基于python的onenet物联网平台温度数据仿真

一、设计思路:软件仿真是利用MQTT协议模拟前端设备与OneNet平台进行通信,OneNet云平台利用MQTT协议下发指令。

二、相关代码

初始化:

BrokerHost = '183.230.40.39'    # OneNET使用TCP方式连接时的主机地址
BrokerPort = 6002               # OneNET使用TCP方式连接时的主机端口号
DeviceId = 'xxxxxxxxx'          # 设备ID
ProductId = 'xxxxxx'            # 产品ID
APIKey = "xxxxxxxxxxxxxxxxx"    # MasterAPIKey
headers = {'api-key': APIKey}
url_post = "https://api.heclouds.com/devices/" + DeviceId + "/datapoints"  # 数据点
url_get = "https://api.heclouds.com/devices/" + DeviceId + "/datastreams"  # 数据流

MQTT连接结果:

def on_connect(client, userdata, flags, rc):
    if rc != 0:
        print("连接失败:" + mqtt.connack_string(rc))
        return
    print("***连接成功***")

消息发送:

def MQTT_send():
    Chang = random.uniform(-5, 15)
    Temperature= 20+Chang
    Temperature=round(Temperature, 2)
    data =  {
        'datastreams': [
            {
                'id': 'Temperature',    # id为数据流名称
                'datapoints': [
                    {
                        'value': Temperature
                    }
                ]
            }
        ]
    }
    jdata = json.dumps(data).encode("utf-8")
    r = requests.post(url=url_post, headers=headers, data=jdata)
    print("发送成功:", r.text)

消息发送回调:

def on_publish(client, userdata, mid):
    print("[on_publish] mid:" + str(mid))
broker响应订阅请求时被调用:
def on_subscribe(client, userdata, mid, granted_qos):
    print("***** Broker响应订阅请求*****")
    print(granted_qos)
当与代理断开连接时调用:
def on_disconnect(client, userdata,rc=0):
    logging.debug("DisConnected result code "+str(rc))
    client.loop_stop()
从服务器接收发布消息时的回调:
def on_message(client, userdata, msg):
    print("----------- 接收到消息-----------")
    # print(msg.topic + ":" + msg.payload.decode("utf-8"))
    print('接收到发布消息:'+msg.payload.decode("utf-8"))

实现代码如下:

# -*- coding: utf-8 -*-
"""
@author: 浅笑醉红楼.([email protected])
"""
import paho.mqtt.client as mqtt
import json
import random
import time
import requests
import logging

BrokerHost = '183.230.40.39'    # OneNET使用TCP方式连接时的主机地址
BrokerPort = 6002               # OneNET使用TCP方式连接时的主机端口号
DeviceId = 'xxxxxxxxx'          # 设备ID
ProductId = 'xxxxxx'            # 产品ID
APIKey = "xxxxxxxxxxxxxxxxx"    # MasterAPIKey
header = {'api-key': APIKey}
url_post = "https://api.heclouds.com/devices/" + DeviceId + "/datapoints"  # 数据点
url_get = "https://api.heclouds.com/devices/" + DeviceId + "/datastreams"  # 数据流

# 传输数据,随机数模拟
def MQTT_send():
    Chang = random.uniform(-5, 15)
    Temperature= 20+Chang
    Temperature=round(Temperature, 2)
    data =  {
        'datastreams': [
            {
                'id': 'Temperature',    # id为数据流名称
                'datapoints': [
                    {
                        'value': Temperature
                    }
                ]
            }
        ]
    }
    jdata = json.dumps(data).encode("utf-8")
    r = requests.post(url=url_post, headers=header, data=jdata)
    print("发送成功:", r.text)

def MQTT_get():
    r = requests.get(url=url_get, headers=header)
    print("返回成功:\n", r.text)

def on_connect(client, userdata, flags, rc):
    if rc != 0:
        print("连接失败:" + mqtt.connack_string(rc))
        return
    print("***连接成功***")

def on_message(client, userdata, msg):
    print("---------- 接收到消息 ----------")
    # print(msg.topic + ":" + msg.payload.decode("utf-8"))
    print('接收到发布消息:'+msg.payload.decode("utf-8"))

def on_subscribe(client, userdata, mid, granted_qos):
    print("***** Broker响应订阅请求*****")
    print(granted_qos)

def on_publish(client, userdata, mid):
    print("[on_publish] mid:" + str(mid))

def on_disconnect(client, userdata,rc=0):
    logging.debug("DisConnected result code "+str(rc))
    client.loop_stop()

if __name__ == "__main__":
    client = mqtt.Client(client_id=DeviceId, protocol=mqtt.MQTTv311)
    client.on_connect = on_connect
    client.on_publish = on_publish
    client.on_message = on_message
    client.on_subscribe = on_subscribe
    client.username_pw_set(username=ProductId, password=APIKey)
    client.connect(host=BrokerHost, port=BrokerPort, keepalive=60)
    # client.loop_forever()
    while (True):
        client.loop_start()   
        on_disconnect(client, client.username_pw_set)
        MQTT_send()
        time.sleep(2)  # 等待两秒
        MQTT_get()
        t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        print('数据上传成功:',t)

你可能感兴趣的:(物联网,物联网,python,iot,mqtt)