Skip to content

Modified ManufacturerDataField to return a namedtuple if possible #116

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

Merged
merged 2 commits into from
Jun 9, 2021
Merged
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
9 changes: 8 additions & 1 deletion adafruit_ble/advertising/standard.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"""

import struct
from collections import OrderedDict
from collections import OrderedDict, namedtuple

from . import (
Advertisement,
Expand Down Expand Up @@ -268,6 +268,9 @@ def __init__(self, key, value_format, field_names=None):
)
self._entry_length = struct.calcsize(value_format)
self.field_names = field_names
if field_names:
# Mostly, this is to raise a ValueError if field_names has invalid entries
self.mdf_tuple = namedtuple("mdf_tuple", self.field_names)

def __get__(self, obj, cls):
if obj is None:
Expand All @@ -279,6 +282,10 @@ def __get__(self, obj, cls):
unpacked = struct.unpack_from(self._format, packed)
if self.element_count == 1:
unpacked = unpacked[0]
if self.field_names and len(self.field_names) == len(unpacked):
# If we have field names, we should already have a namedtuple type to use
# Unless the element count is off, which... werid.
return self.mdf_tuple(*unpacked)
return unpacked
if len(packed) % self._entry_length != 0:
raise RuntimeError("Invalid data length")
Expand Down