88import CoreBluetooth
99import Mobileserver
1010
11-
1211class BluetoothManager : NSObject , ObservableObject , CBCentralManagerDelegate , CBPeripheralDelegate {
1312 var centralManager : CBCentralManager !
1413 var discoveredPeripheral : CBPeripheral ?
@@ -17,7 +16,7 @@ class BluetoothManager: NSObject, ObservableObject, CBCentralManagerDelegate, CB
1716 var pProduct : CBCharacteristic ?
1817
1918 private var readBuffer = Data ( )
20- private let readBufferLock = NSLock ( ) // Ensure thread-safe buffer access
19+ private let readBufferLock = NSLock ( ) // Ensure thread-safe buffer access
2120 private let semaphore = DispatchSemaphore ( value: 0 )
2221
2322 override init ( ) {
@@ -26,95 +25,118 @@ class BluetoothManager: NSObject, ObservableObject, CBCentralManagerDelegate, CB
2625 }
2726
2827 func isConnected( ) -> Bool {
29- return discoveredPeripheral != nil && pReader != nil && pWriter != nil ;
28+ return discoveredPeripheral != nil && pReader != nil && pWriter != nil
3029 }
3130
3231 func centralManagerDidUpdateState( _ central: CBCentralManager ) {
3332 switch central. state {
3433 case . poweredOn:
35- print ( " Bluetooth on" )
34+ print ( " BLE: on" )
3635 centralManager. scanForPeripherals (
3736 withServices: [ CBUUID ( string: " e1511a45-f3db-44c0-82b8-6c880790d1f1 " ) ] ,
3837 options: nil )
3938 case . poweredOff, . unauthorized, . unsupported, . resetting, . unknown:
40- print ( " Bluetooth unavailable or not supported " )
39+ print ( " BLE: Bluetooth Unavailable or not supported" )
4140 discoveredPeripheral = nil
4241 pReader = nil
4342 pWriter = nil
4443 @unknown default :
45- print ( " Unknown Bluetooth state " )
44+ print ( " BLE: Unknown Bluetooth state" )
4645 }
4746 }
4847
49- func centralManager( _ central: CBCentralManager , didDiscover peripheral: CBPeripheral , advertisementData: [ String : Any ] , rssi RSSI: NSNumber ) {
50- print ( " Bluetooth: discovered \( peripheral. name ?? " unknown device " ) " )
48+ func centralManager(
49+ _ central: CBCentralManager , didDiscover peripheral: CBPeripheral ,
50+ advertisementData: [ String : Any ] , rssi RSSI: NSNumber
51+ ) {
52+ print ( " BLE: discovered \( peripheral. name ?? " unknown device " ) " )
53+
54+ if let data = advertisementData [ " kCBAdvDataManufacturerData " ] as? Data {
55+ let data = data. advanced ( by: 2 ) // 2 bytes for manufacturer ID
56+ print ( " BLE: manufacturer data: \( data. hexEncodedString ( ) ) " )
57+ }
58+
5159 discoveredPeripheral = peripheral
5260 centralManager. stopScan ( )
5361 centralManager. connect ( peripheral, options: nil )
5462 }
5563
5664 func centralManager( _ central: CBCentralManager , didConnect peripheral: CBPeripheral ) {
57- print ( " Connected to \( peripheral. name ?? " unknown device " ) " )
65+ print ( " BLE: Connected to \( peripheral. name ?? " unknown device " ) " )
5866
5967 peripheral. delegate = self
6068 peripheral. discoverServices ( nil )
6169 }
6270
6371 func peripheral( _ peripheral: CBPeripheral , didDiscoverServices error: Error ? ) {
6472 if let error = error {
65- print ( " Error discovering services: \( error. localizedDescription) " )
73+ print ( " BLE: Error discovering services: \( error. localizedDescription) " )
6674 return
6775 }
6876
6977 if let services = peripheral. services {
7078 for service in services {
71- print ( " Discovered service: \( service. uuid) " )
79+ print ( " BLE: Discovered service: \( service. uuid) " )
7280 peripheral. discoverCharacteristics ( nil , for: service)
7381 }
7482 }
7583 }
7684
77- func peripheral( _ peripheral: CBPeripheral , didDiscoverCharacteristicsFor service: CBService , error: Error ? ) {
85+ func peripheral(
86+ _ peripheral: CBPeripheral , didDiscoverCharacteristicsFor service: CBService , error: Error ?
87+ ) {
7888 if let error = error {
79- print ( " Error discovering characteristics: \( error. localizedDescription) " )
89+ print ( " BLE: Error discovering characteristics: \( error. localizedDescription) " )
8090 return
8191 }
8292 if let characteristics = service. characteristics {
8393 for c in characteristics {
84- print ( " Discovered characteristic: \( c. uuid) " )
85- if c. uuid == CBUUID ( string: " 0001 " ) {
94+ print ( " BLE: Discovered characteristic: \( c. uuid) " )
95+ if c. uuid == CBUUID ( string: " 799d485c-d354-4ed0-b577-f8ee79ec275a " ) {
8696 pWriter = c
87- let max_len = peripheral. maximumWriteValueLength ( for: CBCharacteristicWriteType . withoutResponse)
88- print ( " Found writer service with max length \( max_len) - \( c. properties. contains ( . write) ) " )
97+ let max_len = peripheral. maximumWriteValueLength (
98+ for: CBCharacteristicWriteType . withoutResponse)
99+ print (
100+ " BLE: Found writer service with max length \( max_len) - \( c. properties. contains ( . write) ) "
101+ )
89102 }
90- if c. uuid == CBUUID ( string: " 0002 " ) {
103+ if c. uuid == CBUUID ( string: " 419572a5-9f53-4eb1-8db7-61bcab928867 " ) {
104+ peripheral. setNotifyValue ( true , for: c)
91105 pReader = c
92106 }
93- if c. uuid == CBUUID ( string: " 0003 " ) {
94- print ( " Found product characteristic " )
107+ if c. uuid == CBUUID ( string: " 9d1c9a77-8b03-4e49-8053-3955cda7da93 " ) {
108+ print ( " BLE: Found product characteristic" )
95109 peripheral. setNotifyValue ( true , for: c)
96110 pProduct = c
97111 }
98112 }
99113 }
100114 }
101115
102- func peripheral( _ peripheral: CBPeripheral , didWriteValueFor characteristic: CBCharacteristic , error: Error ? ) {
116+ func peripheral(
117+ _ peripheral: CBPeripheral , didWriteValueFor characteristic: CBCharacteristic , error: Error ?
118+ ) {
103119 if let error = error {
104- print ( " Bluetooth error writing data: \( error) " )
120+ print ( " BLE: Error writing data: \( error) " )
105121 return
106122 }
107- print ( " Blluetooth write ok" )
123+ print ( " BLE: write ok" )
108124 }
109125
110- func peripheral( _ peripheral: CBPeripheral , didUpdateValueFor characteristic: CBCharacteristic , error: Error ? ) {
126+ func peripheral(
127+ _ peripheral: CBPeripheral , didUpdateValueFor characteristic: CBCharacteristic ,
128+ error: Error ?
129+ ) {
111130 if let error = error {
112- print ( " Error receiving data: \( error) " )
131+ print ( " BLE: Error receiving data: \( error) " )
113132 return
114133 }
115134
116135 if characteristic == pReader, let data = characteristic. value {
117- print ( " Bluetooth received data: \( data. hexEncodedString ( ) ) " )
136+ if data. count != 64 {
137+ print ( " BLE: ERROR, expected 64 bytes " )
138+ }
139+ print ( " BLE: received data: \( data. hexEncodedString ( ) ) " )
118140 readBufferLock. lock ( )
119141 readBuffer. append ( data)
120142 readBufferLock. unlock ( )
@@ -123,7 +145,7 @@ class BluetoothManager: NSObject, ObservableObject, CBCentralManagerDelegate, CB
123145 semaphore. signal ( )
124146 }
125147 if characteristic == pProduct, let val = characteristic. value {
126- print ( " Bluetooth product changed: \( val) " )
148+ print ( " BLE: product changed: \( val) " )
127149 // Invoke device manager to scan now, which will make it detect the device being connected
128150 // (or disconnected, in case the product string indicates that) now instead of waiting for
129151 // the next scan.
@@ -132,11 +154,13 @@ class BluetoothManager: NSObject, ObservableObject, CBCentralManagerDelegate, CB
132154 }
133155
134156 // This method gets called if the peripheral disconnects
135- func centralManager( _ central: CBCentralManager , didDisconnectPeripheral peripheral: CBPeripheral , error: Error ? ) {
136- print ( " Bluetooth disconnected " )
137- discoveredPeripheral = nil ;
138- pReader = nil ;
139- pWriter = nil ;
157+ func centralManager(
158+ _ central: CBCentralManager , didDisconnectPeripheral peripheral: CBPeripheral , error: Error ?
159+ ) {
160+ print ( " BLE: perhipheral disconnected " )
161+ discoveredPeripheral = nil
162+ pReader = nil
163+ pWriter = nil
140164
141165 // TODO: start scanning again.
142166 }
@@ -150,26 +174,24 @@ class BluetoothManager: NSObject, ObservableObject, CBCentralManagerDelegate, CB
150174 print ( " discoveredPeripheral is not set " )
151175 return nil
152176 }
153- print ( " Bluetooth wants to read \( length) " )
154- readBufferLock. lock ( )
155- readBuffer. removeAll ( ) // Clear buffer before starting
156- readBufferLock. unlock ( )
177+ print ( " BLE: wants to read \( length) " )
178+
179+ var data = Data ( )
157180
158181 // Loop until we've read the required amount of data
159- while readBuffer. count < length {
160- // Trigger a read request
161- peripheral. readValue ( for: pReader)
162- // Block until the delegate signals
182+ while data. count < length {
183+ // Block until BLE reader callback notifies us
163184 semaphore. wait ( )
185+ readBufferLock. lock ( )
186+ data. append ( readBuffer. prefix ( 64 ) )
187+ readBuffer = readBuffer. advanced ( by: 64 )
188+ readBufferLock. unlock ( )
164189 }
165- print ( " Bluetooth read: need \( length) , got \( readBuffer. count) " )
166- readBufferLock. lock ( )
167- let data = readBuffer. prefix ( length)
168- readBufferLock. unlock ( )
190+ print ( " BLE: got \( data. count) " )
169191
170192 return data
171193 }
172-
194+
173195 func productStr( ) -> String {
174196 guard let pProduct = self . pProduct else {
175197 return " "
@@ -206,7 +228,7 @@ class BluetoothDeviceInfo: NSObject, MobileserverGoDeviceInfoInterfaceProtocol {
206228 }
207229
208230 func open( ) throws -> MobileserverGoReadWriteCloserInterfaceProtocol {
209- return BluetoothReadWriteCloser ( bluetoothManager: bluetoothManager)
231+ return BluetoothReadWriteCloser ( bluetoothManager: bluetoothManager)
210232 }
211233
212234 func product( ) -> String {
@@ -250,10 +272,10 @@ class BluetoothReadWriteCloser: NSObject, MobileserverGoReadWriteCloserInterface
250272 return
251273 }
252274
253- print ( " Bluetooth write data: \( data!. hexEncodedString ( ) ) " )
275+ print ( " BLE: write data: \( data!. hexEncodedString ( ) ) " )
254276
255277 bluetoothManager. discoveredPeripheral!. writeValue ( data!, for: pWriter, type: . withResponse)
256- n!. pointee = data!. count;
278+ n!. pointee = data!. count
257279 }
258280}
259281
0 commit comments