Skip to content

Commit

Permalink
Sample code for a downstream device that connects to an IoT Edge devi…
Browse files Browse the repository at this point in the history
…ce (#367)

Sample code for a downstream device that connects to an IoT Edge device
  • Loading branch information
mrohera authored and pierreca committed Sep 19, 2018
1 parent 6bc7c63 commit 1fb1a2f
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 1 deletion.
89 changes: 89 additions & 0 deletions device/samples/edge_downstream_device.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// 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 fs = require('fs');
var Protocol = require('azure-iot-device-mqtt').Mqtt;
// Uncomment one of these transports and then change it in fromConnectionString to test other transports
// var Protocol = require('azure-iot-device-http').Http;
// var Protocol = require('azure-iot-device-amqp').Amqp;
var Client = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;

// 1) Obtain the connection string for your downstream device and to it
// append this string GatewayHostName=<edge device hostname>;
// 2) The edge device hostname is the hostname set in the config.yaml of the Edge device
// to which this sample will connect to.
//
// The resulting string should look like the following
// "HostName=<iothub_host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>;GatewayHostName=<edge device hostname>"
var connectionString = '[Downstream device IoT Edge connection string]';

// Path to the Edge "owner" root CA certificate
var edge_ca_cert_path = '[Path to Edge CA certificate]';

// 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);
// When using MQTT the following line is a no-op.
client.complete(msg, printResultFor('completed'));
// The AMQP and HTTP transports also have the notion of completing, rejecting or abandoning the message.
// When completing a message, the service that sent the C2D message is notified that the message has been processed.
// When rejecting a message, the service that sent the C2D message is notified that the message won't be processed by the device. the method to use is client.reject(msg, callback).
// When abandoning the message, IoT Hub will immediately try to resend it. The method to use is client.abandon(msg, callback).
// MQTT is simpler: it accepts the message by default, and doesn't support rejecting or abandoning a message.
});

// 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 temperature = 20 + (Math.random() * 10); // range: [20, 30]
var humidity = 60 + (Math.random() * 20); // range: [60, 80]
var data = JSON.stringify({ deviceId: 'myFirstDownstreamDevice', 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);
});
}
};

// Provide the Azure IoT device client via setOptions with the X509
// Edge root CA certificate that was used to setup the Edge runtime
var options = {
ca : fs.readFileSync(edge_ca_cert_path, 'utf-8'),
};

client.setOptions(options, function(err) {
if (err) {
console.log('SetOptions Error: ' + err);
} else {
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);
};
}
3 changes: 2 additions & 1 deletion device/samples/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ This folder contains simple samples showing how to use the various features of t
* **simple_sample_device_x509.js**: Connect using an X-509 certificate to IoT Hub and send and receive messages.
* **send_batch_http.js**: Connect to IoT Hub and send a batch of messages over an HTTP connection.
* **remote_monitoring**: Implements the device code used to connect to an [Azure IoT Suite Remote Monitoring preconfigured solution][remote-monitoring-pcs].
* **edge_downstream_device.js**: Connect a downstream device to IoT Edge and send and receive messages.

* Device services samples (Device Twins, Methods, and Device Management):
* **simple_sample_device_twin.js**: Shows how to syncrhonize a Device Twin with Azure IoT Hub on a device.
* **simple_sample_device_twin.js**: Shows how to synchronize a Device Twin with Azure IoT Hub on a device.
* **device_method.js**: Shows how to implement an Azure IoT Hub Cloud to Device Direct Method on a device.
* **dmpatterns_reboot_device.js**: Shows how a device handles a C2D method to reboot and provides progress updates through twin reported properties. See [device management patterns][dm-patterns] for instructions on running the device management patterns samples.
* **dmpatterns_fwupdate_device.js**: Shows how a device handles a C2D method to initiate a firmware update and provides progress updates through twin reported properties. See [device management patterns][dm-patterns] for instructions on running the device management patterns samples.
Expand Down

0 comments on commit 1fb1a2f

Please sign in to comment.