How to use the azure-iot-device.Client.fromConnectionString 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 / iot-hub-node-ping / devicesample / node / node_device.js View on Github external
function main() {
  // receive the IoT Hub connection string as a command line parameter
  if(process.argv.length < 3) {
    console.error('Usage: node_device.js <>');
    process.exit(1);
  }

  // open a connection to the device
  deviceConnectionString = process.argv[2];

  client = Client.fromConnectionString(deviceConnectionString, Protocol);
  client.open(onConnect);
}
github Azure-Samples / iot-devkit-web-simulator / src / data / ShakeShake / mockedSample.js View on Github external
app_status = 0;
    shake_progress = 0;
    DrawAppTitle("IoT DevKit");
    Screen.print(2, "Connecting...");

    Screen.print(3, " > WiFi");
    await delay(1500);
    // todo turn on wifi led
    Screen.print(3, " > LEDs");
    rgbLed.turnOff();
    await delay(100);
    Screen.print(3, " > IoT Hub");
    await delay(1500);
    rgbLed.setColor(RGB_LED_BRIGHTNESS, 0, 0);
    // TODO: send telemetry data
    client = Client.fromConnectionString(connectionString, Protocol);
    client.open(function (err) {
        if (err) {
            console.error('[IoT hub Client] Connect error: ' + err.message);
            return;
        }
        client.on('message', TwitterMessageCallback);
        sendingMessage = true;
        hb_interval_ms = -(HEARTBEAT_INTERVAL);   // Trigger heart beat immediately
        HeartBeat();
        rgbLed.turnOff();
        // todo turn on azure led
        Screen.print(1, "192.168.1.1");
        Screen.print(2, "Press A to Shake!");
        Screen.print(3, " ");
    });
}
github Azure / azure-iot-sdk-node / device / samples / upload_to_blob_v12.js View on Github external
let uploadError;
  try {
    const uploadBlobResponse = blockBlobClient.upload(content, content.length);
    console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);
  } catch (e) {
    console.log(`Upload block blob failed`);
    uploadError = e;
  }
  // END STORAGE CODE

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

uploadToBlob(Client.fromConnectionString(deviceConnectionString, Protocol))
  .catch((err) => {
    return new Error(err);
  });
github Azure / azure-iot-sdk-node / device / samples / simple_sample_device_twin.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-iot-device').Client;
//var Protocol = require('azure-iot-device-amqp').Amqp;
var Protocol = require('azure-iot-device-mqtt').Mqtt;
var _ = require('lodash');

var deviceConnectionString = process.env.DEVICE_CONNECTION_STRING;

// create the IoTHub client
var client = Client.fromConnectionString(deviceConnectionString, Protocol);
console.log('got client');

// connect to the hub
client.open(function(err) {
  if (err) {
    console.error('could not open IotHub client');
  }  else {
    console.log('client opened');

    // Create device Twin
    client.getTwin(function(err, twin) {
      if (err) {
        console.error('could not get twin');
      } else {
        console.log('twin created');
github ThingLabsIo / IoTLabs / Photon / Weather / weather.js View on Github external
// For this lab we will use AMQP over Web Sockets.
// If you want to use a different protocol, comment out the protocol you want to replace, 
// and uncomment one of the other transports.
var Protocol = require('azure-iot-device-amqp-ws').AmqpWs;
// var Protocol = require('azure-iot-device-amqp').Amqp;
// var Protocol = require('azure-iot-device-http').Http;
// var Protocol = require('azure-iot-device-mqtt').Mqtt;

// Define the client object that communicates with Azure IoT Hubs
var Client = require('azure-iot-device').Client;
// Define the message object that will define the message format going into Azure IoT Hubs
var Message = require('azure-iot-device').Message;

// Create the client instanxe that will manage the connection to your IoT Hub
// The client is created in the context of an Azure IoT device.
var client = Client.fromConnectionString(connectionString, Protocol);
// Extract the Azure IoT Hub device ID from the connection string 
// (this may not be the same as the Photon device ID)
var deviceId = device.ConnectionString.parse(connectionString).DeviceId;
console.log("Device ID: " + deviceId);

// Create a Johnny-Five board instance to represent your Particle Photon
// Board is simply an abstraction of the physical hardware, whether is is a 
// Photon, Arduino, Raspberry Pi or other boards. 
// When creating a Board instance for the Photon you must specify the token and device ID
// for your Photon using the Particle-IO Plugin for Johnny-five.
// Replace the Board instantiation with the following:
var board = new five.Board({
  io: new Particle({
    token: token,
    deviceId: 'YOUR PARTICLE PHOTON DEVICE IS OR ALIAS'
  })
github Azure / azure-iot-sdk-node / digitaltwins / samples / iot_central_device / sample_device.js View on Github external
description: 'helpful descriptive text',
      version: version
    })
      .then(() => console.log('updated the property'))
      .catch(() => console.log('failed to update the property'));
  };

  const commandHandler = (request, response) => {
    console.log('received command: ' + request.commandName + ' for interfaceInstance: ' + request.interfaceInstanceName);
    response.acknowledge(200, 'helpful response text')
      .then(() => console.log('acknowledgement succeeded.'))
      .catch(() => console.log('acknowledgement failed'));
  };

  const environmentalSensor = new EnvironmentalSensor('sensor', propertyUpdateHandler, commandHandler);
  const deviceClient = DeviceClient.fromConnectionString(deviceConnectionString, Mqtt);

  const digitalTwinClient = new DigitalTwinClient(capabilityModel, deviceClient);
  digitalTwinClient.addInterfaceInstance(environmentalSensor);

  await digitalTwinClient.register();

  // send telemetry
  setInterval(async () => {
    const temp = 65.5 + Math.ceil(Math.random() * 10);
    const humidity = 12.2 + Math.ceil(Math.random() * 10);
    await environmentalSensor.temp.send(temp);
    await environmentalSensor.humid.send(humidity);
    console.log('Done sending telemetry: temp: ' + temp + ' humidity ' + humidity);
  }, 3000);
};
github Azure / azure-iot-sdk-node / device / samples / upload_to_blob_advanced.js View on Github external
const run = async() => {
    try {
        const blobName = 'dummyBlob.txt';
        // Create a dummy file to upload.
        const dummyFilePath = path.resolve(__dirname, blobName);
        await writeFileAsync(dummyFilePath, 'Microsoft loves you!');
        const { size : fileSize } = await statAsync(dummyFilePath);

        // Connect to IoT Hub.
        const client = Client.fromConnectionString(process.env.DEVICE_CONNECTION_STRING, Protocol);

        // Get the Shared Access Signature for the linked Azure Storage Blob from IoT Hub.
        // The IoT Hub needs to have a linked Storage Account for Upload To Blob.
        let blobInfo = await client.getBlobSharedAccessSignature(blobName);
        if (!blobInfo) {
            throw new Error('Invalid upload parameters');
        }

        // Create a new Pipeline
        const pipeline = StorageURL.newPipeline(new AnonymousCredential(), {
            retryOptions: { maxTries: 4 },
            telemetry: { value: 'HighLevelSample V1.0.0' }, // Customized telemetry string
            keepAliveOptions: {
            enable: false
            }
        });
github Azure / azure-iot-sdk-node / ts-e2e / src / device_twin.tests.ts View on Github external
it('service can modify desired properties and the device gets a notification', (testCallback) => {
        let sendOK = false;
        let receiveOK = false;
        const twinPatch = {
          properties: {
            desired: {
              desiredKey: 'desiredValue'
            }
          }
        };

        const deviceClient = DeviceClient.fromConnectionString(testDeviceCS, transportCtor);
        deviceClient.open((err) => {
          if (err) throw err;
          debug('Device Client: Opened');
          deviceClient.getTwin((err, twin) => {
            if (err) throw err;
            debug('Device Client: Received Twin');
            twin.on('properties.desired', (patch) => {
              debug('Device Client: Received Twin Patch');
              if (patch.$version > 1) {
                assert.strictEqual(patch.desiredKey, twinPatch.properties.desired.desiredKey);
                receiveOK = true;
              }
              if (sendOK && receiveOK) {
                testCallback();
              }
            });
github Azure / azure-iot-sdk-node / device / transport / amqp / lib / _client_test_integration.js View on Github external
function makeRequestWith(connectionString, test, done) {
    var client = Client.fromConnectionString(connectionString, Transport);
    requestFn(client, function (err, res) {
      test(err, res);
      done();
    });
  }
github Azure / azure-iot-sdk-node / device / samples / upload_to_blob.js View on Github external
const run = async() => {
    try {
        //create the connection using the mqtt protocol and device connection string
        const client = Client.fromConnectionString(process.env.DEVICE_CONNECTION_STRING, Protocol);
        
        //create a dummy file to upload
        const dummyFilePath = path.resolve(__dirname, 'dummyFile.txt');
        await writeFileAsync(dummyFilePath, 'Microsoft loves you!');

        //we also need to know the exact size for the upload
        const { size : fileSize } = await statAsync(dummyFilePath);

        //uploadToBlob also takes a filestream
        const fileStream = createReadStream(dummyFilePath);
        await client.uploadToBlob('testblob.txt', fileStream, fileSize);
        console.log('File has been uploaded from simulated device to your iot hub\'s storage container!');
        
        //destroy the read stream
        fileStream.destroy();
        //remove the dummy file we just created