Fetch twin from Azure device sdk

443 Views Asked by At

I need to just get the twin of a device using the Azure device sdk for node.js. I did used the Client clode as below:-

import { Client } from 'azure-iot-device';
import { Mqtt } from 'azure-iot-device-mqtt';
await client.setOptions(options);
await client.open();
const twin = await client.getTwin();

The issue is the twin returned doesn't have the device twin fields but other fields like below:-

{
  _events: [Object: null prototype] { newListener: [Function: bound ] },
  _eventsCount: 1,
  _maxListeners: undefined,
  _transport: Mqtt {
    _events: [Object: null prototype] {
      error: [Function],
      connected: [Function],
      disconnect: [Array],
      message: [Function],
      twinDesiredPropertiesUpdate: [Function: bound ]
    },
    _eventsCount: 5,
    _maxListeners: undefined,
    _mid: '',
    _firstConnection: false,
    _authenticationProvider: X509AuthenticationProvider { type: 0, _credentials: [Object] },
    _mqtt: MqttBase {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      mqttProvider: [Object],
      _onTheWirePublishes: [OnTheWireMessageContainer],
      _fsm: [constructor],
      _options: [Object],
      _config: [Object],
      _mqttClient: [MqttClient],
      [Symbol(kCapture)]: false
    },
    _twinClient: MqttTwinClient {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      _pendingTwinRequests: {},
      _mqtt: [MqttBase],
      _topicFsm: [BehavioralFsm],
      _responseTopic: [Object],
      _desiredPropertiesUpdatesTopic: [Object],
      [Symbol(kCapture)]: false
    },
    _fsm: constructor {
      initialState: 'disconnected',
      states: [Object],
      eventListeners: [Object],
      namespace: 'fsm.2',
      useSafeEmit: false,
      hierarchy: {},
      pendingDelegations: {},
      _stamped: true,
      inputQueue: [],
      targetReplayState: 'connected',
      state: 'connected',
      priorState: 'connecting',
      priorAction: 'connected.getTwin',
      currentAction: '',
      currentActionArgs: undefined,
      inExitHandler: false
    },
    _topicTelemetryPublish: 'devices/amidha/messages/events/',
    _topics: { method: [Object], message: [Object] },
    _userAgentString: 'azure-iot-device/1.17.1 (node v12.18.0; Ubuntu 18.04; x64)',
    [Symbol(kCapture)]: false
  },
  _retryPolicy: ExponentialBackOffWithJitter {
    _errorFilter: DefaultErrorFilter {
      ArgumentError: false,
      ArgumentOutOfRangeError: false,
      DeviceMaximumQueueDepthExceededError: false,
      DeviceNotFoundError: false,
      FormatError: false,
      UnauthorizedError: false,
      NotImplementedError: false,
      NotConnectedError: true,
      IotHubQuotaExceededError: false,
      MessageTooLargeError: false,
      InternalServerError: true,
      ServiceUnavailableError: true,
      IotHubNotFoundError: false,
      IoTHubSuspendedError: false,
      JobNotFoundError: false,
      TooManyDevicesError: false,
      ThrottlingError: true,
      DeviceAlreadyExistsError: false,
      DeviceMessageLockLostError: false,
      InvalidEtagError: false,
      InvalidOperationError: false,
      PreconditionFailedError: false,
      TimeoutError: true,
      BadDeviceResponseError: false,
      GatewayTimeoutError: false,
      DeviceTimeoutError: false,
      TwinRequestError: false
    },
    immediateFirstRetry: true,
    normalParameters: ExponentialBackoffWithJitterParameters {
      c: 100,
      cMin: 100,
      cMax: 10000,
      ju: 0.25,
      jd: 0.5
    },
    throttledParameters: ExponentialBackoffWithJitterParameters {
      c: 5000,
      cMin: 10000,
      cMax: 60000,
      ju: 0.25,
      jd: 0.5
    }
  },
  _maxOperationTimeout: 240000,
  desiredPropertiesUpdatesEnabled: false,
  properties: {
    reported: { update: [Function: update], '$version': 1 },
    desired: { '$version': 1 }
  },
  [Symbol(kCapture)]: false
}

I don't want to listen the twin change events that I can do easily by using above object using twin.on. I need to just get the current twin of the device. Is it possible?

3

There are 3 best solutions below

0
On BEST ANSWER

Above is not feasible to get the whole twin not just the desired and reported properties from device IoT sdk and that has been confirmed by Azure too. Check here.

The link also has a solution to assign parent child relationship between the leaf and the edge device.

2
On

The current twin is in the JSON you posted. See the section properties:

 properties: {
    reported: { update: [Function: update], '$version': 1 },
    desired: { '$version': 1 }
  },

The twin you posted is empty.

1
On

After reading your comments it seems you are expecting some values to be there that just aren't available to the device (when you use the device SDK). The device can read and receive updates on desired properties and read/write to reported properties, the rest is unavailable.

Available operations

In a comment, you mentioned you want to find the deviceScope in the twin, but that isn't available to the device SDK. You would need the service SDK for that.

When you print the result of const twin = await client.getTwin();, what you see is an object with helper methods to subscribe to desired property changes and patching new reported properties. Like Mark stated in his question, the properties of your twin are included in this object as well.