コード例 #1
0
ファイル: client.py プロジェクト: cHemingway/bleak
    async def write_gatt_descriptor(self, handle: int, data: bytearray) -> None:
        """Perform a write operation on the specified GATT descriptor.

        Args:
            handle (int): The handle of the descriptor to read from.
            data (bytes or bytearray): The data to send.

        """
        descriptor = self.services.get_descriptor(handle)
        if not descriptor:
            raise BleakError("Descriptor {0} was not found!".format(handle))

        writer = DataWriter()
        writer.WriteBytes(Array[Byte](data))
        write_result = await wrap_IAsyncOperation(
            IAsyncOperation[GattWriteResult](
                descriptor.obj.WriteValueAsync(writer.DetachBuffer())
            ),
            return_type=GattWriteResult,
            loop=self.loop,
        )
        if write_result.Status == GattCommunicationStatus.Success:
            logger.debug("Write Descriptor {0} : {1}".format(handle, data))
        else:
            raise BleakError(
                "Could not write value {0} to descriptor {1}: {2}".format(
                    data, descriptor.uuid, write_result.Status
                )
            )
コード例 #2
0
ファイル: client.py プロジェクト: tlongeri/bleak
    async def write_gatt_char(self,
                              _uuid: str,
                              data: bytearray,
                              response: bool = False) -> None:
        """Perform a write operation of the specified GATT characteristic.

        Args:
            _uuid (str or UUID): The uuid of the characteristics to write to.
            data (bytes or bytearray): The data to send.
            response (bool): If write-with-response operation should be done. Defaults to `False`.

        """
        characteristic = self.services.get_characteristic(str(_uuid))
        if not characteristic:
            raise BleakError("Characteristic {0} was not found!".format(_uuid))

        writer = DataWriter()
        writer.WriteBytes(Array[Byte](data))
        response = (GattWriteOption.WriteWithResponse
                    if response else GattWriteOption.WriteWithoutResponse)
        write_result = await wrap_IAsyncOperation(
            IAsyncOperation[GattWriteResult](
                characteristic.obj.WriteValueWithResultAsync(
                    writer.DetachBuffer(), response)),
            return_type=GattWriteResult,
            loop=self.loop,
        )
        if write_result.Status == GattCommunicationStatus.Success:
            logger.debug("Write Characteristic {0} : {1}".format(_uuid, data))
        else:
            raise BleakError(
                "Could not write value {0} to characteristic {1}: {2}".format(
                    data, characteristic.uuid, write_result.Status))
コード例 #3
0
ファイル: client.py プロジェクト: satyajitghana/bleak
    async def write_gatt_char(
        self,
        char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
        data: bytearray,
        response: bool = False,
    ) -> None:
        """Perform a write operation of the specified GATT characteristic.

        Args:
            char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to write
                to, specified by either integer handle, UUID or directly by the
                BleakGATTCharacteristic object representing it.
            data (bytes or bytearray): The data to send.
            response (bool): If write-with-response operation should be done. Defaults to `False`.

        """
        if not isinstance(char_specifier, BleakGATTCharacteristic):
            characteristic = self.services.get_characteristic(char_specifier)
        else:
            characteristic = char_specifier
        if not characteristic:
            raise BleakError(
                "Characteristic {} was not found!".format(char_specifier))

        writer = DataWriter()
        writer.WriteBytes(Array[Byte](data))
        response = (GattWriteOption.WriteWithResponse
                    if response else GattWriteOption.WriteWithoutResponse)
        write_result = await wrap_IAsyncOperation(
            IAsyncOperation[GattWriteResult](
                characteristic.obj.WriteValueWithResultAsync(
                    writer.DetachBuffer(), response)),
            return_type=GattWriteResult,
            loop=self.loop,
        )
        if write_result.Status == GattCommunicationStatus.Success:
            logger.debug("Write Characteristic {0} : {1}".format(
                characteristic.uuid, data))
        else:
            if write_result.Status == GattCommunicationStatus.ProtocolError:
                raise BleakError(
                    "Could not write value {0} to characteristic {1}: {2} (Error: 0x{3:02X})"
                    .format(
                        data,
                        characteristic.uuid,
                        _communication_statues.get(write_result.Status, ""),
                        write_result.ProtocolError,
                    ))
            else:
                raise BleakError(
                    "Could not write value {0} to characteristic {1}: {2}".
                    format(
                        data,
                        characteristic.uuid,
                        _communication_statues.get(write_result.Status, ""),
                    ))
コード例 #4
0
    def read_characteristic(self, sender: GattLocalCharacteristic,
                            args: GattReadRequestedEventArgs):
        """
        The is triggered by pythonnet when windows receives a read request for
        a given characteristic

        Parameters
        ----------
        sender : GattLocalCharacteristic
            The characteristic Gatt object whose value was requested
        args : GattReadRequestedEventArgs
            Arguments for the read request
        """
        logger.debug("Reading Characteristic")
        deferral: Deferral = args.GetDeferral()
        value: bytearray = self.read_request(str(sender.Uuid))
        logger.debug(f"Current Characteristic value {value}")
        value = value if value is not None else b"\x00"
        writer: DataWriter = DataWriter()
        writer.WriteBytes(value)
        logger.debug("Getting request object {}".format(self))
        request: GattReadRequest = sync_async_wrap(GattReadRequest,
                                                   args.GetRequestAsync)
        logger.debug("Got request object {}".format(request))
        request.RespondWithValue(writer.DetachBuffer())
        deferral.Complete()
コード例 #5
0
class BleakDataWriter:
    def __init__(self, data):
        self.data = data

    def __enter__(self):
        self.writer = DataWriter()
        self.writer.WriteBytes(Array[Byte](self.data))
        return self

    def detach_buffer(self):
        return self.writer.DetachBuffer()

    def __exit__(self, exc_type, exc_val, exc_tb):
        try:
            self.writer.Dispose()
        except Exception:
            pass
        del self.writer
        self.writer = None
コード例 #6
0
 def read(sender: GattLocalCharacteristic,
          args: GattReadRequestedEventArgs):
     deferral: Deferral = args.GetDeferral()
     value = self.val
     writer: DataWriter = DataWriter()
     writer.WriteBytes(value)
     request: GattReadRequest = sync_async_wrap(GattReadRequest,
                                                args.GetRequestAsync)
     request.RespondWithValue(writer.DetachBuffer())
     deferral.Complete()
コード例 #7
0
 def __enter__(self):
     self.writer = DataWriter()
     self.writer.WriteBytes(Array[Byte](self.data))
     return self