forked from TRU-E-Bike-Project/bg96sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathATCommandClient.cs
More file actions
278 lines (238 loc) · 10.5 KB
/
ATCommandClient.cs
File metadata and controls
278 lines (238 loc) · 10.5 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
using Microsoft.Extensions.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BG96Sharp
{
public class ATCommandClient : IATCommandClient
{
protected string _serialPort;
public SerialPort BaseSerialPort { get; protected set; }
public bool IsConnected => BaseSerialPort.IsOpen;
internal LinkedList<TaskCompletionSource<CommandResult>> AtCommandResultQueue = new LinkedList<TaskCompletionSource<CommandResult>>();
internal List<KeyValuePair<string, TaskCompletionSource<string>>> AtCommandResponseResultQueue = new List<KeyValuePair<string, TaskCompletionSource<string>>>();
private readonly object _serialLock = new object();
internal TaskCompletionSource<bool> CurrentBinaryWriteTask = null;
public bool ATResultPresentationCodeMode { get; set; } = false;
public bool EchoModeOn { get; set; } = true;
public char LineTerminationCharacter { get; set; } = (char) 0x0D; //CR
public char ResponseFormattingCharacter { get; set; } = (char) 0x0A; //LF
public event EventHandler CommandLineReceived;
private bool RequestCancel { get; set; } = false;
private ILogger logger;
private Thread _atListenThread;
public ATCommandClient(string serialPort, ILogger logger)
{
_serialPort = serialPort;
this.logger = logger;
}
public void CloseSerialPort()
{
BaseSerialPort.Close();
}
public void OpenSerialPort()
{
_atListenThread = new Thread(ReadDataLoop);
BaseSerialPort.Open();
BaseSerialPort.Encoding = Encoding.UTF8; //technically, this should be GSM but whatever
_atListenThread.Start();
}
private void ReadDataLoop()
{
while (!RequestCancel)
{
var s = new StringBuilder();
var binaryWriteSignal = false;
while (true)
{
if (RequestCancel) return;
var c = BaseSerialPort.ReadByte(); //this will block the thread until it reads something.
if (c > char.MaxValue)
{
logger.LogError("Read character from serial port that exceeded max char value!");
continue;
}
if (c < 0 )
break; //means we couldn't read
if (c == '>') //we hit an input thing, need to signal to start writing.
{
logger.LogInformation("Received binary start symbol");
binaryWriteSignal = true;
break;
}
if (c == ResponseFormattingCharacter)
break;
s.Append((char)c);
}
if (binaryWriteSignal)
{
//TODO: start signal
if (CurrentBinaryWriteTask == null)
{
logger.LogWarning("Received binary write indicator but no binary write task existed!");
//throw new Exception("Binary write task was null but received start character!");
continue;
}
CurrentBinaryWriteTask.SetResult(true);
continue;
}
logger.LogInformation("Received serial line: " + s.ToString().Replace("\n", "<LN>").Replace("\r", "<CR>"));
var line = s.ToString().Trim();
if (string.IsNullOrEmpty(line))
continue;
if (line.StartsWith("AT+")) continue; //means that we are receiving what we sent (echo)
if (line == "OK" || line == "ERROR")
{
if (CurrentBinaryWriteTask != null)
{
CurrentBinaryWriteTask.SetResult(false);
}
else
{
try
{
AtCommandResultQueue.First.Value.SetResult(new CommandResult(line switch
{
"OK" => ATCommandResultCode.OK,
"ERROR" => ATCommandResultCode.Error
}));
}
catch (Exception ex)
{
logger.LogCritical("Error setting AtCommandResult value: " + ex.Message + "\n" + ex.StackTrace);
throw ex;
}
AtCommandResultQueue.RemoveFirst();
}
}
else if (line.StartsWith("+"))
{
CommandLineReceived?.Invoke(this, new CommandLineReceivedEventArgs(line));
if (line.StartsWith("+QMTRECV"))
{
logger.LogInformation("Received MQTT message.");
//we got an MQTT message
}
else if (line.StartsWith("+CME ERROR"))
{
logger.LogWarning("Received CME error: " + line);
//just grab the first mofo I guess? I mean, hopefully they don't sit in the queue long enough... Especially if they have a CME error.
//if (_atCommandResponseResultQueue.Count > 0)
// _atCommandResponseResultQueue.First().Value.SetResult(line);
AtCommandResultQueue.First.Value.SetResult(new CommandResult(true, line));
AtCommandResultQueue.RemoveFirst();
}
else
{
var firstItem = AtCommandResponseResultQueue.FirstOrDefault(x => line.StartsWith(x.Key));
if (!string.IsNullOrEmpty(firstItem.Key))
{
var removedItem =
AtCommandResponseResultQueue.Remove(firstItem);
firstItem.Value.SetResult(line);
}
}
}
else
{
logger.LogWarning("Received line but was not a response code nor a command response: \"" + line + "\"");
}
}
}
internal void WriteLine(string command)
{
lock (_serialLock)
{
BaseSerialPort.Write(command + LineTerminationCharacter);
}
}
public Task<CommandResult> SendATCommandAsync(string command)
{
WriteLine(command);
var completionSource = new TaskCompletionSource<CommandResult>(TaskCreationOptions.RunContinuationsAsynchronously);
AtCommandResultQueue.AddLast(completionSource);
return completionSource.Task;
}
public Task<CommandResult> SendATCommandAsync(IATCommand command)
{
if (command.HasReply)
throw new Exception("Wrong method called! You should be doing something with the result!");
return SendATCommandAsync(command.Command);
}
public async Task<(CommandResult Result, string Response)> SendATCommandAsync(IATCommandWithReply command)
{
var commandResultTaskCompletionSource = new TaskCompletionSource<CommandResult>(TaskCreationOptions.RunContinuationsAsynchronously);
AtCommandResultQueue.AddLast(commandResultTaskCompletionSource);
var commandResponseResultTaskCompletionSource = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var queueItem = new KeyValuePair<string, TaskCompletionSource<string>>(command.DesiredReply,
commandResponseResultTaskCompletionSource);
AtCommandResponseResultQueue.Add(queueItem);
lock (_serialLock)
{
BaseSerialPort.Write(command.Command + LineTerminationCharacter);
}
var resultCommandResult = await commandResultTaskCompletionSource.Task;
if (resultCommandResult.WasCMEError)
{
AtCommandResponseResultQueue.Remove(queueItem); //clean up, since we got ourselves an error
return (commandResultTaskCompletionSource.Task.Result, resultCommandResult.CMEError);
}
await commandResponseResultTaskCompletionSource.Task;
return (commandResultTaskCompletionSource.Task.Result, commandResponseResultTaskCompletionSource.Task.Result);
}
}
public class CommandLineReceivedEventArgs : EventArgs
{
public CommandLineReceivedEventArgs(string commandLine)
{
CommandLine = commandLine;
}
public string CommandLine { get; }
}
public class CommandResult
{
public CommandResult(bool wasCmeError, string cmeError)
{
WasCMEError = wasCmeError;
CMEError = cmeError;
}
public CommandResult(ATCommandResultCode result)
{
WasCMEError = false;
Result = result;
}
public void ThrowIfError()
{
if (WasCMEError)
throw new CmeErrorException(CMEError);
if (Result != ATCommandResultCode.OK)
throw new ATCommandResultCodeException(Result);
}
public bool WasCMEError { get; }
public string CMEError { get; }
public ATCommandResultCode Result { get; private set; } = ATCommandResultCode.Unknown;
}
public class CellularBandInfoCommandResult : CommandResult
{
public CellularBandInfoCommandResult(ATCommandResultCode result) : base(result)
{
}
public CellularBandInfoCommandResult(bool wasCmeError, string cmeError) : base(wasCmeError, cmeError)
{
}
public CellularBandInfoCommandResult(ATCommandResultCode resultCode, GSMBand gsmBand, LTEBand catm1Band, LTEBand nmIotBand) : this(resultCode)
{
GsmBand = gsmBand;
Catm1Band = catm1Band;
NmIotBand = nmIotBand;
}
public GSMBand GsmBand { get; }
public LTEBand Catm1Band { get; }
public LTEBand NmIotBand { get; }
}
}