~martijnbraam/pyatem

ref: 54781b49332b0ffbb4c8b11454da2ccc4b744cc2 pyatem/pyatem/macro.py -rw-r--r-- 2.2 KiB
54781b49Martijn Braam Vendor the hexdump dependency 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from pyatem.macrocommand import *
import pyatem.macrocommand as macromodule

macro_command_map = {
    0x0002: ProgramInputMacroCommand,
    0x0003: PreviewInputMacroCommand,
    0x0007: SleepMacroCommand,
    0x0014: TransitionWipeMacroCommand,
    0x0015: TransitionWipeMacroCommand,
    0x0016: TransitionWipeMacroCommand
}


def decode_macro(raw):
    result = []
    offset = 0

    last_command = None
    while offset < len(raw):
        length, command_id = struct.unpack_from('<HH', raw, offset)
        command_raw = raw[offset:offset + length]
        if command_id in macro_command_map:
            command = macro_command_map[command_id]
            if command == last_command:
                result[-1].add_action(command_id, command_raw)
            else:
                decoder = command()
                decoder.add_action(command_id, command_raw)
                result.append(decoder)
        else:
            decoder = BaseMacroCommand()
            decoder.add_action(command_id, command_raw)
            result.append(decoder)
        offset += length

    for decoder in result:
        decoder.decode()

    return result


def encode_macro(actions):
    result = b''
    for action in actions:
        result += action.encode()
    return result


def encode_macroscript(actions):
    result = ''
    for action in actions:
        result += action.encode_script()
    return result


def decode_macroscript(script):
    classmap = {}
    for name, cls in macromodule.__dict__.items():
        if isinstance(cls, type) and name != "BaseMacroCommand":
            classmap[cls.TAG] = cls

    result = []
    for line in script.splitlines(keepends=False):
        name, data = line.split(' ', maxsplit=1)
        if name in classmap:
            inst = classmap[name]()
        else:
            inst = BaseMacroCommand()
        inst.decode_script(data)
        result.append(inst)
    return result


if __name__ == '__main__':

    with open('/workspace/usb-65535-0.bin', 'rb') as handle:
        raw_macro = handle.read()

    result = decode_macro(raw_macro)
    print(result)

    encoded = encode_macroscript(result)
    print(encoded)
    decoded = decode_macroscript(encoded)
    print(decoded)