Repository navigation
Expand file tree
/
Copy pathConnection.cs
More file actions
459 lines (432 loc) · 17.1 KB
/
Copy pathConnection.cs
File metadata and controls
459 lines (432 loc) · 17.1 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
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Rfcomm;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
namespace Something
{
public class SomethingElse
{
private readonly Guid handsFreeId = new("0000111f-0000-1000-8000-00805f9b34fb");
private RfcommDeviceService deviceService;
private CancellationTokenSource cts;
private DataWriter writer;
private DataReader reader;
public async Task ConnectAsync(BluetoothDevice device)
{
RfcommDeviceServicesResult serviceResult = await device.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(handsFreeId));
deviceService = serviceResult.Services[0];
var serviceSocket = new StreamSocket();
await serviceSocket.ConnectAsync(
deviceService.ConnectionHostName,
deviceService.ConnectionServiceName,
Windows.Networking.Sockets.SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
writer = new DataWriter(serviceSocket.OutputStream);
reader = new DataReader(serviceSocket.InputStream);
cts = new CancellationTokenSource();
PhoneEventListener(reader, cts.Token);
await Negotiate();
}
private async Task Negotiate()
{
handsFreeSupportedFeatures = new BLUETOOTH_HF_SUPPORTED_FEATURES()
{
CLI_PRESENTATION_CAPABILITY = true,
CODEC_NEGOTIATION = true,
EC_AD_NR_FUNCTION = true,
ENHANCED_CALL_CONTROL = true,
ENHANCED_CALL_STATUS = true,
ENHANCED_VOICE_RECOGNITION_STATUS = true,
ESCO_S4_SETTINGS_SUPPORTED = true,
HANDS_FREE_INDICATORS = true,
REMOTE_VOLUME_CONTROL = true,
THREE_WAY_CALLING = true,
VOICE_RECOGNITION_ACTIVATION = true,
VOICE_RECOGNITION_TEXT = true
};
await SendCommandAsync("AT+BRSF=" + handsFreeSupportedFeatures.ToUInt());
if (gatewaySupportedFeatures.CODEC_NEGOTIATION)
{
//supported codecs phone.
await SendCommandAsync("AT+BAC=1,2");
}
//Getting audio gateway indicators.
await SendCommandAsync("AT+CIND=?");
//Getting indicators status.
await SendCommandAsync("AT+CIND?");
//Enabling indicators.
await SendCommandAsync("AT+CMER=3,0,0,1");
if (gatewaySupportedFeatures.THREE_WAY_CALLING)
{
//Getting 3-way calling capabilities.
await SendCommandAsync("AT+CHLD=?");
}
if (gatewaySupportedFeatures.HANDS_FREE_INDICATORS)
{
//Device supports hands free indicators.
await SendCommandAsync("AT+BIND=1,2");
//Getting hands free supported indicators.
await SendCommandAsync("AT+BIND=?");
//Getting hands free enabled indicators."
await SendCommandAsync("AT+BIND?");
}
}
private async Task SendCommandAsync(string command)
{
if (string.IsNullOrEmpty(command))
throw new ArgumentNullException(nameof(command));
writer.WriteString(command + "\r\n");
await writer.StoreAsync();
await Task.Delay(50);
}
private void PhoneEventListener(DataReader reader, CancellationToken token) => _ = Task.Run(async () =>
{
var receiver = new StringBuilder();
while (true)
{
// TODO: sometimes when something goes wrong, there's an empty message in the reader.
// when this happens the loop is always running as opposed to waiting on the line below.
// if this happens, we should detect it then clear out the bytes but it sucks and I hate it.
var buf = await reader.LoadAsync(1);
if (token.IsCancellationRequested)
return;
if (reader.UnconsumedBufferLength > 0)
{
// wait for a newline so we know it's the end of the message.
var s = reader.ReadString(1);
if (s.Equals("\n") || s.Equals("\r"))
{
try
{
// NOTE: This is not good.
PhoneEventHandler(receiver.ToString());
receiver.Clear();
}
catch (Exception ex) { _loggingService.Error(ex); }
}
else { receiver.Append(s); }
}
else { await Task.Delay(TimeSpan.FromSeconds(0)); }
}
}, token);
private async Task PhoneEventHandler(string message)
{
if (string.IsNullOrWhiteSpace(message))
return;
try
{
// build your parsing for the AT command and object.
var responseObject = CommandBuilder.BuildResponse(message);
_eventService.Publish(new HfpCommandResultEventMessage<IAttentionCommandResponse>()
{
Result = responseObject
});
}
catch (Exception ex) { _loggingService.Error(ex); }
if (message.Equals("OK"))
{
_loggingService.Info($"Waiting for next command.");
waiter.Set();
}
else if (message.Equals("ERROR"))
{
await SendCommandAsync("+CME ERROR");
waiter.Set();
}
// TODO: handling the respones to commands in this loop is bad.
// need to figure out how to wait for a response and return to the caller if wanted
// e.g.: var response = SendCommand("AT+BRSF:1"), where response could be "OK", "+BRSF:0", "ERROR" etc.
else if (message.StartsWith("+BRSF:"))
{
//Received +BRSF: command, responding with supported features.
if (uint.TryParse(message[6..], out var i))
gatewaySupportedFeatures.FromInt(i);
}
else if (message.StartsWith("+BCS:"))
{
//Received +BCS: command.
if (uint.TryParse(message[5..], out var i))
{
//Responding with 'AT+BCS={i}' command."
await SendCommandAsync("AT+BCS=" + i);
}
}
else if (message.StartsWith("+CLIP"))
{
//Sending AT+CLCC command.
await SendCommandAsync("AT+CLCC");
}
}
}
/// <summary>
/// Represents a 32-bit unsigned integer of the supported features in a Handsfree Device.
/// </summary>
/// <specification>
/// HFP v1.8 Section 4.3.1 Subsection AT+BRSF
/// </specification>
public struct BLUETOOTH_HF_SUPPORTED_FEATURES
{
/// <summary>
/// True to request echo and noise reduction functionality.
/// </summary>
public bool EC_AD_NR_FUNCTION;
/// <summary>
/// True to request three way calling functionality.
/// </summary>
public bool THREE_WAY_CALLING;
/// <summary>
/// True to request call identification functionality.
/// </summary>
public bool CLI_PRESENTATION_CAPABILITY;
/// <summary>
/// True to request voice recognition functionality.
/// </summary>
public bool VOICE_RECOGNITION_ACTIVATION;
/// <summary>
/// True to request remote volume control functionality.
/// </summary>
public bool REMOTE_VOLUME_CONTROL;
/// <summary>
/// True to request enhanced call status functionality.
/// </summary>
public bool ENHANCED_CALL_STATUS;
/// <summary>
/// True to request enhanced call control functionality.
/// </summary>
public bool ENHANCED_CALL_CONTROL;
/// <summary>
/// True to request codec negotiation functionality.
/// </summary>
public bool CODEC_NEGOTIATION;
/// <summary>
/// True to request hands free indicators functionality.
/// </summary>
public bool HANDS_FREE_INDICATORS;
/// <summary>
/// True to request eSCO for full duplex audio functionality.
/// </summary>
public bool ESCO_S4_SETTINGS_SUPPORTED;
/// <summary>
/// True to request enhanced voice recognition functionality.
/// </summary>
public bool ENHANCED_VOICE_RECOGNITION_STATUS;
/// <summary>
/// True to request voice to text functionality.
/// </summary>
public bool VOICE_RECOGNITION_TEXT;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved12;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved13;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved14;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved15;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved16;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved17;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved18;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved19;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved20;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved21;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved22;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved23;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved24;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved25;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved26;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved27;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved28;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved29;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved30;
/// <summary>
/// Reserver for future use.
/// </summary>
public bool Reserved31;
/// <summary>
/// Sets all the non-reserved fields to <paramref name="value"/>.
/// </summary>
/// <param name="value">The value to set the fields.</param>
public void SetAll(bool value)
{
EC_AD_NR_FUNCTION = value; THREE_WAY_CALLING = value;
CLI_PRESENTATION_CAPABILITY = value;
VOICE_RECOGNITION_ACTIVATION = value;
REMOTE_VOLUME_CONTROL = value;
ENHANCED_CALL_STATUS = value;
ENHANCED_CALL_CONTROL = value;
CODEC_NEGOTIATION = value;
HANDS_FREE_INDICATORS = value;
ESCO_S4_SETTINGS_SUPPORTED = value;
ENHANCED_VOICE_RECOGNITION_STATUS = value;
VOICE_RECOGNITION_TEXT = value;
SetReserved();
}
/// <summary>
/// Fills all values of the current struct from an <see cref="Array"/> of <see cref="bool"/>.
/// </summary>
/// <param name="content">The byte values for the struct.</param>
public void FromBytes(byte[] content)
{
// convert the byte array to an array of bits/bool
var bits = new BitArray(content);
var bitArray = new bool[bits.Length];
bits.CopyTo(bitArray, 0);
FromBits(bitArray);
}
/// <summary>
/// Converts the values of the struct into an <see cref="Array"/> of <see cref="byte"/>.
/// </summary>
/// <returns>An <see cref="Array"/> of <see cref="byte"/> values.</returns>
public byte[] ToBytes()
{
// https://stackoverflow.com/questions/560123/convert-from-bitarray-to-byte
var bitArray = ToBits();
var paramBits = new BitArray(bitArray);
// Get the number of bytes needed. 8 bits per byte so divide by 8.
var bitsInByte = paramBits.Length / 8;
var bytes = new byte[bitsInByte];
paramBits.CopyTo(bytes, 0);
return bytes;
}
/// <summary>
/// Converts the values of the struct into an unsigned Int32.
/// </summary>
/// <returns><see cref="uint"/></returns>
public uint ToUInt() => ToBits().ToUInt32();
/// <summary>
/// Fills all values of the current struct from an <see cref="Array"/> of <see cref="bool"/>.
/// </summary>
/// <param name="propertySelectors">The bit/bool values for the struct.</param>
private void FromBits(bool[] propertySelectors)
{
EC_AD_NR_FUNCTION = propertySelectors[0];
THREE_WAY_CALLING = propertySelectors[1];
CLI_PRESENTATION_CAPABILITY = propertySelectors[2];
VOICE_RECOGNITION_ACTIVATION = propertySelectors[3];
REMOTE_VOLUME_CONTROL = propertySelectors[4];
ENHANCED_CALL_STATUS = propertySelectors[5];
ENHANCED_CALL_CONTROL = propertySelectors[6];
CODEC_NEGOTIATION = propertySelectors[7];
HANDS_FREE_INDICATORS = propertySelectors[8];
ESCO_S4_SETTINGS_SUPPORTED = propertySelectors[9];
ENHANCED_VOICE_RECOGNITION_STATUS = propertySelectors[10];
VOICE_RECOGNITION_TEXT = propertySelectors[11];
Reserved12 = propertySelectors[12];
Reserved13 = propertySelectors[13];
Reserved14 = propertySelectors[14];
Reserved15 = propertySelectors[15];
Reserved16 = propertySelectors[16];
Reserved17 = propertySelectors[17];
Reserved18 = propertySelectors[18];
Reserved19 = propertySelectors[19];
Reserved20 = propertySelectors[20];
Reserved21 = propertySelectors[21];
Reserved22 = propertySelectors[22];
Reserved23 = propertySelectors[23];
Reserved24 = propertySelectors[24];
Reserved25 = propertySelectors[25];
Reserved26 = propertySelectors[26];
Reserved27 = propertySelectors[27];
Reserved28 = propertySelectors[28];
Reserved29 = propertySelectors[29];
Reserved30 = propertySelectors[30];
Reserved31 = propertySelectors[31];
}
/// <summary>
/// Converts the values of the struct into an <see cref="Array"/> of <see cref="bool"/>.
/// </summary>
/// <returns>An <see cref="Array"/> of <see cref="bool"/> values.</returns>
private bool[] ToBits()
{
// NOTE: we don't want to count the reserved flags
return new bool[]
{
EC_AD_NR_FUNCTION, THREE_WAY_CALLING, CLI_PRESENTATION_CAPABILITY, VOICE_RECOGNITION_ACTIVATION,
REMOTE_VOLUME_CONTROL, ENHANCED_CALL_STATUS, ENHANCED_CALL_CONTROL, CODEC_NEGOTIATION,
HANDS_FREE_INDICATORS, ESCO_S4_SETTINGS_SUPPORTED, ENHANCED_VOICE_RECOGNITION_STATUS,
VOICE_RECOGNITION_TEXT
};
}
/// <summary>
/// Sets all reserved to false.
/// </summary>
private void SetReserved()
{
Reserved12 = false;
Reserved13 = false;
Reserved14 = false;
Reserved15 = false;
Reserved16 = false;
Reserved17 = false;
Reserved18 = false;
Reserved19 = false;
Reserved20 = false;
Reserved21 = false;
Reserved22 = false;
Reserved23 = false;
Reserved24 = false;
Reserved25 = false;
Reserved26 = false;
Reserved27 = false;
Reserved28 = false;
Reserved29 = false;
Reserved30 = false;
Reserved31 = false;
}
}
}