import xml.etree.ElementTree as ET
import os

# structure:
# <packet>
#   <proto.../>
#   <proto.../>
#   <proto.../>
#   <proto name="usb" showname="USB isochronous packet"...>
#       <field.../>
#       <field.../>
#       <field name="usb.iso.data" showname="ISO Data [...]: 0200ff..." show="02:00:ff:..." value="0200ff..."/>
#   </proto>
# </packet>

def parseXML(xmlfile):
    packets=[]
    tree = ET.parse(xmlfile)
    myroot = tree.getroot()
    for pkt in myroot:
        # "pkt" should have tag "packet"
        for proto in pkt:
            # grab the frame number
            if 'geninfo' == proto.attrib['name']:
                for field in proto:
                    if 'num' == field.attrib['name']:
                        frame_number = int(field.attrib['value'],16)
        for proto in pkt:                
            # looking for the USB Isochronous Packet showname
            if 'showname' in proto.attrib.keys():
                if proto.attrib['showname'] == 'USB isochronous packet':
                    for field in proto:
                        # looking for the "usb.iso.data" field
                        if field.attrib['name'] == 'usb.iso.data':
                            hexstr = bytes.fromhex(field.attrib['value'])
                            offset = int(proto.attrib['pos'])
                            packets.append((frame_number, offset, hexstr))
    return packets

packets = parseXML(r"C:\Users\david\Desktop\debugging_tx_counter\still_fucking_up.pdml")



i = 0
for i, pkt in enumerate(packets):
    soi_pos = pkt[2].find(b'\xff\xd8')
    if (soi_pos >= 0) and (soi_pos != 2):
        # uh oh, misaligned!
        print(f'bad alignment in packet #{i}, byte pos {soi_pos}, frame {pkt[0]}, offset {pkt[1]}')

