Skip to content

Instantly share code, notes, and snippets.

@rido-min
Last active March 7, 2020 06:39
Show Gist options
  • Save rido-min/854b7494c8eb561e37b861e5d0da20d7 to your computer and use it in GitHub Desktop.
Save rido-min/854b7494c8eb561e37b861e5d0da20d7 to your computer and use it in GitHub Desktop.
basic_node_iot_client
node_modules/
.vscode/
'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)
})
{
"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