Nodejs设备接入阿里云IoT平台

1. 准备工作

1.1 注册阿里云账号

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

1.2 免费开通IoT物联网套件

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

Screen Shot 2018-06-01 at 13.53.55.png | center | 569x357

1.3 软件环境

Nodejs安装 https://nodejs.org/en/download/
编辑器 sublimeText/nodepad++/vscode
MQTT lib https://www.npmjs.com/package/mqtt

2. 开发步骤

2.1 云端开发

1) 创建高级版产品

image.png | left | 747x253

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

添加产品属性定义

属性名标识符数据类型范围
温度temperaturefloat-50~100
湿度humidityfloat0~100

image.png | left | 747x186

物模型对应属性上报topic

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

物模型对应的属性上报payload

{
    id: 123452452,
    params: {
        temperature: 26.2,
        humidity: 60.4
    },
    method: "thing.event.property.post"
}
3) 设备管理>注册设备,获得身份三元组

image.png | left | 747x188

2.2 设备端开发

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

1.创建文件夹 aliyun-iot-demo-nodejs
2.进入文件夹,创建package.json文件,添加内容
3.执行npm install命令,安装sdk
4.创建thermometer.js文件,添加内容
5.执行node thermometer.js命令
1) package.json添加阿里云IoT套件sdk依赖
{
  "name": "aliyun-iot",
  "dependencies": {
    "mqtt": "2.18.8"
  },
  "author": "wongxming",
  "license": "MIT"
}
2) 下载安装SDK

在aliyun-iot-demo-nodejs文件夹下,执行命令

$ npm install
3) 应用程序目录结构
4) 模拟设备thermometer.js代码
/**
"dependencies": { "mqtt": "2.18.8" }
*/
const crypto = require('crypto');
const mqtt = require('mqtt');
//设备身份三元组+区域
const deviceConfig = require("./iot-device-config.json");

const options = {
    productKey: deviceConfig.productKey,
    deviceName: deviceConfig.deviceName,
    timestamp: Date.now(),
    clientId: Math.random().toString(36).substr(2)
}

options.password = signHmacSha1(options, deviceConfig.deviceSecret);
options.clientId = `${options.clientId}|securemode=3,signmethod=hmacsha1,timestamp=${options.timestamp}|`;
options.username = `${options.deviceName}&${options.productKey}`;

const url = `tcp://${deviceConfig.productKey}.iot-as-mqtt.${deviceConfig.regionId}.aliyuncs.com:1883`;
//建立连接
const client = mqtt.connect(url,options);

//属性上报的Topic
const topic = `/sys/${deviceConfig.productKey}/${deviceConfig.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() * 40) + 60)
        },
        method: "thing.event.property.post"
    }

    console.log("===postData topic=" + topic)
    console.log(payloadJson)

    return JSON.stringify(payloadJson);
}

/*
  生成基于HmacSha1的password
  参考文档:https://help.aliyun.com/document_detail/73742.html?#h2-url-1
*/
function signHmacSha1(options, deviceSecret) {

    let keys = Object.keys(options).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
        list.push(`${key}${options[key]}`);
    });
    const contentStr = list.join('');
    return crypto.createHmac('sha1', deviceSecret).update(contentStr).digest('hex');
}

设备配置文件

{
    "productKey": "替换productKey",
    "deviceName": "替换deviceName",
    "deviceSecret": "替换deviceSecret",
    "regionId": "cn-shanghai"
}

3. 启动运行

3.1 设备启动

$ node thermometer.js

3.2 云端查看设备运行状态

image.png | left | 602x225

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值