-
Notifications
You must be signed in to change notification settings - Fork 20
/
AtChannel.cs
372 lines (331 loc) · 12.8 KB
/
AtChannel.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
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace HeboTech.ATLib.Parsers
{
public class AtChannel : IAtChannel, IDisposable
{
private static readonly string[] FinalResponseErrors = new string[]
{
"ERROR",
"+CMS ERROR:",
"+CME ERROR:",
"NO CARRIER",
"NO ANSWER",
"NO DIALTONE"
};
private static readonly string[] FinalResponseSuccesses = new string[]
{
"OK",
"CONNECT"
};
private static readonly string[] SmsUnsoliciteds = new string[]
{
"+CMT:",
"+CDS:",
"+CBM:"
};
public event EventHandler<UnsolicitedEventArgs> UnsolicitedEvent;
private bool debugEnabled;
private Action<string> debugAction;
private bool isDisposed;
private IAtReader atReader;
private IAtWriter atWriter;
private CancellationTokenSource cancellationTokenSource;
private Task readerTask;
private SemaphoreSlim waitingForCommandResponse;
private AtCommand currentCommand;
private AtResponse currentResponse;
public AtChannel(IAtReader atReader, IAtWriter atWriter)
{
this.atReader = atReader;
this.atWriter = atWriter;
cancellationTokenSource = new CancellationTokenSource();
waitingForCommandResponse = new SemaphoreSlim(0, 1);
}
public TimeSpan DefaultCommandTimeout { get; set; } = TimeSpan.FromSeconds(5);
public void Open()
{
atReader.Open();
readerTask = Task.Factory.StartNew(() => ReaderLoopAsync(cancellationTokenSource.Token), TaskCreationOptions.LongRunning);
}
public void Close()
{
Dispose();
}
public bool IsDebugEnabled()
{
return debugEnabled;
}
public void EnableDebug(Action<string> debugAction)
{
this.debugAction = debugAction ?? throw new ArgumentNullException(nameof(debugAction));
debugEnabled = true;
}
public void DisableDebug()
{
debugEnabled = false;
debugAction = default;
}
/// <summary>
/// Clears all available items
/// </summary>
/// <returns></returns>
public async Task ClearAsync(CancellationToken cancellationToken = default)
{
for (int i = 0; i < atReader.AvailableItems(); i++)
{
await atReader.ReadAsync(cancellationToken);
}
}
/// <summary>
/// Send command and get command status
/// </summary>
/// <param name="command"></param>
/// <param name="response"></param>
/// <returns></returns>
public virtual Task<AtResponse> SendCommand(string command, TimeSpan? timeout = null)
{
return SendFullCommandAsync(new AtCommand(AtCommandType.NO_RESULT, command, null, null, timeout ?? DefaultCommandTimeout));
}
public virtual async Task<AtResponse> SendSingleLineCommandAsync(string command, string responsePrefix, TimeSpan? timeout = null)
{
AtResponse response = await SendFullCommandAsync(new AtCommand(AtCommandType.SINGELLINE, command, responsePrefix, null, timeout ?? DefaultCommandTimeout));
if (response != null && response.Success && !response.Intermediates.Any())
{
// Successful command must have an intermediate response
throw new InvalidResponseException("Did not get an intermediate response");
}
return response;
}
public virtual Task<AtResponse> SendMultilineCommand(string command, string responsePrefix, TimeSpan? timeout = null)
{
AtCommandType commandType = responsePrefix == null ? AtCommandType.MULTILINE_NO_PREFIX : AtCommandType.MULTILINE;
return SendFullCommandAsync(new AtCommand(commandType, command, responsePrefix, null, timeout ?? DefaultCommandTimeout));
}
public virtual async Task<AtResponse> SendSmsAsync(string command, string pdu, string responsePrefix, TimeSpan? timeout = null)
{
AtResponse response = await SendFullCommandAsync(new AtCommand(AtCommandType.SINGELLINE, command, responsePrefix, pdu, timeout ?? DefaultCommandTimeout));
if (response != null && response.Success && !response.Intermediates.Any())
{
// Successful command must have an intermediate response
throw new InvalidResponseException("Did not get an intermediate response");
}
return response;
}
/// <summary>
/// Not re-entrant
/// </summary>
/// <param name="command"></param>
/// <param name="commandType"></param>
/// <param name="responsePrefix"></param>
/// <param name="smsPdu"></param>
/// <param name="timeout"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<AtResponse> SendFullCommandAsync(AtCommand command, CancellationToken cancellationToken = default)
{
try
{
this.currentCommand = command;
this.currentResponse = new AtResponse();
if (debugEnabled)
debugAction($"Out: {command.Command}");
await atWriter.WriteLineAsync(command.Command);
if (!await waitingForCommandResponse.WaitAsync(command.Timeout, cancellationToken))
throw new TimeoutException("Timed out while waiting for command response");
return currentResponse;
}
finally
{
this.currentCommand = default;
this.currentResponse = default;
}
}
private async Task ReaderLoopAsync(CancellationToken cancellationToken = default)
{
while (!cancellationToken.IsCancellationRequested)
{
string line1;
try
{
line1 = await atReader.ReadAsync(cancellationToken);
if (debugEnabled)
debugAction($"In: {line1}");
}
catch (OperationCanceledException)
{
break;
}
if (line1 == null)
break;
if (line1 == string.Empty)
continue;
if (IsSMSUnsolicited(line1))
{
string line2;
try
{
line2 = await atReader.ReadAsync(cancellationToken);
if (debugEnabled)
debugAction($"In: {line2}");
}
catch (OperationCanceledException)
{
break;
}
if (line2 == null)
break;
HandleUnsolicited(line1, line2);
}
else
ProcessMessage(line1);
}
}
private void ProcessMessage(string line)
{
if (currentResponse == null)
{
HandleUnsolicited(line);
}
else if (IsFinalResponseSuccess(line))
{
currentResponse.Success = true;
HandleFinalResponse(line);
}
else if (IsFinalResponseError(line))
{
currentResponse.Success = false;
HandleFinalResponse(line);
}
else if (currentCommand.SmsPdu != null && line == "> ")
{
// See eg. TS 27.005 4.3
// Commands like AT+CMGS have a "> " prompt
if (debugEnabled)
debugAction($"Out: {currentCommand.SmsPdu}");
atWriter.WriteSmsPduAndCtrlZAsync(currentCommand.SmsPdu);
currentCommand.SmsPdu = null;
}
else
{
switch (currentCommand.CommandType)
{
case AtCommandType.NO_RESULT:
HandleUnsolicited(line);
break;
case AtCommandType.NUMERIC:
if (!currentResponse.Intermediates.Any() && char.IsDigit(line[0]))
{
AddIntermediate(line);
}
else
{
// Either we already have an intermediate response or the line doesn't begin with a digit
HandleUnsolicited(line);
}
break;
case AtCommandType.SINGELLINE:
if (!currentResponse.Intermediates.Any() && line.StartsWith(currentCommand.ResponsePrefix))
{
AddIntermediate(line);
}
else
{
// We already have an intermediate response
HandleUnsolicited(line);
}
break;
case AtCommandType.MULTILINE:
if (line.StartsWith(currentCommand.ResponsePrefix))
{
AddIntermediate(line);
}
else
{
HandleUnsolicited(line);
}
break;
case AtCommandType.MULTILINE_NO_PREFIX:
AddIntermediate(line);
break;
default:
// This should never be reached
//TODO: Log error or something
HandleUnsolicited(line);
break;
}
}
}
private void AddIntermediate(string line)
{
currentResponse.Intermediates.Add(line);
}
private void HandleFinalResponse(string line)
{
currentResponse.FinalResponse = line;
waitingForCommandResponse.Release();
}
private void HandleUnsolicited(string line1, string line2 = null)
{
UnsolicitedEvent?.Invoke(this, new UnsolicitedEventArgs(line1, line2));
}
private static bool IsFinalResponseSuccess(string line)
{
return FinalResponseSuccesses.Any(response => line.StartsWith(response));
}
private static bool IsFinalResponseError(string line)
{
return FinalResponseErrors.Any(response => line.StartsWith(response));
}
private static bool IsSMSUnsolicited(string line)
{
return SmsUnsoliciteds.Any(response => line.StartsWith(response));
}
public static AtChannel Create(Stream stream)
{
return new AtChannel(new AtReader(stream), new AtWriter(stream));
}
public static AtChannel Create(Stream inputStream, Stream outputStream)
{
return new AtChannel(new AtReader(inputStream), new AtWriter(outputStream));
}
#region Dispose
protected virtual void Dispose(bool disposing)
{
if (!isDisposed)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
cancellationTokenSource.Cancel();
readerTask?.Wait();
readerTask?.Dispose();
readerTask = null;
atReader.Close();
atWriter.Close();
waitingForCommandResponse.Dispose();
waitingForCommandResponse = null;
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
isDisposed = true;
}
}
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
// ~AtChannel()
// {
// // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
// Dispose(disposing: false);
// }
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
#endregion
}
}