Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

only use __bytes__ when not argument is needed. #600

Merged
merged 1 commit into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/hci_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def host_to_controller_filter(hci_packet):
return_parameters=bytes([hci.HCI_SUCCESS]),
)
# Return a packet with 'respond to sender' set to True
return (response.to_bytes(), True)
return (bytes(response), True)

return None

Expand Down
5 changes: 1 addition & 4 deletions bumble/att.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,9 +291,6 @@ def __init__(self, pdu=None, **kwargs):
def init_from_bytes(self, pdu, offset):
return HCI_Object.init_from_bytes(self, pdu, offset, self.fields)

def to_bytes(self):
return self.pdu

@property
def is_command(self):
return ((self.op_code >> 6) & 1) == 1
Expand All @@ -303,7 +300,7 @@ def has_authentication_signature(self):
return ((self.op_code >> 7) & 1) == 1

def __bytes__(self):
return self.to_bytes()
return self.pdu

def __str__(self):
result = color(self.name, 'yellow')
Expand Down
4 changes: 2 additions & 2 deletions bumble/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ def send_hci_packet(self, packet):
f'{color("CONTROLLER -> HOST", "green")}: {packet}'
)
if self.host:
self.host.on_packet(packet.to_bytes())
self.host.on_packet(bytes(packet))

# This method allows the controller to emulate the same API as a transport source
async def wait_for_termination(self):
Expand Down Expand Up @@ -1192,7 +1192,7 @@ def on_hci_read_bd_addr_command(self, _command):
See Bluetooth spec Vol 4, Part E - 7.4.6 Read BD_ADDR Command
'''
bd_addr = (
self._public_address.to_bytes()
bytes(self._public_address)
if self._public_address is not None
else bytes(6)
)
Expand Down
3 changes: 0 additions & 3 deletions bumble/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1624,9 +1624,6 @@ def __bytes__(self):
[bytes([len(x[1]) + 1, x[0]]) + x[1] for x in self.ad_structures]
)

def to_bytes(self) -> bytes:
return bytes(self)

def to_string(self, separator=', '):
return separator.join(
[AdvertisingData.ad_data_to_string(x[0], x[1]) for x in self.ad_structures]
Expand Down
2 changes: 1 addition & 1 deletion bumble/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -1986,7 +1986,7 @@ def find_connection_by_bd_addr(
check_address_type: bool = False,
) -> Optional[Connection]:
for connection in self.connections.values():
if connection.peer_address.to_bytes() == bd_addr.to_bytes():
if bytes(connection.peer_address) == bytes(bd_addr):
if (
check_address_type
and connection.peer_address.address_type != bd_addr.address_type
Expand Down
2 changes: 1 addition & 1 deletion bumble/gatt.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ class IncludedServiceDeclaration(Attribute):

def __init__(self, service: Service) -> None:
declaration_bytes = struct.pack(
'<HH2s', service.handle, service.end_group_handle, service.uuid.to_bytes()
'<HH2s', service.handle, service.end_group_handle, bytes(service.uuid)
)
super().__init__(
GATT_INCLUDE_ATTRIBUTE_TYPE, Attribute.READABLE, declaration_bytes
Expand Down
6 changes: 3 additions & 3 deletions bumble/gatt_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ async def send_command(self, command: ATT_PDU) -> None:
logger.debug(
f'GATT Command from client: [0x{self.connection.handle:04X}] {command}'
)
self.send_gatt_pdu(command.to_bytes())
self.send_gatt_pdu(bytes(command))

async def send_request(self, request: ATT_PDU):
logger.debug(
Expand All @@ -310,7 +310,7 @@ async def send_request(self, request: ATT_PDU):
self.pending_request = request

try:
self.send_gatt_pdu(request.to_bytes())
self.send_gatt_pdu(bytes(request))
response = await asyncio.wait_for(
self.pending_response, GATT_REQUEST_TIMEOUT
)
Expand All @@ -328,7 +328,7 @@ def send_confirmation(self, confirmation: ATT_Handle_Value_Confirmation) -> None
f'GATT Confirmation from client: [0x{self.connection.handle:04X}] '
f'{confirmation}'
)
self.send_gatt_pdu(confirmation.to_bytes())
self.send_gatt_pdu(bytes(confirmation))

async def request_mtu(self, mtu: int) -> int:
# Check the range
Expand Down
4 changes: 2 additions & 2 deletions bumble/gatt_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ def send_response(self, connection: Connection, response: ATT_PDU) -> None:
logger.debug(
f'GATT Response from server: [0x{connection.handle:04X}] {response}'
)
self.send_gatt_pdu(connection.handle, response.to_bytes())
self.send_gatt_pdu(connection.handle, bytes(response))

async def notify_subscriber(
self,
Expand Down Expand Up @@ -450,7 +450,7 @@ async def indicate_subscriber(
)

try:
self.send_gatt_pdu(connection.handle, indication.to_bytes())
self.send_gatt_pdu(connection.handle, bytes(indication))
await asyncio.wait_for(pending_confirmation, GATT_REQUEST_TIMEOUT)
except asyncio.TimeoutError as error:
logger.warning(color('!!! GATT Indicate timeout', 'red'))
Expand Down
40 changes: 8 additions & 32 deletions bumble/hci.py
Original file line number Diff line number Diff line change
Expand Up @@ -1496,14 +1496,11 @@ def parse_from_bytes(cls, data: bytes, offset: int) -> tuple[int, CodingFormat]:
def from_bytes(cls, data: bytes) -> CodingFormat:
return cls.parse_from_bytes(data, 0)[1]

def to_bytes(self) -> bytes:
def __bytes__(self) -> bytes:
return struct.pack(
'<BHH', self.codec_id, self.company_id, self.vendor_specific_codec_id
)

def __bytes__(self) -> bytes:
return self.to_bytes()


# -----------------------------------------------------------------------------
class HCI_Constant:
Expand Down Expand Up @@ -1720,7 +1717,7 @@ def serialize_field(field_value, field_type):
field_length = len(field_bytes)
field_bytes = bytes([field_length]) + field_bytes
elif isinstance(field_value, (bytes, bytearray)) or hasattr(
field_value, 'to_bytes'
field_value, '__bytes__'
):
field_bytes = bytes(field_value)
if isinstance(field_type, int) and 4 < field_type <= 256:
Expand Down Expand Up @@ -1765,7 +1762,7 @@ def dict_to_bytes(hci_object, fields):
def from_bytes(cls, data, offset, fields):
return cls(fields, **cls.dict_from_bytes(data, offset, fields))

def to_bytes(self):
def __bytes__(self):
return HCI_Object.dict_to_bytes(self.__dict__, self.fields)

@staticmethod
Expand Down Expand Up @@ -1860,9 +1857,6 @@ def format_fields(hci_object, fields, indentation='', value_mappers=None):
for field_name, field_value in field_strings
)

def __bytes__(self):
return self.to_bytes()

def __init__(self, fields, **kwargs):
self.fields = fields
self.init_from_fields(self, fields, kwargs)
Expand Down Expand Up @@ -2037,9 +2031,6 @@ def is_resolvable(self):
def is_static(self):
return self.is_random and (self.address_bytes[5] >> 6 == 3)

def to_bytes(self):
return self.address_bytes

def to_string(self, with_type_qualifier=True):
'''
String representation of the address, MSB first, with an optional type
Expand All @@ -2051,7 +2042,7 @@ def to_string(self, with_type_qualifier=True):
return result + '/P'

def __bytes__(self):
return self.to_bytes()
return self.address_bytes

def __hash__(self):
return hash(self.address_bytes)
Expand Down Expand Up @@ -2257,16 +2248,13 @@ def __init__(self, op_code=-1, parameters=None, **kwargs):
self.op_code = op_code
self.parameters = parameters

def to_bytes(self):
def __bytes__(self):
parameters = b'' if self.parameters is None else self.parameters
return (
struct.pack('<BHB', HCI_COMMAND_PACKET, self.op_code, len(parameters))
+ parameters
)

def __bytes__(self):
return self.to_bytes()

def __str__(self):
result = color(self.name, 'green')
if fields := getattr(self, 'fields', None):
Expand Down Expand Up @@ -5190,13 +5178,10 @@ def __init__(self, event_code=-1, parameters=None, **kwargs):
self.event_code = event_code
self.parameters = parameters

def to_bytes(self):
def __bytes__(self):
parameters = b'' if self.parameters is None else self.parameters
return bytes([HCI_EVENT_PACKET, self.event_code, len(parameters)]) + parameters

def __bytes__(self):
return self.to_bytes()

def __str__(self):
result = color(self.name, 'magenta')
if fields := getattr(self, 'fields', None):
Expand Down Expand Up @@ -6747,7 +6732,7 @@ def from_bytes(packet: bytes) -> HCI_AclDataPacket:
connection_handle, pb_flag, bc_flag, data_total_length, data
)

def to_bytes(self):
def __bytes__(self):
h = (self.pb_flag << 12) | (self.bc_flag << 14) | self.connection_handle
return (
struct.pack('<BHH', HCI_ACL_DATA_PACKET, h, self.data_total_length)
Expand All @@ -6761,9 +6746,6 @@ def __init__(self, connection_handle, pb_flag, bc_flag, data_total_length, data)
self.data_total_length = data_total_length
self.data = data

def __bytes__(self):
return self.to_bytes()

def __str__(self):
return (
f'{color("ACL", "blue")}: '
Expand Down Expand Up @@ -6797,7 +6779,7 @@ def from_bytes(packet: bytes) -> HCI_SynchronousDataPacket:
connection_handle, packet_status, data_total_length, data
)

def to_bytes(self) -> bytes:
def __bytes__(self) -> bytes:
h = (self.packet_status << 12) | self.connection_handle
return (
struct.pack('<BHB', HCI_SYNCHRONOUS_DATA_PACKET, h, self.data_total_length)
Expand All @@ -6816,9 +6798,6 @@ def __init__(
self.data_total_length = data_total_length
self.data = data

def __bytes__(self) -> bytes:
return self.to_bytes()

def __str__(self) -> str:
return (
f'{color("SCO", "blue")}: '
Expand Down Expand Up @@ -6891,9 +6870,6 @@ def from_bytes(packet: bytes) -> HCI_IsoDataPacket:
)

def __bytes__(self) -> bytes:
return self.to_bytes()

def to_bytes(self) -> bytes:
fmt = '<BHH'
args = [
HCI_ISO_DATA_PACKET,
Expand Down
2 changes: 1 addition & 1 deletion bumble/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def find_connection_by_bd_addr(
check_address_type: bool = False,
) -> Optional[Connection]:
for connection in self.connections.values():
if connection.peer_address.to_bytes() == bd_addr.to_bytes():
if bytes(connection.peer_address) == bytes(bd_addr):
if (
check_address_type
and connection.peer_address.address_type != bd_addr.address_type
Expand Down
10 changes: 2 additions & 8 deletions bumble/l2cap.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,17 +225,14 @@ def from_bytes(data: bytes) -> L2CAP_PDU:

return L2CAP_PDU(l2cap_pdu_cid, l2cap_pdu_payload)

def to_bytes(self) -> bytes:
def __bytes__(self) -> bytes:
header = struct.pack('<HH', len(self.payload), self.cid)
return header + self.payload

def __init__(self, cid: int, payload: bytes) -> None:
self.cid = cid
self.payload = payload

def __bytes__(self) -> bytes:
return self.to_bytes()

def __str__(self) -> str:
return f'{color("L2CAP", "green")} [CID={self.cid}]: {self.payload.hex()}'

Expand Down Expand Up @@ -333,11 +330,8 @@ def __init__(self, pdu=None, **kwargs) -> None:
def init_from_bytes(self, pdu, offset):
return HCI_Object.init_from_bytes(self, pdu, offset, self.fields)

def to_bytes(self) -> bytes:
return self.pdu

def __bytes__(self) -> bytes:
return self.to_bytes()
return self.pdu

def __str__(self) -> str:
result = f'{color(self.name, "yellow")} [ID={self.identifier}]'
Expand Down
Loading
Loading