-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMQTTClient.cs
356 lines (316 loc) · 14.2 KB
/
MQTTClient.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Diagnostics;
using MQTTnet.Protocol;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace IoTSharp.MqttSdk
{
public class MqttClientHost : BackgroundService
{
private readonly MQTTClient client;
public MqttClientHost(MQTTClient client)
{
this.client = client;
}
DateTime _lastconnect=DateTime.MinValue;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
do
{
if (!client.IsConnected)
{
var ts = DateTime.Now.Subtract(_lastconnect).TotalSeconds;
if (10 < ts && ts < 40)//如果 10到40秒内又重新连接一次, 则更换客户端ID再次登录。
{
client.ClientId = Guid.NewGuid().ToString();
_lastconnect = DateTime.Now;
}
await client.ConnectAsync();
}
else
{
client.Ping();
await Task.Delay(TimeSpan.FromSeconds(50));
}
await Task.Delay(TimeSpan.FromSeconds(10));
} while (!stoppingToken.IsCancellationRequested);
}
}
public class MQTTClient
{
public MQTTClient(IServiceScopeFactory scopeFactor, IOptions<MqttSettings> options, ILogger<MQTTClient> logger)
{
_settings = options.Value;
BrokerUri = new Uri(_settings.MqttBroker);
OnReceiveAttributes += MQTTClient_OnReceiveAttributes;
OnExcRpc += Client_OnExcRpc;
OnConnected += MQTTClient_OnConnected;
_logger = logger;
}
public async void Ping()
{
if (Client != null)
{
var ping_ = await Client?.TryPingAsync();
_logger.LogInformation($"TryPing {ping_}");
}
}
private void MQTTClient_OnReceiveAttributes(object sender, AttributeResponse e)
{
switch (e.KeyName)
{
case "rootuser":
break;
default:
break;
}
}
private void MQTTClient_OnConnected(object? sender, MqttClientConnectedEventArgs e)
{
}
public async Task DisconnectAsync()
{
await Client.DisconnectAsync();
Client.Dispose();
}
private void Client_OnExcRpc(object? sender, RpcRequest e)
{
}
private readonly MqttSettings _settings;
private readonly ILogger<MQTTClient> _logger;
public Uri BrokerUri { get; set; }
public bool IsConnected => (Client?.IsConnected).GetValueOrDefault();
private IMqttClient Client { get; set; }
public event EventHandler<RpcRequest> OnExcRpc;
public event EventHandler<AttributeResponse> OnReceiveAttributes;
public event EventHandler<MqttClientConnectedEventArgs> OnConnected;
public async Task<bool> ConnectAsync(Uri uri)
{
BrokerUri = uri;
return await ConnectAsync();
}
public string DeviceId => BrokerUri?.PathAndQuery?.Trim('/');
private string _client_id;
public string ClientId
{
get {
if (string.IsNullOrEmpty(_client_id))
{
var st = DeviceId;
if (string.IsNullOrEmpty(st))
{
st = Guid.NewGuid().ToString();
}
return st;
}
else
{
return _client_id;
}
}
set { _client_id = value; }
}
public async Task<bool> ConnectAsync()
{
var uri = BrokerUri;
bool initok = false;
string username = "";
string password = "";
if (!string.IsNullOrEmpty(uri.UserInfo))
{
var uinfo = uri.UserInfo.Split(':');
if (uinfo.Length > 0) username = uinfo[0];
if (uinfo.Length > 1) password = uinfo[1];
}
try
{
if (Client != null)
{
Disconnect();
}
var factory = new MqttFactory();
Client = factory.CreateMqttClient();
var clientOptions = new MqttClientOptionsBuilder()
.WithClientId(ClientId)
.WithTcpServer(uri.Host, uri.Port)
.WithCredentials(username, password).WithKeepAlivePeriod(TimeSpan.FromSeconds(30))
.Build();
Client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceived;
Client.ConnectedAsync+= Client_ConnectedAsync;
Client.DisconnectedAsync += (MqttClientDisconnectedEventArgs e) =>
{
try
{
_logger.LogWarning($"CONNECTING FAILED,{e.Reason}-{e.ReasonString}");
}
catch (Exception exception)
{
_logger.LogError(exception, "CONNECTING FAILED");
}
return Task.CompletedTask;
};
try
{
var result = await Client.ConnectAsync(clientOptions);
initok = result.ResultCode == MqttClientConnectResultCode.Success;
}
catch (Exception exception)
{
_logger.LogError(exception, "CONNECTING FAILED");
}
_logger.LogInformation("WAITING FOR APPLICATION MESSAGES");
}
catch (Exception exception)
{
_logger.LogError(exception, "CONNECTING FAILED");
}
return initok;
}
public void Disconnect()
{
try
{
Client.DisconnectAsync();
}
catch
{
}
try
{
Client.Dispose();
}
catch
{
}
}
private async Task Client_ConnectedAsync(MqttClientConnectedEventArgs e)
{
await Client.SubscribeAsync($"devices/{DeviceId}/rpc/request/+/+");
await Client.SubscribeAsync($"devices/{DeviceId}/attributes/update/", MqttQualityOfServiceLevel.ExactlyOnce);
_logger.LogInformation($"CONNECTED WITH SERVER ");
OnConnected?.Invoke(this, e);
}
/// <summary>
/// 网关的字设备订阅名称, 不订阅 ID,因为 网关可能没法知道自己子设备的ID,但一定知道自己的ID,因此 连接时订阅自己的消息, 后期订阅子设备的消息
/// </summary>
/// <param name="name">子设备名称</param>
public async Task SubscribeDeviceAsync(string name)
{
///devices/SafetyBeltBox_863488055345618/rpc/request/clasp/6c86c79cbb2f486cb3ae5c491acb828d
///devices/SafetyBeltBox_863488055345618/rpc/request/+/+
var res1 = await Client.SubscribeAsync($"devices/{name}/rpc/request/+/+", MqttQualityOfServiceLevel.ExactlyOnce);
_logger.LogInformation($"订阅{name} {res1.ReasonString}");
var resu2 = await Client.SubscribeAsync($"devices/{name}/attributes/update/", MqttQualityOfServiceLevel.ExactlyOnce);
_logger.LogInformation($"订阅{name} {res1.ReasonString}");
}
private Task Client_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
{
_logger.LogInformation($"ApplicationMessageReceived Topic {e.ApplicationMessage.Topic} QualityOfServiceLevel:{e.ApplicationMessage.QualityOfServiceLevel} Retain:{e.ApplicationMessage.Retain} ");
try
{
if (e.ApplicationMessage.Topic.StartsWith($"devices/") && e.ApplicationMessage.Topic.Contains("/response/"))
{
ReceiveAttributes(e);
}
else if (e.ApplicationMessage.Topic.StartsWith($"devices/") && e.ApplicationMessage.Topic.Contains("/rpc/request/"))
{
var tps = e.ApplicationMessage.Topic.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var rpcmethodname = tps[4];
var rpcdevicename = tps[1];
var rpcrequestid = tps[5];
_logger.LogInformation($"rpcmethodname={rpcmethodname} ");
_logger.LogInformation($"rpcdevicename={rpcdevicename } ");
_logger.LogInformation($"rpcrequestid={rpcrequestid} ");
if (!string.IsNullOrEmpty(rpcmethodname) && !string.IsNullOrEmpty(rpcdevicename) && !string.IsNullOrEmpty(rpcrequestid))
{
OnExcRpc?.Invoke(Client, new RpcRequest()
{
Method = rpcmethodname,
DeviceId = rpcdevicename,
RequestId = rpcrequestid,
Params = e.ApplicationMessage.ConvertPayloadToString()
});
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, $"ClientId:{e.ClientId} Topic:{e.ApplicationMessage.Topic},Payload:{e.ApplicationMessage.ConvertPayloadToString()}");
}
return Task.CompletedTask;
}
private void ReceiveAttributes(MqttApplicationMessageReceivedEventArgs e)
{
var tps = e.ApplicationMessage.Topic.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var rpcmethodname = tps[2];
var rpcdevicename = tps[1];
var rpcrequestid = tps[4];
_logger.LogInformation($"rpcmethodname={rpcmethodname} ");
_logger.LogInformation($"rpcdevicename={rpcdevicename } ");
_logger.LogInformation($"rpcrequestid={rpcrequestid} ");
if (!string.IsNullOrEmpty(rpcmethodname) && !string.IsNullOrEmpty(rpcdevicename) && !string.IsNullOrEmpty(rpcrequestid))
{
if (e.ApplicationMessage.Topic.Contains("/attributes/"))
{
OnReceiveAttributes?.Invoke(Client, new AttributeResponse()
{
KeyName = rpcmethodname,
DeviceName = rpcdevicename,
Id = rpcrequestid,
Data = e.ApplicationMessage.ConvertPayloadToString()
});
}
}
}
public Task UploadAttributeAsync(object obj) => UploadAttributeAsync("me", obj);
public Task UploadAttributeAsync(string _devicename, object obj)
{
return Client.PublishAsync($"devices/{_devicename}/attributes", JsonSerializer.Serialize(obj));
}
public Task UploadAttributeAsync(string _devicename, JsonDocument jo)
{
return Client.PublishAsync($"devices/{_devicename}/attributes", jo.ToString());
}
public Task UploadTelemetryDataAsync(object obj) => UploadTelemetryDataAsync("me", obj);
public Task UploadTelemetryDataAsync(string _devicename, object obj)
{
return Client.PublishAsync($"devices/{_devicename}/telemetry", JsonSerializer.Serialize(obj));
}
public Task UploadDeviceStatusAsync(string _devicename, bool online)
{
return Client.PublishAsync($"devices/{_devicename}/status/{(online ? "online" : "offline")}", JsonSerializer.Serialize(new { online }));
}
public Task ResponseExecommand(RpcResponse rpcResult)
{
///IoTSharp/Clients/RpcClient.cs#L65 var responseTopic = $"/devices/{deviceid}/rpc/response/{methodName}/{rpcid}";
string topic = $"devices/{rpcResult.DeviceId}/rpc/response/{rpcResult.Method.ToString()}/{rpcResult.ResponseId}";
return Client.PublishAsync( topic, JsonSerializer.Serialize(rpcResult.Data) , MqttQualityOfServiceLevel.ExactlyOnce );
}
public Task RequestExecommand(RpcRequest rpcRequest)
{
///IoTSharp/Clients/RpcClient.cs#L65 var responseTopic = $"/devices/{deviceid}/rpc/response/{methodName}/{rpcid}";
string topic = $"devices/{rpcRequest.DeviceId}/rpc/request/{rpcRequest.Method.ToString()}/{rpcRequest.RequestId}";
return Client.PublishAsync(topic, rpcRequest.Params.ToString(), MqttQualityOfServiceLevel.ExactlyOnce);
}
public Task RequestAttributes(params string[] args) => RequestAttributes("me", false, args);
public Task RequestAttributes(string _device, params string[] args) => RequestAttributes(_device, false, args);
public Task RequestAttributes(bool anySide = true, params string[] args) => RequestAttributes("me", true, args);
public Task RequestAttributes(string _device, bool anySide, params string[] args)
{
string id = Guid.NewGuid().ToString();
string topic = $"devices/{_device}/attributes/request/{id}";
Dictionary<string, string> keys = new Dictionary<string, string>();
keys.Add(anySide ? "anySide" : "server", string.Join(",", args));
Client.SubscribeAsync($"devices/{_device}/attributes/response/{id}", MqttQualityOfServiceLevel.ExactlyOnce);
return Client.PublishAsync(topic, JsonSerializer.Serialize(keys), MqttQualityOfServiceLevel.ExactlyOnce);
}
}
}