import bluespy
from time import sleep

logic_line = 3
bluespy.connect()
bluespy.start_gui()
bluespy.capture("main_cap.pcapng", LE=True, CL=True, logic_mask=0xFFFF, logic_use_external_vref=False, logic_rate=0)

file_p = None
count = 0

pkt_idx = 0
start_ts = bluespy.time_point()
try:
    while True:
        state = bluespy.wait_until_next_logic_change(1 << logic_line, 1*1000000, start_ts)
        if state.change_mask:
            sleep(0.1) #Wait for parser to catch up

        # Copies packets
        while pkt_idx < len(bluespy.packets) and bluespy.packets[pkt_idx].query_int("time") < state.time.value:
            if file_p != None:
                bluespy.add_to_filter_file(file_p, bluespy.packets[pkt_idx])
            pkt_idx += 1

        # Create or Close file
        low_mask = state.change_mask & ~(state.state)
        high_mask = state.change_mask & (state.state)
        if low_mask:
            bluespy.add_log_message(bluespy.log_level.INFO, str(state.time), state.time)
            print("Low Mask: " + bin(low_mask))
            if file_p != None:
                bluespy.close_filter_file(file_p)
                file_p = None
                print("Closing File!")
        elif high_mask:
            bluespy.add_log_message(bluespy.log_level.INFO, str(state.time), state.time)
            print("High Mask: " + bin(high_mask))
            if file_p == None:
                file_p = bluespy.create_filter_file("sub_cap_"+str(count)+".pcapng",  keep_spec = False, keep_logic = False, keep_uart = False, keep_i2s_and_audiopod = False)
                print("File ID: "+ str(file_p.value) +", Name: "+ str(file_p))
                count+=1
except KeyboardInterrupt:
    pass