Как активировать устройство в X509, назначенном пользователем, Тип устройства в Azure IOT-хабе? - PullRequest
1 голос
/ 30 января 2020

Я новичок в обеспечении аутентификации IOT и X509.

Я могу зарегистрировать устройство с помощью node.js в Azure IOT-хабе (Self Assigned X509 Device type).

Конвейер есть,

1. Download certificate of the registered device type.
2. convert into key and cert pem files
3. pass register id as device id

register_X509. js

'use strict';

var fs = require('fs');

var Client = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;

var X509AuthenticationProvider = require('azure-iot-device').X509AuthenticationProvider;
var Protocol = require('azure-iot-device-mqtt').Mqtt;


var Transport = require('azure-iot-provisioning-device-mqtt').Mqtt;

var X509Security = require('azure-iot-security-x509').X509Security;
var ProvisioningDeviceClient = require('azure-iot-provisioning-device').ProvisioningDeviceClient;

var provisioningHost = 'my-provisioning-host';
var idScope = 'id-scope';

var registrationId = 'registration-id';
var deviceCert = {
  cert: fs.readFileSync('cert.pem').toString(),
  key: fs.readFileSync('key.pem').toString()
};


var transport = new Transport();
var securityClient = new X509Security(registrationId, deviceCert);
var deviceClient = ProvisioningDeviceClient.create(provisioningHost, idScope, transport, securityClient);

// Register the device.  Do not force a re-registration.
deviceClient.register(function(err, result) {
  if (err) {
    console.log("error registering device: " + err);
  } else {
    console.log('registration succeeded');
    console.log('assigned hub=' + result.assignedHub);
    console.log('deviceId=' + result.deviceId);

    var client = Client.fromAuthenticationProvider(X509AuthenticationProvider.fromX509Options(
      result.deviceId, result.assignedHub, deviceCert
    ), Protocol);
    var connectCallback = function (err) {
      if (err) {
        console.error('Could not connect: ' + err.message);
      } else {
        console.log('Client connected');
        // Create device Twin
        client.getTwin(function (err, twin) {
          if (err) {
            console.error('could not get twin');
          } else {
            console.log('twin created');

            console.log('twin contents:');
            console.log(twin.properties);

            // Send Event message
            setTimeout(function () {
              var data = JSON.stringify({
                'did':  result.deviceId,
                'dts':  new Date().toISOString(),
                'desiredStatus':  'Activated',
                'reportedStatus':  'Activating',
                'msg': []
              });
              var message = new Message(data);
              console.log('Sending message: ' + message.getData());
              client.sendEvent(message, printResultFor('send'));
            }, 1000);

          }
        });

        client.on('error', function (err) {
          console.error(err.message);
        });

        client.on('message', function (msg) {
          console.log('Id: ' + msg.messageId + ' Body: ' + msg.data);
          // When using MQTT the following line is a no-op.
          client.complete(msg, printResultFor('completed'));
          // The AMQP and HTTP transports also have the notion of completing, rejecting or abandoning the message.
          // When completing a message, the service that sent the C2D message is notified that the message has been processed.
          // When rejecting a message, the service that sent the C2D message is notified that the message won't be processed by the device. the method to use is client.reject(msg, callback).
          // When abandoning the message, IoT Hub will immediately try to resend it. The method to use is client.abandon(msg, callback).
          // MQTT is simpler: it accepts the message by default, and doesn't support rejecting or abandoning a message.
        });
      }
    };
    client.open(connectCallback);
  }
});

// Helper function to print results in the console
function printResultFor(op) {
  return function printResult(err, res) {
    if (err) console.log(op + ' error: ' + err.toString());
    if (res) console.log(op + ' status: ' + res.constructor.name);
  };
}

В конце этого вывода мое устройство зарегистрировано под концентратором IOT, и я Можно также установить соединение, используя следующий код.

Вывод вышеуказанного сценария:

регистрация прошла успешно

назначенный концентратор = my-end-point. net

deviceId = my-device-id

Клиент подключен

создано двойниковое

двойное содержимое: null: Объект {сообщил: Объект, желаемый : Object}

Отправка сообщения: {"did": "my-device-id", "dts": "2020-01-30T07: 18: 38.471Z", "wantedStatus": "Activated", "reportsStatus": "Активация", "msg": []}

состояние отправки: MessageEnqueued

говорит, что сообщения находятся в очереди, но я не могу активировать устройство.

Я застрял на этом этапе. Может ли кто-нибудь помочь мне избавиться от этого?

любая идея, почему она не работает, или я иду в правильном подходе, будет приветствоваться.

...