-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMqttServerConnector.cs
205 lines (179 loc) · 6.98 KB
/
MqttServerConnector.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
using MQTTnet;
using MQTTnet.Server;
using SmartIOT.Connector.Core;
using SmartIOT.Connector.Core.Connector;
using SmartIOT.Connector.Core.Events;
using SmartIOT.Connector.Messages;
using SmartIOT.Connector.Messages.Serializers;
namespace SmartIOT.Connector.Mqtt.Server;
public class MqttServerConnector : AbstractPublisherConnector
{
private new MqttServerConnectorOptions Options => (MqttServerConnectorOptions)base.Options;
private readonly MqttServer _mqttServer;
private readonly ISingleMessageSerializer _messageSerializer;
private bool _started;
public MqttServerConnector(MqttServerConnectorOptions options)
: base(options)
{
_messageSerializer = options.MessageSerializer;
_mqttServer = new MqttFactory().CreateMqttServer(new MqttServerOptionsBuilder()
.WithDefaultEndpoint()
.WithDefaultEndpointPort(Options.ServerPort)
.Build());
_mqttServer.ClientConnectedAsync += OnClientConnected;
_mqttServer.ClientDisconnectedAsync += OnClientDisconnected;
_mqttServer.InterceptingPublishAsync += OnApplicationMessageReceived;
_mqttServer.ClientSubscribedTopicAsync += OnClientSubscribedTopic;
_mqttServer.StartedAsync += OnStarted;
_mqttServer.StoppedAsync += OnStopped;
}
private async Task OnClientSubscribedTopic(ClientSubscribedTopicEventArgs e)
{
if (Options.IsDeviceStatusEventsTopicRoot(e.TopicFilter.Topic))
{
await InvokeInitializationDelegateAsync(true, false);
}
if (Options.IsTagScheduleEventsTopicRoot(e.TopicFilter.Topic))
{
await InvokeInitializationDelegateAsync(false, true);
}
}
public override async Task StartAsync(ISmartIOTConnectorInterface connectorInterface)
{
await base.StartAsync(connectorInterface);
await _mqttServer.StartAsync();
}
private Task OnStarted(EventArgs obj)
{
_started = true;
return Task.CompletedTask;
}
public override async Task StopAsync()
{
await base.StopAsync();
await _mqttServer.StopAsync();
}
private Task OnStopped(EventArgs obj)
{
_started = false;
return Task.CompletedTask;
}
private Task OnApplicationMessageReceived(InterceptingPublishEventArgs e)
{
if (e.ApplicationMessage.Topic.StartsWith(Options.TagWriteRequestCommandsTopicRoot, StringComparison.InvariantCultureIgnoreCase))
{
var command = _messageSerializer.DeserializeMessage<TagWriteRequestCommand>(e.ApplicationMessage.PayloadSegment.Array!);
if (command != null)
ConnectorInterface!.RequestTagWrite(command.DeviceId, command.TagId, command.StartOffset, command.Data);
}
return Task.CompletedTask;
}
private Task OnClientConnected(ClientConnectedEventArgs e)
{
ConnectorInterface!.OnConnectorConnected(new ConnectorConnectedEventArgs(this, $"ClientId {e.ClientId} connected to port {Options.ServerPort}"));
return Task.CompletedTask;
}
private Task OnClientDisconnected(ClientDisconnectedEventArgs e)
{
ConnectorInterface!.OnConnectorDisconnected(new ConnectorDisconnectedEventArgs(this, $"ClientId {e.ClientId} disconnected: {e.DisconnectType}"));
return Task.CompletedTask;
}
protected override async Task PublishExceptionAsync(Exception exception)
{
if (_started)
{
try
{
await _mqttServer.InjectApplicationMessage(new InjectedMqttApplicationMessage(
new MqttApplicationMessageBuilder()
.WithTopic(Options.ExceptionsTopicPattern)
.WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
.WithPayload(_messageSerializer.SerializeMessage(EventExtensions.ToEventMessage(exception)))
.Build())
);
}
catch (Exception ex)
{
OnException(ex);
}
}
}
protected override async Task PublishDeviceStatusEventAsync(DeviceStatusEvent e)
{
if (_started)
{
try
{
await _mqttServer.InjectApplicationMessage(new InjectedMqttApplicationMessage(
new MqttApplicationMessageBuilder()
.WithTopic(Options.GetDeviceStatusEventsTopic(e.Device.DeviceId))
.WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
.WithPayload(_messageSerializer.SerializeMessage(EventExtensions.ToEventMessage(e)))
.Build())
);
}
catch (Exception ex)
{
OnException(ex);
}
}
}
protected override async Task PublishTagScheduleEventAsync(TagScheduleEvent e)
{
await PublishTagScheduleEvent(e, false);
}
private async Task PublishTagScheduleEvent(TagScheduleEvent e, bool isInitializationData)
{
if (_started)
{
var evt = !Options.IsPublishPartialReads && e.Data != null ? TagScheduleEvent.BuildTagData(e.Device, e.Tag, e.IsErrorNumberChanged) : e;
var message = evt.ToEventMessage(isInitializationData);
try
{
await _mqttServer.InjectApplicationMessage(new InjectedMqttApplicationMessage(
new MqttApplicationMessageBuilder()
.WithTopic(Options.GetTagScheduleEventsTopic(e.Device.DeviceId, e.Tag.TagId))
.WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
.WithPayload(_messageSerializer.SerializeMessage(message))
.Build())
);
}
catch (Exception ex)
{
OnException(ex);
}
}
}
private async Task InvokeInitializationDelegateAsync(bool publishDeviceStatusEvents, bool publishTagScheduleEvents)
{
await ConnectorInterface!.RunInitializationActionAsync(
initAction: async (deviceEvents, tagEvents) =>
{
if (publishDeviceStatusEvents)
{
foreach (var deviceEvent in deviceEvents)
{
await PublishDeviceStatusEventAsync(deviceEvent);
}
}
if (publishTagScheduleEvents)
{
foreach (var tagEvent in tagEvents)
{
await PublishTagScheduleEvent(tagEvent, true);
}
}
});
}
private void OnException(Exception ex)
{
try
{
ConnectorInterface!.OnConnectorException(new ConnectorExceptionEventArgs(this, ex));
}
catch
{
// ignoring this
}
}
}