#node.js #json #azure #iot
Вопрос:
Мое приложение Windows Forms запускается после обычной отладки, но когда я нажимаю кнопку «Пуск», оно не отвечает, а когда я прекращаю отладку, в журнале вывода указывается, что оно завершилось с кодом -1 (0xffffffff). Я использую Visual Studio 2017 Community v. 15.7.14. и .NET framework 4.7.03056. Может ли кто-нибудь найти ошибку или другую причину, по которой она не работает?
"use strict";
const chalk = require('chalk');
// Use the Azure IoT device SDK for devices that connect to Azure IoT Central.
var iotHubTransport = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;
var ProvisioningTransport = require('azure-iot-provisioning-device-mqtt').Mqtt;
var SymmetricKeySecurityClient = require('azure-iot-security-symmetric-key').SymmetricKeySecurityClient;
var ProvisioningDeviceClient = require('azure-iot-provisioning-device').ProvisioningDeviceClient;
var provisioningHost = 'global.azure-devices-provisioning.net';
// Enter your Azure IoT keys.
var idScope = '0ne003B0EE0';
var registrationId = 'TemperatureSensor1';
var symmetricKey = 'ZaVPZ03/ 41MYAQVNpnZfK4hNKC 9q7OIB2bFYrC0T4=';
var provisioningSecurityClient = new SymmetricKeySecurityClient(registrationId, symmetricKey);
var provisioningClient = ProvisioningDeviceClient.create(provisioningHost, idScope, new ProvisioningTransport(), provisioningSecurityClient);
var hubClient;
var SensorIdentification = "Sensor number 1";
//var rest = require("azure-maps-rest");
function greenMessage(text) {
console.log(chalk.green(text) "n");
}
function redMessage(text) {
console.log(chalk.red(text) "n");
}
//2
// Truck globals initialized to the starting state of the truck.
// Enums, frozen name:value pairs.
//var stateEnum = Object.freeze({ "ready": "ready", "enroute": "enroute", "delivering": "delivering", "returning": "returning", "loading": "loading", "dumping": "dumping" });
//var contentsEnum = Object.freeze({ "full": "full", "melting": "melting", "empty": "empty" });
//var fanEnum = Object.freeze({ "on": "on", "off": "off", "failed": "failed" });
//const deliverTime = 600; // Time to complete delivery, in seconds.
//const loadingTime = 800; // Time to load contents.
//const dumpingTime = 400; // Time to dump melted contents.
var timeOnCurrentTask = 0; // Time on current task, in seconds.
var interval = 60; // Time interval in seconds.
var tooWarmPeriod = 0; // Time that contents are too warm, in seconds.
var temp = -2; // Current temperature of contents, in degrees C.
var contents = contentsEnum.full; // Truck contents state.
var state = stateEnum.ready; // Truck is full and ready to go!
var TemperatureControl = -5; // Setting - can be changed by the operator from IoT Central.
const noEvent = "none";
var eventText = noEvent; // Text to send to the IoT operator.
var path = []; // Latitude and longitude steps for the route.
var timeOnPath = []; // Time in seconds for each section of the route.
var truckOnSection; // The current path section the truck is on.
var truckSectionsCompletedTime; // The time the truck has spent on previous completed sections.
//6
function dieRoll() {
return Math.random();
}
function UpdateSensor() {
temp = -2.9 dieRoll();
}
//7
function sendSensorTelemetry() {
// Simulate the Sensor.
UpdateSensor();
// Create the telemetry data JSON package.
var data = JSON.stringify(
{
// Format:
// Name from IoT Central app ":" variable name from NodeJS app.
ContentsTemperature: temp.toFixed(2),
});
// Add the eventText event string, if there is one.
if (eventText != noEvent) {
data = JSON.stringify(
{
Event: eventText,
}
);
eventText = noEvent;
}
// Create the message by using the preceding defined data.
var message = new Message(data);
console.log("Message: " data);
// Send the message.
hubClient.sendEvent(message, function (errorMessage) {
// Error
if (errorMessage) {
redMessage("Failed to send message to Azure IoT Central: ${err.toString()}");
} else {
greenMessage("Telemetry sent");
}
});
}
//8
// Send device twin reported properties.
function sendDeviceProperties(twin, properties) {
twin.properties.reported.update(properties, (err) => greenMessage(`Sent device properties: ${JSON.stringify(properties)}; `
(err ? `error: ${err.toString()}` : `status: success`)));
}
// Add any writeable properties your device supports. Map them to a function that's called when the writeable property
// is updated in the IoT Central application.
var writeableProperties = {
'TemperatureControl': (newValue, callback) => {
setTimeout(() => {
TemperatureControl = newValue;
callback(newValue, 'completed', 200);
}, 1000);
},
};
// Handle writeable property updates that come from IoT Central via the device twin.
function handleWriteablePropertyUpdates(twin) {
twin.on('properties.desired', function (desiredChange) {
for (let setting in desiredChange) {
if (writeableProperties[setting]) {
greenMessage(`Received setting: ${setting}: ${desiredChange[setting]}`);
writeableProperties[setting](desiredChange[setting], (newValue, status, code) => {
var patch = {
[setting]: {
value: newValue,
ad: status,
ac: code,
av: desiredChange.$version
}
}
sendDeviceProperties(twin, patch);
});
}
}
});
}
//9
// Handle device connection to Azure IoT Central.
var connectCallback = (err) => {
if (err) {
redMessage(`Device could not connect to Azure IoT Central: ${err.toString()}`);
} else {
greenMessage('Device successfully connected to Azure IoT Central');
// Send telemetry to Azure IoT Central every 5 seconds.
setInterval(sendSensorTelemetry, 3000);
// Get device twin from Azure IoT Central.
hubClient.getTwin((err, twin) => {
if (err) {
redMessage(`Error getting device twin: ${err.toString()}`);
} else {
// Send device properties once on device start up.
var properties =
{
// Format:
// <Property Name in Azure IoT Central> ":" <value in Node.js app>
TruckID: SensorIdentification,
};
sendDeviceProperties(twin, properties);
handleWriteablePropertyUpdates(twin);
}
});
}
};
//10
// Start the device (register and connect to Azure IoT Central).
provisioningClient.register((err, result) => {
if (err) {
redMessage('Error registering device: ' err);
} else {
greenMessage('Registration succeeded');
console.log('Assigned hub=' result.assignedHub);
console.log('DeviceId=' result.deviceId);
var connectionString = 'HostName=' result.assignedHub ';DeviceId=' result.deviceId ';SharedAccessKey=' symmetricKey;
hubClient = Client.fromConnectionString(connectionString, iotHubTransport);
hubClient.open(connectCallback);
}
});