0

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?

Mike Lenart
  • 767
  • 1
  • 5
  • 19
  • What are you trying to update? Is this about Device Twins in IoT Hub? Or is this question regarding IoT PNP? The method you're referring to seems to only exist in the PnP space. – Matthijs van der Veer Aug 28 '22 at 13:46
  • @MatthijsvanderVeer It really is both. I am using PNP but I am trying to update my DeviceTwin via PNP class. How do I create the element in the IDictionary collection that will be the appropriate value that IoT Hub would understand? Should the "string" value equal "DeviceLocation" while the "object" be a json based string consisting of the values after the "DeviceLocation": section? – Mike Lenart Aug 28 '22 at 23:15

1 Answers1

1

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);
Matthijs van der Veer
  • 3,865
  • 2
  • 12
  • 22