Created
May 17, 2019 09:13
-
-
Save bastisk/41f77745fd56c8da469a7581bccbb5a5 to your computer and use it in GitHub Desktop.
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
// Copyright (c) Microsoft. All rights reserved. | |
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | |
'use strict'; | |
var Protocol = require('azure-iot-device-amqp').AmqpWs; | |
var Protocol = require('azure-iot-device-http').Http; | |
var Client = require('azure-iot-device').Client; | |
var Message = require('azure-iot-device').Message; | |
var connectionString = '[IoT device connection string]'; | |
var client = Client.fromConnectionString(connectionString, Protocol); | |
var connectCallback = function (err) { | |
if (err) { | |
console.error('Could not connect: ' + err.message); | |
} else { | |
console.log('Client connected'); | |
client.on('message', function (msg) { | |
console.log('Id: ' + msg.messageId + ' Body: ' + msg.data); | |
client.complete(msg, printResultFor('completed')); | |
}); | |
// Create a message and send it to the IoT Hub every two seconds | |
var sendInterval = setInterval(function () { | |
var windSpeed = 10 + (Math.random() * 4); // range: [10, 14] | |
var temperature = 20 + (Math.random() * 10); // range: [20, 30] | |
var humidity = 60 + (Math.random() * 20); // range: [60, 80] | |
var data = JSON.stringify({ deviceId: 'myFirstDevice', windSpeed: windSpeed, temperature: temperature, humidity: humidity }); | |
var message = new Message(data); | |
message.properties.add('temperatureAlert', (temperature > 28) ? 'true' : 'false'); | |
console.log('Sending message: ' + message.getData()); | |
client.sendEvent(message, printResultFor('send')); | |
}, 2000); | |
client.on('error', function (err) { | |
console.error(err.message); | |
}); | |
client.on('disconnect', function () { | |
clearInterval(sendInterval); | |
client.removeAllListeners(); | |
client.open(connectCallback); | |
}); | |
} | |
}; | |
client.open(connectCallback); | |
// Helper function to print results in the console | |
function printResultFor(op) { | |
return function printResult(err, res) { | |
if (err) console.log(op + ' error: ' + err.toString()); | |
if (res) console.log(op + ' status: ' + res.constructor.name); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment