Search code examples
azure-iot-hubazure-iot-sdkazure-iot-central

How to create a TwinCollection with IDictionary<string, object> for GeoPoint property for Azure IoT Hub?


I have an IoT Device with a property that is a Geopoint.

I am using the Azure IoT C# sdk using the following GitHub examples: azure-iot-samples-csharp

I have code calling the public static TwinCollection CreatePropertyPatch(IDictionary<string, object> propertyPairs) method.

I know the format of the JSON needs to be:

{
  "DeviceLocation": {
    "lat": 47.64263,
    "lon": -122.13035,
    "alt": 0
  }
}

Is there a way to do this with IDictionary<string, object>??

If so what would the c# sample code look like?


Solution

  • The PnpConvention class that you're referring to doesn't do a lot more than serialize the object you give it. So here's a few things you can do to update the device twin.

    You can do it through an anonymous object:

    var location = new { lat = 47.64263, lon = -122.13035, alt = 0 };
    TwinCollection twinCollection = PnpConvention.CreatePropertyPatch("DeviceLocation", location);
    await client.UpdateReportedPropertiesAsync(twinCollection);
    

    Or create a class for this object:

    public class DeviceLocation
    {
        [JsonProperty("lat")]
        public double Latitude { get; set; }
    
        [JsonProperty("lon")]
        public double Longitude { get; set; }
    
        [JsonProperty("alt")]
        public double Altitude { get; set; }
    }
    
    var location = new DeviceLocation { Latitude = 47.64263, Longitude = -122.13035, Altitude = 0 };
    TwinCollection twinCollection = PnpConvention.CreatePropertyPatch("DeviceLocation", location);
    await client.UpdateReportedPropertiesAsync(twinCollection);
    

    Or, my favourite, because the PnpConvention class doesn't do much for device twin updates:

    TwinCollection twinCollection = new TwinCollection();
    twinCollection["DeviceLocation"] = new { lat = 47.64263, lon = -122.13035, alt = 0 };
    await client.UpdateReportedPropertiesAsync(twinCollection);