# Copyright (c) 2019 and onward National Institute for Subatomic Physics Nikhef
# SPDX-License-Identifier: MIT
[docs]
class Field:
def __init__(self, size, offset):
self.offset = offset
self.len = len
self._mask = ((1 << size) - 1) << offset
def __set__(self, obj, val):
obj.word = (obj.word & ~self._mask) | ((val << self.offset) & self._mask)
def __get__(self, obj, objtype=None):
if obj is None:
return None
return (obj.word & self._mask) >> self.offset
[docs]
class BitField:
"""
A BitField is an abstraction to get/set bit-fields on a word. Its used as an super-class for a descriptior
class describing a bitfield for a specific register or word.
For example the Timepix4 pixel configuration byte can be defined as follows:
class PixelConfig(BitField):
mask = Field(1, 7)
tp_enable = Field(1, 6)
power_enable = Field(1, 5)
dac = Field(5, 0)
"""
def __init__(self, *vargs, **kwargs):
"""
Initialize a BitField
A Single positional argument is accepted, and set to be the word value.
"""
if self.__class__ == BitField:
raise RuntimeError("You must create a descriptor sub-class containing 'Field' descriptors")
if len(vargs) == 1:
self.word = vargs[0]
elif len(vargs) > 1:
raise ValueError("Unexpected variable arguments")
else:
self.word = 0
for k, v in kwargs.items():
setattr(self, k, v)
def __str__(self):
name = self.__class__.__name__
values = []
for field in dir(self):
# check if it is also part of the class
if field not in self.__class__.__dict__:
continue
if type(self.__class__.__dict__[field])!=Field:
continue
value = getattr(self, field)
values.append(" %s=%d (%x)" % (field, value, value))
return "{}(\n{}\n)={:x}".format(name, ",\n".join(values), self.word)
[docs]
def short_str(self):
name = self.__class__.__name__
values = []
for field in dir(self):
# check if it is also part of the class
if field not in self.__class__.__dict__:
continue
if type(self.__class__.__dict__[field])!=Field:
continue
value = getattr(self, field)
values.append("%s:%d" % (field, value))
return "{}/{:016x}/{}".format(name, self.word, ",".join(values))