Add Direct Method template for Node.js (#227)

* Add Direct Method template for Node.js, Show 'Create IoT Hub' progress as notification instead of in the status bar

* Also show 'Create resource group' progress as notification
This commit is contained in:
Jun Han 2018-12-21 17:02:12 +08:00 коммит произвёл GitHub
Родитель 018d5c6639
Коммит 0edcbf8708
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
4 изменённых файлов: 136 добавлений и 2 удалений

Просмотреть файл

@ -0,0 +1,41 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';
// Connection string for the IoT Hub service
//
// NOTE:
// For simplicity, this sample sets the connection string in code.
// In a production environment, the recommended approach is to use
// an environment variable to make it available to your application
// or use an x509 certificate.
// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security
var connectionString = '{{iotHubConnectionString}}';
var deviceId = '{{deviceId}}';
// Using the Node.js Service SDK for IoT Hub:
// https://github.com/Azure/azure-iot-sdk-node
// Run 'npm install azure-iothub' to install the required libraries for this application
// The sample connects to service-side endpoint to call direct methods on devices.
var Client = require('azure-iothub').Client;
// Connect to the service-side endpoint on your IoT hub.
var client = Client.fromConnectionString(connectionString);
// Set the direct method name, payload, and timeout values
var methodParams = {
methodName: 'SetTelemetryInterval',
payload: 10, // Number of seconds.
responseTimeoutInSeconds: 30
};
// Call the direct method on your device using the defined parameters.
client.invokeDeviceMethod(deviceId, methodParams, function (err, result) {
if (err) {
console.error('Failed to invoke method \'' + methodParams.methodName + '\': ' + err.message);
} else {
console.log('Response from ' + methodParams.methodName + ' on ' + deviceId + ':');
console.log(JSON.stringify(result, null, 2));
}
});

Просмотреть файл

@ -0,0 +1,89 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';
// The device connection string to authenticate the device with your IoT hub.
//
// NOTE:
// For simplicity, this sample sets the connection string in code.
// In a production environment, the recommended approach is to use
// an environment variable to make it available to your application
// or use an HSM or an x509 certificate.
// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security
var connectionString = '{{deviceConnectionString}}';
// Using the Node.js Device SDK for IoT Hub:
// https://github.com/Azure/azure-iot-sdk-node
// Run 'npm install azure-iot-device-mqtt' to install the required libraries for this application
// The sample connects to a device-specific MQTT endpoint on your IoT Hub.
var Mqtt = require('azure-iot-device-mqtt').Mqtt;
var DeviceClient = require('azure-iot-device').Client
var Message = require('azure-iot-device').Message;
var client = DeviceClient.fromConnectionString(connectionString, Mqtt);
// Timeout created by setInterval
var intervalLoop = null;
// Function to handle the SetTelemetryInterval direct method call from IoT hub
function onSetTelemetryInterval(request, response) {
// Function to send a direct method reponse to your IoT hub.
function directMethodResponse(err) {
if(err) {
console.error('An error ocurred when sending a method response:\n' + err.toString());
} else {
console.log('Response to method \'' + request.methodName + '\' sent successfully.');
}
}
console.log('Direct method payload received:');
console.log(request.payload);
// Check that a numeric value was passed as a parameter
if (isNaN(request.payload)) {
console.log('Invalid interval response received in payload');
// Report failure back to your hub.
response.send(400, 'Invalid direct method parameter: ' + request.payload, directMethodResponse);
} else {
// Reset the interval timer
clearInterval(intervalLoop);
intervalLoop = setInterval(sendMessage, request.payload * 1000);
// Report success back to your hub.
response.send(200, 'Telemetry interval set: ' + request.payload, directMethodResponse);
}
}
// Send a telemetry message to your hub
function sendMessage(){
// Simulate telemetry.
var temperature = 20 + (Math.random() * 15);
var message = new Message(JSON.stringify({
temperature: temperature,
humidity: 60 + (Math.random() * 20)
}));
// Add a custom application property to the message.
// An IoT hub can filter on these properties without access to the message body.
message.properties.add('temperatureAlert', (temperature > 30) ? 'true' : 'false');
console.log('Sending message: ' + message.getData());
// Send the message.
client.sendEvent(message, function (err) {
if (err) {
console.error('send error: ' + err.toString());
} else {
console.log('message sent');
}
});
}
// Set up the handler for the SetTelemetryInterval direct method call.
client.onDeviceMethod('SetTelemetryInterval', onSetTelemetryInterval);
// Create a message and send it to the IoT hub, initially every second.
intervalLoop = setInterval(sendMessage, 1000);

Просмотреть файл

@ -23,6 +23,8 @@ enum TemplateType {
MonitorD2C = "Monitor device-to-cloud message",
DeviceManageDeviceTwin = "Device - Manage device twin",
ServiceManageDeviceTwin = "Service - Manage device twin",
ListenForDirectMethod = "Listen for direct method",
CallDirectMethod = "Call direct method",
}
export class Constants {
@ -126,6 +128,8 @@ export class Constants {
[TemplateType.MonitorD2C]: "node/monitorD2C.js",
[TemplateType.DeviceManageDeviceTwin]: "node/deviceManageDeviceTwin.js",
[TemplateType.ServiceManageDeviceTwin]: "node/serviceManageDeviceTwin.js",
[TemplateType.ListenForDirectMethod]: "node/listenForDirectMethod.js",
[TemplateType.CallDirectMethod]: "node/callDirectMethod.js",
},
[TemplateLanguage.PHP]: {
[TemplateType.SendD2C]: "php/sendD2C.php",

Просмотреть файл

@ -82,7 +82,7 @@ export class IoTHubResourceExplorer extends BaseExplorer {
return vscode.window.withProgress({
title: `Creating IoT Hub '${name}'`,
location: vscode.ProgressLocation.Window,
location: vscode.ProgressLocation.Notification,
}, async (progress) => {
outputChannel.appendLine(`Creating IoT Hub: ${name}`);
const intervalID = setInterval(() => {
@ -385,7 +385,7 @@ export class IoTHubResourceExplorer extends BaseExplorer {
if (locationItem) {
return vscode.window.withProgress({
title: `Creating resource group '${resourceGroupName}'`,
location: vscode.ProgressLocation.Window,
location: vscode.ProgressLocation.Notification,
}, async (progress) => {
const resourceManagementClient = new ResourceManagementClient(subscriptionItem.session.credentials,
subscriptionItem.subscription.subscriptionId, subscriptionItem.session.environment.resourceManagerEndpointUrl);