Skip to content

Instantly share code, notes, and snippets.

@ThomasPe
Created September 7, 2020 15:00
Show Gist options
  • Save ThomasPe/c109332dbba570859854646ade7e504d to your computer and use it in GitHub Desktop.
Save ThomasPe/c109332dbba570859854646ade7e504d to your computer and use it in GitHub Desktop.
IoT Edge Identity Translation Module Sample
'use strict';
const Transport = require('azure-iot-device-mqtt').Mqtt;
const ModuleClient = require('azure-iot-device').ModuleClient;
const Message = require('azure-iot-device').Message;
const DeviceClient = require('azure-iot-device').Client;
let simulatedTemperatureClient;
ModuleClient.fromEnvironment(Transport, function (err, moduleClient) {
if (err) {
throw err;
} else {
moduleClient.on('error', function (err) {
throw err;
});
// connect to the Edge instance
moduleClient.open(function (err) {
if (err) {
throw err;
} else {
console.log('IoT Hub module client initialized');
const simulatedTemperatureClientConnectionString = process.env.simulatedTemperatureClientConnectionString;
if (simulatedTemperatureClientConnectionString) {
console.log("Device Connection string", simulatedTemperatureClientConnectionString);
simulatedTemperatureClient = DeviceClient.fromConnectionString(simulatedTemperatureClientConnectionString, Transport);
}
else {
console.log("Please configure the device connection string in environment variables");
}
// Act on input messages to the module.
moduleClient.on('inputMessage', function (inputName, msg) {
console.log("new message received", msg);
if (simulatedTemperatureClient) {
// Identity Translation configured, wrap message fro IoT device
const message = msg.getBytes().toString('utf8');
const sensorMsg = new Message(message);
simulatedTemperatureClient.sendEvent(sensorMsg);
} else {
// No Identity Translation configured, send message through module
pipeMessage(moduleClient, inputName, msg);
}
});
}
});
}
});
// This function just pipes the messages without any change.
function pipeMessage(client, inputName, msg) {
client.complete(msg, printResultFor('Receiving message'));
if (inputName === 'input1') {
var message = msg.getBytes().toString('utf8');
if (message) {
var outputMsg = new Message(message);
client.sendOutputEvent('output1', outputMsg, printResultFor('Sending received message'));
}
}
}
// 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