35
35
36
36
class _BoundStructArray :
37
37
"""
38
- Actual array object that `StructArray` constructs on demand for
38
+ Array object that `StructArray` constructs on demand.
39
39
40
40
:param object obj: The device object to bind to. It must have a `i2c_device` attribute
41
41
:param int register_address: The register address to read the bit from
@@ -48,9 +48,9 @@ def __init__(self, obj, register_address, struct_format, count):
48
48
self .obj = obj
49
49
self .count = count
50
50
51
- def _header (self , index ):
51
+ def _get_buffer (self , index ):
52
52
"""Shared bounds checking and buffer creation."""
53
- if index < 0 or index >= self .count :
53
+ if not 0 <= index < self .count :
54
54
raise IndexError ()
55
55
size = struct .calcsize (self .format )
56
56
# We create the buffer every time instead of keeping the buffer (which is 32 bytes at least)
@@ -60,14 +60,14 @@ def _header(self, index):
60
60
return buf
61
61
62
62
def __getitem__ (self , index ):
63
- buf = self ._header (index )
63
+ buf = self ._get_buffer (index )
64
64
with self .obj .i2c_device :
65
65
self .obj .i2c_device .write (buf , end = 1 , stop = False )
66
66
self .obj .i2c_device .readinto (buf , start = 1 )
67
67
return struct .unpack_from (self .format , buf , offset = 1 )
68
68
69
69
def __setitem__ (self , index , value ):
70
- buf = self ._header (index )
70
+ buf = self ._get_buffer (index )
71
71
struct .pack_into (self .format , buf , 1 , * value )
72
72
with self .obj .i2c_device :
73
73
self .obj .i2c_device .write (buf )
@@ -84,6 +84,9 @@ class StructArray:
84
84
Values are tuples that map to the values in the defined struct. See struct
85
85
module documentation for struct format string and its possible value types.
86
86
87
+ .. note:: This assumes the device addresses correspond to 8-bit bytes. This is not suitable for
88
+ devices with registers of other widths such as 16-bit.
89
+
87
90
:param int register_address: The register address to begin reading the array from
88
91
:param str struct_format: The struct format string for this register.
89
92
:param int count: Number of elements in the array
@@ -92,7 +95,7 @@ def __init__(self, register_address, struct_format, count):
92
95
self .format = struct_format
93
96
self .address = register_address
94
97
self .count = count
95
- self .array_id = "_structarray" + str (register_address )
98
+ self .array_id = "_structarray{}" . format (register_address )
96
99
97
100
def __get__ (self , obj , objtype = None ):
98
101
# We actually can't handle the indexing ourself due to data descriptor limits. So, we return
@@ -103,6 +106,3 @@ def __get__(self, obj, objtype=None):
103
106
setattr (obj , self .array_id ,
104
107
_BoundStructArray (obj , self .address , self .format , self .count ))
105
108
return getattr (obj , self .array_id )
106
-
107
- def __set__ (self , obj , value ):
108
- raise RuntimeError ()
0 commit comments