Node-Red物联网教程10:上传数据到阿里云物联网平台
1.创建Node-Red应用
const http = require('http') const express = require('express') const RED = require('node-red') const path = require("path") const iot = require('alibabacloud-iot-device-sdk') const userSettings = require('./userSettings') const app = express() app.get('/', function (req, res) { res.send('hello world') }) JSON.stringify const device = iot.device({ productKey: userSettings.productKey, deviceName: userSettings.deviceName, deviceSecret: userSettings.deviceSecret, }) const server = http.createServer(app) const nodePath = path.join(__dirname, 'nodered') const nodeSettings = { httpAdminRoot: '/red', httpNodeRoot: '/api', userDir: nodePath, functionGlobalContext: { device } } RED.init(server, nodeSettings) app.use(nodeSettings.httpAdminRoot, RED.httpAdmin) app.use(nodeSettings.httpNodeRoot, RED.httpNode) server.listen(3000, function () { console.log('server is running on port:3000') }) RED.start()
2.Node-Red中配置
打开浏览器,地址栏输入:localhost:3000/red
Node-Red节点程序
[{"id":"e71c589c.228678","type":"tab","label":"流程1","disabled":false,"info":""},{"id":"1731447b.019a8c","type":"inject","z":"e71c589c.228678","name":"","topic":"","payload":"","payloadType":"date","repeat":"5","crontab":"","once":false,"onceDelay":0.1,"x":270,"y":160,"wires":[["21eeadc.da4cf52"]]},{"id":"21eeadc.da4cf52","type":"function","z":"e71c589c.228678","name":"","func":"msg.payload=Math.round(Math.random()*1000)\nreturn msg;","outputs":1,"noerr":0,"x":510,"y":160,"wires":[["1629134a.1252dd","444b14a.503e8ec"]]},{"id":"1629134a.1252dd","type":"function","z":"e71c589c.228678","name":"上报属性","func":"const device=global.get('device')\n\ndevice.postProps({\n \"temp\":msg.payload\n },res=>{\n console.log(res)\n flow.set('flag',true)\n flow.set('res',res)\n})\n\nlet flag=flow.get('flag')\nlet res=flow.get('res')\n\nif(flag==true){\n msg.payload={\n code:res.code,\n message:res.message\n }\n flow.set('flag',false)\n}else{\n msg=null\n}\n\nreturn msg\n","outputs":1,"noerr":0,"x":770,"y":320,"wires":[["14fe3247.c62eee"]]},{"id":"14fe3247.c62eee","type":"debug","z":"e71c589c.228678","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","x":770,"y":460,"wires":[]},{"id":"444b14a.503e8ec","type":"debug","z":"e71c589c.228678","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":780,"y":160,"wires":[]}]