How to use the azure-iot-device.Client.fromSharedAccessSignature function in azure-iot-device

To help you get started, we’ve selected a few azure-iot-device examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Azure-Samples / azure-iot-samples-node / iot-hub / Tutorials / ConnectivityTests / SimulatedDevice-2.js View on Github external
// 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);
github Azure / azure-iot-sdk-node / digitaltwins / e2e / digitaltwin_commands.js View on Github external
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);
          });
        }
github Azure-Samples / azure-iot-samples-node / Tutorials / Troubleshooting / simulated-device / SimulatedDevice-2.js View on Github external
// 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);
github Azure / azure-iot-sdk-node / digitaltwins / e2e / digitaltwin_commands.js View on Github external
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');
github Azure / azure-iot-sdk-node / digitaltwins / e2e / digitaltwin_telemetry.js View on Github external
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']);
github Azure / azure-iot-sdk-node / device / samples / simple_sample_device_with_sas.js View on Github external
'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.
    });
github Azure / azure-iot-sdk-node / digitaltwins / e2e / digitaltwin_properties.js View on Github external
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) => {
github Azure / azure-iot-sdk-node / device / samples / device_connectionMethods.js View on Github external
const connectWith_sharedAccessSignature = () => Client.fromSharedAccessSignature(process.env.DEVICE_SAS, Protocol)