-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFramedSerialLink.cs
More file actions
253 lines (222 loc) · 8.89 KB
/
FramedSerialLink.cs
File metadata and controls
253 lines (222 loc) · 8.89 KB
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
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Text;
using ThreeByte.LinkLib.Shared.Logging;
namespace ThreeByte.LinkLib.SerialLink
{
public class FramedSerialLink
{
public event EventHandler<Exception>? ErrorOccurred;
public event EventHandler? DataReceived;
public SerialFrame? SendFrame { get; set; }
public SerialFrame? ReceiveFrame { get; set; }
public bool IsConnected => _serialLink.IsConnected;
public bool IsEnabled => _serialLink.IsEnabled;
public bool HasData => _incomingData.Count > 0;
private const int MaxDataSize = 100;
private bool _isDisposed = false;
private int _headerPos = 0;
private int _footerPos = 0;
private List<string> _incomingData = new List<string>();
private MemoryStream _incomingBuffer = new MemoryStream(2048);
private readonly SerialLink _serialLink;
private readonly ILogger _logger;
public FramedSerialLink(string comPort, int baudRate = 9600, int dataBits = 8, Parity parity = Parity.None, bool enabled = true)
: this(new SerialLinkSettings(comPort, baudRate, dataBits, parity), enabled)
{
}
public FramedSerialLink(SerialLinkSettings settings, bool enabled = true)
{
_serialLink = new SerialLink(settings, enabled);
_serialLink.DataReceived += OnDataReceived;
_serialLink.ErrorOccurred += OnErrorOccurred;
_logger = LogFactory.Create<FramedSerialLink>();
}
public void SetEnabled(bool value)
{
_serialLink.SetEnabled(value);
if (!value)
{
//If the link is disabled, clear the buffer of messages
lock (_incomingData)
{
_incomingData.Clear();
}
}
}
/// <summary>
/// Asynchronously sends the tcp message, waiting until the connection is reestablihsed if necessary
/// </summary>
/// <param name="message"></param>
public void SendMessage(string message)
{
if (_isDisposed)
{
throw new ObjectDisposedException("Cannot get message from disposed FramedSerialLink.");
}
//Don't do anything if the link is not enabled
if (!IsEnabled)
{
return;
}
//Add the header and footer
byte[] header = new byte[0];
if (SendFrame != null && SendFrame.Header != null)
{
header = SendFrame.Header;
}
byte[] footer = new byte[0];
if (SendFrame != null && SendFrame.Footer != null)
{
footer = SendFrame.Footer;
}
byte[] messageBytes = new byte[message.Length + header.Length + footer.Length];
header.CopyTo(messageBytes, 0);
Encoding.UTF8.GetBytes(message, 0, message.Length, messageBytes, header.Length);
footer.CopyTo(messageBytes, message.Length + header.Length);
if (_serialLink != null)
{
try
{
_serialLink.SendData(messageBytes);
}
catch (ObjectDisposedException ode)
{
HandleError(ode, "Cannot send a message of disposed FramedSerialLink.");
}
catch (Exception ex)
{
//Also possible for the serial link to raise and UnauthorizedAccessException here
HandleError(ex, "SendMessage error.");
}
}
}
/// <summary>
/// Fetches and removes (pops) the next available message as received on this link in order (FIFO)
/// </summary>
/// <returns>null if the link is not Enabled or there are no messages currently queued to return, a string otherwise.</returns>
public string? GetMessage()
{
if (_isDisposed)
{
throw new ObjectDisposedException("Cannot get message from disposed FramedSerialLink.");
}
//Don't do anything if the link is not enabled
if (!IsEnabled)
{
return null;
}
string? newMessage = null;
lock (_incomingData)
{
if (HasData)
{
newMessage = _incomingData[0];
_incomingData.RemoveAt(0);
}
}
return newMessage;
}
/// <summary>
/// Implementation of IDisposable interface. Cancels the thread and releases resources.
/// Clients of this class are responsible for calling it.
/// </summary>
public void Dispose()
{
if (_isDisposed)
{
return;
}
_isDisposed = true;
_logger.LogInformation("Cleaning up serial resources.");
_serialLink.DataReceived -= OnDataReceived;
_serialLink.ErrorOccurred -= OnErrorOccurred;
_serialLink.Dispose();
}
private void OnDataReceived(object? sender, EventArgs e)
{
bool hasNewData = false;
byte[] header = new byte[0];
if (ReceiveFrame != null && ReceiveFrame.Header != null)
{
header = ReceiveFrame.Header;
}
byte[] footer = new byte[0];
if (ReceiveFrame != null && ReceiveFrame.Footer != null)
{
footer = ReceiveFrame.Footer;
}
while (_serialLink.HasData)
{
lock (_incomingBuffer)
{
byte[]? buffer = _serialLink.GetMessage();
//Must validate this buffer - see issue #4934
if (buffer == null)
{
break;
}
for (int i = 0; i < buffer.Length; i++)
{
if (_headerPos < header.Length - 1 && buffer[i] == header[_headerPos])
{
_headerPos++;
}
else if (_headerPos == header.Length - 1 && buffer[i] == header[_headerPos])
{
_headerPos = 0;
_footerPos = 0;
_incomingBuffer.Position = 0; //Reset to the beginning
}
else if (_footerPos < footer.Length - 1 && buffer[i] == footer[_footerPos])
{
_footerPos++;
}
else if (_footerPos == footer.Length - 1 && buffer[i] == footer[_footerPos])
{
_footerPos = 0; //Reset Footer
string newMessage = Encoding.UTF8.GetString(_incomingBuffer.GetBuffer(), 0, (int)_incomingBuffer.Position);
if (newMessage.Trim() != string.Empty)
{
//log.Debug("Adding Message: " + newMessage.Substring(0, Math.Min(30, newMessage.Length)));
lock (_incomingData)
{
_incomingData.Add(newMessage);
if (_incomingData.Count > MaxDataSize)
{
//Purge messages from the end of the list to prevent overflow
_logger.LogError("Too many incoming messages to handle: {qty}", _incomingData.Count);
_incomingData.RemoveAt(_incomingData.Count - 1);
}
}
}
hasNewData = true;
_incomingBuffer.Position = 0;
}
else
{
_headerPos = 0;
_incomingBuffer.WriteByte(buffer[i]);
}
}
}
}
if (hasNewData && DataReceived != null && !_isDisposed)
{
DataReceived(this, new EventArgs());
}
}
private void OnErrorOccurred(object? sender, Exception ex)
{
ErrorOccurred?.Invoke(sender, ex);
}
private void HandleError(Exception ex, string message)
{
_logger.LogError(exception: ex, message: message);
ErrorOccurred?.Invoke(this, ex);
}
}
}