def init(self):
        """macOS init function for NSObject"""
        self = objc.super(CentralManagerDelegate, self).init()

        if self is None:
            return None

        self.event_loop = asyncio.get_event_loop()
        self.connected_peripheral_delegate = None
        self.connected_peripheral = None
        self._connection_state = CMDConnectionState.DISCONNECTED

        self.powered_on_event = asyncio.Event()
        self.devices = {}

        self.callbacks = {}
        self.disconnected_callback = None

        if not self.compliant():
            logger.warning("CentralManagerDelegate is not compliant")

        self.central_manager = CBCentralManager.alloc(
        ).initWithDelegate_queue_(
            self,
            dispatch_queue_create(b"bleak.corebluetooth",
                                  DISPATCH_QUEUE_SERIAL))

        return self
    def init(self):
        """macOS init function for NSObjects"""
        self = objc.super(PeripheralManagerDelegate, self).init()

        self.event_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()

        self.peripheral_manager: CBPeripheralManager = (
            CBPeripheralManager.alloc().initWithDelegate_queue_(
                self,
                dispatch_queue_create(b"bleak.corebluetooth",
                                      DISPATCH_QUEUE_SERIAL),
            ))

        self._callbacks: Dict[str, Callable] = {}

        # Events
        self._powered_on_event: threading.Event = threading.Event()
        self._advertisement_started_event: asyncio.Event = asyncio.Event()
        self._services_added_events: Dict[str, asyncio.Event] = {}

        # Documentation requires that no calls be made until we can validate
        # that the bluetooth module is powered on
        self._powered_on_event.wait()

        self._central_subscriptions = {}

        if not self.compliant():
            logger.warning("PeripheralManagerDelegate is not compliant")

        return self
Example #3
0
 def __init__(self):
     self._imageQueue = libdispatch.dispatch_queue_create(
         b"Image Queue", None)
     self._semaphore = libdispatch.dispatch_semaphore_create(0)
     self._capture_device_input = (
         self._capture_session) = self._capture_still_image_output = None
     self._devices = self.video_devices()
Example #4
0
    def init(self):
        """macOS init function for NSObject"""
        self = objc.super(CentralManagerDelegate, self).init()

        if self is None:
            return None

        self.event_loop = asyncio.get_event_loop()
        self.connected_peripheral_delegate = None
        self.connected_peripheral = None
        self._connection_state = CMDConnectionState.DISCONNECTED

        self.devices = {}

        self.callbacks = {}
        self.disconnected_callback = None
        self._connection_state_changed = asyncio.Event()

        self._did_update_state_event = threading.Event()
        self.central_manager = CBCentralManager.alloc().initWithDelegate_queue_(
            self, dispatch_queue_create(b"bleak.corebluetooth", DISPATCH_QUEUE_SERIAL)
        )

        # according to CoreBluetooth docs, it is not valid to call CBCentral
        # methods until the centralManagerDidUpdateState_() delegate method
        # is called and the current state is CBManagerStatePoweredOn.
        # It doesn't take long for the callback to occur, so we should be able
        # to do a blocking wait here without anyone complaining.
        self._did_update_state_event.wait(1)
        if self.central_manager.state() != CBManagerStatePoweredOn:
            raise BleakError("Bluetooth device is turned off")

        return self
Example #5
0
 async def test_libdispatch(event_loop: asyncio.AbstractEventLoop):
     did_finish = asyncio.Event()
     block = Function(event_loop, did_finish)
     queue = libdispatch.dispatch_queue_create(
         b'CoreBluetooth Queue', libdispatch.DISPATCH_QUEUE_SERIAL)
     # TODO: figure out if I can use funcutils to pass kwargs to do_it
     libdispatch.dispatch_async(queue, block.do_it)
     await asyncio.wait_for(did_finish.wait(), 10)
     assert did_finish.is_set()
    def initialize(self):
        """Initialize the BLE provider.  Must be called once before any other
        calls are made to the provider.
        """
        # Setup the central manager and its delegate.
        self._central_manager = CBCentralManager.alloc()
        dispatch_queue = libdispatch.dispatch_queue_create(b'q', None)

        self._central_manager.initWithDelegate_queue_options_(
            self._central_delegate, dispatch_queue, None)
Example #7
0
    def init(self, create_loop=True):
        self = super().init()
        self.queue = dispatch_queue_create(b"bleak.corebluetooth",
                                           DISPATCH_QUEUE_SERIAL)
        self._inquiry = IOBluetoothDeviceInquiry.inquiryWithDelegate_(self)
        self.set_updatenames(False)

        self.running = False
        self.t_start = None

        return self
Example #8
0
    def __init__(self, loop=None, *args, **kwargs):
        super(CoreBluetoothCentralManager, self).__init__(loop, *args, **kwargs)
        self._lock = asyncio.Lock()
        self._queue = libdispatch.dispatch_queue_create(b'CoreBluetooth Queue', libdispatch.DISPATCH_QUEUE_SERIAL)
        self._cbmanager = CoreBluetooth.CBCentralManager.alloc().initWithDelegate_queue_options_(self, self._queue, None)
        self._queue_scan_count = 0
        self._queue_isScanning = False
        self._device_found_callback = None

        # We need to defer the import of CoreBluetoothDevice due to circular dependency
        from aioble.corebluetooth.device import CoreBluetoothDevice as _device
        global CoreBluetoothDevice
        CoreBluetoothDevice = _device
        self.devices = {}
Example #9
0
    def init(self) -> Optional["CentralManagerDelegate"]:
        """macOS init function for NSObject"""
        self = objc.super(CentralManagerDelegate, self).init()

        if self is None:
            return None

        self.event_loop = asyncio.get_event_loop()
        self._connect_futures: Dict[NSUUID, asyncio.Future] = {}

        self.devices: Dict[str, BLEDeviceCoreBluetooth] = {}

        self.callbacks: Dict[int, Callable[[CBPeripheral, Dict[str, Any], int],
                                           None]] = {}
        self._disconnect_callbacks: Dict[NSUUID, DisconnectCallback] = {}
        self._disconnect_futures: Dict[NSUUID, asyncio.Future] = {}

        self._did_update_state_event = threading.Event()
        self.central_manager = CBCentralManager.alloc(
        ).initWithDelegate_queue_(
            self,
            dispatch_queue_create(b"bleak.corebluetooth",
                                  DISPATCH_QUEUE_SERIAL))

        # according to CoreBluetooth docs, it is not valid to call CBCentral
        # methods until the centralManagerDidUpdateState_() delegate method
        # is called and the current state is CBManagerStatePoweredOn.
        # It doesn't take long for the callback to occur, so we should be able
        # to do a blocking wait here without anyone complaining.
        self._did_update_state_event.wait(1)

        if self.central_manager.state() == CBManagerStateUnsupported:
            raise BleakError("BLE is unsupported")

        if self.central_manager.state() != CBManagerStatePoweredOn:
            raise BleakError("Bluetooth device is turned off")

        # isScanning property was added in 10.13
        if objc.macos_available(10, 13):
            self.central_manager.addObserver_forKeyPath_options_context_(
                self, "isScanning", NSKeyValueObservingOptionNew, 0)
            self._did_start_scanning_event: Optional[asyncio.Event] = None
            self._did_stop_scanning_event: Optional[asyncio.Event] = None

        return self