How to use the azure-iothub.Client.fromConnectionString function in azure-iothub

To help you get started, we’ve selected a few azure-iothub 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-sdks / node / service / samples / dmpatterns_reboot_service.js View on Github external
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';

var Registry = require('azure-iothub').Registry;
var Client = require('azure-iothub').Client;
var async = require('async');

// receive the IoT Hub connection string as a command line parameter
if(process.argv.length < 4) {
  console.error('Usage: node dmpatterns_reboot_service.js <<IoT Hub Connection String>> <<targetDeviceId>>');
  process.exit(1);
}

var connectionString = process.argv[2];
var registry = Registry.fromConnectionString(connectionString);
var client = Client.fromConnectionString(connectionString);
var deviceToReboot = process.argv[3];

// Initiate the reboot process on the device using a device method
async.waterfall([
  invokeReboot,
  displayRebootStatus 
],
function(err) {
  if (err){
    console.error(err);
  } else {
    console.log('Reboot complete');
  } 
});

// Initiate the reboot through a method
github Azure / azure-iot-sdk-node / service / samples / dmpatterns_fwupdate_service.js View on Github external
'use strict';

var Registry = require('azure-iothub').Registry;
var Client = require('azure-iothub').Client;
var async = require('async');

// receive the target device ID as a command line parameter
if (process.argv.length < 3) {
  console.error('Usage: node dmpatterns_fwupdate_service.js <<targetDeviceId>>');
  process.exit(1);
}

var connectionString = process.env.IOTHUB_CONNECTION_STRING;
var deviceToUpdate = process.argv[2];
var registry = Registry.fromConnectionString(connectionString);
var client = Client.fromConnectionString(connectionString);

// Service entry point: Initiate the firmware update process on the device using a device method
async.waterfall([
  invokeFirmwareUpdate,
  displayFirmwareUpdateStatus 
],
function(err) {
  if (err) {
    console.error(err);
  } else {
    console.log('Fimware update complete');
  } 
});

// Initiate the firmware update through a method
function invokeFirmwareUpdate(callback) {
github Azure / azure-iot-sdk-node / service / samples / device_method.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 Client = require('azure-iothub').Client;

var connectionString = process.env.IOTHUB_CONNECTION_STRING;
var targetDevice = '<Device Id>';
var methodParams = {
  methodName: '<Method Name>', 
  payload: '[Method Payload]',
  responseTimeoutInSeconds: 15 // set response timeout as 15 seconds 
};

var client = Client.fromConnectionString(connectionString);

client.invokeDeviceMethod(targetDevice, methodParams, function (err, result) {
  if (err) {
    console.error('Failed to invoke method \'' + methodParams.methodName + '\': ' + err.message);
  } else {
    console.log(methodParams.methodName + ' on ' + targetDevice + ':');
    console.log(JSON.stringify(result, null, 2));
  }
});
github Azure-Samples / iot-hub-c-thingdev-getstartedkit / command_center_node / server.js View on Github external
var EventHubClient = require('azure-event-hubs').Client;
var DeviceConnectionString = require('azure-iot-device').ConnectionString;
var azure = require('azure-storage');
var nconf = require('nconf');

nconf.argv().env().file('./config.json');
var eventHubName = nconf.get('eventHubName');
var ehConnString = nconf.get('ehConnString');
var deviceConnString = nconf.get('deviceConnString');
var storageAcountName = nconf.get('storageAcountName');
var storageAccountKey = nconf.get('storageAccountKey');
var storageTable = nconf.get('storageTable');
var iotHubConnString = nconf.get('iotHubConnString');

var deviceId = DeviceConnectionString.parse(deviceConnString).DeviceId;
var iotHubClient = ServiceClient.fromConnectionString(iotHubConnString);

// event hub alerts
var alerts = [];
var ehclient = EventHubClient.fromConnectionString(ehConnString, eventHubName)
ehclient.createReceiver('$Default', '0', { startAfterTime: Date.now() })
    .then(function(rx) {
        rx.on('errorReceived', function(err) { console.log(err); });
        rx.on('message', function(message) {
            alerts.push(message.body);
            alerts = alerts.slice(-5); // keep last 5
        });
    });

// table storage
var tableSvc = azure.createTableService(storageAcountName, storageAccountKey);
tableSvc.createTableIfNotExists(storageTable, function(err, result, response) {
github Azure / azure-iot-sdk-node / service / samples / module_method.js View on Github external

'use strict';

var Client = require('azure-iothub').Client;

var connectionString = process.env.IOTHUB_CONNECTION_STRING;
var deviceId = '[Device ID]';
var moduleId = '[Module ID]';

var methodParams = {
  methodName: '<Method Name>',
  payload: '[Method Payload]',
  responseTimeoutInSeconds: 15 // set response timeout as 15 seconds
};

var client = Client.fromConnectionString(connectionString);

client.invokeDeviceMethod(deviceId, moduleId, methodParams, function (err, result) {
  if (err) {
    console.error('Failed to invoke method \'' + methodParams.methodName + '\': ' + err.message);
  } else {
    console.log(methodParams.methodName + ' on ' + deviceId + ':');
    console.log(JSON.stringify(result, null, 2));
  }
});
github Azure-Samples / iot-hub-node-ping / iothubpingfunction / index.js View on Github external
module.exports = function (context, myEventHubTrigger) {
    context.log("Received raw message from device " + JSON.stringify(myEventHubTrigger));
    //var jsonMessage = JSON.parse(myEventHubTrigger.toString());
    var jsonMessage = myEventHubTrigger;
    context.log("After parsing message, reading :");
    context.log("    deviceId : " + jsonMessage.deviceId);
    context.log("    message : " + jsonMessage.message);

    var client = Client.fromConnectionString(connectionString);
    
    client.open(function (err) {
      if (err) {
        context.log('Could not connect: ' + err.message);
      } else {
        context.log('Client connected');
    
        // Create a message and send it to the device
        var data = JSON.stringify(jsonMessage);
        var message = new Message(data);
        context.log('Sending message: ' + message.getData() + 'to: ' + jsonMessage.deviceId);
        client.send(jsonMessage.deviceId, message, printResultFor('send', context));
      }
      context.done();
    });
}
github Azure / azure-iot-sdk-node / ts-e2e / src / file_upload.tests.ts View on Github external
it('can upload a file', (testCallback) => {
      const testBlobName = 'e2eblob';
      const serviceClient = ServiceClient.fromConnectionString(process.env.IOTHUB_CONNECTION_STRING);
      const deviceClient = DeviceClient.fromConnectionString(testDeviceCS, DeviceHttp);
      fs.stat(fileConfig.fileName, (err, fileStats) => {
        if (err) throw err;
        const testFileSize = fileStats.size;
        const fileStream = fs.createReadStream(fileConfig.fileName);

        serviceClient.open((err) => {
          if (err) throw err;
          serviceClient.getFileNotificationReceiver((err, fileNotificationReceiver) => {
            if (err) throw err;
            fileNotificationReceiver.on('message', (msg) => {
              const notification = JSON.parse(msg.getData().toString());
              if (notification.deviceId === testDevice.deviceId && notification.blobName === testDevice.deviceId + '/' + testBlobName) {
                assert.isString(notification.blobUri);
                assert.equal(notification.blobSizeInBytes, testFileSize);
                fileNotificationReceiver.complete(msg, (err) => {
github Azure / azure-iot-sdk-node / ts-e2e / src / device_methods.tests.ts View on Github external
setTimeout(() => {
            const serviceClient = ServiceClient.fromConnectionString(process.env.IOTHUB_CONNECTION_STRING);
            const methodParams: DeviceMethodParams = {
              methodName: methodName,
              payload: requestPayload,
              connectTimeoutInSeconds: 30,
              responseTimeoutInSeconds: 30
            };

            debug('Service Client: Invoking device method');
            serviceClient.invokeDeviceMethod(testDevice.deviceId, methodParams, (err, result, response) => {
              if (err) throw err;
              debug('Service Client: Received device method response');
              sendOK = true;
              assert.strictEqual(response.statusCode, 200);
              assert.deepEqual(result.payload, responsePayload);
              if (sendOK && receiveOK) {
                debug('Service Client: Test Callback');
github Azure / azure-iot-sdk-node / device / samples / device_receive_message_from_cloud.js View on Github external
const sendMessageFromIotHub = async() => {
    try {
        const client = HubClient.fromConnectionString(process.env.IOTHUB_CONNECTION_STRING)

        await client.send(process.env.DEVICE_ID, generateImportantMessage(Math.random()))
        console.log('Message sent from iot hub!');
        
    } catch (err) {
        console.error('Error sending message from iot hub: ', err)
    }
}
github rachelnicole / pigallery / app.js View on Github external
require('dotenv').config();
var IotClient = require('azure-iothub').Client;
var IotMessage = require('azure-iot-common').Message;
var iotClient = IotClient.fromConnectionString(process.env.IOT_CONN_STRING);
var fs = require('fs');
var express = require('express');
var app = module.exports.app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var port = process.env.PORT || 3000;
var azure = require('azure-storage');
var blobService = azure.createBlobService(process.env.AZURE_STORAGE_CONNECTION_STRING);
var tmp = require('tmp');
var path = require('path');

var baseUrlPath = 'https://tinygallery.blob.core.windows.net/pixelart/';