-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataCollector.cs
244 lines (212 loc) · 8.07 KB
/
DataCollector.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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace datacollectionserver
{
public class DataCollector
{
public enum SampleType
{
SampleTypeShort,
SampleTypeFloat
}
public enum ConnectionState
{
Iddle,
Connected,
WaitingData,
CollectingData,
Error
};
public delegate void OnNewConnectionStateEventHandler(ConnectionState state, string lastError);
public event OnNewConnectionStateEventHandler? OnNewConnectionState;
public delegate void OnNewPacketEventHandler(byte[] packet, int samplesPerPacket, SampleType sampleType);
public event OnNewPacketEventHandler? OnNewPacket;
public delegate void OnNewRecordingEventHandler(List<byte[]> recording, int samplesPerPacket, SampleType sampleType);
public event OnNewRecordingEventHandler? OnNewRecording;
private SampleType sampleType = SampleType.SampleTypeShort;
private int samplesPerPacket = 1;
private SerialPort? port = null;
private BackgroundWorker? worker = null;
private const int WORKER_PROGRESS_NEW_PACKET = 0;
private const int WORKER_PROGRESS_NEW_RECORDING = 1;
private const int WORKER_PROGRESS_NEW_STATUS = 2;
/// <summary>
/// Defines how much packets need to be dropped at start (to avoid to "hear" the button click)
/// </summary>
private const int packetsAtStartToDrop = 5;
public static int GetElementSizeByType(SampleType sampleType)
{
switch(sampleType)
{
case SampleType.SampleTypeShort:
return 2;
case SampleType.SampleTypeFloat:
return 4;
}
return 2;
}
public void StartCollecting(string portName, int baudRate, SampleType sampleType, int samplesPerPacket)
{
this.sampleType = sampleType;
this.samplesPerPacket = samplesPerPacket;
try
{
port = new SerialPort
{
BaudRate = baudRate,
DataBits = 8,
Handshake = Handshake.None,
Parity = Parity.None,
PortName = portName,
StopBits = StopBits.One,
ReadTimeout = 500,
WriteTimeout = 2000
};
port.Open();
}
catch(Exception ex)
{
OnNewConnectionState?.Invoke(ConnectionState.Error, ex.ToString());
return;
}
OnNewConnectionState?.Invoke(ConnectionState.Connected, string.Empty);
CreateAndStartBackgroundWorker();
}
public void Stop()
{
if (worker != null) worker.CancelAsync();
}
private void CreateAndStartBackgroundWorker()
{
if (worker != null)
{
worker.CancelAsync();
}
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.ProgressChanged += Worker_ProgressChanged;
worker.DoWork += Worker_DoWork;
worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
worker.RunWorkerAsync();
}
private void Worker_RunWorkerCompleted(object? sender, RunWorkerCompletedEventArgs e)
{
OnNewConnectionState?.Invoke(ConnectionState.Iddle, string.Empty);
}
private void Worker_DoWork(object? sender, DoWorkEventArgs e)
{
if (sender == null) return;
if (port == null) return;
BackgroundWorker worker = (BackgroundWorker)sender;
int elementSizeByte = GetElementSizeByType(sampleType);
int packetSize = elementSizeByte * samplesPerPacket;
for (; ; )
{
if (worker.CancellationPending)
{
try
{
port.Close();
}
catch (Exception) { }
return;
}
// Flush
try
{
port.ReadExisting();
}
catch (Exception) { }
long lastReadPacketTimestamp = 0;
int remainingToDrop = packetsAtStartToDrop;
List<byte[]> recording = new List<byte[]>();
worker.ReportProgress(WORKER_PROGRESS_NEW_STATUS, ConnectionState.WaitingData);
for (; ; )
{
if (worker.CancellationPending)
{
try
{
port.Close();
}
catch (Exception) { }
return;
}
// Wait for enough data
if (port.BytesToRead >= packetSize)
{
if (lastReadPacketTimestamp == 0)
{
worker.ReportProgress(WORKER_PROGRESS_NEW_STATUS, ConnectionState.CollectingData);
}
byte[] readBuffer = new byte[packetSize];
int toRead = packetSize;
int offset = 0;
// Get the answer
while (toRead > 0)
{
int r = port.Read(readBuffer, offset, toRead);
offset += r;
toRead -= r;
}
if (remainingToDrop == 0)
{
worker.ReportProgress(WORKER_PROGRESS_NEW_PACKET, readBuffer);
recording.Add(readBuffer);
}
else
{
remainingToDrop--;
}
lastReadPacketTimestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
}
else if (lastReadPacketTimestamp != 0)
{
long timeDiff = DateTimeOffset.Now.ToUnixTimeMilliseconds() - lastReadPacketTimestamp;
if (timeDiff > 500)
{
worker.ReportProgress(WORKER_PROGRESS_NEW_RECORDING, recording);
break;
}
Thread.Sleep(100);
}
}
}
}
private void Worker_ProgressChanged(object? sender, ProgressChangedEventArgs e)
{
switch(e.ProgressPercentage)
{
case WORKER_PROGRESS_NEW_PACKET:
if (e.UserState != null)
{
byte[] values = (byte[])e.UserState;
OnNewPacket?.Invoke(values, samplesPerPacket, sampleType);
}
break;
case WORKER_PROGRESS_NEW_RECORDING:
if (e.UserState != null)
{
List<byte[]> recording = (List<byte[]>)e.UserState;
OnNewRecording?.Invoke(recording, samplesPerPacket, sampleType);
}
break;
case WORKER_PROGRESS_NEW_STATUS:
if (e.UserState != null)
{
ConnectionState state = (ConnectionState)e.UserState;
OnNewConnectionState?.Invoke(state, string.Empty);
}
break;
}
}
}
}