예제 #1
0
def test_cp34770():
    # Entries added with Int64/UInt64 should be findable with Python long
    from System import Int64, UInt64
    i64 = Int64(1110766100758387874)
    u64 = UInt64(9223372036854775808)
    
    m = {}
    m[i64] = 'a'
    AreEqual(m[1110766100758387874], 'a')
    
    m[u64] = 'b'
    AreEqual(m[9223372036854775808], 'b')
예제 #2
0
    async def connect(self) -> bool:
        """Connect to the specified GATT server.

        Returns:
            Boolean representing connection status.

        """
        # Try to find the desired device.
        devices = await discover(2.0, loop=self.loop)
        sought_device = list(
            filter(lambda x: x.address.upper() == self.address.upper(), devices)
        )

        if len(sought_device):
            self._device_info = sought_device[0].details
        else:
            raise BleakError(
                "Device with address {0} was " "not found.".format(self.address)
            )

        logger.debug("Connecting to BLE device @ {0}".format(self.address))

        self._requester = await wrap_IAsyncOperation(
            IAsyncOperation[BluetoothLEDevice](
                BluetoothLEDevice.FromBluetoothAddressAsync(
                    UInt64(self._device_info.BluetoothAddress)
                )
            ),
            return_type=BluetoothLEDevice,
            loop=self.loop,
        )

        def _ConnectionStatusChanged_Handler(sender, args):
            logger.debug("_ConnectionStatusChanged_Handler: " + args.ToString())

        self._requester.ConnectionStatusChanged += _ConnectionStatusChanged_Handler

        # Obtain services, which also leads to connection being established.
        await self.get_services()
        await asyncio.sleep(0.2, loop=self.loop)
        connected = await self.is_connected()
        if connected:
            logger.debug("Connection successful.")
        else:
            raise BleakError(
                "Connection to {0} was not successful!".format(self.address)
            )

        return connected
예제 #3
0
파일: client.py 프로젝트: scsims/bleak
    async def connect(self, **kwargs) -> bool:
        """Connect to the specified GATT server.

        Keyword Args:
            timeout (float): Timeout for required ``BleakScanner.find_device_by_address`` call. Defaults to 10.0.

        Returns:
            Boolean representing connection status.

        """
        # Try to find the desired device.
        if self._device_info is None:
            timeout = kwargs.get("timeout", self._timeout)
            device = await BleakScannerDotNet.find_device_by_address(
                self.address, timeout=timeout)

            if device:
                self._device_info = device.details.BluetoothAddress
            else:
                raise BleakError(
                    "Device with address {0} was not found.".format(
                        self.address))

        logger.debug("Connecting to BLE device @ {0}".format(self.address))

        args = [UInt64(self._device_info)]
        if self._address_type is not None:
            args.append(BluetoothAddressType.Public if self._address_type ==
                        "public" else BluetoothAddressType.Random)
        self._requester = await wrap_IAsyncOperation(
            IAsyncOperation[BluetoothLEDevice](
                BluetoothLEDevice.FromBluetoothAddressAsync(*args)),
            return_type=BluetoothLEDevice,
        )

        # Called on disconnect event or on failure to connect.
        def handle_disconnect():
            if self._connection_status_changed_token:
                self._requester.remove_ConnectionStatusChanged(
                    self._connection_status_changed_token)
                self._connection_status_changed_token = None

            if self._requester:
                self._requester.Dispose()
                self._requester = None

            if self._session:
                self._session.Dispose()
                self._session = None

        def handle_connection_status_changed(
            connection_status: BluetoothConnectionStatus, ):
            if connection_status == BluetoothConnectionStatus.Connected:
                for e in self._connect_events:
                    e.set()

            elif connection_status == BluetoothConnectionStatus.Disconnected:
                if self._disconnected_callback:
                    self._disconnected_callback(self)

                for e in self._disconnect_events:
                    e.set()

                handle_disconnect()

        loop = asyncio.get_event_loop()

        def _ConnectionStatusChanged_Handler(sender, args):
            logger.debug("_ConnectionStatusChanged_Handler: %d",
                         sender.ConnectionStatus)
            loop.call_soon_threadsafe(handle_connection_status_changed,
                                      sender.ConnectionStatus)

        self._connection_status_changed_token = (
            self._requester.add_ConnectionStatusChanged(
                TypedEventHandler[BluetoothLEDevice,
                                  Object](_ConnectionStatusChanged_Handler)))

        # Start a GATT Session to connect
        event = asyncio.Event()
        self._connect_events.append(event)
        try:
            self._session = await wrap_IAsyncOperation(
                IAsyncOperation[GattSession](GattSession.FromDeviceIdAsync(
                    self._requester.BluetoothDeviceId)),
                return_type=GattSession,
            )
            # This keeps the device connected until we dispose the session or
            # until we set MaintainConnection = False.
            self._session.MaintainConnection = True
            await asyncio.wait_for(event.wait(), timeout=10)
        except BaseException:
            handle_disconnect()
            raise
        finally:
            self._connect_events.remove(event)

        await self.get_services()

        return True
예제 #4
0
    async def connect(self, **kwargs) -> bool:
        """Connect to the specified GATT server.

        Keyword Args:
            timeout (float): Timeout for required ``discover`` call. Defaults to 2.0.

        Returns:
            Boolean representing connection status.

        """
        # Try to find the desired device.
        timeout = kwargs.get("timeout", self._timeout)
        devices = await discover(timeout=timeout, loop=self.loop)
        sought_device = list(
            filter(lambda x: x.address.upper() == self.address.upper(),
                   devices))

        if len(sought_device):
            self._device_info = sought_device[0].details
        else:
            raise BleakError("Device with address {0} was "
                             "not found.".format(self.address))

        logger.debug("Connecting to BLE device @ {0}".format(self.address))

        args = [UInt64(self._device_info.BluetoothAddress)]
        if self._address_type is not None:
            args.append(BluetoothAddressType.Public if self._address_type ==
                        "public" else BluetoothAddressType.Random)
        self._requester = await wrap_IAsyncOperation(
            IAsyncOperation[BluetoothLEDevice](
                BluetoothLEDevice.FromBluetoothAddressAsync(*args)),
            return_type=BluetoothLEDevice,
            loop=self.loop,
        )

        def _ConnectionStatusChanged_Handler(sender, args):
            logger.debug("_ConnectionStatusChanged_Handler: " +
                         args.ToString())

        self._requester.ConnectionStatusChanged += _ConnectionStatusChanged_Handler

        # Obtain services, which also leads to connection being established.
        services = await self.get_services()
        connected = False
        if self._services_resolved:
            # If services has been resolved, then we assume that we are connected. This is due to
            # some issues with getting `is_connected` to give correct response here.
            connected = True
        else:
            for _ in range(5):
                await asyncio.sleep(0.2, loop=self.loop)
                connected = await self.is_connected()
                if connected:
                    break

        if connected:
            logger.debug("Connection successful.")
        else:
            raise BleakError("Connection to {0} was not successful!".format(
                self.address))

        return connected
예제 #5
0
    async def connect(self, **kwargs) -> bool:
        """Connect to the specified GATT server.

        Keyword Args:
            timeout (float): Timeout for required ``BleakScanner.find_device_by_address`` call. Defaults to 10.0.

        Returns:
            Boolean representing connection status.

        """
        # Create a new BleakBridge here.
        self._bridge = Bridge()

        # Try to find the desired device.
        if self._device_info is None:
            timeout = kwargs.get("timeout", self._timeout)
            device = await BleakScannerDotNet.find_device_by_address(
                self.address, timeout=timeout)

            if device:
                self._device_info = device.details.BluetoothAddress
            else:
                raise BleakError(
                    "Device with address {0} was not found.".format(
                        self.address))

        logger.debug("Connecting to BLE device @ {0}".format(self.address))

        args = [UInt64(self._device_info)]
        if self._address_type is not None:
            args.append(BluetoothAddressType.Public if self._address_type ==
                        "public" else BluetoothAddressType.Random)
        self._requester = await wrap_IAsyncOperation(
            IAsyncOperation[BluetoothLEDevice](
                BluetoothLEDevice.FromBluetoothAddressAsync(*args)),
            return_type=BluetoothLEDevice,
        )

        loop = asyncio.get_event_loop()

        def _ConnectionStatusChanged_Handler(sender, args):
            logger.debug("_ConnectionStatusChanged_Handler: %d",
                         sender.ConnectionStatus)
            if (sender.ConnectionStatus
                    == BluetoothConnectionStatus.Disconnected
                    and self._disconnected_callback):
                loop.call_soon_threadsafe(self._disconnected_callback, self)

        self._requester.ConnectionStatusChanged += _ConnectionStatusChanged_Handler

        # Obtain services, which also leads to connection being established.
        services = await self.get_services()
        connected = False
        if self._services_resolved:
            # If services has been resolved, then we assume that we are connected. This is due to
            # some issues with getting `is_connected` to give correct response here.
            connected = True
        else:
            for _ in range(5):
                await asyncio.sleep(0.2)
                connected = await self.is_connected()
                if connected:
                    break

        if connected:
            logger.debug("Connection successful.")
        else:
            raise BleakError("Connection to {0} was not successful!".format(
                self.address))

        return connected