-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSerialParser.cs
More file actions
226 lines (198 loc) · 6.19 KB
/
SerialParser.cs
File metadata and controls
226 lines (198 loc) · 6.19 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text.RegularExpressions;
public class SerialParser
{
private const long k_ticks_per_us = 10; // Tick is 100ns
private const int k_max_buff_size = 1024;
private const int k_max_queue_size = 256;
private SerialPort _sp;
private List<byte> _match;
private List<byte> _buff;
private DateTime _last_activity_dt;
private long _timeout_us;
private Queue<Buffer> _fifo;
private int _port;
/// <summary>
/// Constructor
/// </summary>
/// <param name="match"></param>
/// <param name="timeout_us"></param>
/// <param name="fifo"></param>
public SerialParser (List<byte> match, long timeout_us, Queue<Buffer> fifo)
{
// Assign private vars
if (match == null)
{
_match = new List<byte>();
}
else
{
_match = match;
}
_timeout_us = timeout_us;
_fifo = fifo;
_buff = new List<byte>();
}
/// <summary>
/// Open serial port
/// </summary>
/// <param name="port"></param>
/// <param name="baudrate"></param>
/// <returns></returns>
public bool Open(String port, int baudrate)
{
// Open serial port
Console.Write("Opening Serial Port " + port + " ..");
try
{
_sp = new SerialPort(port, baudrate, Parity.None, 8, StopBits.One);
_sp.Parity = Parity.None;
_sp.StopBits = StopBits.One;
_sp.DataBits = 8;
_sp.Handshake = Handshake.None;
_sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// Reset timeout
_last_activity_dt = HightResTime.NowUTC().ToLocalTime();
// Open port
_sp.Open();
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine("Exception opening serial port " + port + " : " + ex.Message);
return false;
}
Console.WriteLine(". Ok");
// DEBUG
//byte[] b = { 0x05, 0x64, 0x08, 0xc4, 0x37, 0x00, 0x0a, 0x00, 0x3f, 0xd2, 0xc0, 0xca, 0x17, 0xb3, 0xd3};
//PostToFIFO(new List<byte>(b));
//_buff.Clear();
// Figure out com port number
Match m = Regex.Match(_sp.PortName, @"\d+");
if (m.Length <= 0 || !int.TryParse(m.Value, out _port))
{
// Can't parse it, assign defult port
_port = 999;
}
return true;
}
/// <summary>
/// Close serial port
/// </summary>
public void Close()
{
_sp.Close();
}
/// <summary>
/// Call this function periodically to flush packet on timeout
/// </summary>
public void Run()
{
// TODO: Add locking?
// Check for timeout
if (((DateTime.Now - _last_activity_dt).Ticks / k_ticks_per_us) > _timeout_us)
{
// Timeout!
_last_activity_dt = HightResTime.NowUTC().ToLocalTime();
PostToFIFO(_buff);
}
}
// ============================================================
// Private functions
// ============================================================
/// <summary>
/// Serial port receive data interrupt
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// Check for timeout
if ( ((DateTime.Now - _last_activity_dt).Ticks / k_ticks_per_us) > _timeout_us)
{
_last_activity_dt = HightResTime.NowUTC().ToLocalTime();
// Timeout!
PostToFIFO(_buff);
}
while (_sp.BytesToRead > 0)
{
// Got something
// Add to buffer
_last_activity_dt = HightResTime.NowUTC().ToLocalTime();
byte b = (byte)_sp.ReadByte();
_buff.Add(b);
// Does it match the pattern?
if (_match.Count > 0 && _buff.Count > _match.Count)
{
bool match_found = true;
int start = _buff.IndexOf(_match[0]);
if (start >= 0 && _buff.Count >= (start + _match.Count))
{
for (int i = 0; i < _match.Count; i++)
{
if (_buff[start + i] != _match[i])
{
match_found = false;
break;
}
}
}
else
{
match_found = false;
}
// Found match?
if (match_found)
{
List<byte> lst = _buff.GetRange(0, start);
PostToFIFO(lst);
_buff.RemoveRange(0, start);
}
}
// Overfilling buffer?
if (_buff.Count > k_max_buff_size)
{
PostToFIFO(_buff);
}
}
}
/// <summary>
/// Post buffer to FIFO
/// </summary>
/// <param name="lst"></param>
/// <param name="timestamp_us"></param>
private void PostToFIFO (List<byte> lst)
{
if(lst.Count <= 0)
{
return;
}
// Create new buffer
Buffer bf = new Buffer(lst);
bf.timestamp_dt = HightResTime.NowUTC().ToLocalTime();
bf.PortNumber = _port;
// Be sure we are not overfilling queue
if (_fifo.Count <= k_max_queue_size)
{
PrintArray(bf.byte_buff);
_fifo.Enqueue(bf);
lst.Clear();
}
}
/// <summary>
/// Print array to the console
/// </summary>
/// <param name="lst"></param>
private void PrintArray(List<byte> lst)
{
Console.Write(String.Format("Port {0}; Len {1}; Message: ", _sp.PortName, lst.Count));
for (int i = 0; i < lst.Count; i++)
{
Console.Write(String.Format("{0,2:X} ", lst[i]));
}
Console.WriteLine();
}
}