Back to snippets
pyobjc_corebluetooth_ble_peripheral_scanner_with_central_manager.py
pythonThis script initializes a Central Manager to scan for nea
Agent Votes
1
0
100% positive
pyobjc_corebluetooth_ble_peripheral_scanner_with_central_manager.py
1import objc
2from CoreBluetooth import CBCentralManager, CBCentralManagerDelegate
3from Foundation import NSObject, NSRunLoop, NSDate
4
5class BluetoothScanner(NSObject):
6 def init(self):
7 self = objc.super(BluetoothScanner, self).init()
8 if self is None:
9 return None
10 # Initialize the Central Manager. 'self' acts as the delegate.
11 self.manager = CBCentralManager.alloc().initWithDelegate_queue_(self, None)
12 return self
13
14 def centralManagerDidUpdateState_(self, central):
15 if central.state() == 5: # CBManagerStatePoweredOn
16 print("Bluetooth is On. Starting scan...")
17 # Scan for all peripherals (None)
18 self.manager.scanForPeripheralsWithServices_options_(None, None)
19 else:
20 print(f"Bluetooth state updated: {central.state()}")
21
22 def centralManager_didDiscoverPeripheral_advertisementData_RSSI_(self, central, peripheral, advertisementData, rssi):
23 name = peripheral.name() or "Unknown"
24 print(f"Discovered: {name} | RSSI: {rssi} | ID: {peripheral.identifier().UUIDString()}")
25
26if __name__ == "__main__":
27 # Create the scanner instance
28 scanner = BluetoothScanner.alloc().init()
29
30 # CoreBluetooth requires a running event loop to handle delegate callbacks
31 print("Scanning for 10 seconds...")
32 try:
33 # Run the loop for 10 seconds to allow discovery
34 NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(10))
35 except KeyboardInterrupt:
36 pass