-
Notifications
You must be signed in to change notification settings - Fork 0
/
Serial.cs
241 lines (207 loc) · 7.42 KB
/
Serial.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
namespace rt4k_pi;
using System.Text;
// This is all terrible and can be massively improved.
// TODO: Implement a max size for the write queue, we don't want to queue up an entire big file in one go.
public class Serial
{
public bool IsConnected { get; private set; }
private FileStream port = new("/dev/null", FileMode.Open);
private readonly HashSet<Action<byte[]>> readers = [];
private readonly Encoding encoding = Encoding.ASCII;
private readonly CancellationTokenSource cts = new();
private readonly Queue<byte[]> writeQueue = new();
private TaskCompletionSource writeCompletion = new();
private int writeQueueLength = 0;
private bool fileModeRequested = false;
private bool fileModeActive = false;
private readonly int maxQueueLength = 8 * 1024 * 1024; // 8MB write buffer
public Serial(int baudRate)
{
Task.Run(async () =>
{
if (GetPort() == null)
{
Console.WriteLine("Serial port does not exist, waiting for connection.");
}
// TODO: These are async functions, do they even need a task?
var readTask = Task.Run(HandleRead, cts.Token);
var writeTask = Task.Run(HandleWrite, cts.Token);
while (!cts.Token.IsCancellationRequested)
{
try
{
if (IsConnected && !File.Exists(port.Name))
{
throw new IOException("Serial port disconnected");
}
else if (!IsConnected)
{
var currentPort = GetPort();
if (currentPort != null)
{
Console.WriteLine($"Detected serial port at {currentPort}");
Console.WriteLine($"Connecting to {currentPort}");
ConfigurePort(currentPort, baudRate);
port = new FileStream(currentPort, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
Console.WriteLine($"Connected to {currentPort}");
IsConnected = true;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Serial error: {ex.Message}");
IsConnected = false;
port.Dispose();
}
await Task.Delay(2000);
}
}, cts.Token);
}
~Serial()
{
cts.Cancel();
port.Close();
}
private static string? GetPort() => Directory.GetFiles("/dev", "ttyUSB*").FirstOrDefault();
private static void ConfigurePort(string portName, int baudRate) =>
Util.RunCommand("stty", $"-F {portName} {baudRate} cs8 -cstopb -parenb");
private async void HandleWrite()
{
while (!cts.IsCancellationRequested)
{
// Wait until we're notified there's data to write
await writeCompletion.Task.WaitAsync(cts.Token);
writeCompletion = new();
// Handle entering/exiting file mode
if (fileModeRequested && !fileModeActive)
{
fileModeActive = true;
}
else if (fileModeActive && !fileModeRequested)
{
fileModeActive = false;
}
while (IsConnected && !fileModeActive && writeQueue.Count > 0)
{
byte[] data = writeQueue.Dequeue();
writeQueueLength -= data.Length;
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.Write(encoding.GetString(data));
Console.ResetColor();
try
{
port.Write(data);
port.Flush(); // TODO: Do we need this flush here?
}
catch (Exception ex)
{
Console.WriteLine($"Serial error: {ex.Message}");
IsConnected = false;
port.Dispose();
}
}
}
}
private async void EnterFileMode()
{
// Request entering file mode and wake the write thread to acknowledge it
fileModeRequested = true;
writeCompletion.SetResult();
// Wait for file mode to activate
while (!fileModeActive)
{
await Task.Delay(1);
}
}
private async void ExitFileMode()
{
// Request exiting file mode and wake the write thread to acknowledge it
fileModeRequested = false;
writeCompletion.SetResult();
// Wait for file mode to deactivate
while (fileModeActive)
{
await Task.Delay(1);
}
}
private async void HandleRead()
{
Console.WriteLine("Starting serial read loop");
byte[] readBuf = new byte[4096];
while (!cts.Token.IsCancellationRequested)
{
if (IsConnected)
{
int read = 0;
try
{
// Blocks until there's data
read = port.Read(readBuf, 0, readBuf.Length);
}
catch (Exception ex)
{
Console.WriteLine($"Serial error: {ex.Message}");
IsConnected = false;
port.Dispose();
}
if (read > 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(encoding.GetString(readBuf, 0, read));
Console.ResetColor();
foreach (Action<byte[]> action in readers)
{
try
{
action(readBuf[0..read]);
}
catch (Exception ex)
{
Console.WriteLine($"Warning: error calling registered reader: {ex.Message}");
}
}
}
}
else
{
await Task.Delay(100);
}
}
}
public void RegisterReader(Action<byte[]> reader) => readers.Add(reader);
public void UnregisterReader(Action<byte[]> reader) => readers.Remove(reader);
public void WriteLine(string data)
{
this.Write(encoding.GetBytes(data + '\n'));
}
// TODO: If we're in file mode, offer a "read" function
public void Write(byte[] data)
{
if (IsConnected)
{
if (fileModeActive)
{
// If file mode is active, bypass the write queue and just let the stream handle the throttling
// TODO: Make this async
port.Write(data);
}
else
{
while (writeQueueLength >= maxQueueLength)
{
if (!IsConnected)
{
// If we lose the connection, just drop the data
return;
}
Thread.Sleep(1);
}
writeQueue.Enqueue(data);
writeQueueLength += data.Length;
// Wake up the write handler
writeCompletion.TrySetResult();
}
}
}
}