Skip to content

Instantly share code, notes, and snippets.

@rkttu
Last active May 2, 2019 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rkttu/16ac36a5909e7e960b85d8ae5e2b1611 to your computer and use it in GitHub Desktop.
Save rkttu/16ac36a5909e7e960b85d8ae5e2b1611 to your computer and use it in GitHub Desktop.
Azure IoT Hub Device & Service Sample Code
// 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;
// Uncomment one of these transports and then change it in fromConnectionString to test other transports
// var Protocol = require('azure-iot-device-amqp').AmqpWs;
// var Protocol = require('azure-iot-device-http').Http;
// var Protocol = require('azure-iot-device-mqtt').Mqtt;
// var Protocol = require('azure-iot-device-mqtt').MqttWs;
var Client = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;
// String containing Hostname, Device Id & Device Key in the following formats:
// "HostName=<iothub_host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"
var connectionString = 'fill here';
// fromConnectionString must specify a transport constructor, coming from any transport package.
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'));
// reject and abandon follow the same pattern.
// /!\ reject and abandon are not available with MQTT
});
// Create a message and send it to the IoT Hub every second
var sendInterval = setInterval(function () {
var windSpeed = 10 + (Math.random() * 4); // range: [10, 14]
var data = JSON.stringify({ deviceId: 'myFirstDevice', windSpeed: windSpeed });
var message = new Message(data);
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);
};
}
https://github.com/Azure/azure-iot-sdk-node/blob/master/device/core/readme.md
- sudo su
- apt-get install -y npm nodejs-legacy
- npm install -g iothub-explorer
- exit
장치 프로비져닝
- iothub-explorer login "포털에서 얻은 관리용 shared access key"
- iothub-explorer create mydevice --connection-string
- connectionString 항목 복사
- iothub-explorer logout
샘플 코드 실행 (https://github.com/Azure/azure-iot-sdk-node/tree/master/device/samples)
- cd ~
- mkdir iothello
- cd iothello
- npm install --save azure-iot-device-amqp
- https://github.com/Azure/azure-iot-sdk-node/blob/master/device/samples/simple_sample_device.js 코드 복사
- 앞 단계에서 얻은 연결 문자열을 connectionString에 대입
- nodejs device.js
참고 자료
- https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-node-node-getstarted
- https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-node-node-c2d
- https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-node-twin-getstarted
'use strict';
var EventHubClient = require('azure-event-hubs').Client;
var connectionString = 'fill here';
var printError = function (err) {
console.log(err.message);
};
var printMessage = function (message) {
console.log('Message received: ');
console.log(JSON.stringify(message.body));
console.log('');
};
var client = EventHubClient.fromConnectionString(connectionString);
client.open()
.then(client.getPartitionIds.bind(client))
.then(function (partitionIds) {
return partitionIds.map(function (partitionId) {
return client.createReceiver('$Default', partitionId, { 'startAfterTime' : Date.now()}).then(function(receiver) {
console.log('Created partition receiver: ' + partitionId)
receiver.on('errorReceived', printError);
receiver.on('message', printMessage);
});
});
})
.catch(printError);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment