Search code examples
azure-iot-hubazure-iot-sdk

How to get old device twin value from TwinChangeEvents event in Microsoft Azure IoT Hub?


I created a route for TwinChangeEvents in Microsoft Azure portal and I can Receive device-to-cloud messages when device twin changes. But the message only contains the new device twin value. I needed the old value for analysis so that I don’t have to analyze the whole devices.

Is there any way I can get the old value?


Solution

  • First of all, I would like to note, that the implementation of the twin desired change notifications and TwinChangeEvents in the Azure IoT Hub generated an event every time when the service for updating a device twin state has been invoked, doesn't matter if the device twin state stayed the same (no changes). The result of this behavior is a new version number for the same device twin state.

    The following screen snippets show this situation:

    1. The REST API call for updating a twin state, you can send it multiple times: PatchDeviceTwin

    2. Screen snippet of the TwinChangeEvents message - version 37: Version37

    3. Screen snippet of the TwinChangeEvents message - version 38: Version38

    As you can see, the above twin state is the same (no changes) but for each call (step 1) we have a new version number.

    It looks like this is a bug, when the notification of the twin changes is working in the case, when the twin state has been not changed. In other words, this kind of notifications should be work only when the device state has been changed. Fixing this "bug" will be simplified a logic in the device and behind the Azure IoT Hub Routes.

    Well, now the following is my answer to your question how to get the older device twin state.

    Note, that this feature is not currently implemented in the Azure IoT Hub, but adding few components to the Azure IoT infrastructure you can solve this problem.

    Option 1: - Creating the TwinChangeEvents Stream Pipeline, see the following picture: TwinChangeEventsStreamPipeline The ASA job can be run in the hot path or in the cold path based on the business model requirements. Note, that this option requires an additional cost (~$120/month) for Capture and ASA Job entities.

    Option 2: - Creating the TwinChangeEvents Repository (storage), see the following picture:

    TwinChangeEventsRepository

    The Azure Function is triggered by twin change events with a responsibility for mapping them to the row object of the Azure Table Storage. After that, the specific twin state can be queried from the table based on the value, version, timestamp, etc.