|
| 1 | +# The MIT License (MIT) |
| 2 | +# |
| 3 | +# Copyright (c) 2016 Adafruit Industries |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | +# |
| 12 | +# The above copyright notice and this permission notice shall be included in |
| 13 | +# all copies or substantial portions of the Software. |
| 14 | +# |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 21 | +# THE SOFTWARE. |
| 22 | +import ustruct |
| 23 | + |
| 24 | + |
| 25 | +class Struct: |
| 26 | + """ |
| 27 | + Arbitrary structure register that is readable and writeable. |
| 28 | +
|
| 29 | + Values are tuples that map to the values in the defined struct. See struct |
| 30 | + module documentation for struct format string and its possible value types. |
| 31 | +
|
| 32 | + :param int register_address: The register address to read the bit from |
| 33 | + :param type struct_format: The struct format string for this register. |
| 34 | + """ |
| 35 | + def __init__(self, register_address, struct_format): |
| 36 | + self.format = struct_format |
| 37 | + self.buffer = bytearray(1+ustruct.calcsize(self.format)) |
| 38 | + self.buffer[0] = register_address |
| 39 | + |
| 40 | + def __get__(self, obj, objtype=None): |
| 41 | + with obj.i2c_device: |
| 42 | + obj.i2c_device.writeto(self.buffer, end=1, stop=False) |
| 43 | + obj.i2c_device.readfrom_into(self.buffer, start=1) |
| 44 | + return ustruct.unpack_from(self.format, memoryview(self.buffer)[1:]) |
| 45 | + |
| 46 | + def __set__(self, obj, value): |
| 47 | + struct.pack_into(self.format, self.buffer, 1, *value) |
| 48 | + with obj.i2c_device: |
| 49 | + obj.i2c_device.writeto(self.buffer) |
0 commit comments