10分钟虚拟设备接入阿里云IoT平台实战

1. 准备工作



1.1 注册阿里云账号


使用个人淘宝账号或手机号,开通阿里云账号,并通过实名认证(可以用支付宝认证)

1.2 免费开通IoT物联网套件


产品官网 https://www.aliyun.com/product/iot

1527834006370-99ad90ea-18c9-42b6-ba2a-1d5d7bd2d0c5.png

1.3 软件环境


Nodejs安装 https://nodejs.org/en/download/
编辑器 sublimeText/nodepad++/vscode

2. 开发步骤



2.1 云端开发



1) 创建高级版产品



1527592172667-525f6784-fb16-4e3e-9f4f-c1917acae796.png

2) 功能定义,产品物模型添加属性



1527592269959-7a1feae2-25f8-47f9-8e46-8418f654fc65.png
物模型对应属性上报topic

复制代码

  1. /sys/替换为productKey/替换为deviceName/thing/event/property/post

物模型对应的属性上报payload

复制代码

  1. {
  2.     id: 123452452,
  3.     params: {
  4.         temperature: 26.2,
  5.         humidity: 60.4
  6.     },
  7.     method: "thing.event.property.post"
  8. }




3) 注册设备,获得身份三元组



1527592477943-2bda303d-5586-450e-99d5-89acd0a53128.png

2.2 设备端开发


我们以nodejs程序来模拟设备,建立连接,上报数据

1) 应用程序目录结构



1527592919268-9e027a61-00ff-45c5-964c-27acf911a37d.png

2) package.json添加阿里云IoT套件sdk依赖

 

复制代码

  1. {
  2.   "name": "aliyun-iot",
  3.   "dependencies": {
  4.     "aliyun-iot-mqtt": "^0.0.4"
  5.   },
  6.   "author": "wongxming",
  7.   "license": "MIT"
  8. }

下载安装SDK

复制代码

  1. $npm install




3) 模拟设备thermometer.js代码

 

复制代码

  1. /**
  2. "dependencies": { "aliyun-iot-mqtt": "^0.0.4" }
  3. */
  4. const mqtt = require('aliyun-iot-mqtt');
  5. //设备属性
  6. const options = {
  7.     productKey: "替换自己productKey",
  8.     deviceName: "替换自己deviceName",
  9.     deviceSecret: "替换自己deviceSecret",
  10.     regionId: "cn-shanghai"
  11. };
  12. //建立连接
  13. const client = mqtt.getAliyunIotMqttClient(options);
  14. //属性上报的Topic
  15. const topic = `/sys/${options.productKey}/${options.deviceName}/thing/event/property/post`;
  16. setInterval(function() {
  17.     //发布数据到topic
  18.     client.publish(topic, getPostData());
  19. }, 5 * 1000);
  20. function getPostData(){
  21.     const payloadJson = {
  22.         id: Date.now(),
  23.         params: {
  24.             temperature: Math.floor((Math.random() * 20) + 10),
  25.             humidity: Math.floor((Math.random() * 40) + 60)
  26.         },
  27.         method: "thing.event.property.post"
  28.     }
  29.     console.log("===postData topic=" + topic)
  30.     console.log(payloadJson)
  31.     return JSON.stringify(payloadJson);
  32. }




3. 启动运行



3.1 设备启动

 

复制代码

  1. $node thermometer.js




3.2 云端查看设备运行状态

1527593531278-77e6f426-07fc-4c2d-b903-91abae34fe9f.png

阅读后请点击

转载于:https://my.oschina.net/u/3895371/blog/1836425

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值