Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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);
};
// 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 clientFromConnectionString = require('azure-iot-device-mqtt').clientFromConnectionString;
var Message = require('azure-iot-device').Message;
// String containing hostname, device ID, device key in the following format:
var connectionString = '[IoT Hub device connection string]';
var client = clientFromConnectionString(connectionString);
client.open(function () {
// Create a message and send it to the IoT Hub every second
setInterval(function () {
var windSpeed = 10 + (Math.random() * 4); // range: [10, 14]
var data = JSON.stringify({
deviceId: 'myFirstDevice',
windSpeed: windSpeed
});
var message = new Message(data);
message.properties.add('myproperty', 'myvalue');
console.log('Sending message: ' + message.getData());
client.sendEvent(message, function (err, result){
console.log('Message sent: ' + result.constructor.name + '(' + JSON.stringify(result.transportObj) + ')');
});
}, 2000);
const total = deviceCount * numbers;
if (total <= 0) {
this.output(`Invalid Operation.`);
return;
}
const startTime = new Date();
this.output(
`Start sending messages from ${deviceCount} device(s) to IoT Hub.`,
);
let clients = [];
let statuses = [];
let ids = [];
this.totalStatus = new SendStatus("Total", total);
for (let i = 0; i < deviceCount; i++) {
clients.push(
await clientFromConnectionString(deviceConnectionStrings[i]),
);
statuses.push(
new SendStatus(
ConnectionString.parse(deviceConnectionStrings[i]).DeviceId,
numbers,
),
);
ids.push(i);
}
for (let i = 0; i < numbers; i++) {
// No await here, beacause the interval should begin as soon as it called send(), not after it sent.
ids.map((j) => {
// We use a template so that each time the message can be randomly generated.
const generatedMessage = isTemplate
? dummyjson.parse(template)
: template;
const clientFromConnectionString = require('azure-iot-device-mqtt').clientFromConnectionString;
const Message = require('azure-iot-device').Message;
const connectionString = require('./config.json').connectionString;
const client = clientFromConnectionString(connectionString);
client.open(err => {
if (err) {
console.error('Could not connect: ' + err);
process.exit(1);
} else {
const data = {
topic: 'iot'
};
const message = new Message(JSON.stringify(data));
setInterval(() => {
client.sendEvent(message, err => {
if (err) {
console.warn('Send message to IoT Hub failed: ' + err.toString());
} else {
vscode.window.showInputBox({ prompt: `Enter message to send to ${Constants.IoTHub}`, ignoreFocusOut: true }).then((message: string) => {
if (message !== undefined) {
this._outputChannel.show();
try {
let client = clientFromConnectionString(deviceConnectionString);
let stringify = Utility.getConfig(Constants.IoTHubD2CMessageStringifyKey);
client.sendEvent(new Message(stringify ? JSON.stringify(message) : message),
this.sendEventDone(client, Constants.IoTHubMessageLabel, Constants.IoTHub, Constants.IoTHubAIMessageDoneEvent));
} catch (e) {
this.outputLine(Constants.IoTHubMessageLabel, e);
}
}
});
}
public async startMonitorC2DMessage(deviceItem?: DeviceItem) {
if (this._isMonitoring) {
this._outputChannel.show();
this.outputLine(Constants.IoTHubC2DMessageMonitorLabel, "There is a running job to receive C2D message. Please stop it first.");
return;
}
deviceItem = await Utility.getInputDevice(deviceItem, Constants.IoTHubAIStartMonitorC2DEvent);
if (!deviceItem || !deviceItem.connectionString) {
return;
}
const deviceConnectionString: string = deviceItem.connectionString;
this._outputChannel.show();
this._deviceClient = clientFromConnectionString(deviceConnectionString);
this._deviceClient.open(this.connectCallback(deviceConnectionString));
}