Exemple #1
0
def fmt_terse(data, pktn=None):
    if data in p_p2n_r:
        return 'i87c51_read_fw.%s' % p_p2n_r[data]
    if data in p_p2n_w:
        return 'i87c51_write_fw.%s' % p_p2n_w[data]
    '''
    if pktn and data in big_pkt:
        return 'i87c51_write_fw.%s' % big_pkt[data]
    '''

    if args.big_thresh and pktn and len(data) > args.big_thresh:
        big_pkt[data] = 'p' + str(pktn)
        return 'i87c51_write_fw.%s' % big_pkt[data]

    ret = str2hex(data, prefix=prefix)
    if len(data) > 16:
        ret += '\n%s' % prefix
    return ret
Exemple #2
0
def fmt_terse(data, pktn=None):
    if data in p_p2n_r:
        return 'i87c51_read_fw.%s' % p_p2n_r[data]
    if data in p_p2n_w:
        return 'i87c51_write_fw.%s' % p_p2n_w[data]
    '''
    if pktn and data in big_pkt:
        return 'i87c51_write_fw.%s' % big_pkt[data]
    '''
    
    if args.big_thresh and pktn and len(data) > args.big_thresh:
        big_pkt[data] = 'p' + str(pktn)
        return 'i87c51_write_fw.%s' % big_pkt[data]
    
    ret = str2hex(data, prefix=prefix)
    if len(data) > 16:
        ret += '\n%s' % prefix
    return ret
Exemple #3
0
def dump(fin):
    j = json.load(open(fin))
    pi = 0
    ps = j['data']

    line('# Generated from scrape.py')
    line('from uvscada.bpm.startup import bulk2, bulk86')
    line('import i87c51_read_fw')
    line('import i87c51_write_fw')
    line('')
    
    # remove all comments to make processing easier
    # we'll add our own anyway
    # ps = filter(lambda p: p['type'] != 'comment', ps)
    
    def peekp():
        return nextp()[1]

    def nextp():
        ppi = pi + 1
        while True:
            if ppi >= len(ps):
                raise Exception("Out of packets")
            p = ps[ppi]
            if p['type'] != 'comment':
                return ppi, p
            ppi = ppi + 1
    
    line('def replay(dev):')
    indentP()
    line("bulkRead, bulkWrite, controlRead, controlWrite = usb_wraps(dev)")
    line('')
    
    if 0:
        line("# Generated from packet 61/62")
        line("# ...")
        line("# Generated from packet 71/72")
        line("load_fx2(dev)")
        line()
    
    while pi < len(ps):
        p = ps[pi]
        if p['type'] == 'comment':
            line('# %s' % p['v'])
            pass
        elif p['type'] == 'controlRead':
            '''
            # Generated from packet 6/7
            # None (0xB0)
            buff = controlRead(0xC0, 0xB0, 0x0000, 0x0000, 4096)
            # NOTE:: req max 4096 but got 3
            validate_read("\x00\x00\x00", buff, "packet 6/7")
            '''
            line('buff = controlRead(0x%02X, 0x%02X, 0x%04X, 0x%04X, %d)' % (
                    p['reqt'], p['req'], p['val'], p['ind'], p['len']))
            data = binascii.unhexlify(p['data'])
            line('# Req: %d, got: %d' % (p['len'], len(data)))
            line('validate_read(%s, buff, "packet %s/%s")' % (
                    fmt_terse(data, p['packn'][0]), p['packn'][0], p['packn'][1]))
        elif p['type'] == 'controlWrite':
            '''
            controlWrite(0x40, 0xB2, 0x0000, 0x0000, "")
            '''
            data = binascii.unhexlify(p['data'])
            line('buff = controlWrite(0x%02X, 0x%02X, 0x%04X, 0x%04X, %s)' % (
                    p['reqt'], p['req'], p['val'], p['ind'], str2hex(data, prefix=prefix)))
        elif p['type'] == 'bulkRead':
            if p['endp'] != 0x86:
                raise Exception("Unexpected endpoint")
            if 0:
                line('buff = bulkRead(0x%02X, 0x%04X)' % (p['endp'], p['len']))
                data = binascii.unhexlify(p['data'])
                line('# Req: %d, got: %d' % (p['len'], len(data)))
                line('validate_read(%s, buff, "packet %s/%s")' % (
                        fmt_terse(data, p['packn'][0]), p['packn'][0], p['packn'][1]))
            reply_full = binascii.unhexlify(p['data'])
            reply, _truncate, pprefix, suffix = pkt_strip(reply_full)
            pprefix_str = ''
            if pprefix != 0x08:
                pprefix_str = ', prefix=0x%02X' % pprefix
            suffix_str = ''
            if suffix != 0x00:
                suffix_str = ', suffix=0x%02X' % suffix
            #line('# Discarded %d / %d bytes => %d bytes' % (len(reply_full) - len(reply), len(reply_full), len(reply)))
            pack_str = 'packet %s/%s' % (
                     p['packn'][0], p['packn'][1])
            line('buff = bulk86(dev, target=0x%02X%s%s)' % (len(reply), pprefix_str, suffix_str))
            line('validate_read(%s, buff, "%s")' % (fmt_terse(reply, p['packn'][0]), pack_str))
        elif p['type'] == 'bulkWrite':
            '''
            bulkWrite(0x02, "\x01")
            '''
            # Not all 0x02 have readback
            # bulkWrite(0x%02X
            if p['endp'] != 0x02:
                cmd = binascii.unhexlify(p['data'])
                line('bulkWrite(0x%02X, %s)' % (p['endp'], fmt_terse(cmd, p['packn'][0])))
            # bulkWrite(0x02
            elif peekp()['type'] != 'bulkRead':
                cmd = binascii.unhexlify(p['data'])
                if cmd == "\x09\x10\x57\x81\x00":
                    line("cmd_09(dev)")
                elif cmd[0] == '\x0C' and len(cmd) == 2:
                    line('led_mask(dev, 0x%02X)' % ord(cmd[1]))
                elif cmd == "\x20\x01\x00":
                    line('cmd_20(dev)')
                elif cmd == \
                        "\x3B\x0C\x22\x00\xC0\x40\x00\x3B\x0E\x22\x00\xC0\x00\x00\x3B\x1A" \
                        "\x22\x00\xC0\x18\x00":
                    line('cmd_3B(dev)')
                elif cmd == "\x41\x00\x00":
                    line('cmd_41(dev)')
                elif cmd == "\x43\x19\x10\x00\x00":
                    line('cmd_43(dev)')
                elif cmd == "\x4C\x00\x02":
                    line('cmd_4C(dev)')
                elif cmd[0] == "\x57" and len(cmd) == 7:
                    c57a = cmd[0:3]
                    cmp_mask(
                            "\x57\x00\x00" ,
                            "\xFF\x00\xFF" ,
                            c57a)

                    c50a = cmd[3:]
                    cmp_mask(
                            "\x50\x00\x00\x00" ,
                            "\xFF\x00\xFF\xFF" ,
                            c50a)
                    
                    line('cmd_57_50(dev, %s, %s)' % (fmt_terse(c57a[1]), fmt_terse(c50a[1])))
                elif cmd[0] == "\x50":
                    # ex: "\x50\x9F\x09\x00\x00"
                    cmp_mask(
                            "\x50\x00\x00\x00\x00",
                            "\xFF\x00\x00\xFF\xFF",
                            cmd)
                    line('cmd_50(dev, %s)' % (fmt_terse(cmd[1:3])))
                else:
                    line('bulkWrite(0x02, %s)' % (fmt_terse(cmd, p['packn'][0])))
            # bulk2(
            else:
                def bulk2():
                    pprefix_str = ''
                    if pprefix != 0x08:
                        pprefix_str = ', prefix=0x%02X' % pprefix
                    suffix_str = ''
                    if suffix != 0x00:
                        suffix_str = ', suffix=0x%02X' % suffix
                    pack_str = 'packet W: %s/%s, R: %s/%s' % (
                            p_w['packn'][0], p_w['packn'][1], p_r['packn'][0], p_r['packn'][1])
                    line('buff = bulk2(dev, %s, target=0x%02X%s%s)' % (fmt_terse(cmd, p_w['packn'][0]), len(reply), pprefix_str, suffix_str))
                    #line('# Discarded %d / %d bytes => %d bytes' % (len(reply_full) - len(reply), len(reply_full), len(reply)))
                    line('validate_read(%s, buff, "%s")' % (fmt_terse(reply, p_r['packn'][0]), pack_str))
                
                p_w = p
                pi, p_r = nextp()
                cmd = binascii.unhexlify(p_w['data'])
                reply_full = binascii.unhexlify(p_r['data'])
                if 0:
                    line("'''")
                    line(fmt_terse(reply_full, p['packn'][0]))
                    line("'''")
                reply, _truncate, pprefix, suffix = pkt_strip(reply_full)
                if cmd == "\x01":
                    line('cmd_01(dev)')
                elif cmd == "\x02":
                    line('cmd_02(dev, %s)' % fmt_terse(reply))
                elif cmd == "\x03":
                    line('gpio_readi(dev)')
                elif cmd[0] == "\x08":
                    cmp_mask(
                            "\x08\x01\x57\x00\x00",
                            "\xFF\xFF\xFF\x00\xFF",
                            cmd)
                    try:
                        cmp_buff("\x00\x00", reply)
                    except CmpFail:
                        line('# Bad reply for cmd_08()')
                        bulk2()
                    else:
                        line('cmd_08(dev, %s)' % (fmt_terse(cmd[3])))
                elif cmd[0] == "\x0C":
                    if len(cmd) != 3 or cmd[2] != "\x30":
                        raise Exception("Unexpected")
                    #line('led_mask(dev, 0x%02X)' % ord(cmd[1]))
                    line('led_mask(dev, "%s")' % led_i2s[ord(cmd[1])])
                elif cmd == "\x0E\x00":
                    line('sn_read(dev)')
                elif cmd == "\x0E\x02":
                    line('sm_read(dev)')
                elif cmd == "\x10\x80\x02":
                    cmp_buff("\x80\x00\x00\x00\x09\x00", reply)
                    line('cmd_10(dev)')
                elif cmd[0] == "\x22":
                    if cmd == "\x22\x02\x10\x00\x13\x00\x06":
                        line('sm_info10(dev)')
                    elif cmd == "\x22\x02\x10\x00\x1F\x00\x06":
                        line('sm_insert(dev)')
                    elif cmd == "\x22\x02\x22\x00\x23\x00\x06":
                        line('sm_info22(dev)')
                    elif cmd == "\x22\x02\x24\x00\x25\x00\x06":
                        line('sm_info24(dev)')
                    else:
                        raise Exception("Unexpected read")
                elif cmd == "\x45\x01\x00\x00\x31\x00\x06":
                    cmp_buff( \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF",
                            reply)
                    line('cmd_45(dev)')
                elif cmd == "\x49":
                    cmp_buff("\x0F\x00", reply)
                    line('cmd_49(dev)')
                elif cmd == "\x4A\x03\x00\x00\x00":
                    cmp_buff("\x03\x00", reply)
                    line('cmd_4A(dev)')
                # Observed several times as compound command
                # Only handle simple case
                elif cmd[0] == "\x57" and len(cmd) == 3:
                    cmp_mask(
                            "\x57\x00\x00",
                            "\xFF\x00\xFF",
                            cmd)
                    line('cmd_57s(dev, %s, %s)' % (fmt_terse(cmd[1]), fmt_terse(reply)))
                else:
                    bulk2()
        else:
            raise Exception("Unknown type: %s" % p['type'])
        pi += 1

    indentN()

    print
    for pkt, name in big_pkt.iteritems():
        print '%s = %s' % (name, fmt_terse(pkt))

    print '''
Exemple #4
0
    #cmd.bulk86_dbg = 1

    buffs = set()
    i = 0
    while True:
        subprocess.check_call('clear', shell=True)
        # Generated from packet 241/242
        buff = cmd_57s(dev, "\x85", None,  "cmd_57")
        buffs.add(buff)
        i += 1
        if i % 3 == 0:
            print 'Dumping'
            for j, buff in enumerate(buffs):
                print
                print j
                print str2hex(buff)
            print
            print 'press enter'
            raw_input()
            buffs = set()
        continue
        
        # Chip inserted
        if buff == "\x01":
            print 'Continuity OK'
        # Chip removed
        elif buff == ("\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" \
                    "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"):
            print 'Continuity failed'
        # Inserting chip while running
        # I'm guessing its telling me which pins failed
Exemple #5
0
def dump(fin):
    j = json.load(open(fin))
    pi = 0
    ps = j['data']

    line('# Generated from scrape.py')
    line('from uvscada.bpm.startup import bulk2, bulk86')
    line('import i87c51_read_fw')
    line('import i87c51_write_fw')
    line('')

    # remove all comments to make processing easier
    # we'll add our own anyway
    # ps = filter(lambda p: p['type'] != 'comment', ps)

    def peekp():
        return nextp()[1]

    def nextp():
        ppi = pi + 1
        while True:
            if ppi >= len(ps):
                raise Exception("Out of packets")
            p = ps[ppi]
            if p['type'] != 'comment':
                return ppi, p
            ppi = ppi + 1

    line('def replay(dev):')
    indentP()
    line("bulkRead, bulkWrite, controlRead, controlWrite = usb_wraps(dev)")
    line('')

    if 0:
        line("# Generated from packet 61/62")
        line("# ...")
        line("# Generated from packet 71/72")
        line("load_fx2(dev)")
        line()

    while pi < len(ps):
        p = ps[pi]
        if p['type'] == 'comment':
            line('# %s' % p['v'])
            pass
        elif p['type'] == 'controlRead':
            '''
            # Generated from packet 6/7
            # None (0xB0)
            buff = controlRead(0xC0, 0xB0, 0x0000, 0x0000, 4096)
            # NOTE:: req max 4096 but got 3
            validate_read("\x00\x00\x00", buff, "packet 6/7")
            '''
            line('buff = controlRead(0x%02X, 0x%02X, 0x%04X, 0x%04X, %d)' %
                 (p['reqt'], p['req'], p['val'], p['ind'], p['len']))
            data = binascii.unhexlify(p['data'])
            line('# Req: %d, got: %d' % (p['len'], len(data)))
            line(
                'validate_read(%s, buff, "packet %s/%s")' %
                (fmt_terse(data, p['packn'][0]), p['packn'][0], p['packn'][1]))
        elif p['type'] == 'controlWrite':
            '''
            controlWrite(0x40, 0xB2, 0x0000, 0x0000, "")
            '''
            data = binascii.unhexlify(p['data'])
            line('buff = controlWrite(0x%02X, 0x%02X, 0x%04X, 0x%04X, %s)' %
                 (p['reqt'], p['req'], p['val'], p['ind'],
                  str2hex(data, prefix=prefix)))
        elif p['type'] == 'bulkRead':
            if p['endp'] != 0x86:
                raise Exception("Unexpected endpoint")
            if 0:
                line('buff = bulkRead(0x%02X, 0x%04X)' % (p['endp'], p['len']))
                data = binascii.unhexlify(p['data'])
                line('# Req: %d, got: %d' % (p['len'], len(data)))
                line('validate_read(%s, buff, "packet %s/%s")' % (fmt_terse(
                    data, p['packn'][0]), p['packn'][0], p['packn'][1]))
            reply_full = binascii.unhexlify(p['data'])
            reply, _truncate, pprefix, suffix = pkt_strip(reply_full)
            pprefix_str = ''
            if pprefix != 0x08:
                pprefix_str = ', prefix=0x%02X' % pprefix
            suffix_str = ''
            if suffix != 0x00:
                suffix_str = ', suffix=0x%02X' % suffix
            #line('# Discarded %d / %d bytes => %d bytes' % (len(reply_full) - len(reply), len(reply_full), len(reply)))
            pack_str = 'packet %s/%s' % (p['packn'][0], p['packn'][1])
            line('buff = bulk86(dev, target=0x%02X%s%s)' %
                 (len(reply), pprefix_str, suffix_str))
            line('validate_read(%s, buff, "%s")' %
                 (fmt_terse(reply, p['packn'][0]), pack_str))
        elif p['type'] == 'bulkWrite':
            '''
            bulkWrite(0x02, "\x01")
            '''
            # Not all 0x02 have readback
            # bulkWrite(0x%02X
            if p['endp'] != 0x02:
                cmd = binascii.unhexlify(p['data'])
                line('bulkWrite(0x%02X, %s)' %
                     (p['endp'], fmt_terse(cmd, p['packn'][0])))
            # bulkWrite(0x02
            elif peekp()['type'] != 'bulkRead':
                cmd = binascii.unhexlify(p['data'])
                if cmd == "\x09\x10\x57\x81\x00":
                    line("cmd_09(dev)")
                elif cmd[0] == '\x0C' and len(cmd) == 2:
                    line('led_mask(dev, 0x%02X)' % ord(cmd[1]))
                elif cmd == "\x20\x01\x00":
                    line('cmd_20(dev)')
                elif cmd == \
                        "\x3B\x0C\x22\x00\xC0\x40\x00\x3B\x0E\x22\x00\xC0\x00\x00\x3B\x1A" \
                        "\x22\x00\xC0\x18\x00":
                    line('cmd_3B(dev)')
                elif cmd == "\x41\x00\x00":
                    line('cmd_41(dev)')
                elif cmd == "\x43\x19\x10\x00\x00":
                    line('cmd_43(dev)')
                elif cmd == "\x4C\x00\x02":
                    line('cmd_4C(dev)')
                elif cmd[0] == "\x57" and len(cmd) == 7:
                    c57a = cmd[0:3]
                    cmp_mask("\x57\x00\x00", "\xFF\x00\xFF", c57a)

                    c50a = cmd[3:]
                    cmp_mask("\x50\x00\x00\x00", "\xFF\x00\xFF\xFF", c50a)

                    line('cmd_57_50(dev, %s, %s)' %
                         (fmt_terse(c57a[1]), fmt_terse(c50a[1])))
                elif cmd[0] == "\x50":
                    # ex: "\x50\x9F\x09\x00\x00"
                    cmp_mask("\x50\x00\x00\x00\x00", "\xFF\x00\x00\xFF\xFF",
                             cmd)
                    line('cmd_50(dev, %s)' % (fmt_terse(cmd[1:3])))
                else:
                    line('bulkWrite(0x02, %s)' %
                         (fmt_terse(cmd, p['packn'][0])))
            # bulk2(
            else:

                def bulk2():
                    pprefix_str = ''
                    if pprefix != 0x08:
                        pprefix_str = ', prefix=0x%02X' % pprefix
                    suffix_str = ''
                    if suffix != 0x00:
                        suffix_str = ', suffix=0x%02X' % suffix
                    pack_str = 'packet W: %s/%s, R: %s/%s' % (
                        p_w['packn'][0], p_w['packn'][1], p_r['packn'][0],
                        p_r['packn'][1])
                    line('buff = bulk2(dev, %s, target=0x%02X%s%s)' %
                         (fmt_terse(cmd, p_w['packn'][0]), len(reply),
                          pprefix_str, suffix_str))
                    #line('# Discarded %d / %d bytes => %d bytes' % (len(reply_full) - len(reply), len(reply_full), len(reply)))
                    line('validate_read(%s, buff, "%s")' %
                         (fmt_terse(reply, p_r['packn'][0]), pack_str))

                p_w = p
                pi, p_r = nextp()
                cmd = binascii.unhexlify(p_w['data'])
                reply_full = binascii.unhexlify(p_r['data'])
                if 0:
                    line("'''")
                    line(fmt_terse(reply_full, p['packn'][0]))
                    line("'''")
                reply, _truncate, pprefix, suffix = pkt_strip(reply_full)
                if cmd == "\x01":
                    line('cmd_01(dev)')
                elif cmd == "\x02":
                    line('cmd_02(dev, %s)' % fmt_terse(reply))
                elif cmd == "\x03":
                    line('gpio_readi(dev)')
                elif cmd[0] == "\x08":
                    cmp_mask("\x08\x01\x57\x00\x00", "\xFF\xFF\xFF\x00\xFF",
                             cmd)
                    try:
                        cmp_buff("\x00\x00", reply)
                    except CmpFail:
                        line('# Bad reply for cmd_08()')
                        bulk2()
                    else:
                        line('cmd_08(dev, %s)' % (fmt_terse(cmd[3])))
                elif cmd[0] == "\x0C":
                    if len(cmd) != 3 or cmd[2] != "\x30":
                        raise Exception("Unexpected")
                    #line('led_mask(dev, 0x%02X)' % ord(cmd[1]))
                    line('led_mask(dev, "%s")' % led_i2s[ord(cmd[1])])
                elif cmd == "\x0E\x00":
                    line('sn_read(dev)')
                elif cmd == "\x0E\x02":
                    line('sm_read(dev)')
                elif cmd == "\x10\x80\x02":
                    cmp_buff("\x80\x00\x00\x00\x09\x00", reply)
                    line('cmd_10(dev)')
                elif cmd[0] == "\x22":
                    if cmd == "\x22\x02\x10\x00\x13\x00\x06":
                        line('sm_info10(dev)')
                    elif cmd == "\x22\x02\x10\x00\x1F\x00\x06":
                        line('sm_insert(dev)')
                    elif cmd == "\x22\x02\x22\x00\x23\x00\x06":
                        line('sm_info22(dev)')
                    elif cmd == "\x22\x02\x24\x00\x25\x00\x06":
                        line('sm_info24(dev)')
                    else:
                        raise Exception("Unexpected read")
                elif cmd == "\x45\x01\x00\x00\x31\x00\x06":
                    cmp_buff( \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" \
                            "\xFF\xFF\xFF\xFF",
                            reply)
                    line('cmd_45(dev)')
                elif cmd == "\x49":
                    cmp_buff("\x0F\x00", reply)
                    line('cmd_49(dev)')
                elif cmd == "\x4A\x03\x00\x00\x00":
                    cmp_buff("\x03\x00", reply)
                    line('cmd_4A(dev)')
                # Observed several times as compound command
                # Only handle simple case
                elif cmd[0] == "\x57" and len(cmd) == 3:
                    cmp_mask("\x57\x00\x00", "\xFF\x00\xFF", cmd)
                    line('cmd_57s(dev, %s, %s)' %
                         (fmt_terse(cmd[1]), fmt_terse(reply)))
                else:
                    bulk2()
        else:
            raise Exception("Unknown type: %s" % p['type'])
        pi += 1

    indentN()

    print
    for pkt, name in big_pkt.iteritems():
        print '%s = %s' % (name, fmt_terse(pkt))

    print '''
Exemple #6
0
 def pyd(p):
     data = binascii.unhexlify(p['data'])
     return str2hex(data)
Exemple #7
0
def dump(fin):
    global resets

    j = json.load(open(fin))
    pi = 0
    ps = j['data']

    line('# Generated from scrape.py')

    def peekp():
        return nextp()[1]

    def nextp():
        ppi = pi + 1
        while True:
            if ppi >= len(ps):
                raise Exception("Out of packets")
            p = ps[ppi]
            if p['type'] != 'comment':
                return ppi, p
            ppi = ppi + 1

    line('def replay(dev):')
    indentP()

    def mk_i2c_w(addr, buff):
        return ('controlWrite', 0x40, 0xB0, 0x0A, addr, buff)

    def dec_wh_w(p):
        data = binascii.unhexlify(p['data'])
        w, h = struct.unpack('>HH', data)
        return 'gxs.img_wh_w(%d, %d)' % (w, h)

    def pyd(p):
        data = binascii.unhexlify(p['data'])
        return str2hex(data)

    def pdat(p):
        return binascii.unhexlify(p['data'])

    xlates = {
        ('controlWrite', 0x40, 0xB0, 0x2E, 0, '\x00'):
        lambda p: 'gxs.hw_trig_arm()',
        ('controlWrite', 0x40, 0xB0, 0x2F, 0, None):
        lambda p: 'gxs.hw_trig_disarm()',
        ('controlRead', 0xC0, 0xB0, 0x0B, None, None):
        lambda p: 'gxs.eeprom_r(...)',
        ('controlWrite', 0x40, 0xB0, 0x0C, None, None):
        lambda p: 'gxs.eeprom_w(...)',
        ('controlRead', 0xC0, 0xB0, 0x10, None, None):
        lambda p: 'gxs.flash_r(0x%04X, 0x%04X)' % (p['ind'], p['len']),
        ('controlWrite', 0x40, 0xB0, 0x11, None, None):
        lambda p: 'gxs.flash_erase(...)',
        ('controlWrite', 0x40, 0xB0, 0x0F, None, None):
        lambda p: 'gxs.flash_w(...)',
        ('controlRead', 0xC0, 0xB0, 0x03, None, None):
        lambda p: 'gxs.fpga_rv(0x%04x, %d)' % (p['ind'], p['len'] / 2),
        ('controlRead', 0xC0, 0xB0, 0x04, 0, 2):
        lambda p: 'gxs.fpga_rsig()',
        ('controlWrite', 0x40, 0xB0, 0x02, None, None):
        lambda p: 'gxs.fpga_wv2(0x%04X, %s)' % (p['ind'], pyd(p)),
        ('controlRead', 0xC0, 0xB0, 0x25, 0, 6):
        lambda p: 'gxs.trig_param_r()',
        ('controlRead', 0xC0, 0xB0, 0x0A, None, None):
        lambda p: 'gxs.i2c_r()',
        ('controlWrite', 0x40, 0xB0, 0x0A, None, None):
        lambda p: 'gxs.i2c_w(...)',
        ('controlWrite', 0x40, 0xB0, 0xe600, None, None):
        lambda p: 'gxs.fx2_w(...)',
        (mk_i2c_w(0x82, '\x03\x00')):
        lambda p: 'gxs.fpga_off__1()',
        (mk_i2c_w(0x82, '\x01\x0E')):
        lambda p: 'gxs.fpga_off__2()',
        ('controlRead', 0xC0, 0xB0, 0x51, 0, 0x1C):
        lambda p: 'gxs.versions()',
        ('controlRead', 0xC0, 0xB0, 0x40, 0, 8):
        lambda p: 'gxs.img_ctr_r()',
        ('controlRead', 0xC0, 0xB0, 0x23, 0, 4):
        lambda p: 'gxs.img_wh()',
        ('controlWrite', 0x40, 0xB0, 0x22, 0, None):
        dec_wh_w,
        ('controlWrite', 0x40, 0xB0, 0x2C, 0, None):
        lambda p: 'gxs.int_t_w(0x%04X)' % (struct.unpack('>H', pdat(p))[0]),
        ('controlRead', 0xC0, 0xB0, 0x2D, 0, 4):
        lambda p: 'gxs.int_time()',
        ('controlWrite', 0x40, 0xB0, 0x41, 0, '\x00'):
        lambda p: 'gxs.img_ctr_rst()',
        ('controlWrite', 0x40, 0xB0, 0x0E, None, ''):
        lambda p: 'gxs.set_act_sec(%d)' % p['ind'],
        ('controlWrite', 0x40, 0xB0, 0x21, None, '\x00'):
        lambda p: 'gxs.cap_mode_w(...)',
        ('controlWrite', 0x40, 0xB0, 0x24, 0, None):
        lambda p: 'gxs.trig_param_w(...)',
        ('controlWrite', 0x40, 0xB0, 0x2b, 0, '\x00'):
        lambda p: 'gxs.sw_trig(...)',
        ('controlRead', 0xC0, 0xB0, 0x20, 0, 1):
        lambda p: 'gxs.state()',
        ('controlRead', 0xC0, 0xB0, 0x80, 0, 1):
        lambda p: 'gxs.error()',
    }

    def run_xlate(p):
        data = None
        if 'data' in p:
            data = binascii.unhexlify(p['data'])
        for xlate, xf in xlates.iteritems():
            xtype, xreqt, xreq, xval, xind, xdata = xlate
            #print 'xlate', xlate
            #print 'p', p
            if p['type'] != xtype:
                continue
            if xreqt is not None and p['reqt'] != xreqt:
                continue
            if xval is not None and p['val'] != xval:
                continue
            if xind is not None and p['ind'] != xind:
                continue
            if xtype == 'controlWrite':
                if xdata is not None and data != xdata:
                    continue
            line('# ' + xf(p))
            break

    while pi < len(ps):
        p = ps[pi]
        try:
            run_xlate(p)

            data = None
            if 'data' in p:
                data = binascii.unhexlify(p['data'])

            if p['type'] == 'comment':
                line('# %s' % p['v'])
                pass
            elif p['type'] == 'controlRead':
                line('buff = controlRead(0x%02X, 0x%02X, 0x%04X, 0x%04X, %d)' %
                     (p['reqt'], p['req'], p['val'], p['ind'], p['len']))
                line('# Req: %d, got: %d' % (p['len'], len(data)))
                line('validate_read(%s, buff, "packet %s/%s")' % (str2hex(
                    data, prefix=prefix), p['packn'][0], p['packn'][1]))
            elif p['type'] == 'controlWrite':
                line('buff = controlWrite(0x%02X, 0x%02X, 0x%04X, 0x%04X, %s)'
                     % (p['reqt'], p['req'], p['val'], p['ind'],
                        str2hex(data, prefix=prefix)))
            elif p['type'] == 'bulkRead':
                pass
            elif p['type'] == 'bulkWrite':
                pass
            else:
                raise Exception("Unknown type: %s" % p['type'])
            if is_rst_release(p):
                resets += 1
                if resets == 2:
                    line('# Filtered %d FW load packets' % reset_filters[0])
            pi += 1
        except:
            print 'Error on packet %s' % (p['packn'], )
            raise

    indentN()

    print