import xml.etree.ElementTree as ET
import os

def parseXML(xmlfile):
    packets=[]
    tree = ET.parse(xmlfile)
    myroot = tree.getroot()
    for x in myroot:
        #print(x.tag, x.attrib)
        #usb_data = x.find("fake-field-wrapper")
        # find the usb.capdata field
        for proto in x:
            if(proto.attrib['name'] == 'fake-field-wrapper'):
                for field in proto:
                    if(field.attrib['name'] == 'usb.capdata'):
                        hexstr = field.attrib['value']
                        packet_bytes = [hexstr[2*i:2*i+2] for i in range(int(len(hexstr)/2))]
                        packet_bytes = bytes(list(map(lambda x: int(x,16), packet_bytes)))
                        packets.append(packet_bytes)
    return packets

packets = parseXML(r"C:\Users\david\Desktop\new_split_frame.pdml")
saved_frames_folder = r"C:\Users\david\Desktop\bs2_frames"
img = bytearray()

n=0
img_id = packets[0][1] & 0x01
save_file = os.path.join(saved_frames_folder, "dumped_frame")
for i in range(len(packets)):
    if (packets[i][1] & 0x01) != img_id:
        # on to the next image, so dump what we have so far
        
        fil = open(f'{save_file}_{n}.jpg','wb')
        fil.write(img)
        fil.close()
        img = bytearray()
        img_id = packets[i][1] & 0x01
        n = n + 1
    img = img + packets[i][2:]

# at the very end, dump the last chunk we have
fil = open(f'{save_file}_{n}.jpg','wb')
fil.write(img)
fil.close()