Azure Iot集线器Device vs. Service SDK是否可以从Device twin获得所需的属性?

问题描述

这给出了 service device sdk的段落摘要

https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-sdks

嗨,我有两个正在处理的存储库或项目,一个正在使用Azure Iot Hub Service SDK(此处为Java的文档API:https://docs.microsoft.com/en-us/java/api/com.microsoft.azure.sdk.iot.service?view=azure-java-stable),很容易获得DeviceTwin所需的属性。我只需要一个DeviceTwindevice对象,然后在其上调用getDesiredProperties()。这一切都来自于依赖项:

compile group: 'com.microsoft.azure.sdk.iot',name: 'iot-service-client',version: '1.16.0'

现在 ,我正在另一个仓库中,我必须从Device twin中读取特定属性,但是该项目正在使用Azure Iot Hub 设备 SDK(此处为Java文档API:https://docs.microsoft.com/en-us/java/api/com.microsoft.azure.sdk.iot.device?view=azure-java-stable),其工作方式略有不同。看来他们使用DeviceClient对象来连接Iot集线器等。除了getDeviceTwin()方法之外,没有其他方法可以检索DeviceTwin的所需属性,但是它是一个void方法,什么都不返回?对此的依赖是

 compile(group: 'com.microsoft.azure.sdk.iot',name: 'iot-device-client',version: '1.19.1')

对于那些以前从未看过这些“属性”的人来说,它只是位于Azure门户网站上的JSON:

enter image description here

是否有一种简单的方法可以使用 device sdk来获取这些属性,还是必须将Gradle中的依赖项拖动到 service sdk并以此方式进行?似乎多余。请帮忙!

解决方法

Java的Device SDK中的getDeviceTwin()方法与其他语言略有不同。有一个非常好的示例here。神奇之处在于调用getDeviceTwin()的几行,您首先在其中定义了要为其注册回调的属性。以下示例均来自上述链接:

System.out.println("Subscribe to Desired properties on device Twin...");
Map<Property,Pair<TwinPropertyCallBack,Object>> desiredProperties = new HashMap<Property,Object>>()
{
  {
    put(new Property("HomeTemp(F)",null),new Pair<TwinPropertyCallBack,Object>(new onHomeTempChange(),null));
    put(new Property("LivingRoomLights",Object>(new onProperty(),null));
    put(new Property("BedroomRoomLights",null));
    put(new Property("HomeSecurityCamera",Object>(new onCameraActivity(),null));
  }
};

client.subscribeToTwinDesiredProperties(desiredProperties);

System.out.println("Get device Twin...");
client.getDeviceTwin(); // Will trigger the callbacks.

然后在回调中完成对接收到的属性的处理,例如:

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());
  }
}