10分钟虚拟设备接入阿里云IoT平台实战
1. 准备工作
1.1注册阿里云账号
使用个人淘宝账号或手机号,开通阿里云账号,并通过实名认证(可以用支付宝认证)
1.2免费开通IoT物联网套件
产品官网/product/iot
1.3 软件环境
Nodejs安装/en/download/
编辑器 sublimeText/nodepad++/vscode
2.开发步骤
2.1 云端开发
1) 创建高级版产品
2) 功能定义,产品物模型添加属性
物模型对应属性上报topic
复制代码
/sys/替换为productKey/替换为deviceName/thing/event/property/post
物模型对应的属性上报payload
复制代码
{id: 123452452,params: {temperature: 26.2,humidity: 60.4},method: "thing.event.property.post"}
3) 注册设备,获得身份三元组
2.2 设备端开发
我们以nodejs程序来模拟设备,建立连接,上报数据。
1) 应用程序目录结构
2) package.json添加阿里云IoT套件sdk依赖
复制代码
{"name": "aliyun-iot","dependencies": {"aliyun-iot-mqtt": "^0.0.4"},"author": "wongxming","license": "MIT"}
下载安装SDK
复制代码
$npm install
3) 模拟设备thermometer.js代码
复制代码
/**"dependencies": { "aliyun-iot-mqtt": "^0.0.4" }*/const mqtt = require('aliyun-iot-mqtt');//设备属性const options = {productKey: "替换自己productKey",deviceName: "替换自己deviceName",deviceSecret: "替换自己deviceSecret",regionId: "cn-shanghai"};//建立连接const client = mqtt.getAliyunIotMqttClient(options);//属性上报的Topicconst topic = `/sys/${options.productKey}/${options.deviceName}/thing/event/property/post`;setInterval(function() {//发布数据到topicclient.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() * 40) + 60)},method: "thing.event.property.post"}console.log("===postData topic=" + topic)console.log(payloadJson)return JSON.stringify(payloadJson);}
3. 启动运行
3.1 设备启动
复制代码
$node thermometer.js
3.2 云端查看设备运行状态