Example #1
0
 def __init__(self):
     self.protocol_header = b'\x00'
     self.message_format = Struct(
         "fields" / RawCopy(
             Struct("NetworkID" / Bytes(32), "DeviceID" / Int8sb,
                    "Sequence" / Int16ub, "Payload_length" / Byte,
                    "Payload" / Bytes(this.Payload_length))),
         "checksum" /
         Checksum(Bytes(4), lambda data: hashlib.sha256(data).digest()[0:4],
                  this.fields.data),
     )
Example #2
0
            decrypted = decrypted.rstrip(b"\x00")
        except Exception as ex:
            _LOGGER.debug("Unable to decrypt, returning raw bytes.")
            return obj

        try:
            jsoned = json.loads(decrypted.decode('utf-8'))
        except:
            _LOGGER.error("unable to parse json, was: %s", decrypted)
            jsoned = b'{}'
            raise

        return jsoned


Message = Struct(
    # for building we need data before anything else.
    "data" / Pointer(32, RawCopy(EncryptionAdapter(GreedyBytes))),
    "header" / RawCopy(
        Struct(
            Const(Int16ub,
                  0x2131), "length" / Rebuild(Int16ub, Utils.get_length),
            "unknown" / Default(Int32ub, 0x00000000), "devtype" /
            Enum(Default(Int16ub, 0x02c1), default=Pass, **xiaomi_devices),
            "serial" / Default(Int16ub, 0xa40d),
            "ts" / TimeAdapter(Default(Int32ub, datetime.datetime.utcnow())))),
    "checksum" /
    IfThenElse(Utils.is_hello, Bytes(16),
               Checksum(Bytes(16), Utils.md5, Utils.checksum_field_bytes)),
)
Example #3
0
        for i, quirk in enumerate(decrypted_quirks):
            decoded = quirk(decrypted).decode('utf-8')
            try:
                return json.loads(decoded)
            except Exception as ex:
                # log the error when decrypted bytes couldn't be loaded
                # after trying all quirk adaptions
                if i == len(decrypted_quirks) - 1:
                    _LOGGER.error("unable to parse json '%s': %s", decoded, ex)

        return None


Message = Struct(
    # for building we need data before anything else.
    "data" / Pointer(32, RawCopy(EncryptionAdapter(GreedyBytes))),
    "header" / RawCopy(Struct(
        Const(0x2131, Int16ub),
        "length" / Rebuild(Int16ub, Utils.get_length),
        "unknown" / Default(Int32ub, 0x00000000),
        "device_id" / Hex(Bytes(4)),
        "ts" / TimeAdapter(Default(Int32ub, datetime.datetime.utcnow()))
    )),
    "checksum" / IfThenElse(
        Utils.is_hello,
        Bytes(16),
        Checksum(Bytes(16),
                 Utils.md5,
                 Utils.checksum_field_bytes)),
)
Example #4
0
from collections.abc import Mapping

from construct import Struct, RawCopy, BitStruct, Const, Nibble, Flag, Int8ub, BitsInteger, Int16ub, \
    Checksum, Bytes, this, Default, Padding, Enum, Int24ub, ExprAdapter, Byte, obj_, Array, Computed, Subconstruct, \
    ValidationError, ExprSymmetricAdapter, Bitwise, BitsSwapped, Embedded, ByteSwapped

from .adapters import StatusFlags, ZoneFlags, DateAdapter, PartitionStatus, EventAdapter, \
    ZoneFlagBitStruct, DictArray, EnumerationAdapter
from ..common import CommunicationSourceIDEnum, ProductIdEnum, calculate_checksum, PacketLength, PacketChecksum

LoginConfirmationResponse = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / BitStruct(
                "command" / Const(0x1, Nibble), "status" /
                Struct("reserved" / Flag, "alarm_reporting_pending" / Flag,
                       "Winload_connected" / Flag, "NeWare_connected" / Flag)),
            "length" / PacketLength(Int8ub), "result" /
            BitStruct("_not_used0" / BitsInteger(4), "partition_2" / Flag,
                      "_not_used1" / BitsInteger(3)), "callback" / Int16ub)),
    "checksum" / PacketChecksum(Bytes(1)))

InitializeCommunication = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / Struct("command" / Const(0x00, Int8ub)),
            "module_address" / Default(Int8ub, 0x00),  # (00= panel/module)
            "_not_used0" / Padding(2),
            "product_id" / ProductIdEnum,
            "firmware" /
            Struct("version" / Int8ub, "revision" / Int8ub, "build" / Int8ub),
Example #5
0
File: panel.py Project: skeary/pai
    def control_zones(self, zones, command) -> bool:
        raise NotImplementedError("override control_zones in a subclass")

    def control_partitions(self, partitions, command) -> bool:
        raise NotImplementedError("override control_partitions in a subclass")

    def control_outputs(self, outputs, command) -> bool:
        raise NotImplementedError("override control_outputs in a subclass")

    def dump_memory(self):
        raise NotImplementedError("override dump_memory in a subclass")


InitiateCommunication = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / BitStruct("command" / Const(7, Nibble), "reserved0" /
                             Const(2, Nibble)), "reserved1" / Padding(35))),
    "checksum" / Checksum(Bytes(1), lambda data: calculate_checksum(data),
                          this.fields.data))

InitiateCommunicationResponse = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / BitStruct("command" / Const(7, Nibble), "message_center" /
                             Nibble), "new_protocol" / Const(0xFF, Int8ub),
            "protocol_id" / Int8ub, "protocol" /
            Struct("version" / Int8ub, "revision" / Int8ub, "build" / Int8ub),
            "family_id" / Int8ub, "product_id" / ProductIdEnum,
            "talker" / Enum(Int8ub,
                            BOOT_LOADER=0,
                            CONTROLLER_APPLICATION=1,
Example #6
0
from construct import Struct, Switch, Bytes, Int16ul, RawCopy, this
from .kdbx3 import DynamicHeader as DynamicHeader3
from .kdbx3 import Body as Body3
from .kdbx4 import DynamicHeader as DynamicHeader4
from .kdbx4 import Body as Body4

KDBX = Struct(
    "header" / RawCopy(
        Struct(
            "magic1" / Bytes(4), "magic2" / Bytes(4),
            "minor_version" / Int16ul, "major_version" / Int16ul,
            "dynamic_header" / Switch(this.major_version, {
                3: DynamicHeader3,
                4: DynamicHeader4
            }))), "body" / Switch(this.header.value.major_version, {
                3: Body3,
                4: Body4
            }))
Example #7
0
        lambda ctx: ctx.size,
        Switch(lambda ctx: ctx.type,
               kcdata_types_structures,
               default=GreedyBytes)))

kcdata = GreedyRange(kcdata_item)

kd_threadmap = Struct(
    'tid' / Int64ul,
    'pid' / Int32ul,
    'process' / FixedSized(20, CString('utf8')),
)

kd_buf = Struct(
    'timestamp' / Int64ul,
    'args' / RawCopy(Array(4, Int64ul)),
    'tid' / Int64ul,
    'debugid' / Int32ul,
    'eventid' / Computed(lambda ctx: ctx.debugid & KDBG_EVENTID_MASK),
    'class_' /
    Computed(lambda ctx: (ctx.debugid & KDBG_CLASS_MASK) >> KDBG_CLASS_OFFSET),
    'subclass' /
    Computed(lambda ctx:
             (ctx.debugid & KDBG_SUBCLASS_MASK) >> KDBG_SUBCLASS_OFFSET),
    'code' /
    Computed(lambda ctx: (ctx.debugid & KDBG_CODE_MASK) >> KDBG_CODE_OFFSET),
    'func_qualifier' / Computed(lambda ctx: ctx.debugid & KDBG_FUNC_MASK),
    'cpuid' / Int32ul,
    'unused' / Int64ul,
)
Example #8
0
    # it includes the offset into 0x90000000 (external flash)
    # we mask out the highest nibble to correct this into the actual bin length
    # plus subtract 20 bytes for header, symbol and length dwords
    'bin' / Bytes((this.length & 0x0FFFFFFF) - 20)
)

struct_blit_relo = Struct(
    'header' / Const(b'RELO'),
    'relocs' / PrefixedArray(Int32ul, Struct(
        'reloc' / Int32ul
    ))
)

blit_game = Struct(
    'relo' / Optional(struct_blit_relo),
    'bin' / RawCopy(struct_blit_bin),
    'meta' / Optional(struct_blit_meta)
)

blit_game_with_meta = Struct(
    'relo' / Optional(struct_blit_relo),
    'bin' / RawCopy(struct_blit_bin),
    'meta' / struct_blit_meta
)

blit_game_with_meta_and_relo = Struct(
    'relo' / struct_blit_relo,
    'bin' / RawCopy(struct_blit_bin),
    'meta' / struct_blit_meta
)
Example #9
0
from ..common import CommunicationSourceIDEnum, PacketChecksum, ProductIdEnum
from .adapters import (DateAdapter, ModuleSerialAdapter,
                       PartitionStatusAdapter, SignalStrengthAdapter,
                       StatusAdapter, ZoneStatusAdapter, PGMDefinitionAdapter,
                       PGMStatusAdapter)

InitializeCommunication = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / Struct("command" / Const(0x00, Int8ub)),
            "_not_used0" / Padding(3),
            "product_id" / ProductIdEnum,
            "firmware" /
            Struct("version" / Int8ub, "revision" / Int8ub, "build" / Int8ub),
            "panel_id" / Int16ub,
            "pc_password" / Default(Bytes(2), b"0000"),
            "_not_used1" / Bytes(1),
            "source_method" / Default(
                Enum(Int8ub, Winload_Connection=0x00, NEware_Connection=0x55),
                0x00),
            "user_code" / Default(Int32ub, 0x00000000),
            "_not_used2" / Padding(15),
            "source_id" / Default(CommunicationSourceIDEnum, 1),
            "user_id" / Default(Int16ul, 0),
        )),
    "checksum" / PacketChecksum(Bytes(1)),
)

InitializeCommunicationResponse = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / Struct("command" / Const(0x10, Int8ub)),
Example #10
0
import collections

from construct import Struct, RawCopy, BitStruct, Const, Nibble, Flag, Rebuild, Int8ub, BitsInteger, Int16ub, Checksum, \
    Bytes, this, Default, Padding, Enum, Int24ub, ExprAdapter, Byte, obj_, Array, Computed, Subconstruct, \
    ValidationError, ExprSymmetricAdapter

from .adapters import PGMFlags, StatusAdapter, DateAdapter, ZoneFlags, PartitionStatus, EventAdapter
from ..common import CommunicationSourceIDEnum, ProductIdEnum, calculate_checksum

LoginConfirmationResponse = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / BitStruct(
                "command" / Const(0x1, Nibble), "status" /
                Struct("reserved" / Flag, "alarm_reporting_pending" / Flag,
                       "Winload_connected" / Flag, "NeWare_connected" / Flag)),
            "length" / Rebuild(
                Int8ub, lambda this: this._root._subcons.fields.sizeof() + this
                ._root._subcons.checksum.sizeof()), "result" /
            BitStruct("_not_used0" / BitsInteger(4), "partition_2" / Flag,
                      "_not_used1" / BitsInteger(3)), "callback" / Int16ub)),
    "checksum" / Checksum(Bytes(1), lambda data: calculate_checksum(data),
                          this.fields.data))

InitializeCommunication = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / Struct("command" / Const(0x00, Int8ub)),
            "module_address" / Default(Int8ub, 0x00),
            "_not_used0" / Padding(2),
            "product_id" / ProductIdEnum,
Example #11
0
    c = 0
    for i in range(len(data) // 2):
        c = c + (data[i * 2 + 1] << 8) + data[i * 2]

    return c & 0xFFFF


WriteCommand = Struct("address" / Int16ul, "value" / Int16ul)

WriteMessageRequest = Struct(
    "fields" / RawCopy(
        Struct(
            "length" / Rebuild(
                Int16ul,
                len_(this.items) * WriteCommand.sizeof() // Int16ul.sizeof() +
                2,
            ),
            "command" /
            Const(vlxDevConstants.WS_WEB_UI_COMMAND_WRITE_DATA, Int16ul),
            "items" / WriteCommand[len_(this.items)],
        )),
    "checksum" /
    Checksum(Int16ul, lambda data: checksum_16(data), this.fields.data),
)

ReadTableResponse = GreedyRange(Int16ub)

ReadTableRequest = Struct(
    "fields" / RawCopy(
        Struct(
            "length" / Const(3, Int16ul),
Example #12
0
    def _encode(self, obj, context, path=None):
        return Container()

    def _decode(self, obj, context, path=None):
        offset = datetime(2000, 1, 1, 12) - datetime(1970, 1, 1)
        return (datetime.utcfromtimestamp(obj.time_stamp_seconds) + offset)


SecondaryHeaderRaw = Struct('time_stamp_seconds' / Int32ub,
                            'sub_seconds' / Int8ub, Padding(1))

SecondaryHeader = TimeAdapter(SecondaryHeaderRaw)

cute_ax25_packet_header = RawCopy(
    Struct(
        'ax25_header' / Header, 'primary_header' / PrimaryHeader,
        'secondary_header' /
        If(lambda c: c.primary_header.secondary_header_flag, SecondaryHeader)))

cute_ax25_packet_fragment = Struct('header' / cute_ax25_packet_header,
                                   'packet' / GreedyBytes)

cute_ax25_packet_complete = Struct(
    'ax25_header' / Header, 'primary_header' / PrimaryHeader,
    'secondary_header' /
    If(lambda c: c.primary_header.secondary_header_flag, SecondaryHeader),
    'packet' / Switch(lambda c: (c.primary_header.APID), {
        (0x55): cute_bct_fsw,
        (0x56): cute_bct_soh,
        (0x1FF): cute_pld_sw_stat
    }))
Example #13
0
 def run(self):
     while True:
         readable, _, _ = select.select([self._hci_socket], [], [])
         if readable is not None:
             packet = self._hci_socket.recv(4096)
             log.info('SOCKET: %s', RawCopy(HciPacket).parse(packet))
Example #14
0
from PyCRC.CRCCCITT import CRCCCITT

TIME_FORMAT = '%Y-%m-%d;%H:%M'

crc16 = lambda val: '{:04x}'.format(CRCCCITT().calculate(val)).upper()

TabTerminated = CString(terminators=b'\x09', encoding='cp1250')

PosnetParameter = Struct(
    'name' / Select(Const('@'), Const('?'), String(length=2)),
    'value' / TabTerminated)

PosnetFrame = Struct(
    Const(b'\x02'), 'summed' / RawCopy(
        Struct('instruction' / TabTerminated,
               'parameters' / GreedyRange(PosnetParameter))), Const('#'),
    'crc' / Checksum(Bytes(4), crc16, 'summed'), Const('\x03'),
    'instruction' / Computed(this.summed.value.instruction),
    'parameters' / Computed(this.summed.value.parameters))


def build_frame(instruction, *params):
    '''
    Helper for building Posnet protocol frames out of instructions and
    params passed as (name, value) tuples. Can't use **kwargs: Posnet protocol
    uses reserved chars (such as @ and ?)
    '''
    data = Container(summed=Container(
        value=Container(instruction=instruction,
                        parameters=[