How to use azure-iot-device-mqtt - 10 common examples

To help you get started, we’ve selected a few azure-iot-device-mqtt 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 / azure-iot-sdk-node / longhaultests / src / iothub_longhaul.ts View on Github external
const deviceId = 'node-longhaul-sak-' + uuid.v4();
let protocol;

/* tslint:disable:no-var-requires */
switch (process.env.DEVICE_PROTOCOL) {
  case 'amqp':
    protocol = require('azure-iot-device-amqp').Amqp;
  break;
  case 'amqp-ws':
    protocol = require('azure-iot-device-amqp').AmqpWs;
  break;
  case 'mqtt':
    protocol = require('azure-iot-device-mqtt').Mqtt;
  break;
  case 'mqtt-ws':
    protocol = require('azure-iot-device-mqtt').MqttWs;
  break;
  case 'http':
    protocol = require('azure-iot-device-mqtt').Http;
  break;
  default:
    debug('unknown protocol: ' + process.env.DEVICE_PROTOCOL);
    process.exit(ERROR_EXIT_CODE);
}
/* tslint:enable:no-var-requires */

const createDevice = (callback) => {
  debug('creating device: ' + deviceId);
  timeout(registry.create.bind(registry), MAX_CREATE_TIME)({ deviceId: deviceId }, (err, deviceInfo) => {
    if (err) {
      debug('error creating device: ' + deviceId + ':' + err.toString());
      callback(err);
github Azure / azure-iot-sdk-node / longhaultests / src / iothub_longhaul.ts View on Github external
/* tslint:disable:no-var-requires */
switch (process.env.DEVICE_PROTOCOL) {
  case 'amqp':
    protocol = require('azure-iot-device-amqp').Amqp;
  break;
  case 'amqp-ws':
    protocol = require('azure-iot-device-amqp').AmqpWs;
  break;
  case 'mqtt':
    protocol = require('azure-iot-device-mqtt').Mqtt;
  break;
  case 'mqtt-ws':
    protocol = require('azure-iot-device-mqtt').MqttWs;
  break;
  case 'http':
    protocol = require('azure-iot-device-mqtt').Http;
  break;
  default:
    debug('unknown protocol: ' + process.env.DEVICE_PROTOCOL);
    process.exit(ERROR_EXIT_CODE);
}
/* tslint:enable:no-var-requires */

const createDevice = (callback) => {
  debug('creating device: ' + deviceId);
  timeout(registry.create.bind(registry), MAX_CREATE_TIME)({ deviceId: deviceId }, (err, deviceInfo) => {
    if (err) {
      debug('error creating device: ' + deviceId + ':' + err.toString());
      callback(err);
    } else {
      debug('device created: ' + deviceId);
      const cs = HubConnectionString.parse(hubConnectionString);
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 / iot-hub / Tutorials / ConnectivityTests / SimulatedDevice-1.js View on Github external
'use strict';

// The device connection string to authenticate the device with your IoT hub.
// Using the Azure CLI:
// az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyTestDevice --output table
var connectionString = '{your device connection string}';

// Using the Node.js Device SDK for IoT Hub:
//   https://github.com/Azure/azure-iot-sdk-node
// The sample connects to a device-specific MQTT endpoint on your IoT Hub.
var Protocol = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;
var NoRetry = require('azure-iot-common').NoRetry;
var client = Client.fromConnectionString(connectionString, Protocol);

console.log('IoT Hub troubleshooting tutorial\nSimulated device #1\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-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 / device / samples / upload_to_blob_v2.js View on Github external
blockBlobURL,
    4 * 1024 * 1024, // 4MB block size
    20, // 20 concurrency
    {
      progress: ev => console.log(ev)
    }
    );
    console.log('uploadStreamToBlockBlob success');
    // END STORAGE CODE

    // notify IoT Hub of upload to blob status (success/faillure)
    await client.notifyBlobUploadStatus(uploadStatus);
    return 0;
}

uploadToBlob(localFilePath, Client.fromConnectionString(deviceConnectionString, Protocol))
  .catch((err) => {
    return new Error(err);
  });
github Azure / azure-iot-sdk-node / device / edge-sample / edge_sample_module.js View on Github external
// 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-mqtt').Mqtt;
var Client = require('azure-iot-device').ModuleClient;
var Message = require('azure-iot-device').Message;
var fs = require('fs');

var connectionString = process.env.EdgeHubConnectionString;

var client = Client.fromConnectionString(connectionString, Protocol);
console.log('got client');

client.on('error', function (err) {
  console.error(err.message);
});

client.setOptions({
  ca: fs.readFileSync(process.env.EdgeModuleCACertificateFile).toString('ascii')
}, function(err) {
  if (err) {
    console.log('error:' + err);
  } else {
    // connect to the edge instance
    client.open(function (err) {
      if (err) {
        console.error('Could not connect: ' + err.message);
github Azure / azure-iot-sdk-node / digitaltwins / e2e / digitaltwin_telemetry.js View on Github external
it('can send telemetry and it is received on the Event Hubs endpoint', function (done) {
    this.timeout(60000);

    const testTelemetryBody = uuid.v4();
    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.telemetry && eventData.body.telemetry === testTelemetryBody) {
          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 / iotedge / edge-modules / node-sensor-sample / app.js View on Github external
function main() {
  ModuleClient.fromEnvironment(Protocol, (err, client) => {
    if (err) {
      console.error(`Error creating ModuleClient instance: ${err}`);
    } else {
      client.open(err => {
        if (err) {
          console.error(`Connection error: ${err}`);
        } else {
          // register event handler for incoming messages
          client.on("inputMessage", (inputName, msg) => {
            client.complete(msg, printResultFor("completed"));
            const data = Buffer.from(msg.data).toString();
            console.log(`<- Data: ${JSON.stringify(JSON.parse(data))}`);
          });

          client.onMethod("reset", (req, res) => {
            console.log(
github Azure / connectthedots / Devices / DirectlyConnectedDevices / Common / javascript / connectthedots.js View on Github external
exports.init_connection = function(settings, initCallback, receiveCallback)
{
    console.log("Initializig the connection with Azure IoT Hub");
    devicesettings = settings;
    
    console.log("Validating connection settings");
    // Validate settings
    validate_settings(devicesettings, ['deviceid', 'iothubconnectionstring', 'displayname', 'organization', 'location']);

    console.log("Connecting to Azure IoT Hub");
    // Create Iot Hub Client instance 
    client = clientFromConnectionString(devicesettings.iothubconnectionstring);
    init_callback = initCallback;

    if (receiveCallback!==undefined) receive_callback = receiveCallback;  
    
    // Open the transport stack
    client.open(connectCallback);
};

azure-iot-device-mqtt

MQTT transport for Azure IoT device SDK

MIT
Latest version published 1 year ago

Package Health Score

57 / 100
Full package analysis

Similar packages