-
Notifications
You must be signed in to change notification settings - Fork 1
/
Device.cs
65 lines (56 loc) · 2.83 KB
/
Device.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using Rido.Mqtt.HubClient;
using Rido.Mqtt.MqttNet3Adapter;
using Rido.MqttCore;
using Rido.MqttCore.PnP;
using System.Text.Json;
namespace layer2_sample
{
public class Device : BackgroundService
{
private readonly ILogger<Device> _logger;
private readonly IConfiguration _configuration;
public Device(ILogger<Device> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
//IMqttBaseClient adapter = await new MqttNet4Adapter.MqttNetClientConnectionFactory().CreateHubClientAsync(_configuration.GetConnectionString("cs"),stoppingToken);
//IMqttBaseClient adapter = await new M2MAdapter.M2MClientConnectionFactory().CreateHubClientAsync(_configuration.GetConnectionString("cs"), stoppingToken);
IMqttBaseClient adapter = await new MqttNetClientConnectionFactory().CreateHubClientAsync(_configuration.GetConnectionString("cs"), stoppingToken);
var client = new HubMqttClient(adapter);
_logger.LogInformation($"CONNECTED: DeviceId: {client.Connection.ConnectionSettings.DeviceId} - HostName: {client.Connection.ConnectionSettings.HostName} ");
_logger.LogInformation($"Using MQTT Library:" + client.Connection.BaseClientLibraryInfo);
var v = await client.ReportPropertyAsync(new { started = DateTime.Now }, stoppingToken);
_logger.LogInformation($"Property updated with version {v}");
var twin = await client.GetTwinAsync(stoppingToken);
_logger.LogInformation(twin);
client.OnCommandReceived = async m =>
{
_logger.LogInformation("Processing command: " + m.CommandName);
return await Task.FromResult(new CommandResponse()
{
Status = 200,
ReponsePayload = JsonSerializer.Serialize(new { myResponse = "whatever" })
});
};
client.OnPropertyUpdateReceived = async m =>
{
_logger.LogInformation("Processing desired: " + m.ToJsonString());
return await Task.FromResult(new GenericPropertyAck
{
Value = m.ToJsonString(),
Status = 200,
Version = m["$version"].GetValue<int>()
});
};
while (!stoppingToken.IsCancellationRequested)
{
var puback = await client.SendTelemetryAsync(new { workingSet = Environment.WorkingSet }, stoppingToken);
_logger.LogInformation($"Telemetry pubAck {puback}", DateTimeOffset.Now);
await Task.Delay(5000, stoppingToken);
}
}
}
}