def _read_scd_header(self, offset): self._scd_header = Struct(BytesInteger(2, swapped=self._use_little_endian), BytesInteger(2, swapped=self._use_little_endian), 'entry_count' / BytesInteger(2, swapped=self._use_little_endian), BytesInteger(2, swapped=self._use_little_endian), BytesInteger(4, swapped=self._use_little_endian), 'entry_table_offset' / BytesInteger(4, swapped=self._use_little_endian), BytesInteger(4, swapped=self._use_little_endian), BytesInteger(4, swapped=self._use_little_endian), BytesInteger(4, swapped=self._use_little_endian))\ .parse(self._input_buffer[offset:])
def _read_entry_header(self, offset): return Struct('data_size' / BytesInteger(4, swapped=self._use_little_endian), 'channel_count' / BytesInteger(4, swapped=self._use_little_endian), 'frequency' / BytesInteger(4, swapped=self._use_little_endian), 'codec' / BytesInteger(4, swapped=self._use_little_endian), 'loop_start_sample' / BytesInteger(4, swapped=self._use_little_endian), 'loop_end_sample' / BytesInteger(4, swapped=self._use_little_endian), 'samples_offset' / BytesInteger(4, swapped=self._use_little_endian), 'aux_chunk_count' / BytesInteger(2, swapped=self._use_little_endian), BytesInteger(2, swapped=self._use_little_endian))\ .parse(self._input_buffer[offset:])
def __init__(self, swapped: bool = False): """ Utilize :class:`BytesInteger` as :class:`Subconstruct`. :param swapped: invert byte ordering (endianness) """ # subcon = ByteSwapped(Bytes(16)) if swapped else Bytes(16) subcon = BytesInteger(16, False, swapped) super(UUIDAdapter, self).__init__(subcon)
def f(client: LedgerClient) -> DeviceResponse: raw_response = bytes() for idx, each in enumerate(chunk(data, 255)): P1 = 0x00 if idx == 0 else 0x80 raw_response = client.apdu_exchange(INS, each, P1, P2) response_template = Struct( v=BytesInteger(1), r=BytesInteger(32), s=BytesInteger(32), ) parsed_response = response_template.parse(raw_response) return DeviceResponse( v=parsed_response.v, r=parsed_response.r, s=parsed_response.s, )
def __init__(self, octets: Octets, swapped: bool): """ Utilize :class:`BytesInteger` as :class:`Subconstruct`. :param octets: number of bytes for integer :param swapped: invert byte ordering (endianness) :raise ValueError: if neither 48-bit nor 64-bit EUI """ length = EUIOctets(octets) subcon = BytesInteger(length, False, swapped) super(EUIAdapter, self).__init__(subcon)
def __init__(self, filepath): self.filepath = Path(filepath) if not self.filepath.exists(): raise FileNotFoundError(self.filepath) self.oct_header = Struct( "magicNumber" / Hex(Int32un), "version" / Hex(Int16un), "frameheader" / headerField, "framecount" / intField, "linecount" / intField, "linelength" / intField, "sampleformat" / intField, "description" / strField, "xmin" / floatField, "xmax" / floatField, "xcaption" / strField, "ymin" / floatField, "ymax" / floatField, "ycaption" / strField, "scantype" / intField, "scandepth" / floatField, "scanlength" / floatField, "azscanlength" / floatField, "elscanlength" / floatField, "objectdistance" / floatField, "scanangle" / floatField, "scans" / intField, "frames" / intField, "dopplerflag" / intField, "config" / lazyIntField, BytesInteger(4, signed=False, swapped=True)) self.frame_header = Struct( "framedata" / headerField, "framedatetime" / dateField, "frametimestamp" / floatField, "framelines" / intField, "keylength" / Int32un, "key" / PaddedString(this.keylength, "utf8"), "dataLength" / Int32un) self.frame_image = Struct( 'rows' / Computed(this._._.header.linelength.value), 'columns' / Computed(this._.header.framelines.value), 'totalpixels' / Computed(this.rows * this.columns), 'offset' / Tell, 'end' / Computed(this.offset + this.totalpixels * 2), 'pixels' / Lazy(Array(this.totalpixels, Int16un)), Seek(this.end)) self.frame = Struct("header" / self.frame_header, "image" / self.frame_image, BytesInteger(4, signed=False, swapped=True)) self.frame_stack = Array(this.header.framecount.value, self.frame) self.file_structure = Struct("header" / self.oct_header, "data" / self.frame_stack)
def get_frame_format(cls) -> Struct: """ Returns Struct object containing frame structure. """ frame_format = Struct( frame_signature=Bytes(FRAME_SIGNATURE_BYTES_LENGTH), signed_part_of_the_frame=Struct( request_id=BytesInteger(FRAME_REQUEST_ID_BYTES_LENGTH), payload_type=Enum(Byte, PayloadType), payload=Prefixed(VarInt, GreedyBytes), ), ) assert FRAME_PAYLOAD_STARTING_BYTE == ( frame_format.frame_signature.subcon.length + frame_format.signed_part_of_the_frame.request_id.subcon.length + FRAME_PAYLOAD_TYPE_LENGTH ) return frame_format
class AerospikeHeader: # Using construct because it's easier for 48bit integer. FORMAT = Struct( "version" / Const(2, Int8ub), "message_type" / Int8ub, "length" / BytesInteger(6), ) message_type: MessageType length: int def pack(self) -> bytes: return self.FORMAT.build( Container(message_type=self.message_type, length=self.length)) @classmethod def parse(cls: Type["AerospikeHeader"], data: bytes) -> "AerospikeHeader": parsed_data = cls.FORMAT.parse(data) return cls(message_type=parsed_data.message_type, length=parsed_data.length)
from construct import BytesInteger, Const, If, Int8ul, Struct from common import srp from login_server import op_code, router ClientLoginProof = router.ClientPacket.Register( op_code.Client.LOGIN_PROOF, Struct( 'A' / BytesInteger(32, swapped=True), 'M' / BytesInteger(20, swapped=True), 'crc_hash' / BytesInteger(20, swapped=True), 'number_of_keys' / Int8ul, 'security_flags' / Int8ul, )) ServerLoginProof = Struct( 'error' / Int8ul, 'proof' / If( lambda self: self.error == 0, Struct( 'proof' / BytesInteger(20, swapped=True), 'unk1' / Const(int(0).to_bytes(4, 'little')), )), )
import h5py, tempfile headerField = Struct(keylength=Int32un, key=PaddedString(this.keylength, "utf8"), dataLength=Int32un) floatField = Struct(keylength=Int32un, key=PaddedString(this.keylength, "utf8"), dataLength=Int32un, value=Float64n) intField = Struct(keylength=Int32un, key=PaddedString(this.keylength, "utf8"), dataLength=Int32un, value=BytesInteger(this.dataLength, signed=False, swapped=True)) lazyIntField = Struct("keylength" / Int32un, "key" / PaddedString(this.keylength, "utf8"), "dataLength" / Int32un, "offset" / Tell, "end" / Computed(this.offset + this.dataLength), "value" / Lazy(Bytes(this.dataLength)), Seek(this.end)) date = Struct(year=Int16un, month=Int16un, dow=Int16un, day=Int16un, hour=Int16un, minute=Int16un, second=Int16un,
CorrelatedColorTemperature = Struct( "correlated_color_temperature" / DefaultCountValidator(Int16ul, rounding=1, resolution=1)) ChromaticityCoordinates = Struct( "chromaticity_x_coordinate" / DefaultCountValidator(Int16ul, resolution=1 / 0xffff), "chromaticity_y_coordinate" / DefaultCountValidator(Int16ul, resolution=1 / 0xffff)) ColorRenderingIndex = Struct("color_rendering_index" / DefaultCountValidator(Int8sl)) # misc GlobalTradeItemNumber = Struct("global_trade_item_number" / BytesInteger(6, swapped=True)) Appearance = Struct( # TODO: check if correct *EmbeddedBitStruct("_", "category" / BitsInteger(10), "sub_category" / BitsInteger(6), reversed=True)) CountryCode = Struct("country_code" / DefaultCountValidator(Int16ul)) Presence = Struct("presence_detected" / Flag) EventStatistics = Struct( "number_of_events" / Count16, "average_event_duration" / TimeSecond16, "time_elapsed_since_last_event" / TimeExponential8,
Terminated, this ) from .compat import Const # RFC 4251 section 5 SshBytes = Prefixed(Int32ub, GreedyBytes) SshString = PascalString(Int32ub, 'utf8') SshMPInt = Select( Const(0, Int32ub), # zero stored as zero bytes of data FocusedSeq( 'num', 'len' / Rebuild(Int32ub, lambda ctx: int(ctx.num.bit_length() // 8 + 1)), 'num' / BytesInteger(this.len, signed=True), ), ) # RFC 4253 section 6.6 SshRSAKeyBlob = Struct( 'algo' / Const('ssh-rsa', SshString), 'e' / SshMPInt, 'n' / SshMPInt, Terminated ) # I-D.ietf-curdle-ssh-ed25519, section 4 SshEd25519KeyBlob = Struct( 'algo' / Const('ssh-ed25519', SshString), 'public_key' / SshBytes,
import json import socket import sys from construct import BytesInteger, PascalString listen_queue_length = 10 header_len = 4 LENGTH = BytesInteger(header_len) MESSAGE = PascalString(LENGTH, 'ascii') def write_message(socket, **kwargs): message = json.dumps(kwargs) socket.send(MESSAGE.build(message)) def read_message(socket): header = socket.recv(header_len) length = LENGTH.parse(header) body = socket.recv(length) message = MESSAGE.parse(header + body) return json.loads(message) def one_time_message(addr, **kwargs): """ Parameter addr is a tuple (host, port) to be given to connect. """ sock = socket.socket() sock.connect(addr)
# Night mode query: # 4370 00000000000000000000000000000000 # Set Night mode on 0000-0500 # 436f 01 01 0000 0500 00000000000000000000 # set night mode off 0000-0500 # 436f 00 01 0000 0500 00000000000000000000 # night mode on response 0000-0500 # 4371 01 01 0000 0500 00000000000000000000 # night mode off # 4371 00 01 0000 0500 00000000000000000000 # hex is here the real value, so 1800 = 18:00, 0600 = 06:00 NightMode = "nightmode" / Struct( "state" / Enum(Byte, Off=0x00, On=0x01), "unkn" / Byte, "start_time" / BytesInteger(2), "end_time" / BytesInteger(2), ) # ON MO R G B BR TEMP # max brightness: # 4345 02 01 d6 71 00 00 64 0000 15000000000000 # min brightness: # 4345 02 01 d6 71 00 00 01 0000 15000000000000 # # blue max: # 4345 02 01 00 02 f2 00 64 0000 15000000000000 # # red max: # 4345 01 01 f2 01 00 00 64 0000 15000000000000
ReqCommand = Enum(Byte, CONNECT=0x1, BIND=0x02, UDP_ASSOCIATE=0x03) RespStatus = Enum(Byte, SUCCESS=0x0, GENRAL_FAILURE=0x01, CONNECTION_NOT_ALLOWED=0x02, NETWORK_UNREACHABLE=0x03, HOST_UNREACHABLE=0x04, CONNECTION_REFUSED=0x05, TTL_EXPIRED=0x06, COMMAND_NOT_SUPPORTED=0x07, ADDRESS_TYPE_NOT_SUPPORTED=0x08) AddrType = Enum(Byte, IPV4=0x01, DOMAINNAME=0x03, IPV6=0x04) Requestv4 = Struct("cmd" / Byte, "port" / Int16ub, "addr" / BytesInteger(4), "name" / CString(), "domainname" / If(this.addr == 1, CString())) Responsev4 = Struct( "status" / Byte, "port" / Int16ub, "addr" / BytesInteger(4), ) GreetingRequest = Struct( "version" / OneOf(Int8ub, [4, 5]), Embedded( Switch( this.version, { 0x4:
BytesInteger, Const, Construct, GreedyRange, Int16ub, Int32ub, Struct, this, ) from .crypto import decrypt_bom, encrypt_bom, decrypt_psarc, encrypt_psarc ENTRY = Struct( "md5" / Bytes(16), "zindex" / Int32ub, "length" / BytesInteger(5), "offset" / BytesInteger(5), ) class BOMAdapter(Adapter): def _encode(self, obj, context, path): data = Struct("entries" / ENTRY[context.n_entries], "zlength" / GreedyRange(Int16ub)).build(obj) return encrypt_bom(data) def _decode(self, obj, context, path): data = decrypt_bom(obj) return Struct("entries" / ENTRY[context.n_entries], "zlength" / GreedyRange(Int16ub)).parse(data)
Struct( 'game_name' / PaddedString(4, 'ascii'), 'version_major' / Int8ul, 'version_minor' / Int8ul, 'version_bug' / Int8ul, 'build' / Int16ul, 'platform' / PaddedString(4, 'ascii'), 'os' / PaddedString(4, 'ascii'), 'locale' / PaddedString(4, 'ascii'), 'timezone_offset' / Int32ul, 'ip_address' / Int32ub, 'account_name' / PascalString(Int8ul, 'ascii'), )) ServerLoginChallenge = Struct( 'unk1' / Const(b'\x00'), 'error' / Int8ul, 'challenge' / If( lambda self: self.error == 0, Struct( 'B' / BytesInteger(32, swapped=True), 'g_len' / Const(b'\x01'), 'g' / Const(int(srp.g).to_bytes(1, 'little')), 'N_len' / Const(int(32).to_bytes(1, 'little')), 'N' / Const(int(srp.N).to_bytes(32, 'little')), 'salt' / BytesInteger(32, swapped=True), 'crc_salt' / BytesInteger(16, swapped=True), 'unk2' / Const(b'\x00'), )), )
JOIN = 0 LEAVE = 1 ERROR = 2 CHMOD = 3 CREATE = 4 GETATTR = 5 OPEN = 6 READ = 7 READDIR = 8 UNLINK = 9 WRITE = 10 TAKE = 11 MESSAGE = Struct( 'opcode' / BytesInteger(OPCODE_LEN), 'body' / PascalString(BytesInteger(LEN_FIELD_LEN), 'ascii') ) def read_message(socket): header = socket.recv(3) body = socket.recv(BytesInteger(4).parse(header[1:])) message = MESSAGE.parse(header + body) message['body'] = json.loads(message['body']) return message def write_message(socket, opcode, **kwargs): socket.send(MESSAGE.build(dict(opcode=opcode, body=json.dumps(kwargs)))) def message_addr(addr, opcode, **kwargs): sock = socket(AF_INET, SOCK_STREAM)
def subcon(octets: int, swapped: bool): if octets not in (6, 8): pytest.xfail("neither 48-bit nor 64-bit EUI") return BytesInteger(octets, False, swapped)
from construct import (Bytes, BytesInteger, Compressed, CString, Default, Int32ul, Struct) from world_server import op_code, router ClientAuthSession = router.ClientPacket.Register( op_code.Client.AUTH_SESSION, Struct( 'build_number' / Int32ul, 'unk1' / Default(Int32ul, 0), 'account_name' / CString('ascii'), 'client_seed' / Int32ul, 'client_proof' / BytesInteger(20, swapped=True), 'addon_size' / Int32ul, 'addons' / Compressed( Bytes(lambda this: this.addon_size), 'zlib', level=6, ), ))
Name = Struct( "id" / Byte, "index" / Byte, # convert greeedystring to use this "text" / PascalString(Byte, "ascii"), ) Version = Struct( "currentrunning" / Enum(Byte, App1=0x01, App2=0x02, Candela=0x31), "hw_version" / Int16ub, "sw_version_app1" / Int16ub, "sw_version_app2" / Int16ub, "beacon_version" / Int16ub, ) SerialNumber = Struct("serialno" / BytesInteger(12), ) # REVIEW: Enum34 module should not be used unless absolutely necessary. # For equality use (parsed value) == LampMode.Color (its a string value). # If integer value is not mapped, parsing returns an integer not string. # # YOU NEED TO ADJUST OTHER CODE THAT USES THIS FIELD ALSO. # LampMode = Enum( Byte, Color=0x01, White=0x02, Flow=0x03, )
from construct import Bytes, Padding, Int64ul, Int8ul, BytesInteger from construct import BitsInteger, BitsSwapped, BitStruct, Const, Flag from construct import Struct # Fusion Pools Layout STAKE_INFO_LAYOUT_V4 = Struct( "state" / Int64ul, "nonce" / Int64ul, "poolLpTokenAccount" / Bytes(32), "poolRewardTokenAccount" / Bytes(32), "totalReward" / Int64ul, "perShare" / BytesInteger(16), "perBlock" / Int64ul, "option" / Int8ul, "poolRewardTokenAccountB" / Bytes(32), Padding(7), "totalRewardB" / Int64ul, "perShareB" / BytesInteger(16), "perBlockB" / Int64ul, "lastBlock" / Int64ul, "owner" / Bytes(32)) # RAY Yield Farming STAKE_INFO_LAYOUT = Struct( "state" / Int64ul, "nonce" / Int64ul, "poolLpTokenAccount" / Bytes(32), "poolRewardTokenAccount" / Bytes(32), "owner" / Bytes(32), "feeOwner" / Bytes(32), "feeY" / Int64ul, "feeX" / Int64ul, "totalReward" / Int64ul, "rewardPerShareNet" / BytesInteger(16), "lastBlock" / Int64ul, "rewardPerBlock" / Int64ul) # Serum Open Orders Book ACCOUNT_FLAGS_LAYOUT = BitsSwapped( # Swap to little endian BitStruct( "initialized" / Flag, "market" / Flag, "open_orders" / Flag, "request_queue" / Flag, "event_queue" / Flag, "bids" / Flag, "asks" / Flag,
def timedelta_to_mesh_tai_utc_delta(time_zone: timedelta) -> int: assert (time_zone.total_seconds().is_integer()) return int(time_zone.total_seconds() + TAI_UTC_DELTA_ZERO) def subsecond_to_seconds(subsecond: int) -> float: return subsecond / 256 def seconds_to_subsecond(seconds: float) -> int: return round((seconds - int(seconds)) * 256) Time = Struct( "tai_seconds" / BytesInteger(5, swapped=True), StopIf(this.tai_seconds == 0), "subsecond" / Int8ul, "uncertainty" / Int8ul, *EmbeddedBitStruct("_", "tai_utc_delta" / BitsInteger(15), "time_authority" / Flag, reversed=True), "time_zone_offset" / Int8ul, ) class TimeAdapter(Adapter): def _decode(self, obj, context, path): if obj["tai_seconds"] == 0: return Container(date=None,
https://www.raspberrypi-spy.co.uk/ Created 2020.10.17 by Oliver Schwaneberg """ import time from logging import debug, error, warning import typing as tp from threading import Lock import smbus from construct import Struct, BytesInteger, BitStruct, BitsInteger from pymeterreader.device_lib.base import BaseReader from pymeterreader.device_lib.common import Sample, Device AUX_STRUCT = BitStruct('H4' / BitsInteger(12, True), 'H5' / BitsInteger(12, True)) COMP_PARAM_STRUCT = Struct( 'T1' / BytesInteger(2, False, True), 'T2' / BytesInteger(2, True, True), 'T3' / BytesInteger(2, True, True), 'P1' / BytesInteger(2, False, True), 'P2' / BytesInteger(2, True, True), 'P3' / BytesInteger(2, True, True), 'P4' / BytesInteger(2, True, True), 'P5' / BytesInteger(2, True, True), 'P6' / BytesInteger(2, True, True), 'P7' / BytesInteger(2, True, True), 'P8' / BytesInteger(2, True, True), 'P9' / BytesInteger(2, True, True), 'H1' / BytesInteger(1, False), 'H2' / BytesInteger(2, True, True), 'H3' / BytesInteger(1, False), 'bitfield' / BitStruct( 'n1' / BitsInteger(4), 'n2' / BitsInteger(4), 'n3' / BitsInteger(4), 'n4' / BitsInteger(4), 'n5' / BitsInteger(4), 'n6' / BitsInteger(4)), 'H6' / BytesInteger(1, False)) class Bme280Reader(BaseReader): """ Polls meters with plain text output via
def read_message(socket): header = socket.recv(3) body = socket.recv(BytesInteger(4).parse(header[1:])) message = MESSAGE.parse(header + body) message['body'] = json.loads(message['body']) return message
def timedelta_to_mesh_tai_utc_delta(time_zone: timedelta) -> int: assert (time_zone.total_seconds().is_integer()) return int(time_zone.total_seconds() + TAI_UTC_DELTA_ZERO) def subsecond_to_seconds(subsecond: int) -> float: return subsecond / 256 def seconds_to_subsecond(seconds: float) -> int: return round((seconds - int(seconds)) * 256) TimeMinimal = Struct("tai_seconds" / BytesInteger(5, swapped=True), ) TimeOptional = Struct( "tai_seconds" / BytesInteger(5, swapped=True), StopIf(this.tai_seconds == 0), "subsecond" / Int8ul, "uncertainty" / Int8ul, *EmbeddedBitStruct("_", "tai_utc_delta" / BitsInteger(15), "time_authority" / Flag, reversed=True), "time_zone_offset" / Int8ul, ) Time = NamedSelect( optional=TimeOptional,
Name = "name" / Struct( "id" / Byte, "index" / Byte, # convert greeedystring to use this "text" / PascalString(Byte, "ascii"), ) Version = "version" / Struct( "currentrunning" / Enum(Byte, App1=0x01, App2=0x02, Candela=0x31), "hw_version" / Int16ub, "sw_version_app1" / Int16ub, "sw_version_app2" / Int16ub, "beacon_version" / Int16ub, ) SerialNumber = "serialno" / BytesInteger(12) OnOff = "OnOff" / Struct("state" / Mapping(Byte, {True: 0x01, False: 0x02})) # brightness max # 4342 64 000000000000000000000000000000 # brightness min # 4342 01 000000000000000000000000000000 # brightness middle # 4342 31 000000000000000000000000000000 # 1-100 Brightness = "brightness" / Struct("brightness" / Int8ub, ) # Note, requests with (mostly) even, responses with odd
def subcon(swapped: bool) -> Construct: return BytesInteger(16, False, swapped)
from construct import Pass, Prefixed, PrefixedArray from construct import Sequence from construct import Struct TUPLE_DATA = "tuple_data" NAMED_TUPLE_FIELD_ERROR = ValueError("TupleStruct cannot have named fields") UNNAMED_SUBCON_ERROR = ValueError("CStruct fields and enum variants must be named") NON_STR_NAME_ERROR = ValueError("Names must be strings.") TUPLE_DATA_NAME_ERROR = ValueError( f"The name {TUPLE_DATA} is reserved. If you encountered this " "error it's either a wild coincidence or you're " "doing it wrong." # noqa: C812 ) UNDERSCORE_NAME_ERROR = ValueError("names cannot start with an underscore.") U128 = BytesInteger(16, signed=False, swapped=True) I128 = BytesInteger(16, signed=True, swapped=True) class TupleStruct(Sequence): """Python implementation of Rust tuple struct.""" def __init__(self, *subcons) -> None: super().__init__(*subcons) # type: ignore for subcon in self.subcons: if subcon.name is not None: raise NAMED_TUPLE_FIELD_ERROR class CStruct(Struct): """Python implementation of Rust C-like struct."""
"correlated_color_temperature" / DefaultCountValidator(Int16ul, rounding=1, resolution=1) ) ChromaticityCoordinates = Struct( "chromaticity_x_coordinate" / DefaultCountValidator(Int16ul, resolution=1/0xffff, unknown_value=False), "chromaticity_y_coordinate" / DefaultCountValidator(Int16ul, resolution=1/0xffff, unknown_value=False) ) ColorRenderingIndex = Struct( "color_rendering_index" / DefaultCountValidator(Int8sl, unknown_value=False) ) # misc GlobalTradeItemNumber = Struct( "global_trade_item_number" / BytesInteger(6, swapped=True) ) Appearance = Struct( # TODO: check if correct *EmbeddedBitStruct( "_", "category" / BitsInteger(10), "sub_category" / BitsInteger(6), reversed=True ) ) CountryCode = Struct( "country_code" / DefaultCountValidator(Int16ul) )