Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
// There are two ways to create a SAS token for a device to connect:
//
// var token = generateSasToken(
// 'hubname.azure-devices.net/devices/devicename',
// 'device shared access policy key',
// 'device',
// expiryInMins)
//
// var token = generateSasToken(
// 'hubname.azure-devices.net/devices/devicename',
// 'device key',
// null,
// expiryInMins)
var client = Client.fromSharedAccessSignature(test_token, Protocol);
console.log('IoT Hub troubleshooting tutorial\nSimulated device #2\n')
// Disable retries so you see the connection error immediately
client.setRetryPolicy(new NoRetry());
// Callback function to run after connecting to the IoT hub.
var connectCallback = function (err) {
if (err) {
console.log('Could not connect: ' + err);
} else {
console.log('Client connected');
}
client.close();
process.exit(0);
it('service invokes a sync command and it is acknowledged by the device client', function (done) {
this.timeout(60000); // eslint-disable-line no-invalid-this
// test device client
const deviceSasExpiry = Math.floor(new Date() / 1000) + 3600;
const deviceSas = DeviceSas.create(hubHostName, createdDevice.deviceId, createdDevice.authentication.symmetricKey.primaryKey, deviceSasExpiry);
const deviceClient = DeviceClient.fromSharedAccessSignature(deviceSas, Mqtt);
const digitalTwinClient = new DigitalTwinDeviceClient(capabilityModelDocument['@id'], deviceClient);
const digitalTwinServiceClient = new DigitalTwinServiceClient(credentials);
const testInterfaceInstance = new TestInterfaceInstance(testInterfaceInstanceName, function () {}, (request, response) => {
debug('command handler invoked');
assert.isNotNull(request);
assert.strictEqual(request.commandName, syncCommandName);
console.log('invoked command: ' + syncCommandName);
response.acknowledge(200, invokeCommandResponse, (err) => {
if (err) {
console.log('responding to the testInvokeCommand command failed.');
deviceClient.close(function () {
debug('device client closed');
done(err);
});
}
// There are two ways to create a SAS token for a device to connect:
//
// var token = generateSasToken(
// 'hubname.azure-devices.net/devices/devicename',
// 'device shared access policy key',
// 'device',
// expiryInMins)
//
// var token = generateSasToken(
// 'hubname.azure-devices.net/devices/devicename',
// 'device key',
// null,
// expiryInMins)
var client = Client.fromSharedAccessSignature(test_token, Mqtt);
console.log('IoT Hub troubleshooting tutorial\nSimulated device #2\n')
// Disable retries so you see the connection error immediately
client.setRetryPolicy(new NoRetry());
// Callback function to run after connecting to the IoT hub.
var connectCallback = function (err) {
if (err) {
console.log('Could not connect: ' + err);
} else {
console.log('Client connected');
}
client.close();
process.exit(0);
it('service invokes an async command and it is acknowledged then updated by the device client', function (done) {
this.timeout(60000); // eslint-disable-line no-invalid-this
// test device client
const deviceSasExpiry = Math.floor(new Date() / 1000) + 3600;
const deviceSas = DeviceSas.create(hubHostName, createdDevice.deviceId, createdDevice.authentication.symmetricKey.primaryKey, deviceSasExpiry);
const deviceClient = DeviceClient.fromSharedAccessSignature(deviceSas, Mqtt);
const digitalTwinClient = new DigitalTwinDeviceClient(capabilityModelDocument['@id'], deviceClient);
const digitalTwinServiceClient = new DigitalTwinServiceClient(credentials);
const startAfterTime = Date.now() - 5000;
let ehClient;
let requestId;
const onEventHubMessage = function (eventData) {
if (eventData.annotations['iothub-connection-device-id'] === createdDevice.deviceId) {
debug('received a message from the test device: ');
if (eventData.body.modelInformation) {
debug('device registered its interfaces');
}
if (eventData.applicationProperties && eventData.applicationProperties['iothub-command-name'] === asyncCommandName) {
assert.strictEqual(eventData.body, invokeCommandResponse);
assert.strictEqual(eventData.applicationProperties['iothub-command-statuscode'], '200');
it('can send "imploded" telemetry and it is received on the Event Hubs endpoint', function (done) {
this.timeout(60000);
const testTelemetryBody = {
firstTelemetryProperty: 1,
thirdTelemetryProperty: 'end'
};
const startAfterTime = Date.now() - 5000;
let ehClient;
// test device client
const deviceSasExpiry = Math.floor(new Date() / 1000) + 3600;
const deviceSas = DeviceSas.create(hubHostName, createdDevice.deviceId, createdDevice.authentication.symmetricKey.primaryKey, deviceSasExpiry);
const deviceClient = DeviceClient.fromSharedAccessSignature(deviceSas, Mqtt);
const digitalTwinClient = new DigitalTwinDeviceClient(capabilityModelDocument['@id'], deviceClient);
const testInterfaceInstance = new TestInterfaceInstance('testInterfaceInstance', function () {}, function () {});
digitalTwinClient.addInterfaceInstance(testInterfaceInstance);
const onEventHubMessage = function (eventData) {
if (eventData.annotations['iothub-connection-device-id'] === createdDevice.deviceId) {
debug('received a message from the test device: ');
debug(JSON.stringify(eventData.body));
if ((eventData.body.firstTelemetryProperty && eventData.body.firstTelemetryProperty === testTelemetryBody.firstTelemetryProperty) &&
(eventData.body.thirdTelemetryProperty && eventData.body.thirdTelemetryProperty === testTelemetryBody.thirdTelemetryProperty) &&
(Object.keys(eventData.body).length === 2)) {
debug('found telemetry message from test device. test successful.');
closeClients(deviceClient, ehClient, done);
}
} else {
debug('Incoming device id is: ' + eventData.annotations['iothub-connection-device-id']);
'use strict';
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-amqp').AmqpWs;
// 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;
// String SharedAccessSignature in the following formats:
// "SharedAccessSignature sr=/devices/&sig=&se="
var sas = process.env.IOTHUB_SAS;
// fromSharedAccessSignature must specify a transport constructor, coming from any transport package.
var client = Client.fromSharedAccessSignature(sas, Protocol);
var connectCallback = function (err) {
if (err) {
console.error('Could not connect: ' + err);
} 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.
});
it('service client gets the digital twin, updates a property using a partial patch, the device accepts the property update and the service is updated again.', function (done) {
this.timeout(60000);
// test device client
const deviceSasExpiry = Math.floor(new Date() / 1000) + 3600;
const deviceSas = DeviceSas.create(hubHostName, createdDevice.deviceId, createdDevice.authentication.symmetricKey.primaryKey, deviceSasExpiry);
const deviceClient = DeviceClient.fromSharedAccessSignature(deviceSas, Mqtt);
const digitalTwinClient = new DigitalTwinDeviceClient(capabilityModelDocument['@id'], deviceClient);
const desiredPropertyValue = uuid.v4();
const closeClients = function (deviceClient, err) {
debug('closing device and event hubs clients');
deviceClient.close()
.then(() => {
debug('device client closed');
done(err);
}).catch((closeErr)=> {
debug('error closing clients: ' + closeErr.toString());
done(err || closeErr);
});
};
const propertyUpdateCallback = (interfaceInstance, propertyName, reportedValue, desiredValue, version) => {
const connectWith_sharedAccessSignature = () => Client.fromSharedAccessSignature(process.env.DEVICE_SAS, Protocol)