Skip to content

Instantly share code, notes, and snippets.

@rido-min
Created July 7, 2021 00:46
Show Gist options
  • Select an option

  • Save rido-min/3013eada730837bc1ff4d917f1903c9a to your computer and use it in GitHub Desktop.

Select an option

Save rido-min/3013eada730837bc1ff4d917f1903c9a to your computer and use it in GitHub Desktop.
DefaultTwinProps
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Shared;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Text;
using System.Threading.Tasks;
namespace STS.Device
{
class Program
{
static async Task Main(string[] args)
{
var mid = "dtmi:rido:sts;1";
var CS = Environment.GetEnvironmentVariable("CS");
var dc = DeviceClient.CreateFromConnectionString(CS, TransportType.Mqtt, new ClientOptions { ModelId = mid });
Console.WriteLine("Connected");
bool dirty = false;
int SendInterval = 3;
bool SendData = true;
int count = 0;
var props = (await dc.GetTwinAsync()).Properties;
var defaultProps = new TwinCollection();
if (!props.Desired.TryGetValue<bool>("SendData", out SendData, SendData))
{
Console.WriteLine("desired SendData not found");
if (!props.Reported.TryGetValue<bool>("SendData", out SendData, SendData))
{
Console.WriteLine("reported SendData not found.");
defaultProps["SendData"] = new
{
ac = 200,
av = props.Reported.Version,
value = SendData
};
dirty = true;
}
}
if (!props.Desired.TryGetValue<int>("SendInterval", out SendInterval, SendInterval))
{
Console.WriteLine("SendInterval not found");
if (!props.Reported.TryGetValue("SendInterval" , out SendInterval, SendInterval))
{
Console.WriteLine("reported SendInterval not found.");
defaultProps["SendInterval"] = new
{
ac = 200,
av = props.Reported.Version,
value = SendInterval
};
dirty = true;
}
}
if (dirty)
{
await dc.UpdateReportedPropertiesAsync(defaultProps);
Console.WriteLine("Aplied Default Values (Dirty)");
}
Console.WriteLine($"Initialized with SendData: {SendData} SendInterval: {SendInterval} ");
await dc.SetMethodDefaultHandlerAsync(
async (commandRequest, userContext) =>
{
if (commandRequest.Name == "reset")
{
Console.WriteLine("Command RESET received.");
count = 0;
return await Task.FromResult(new MethodResponse(200));
}
else
{
Console.WriteLine("Received an unknown command: " + commandRequest.Name);
return await Task.FromResult(new MethodResponse(200));
}
}, null);
await dc.SetDesiredPropertyUpdateCallbackAsync(
async (desired, userContext) =>
{
var propertiesToBeUpdated = new TwinCollection();
if (desired.TryGetValue<int>("SendInterval", out SendInterval, SendInterval))
{
propertiesToBeUpdated["SendInterval"] = new
{
ac = 200,
av = desired.Version,
value = SendInterval
};
Console.WriteLine("Received SendInterval property" + SendInterval);
}
if (desired.TryGetValue<bool>("SendData", out SendData, SendData))
{
propertiesToBeUpdated["SendData"] = new
{
ac = 200,
av = desired.Version,
value = SendData
};
Console.WriteLine("Received SendData property " + SendData);
}
await dc.UpdateReportedPropertiesAsync(propertiesToBeUpdated);
}, null);
while (true)
{
if (SendData)
{
var Rnd = new Random();
var tempData = new MessageBody
{
Machine = new Machine
{
Temperature = Rnd.NextDouble(),
Pressure = Rnd.NextDouble(),
},
Ambient = new Ambient
{
Temperature = Rnd.NextDouble() - 0.5,
Humidity = Rnd.Next(24, 27)
},
TimeCreated = DateTime.UtcNow
};
string dataBuffer = JsonConvert.SerializeObject(tempData);
var eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer))
{
ContentType = "application/json",
ContentEncoding = "utf-8"
};
eventMessage.Properties.Add("sequenceNumber", count.ToString());
eventMessage.Properties.Add("batchId", "BatchId.ToString()");
Console.WriteLine($"\t{DateTime.Now.ToLocalTime()}> Sending message: {count}, Body: [{dataBuffer}]");
await dc.SendEventAsync(eventMessage);
}
else
{
Console.WriteLine("SendData disabled");
}
count++;
await Task.Delay(Convert.ToInt32(SendInterval * 1000));
}
}
}
public static class TwinCollectionExtensions
{
public static bool TryGetValue<T>(this TwinCollection collection, string propertyName, out T result, T defaultVAlue = default(T))
{
bool found = false;
result = defaultVAlue;
if (collection.Contains(propertyName))
{
found = true;
JObject propertyJson = collection[propertyName] as JObject;
if (propertyJson != null)
{
if (propertyJson.ContainsKey("value"))
{
var propertyValue = propertyJson["value"];
result = propertyValue.Value<T>();
}
}
else
{
result = collection[propertyName];
}
}
return found;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment