Azure Iot Android 开发-MQTT协议通信(设备和IoT 实时通信)2-设备孪生详解

之前简单讲解了IotHub 使用,现在详解DeviceTwin,看文章之前先了解Azure Iot Android 开发-MQTT协议通信(设备和IoT 实时通信)1

设备孪生

设备孪生存储具有以下用途的设备相关信息:

  • 设备和后端可以使用这些信息来同步设备状态和配置。
  • 解决方案后端可以使用这些信息来查询和定位长时间运行的操作。

设备孪生的生命周期链接到相应的 设备标识。 在 IoT 中心创建或删除设备标识时,将隐式创建和删除设备孪生。

设备孪生是一个 JSON 文档,其中包含:

  • 标记。 解决方案后端可从中读取和写入数据的 JSON 文档的某个部分。 标记对设备应用不可见。
  • 所需的属性。 与报告的属性结合使用,同步设备配置或状态。 解决方案后端可设置所需的属性,并且设备应用可进行读取。 此外,当所需的属性发生更改时,设备应用可收到通知。
  • 报告的属性。 与所需的属性结合使用,同步设备配置或状态。 设备应用可设置报告的属性,并且解决方案后端可进行读取和查询。
  • 设备标识属性。 设备孪生 JSON 文档的根包含标识注册表中存储的相应设备标识的只读属性。

《Azure Iot Android 开发-MQTT协议通信(设备和IoT 实时通信)2-设备孪生详解》

以下示例显示了一个设备孪生 JSON 文档:

JSON复制

{
    "deviceId": "devA",
    "etag": "AAAAAAAAAAc=", 
    "status": "enabled",
    "statusReason": "provisioned",
    "statusUpdateTime": "0001-01-01T00:00:00",
    "connectionState": "connected",
    "lastActivityTime": "2015-02-30T16:24:48.789Z",
    "cloudToDeviceMessageCount": 0, 
    "authenticationType": "sas",
    "x509Thumbprint": {     
        "primaryThumbprint": null, 
        "secondaryThumbprint": null 
    }, 
    "version": 2, 
    "tags": {
        "$etag": "123",
        "deploymentLocation": {
            "building": "43",
            "floor": "1"
        }
    },
    "properties": {
        "desired": {
            "telemetryConfig": {
                "sendFrequency": "5m"
            },
            "$metadata" : {...},
            "$version": 1
        },
        "reported": {
            "telemetryConfig": {
                "sendFrequency": "5m",
                "status": "success"
            }
            "batteryLevel": 55,
            "$metadata" : {...},
            "$version": 4
        }
    }
}

根对象中包含设备标识属性,以及 tagsreporteddesired 属性的容器对象。 properties 容器包含一些只读元素($metadata$etag$version),设备孪生元数据乐观并发部分描述了这些元素。

一、设备孪生修改属性(reported单个属性)、查看属性(方法一)(Desired 所有属性)

创建一个 Device 对象用于存储设备孪生属性。

DeviceClient client = new DeviceClient(connString, protocol);

// Create a Device object to store the device twin properties
Device dataCollector = new Device() {
// Print details when a property value changes
@Override
public void PropertyCall(String propertyKey, Object propertyValue, Object context) {
  System.out.println(propertyKey + " changed to " + propertyValue);
}
};

创建 connectivityType 报告属性并将其发送到 IoT 中心:

try {
  // Open the DeviceClient and start the device twin services.
  client.open();
  client.startDeviceTwin(new DeviceTwinStatusCallBack(), null, dataCollector, null);
  //可获取到Desired 属性
  client.subscribeToDesiredProperties(telemetryConfig.getDesiredProp());
  // Create a reported property and send it to your IoT hub.
  dataCollector.setReportedProp(new Property("connectivityType", "cellular"));
  client.sendReportedProperties(dataCollector.getReportedProp());
}
catch (Exception e) {
  System.out.println("On exception, shutting down \n" + " Cause: " + e.getCause() + " \n" + e.getMessage());
  dataCollector.clean();
  client.close();
  System.out.println("Shutting down...");
}

通过getDeviceTwin() 回调PropertyCall方法

client.getDeviceTwin();

二、通过PropertyCallback 获取reported、Desired 所有属性

实现设备孪生功能,请通过将以下嵌套类添加到 App 类来提供回调:

protected static class DeviceTwinStatusCallback implements IotHubEventCallback
{
  public void execute(IotHubStatusCode status, Object context)
  {
    System.out.println("IoT Hub responded to device twin operation with status " + status.name());
  }
}
protected static class PropertyCallback implements PropertyCallBack<String, String>
{
  public void PropertyCall(String propertyKey, String propertyValue, Object context)
  {
    System.out.println("PropertyKey:     " + propertyKey);
    System.out.println("PropertyKvalue:  " + propertyKey);
  }
}

要启动直接方法和设备孪生例程,以下代码:

client = new DeviceClient(connString, protocol);

try
{
  client.open();
  client.subscribeToDeviceMethod(new DirectMethodCallback(), null, new DirectMethodStatusCallback(), null);
  client.startDeviceTwin(new DeviceTwinStatusCallback(), null, new PropertyCallback(), null);
  System.out.println("Client connected to IoT Hub.  Waiting for firmwareUpdate direct method.");
}
catch (Exception e)
{
  System.out.println("On exception, shutting down \n" + " Cause: " + e.getCause() + " \n" +  e.getMessage());
  client.close();
  System.out.println("Shutting down...");
}

三、通过PropertyCallback 、subscribeToTwinDesiredProperties 订阅指定属性、批量更新reported属性

添加以下回调:

 protected static class DeviceTwinStatusCallBack implements IotHubEventCallback
    {
        @Override
        public void execute(IotHubStatusCode status, Object context)
        {
            if((status == IotHubStatusCode.OK) || (status == IotHubStatusCode.OK_EMPTY))
            {
                Succeed.set(true);
            }
            else
            {
                Succeed.set(false);
            }
            System.out.println("IoT Hub responded to device twin operation with status " + status.name());
        }
    }

    /*
     * If you don't care about version, you can use the PropertyCallBack.
     */
    protected static class onHomeTempChange implements TwinPropertyCallBack
    {
        @Override
        public void TwinPropertyCallBack(Property property, Object context)
        {
            System.out.println(
                    "onHomeTempChange change " + property.getKey() +
                            " to " + property.getValue() +
                            ", Properties version:" + property.getVersion());
        }
    }

 

    protected static class onProperty implements TwinPropertyCallBack
    {
        @Override
        public void TwinPropertyCallBack(Property property, Object context)
        {
            System.out.println(
                    "onProperty callback for " + (property.getIsReported()?"reported": "desired") +
                            " property " + property.getKey() +
                            " to " + property.getValue() +
                            ", Properties version:" + property.getVersion());
        }
    }

订阅指定属性、批量更新reported属性

   DeviceClient client = new DeviceClient(connString, protocol);
        try
        {
            client.open();
            //  onHomeTempChange 里面获取所有属性值(Desired、 Report)
            client.startDeviceTwin(new DeviceTwinStatusCallBack(), null, new onHomeTempChange(), null);
    
            Map<Property, Pair<TwinPropertyCallBack, Object>> desiredProperties = new HashMap<Property, Pair<TwinPropertyCallBack, Object>>()
            {
                {
          //此处订阅指定的属性值Desired
                    put(new Property("LivingRoomLights", null), new Pair<TwinPropertyCallBack, Object>(new onProperty(), null));
                    put(new Property("BedroomRoomLights", null), new Pair<TwinPropertyCallBack, Object>(new onProperty(), null));
 
                }
            };
            client.subscribeToTwinDesiredProperties(desiredProperties);

        
            client.getDeviceTwin(); 
             // For each desired property in the Service, the SDK will call the appropriate callback with the value and version.

             //批量更新多个属性
            Set<Property> reportProperties = new HashSet<Property>()
            {
                {
                    add(new Property("HomeTemp(F)", 70));
                    add(new Property("LivingRoomLights", LIGHTS.ON));
                    add(new Property("BedroomRoomLights", LIGHTS.OFF));
                }
            };
            client.sendReportedProperties(reportProperties);
        catch (Exception e)
        {
            client.closeNow();
            System.out.println("Shutting down...");
        }
    }

以上就是DeviceTwin使用详解

参考:

Azure IoT文档中心:https://docs.azure.cn/zh-cn/iot-hub/iot-hub-devguide

GitHub:https://github.com/Azure/azure-iot-sdk-java/tree/master/device

官方GitHub详细地址

    原文作者:流水潺湲
    原文地址: https://www.jianshu.com/p/1b0381d10cd4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞