#!/usr/bin/env python3
"""Search MCU firmware bin for project number and upgrade-related data."""
with open('/Users/admin/workspace/jyq/mcubin/mcu_app.bin','rb') as f:
    d = f.read()

# Search for key strings
for s in [b'UPDATE', b'UPGRADE', b'iBinLength', b'bin_len', b'BinLength', b'project', b'PROJECT']:
    idx = 0
    while True:
        idx = d.find(s, idx)
        if idx < 0:
            break
        ctx = d[max(0,idx-8):idx+len(s)+8]
        ascii_view = ''.join(chr(b) if 32<=b<127 else '.' for b in ctx)
        print(f'{s.decode()} at 0x{idx:04X}: {ctx.hex()} [{ascii_view}]')
        idx += 1

# Look for 4-byte sequences that look like project IDs near 0x80/0x81 command handlers
# These are often sent as P4~Pn bytes in UPDATE_REQ(0x80) and UPDATE_BEGIN(0x81)
# Common formats: ASCII project name, or a 4-byte integer
print('\n--- Looking for potential project IDs (4-byte ASCII-coded) ---')
for i in range(0, len(d)):
    if d[i] >= 0x30 and d[i] <= 0x7A:  # start with alphanumeric
        chunk = d[i:i+8]
        if all(0x20 <= b < 0x7F for b in chunk):
            s = chunk.decode('ascii', errors='ignore').rstrip('\x00').strip()
            if len(s) >= 4 and (s.startswith(('SGMW','HW','MCU','ARM','E1','C0')) or '20' in s):
                before = d[max(0,i-4):i].hex()
                after_hex = d[i+len(s):i+len(s)+4].hex()
                print(f'  Candidate at 0x{i:04X}: {s!r} (before:{before}, after:{after_hex})')
