一、准备工作1.1注册阿里云账号使用个人淘宝账号或手机号开通阿里云账号,并通过__实名认证(可使用支付宝认证)__1.2打开物联网IoT套件官网产品免费https://www.aliyun.com/product/iot1.3软件环境Nodejs安装https://nodejs.org/en/download/EditorsublimeText/nodepad++/vscodeMQTTlibhttps://www.npmjs。com/包/mqtt2.开发步骤2.1云端开发1)创建产品的高级版本2)功能定义,为产品对象模型添加属性添加产品属性,定义对象模型的对应属性,并上报topic/sys/replacedbyproductKey/replacedbydeviceName/thing/event/property/post上报payload对应的属性模型{id:123452452,params:{temperature:26.2,humidity:60.4},method:"thing.event.property.post"}3)DeviceManagement>Register设备并获取身份三元组2.2设备端开发我们使用nodejs程序模拟设备,建立连接,上报数据。1.创建文件夹aliyun-iot-demo-nodejs2。进入文件夹,创建package.json文件,添加内容3.执行npminstall命令安装sdk4。创建一个thermometer.js文件,添加内容5.执行nodethermometer.js命令1)package.json添加阿里云物联网套件sdk依赖{"name":"aliyun-iot","dependencies":{"mqtt":"2.18.8"},"author":"wongxming","license":"MIT"}2)在阿里下载安装SDK在yun-iot-demo-nodejs文件夹下,执行命令$npminstall3)应用目录结构4)模拟设备thermometer.js代码/**"dependencies":{"mqtt":"2.18.8"}*/constcrypto=require('crypto');constmqtt=require('mqtt');//设备身份三元组+区域constdeviceConfig=require("./iot-device-config.json");constoptions={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}`;consturl=`tcp://${deviceConfig.productKey}.iot-as-mqtt.${deviceConfig.regionId}.aliyuncs.com:1883`;//建立连接constclient=mqtt.connect(url,options);//Topicconsttopic=`/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`;setInterval(function(){//发布数据到topicclient.publish(topic,getPostData());},5*1000);functiongetPostData(){constpayloadJson={id:Date.now(),参数:{温度:Math.floor((Math.random()*20)+10),湿度:Math.floor((Math.random()*40)+60)},方法:“thing.event.property.post"}console.log("===postDatatopic="+topic)console.log(payloadJson)returnJSON.stringify(payloadJson);}/*根据HmacSha1生成密码参考文档:https://help.aliyun.com/document_detail/73742.html?#h2-url-1*/functionsignHmacSha1(options,deviceSecret){letkeys=Object.keys(options).sort();//按字典顺序对键进行排序=keys.种类();常量列表=[];键。map((key)=>{list.push(`${key}${options[key]}`);});constcontentStr=列表。加入('');returncrypto.createHmac('sha1',deviceSecret).update(contentStr).digest('hex');}设备配置文件{"productKey":"replaceproductKey","deviceName":"replacedeviceName","deviceSecret":"replacedeviceSecret","regionId":"cn-shanghai"}3.启动并运行3.1设备启动$nodethermometer.js3。2在云物联网平台产品介绍详情查看设备运行状态:https://www.aliyun.com/product/iot/iot_instc_public_cn阿里云物联网平台客户交流群
