Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
// 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 Registry = require('azure-iothub').Registry;
var connectionString = process.env.IOTHUB_CONNECTION_STRING;
var registry = Registry.fromConnectionString(connectionString);
var query = registry.createQuery('SELECT * FROM devices', 100);
var onResults = function(err, results) {
if (err) {
console.error('Failed to fetch the results: ' + err.message);
} else {
// Do something with the results
results.forEach(function(twin) {
console.log(twin.deviceId);
});
if (query.hasMoreResults) {
query.nextAsTwin(onResults);
}
}
};
var ProvisioningDeviceClient = require('azure-iot-provisioning-device').ProvisioningDeviceClient;
var ProvisioningServiceClient = require('azure-iot-provisioning-service').ProvisioningServiceClient;
var X509Security = require('azure-iot-security-x509').X509Security;
var Registry = require('azure-iothub').Registry;
var certHelper = require('./cert_helper');
var TpmSecurityClient = require('azure-iot-security-tpm').TpmSecurityClient;
var SymmetricKeySecurityClient = require('azure-iot-security-symmetric-key').SymmetricKeySecurityClient;
var TssJs = require("tss.js");
var idScope = process.env.IOT_PROVISIONING_DEVICE_IDSCOPE;
var provisioningConnectionString = process.env.IOT_PROVISIONING_SERVICE_CONNECTION_STRING;
var registryConnectionString = process.env.IOTHUB_CONNECTION_STRING;
var provisioningHost = process.env.IOT_PROVISIONING_DEVICE_ENDPOINT;
var provisioningServiceClient = ProvisioningServiceClient.fromConnectionString(provisioningConnectionString);
var registry = Registry.fromConnectionString(registryConnectionString);
var X509IndividualTransports = [ Http, Amqp, AmqpWs, Mqtt, MqttWs ];
var X509GroupTransports = [ Http, Amqp, Mqtt, MqttWs ]; // AmqpWs is disabled because of an occasional ECONNRESET error when closing the socket. See Task 2233264.
var TpmIndividualTransports = [ Http, Amqp, AmqpWs ];
var SymmetricKeyIndividualTransports = [ Http, Amqp, AmqpWs, Mqtt, MqttWs ];
var SymmetricKeyGroupTransports = [ Http, Amqp, AmqpWs, Mqtt, MqttWs ];
var rootCert = {
cert: Buffer.from(process.env.IOT_PROVISIONING_ROOT_CERT,"base64").toString('ascii'),
key: Buffer.from(process.env.IOT_PROVISIONING_ROOT_CERT_KEY,"base64").toString('ascii'),
};
var selfSignedCert;
var certWithoutChain;
var intermediateCert1;
var intermediateCert2;
before('creating device identity: ' + deviceDescription.deviceId, function () {
this.timeout(60000); // eslint-disable-line no-invalid-this
debug('creating test device: ' + deviceDescription.deviceId);
return Registry.fromConnectionString(hubConnectionString).create(deviceDescription
).then((device) => {
createdDevice = device.responseBody;
debug('create or update test interface model: ' + interfaceDocument['@id']);
return createModel(interfaceDocument);
}).then(() => {
debug('interface model creation succeeded');
debug('create or update test capability model: ' + capabilityModelDocument['@id']);
return createModel(capabilityModelDocument);
}).then(() => {
debug('beforeAll hook done');
return Promise.resolve();
}).catch((err) => {
debug('error creating test resources: ' + err.toString());
throw err;
});
});
it('creates a device -> gets it -> updates it -> deletes it', (testCallback) => {
const testDeviceId = uuid.v4();
const registry = Registry.fromConnectionString(process.env.IOTHUB_CONNECTION_STRING);
registry.create({ deviceId: testDeviceId }, (err, createDevDesc) => {
if (err) throw err;
assert.strictEqual(createDevDesc.deviceId, testDeviceId);
registry.get(testDeviceId, (err, getDevDesc) => {
if (err) throw err;
assert.strictEqual(getDevDesc.deviceId, testDeviceId);
assert.strictEqual(getDevDesc.status, 'enabled');
registry.update({ deviceId: testDeviceId, status: 'disabled' }, (err, updateDevDesc) => {
assert.strictEqual(updateDevDesc.deviceId, testDeviceId);
assert.strictEqual(updateDevDesc.status, 'disabled');
registry.delete(testDeviceId, (err) => {
if (err) throw err;
registry.get(testDeviceId, (err, getDevDesc2) => {
assert.instanceOf(err, Error);
testCallback();
});
export function removeTestDeviceFromRegistry(testDevice: TestDevice, removeCallback: (err?: Error) => void): void {
const reg = Registry.fromConnectionString(process.env.IOTHUB_CONNECTION_STRING);
debug('deleting device ' + testDevice.deviceId);
reg.delete(testDevice.deviceId, (err) => {
if (err) debug('failed to delete device ' + testDevice.deviceId + ': ' + err.toString());
removeCallback(err);
});
}
twin.properties.reported.update(twinPatch, (err) => {
if (err) throw err;
const registry = Registry.fromConnectionString(process.env.IOTHUB_CONNECTION_STRING);
registry.getTwin(testDevice.deviceId, (err, twin) => {
debug('Registry: Got Device Twin');
assert.strictEqual(twin.properties.reported.twinKey, twinPatch.twinKey);
testCallback();
});
});
});
before('creating device identity: ' + deviceDescription.deviceId, async function () {
this.timeout(60000);
debug('creating test device: ' + deviceDescription.deviceId);
return Registry.fromConnectionString(hubConnectionString).create(deviceDescription)
.then((device) => {
createdDevice = device.responseBody;
debug('create or update test interface model: ' + interfaceDocument['@id']);
return createModel(interfaceDocument);
}).then(() => {
debug('interface model creation succeeded');
debug('create or update test capability model: ' + capabilityModelDocument['@id']);
return createModel(capabilityModelDocument);
}).then(() => {
debug('beforeAll hook done');
return Promise.resolve();
}).catch((err) => {
debug('error creating test resources: ' + err.toString());
throw err;
});
});
node.on('input', function (msg) {
if (typeof (msg.payload) == 'string') {
msg.payload = JSON.parse(msg.payload);
}
var registry = Registry.fromConnectionString(node.credentials.connectionString);
registry.create(msg.payload, function (err, device) {
if (err) {
node.error('Error while trying to create a new device: ' + err.toString());
setStatus(node, statusEnum.error);
} else {
node.log("Device created: " + JSON.stringify(device));
node.log("Device ID: " + device.deviceId + " - primaryKey: " + device.authentication.SymmetricKey.primaryKey + " - secondaryKey: " + device.authentication.SymmetricKey.secondaryKey);
node.send("Device ID: " + device.deviceId + " - primaryKey: " + device.authentication.SymmetricKey.primaryKey + " - secondaryKey: " + device.authentication.SymmetricKey.secondaryKey);
}
});
});
public static async updateModuleTwin(iotHubConnectionString: string, deviceId: string, moduleId: string, twin: any): Promise {
const registry: Registry = Registry.fromConnectionString(iotHubConnectionString);
await registry.updateModuleTwin(deviceId, moduleId, twin, "*");
}
node.on('input', function (msg) {
var registry = Registry.fromConnectionString(node.credentials.connectionString);
if( typeof msg.payload === "string" ) var query = registry.createQuery("SELECT * FROM devices WHERE deviceId ='" + msg.payload + "'");
else var query = registry.createQuery("SELECT * FROM devices");
query.nextAsTwin( function(err, results){
if (err) {
node.error('Error while trying to retrieve device twins: ' + err.message);
msg.error = err;
delete msg.payload;
node.send(msg);
} else {
msg.payload = results;
disconnectFromIoTHub(node, this);
node.send(msg);
}
});