首先在阿里雲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()
運行效果
控制檯顯示