Last active
March 7, 2020 06:39
-
-
Save rido-min/854b7494c8eb561e37b861e5d0da20d7 to your computer and use it in GitHub Desktop.
basic_node_iot_client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
node_modules/ | |
.vscode/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const Mqtt = require('azure-iot-device-mqtt').Mqtt | |
const DeviceClient = require('azure-iot-device').Client | |
const Message = require('azure-iot-device').Message | |
const cs = 'HostName=demopnp.azure-devices.net;DeviceId=node-pnp-01;SharedAccessKey=WtXD0wzRE/BZ5z/16AIYOzqTE3f5EJiU9fFGZmpRwkw=' | |
const client = DeviceClient.fromConnectionString(cs, Mqtt) | |
client.open((err)=>{ | |
if (err) throw err | |
client.getTwin((e,t)=>{ | |
if (e) throw e | |
t.on('properties.desired', (d)=>{ | |
console.log(JSON.stringify(d)) | |
}) | |
t.properties.reported.update({"deviceProperty" : "some Value"}, (e)=> { | |
if (e) throw e; | |
console.log("twin prop reported") | |
}) | |
}) | |
client.onDeviceMethod('$iotin:sensor*start', (req, resp) => { | |
console.log('received command: $iotin:sensor*start') | |
console.log(req.status) | |
console.log(req.payload) | |
resp.send(200, (e) => console.log(e) ) | |
}) | |
setInterval(()=> { | |
const t = 65.5 + Math.ceil(Math.random() * 10) | |
const h = 12.2 + Math.ceil(Math.random() * 10) | |
const b = 10 + Math.ceil(Math.random() * 10) | |
const json = { temperature: t, humidity: h, battery: b } | |
const msg = new Message(JSON.stringify(json)) | |
client.sendEvent(msg, (e) => { | |
if (e) throw e | |
console.log(`Telemetry sent- temp:${t} humd:${h} batt:${b}`) | |
}) | |
}, 3000) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "iot-demo", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"keywords": [], | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"azure-iot-device": "^1.12.2", | |
"azure-iot-device-mqtt": "^1.11.2" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment