首先在阿里云IoT平台配置产品,属性和设备
添加产品
设置产品名称和自定义品类,其他默认,保存
回到产品页面设置属性
添加自定义温度和湿度属性后保存,注意标识符需要之后在代码中使用,不能有带小写或字符错误
发布上线
添加设备
查看设备
可以看到目前还没有任何数据
编写代码,需要知道三个参数
nodejs代码
安装模块
npm install aliyun-iot-mqtt -S
写码
//1.引入阿里云IoT的sdk
const mqtt = require('aliyun-iot-mqtt');
//2.设备属性
const options = {
productKey: "a1tDrXn2Dyk",
deviceName: "test1",
deviceSecret: "kTON6RVYJHO7q3V394vUl2ZAGYtYxDcw",
regionId: "cn-shanghai"};
//3.建立连接
const client = mqtt.getAliyunIotMqttClient(options);
//4.属性数据上报
const topic = `/sys/${options.productKey}/${options.deviceName}/thing/event/property/post`;
setInterval(function() {
//发布数据到topic
client.publish(topic, getPostData());
}, 5 * 1000);
function getPostData(){
const payloadJson = {
id: Date.now(),
params: {
Temperature: Math.floor((Math.random() * 20) + 10),
Humidity: Math.floor((Math.random() * 20) + 60)
},
method: "thing.event.property.post"
}
console.log("===postData topic=" + topic)
console.log(payloadJson)
return JSON.stringify(payloadJson);
}
运行效果
python代码
安装模块
pip install aliyun-python-sdk-iot-client
# -*- coding: utf-8 -*-
import aliyunsdkiotclient.AliyunIotMqttClient as iot
import json
import multiprocessing
import time
import random
options = {
'productKey':'a1tDrXn2Dyk',
'deviceName':'test1',
'deviceSecret':'kTON6RVYJHO7q3V394vUl2ZAGYtYxDcw',
'port':1883,
'host':'iot-as-mqtt.cn-shanghai.aliyuncs.com'
}
host = options['productKey'] + '.' + options['host']
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
#topic = '/' + productKey + '/' + deviceName + '/update'
print(msg.payload)
def on_connect(client, userdata, flags_dict, rc):
print("Connected with result code " + str(rc))
def on_disconnect(client, userdata, flags_dict, rc):
print("Disconnected.")
def worker(client):
topic = '/sys/'+options['productKey']+'/'+options['deviceName']+'/thing/event/property/post'
while True:
time.sleep(5)
payload_json = {
'id': int(time.time()),
'params': {
'Temperature': random.randint(20, 30),
'Humidity': random.randint(40, 50)
},
'method': "thing.event.property.post"
}
print('send data to iot server: ' + str(payload_json))
client.publish(topic, payload=str(payload_json))
if __name__ == '__main__':
client = iot.getAliyunIotMqttClient(options['productKey'], options['deviceName'], options['deviceSecret'], secure_mode=3)
client.on_connect = on_connect
client.connect(host=host, port=options['port'], keepalive=60)
p = multiprocessing.Process(target=worker, args=(client,))
p.start()
client.loop_forever()
运行效果
控制台显示