/
GATTClient.swift
executable file
·1517 lines (1031 loc) · 59.5 KB
/
GATTClient.swift
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// GATTClient.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 2/29/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
import Foundation
public extension GATT {
public typealias Client = GATTClient
}
/// GATT Client
public final class GATTClient {
// MARK: - Properties
public var log: ((String) -> ())?
public var writePending: (() -> ())? {
get { return connection.writePending }
set { connection.writePending = newValue }
}
public private(set) var maximumTransmissionUnit: ATTMaximumTransmissionUnit {
get { return connection.maximumTransmissionUnit }
set { connection.maximumTransmissionUnit = newValue }
}
public let preferredMaximumTransmissionUnit: ATTMaximumTransmissionUnit
// Don't modify
@_versioned
internal private(set) var connection: ATTConnection
/// Whether the client is currently writing a long value.
internal private(set) var inLongWrite: Bool = false
/// Notications
internal private(set) var notifications = [UInt16: Notification]()
/// Indications
internal private(set) var indications = [UInt16: Notification]()
// MARK: - Initialization
public init(socket: L2CAPSocketProtocol,
maximumTransmissionUnit: ATT.MaximumTransmissionUnit = .default,
log: ((String) -> ())? = nil,
writePending: (() -> ())? = nil) {
self.connection = ATTConnection(socket: socket)
self.preferredMaximumTransmissionUnit = maximumTransmissionUnit
self.log = log
self.writePending = writePending
// setup notifications and indications
self.registerATTHandlers()
// queue MTU exchange if not default value
if maximumTransmissionUnit > .default {
self.exchangeMTU()
}
}
// MARK: - Methods
/// Performs the actual IO for recieving data.
public func read() throws -> Bool {
return try connection.read()
}
/// Performs the actual IO for sending data.
public func write() throws -> Bool {
return try connection.write()
}
// MARK: Requests
/// Discover All Primary Services
///
/// This sub-procedure is used by a client to discover all the primary services on a server.
/// ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/DiscoverAllPrimaryServices.png)
///
/// - Parameter completion: The completion closure.
public func discoverAllPrimaryServices(completion: @escaping (GATTClientResponse<[Service]>) -> ()) {
/// The Attribute Protocol Read By Group Type Request shall be used with
/// the Attribute Type parameter set to the UUID for «Primary Service».
/// The Starting Handle shall be set to 0x0001 and the Ending Handle shall be set to 0xFFFF.
discoverServices(start: 0x0001, end: 0xFFFF, primary: true, completion: completion)
}
/// Discover Primary Service by Service UUID
///
/// This sub-procedure is used by a client to discover a specific primary service on a server
/// when only the Service UUID is known. The specific primary service may exist multiple times on a server.
/// The primary service being discovered is identified by the service UUID.
/// ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/DiscoverPrimaryServiceByServiceUUID.png)
///
/// - Parameter uuid: The UUID of the service to find.
/// - Parameter completion: The completion closure.
public func discoverPrimaryServices(by uuid: BluetoothUUID,
completion: @escaping (GATTClientResponse<[Service]>) -> ()) {
// The Attribute Protocol Find By Type Value Request shall be used with the Attribute Type
// parameter set to the UUID for «Primary Service» and the Attribute Value set to the 16-bit
// Bluetooth UUID or 128-bit UUID for the specific primary service.
// The Starting Handle shall be set to 0x0001 and the Ending Handle shall be set to 0xFFFF.
discoverServices(uuid: uuid, start: 0x0001, end: 0xFFFF, primary: true, completion: completion)
}
/// Discover All Characteristics of a Service
///
/// This sub-procedure is used by a client to find all the characteristic declarations within
/// a service definition on a server when only the service handle range is known.
/// The service specified is identified by the service handle range.
/// ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/DiscoverAllCharacteristics.png)
///
/// - Parameter service: The service.
/// - Parameter completion: The completion closure.
public func discoverAllCharacteristics(of service: Service,
completion: @escaping (GATTClientResponse<[Characteristic]>) -> ()) {
// The Attribute Protocol Read By Type Request shall be used with the Attribute Type
// parameter set to the UUID for «Characteristic» The Starting Handle shall be set to
// starting handle of the specified service and the Ending Handle shall be set to the
// ending handle of the specified service.
discoverCharacteristics(service: service, completion: completion)
}
/// Discover Characteristics by UUID
///
/// This sub-procedure is used by a client to discover service characteristics on a server when
/// only the service handle ranges are known and the characteristic UUID is known.
/// The specific service may exist multiple times on a server.
/// The characteristic being discovered is identified by the characteristic UUID.
/// ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/DiscoverCharacteristicsByUUID.png)
///
/// - Parameter service: The service of the characteristics to find.
/// - Parameter uuid: The UUID of the characteristics to find.
/// - Parameter completion: The completion closure.
public func discoverCharacteristics(of service: Service,
by uuid: BluetoothUUID,
completion: @escaping (GATTClientResponse<[Characteristic]>) -> ()) {
// The Attribute Protocol Read By Type Request is used to perform the beginning of the sub-procedure.
// The Attribute Type is set to the UUID for «Characteristic» and the Starting Handle and Ending Handle
// parameters shall be set to the service handle range.
discoverCharacteristics(uuid: uuid, service: service, completion: completion)
}
/// Read Characteristic Value
///
/// This sub-procedure is used to read a Characteristic Value from a server when the client knows
/// the Characteristic Value Handle.
///
/// ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/ReadCharacteristicValue.png)
public func readCharacteristic(_ characteristic: Characteristic,
completion: @escaping (GATTClientResponse<Data>) -> ()) {
// read value and try to read blob if too big
readAttributeValue(characteristic.handle.value, completion: completion)
}
/// Read Using Characteristic UUID
///
/// This sub-procedure is used to read a Characteristic Value from a server when the client
/// only knows the characteristic UUID and does not know the handle of the characteristic.
///
/// ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/ReadUsingCharacteristicUUID.png)
public func readCharacteristics(using uuid: BluetoothUUID,
handleRange: (start: UInt16, end: UInt16) = (.min, .max),
completion: @escaping (GATTClientResponse<[UInt16: Data]>) -> ()) {
precondition(handleRange.start < handleRange.end)
// The Attribute Protocol Read By Type Request is used to perform the sub-procedure.
// The Attribute Type is set to the known characteristic UUID and the Starting Handle and Ending Handle parameters
// shall be set to the range over which this read is to be performed. This is typically the handle range for the service in which the characteristic belongs.
let pdu = ATTReadByTypeRequest(startHandle: handleRange.start,
endHandle: handleRange.end,
attributeType: uuid)
let operation = ReadUsingUUIDOperation(uuid: uuid, completion: completion)
send(pdu) { [unowned self] in self.readByTypeResponse($0, operation: operation) }
}
/// Read Multiple Characteristic Values
///
/// This sub-procedure is used to read multiple Characteristic Values from a server when the client
/// knows the Characteristic Value Handles.
///
/// ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/ReadMultipleCharacteristicValues.png)
///
/// - Note: A client should not use this request for attributes when the Set Of Values parameter could be `(ATT_MTU–1)`
/// as it will not be possible to determine if the last attribute value is complete, or if it overflowed.
public func readCharacteristics(_ characteristics: [Characteristic], completion: @escaping (GATTClientResponse<Data>) -> ()) {
// The Attribute Protocol Read Multiple Request is used with the Set Of Handles parameter set to the Characteristic Value Handles.
// The Read Multiple Response returns the Characteristic Values in the Set Of Values parameter.
let handles = characteristics.map { $0.handle.value }
guard let pdu = ATTReadMultipleRequest(handles: handles)
else { fatalError("Must provide at least 2 characteristics") }
let operation = ReadMultipleOperation(characteristics: characteristics, completion: completion)
send(pdu) { [unowned self] in self.readMultipleResponse($0, operation: operation) }
}
/**
Write Characteristic
Uses the appropriate procecedure to write the characteristic value.
*/
public func writeCharacteristic(_ characteristic: Characteristic,
data: Data,
reliableWrites: Bool = true,
completion: ((GATTClientResponse<()>) -> ())?) {
writeAttribute(characteristic.handle.value,
data: data,
reliableWrites: reliableWrites,
completion: completion)
}
/**
Discover All Characteristic Descriptors
This sub-procedure is used by a client to find all the characteristic descriptor’s Attribute Handles and Attribute Types within a characteristic definition when only the characteristic handle range is known. The characteristic specified is identified by the characteristic handle range.
![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/DiscoverAllCharacteristicDescriptors.png)
*/
public func discoverDescriptors(for characteristic: Characteristic,
service: (declaration: Service, characteristics: [Characteristic]),
completion: @escaping (GATTClientResponse<[Descriptor]>) -> ()) {
/**
The Attribute Protocol Find Information Request shall be used with the Starting Handle set
to the handle of the specified characteristic value + 1 and the Ending Handle set to the
ending handle of the specified characteristic.
*/
let start = characteristic.handle.value + 1
let end = endHandle(for: characteristic, service: service)
let operation = DescriptorDiscoveryOperation(start: start, end: end, completion: completion)
discoverDescriptors(operation: operation)
}
/// Read Characteristic Descriptor
///
/// This sub-procedure is used to read a characteristic descriptor from a server when the client knows
/// the characteristic descriptor declaration’s Attribute handle.
///
/// ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/ReadCharacteristicValue.png)
public func readDescriptor(_ descriptor: Descriptor,
completion: @escaping (GATTClientResponse<Data>) -> ()) {
/**
The Attribute Protocol Read Request is used for this sub-procedure. The Read Request is used with the Attribute Handle parameter set to the characteristic descriptor handle. The Read Response returns the characteristic descriptor value in the Attribute Value parameter.
An Error Response shall be sent by the server in response to the Read Request if insufficient authentication, insufficient authorization, insufficient encryption key size is used by the client, or if a read operation is not permitted on the Characteristic Value. The Error Code parameter is set accordingly.
*/
// read value and try to read blob if too big
readAttributeValue(descriptor.handle, completion: completion)
}
/**
Write Descriptor
Uses the appropriate procecedure to write the characteristic descriptor value.
*/
public func writeDescriptor(_ descriptor: Descriptor,
data: Data,
reliableWrites: Bool = true,
completion: ((GATTClientResponse<()>) -> ())?) {
writeAttribute(descriptor.handle,
data: data,
reliableWrites: reliableWrites,
completion: completion)
}
/**
Notifications
This sub-procedure is used when a server is configured to notify a Characteristic Value to a client without expecting any Attribute Protocol layer acknowledgment that the notification was successfully received.
![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/Notifications.png)
*/
public func clientCharacteristicConfiguration(notification: Notification?,
indication: Notification?,
for characteristic: Characteristic,
descriptors: [GATTClient.Descriptor],
completion: @escaping (GATTClientResponse<()>) -> ()) {
guard let descriptor = descriptors.first(where: { $0.uuid == .clientCharacteristicConfiguration })
else { completion(.error(GATTClientError.clientCharacteristicConfigurationNotAllowed(characteristic))); return }
var clientConfiguration = GATTClientCharacteristicConfiguration()
if notification != nil {
clientConfiguration.configuration.insert(.notify)
}
if indication != nil {
clientConfiguration.configuration.insert(.indicate)
}
writeDescriptor(descriptor, data: clientConfiguration.data) { [unowned self] (response) in
switch response {
case .error:
break
case .value:
self.notifications[characteristic.handle.value] = notification
self.indications[characteristic.handle.value] = indication
}
completion(response)
}
}
// MARK: - Private Methods
@inline(__always)
private func registerATTHandlers() {
// value notifications / indications
connection.register { [weak self] in self?.notification($0) }
connection.register { [weak self] in self?.indication($0) }
}
@inline(__always)
private func send <Request: ATTProtocolDataUnit, Response> (_ request: Request, response: @escaping (ATTResponse<Response>) -> ()) {
let log = self.log
log?("Request: \(request)")
let callback: (AnyATTResponse) -> () = {
log?("Response: \($0.rawValue)")
response(ATTResponse<Response>($0))
}
let responseType: ATTProtocolDataUnit.Type = Response.self
guard let _ = connection.send(request, response: (callback, responseType))
else { fatalError("Could not add PDU to queue: \(request)") }
}
@inline(__always)
private func send <Request: ATTProtocolDataUnit> (_ request: Request) {
log?("Request: \(request)")
guard let _ = connection.send(request)
else { fatalError("Could not add PDU to queue: \(request)") }
}
internal func endHandle(for characteristic: Characteristic,
service: (declaration: Service, characteristics: [Characteristic])) -> UInt16 {
// calculate ending handle of characteristic
let end: UInt16
guard let index = service.characteristics.index(where: { $0.handle.declaration == characteristic.handle.declaration })
else { fatalError("Invalid characteristics \(service.characteristics.map { $0.uuid })") }
let nextIndex = index + 1
// get start handle of next characteristic
if nextIndex < service.characteristics.count {
let nextCharacteristic = service.characteristics[nextIndex]
end = nextCharacteristic.handle.declaration - 1
} else {
// use service end handle
end = service.declaration.end
}
return end
}
// MARK: Requests
private func exchangeMTU() {
let clientMTU = preferredMaximumTransmissionUnit
let pdu = ATTMaximumTransmissionUnitRequest(clientMTU: clientMTU.rawValue)
send(pdu) { [unowned self] in self.exchangeMTUResponse($0) }
}
private func discoverServices(uuid: BluetoothUUID? = nil,
start: UInt16 = 0x0001,
end: UInt16 = 0xffff,
primary: Bool = true,
completion: @escaping (GATTClientResponse<[Service]>) -> ()) {
let serviceType = GATT.UUID(primaryService: primary)
let operation = DiscoveryOperation<Service>(uuid: uuid,
start: start,
end: end,
type: serviceType,
completion: completion)
if let uuid = uuid {
let pdu = ATTFindByTypeRequest(startHandle: start,
endHandle: end,
attributeType: serviceType.rawValue,
attributeValue: uuid.littleEndian.data)
send(pdu) { [unowned self] in self.findByTypeResponse($0, operation: operation) }
} else {
let pdu = ATTReadByGroupTypeRequest(startHandle: start,
endHandle: end,
type: serviceType.uuid)
send(pdu) { [unowned self] in self.readByGroupTypeResponse($0, operation: operation) }
}
}
private func discoverCharacteristics(uuid: BluetoothUUID? = nil,
service: Service,
completion: @escaping (GATTClientResponse<[Characteristic]>) -> ()) {
let attributeType = GATT.UUID.characteristic
let operation = DiscoveryOperation<Characteristic>(uuid: uuid,
start: service.handle,
end: service.end,
type: attributeType,
completion: completion)
let pdu = ATTReadByTypeRequest(startHandle: service.handle,
endHandle: service.end,
attributeType: attributeType.uuid)
send(pdu) { [unowned self] in self.readByTypeResponse($0, operation: operation) }
}
private func discoverDescriptors(operation: DescriptorDiscoveryOperation) {
assert(operation.start <= operation.end, "Invalid range")
let pdu = ATTFindInformationRequest(startHandle: operation.start, endHandle: operation.end)
send(pdu) { [unowned self] in self.findInformationResponse($0, operation: operation) }
}
/// Read Characteristic Value
///
/// This sub-procedure is used to read a Characteristic Value from a server when the client knows
/// the Characteristic Value Handle.
///
/// ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/ReadCharacteristicValue.png)
private func readAttributeValue(_ handle: UInt16, completion: @escaping (GATTClientResponse<Data>) -> ()) {
// The Attribute Protocol Read Request is used with the
// Attribute Handle parameter set to the Characteristic Value Handle.
// The Read Response returns the Characteristic Value in the Attribute Value parameter.
// read value and try to read blob if too big
let pdu = ATTReadRequest(handle: handle)
let operation = ReadOperation(handle: handle, completion: completion)
send(pdu) { [unowned self] in self.readResponse($0, operation: operation) }
}
/// Read Long Characteristic Value
///
/// This sub-procedure is used to read a Characteristic Value from a server when the client knows
/// the Characteristic Value Handle and the length of the Characteristic Value is longer than can
/// be sent in a single Read Response Attribute Protocol message.
///
/// ![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/ReadLongCharacteristicValues.png)
@inline(__always)
private func readLongAttributeValue(_ operation: ReadOperation) {
// The Attribute Protocol Read Blob Request is used to perform this sub-procedure.
// The Attribute Handle shall be set to the Characteristic Value Handle of the Characteristic Value to be read.
// The Value Offset parameter shall be the offset within the Characteristic Value to be read. To read the
// complete Characteristic Value the offset should be set to 0x00 for the first Read Blob Request.
// The offset for subsequent Read Blob Requests is the next octet that has yet to be read.
// The Read Blob Request is repeated until the Read Blob Response’s Part Attribute Value parameter is shorter than (ATT_MTU-1).
let pdu = ATTReadBlobRequest(handle: operation.handle,
offset: operation.offset)
send(pdu) { [unowned self] in self.readBlobResponse($0, operation: operation) }
}
private func writeAttribute(_ handle: UInt16,
data: Data,
reliableWrites: Bool,
completion: ((GATTClientResponse<()>) -> ())?) {
// short value
if data.count <= Int(maximumTransmissionUnit.rawValue) - ATTWriteRequest.length { // ATT_MTU - 3
if let completion = completion {
writeAttributeValue(handle,
data: data,
completion: completion)
} else {
writeAttributeCommand(handle,
data: data)
}
} else {
let completion = completion ?? { _ in }
writeLongAttributeValue(handle,
data: data,
reliableWrites: reliableWrites,
completion: completion)
}
}
private func writeAttributeCommand(_ attribute: UInt16, data: Data) {
let data = Data(data.prefix(Int(maximumTransmissionUnit.rawValue) - 3))
let pdu = ATTWriteCommand(handle: attribute, value: data)
send(pdu)
}
/// Write attribute request.
private func writeAttributeValue(_ attribute: UInt16,
data: Data,
completion: @escaping (GATTClientResponse<()>) -> ()) {
let data = Data(data.prefix(Int(maximumTransmissionUnit.rawValue) - ATTWriteRequest.length))
let pdu = ATTWriteRequest(handle: attribute, value: data)
send(pdu) { [unowned self] in self.writeResponse($0, completion: completion) }
}
private func writeLongAttributeValue(_ attribute: UInt16,
data: Data,
reliableWrites: Bool = false,
completion: @escaping (GATTClientResponse<()>) -> ()) {
// The Attribute Protocol Prepare Write Request and Execute Write Request are used to perform this sub-procedure.
// The Attribute Handle parameter shall be set to the Characteristic Value Handle of the Characteristic Value to be written.
// The Part Attribute Value parameter shall be set to the part of the Attribute Value that is being written.
// The Value Offset parameter shall be the offset within the Characteristic Value to be written.
// To write the complete Characteristic Value the offset should be set to 0x0000 for the first Prepare Write Request.
// The offset for subsequent Prepare Write Requests is the next octet that has yet to be written.
// The Prepare Write Request is repeated until the complete Characteristic Value has been transferred,
// after which an Executive Write Request is used to write the complete value.
guard inLongWrite == false
else { completion(.error(GATTClientError.inLongWrite)); return }
let firstValuePart = Data(data.prefix(Int(maximumTransmissionUnit.rawValue) - ATTPrepareWriteRequest.length))
let pdu = ATTPrepareWriteRequest(handle: attribute,
offset: 0x00,
partValue: firstValuePart)
let operation = WriteOperation(handle: attribute,
data: data,
reliableWrites: reliableWrites,
lastRequest: pdu,
completion: completion)
send(pdu) { [unowned self] in self.prepareWriteResponse($0, operation: operation) }
}
/**
Signed Write Without Response
This sub-procedure is used to write a Characteristic Value to a server when the client knows the Characteristic Value Handle and the ATT Bearer is not encrypted. This sub-procedure shall only be used if the Characteristic Properties authenticated bit is enabled and the client and server device share a bond.
If the authenticated Characteristic Value that is written is the wrong size, has an invalid value as defined by the profile, or the signed value does not authenticate the client, then the write shall not succeed and no error shall be gener- ated by the server.
![Image](https://github.com/PureSwift/Bluetooth/raw/master/Assets/SignedWriteWithoutResponse.png)
- Note: On BR/EDR, the ATT Bearer is always encrypted, due to the use of Security Mode 4, therefore this sub-procedure shall not be used.
*/
private func writeSignedCharacteristicCommand(_ characteristic: Characteristic, data: Data) {
// This sub-procedure only writes the first (ATT_MTU – 15) octets of an Attribute Value.
// This sub-procedure cannot be used to write a long Attribute.
// The Attribute Protocol Write Command is used for this sub-procedure.
// The Attribute Handle parameter shall be set to the Characteristic Value Handle.
// The Attribute Value parameter shall be set to the new Characteristic Value authenticated by signing the value.
// If a connection is already encrypted with LE security mode 1, level 2 or level 3 as defined in [Vol 3] Part C,
// Section 10.2 then, a Write Without Response as defined in Section 4.9.1 shall be used instead of
// a Signed Write Without Response.
let data = Data(data.prefix(Int(maximumTransmissionUnit.rawValue) - 15))
// TODO: Sign Data
let pdu = ATTWriteCommand(handle: characteristic.handle.value, value: data)
send(pdu)
}
// MARK: - Callbacks
private func exchangeMTUResponse(_ response: ATTResponse<ATTMaximumTransmissionUnitResponse>) {
switch response {
case let .error(error):
log?("Could not exchange MTU: \(error)")
case let .value(pdu):
let clientMTU = preferredMaximumTransmissionUnit
let finalMTU = ATTMaximumTransmissionUnit(server: pdu.serverMTU, client: clientMTU.rawValue)
log?("MTU Exchange (\(clientMTU) -> \(finalMTU))")
self.maximumTransmissionUnit = finalMTU
}
}
private func readByGroupTypeResponse(_ response: ATTResponse<ATTReadByGroupTypeResponse>,
operation: DiscoveryOperation<Service>) {
// Read By Group Type Response returns a list of Attribute Handle, End Group Handle, and Attribute Value tuples
// corresponding to the services supported by the server. Each Attribute Value contained in the response is the
// Service UUID of a service supported by the server. The Attribute Handle is the handle for the service declaration.
// The End Group Handle is the handle of the last attribute within the service definition.
// The Read By Group Type Request shall be called again with the Starting Handle set to one greater than the
// last End Group Handle in the Read By Group Type Response.
switch response {
case let .error(errorResponse):
operation.error(errorResponse)
case let .value(pdu):
// store PDU values
for serviceData in pdu.attributeData {
guard let littleEndianServiceUUID = BluetoothUUID(data: serviceData.value)
else { operation.completion(.error(Error.invalidResponse(pdu))); return }
let serviceUUID = BluetoothUUID(littleEndian: littleEndianServiceUUID)
let service = Service(uuid: serviceUUID,
type: operation.type,
handle: serviceData.attributeHandle,
end: serviceData.endGroupHandle)
operation.foundData.append(service)
}
// get more if possible
let lastEnd = pdu.attributeData.last?.endGroupHandle ?? 0x00
// prevent infinite loop
guard lastEnd >= operation.start
else { operation.completion(.error(Error.invalidResponse(pdu))); return }
guard lastEnd < .max // End of database
else { operation.success(); return }
operation.start = lastEnd + 1
if lastEnd < operation.end {
let pdu = ATTReadByGroupTypeRequest(startHandle: operation.start,
endHandle: operation.end,
type: operation.type.uuid)
send(pdu) { [unowned self] in self.readByGroupTypeResponse($0, operation: operation) }
} else {
operation.success()
}
}
}
private func findByTypeResponse(_ response: ATTResponse<ATTFindByTypeResponse>, operation: DiscoveryOperation<Service>) {
// Find By Type Value Response returns a list of Attribute Handle ranges.
// The Attribute Handle range is the starting handle and the ending handle of the service definition.
// If the Attribute Handle range for the Service UUID being searched is returned and the End Found Handle
// is not 0xFFFF, the Find By Type Value Request may be called again with the Starting Handle set to one
// greater than the last Attribute Handle range in the Find By Type Value Response.
switch response {
case let .error(errorResponse):
operation.error(errorResponse)
case let .value(pdu):
guard let serviceUUID = operation.uuid
else { fatalError("Should have UUID specified") }
// pre-allocate array
operation.foundData.reserveCapacity(operation.foundData.count + pdu.handlesInformationList.count)
// store PDU values
for serviceData in pdu.handlesInformationList {
let service = Service(uuid: serviceUUID,
type: operation.type,
handle: serviceData.foundAttribute,
end: serviceData.groupEnd)
operation.foundData.append(service)
}
// get more if possible
let lastEnd = pdu.handlesInformationList.last?.groupEnd ?? 0x00
guard lastEnd < .max // End of database
else { operation.success(); return }
operation.start = lastEnd + 1
// need to continue scanning
if lastEnd < operation.end {
let pdu = ATTFindByTypeRequest(startHandle: operation.start,
endHandle: operation.end,
attributeType: operation.type.rawValue,
attributeValue: serviceUUID.littleEndian.data)
send(pdu) { [unowned self] in self.findByTypeResponse($0, operation: operation) }
} else {
operation.success()
}
}
}
private func findInformationResponse(_ response: ATTResponse<ATTFindInformationResponse>,
operation: DescriptorDiscoveryOperation) {
/**
Two possible responses can be sent from the server for the Find Information Request: Find Information Response and Error Response.
Error Response is returned if an error occurred on the server.
Find Information Response returns a list of Attribute Handle and Attribute Value pairs corresponding to the characteristic descriptors in the characteristic definition. The Attribute Handle is the handle for the characteristic descriptor declaration. The Attribute Value is the Characteristic Descriptor UUID.
The Find Information Request shall be called again with the Starting Handle set to one greater than the last Attribute Handle in the Find Information Response.
The sub-procedure is complete when the Error Response is received and the Error Code is set to Attribute Not Found or the Find Information Response has an Attribute Handle that is equal to the Ending Handle of the request.
It is permitted to end the sub-procedure early if a desired Characteristic Descriptor is found prior to discovering all the characteristic descriptors of the specified characteristic.
*/
switch response {
case let .error(errorResponse):
operation.error(errorResponse)
case let .value(pdu):
// pre-allocate array
operation.foundDescriptors.reserveCapacity(operation.foundDescriptors.count + pdu.data.count)
let foundData: [Descriptor]
switch pdu.attributeData {
case let .bit16(values):
foundData = values.map { Descriptor(uuid: .bit16($0.uuid), handle: $0.handle) }
case let .bit128(values):
foundData = values.map { Descriptor(uuid: .bit128($0.uuid), handle: $0.handle) }
}
operation.foundDescriptors += foundData
// get more if possible
let lastHandle = foundData.last?.handle ?? 0x00
// prevent infinite loop
guard lastHandle >= operation.start
else { operation.completion(.error(Error.invalidResponse(pdu))); return }
guard lastHandle < .max // End of database
else { operation.success(); return }
let start = lastHandle + 1
// need to continue discovery
if lastHandle != 0, start < operation.end {
operation.start = start
discoverDescriptors(operation: operation)
} else {
// end of service
operation.success()
}
}
}
private func readByTypeResponse(_ response: ATTResponse<ATTReadByTypeResponse>,
operation: DiscoveryOperation<Characteristic>) {
typealias DeclarationAttribute = GATTDatabase.CharacteristicDeclarationAttribute
typealias Attribute = GATTDatabase.Attribute
// Read By Type Response returns a list of Attribute Handle and Attribute Value pairs corresponding to the
// characteristics in the service definition. The Attribute Handle is the handle for the characteristic declaration.
// The Attribute Value is the Characteristic Properties, Characteristic Value Handle and Characteristic UUID.
// The Read By Type Request shall be called again with the Starting Handle set to one greater than the last
// Attribute Handle in the Read By Type Response.
switch response {
case let .error(errorResponse):
operation.error(errorResponse)
case let .value(pdu):
// pre-allocate array
operation.foundData.reserveCapacity(operation.foundData.count + pdu.data.count)
// parse pdu data
for characteristicData in pdu.attributeData {
let handle = characteristicData.handle
let attribute = Attribute(handle: handle,
uuid: .characteristic,
value: Data(characteristicData.value),
permissions: [.read])
guard let declaration = DeclarationAttribute(attribute: attribute)
else { operation.completion(.error(Error.invalidResponse(pdu))); return }
let characteristic = Characteristic(uuid: declaration.uuid,
properties: declaration.properties,
handle: (handle, declaration.valueHandle))
operation.foundData.append(characteristic)
// if we specified a UUID to be searched,
// then call completion if it matches
if let operationUUID = operation.uuid {
guard characteristic.uuid != operationUUID
else { operation.success(); return }
}
}
// get more if possible
let lastEnd = pdu.attributeData.last?.handle ?? 0x00
// prevent infinite loop
guard lastEnd >= operation.start
else { operation.completion(.error(Error.invalidResponse(pdu))); return }
operation.start = lastEnd + 1
// need to continue discovery
if lastEnd != 0, operation.start < operation.end {
let pdu = ATTReadByTypeRequest(startHandle: operation.start,
endHandle: operation.end,
attributeType: operation.type.uuid)
send(pdu) { [unowned self] in self.readByTypeResponse($0, operation: operation) }
} else {
// end of service
operation.success()
}
}
}
/// Read Characteristic (or Descriptor) Value Response
private func readResponse(_ response: ATTResponse<ATTReadResponse>, operation: ReadOperation) {
// The Read Response only contains a Characteristic Value that is less than or equal to (ATT_MTU – 1) octets in length.
// If the Characteristic Value is greater than (ATT_MTU – 1) octets in length, the Read Long Characteristic Value procedure
// may be used if the rest of the Characteristic Value is required.
switch response {
case let .error(error):
operation.error(error)
case let .value(pdu):
operation.data = pdu.attributeValue
// short value
if pdu.attributeValue.count < (Int(maximumTransmissionUnit.rawValue) - 1) {
operation.success()
} else {
// read blob
readLongAttributeValue(operation)
}
}
}
/// Read Blob Response
private func readBlobResponse(_ response: ATTResponse<ATTReadBlobResponse>, operation: ReadOperation) {
// For each Read Blob Request a Read Blob Response is received with a portion of the Characteristic Value contained in the Part Attribute Value parameter.
switch response {
case let .error(error):
operation.error(error)
case let .value(pdu):
operation.data += pdu.partAttributeValue
// short value
if pdu.partAttributeValue.count < (Int(maximumTransmissionUnit.rawValue) - 1) {
operation.success()
} else {
// read blob
readLongAttributeValue(operation)
}
}
}
private func readMultipleResponse(_ response: ATTResponse<ATTReadMultipleResponse>, operation: ReadMultipleOperation) {
switch response {
case let .error(error):
operation.error(error)
case let .value(pdu):
operation.success(pdu.values)