Skip to content

Instantly share code, notes, and snippets.

@Alexandro1112
Last active February 14, 2025 19:54
Show Gist options
  • Select an option

  • Save Alexandro1112/ff63b5249bf8d5bd61ed8a76b8a9edda to your computer and use it in GitHub Desktop.

Select an option

Save Alexandro1112/ff63b5249bf8d5bd61ed8a76b8a9edda to your computer and use it in GitHub Desktop.
"""The code defines a BluetoothManager class that manages Bluetooth functionality using the CoreBluetooth framework.
It initializes a central Bluetooth manager, listens for Bluetooth state changes, and scans for nearby Bluetooth peripherals. It captured it and return."""
import time
from Foundation import NSObject, NSRunLoop, NSDefaultRunLoopMode, NSDate, NSUUID
from CoreBluetooth import (CBCentralManager, CBManagerStatePoweredOn,
CBManagerStatePoweredOff, CBCentralManagerScanOptionAllowDuplicatesKey,
NSKeyValueObservingOptionNew, CBCentralManagerScanOptionAllowDuplicatesKey, NSLog,
CBConnectPeripheralOptionNotifyOnConnectionKey, CBConnectPeripheralOptionNotifyOnDisconnectionKey,
NSDictionary, CBAdvertisementDataLocalNameKey)
class BluetoothManager(NSObject):
def init(self):
self.centralmanager = CBCentralManager.alloc().initWithDelegate_queue_options_(self, None, None)
self.peripherals = []
return self
def centralManagerDidUpdateState_(self, central):
if central.state() == CBManagerStatePoweredOn:
print("Bluetooth is powered on.")
central.scanForPeripheralsWithServices_options_(
None, None
)
elif central.state() == CBManagerStatePoweredOff:
print("Bluetooth is enable.")
else:
print('Bluetooth is not available')
def centralManager_didDiscoverPeripheral_advertisementData_RSSI_(self, central, peripheral, advertisementData, rssi):
self.central = central
if not peripheral.name() is None:
info = {'name': peripheral.name(),
'identifier': peripheral.identifier(),
'rssi': rssi,
'date': NSDate.dateWithTimeIntervalSinceReferenceDate_(advertisementData['kCBAdvDataTimestamp']),
}
for k, v in info.items():
time.sleep(0.5)
print(f'{k}:{v}')
advertisementDataDict = advertisementData
# Get the local name from advertisement data
device_name = advertisementDataDict.objectForKey_(CBAdvertisementDataLocalNameKey)
if device_name and isinstance(device_name, str):
if '[TV] Samsung' in device_name:
while peripheral.isConnected() is not True:
time.sleep(0.5)
NSLog(f"Discovered: {device_name}")
self.connectPeripheral = peripheral
self.connectPeripheral.setDelegate_(self)
self.central.connectPeripheral_options_(self.connectPeripheral, None)
self.central.stopScan()
NSLog(f"Connecting to {device_name}...")
def centralManager_didConnect_(self, central, peripheral):
print("Connected to peripheral: %s" % peripheral.name())
def centralManager_didFailToConnectPeripheral_error_(self, central, peripheral, error):
print("Failed to connect to peripheral: %@, error: %@", peripheral.name(), error)
def run(self):
NSRunLoop.currentRunLoop().run()
def scan_devices():
manager = BluetoothManager.alloc().init()
manager.run()
scan_devices()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment