def setUp(self): self.cons = Struct( 'foo', Enum(Byte("a_enum"), ALFA=1, BETA=2), Switch( 'switch', lambda ctx: ctx.a_enum, { 'ALFA': Embed(Struct('struct_alfa', Byte('byte_alfa'))), 'BETA': Embed(Struct('struct_beta', Byte('byte_beta'))), }))
def nfc_cmd(cmd): return Struct( 'nfc_msg', OneOf(Byte('start'), (NFC_STX, )), OneOf(Byte('device'), NFC_RESPONSE_SET), OneOf(Byte('command'), NFC_COMMAND_SET), UBInt16('len'), String('data', lambda ctx: ctx['len']) if cmd is None else cmd, OneOf(Byte('stop'), (NFC_ETX, )), Embed(crc))
def ResourceRecord(name): return Struct( name, Embed(RRNAME), TYPE, CLASS, TTL, RDLENGTH, RDATA, )
class ColorForm(Form): """A rectangular array of pixels, used for holding images. width, height - dimensions depth - how many bits are used to specify the color at each pixel. bits - a Bitmap with varying internal structure, depending on depth. colors - the colors pointed to by the bits array. (I think?) privateOffset - ? """ classID = 35 _construct = Struct("", Embed(Form._construct), Rename("colors", field), # Array )
def PreDataRegion(name): rde = DirEntry("rootdirs") fe = FatEntry("fats") return Struct(name, Embed(BootSector("bootSector")), # the remaining reserved sectors Padding(lambda ctx: (ctx.reservedSectorCount - 1) * ctx.sectorSize), # file allocation tables Array(lambda ctx: (ctx.fatCount), Array(lambda ctx: ctx.sectorsPerFat * ctx.sectorSize / fe.sizeof(), fe)), # root directories Array(lambda ctx: (ctx.rootdirEntryCount*rde.sizeof()) / ctx.sectorSize, rde))
class TranslucentColor(Color): classID = 31 _construct = Struct( "", Embed(Color._construct), UBInt8("alpha"), # I think. ) _construct_32 = Struct( "", UBInt8("alpha"), UBInt8("r"), UBInt8("g"), UBInt8("b"), ) def __init__(self, value): self.value = value def to_value(self): (r, g, b, alpha) = self.value return Container(r=r, g=g, b=b, alpha=alpha) @classmethod def from_value(cls, value): return cls((value.r, value.g, value.b, value.alpha)) @classmethod def from_32bit_raw_argb(cls, raw): container = cls._construct_32.parse(raw) parts = cls.from_value(container) color = cls(*(x << 2 for x in parts.value)) if color.alpha == 0 and (color.r > 0 or color.g > 0 or color.b > 0): color.alpha = 1023 return color def to_rgba_array(self): return array('B', self.to_8bit()) def to_argb_array(self): (r, g, b, a) = self.to_8bit() return bytearray((a, r, g, b))
""" Snapcast messages. """ from construct import (ULInt8, ULInt16, ULInt32, ULInt64, Embed, Struct, Enum, Array, PascalString, Switch, Container) ENCODING = 'utf-8' BASE_SIZE = 26 # pylint: disable=bad-continuation,invalid-name timestamp = Embed(Struct('time', ULInt32('secs'), ULInt32('usecs') )) snaptype = Enum(ULInt16('type'), Base=0, Header=1, WireChunk=2, SampleFormat=3, ServerSettings=4, Time=5, Request=6, Ack=7, Command=8, Hello=9, Map=10, String=11 )
SLInt32('mac_ap_size'), If(lambda ctx: ctx["mac_ap_size"] > 0, CString("mac_ap")), ) """ handles the ap's mac address used in msg_association """ field_mac_sta = Struct( 'mac_sta', SLInt32('mac_sta_size'), If(lambda ctx: ctx["mac_sta_size"] > 0, CString("mac_sta")), ) """ handles the station's mac address used in msg_association """ msg_association = Struct( 'msg_association', Embed(msg_default), # default fields Embed(field_mac_ap), Embed(field_mac_sta), SLInt8('allowed'), SLInt32('response'), ) """ all association message types are the same, and use msg_association struct to send information """ def get_association(server, id=0, association_type=None, mac_sta=None, mac_ap=None): """ only for tests. the controller don't use this!!!
# construtc imports from construct import Struct, OneOf, Byte, String, Embed # card reader imports from crc import crc # magnetic stripe command markers MS_STX = 0x02 # start of command MS_ETX = 0x03 # end of command # operation modes MS_MODES = (0x31, ) # response codes MS_RESPONSE_STATUS = (0x06, 0x15) # message structure ms_cmd = Struct('ms_msg', OneOf(Byte('start'), (MS_STX, )), OneOf(Byte('mode'), MS_MODES), Byte('track1_id'), Byte('track1_len'), OneOf(Byte('track1_status'), MS_RESPONSE_STATUS), String('track1', lambda ctx: ctx['track1_len']), Byte('track2_id'), Byte('track2_len'), OneOf(Byte('track2_status'), MS_RESPONSE_STATUS), String('track2', lambda ctx: ctx['track2_len']), Byte('track3_id'), Byte('track3_len'), OneOf(Byte('track3_status'), MS_RESPONSE_STATUS), String('track3', lambda ctx: ctx['track3_len']), OneOf(Byte('stop'), (MS_ETX, )), Embed(crc))
def BootSector(name): header = Fat16Header("header") return Struct(name, Embed(header), Padding(lambda ctx: ctx.sectorSize - header.sizeof()))
MetaField("data", lambda context: context["length"]), ), } packets_by_name = { "ping": 0, "disconnect": 255, } infinipacket_parser = Struct( "parser", OptionalGreedyRange( Struct( "packets", Peek(UBInt8("header")), Embed(Switch("packet", lambda context: context["header"], packets)), ), ), OptionalGreedyRange(UBInt8("leftovers"), ), ) def parse_packets(bytestream): container = infinipacket_parser.parse(bytestream) l = [(i.header, i.payload) for i in container.packets] leftovers = "".join(chr(i) for i in container.leftovers) if DUMP_ALL_PACKETS: for packet in l: print "Parsed packet %d" % packet[0] print packet[1]
@requires: construct 2.5.2 """ from construct import SLInt64 from construct import Embed from construct import Struct from construct import Container # from construct.debug import Probe from pox.ethanol.ssl_message.msg_core import msg_default, field_intf_name, field_station from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string msg_sent_received = Struct( 'msg_sent_received', Embed(msg_default), # default fields Embed(field_intf_name), Embed(field_station), SLInt64('value'), # Probe() ) """ message structure common to all supported_messages messages""" supported_messages = [ MSG_TYPE.MSG_GET_BYTESRECEIVED, MSG_TYPE.MSG_GET_BYTESSENT, MSG_TYPE.MSG_GET_BYTESLOST, MSG_TYPE.MSG_GET_PACKETSRECEIVED, MSG_TYPE.MSG_GET_PACKETSSENT, MSG_TYPE.MSG_GET_PACKETSLOST, ]
grounded = Struct("grounded", UBInt8("grounded")) position = Struct("position", BFloat64("x"), BFloat64("y"), BFloat64("stance"), BFloat64("z")) orientation = Struct("orientation", BFloat32("rotation"), BFloat32("pitch")) # TODO: this must be replaced with 'slot' (see below) # Notchian item packing (slot data) items = Struct( "items", SBInt16("primary"), If( lambda context: context["primary"] >= 0, Embed( Struct( "item_information", UBInt8("count"), UBInt16("secondary"), Magic("\xff\xff"), )), ), ) Speed = namedtuple('speed', 'x y z') class Slot(object): def __init__(self, item_id=-1, count=1, damage=0, nbt=None): self.item_id = item_id self.count = count self.damage = damage # TODO: Implement packing/unpacking of gzipped NBT data
from construct import Struct, Array from construct import Container # from construct.debug import Probe from pox.ethanol.ssl_message.msg_core import msg_default from pox.ethanol.ssl_message.msg_core import field_station, field_intf_name, field_mac_addr from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string field_time_stamp = Struct('time_stamp', SLInt32('time_stamp_size'), If(lambda ctx: ctx["time_stamp_size"] > 0, CString("time_stamp")), ) stats_field = Struct('stats', Embed(field_mac_addr), Embed(field_intf_name), SLInt32('inactive_time'), # long SLInt64('rx_bytes'), SLInt64('tx_bytes'), SLInt64('rx_packets'), SLInt64('rx_duration'), SLInt64('tx_packets'), SLInt64('tx_retries'), SLInt64('tx_failed'), SLInt64('beacon_loss'), SLInt64('beacon_rx'), SLInt64('rx_drop_misc'), SLInt32('signal'), SLInt32('signal_avg'), SLInt32('beacon_signal_avg'),
class Bitmap(FixedObjectByteArray): classID = 13 _construct = Struct( "", UBInt32("length"), construct.String("items", lambda ctx: ctx.length * 4), # Identically named "String" class -_- ) @classmethod def from_value(cls, obj): return cls(obj.items) def to_value(self): value = self.value length = (len(value) + 3) / 4 value += "\x00" * (length * 4 - len(value)) # padding return Container(items=value, length=length) _int = Struct( "int", UBInt8("_value"), If( lambda ctx: ctx._value > 223, IfThenElse( "", lambda ctx: ctx._value <= 254, Embed( Struct( "", UBInt8("_second_byte"), Value( "_value", lambda ctx: (ctx._value - 224) * 256 + ctx._second_byte), )), Embed(Struct( "", UBInt32("_value"), )))), ) _length_run_coding = Struct( "", Embed(_int), #ERROR? Value("length", lambda ctx: ctx._value), OptionalGreedyRepeater( Struct( "data", Embed(_int), Value("data_code", lambda ctx: ctx._value % 4), Value("run_length", lambda ctx: (ctx._value - ctx.data_code) / 4), Switch( "", lambda ctx: ctx.data_code, { 0: Embed( Struct( "", StrictRepeater( get_run_length, Value("pixels", lambda ctx: "\x00\x00\x00\x00")), )), 1: Embed( Struct( "", Bytes("_b", 1), StrictRepeater( get_run_length, Value("pixels", lambda ctx: ctx._b * 4), ), )), 2: Embed( Struct( "", Bytes("_pixel", 4), StrictRepeater( get_run_length, Value("pixels", lambda ctx: ctx._pixel), ), )), 3: Embed( Struct( "", StrictRepeater( get_run_length, Bytes("pixels", 4), ), )), }), ))) @classmethod def from_byte_array(cls, bytes_): """Decodes a run-length encoded ByteArray and returns a Bitmap. The ByteArray decompresses to a sequence of 32-bit values, which are stored as a byte string. (The specific encoding depends on Form.depth.) """ runs = cls._length_run_coding.parse(bytes_) pixels = (run.pixels for run in runs.data) data = "".join(itertools.chain.from_iterable(pixels)) return cls(data) def compress(self): """Compress to a ByteArray""" raise NotImplementedError
TunnelAdapter( PascalString("alpn_protocols", length_field=UBInt16("length")), TunnelAdapter(PascalString("", length_field=UBInt16("length")), GreedyRange(PascalString("name"))), ), ) UnknownExtension = Struct( "", PascalString("bytes", length_field=UBInt16("extensions_length"))) Extension = Struct( "Extension", UBInt16("type"), Embed( Switch("", lambda ctx: ctx.type, { 0x00: SNIExtension, 0x10: ALPNExtension }, default=UnknownExtension))) extensions = TunnelAdapter( PascalString("extensions", length_field=UBInt16("extensions_length")), OptionalGreedyRange(Extension)) ClientHello = Struct( "ClientHello", ProtocolVersion, Random, SessionID, CipherSuites, CompressionMethods,
# Flying, position, and orientation, reused in several places. grounded = Struct("grounded", UBInt8("grounded")) position = Struct("position", BFloat64("x"), BFloat64("y"), BFloat64("stance"), BFloat64("z")) orientation = Struct("orientation", BFloat32("rotation"), BFloat32("pitch")) # Notchian item packing items = Struct( "items", SBInt16("primary"), If( lambda context: context["primary"] >= 0, Embed( Struct( "item_information", UBInt8("count"), UBInt16("secondary"), )), ), ) Metadata = namedtuple("Metadata", "type value") metadata_types = ["byte", "short", "int", "float", "string", "slot", "coords"] # Metadata adaptor. class MetadataAdapter(Adapter): def _decode(self, obj, context): d = {} for m in obj.data: d[m.id.second] = Metadata(metadata_types[m.id.first], m.value)
"voto", Bytes("len_ubic", 2), Bytes("ubicacion", lambda ctx: int(ctx.len_ubic)), Bytes("cod_interna", len_cods.get('interna')), GreedyRange( Struct("voto_categoria", Bytes("cod_categoria", len_cods.get('categoria')), Bytes("cod_candidatura", len_cods.get('candidato'))))) struct_recuento = Struct( "Recuento", Bytes("por_categoria", 1), If(lambda ctx: ctx.por_categoria == "1", Bytes("cod_categoria", len_cods.get('categoria'))), GreedyRange(Bytes("datos", 1))) struct_recuento_dni = Struct( "Recuento con dni", Array(11, Bytes("documentos", 1)), Embed(struct_recuento), ) struct_apertura = Struct( "Apertura", UBInt16("numero_mesa"), UBInt8("hora"), UBInt8("minutos"), UBInt8("cantidad_autoridades"), UBInt8("len_nombres"), Array(lambda ctx: ctx.len_nombres, Bytes("nombres", 1)), Array(lambda ctx: ctx.cantidad_autoridades, Bytes("tipos", 1)), Array(lambda ctx: ctx.cantidad_autoridades, Bytes("dnis", 4)), )
@requires: construct 2.5.2 """ from construct import SLInt64 from construct import Embed from construct import Struct from construct import Container # from construct.debug import Probe from pox.ethanol.ssl_message.msg_core import msg_default, field_station from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string msg_memcpu = Struct('msg_memcpu', Embed(msg_default), # default fields Embed(field_station), SLInt64('value'), # Probe() ) """ format the MSG_GET_CPU and MSG_GET_MEMORY data structure to be sent by ethanol protocol """ def __get_memcpu(server, id=0, type=None, sta_ip=None, sta_port=0): """ INTERNAL FUNCTION: don't call it @param server: tuple (ip, port_num) @param id: message id @param sta_ip: ip address of a station that this message should be relayed to @param sta_port: socket port of the station
def _decode(self, obj, context): return NBTFile(StringIO(obj), compression=NBTFile.Compression.GZIP) def NBTdata(name, size_name): return NBTAdapter(MetaField(name, lambda ctx: ctx[size_name])) # item packing slotdata = Struct( "slotdata", SBInt16("id"), If( lambda context: context["id"] >= 0, Embed( Struct( "item_information", UBInt8("count"), UBInt16("damage"), SBInt16("size"), If(lambda context: context["size"] >= 0, NBTdata("data", size_name="size")))))) def itemstack_as_slotdata(itemstack): if itemstack is None: data = {'id': -1} else: data = { 'id': itemstack.number, 'count': itemstack.count, 'damage': itemstack.meta } if itemstack.nbt is None: data['size'] = -1
# Flying, position, and orientation, reused in several places. grounded = Struct("grounded", UBInt8("grounded")) position = Struct("position", BFloat64("x"), BFloat64("y"), BFloat64("stance"), BFloat64("z")) orientation = Struct("orientation", BFloat32("rotation"), BFloat32("pitch")) # Notchian item packing items = Struct( "items", SBInt16("primary"), If( lambda context: context["primary"] >= 0, Embed( Struct( "item_information", UBInt8("count"), UBInt16("secondary"), )), ), ) # Metadata inner container. metadata_switch = { 0: UBInt8("value"), 1: UBInt16("value"), 2: UBInt32("value"), 3: BFloat32("value"), 4: AlphaString("value"), 5: Struct( "slot", UBInt16("primary"),
""" from construct import SLInt32 from construct import Embed from construct import Struct from construct import Container # from construct.debug import Probe from pox.ethanol.ssl_message.msg_core import msg_default from pox.ethanol.ssl_message.msg_core import field_station, field_ssid, field_intf_name, field_mac_addr from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string msg_sta_link_info = Struct( 'msg_sta_link_info', Embed(msg_default), Embed(field_intf_name), Embed(field_station), Embed(field_mac_addr), Embed(field_ssid), SLInt32('frequency'), ) def get_sta_link_info(server, id=0, sta_ip=None, sta_port=0, intf_name=None): """ returns three values: mac_addr, ssid, frequency None equals an error has occured (or no interface found) @todo: Nao eh necessario retornar intf_name
ULInt32('record_number')) RECORD_STRUCT = Struct( 'record', ULInt16('data_size'), Peek(Byte('first_byte')), Embed( IfThenElse( 'record_type', lambda ctx: ctx['first_byte'] == 0xFE, Embed( Struct( 'record', RECORD_TYPE, String('table_name', lambda ctx: ctx['data_size'] - 5, encoding=record_encoding), UBInt32('table_number'), )), Embed( Struct( 'record', UBInt32('table_number'), RECORD_TYPE, Switch( 'record_type', lambda ctx: ctx.type, { 'DATA': Embed(DATA_RECORD_DATA), 'METADATA': Embed(METADATA_RECORD_DATA), 'TABLE_DEFINITION': Embed(TABLE_DEFINITION_RECORD_DATA), 'INDEX': Embed(INDEX_RECORD_DATA) })))))) class TpsRecord: def __init__(self, header_size, data):
UBInt32('sending_node'), # byes 16-19 If(lambda ctx: ctx.payload_length > 8, # Message data is optional # message_length: bytes 20-23, message: bytes 24+ PascalString('message', length_field=UBInt32('message_length'), encoding='ascii') ) ) _EEG_data = Struct('embedded', BFloat32('timestamp'), # bytes 12-15 UBInt8('data_counter'), # byte 16; Unused, just 0 currently Field('ADC_status', 6), # bytes 17-22 Array(lambda ctx: (ctx.payload_length - 11)/4, BFloat32('sensor_data')) # bytes 23-26, 27-30, etc. ) _null = Struct('embedded', Array(111, UBInt8('none')) ) DSI_streamer_packet = Struct('DSI_streamer_packet', Embed(_header), Switch('payload', lambda ctx: ctx.type, {"NULL": Embed(_null), "EVENT": Embed(_event), "EEG_DATA": Embed(_EEG_data)} ) )
@status: in development @requires: construct 2.5.2 """ from construct import SLInt32 from construct import Embed, Struct, Container from pox.ethanol.ssl_message.msg_core import msg_default from pox.ethanol.ssl_message.msg_core import field_intf_name from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string msg_beacon_interval = Struct( 'msg_beacon_interval', Embed(msg_default), # default fields Embed(field_intf_name), SLInt32('beacon_interval'), ) ERROR = -1 def get_beacon_interval(server, id=0, intf_name=None): """ get beacon interval in miliseconds for the interface intf_name @param server: tuple (ip, port_num) @param id: message id @param intf_name: name of the wireless interface @type intf_name: str
from pox.ethanol.ssl_message.msg_core import field_intf_name from pox.ethanol.ssl_message.msg_core import field_station from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string field_mac_new_ap = Struct('mac_new_ap', SLInt32('mac_new_ap_size'), If(lambda ctx: ctx["mac_new_ap_size"] > 0, CString("mac_new_ap") ), ) """ handles a mac address field for the new ap (a C char * field) """ msg_station_trigger_transition = Struct('msg_station_trigger_transition', Embed(msg_default), # default fields Embed(field_station), Embed(field_mac_addr), # mac_sta Embed(field_intf_name), # intf_name Embed(field_mac_new_ap), # mac_new_ap # Probe() ) """ message structure common to all supported_messages messages""" def station_trigger_transition(server, id=0, sta_ip=None, sta_port=0, sta_mac=None, intf_name=None, mac_new_ap=None): """ sendo command to station to change to a new ap @param server: tuple (ip, port_num) @param id: message id
class SizeAdapter(Adapter): def _encode(self, obj, context): encoded = tohex(obj) return encoded def _decode(self, obj, context): return unpack('>L', b'\x00' + obj)[0] struct_base = Struct("base", UBInt8("version"), SizeAdapter(Field("size", 3))) struct_common = Struct("common", Embed(struct_base), UBInt8("msg_type"), UBInt8("device"), UBInt8("command"), Field("data", lambda ctx: ctx.size - 7)) struct_byte = Struct("byte", UBInt8("byte")) struct_batt_connected = Struct("batt_connected", UBInt8("slots_number"), Array(lambda ctx: ctx.slots_number, UBInt8("slots"))) struct_batt_get_status = Struct("batt_get_status", UBInt8("batt_number"), Array(lambda ctx: ctx.batt_number, Struct("batt_data",
@requires: construct 2.5.2 """ from datetime import datetime from construct import SLInt32, LFloat32, CString, SLInt8 from construct import Embed, Struct, Container from construct import If # from construct.debug import Probe from pox.ethanol.ssl_message.msg_core import msg_default from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION, BUFFER_SIZE from pox.ethanol.ssl_message.msg_common import connect_ssl_socket from pox.ethanol.ssl_message.msg_common import is_error_msg, tri_boolean, len_of_string msg_ping = Struct( 'msg_ping', Embed(msg_default), # default fields SLInt32('data_size'), If(lambda ctx: ctx["data_size"] > 0, CString("data")), # Probe(), ) """ ping message data structure """ msg_pong = Struct( 'msg_pong', Embed(msg_default), # default fields LFloat32('rtt'), # float com 32 bits, LFloat32 (C little endian 32 bits) SLInt8('verify_data'), # class boolean # Probe(), ) """ pong message data structure
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'),
from pox.ethanol.ssl_message.msg_core import msg_default from pox.ethanol.ssl_message.msg_core import field_intf_name from pox.ethanol.ssl_message.msg_core import field_station from pox.ethanol.ssl_message.msg_core import field_mac_addr from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string iw_bitrates = Struct( 'iw_bitrates', LFloat32("bitrate"), ULInt8('is_short'), # this is a boolean coded as a byte ) iw_bands = Struct( 'iw_bands', Embed(field_intf_name), ULInt32('band'), ULInt32('num_bitrates'), # Probe(), Array(lambda ctx: ctx.num_bitrates, iw_bitrates), ) msg_tx_bitrates = Struct( 'msg_tx_bitrates', Embed(msg_default), # default fields Embed(field_intf_name), Embed(field_station), ULInt32('num_bands'), # Probe(), Array(lambda ctx: ctx.num_bands, iw_bands), )