Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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);
});
}
'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);
};
// 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);
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);
});
// 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);
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']);
}
};
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(
function main() {
// open a connection to the device
var deviceConnectionString = process.env.DEVICE_CONNECTION_STRING;
client = Client.fromConnectionString(deviceConnectionString, Protocol);
client.open(onConnect);
}
provisioningClient.register(function(err, result) {
if (err) {
console.log("error registering device: " + err);
} else {
console.log('registration succeeded');
console.log('assigned hub=' + result.registrationState.assignedHub);
console.log('deviceId=' + result.registrationState.deviceId);
var tpmAuthenticationProvider = tpmSecurity.TpmAuthenticationProvider.fromTpmSecurityClient(result.registrationState.deviceId, result.registrationState.assignedHub, securityClient);
var hubClient = Client.fromAuthenticationProvider(tpmAuthenticationProvider, iotHubTransport);
var connectCallback = function (err) {
if (err) {
console.error('Could not connect: ' + err.message);
} else {
console.log('Client connected');
var message = new Message('Hello world');
hubClient.sendEvent(message, printResultFor('send'));
}
};
hubClient.open(connectCallback);
function printResultFor(op) {
return function printResult(err, res) {
if (err) console.log(op + ' error: ' + err.toString());