一. 创建模型
进入阿里云物联网平台
点击“ 产品”
创建产品, 名称随意, 所属品类:自定义类型, 其他看情况, 确定.
创建物模型
- 编辑草稿, 创建物模型
- 添加自定义功能, 根据情况设置上传信息格式, 记着标识符
- 发布上线
二. 创建设备
产品与设备的关系: 产品是模板, 设备是按照产品生产出来的; 产品具有的功能, 设备也有.
- 创建设备
- 获取设备证书
- 保存设备证书
三. 客户端设置
- 创建python文件
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import random
import json
# 这个就是我们在阿里云注册产品和设备时的三元组啦
# 把我们自己对应的三元组填进去即可
options = {
'productKey': 'XXXXXXXX',
'deviceName': 'XXXXXXX',
'deviceSecret': 'XXXXXXX',
'regionId': 'cn-shanghai' #看情况
}
HOST = options['productKey'] + '.iot-as-mqtt.' + options['regionId'] + '.aliyuncs.com'
PORT = 1883
PUB_TOPIC = "/sys/" + options['productKey'] + "/" + options['deviceName'] + "/thing/event/property/post";
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
# client.subscribe("the/topic")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
def hmacsha1(key, msg):
return hmac.new(key.encode(), msg.encode(), hashlib.sha1).hexdigest()
def getAliyunIoTClient():
timestamp = str(int(time.time()))
CLIENT_ID = "paho.py|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|"
CONTENT_STR_FORMAT = "clientIdpaho.pydeviceName" + options['deviceName'] + "productKey" + options[
'productKey'] + "timestamp" + timestamp
# set username/password.
USER_NAME = options['deviceName'] + "&" + options['productKey']
PWD = hmacsha1(options['deviceSecret'], CONTENT_STR_FORMAT)
client = mqtt.Client(client_id=CLIENT_ID, clean_session=False)
client.username_pw_set(USER_NAME, PWD)
return client
if __name__ == '__main__':
client = getAliyunIoTClient()
client.on_connect = on_connect
client.on_message = on_message
client.connect(HOST, 1883)
#开启连接线程
client.loop_start() # client.loop_stop() 停止线程
#循环上报数据
while True:
payload_json = {
'id': int(time.time()),
'params': {
'zfx:Har': har, # 随机温度
'zfx:Mar': mar, # 随机相对湿度
'zfx:Ear': ear,
'zfx:DriveWarning': 1
},
'method': "thing.event.property.post"
}
print('send data to iot server: ' + str(payload_json))
client.publish(PUB_TOPIC, payload=str(payload_json), qos=1)
time.sleep(0.15)
params设置问题
#若是默认模块, 各标识符前不加模块的标识符, 若是创建新的模块, 那么需要加上模块标识符
例:
图中两个模块配置一样
若是默认模块:
'params': {
'Har': har, # 随机温度
'Mar': mar, # 随机相对湿度
'Ear': ear,
'DriveWarning': 1
},
若是自定义模块 标识符为:zfx
'params': {
'zfx:Har': har, # 随机温度
'zfx:Mar': mar, # 随机相对湿度
'zfx:Ear': ear,
'zfx:DriveWarning': 1
},
- 运行程序
完