Skip to content

Instantly share code, notes, and snippets.

@rido-min
Created February 10, 2023 01:48
Show Gist options
  • Save rido-min/6568aae11d45e4290311824a65655f5e to your computer and use it in GitHub Desktop.
Save rido-min/6568aae11d45e4290311824a65655f5e to your computer and use it in GitHub Desktop.
IoTHubCommands
using Microsoft.Azure.Devices;
using System.Text.Json;
namespace SampleDtdlCmd
{
public class Command<TReq, TResp>
{
string _cs;
string _did;
string _name;
public Command(string cs, string did, string cmdName)
{
_cs = cs;
_did = did;
_name = cmdName;
}
public async Task<TResp> ExecuteAsync(TReq request)
{
var sc = ServiceClient.CreateFromConnectionString(_cs);
CloudToDeviceMethod c2d = new CloudToDeviceMethod(_name, TimeSpan.FromMinutes(2), TimeSpan.FromSeconds(30));
c2d.SetPayloadJson(JsonSerializer.Serialize(request));
var res = await sc.InvokeDeviceMethodAsync(_did, c2d);
string respJson = res.GetPayloadAsJson();
TResp result = JsonSerializer.Deserialize<TResp>(respJson)!;
return result;
}
}
}
using Microsoft.Azure.Devices;
using System.Text.Json;
namespace SampleDtdlCmd
{
internal class Memmon
{
public Command<int, Dictionary<string, string>> getRuntimeStats { get; set; }
public Memmon(string hubConnectionString, string deviceId)
{
getRuntimeStats = new Command<int, Dictionary<string, string>>(hubConnectionString,deviceId, "getRuntimeStats");
}
}
}
using SampleDtdlCmd;
using System.Text.Json;
internal class Program
{
private static async Task Main(string[] args)
{
var did = "";
var did2 = "";
var cs = "HostName=.azure-devices.net;SharedAccessKeyName=;SharedAccessKey=";
Sensor sensor = new Sensor(cs, did);
var tr = await sensor.getMaxMinReport.ExecuteAsync(DateTime.Now.AddDays(-2));
Console.WriteLine(JsonSerializer.Serialize(tr, new JsonSerializerOptions { WriteIndented = true }));
Memmon mm = new Memmon(cs, did2);
var res = await mm.getRuntimeStats.ExecuteAsync(2);
Console.WriteLine(JsonSerializer.Serialize(res, new JsonSerializerOptions { WriteIndented = true }));
}
}
using System.Text.Json;
using System.Text.Json.Serialization;
namespace SampleDtdlCmd
{
public class TempReport
{
[JsonPropertyName("maxTemp")]
public double MaxTemp { get; set; }
[JsonPropertyName("minTemp")]
public double minTemp { get; set; }
[JsonPropertyName("avgTemp")]
public double AvgTemp { get; set; }
[JsonPropertyName("startTime")]
public DateTime StartTime { get; set; }
[JsonPropertyName("endTime")]
public DateTime EndTime { get; set; }
}
internal class Sensor
{
public Command<DateTime, TempReport?> getMaxMinReport { get; set; }
public Sensor(string hubConnectionString, string deviceId)
{
getMaxMinReport = new Command<DateTime, TempReport?>(hubConnectionString, deviceId, "getMaxMinReport");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment