def test_parse_nested(self): struct = BitStruct("foo", BitField("a", 3), Flag("b"), Padding(3), Nibble("c"), Struct( "bar", Nibble("d"), Bit("e"), )) self.assertEqual( struct.parse(b"\xe1\x1f"), Container(a=7, b=False, bar=Container(d=15, e=1), c=8))
def test_parse(self): struct = BitStruct("foo", BitField("a", 3), Flag("b"), Padding(3), Nibble("c"), BitField("d", 5), ) self.assertEqual(struct.parse(six.b("\xe1\x1f")), Container(a=7, b=False, c=8, d=31))
def test_parse_nested(self): struct = BitStruct("foo", BitField("a", 3), Flag("b"), Padding(3), Nibble("c"), Struct("bar", Nibble("d"), Bit("e"), ) ) self.assertEqual(struct.parse(six.b("\xe1\x1f")), Container(a=7, b=False, bar=Container(d=15, e=1), c=8))
def test(self): struct = BitStruct( "bitstruct", BitField("a", 3), Flag("b"), Padding(3), Nibble("c"), BitField("d", 5), ) self.assertEqual(struct.parse(b"\xe1\x1f"), Container(a=7)(b=False)(c=8)(d=31)) self.assertEqual(struct.build(Container(a=7)(b=False)(c=8)(d=31)), b"\xe1\x1f")
def test_nested(self): struct = BitStruct("bitstruct", BitField("a", 3), Flag("b"), Padding(3), Nibble("c"), Struct( "sub", Nibble("d"), Bit("e"), )) self.assertEqual( struct.parse(b"\xe1\x1f"), Container(a=7)(b=False)(c=8)(sub=Container(d=15)(e=1))) self.assertEqual( struct.build( Container(a=7)(b=False)(c=8)(sub=Container(d=15)(e=1))), b"\xe1\x1f")
def create_xrf_struct(self, control_record): shift = control_record.shift Int32s, BitStructWrapper = { "big": (Int32sb, lambda x: x), "little": (Int32sl, ByteSwapped), }[self.endianness] return FocusedSeq( "data", "data" / DictSegSeq( idx_field=Int32s, subcon=BitStructWrapper( BitStruct( "block" / Default(BitsInteger(21 + shift, signed=True), 0), "is_new" / Default(Flag, False), "is_updated" / Default(Flag, False), "offset" / Default( ExprAdapter( BitsInteger(9 - shift), lambda obj, context: obj << shift, lambda obj, context: obj >> shift, ), 0), )), block_size=127, # Not counting the index field empty_item={}, check_nonempty=lambda item: any([ item.block, item.offset, item.is_new, item.is_updated, ]), ), Terminated, )
def _Status(self): return BitStruct( 'CameraRunning' / Flag, 'MainImuCalibRunning' / Flag, 'AuxiliaryImuCalibRunning' / Flag, 'AuxiliaryConnected' / Flag, 'GpsRunning' / Flag, 'RemoteGpsRunning' / Flag, 'CamNumber01Error' / Flag, 'CamNumber02Error' / Flag, 'CamNumber03Error' / Flag, 'CamNumber04Error' / Flag, 'CamNumber05Error' / Flag, 'CamNumber06Error' / Flag, 'CamNumber07Error' / Flag, 'CamNumber08Error' / Flag, 'CamNumber09Error' / Flag, 'CamNumber10Error' / Flag, 'CamNumber11Error' / Flag, 'CamNumber12Error' / Flag, 'CamNumber13Error' / Flag, 'CamNumber14Error' / Flag, 'CamNumber15Error' / Flag, 'CamNumber16Error' / Flag, # If new flags are defined, the padding should be adjusted. Padding(10), )
def perf_event_header(): return Embedded(Struct(None, Enum(UNInt32("type"), MMAP = 1, LOST = 2, COMM = 3, EXIT = 4, THROTTLE = 5, UNTHROTTLE = 6, FORK = 7, READ = 8, SAMPLE = 9, MMAP2 = 10, RECORD_AUX = 11, ITRACE_START = 12, LOST_SAMPLES = 13, SWITCH = 14, SWITCH_CPU_WIDE = 15, NAMESPACES = 16, KSYMBOL = 17, BPF_EVENT = 18, CGROUP = 19, HEADER_ATTR = 64, HEADER_EVENT_TYPE = 65, TRACING_DATA = 66, HEADER_BUILD_ID = 67, FINISHED_ROUND = 68, ID_INDEX = 69, AUXTRACE_INFO = 70, AUXTRACE = 71, AUXTRACE_ERROR = 72, THREAD_MAP = 73, CPU_MAP = 74, STAT_CONFIG = 75, STAT = 76, STAT_ROUND = 77, EVENT_UPDATE = 78, TIME_CONV = 79, HEADER_FEATURE = 80, COMPRESSED = 81), Embedded(BitStruct(None, Padding(1), Enum(BitField("cpumode", 7), UNKNOWN = 0, KERNEL = 1, USER = 2, HYPERVISOR = 3, GUEST_KERNEL = 4, GUEST_USER = 5), Flag("ext_reserved"), Flag("exact_ip"), Flag("mmap_data"), Padding(5))), UNInt16("size"), If(has_sample_id_all, Pointer(lambda ctx: ctx.start + ctx.size - 8, UNInt64("end_id"))), Value("attr", lookup_event_attr)))
def get_packet_header(): return Struct( "sig_1" / Byte, "sig_2" / Byte, "sig_3" / Byte, "flag" / BitStruct("battery_h" / Byte, "battery_l" / Byte, "rr_error" / Byte, "dummy_4" / Byte, "dummy_3" / Byte, "dummy_2" / Byte, "dummy_1" / Byte, "rr_in_packet" / Byte), "packet_number" / Int32ul)
def EmbeddedBitStruct(name, *args, reversed=False): """ Emulates BitStruct embedding: - for parsing, adds Computed accessor fields to the parent construct, - for building, Rebuild the bit struct using keys passed to the parent NOTE: This is a hack. Do not use unless you absolutely have to. """ bit_struct = BitStruct(*args) if reversed: bit_struct = Reversed(bit_struct) bit_struct.__construct_doc__ = Embedded(Struct(*args)) return (name / Rebuild(bit_struct, dict), ) + \ tuple(i.name / Computed(this[name][i.name]) for i in args if i.name is not None)
def generate_register_ctrl_meas(mode_enum: Bme280SensorMode, temperature_oversampling: int, # noqa: MC0001 pressure_oversampling: int) -> None: # Set temperature oversampling if temperature_oversampling == 16: osrs_t = 0b101 elif temperature_oversampling == 8: osrs_t = 0b100 elif temperature_oversampling == 4: osrs_t = 0b011 elif temperature_oversampling == 2: osrs_t = 0b010 elif temperature_oversampling == 1: osrs_t = 0b001 elif temperature_oversampling == 0: osrs_t = 0b000 else: raise ConfigurationError(f"Pressure oversampling value {temperature_oversampling} is invalid!") # Set pressure oversampling if pressure_oversampling == 16: osrs_p = 0b101 elif pressure_oversampling == 8: osrs_p = 0b100 elif pressure_oversampling == 4: osrs_p = 0b011 elif pressure_oversampling == 2: osrs_p = 0b010 elif pressure_oversampling == 1: osrs_p = 0b001 elif pressure_oversampling == 0: osrs_p = 0b000 else: raise ConfigurationError(f"Pressure oversampling value {pressure_oversampling} is invalid!") # Determine operation mode if mode_enum is Bme280SensorMode.NORMAL: mode = 0b11 elif mode_enum is Bme280SensorMode.FORCED: mode = 0b01 elif mode_enum is Bme280SensorMode.SLEEP: mode = 0b00 else: raise ConfigurationError(f"Measurement mode {mode_enum.name} is undefined!") # Concatenate bit sequences ctrl_meas_struct = BitStruct("osrs_t" / BitsInteger(3), "osrs_p" / BitsInteger(3), "mode" / BitsInteger(2)) ctrl_meas_byte = ctrl_meas_struct.build({"osrs_t": osrs_t, "osrs_p": osrs_p, "mode": mode}) return int.from_bytes(ctrl_meas_byte, endianness)
def get_user_definition(settings): if ( settings.system_options.user_code_length_6 or settings.system_options.user_code_length_flexible ): code = ExprAdapter( Bytes(3), lambda obj, path: binascii.hexlify(obj) .decode() .rstrip("0") .replace("a", "0") or None, lambda obj, path: binascii.unhexlify(obj.replace("0", "a")), ) else: code = ExprAdapter( Bytes(3), lambda obj, path: binascii.hexlify(obj) .decode() .rstrip("0") .replace("a", "0")[:4] or None, lambda obj, path: binascii.unhexlify((obj + obj[:2]).replace("0", "a")), ) return Struct( "code" / code, "options" / BitsSwapped( BitStruct( "type" / Enum(BitsInteger(2), FullMaster=0x3, Master=0x2, Regular=0x0), "duress" / Flag, "bypass" / Flag, "arm_only" / Flag, "stay_instant_arming" / Flag, "force_arming" / Flag, "all_subsystems" / Flag, ) ), "partitions" / BitsSwapped(Bitwise(StatusFlags(8))), "access" / BitStruct("level" / Nibble, "schedule" / Nibble), "access_options" / Bytes(1), "card_serial_number" / Bytes(3), )
def generate_register_config(standby_time: float, irr_filter_coefficient: int) -> int: # Set the standby time if standby_time == 1000: t_sb = 0b101 elif standby_time == 500: t_sb = 0b100 elif standby_time == 250: t_sb = 0b011 elif standby_time == 125: t_sb = 0b010 elif standby_time == 62.5: t_sb = 0b001 elif standby_time == 20: t_sb = 0b111 elif standby_time == 10: t_sb = 0b110 elif standby_time == 0.5: t_sb = 0b000 else: raise ConfigurationError(f"Standby time value {standby_time} is invalid!") # Set irr filter coefficient if irr_filter_coefficient == 16: irr_filter = 0b100 elif irr_filter_coefficient == 8: irr_filter = 0b011 elif irr_filter_coefficient == 4: irr_filter = 0b010 elif irr_filter_coefficient == 2: irr_filter = 0b001 elif irr_filter_coefficient == 0: irr_filter = 0b000 else: raise ConfigurationError(f"IRR filter coefficient value {irr_filter_coefficient} is invalid!") # Disable SPI Interface spi3wire_enable = 0 # Concatenate bit sequences config_byte_struct = BitStruct("t_sb" / BitsInteger(3), "irr_filter" / BitsInteger(3), "spi3wire_enable" / BitsInteger(2)) config_byte = config_byte_struct.build({"t_sb": t_sb, "irr_filter": irr_filter, "spi3wire_enable": spi3wire_enable}) return int.from_bytes(config_byte, endianness)
def ZoneFlags(count, start_index_from=1): return DictArray(count, start_index_from, BitStruct( "_index" / Computed(this._index + start_index_from), "generated_alarm" / Default(Flag, False), "presently_in_alarm" / Default(Flag, False), "activated_entry_delay" / Default(Flag, False), "activated_intellizone_delay" / Default(Flag, False), "bypassed" / Default(Flag, False), "shutted_down" / Default(Flag, False), "tx_delay" / Default(Flag, False), "supervision_trouble" / Default(Flag, False), ))
def _parse_symbol_section(self, section): sh_link = section.sh_link if self.b64: pass else: pass Symbol = Struct( "st_name" / self.Word, "st_value" / self.Addr, "st_size" / self.Word, "st_info" / BitStruct( "st_bind" / BitsInteger(4), "st_type" / BitsInteger(4), ), "st_other" / Int8ul, "symbol_name" / Computed(lambda ctx: self.get_string(sh_link, ctx.st_name)), "st_shndx" / self.Half, "section_name" / Computed(lambda ctx: defs.section_name(ctx.st_shndx)), "hidden" / Computed(lambda ctx: ctx.st_other in (defs.SymbolVisibility.STV_HIDDEN, defs.SymbolVisibility.STV_INTERNAL)), ) """ typedef struct { Elf32_Word st_name; Elf32_Addr st_value; Elf32_Word st_size; unsigned char st_info; unsigned char st_other; Elf32_Half st_shndx; } Elf32_Sym; typedef struct { Elf64_Word st_name; unsigned char st_info; unsigned char st_other; Elf64_Half st_shndx; Elf64_Addr st_value; Elf64_Xword st_size; } Elf64_Sym; """ num_symbols = len(section.image) // Symbol.sizeof() for offset in range(0, len(section.image), Symbol.sizeof()): sym = Symbol.parse(section.image[offset : offset + Symbol.sizeof()]) db_sym = Elf_Symbol(st_name = sym.st_name, st_value = sym.st_value, st_size = sym.st_size, st_bind = sym.st_info.st_bind, st_type = sym.st_info.st_type, st_other = sym.st_other, st_shndx = sym.st_shndx, symbol_name = sym.symbol_name, section_name = sym.section_name, hidden = sym.hidden) self.session.add(db_sym) #print(db_sym) self.session.commit() query = self.session.query(Elf_Symbol) aaa = query.filter(Elf_Symbol.section_name == "SHN_ABS").all() print("SECTIONS", [a.symbol_name for a in aaa])
def _to_pixels(self): pixel_bytes = self.bits.value if self.depth == 32: for i in range(0, len(pixel_bytes), 4): (a, r, g, b) = (ord(x) for x in pixel_bytes[i:i+4]) if a == 0 and (r > 0 or g > 0 or b > 0): a = 255 yield array("B", (r, g, b, a)) elif self.depth == 16: raise NotImplementedError # TODO: depth 16 elif self.depth <= 8: if self.colors: colors = [color.to_rgba_array() for color in self.colors] else: colors = default_colormap() length = len(pixel_bytes) * 8 / self.depth repeater = MetaRepeater(length, Bits("pixels", self.depth)) pixels_construct = BitStruct("", repeater) for pixel in pixels_construct.parse(pixel_bytes).pixels: yield colors[pixel]
def DirEntry(name): return Struct( name, Bytes("name", 8), Bytes("extension", 3), BitStruct("attributes", Flag("unused"), Flag("device"), Flag("archive"), Flag("subDirectory"), Flag("volumeLabel"), Flag("system"), Flag("hidden"), Flag("readonly")), # reserved Padding(10), ULInt16("timeRecorded"), ULInt16("dateRecorded"), ULInt16("firstCluster"), ULInt32("fileSize"))
def LittleEndianBitStruct(*args): """Construct's bit structs read a byte at a time in the order they appear, reading each bit from most to least significant. Alas, this doesn't work at all for a 32-bit bit field, because the bytes are 'backwards' in little-endian files. So this acts as a bit struct, but reverses the order of bytes before reading/writing, so ALL the bits are read from most to least significant. """ return Buffered( BitStruct(*args), encoder=lambda s: s[::-1], decoder=lambda s: s[::-1], resizer=lambda _: _, )
def ModuleTroubles(count, start_index_from=1): return DictArray( count=count, first_index=start_index_from, subcon=BitStruct( "_index" / Computed(this._index + start_index_from), "aux_trouble" / Flag, "battery_fail" / Flag, "ac_trouble" / Flag, "printer_trouble" / Flag, "fail_to_comm" / Flag, "tlm_trouble" / Flag, "rom_error" / Flag, "tamper" / Flag, ), )
def _parse_symbol_section(self, section): sh_link = section.sh_link symbols = [] Symbol = Struct( "st_name" / self.Word, "st_value" / self.Addr, "st_size" / self.Word, "st_info" / BitStruct( "st_bind" / BitsInteger(4), "st_type" / BitsInteger(4), ), "st_other" / Int8ul, "symbol_name" / Computed(lambda ctx: self.get_string(sh_link, ctx.st_name)), "st_shndx" / self.Half, ) symbol_cache = {} num_symbols = len(section.image) // Symbol.sizeof() for offset in range(0, len(section.image), Symbol.sizeof()): sym = Symbol.parse(section.image[offset:offset + Symbol.sizeof()]) section_header = None if sym.st_shndx in defs.SpecialSections: section_name = defs.special_section_name(sym.st_shndx) else: if not sym.st_shndx in symbol_cache: section_header = self.session.query(model.Elf_Section).\ filter(model.Elf_Section.index == sym.st_shndx).first() if section_header: section_name = section_header.section_name else: section_name = str(sym.st_shndx) db_sym = model.Elf_Symbol( st_name=sym.st_name, st_value=sym.st_value, st_size=sym.st_size, st_bind=sym.st_info.st_bind, st_type=sym.st_info.st_type, st_other=sym.st_other, st_shndx=sym.st_shndx, symbol_name=sym.symbol_name, section_name=section_name, access=section_header.sh_flags if section_header else 0) symbols.append(db_sym) self.session.bulk_save_objects(symbols) self.session.commit()
class USBTokenPacket(USBPacket): """ Class representing a token packet. """ FIELDS = {'crc5', 'crc_valid'} DATA_FORMAT = BitsSwapped( BitStruct( "device_address" / BitsInteger(7), "endpoint_number" / BitsInteger(4), "crc5" / BitsInteger(5), )) def validate(self): #parsed = self.parse_data() # TODO: validate crc5 pass def generate_summary(self): return "{} token".format(self.pid.summarize()) def summarize_data(self, summary_length_bytes=8): # NOTE: summary_length_bytes is ignored for a token packet. return "address={}, endpoint=0x{:02x}, direction={}".format( self.device_address, self.endpoint_number, self.direction) def get_detail_fields(self): fields = { 'Length': '{} bytes'.format(len(self.get_raw_data())), 'PID': '{} (0x{:02x})'.format(self.pid.name, self.pid.value), 'Device': '0x{:02x}'.format(self.device_address), 'Endpoint': '0x{:02x}'.format(self.endpoint_number), 'CRC5': '0x{:02x}'.format(self.crc5) } return [(self.generate_summary(), fields)] def get_raw_data(self): # device_address, endpoint, and crc5 are included in self.data. return b''.join([bytes([self.pid]), self.data])
class USBStartOfFrame(USBPacket): """ Class representing a USB start-of-frame (pseudo) packet. """ FIELDS = {'frame_number', 'crc5', 'crc_valid'} DATA_FORMAT = BitsSwapped( BitStruct( "frame_number" / BitsInteger(11), "crc5" / BitsInteger(5), )) def validate(self): #parsed = self.parse_data() # TODO: validate crc5 pass def generate_summary(self): return "{}".format(self.pid.summarize()) def summarize_data(self, summary_length_bytes=8): # NOTE: summary_length_bytes is ignored for a token packet. return "frame={}".format(self.frame_number) def get_detail_fields(self): fields = { 'Length': '{} bytes'.format(len(self.get_raw_data())), 'PID': '{} (0x{:02x})'.format(self.pid.name, self.pid.value), 'Frame Number': '{:0d}'.format(self.frame_number), 'CRC5': '0x{:02x}'.format(self.crc5) } return [(self.generate_summary(), fields)] def get_raw_data(self): # frame number, and crc5 are included in self.data. return b''.join([bytes([self.pid]), self.data])
def create_entry_chunk(): a = Struct( DATEPACKED / BitStruct( "Isfut" / BitsInteger(length=1), "Reserved" / BitsInteger(length=5), "MicroSec" / BitsInteger(length=10), "MilliSec" / BitsInteger(length=10), "Second" / BitsInteger(length=6), "Minute" / BitsInteger(length=6), "Hour" / BitsInteger(length=5), DAY / RevBitsInteger(length=5), MONTH / RevBitsInteger(length=4), YEAR / RevBitsInteger(length=12), # 64bit ), CLOSE / RevFormatField("<", "f"), OPEN / RevFormatField("<", "f"), HIGH / RevFormatField("<", "f"), LOW / RevFormatField("<", "f"), VOLUME / RevFormatField("<", "f"), # 160 "AUX1" / RevFormatField("<", "f"), "AUX2" / RevFormatField("<", "f"), "TERMINATOR" / RevFormatField("<", "f"), ) return a
def perf_event_header(): return Embedded( Struct( None, Enum(UNInt32("type"), MMAP=1, LOST=2, COMM=3, EXIT=4, THROTTLE=5, UNTHROTTLE=6, FORK=7, READ=8, SAMPLE=9, MMAP2=10, TRACING_DATA=66, FINISHED_ROUND=68, ID_INDEX=69, AUXTRACE_INFO=70, AUXTRACE=71, AUXTRACE_ERROR=72), Embedded( BitStruct( None, Padding(1), Enum(BitField("cpumode", 7), UNKNOWN=0, KERNEL=1, USER=2, HYPERVISOR=3, GUEST_KERNEL=4, GUEST_USER=5), Flag("ext_reserved"), Flag("exact_ip"), Flag("mmap_data"), Padding(5))), UNInt16("size"), If( has_sample_id_all, Pointer(lambda ctx: ctx.start + ctx.size - 8, UNInt64("end_id"))), Value("attr", lookup_event_attr)))
def parse_calibration_bytes(calibration_segment1: bytes, calibration_segment2: bytes) -> Bme280CalibrationData: # Parse bytes to container calibration_segment1_container = Bme280Reader.STRUCT_CALIBRATION1.parse(calibration_segment1) calibration_segment2_container = Bme280Reader.STRUCT_CALIBRATION2.parse(calibration_segment2) # Bit order from the sensor does not allow for parsing dig_H4 and dig_h5 inside of a BitStruct with BitsInteger # Required order is 0xE4,0xE5[right 4 Bits],0xE6,0xE5[left 4 Bits] reorder_struct = BitStruct("byte_0xE4" / BitsInteger(8), "bits_0xE5_right" / BitsInteger(4), "byte_OxE6" / BitsInteger(8), "bits_0xE5_left" / BitsInteger(4)) reorder_bitsegments = calibration_segment2_container.pop("misaligned_bitsegment") reorder_bitsegments.pop("_io") # Recreate bytes with correct order reordered_bytes = reorder_struct.build(reorder_bitsegments) # Parse the reordered bytes with a Bitstruct humidity_struct = BitStruct("dig_H4" / BitsInteger(12), "dig_H5" / BitsInteger(12)) # Parse bytes to container humidity_container = humidity_struct.parse(reordered_bytes) # Unpack containers into dataclass calibration_dict = {**calibration_segment1_container, **calibration_segment2_container, **humidity_container} # Remove construct container _io object calibration_dict.pop("_io", None) return Bme280CalibrationData(**calibration_dict)
INDEX_FIELD_ORDER_TYPE_STRUCT = Enum(ULInt16('field_order_type'), ASCENDING=0, DESCENDING=1, _default_='DESCENDING') TABLE_DEFINITION_INDEX_STRUCT = Struct( 'record_table_definition_index', # May be external_filename # if external_filename == 0, no external file index CString('external_filename'), If(lambda x: len(x['external_filename']) == 0, Const(Byte('index_mark'), 1)), CString('name'), Embed( BitStruct('flags', Padding(1), INDEX_TYPE_STRUCT, Padding(2), Flag('NOCASE'), Flag('OPT'), Flag('DUP'))), ULInt16('field_count'), Array( lambda x: x['field_count'], Struct('index_field_propertly', ULInt16('field_number'), INDEX_FIELD_ORDER_TYPE_STRUCT)), ) MEMO_TYPE_STRUCT = Enum(Flag('memo_type'), MEMO=0, BLOB=1) TABLE_DEFINITION_MEMO_STRUCT = Struct( 'record_table_definition_memo', # May be external_filename # if external_filename == 0, no external file index CString('external_filename'), If(lambda x: len(x['external_filename']) == 0, Const(Byte('memo_mark'),
) ) ArapContentGet = Struct( "page" / Int8ul ) ArapContent = Struct( "current_page" / Int8ul, "last_page" / Int8ul, "nodes" / DictAdapter( GreedyRange( ByteSwapped( BitStruct( "sequence" / Bytewise(Int24ub), "ivi" / BitsInteger(1), "address" / BitsInteger(15), ) ) ), key=this.address, value=[this.ivi, this.sequence] ) ) DebugPayload = Struct( "subopcode" / EnumAdapter(Int8ul, DebugSubOpcode), "data" / Default(Switch( this.subopcode, { DebugSubOpcode.RSSI_THRESHOLD_SET: RssiThreshold,
class Color(FixedObject): """A 32-bit RGB color value. Each component r, g, b has a value between 0 and 1023. However, Colors are considered equal if they have the same 8-bit value. """ classID = 30 _construct = BitStruct( "value", Padding(2), Bits("r", 10), Bits("g", 10), Bits("b", 10), ) _construct_32_rgba = Struct( "", UBInt8("r"), UBInt8("g"), UBInt8("b"), UBInt8("alpha"), ) def __init__(self, value): self.value = value def __eq__(self, other): return (isinstance(other, Color) and self.to_8bit() == other.to_8bit()) def __ne__(self, other): return not self == other @classmethod def from_value(cls, value): return cls((value.r, value.g, value.b)) def to_value(self): (r, g, b) = self.value return Container(r=r, g=g, b=b) @classmethod def from_8bit(self, r, g=None, b=None): if g is None and b is None: rgb = r else: rgb = (r, g, b) return Color((x << 2 for x in rgb)) def to_8bit(self): """Returns value with components between 0-255.""" return tuple(x >> 2 for x in self.value) def __repr__(self): return "%s(%s)" % ( self.__class__.__name__, repr(self.value).strip("()"), ) def to_rgba_array(self): (r, g, b) = self.to_8bit() return array('B', (r, g, b, 255)) def to_argb_array(self): (r, g, b) = self.to_8bit() return bytearray((255, r, g, b))
#!/usr/bin/env python from construct import BitStruct, BitsInteger, Padding, Enum, Flag SCB_ICSR = 0xe000ed04 scb_icsr = BitStruct( "NMIPENDSET" / Flag, Padding(2), "PENDSVSET" / Flag, "PENDSVCLR" / Flag, "PENDSTSET" / Flag, "PENDSTCLR" / Flag, Padding(1), "DEBUG" / Flag, "ISRPENDING" / Flag, "VECTPENDING" / BitsInteger(10), "RETOBASE" / Flag, Padding(2), "VECTACTIVE" / BitsInteger(9) ) SCB_SHCSR = 0xe000ed24 scb_shcsr = BitStruct( Padding(13), "USGFAULTENA" / Flag, "BUSFAULTENA" / Flag, "MEMFAULTENA" / Flag, "SVCALLPENDED"/ Flag, "BUSFAULTPENDED" / Flag, "MEMFAULTPENDED" / Flag, "USGFAULTPENDED" / Flag,
UBInt8("op")) HELLO = Struct("hello", UBInt32("padding")) CAPS_C = Struct("cells", UBInt16("pci"), UBInt32("cap"), UBInt16("DL_earfcn"), UBInt8("DL_prbs"), UBInt16("UL_earfcn"), UBInt8("UL_prbs")) CAPS_RESPONSE = Struct("caps_response", BitStruct("flags", Padding(30), Bit("ue_measure"), Bit("ue_report")), UBInt32("nof_cells"), Array(lambda ctx: ctx.nof_cells, CAPS_C)) UE_R = Struct("ues", UBInt16("pci"), Bytes("plmn_id", 4), UBInt16("rnti"), UBInt64("imsi")) UE_REPORT_RESPONSE = Struct("ue_report_response", UBInt32("nof_ues"), Array(lambda ctx: ctx.nof_ues, UE_R)) CAPS_REQUEST = Struct("caps_request",
ERR=0xfe, EV=0xfd, SERV=0xfc, )) DAQ = Struct( "odt" / Byte, "daq" / Byte, "data" / GreedyBytes, ) ResourceType = BitStruct( Padding(2), "dbg" / Flag, "pgm" / Flag, "stim" / Flag, "daq" / Flag, Padding(1), "calpag" / Flag, ) AddressGranularity = Enum(BitsInteger(2), BYTE=0b00, WORD=0b01, DWORD=0b10, RESERVED=0b11) ByteOrder = Enum(BitsInteger(1), INTEL=0, MOTOROLA=1) # byte-order dependent types Int16u = IfThenElse(this._.byteOrder == ByteOrder.INTEL, Int16ul, Int16ub)
ConfigurationSet = Select( static=ConfigurationSetWithOptionalDhcpDisabled, dns=ConfigurationSetWithOptionalDhcpEnabledWithStaticDns, minimal=ConfigurationSetWithoutOptionalAutoDhcpEnabled, ) ConfigurationStatus = Struct( "chip_revision_id" / Int8ul, Embedded(ConfigurationSetWithOptionalDhcpDisabled), "flags" / EnumAdapter(Int8ul, DhcpFlag), "status_code" / EnumAdapter(Int8ul, StatusCode), ) ConnectionState = BitStruct( "conn_state" / EnumAdapter(BitsInteger(3), ConnState), "link_status" / EnumAdapter(BitsInteger(1), LinkStatus), "last_error" / EnumAdapter(BitsInteger(4), LastError)) # GATEWAY PACKETS MSG PacketsStatus = Struct( "total_eth_rx_errors" / Int16ul, "total_eth_tx_errors" / Int16ul, "bandwidth" / Int16ul, "connection_state" / ConnectionState, ) GatewayConfigParams = SwitchStruct( "subopcode" / EnumAdapter(Int8ul, GatewayConfigServerSubOpcode), "payload" / Switch( this.subopcode, {