from saleae import automation
import os
import os.path
from datetime import datetime

print("I3C Basic Protocol Analyzer Automation Script Demo")
print()

#Your device serial number (F4241 for demo Logic Pro 16)
device_id_num = "F4241"
#Lincesnce Key for the configuration of the i3c analyzer
License_Key = "ADD lincense key"
Capture_File_Path = "/full path/to/i3c-basic-automation-demo-capture.sal"

if "ADD lincense key" in License_Key:
    print("Please add your license key to the python script on line #12!")
    print("Without it, the script will return an error.")
    exit(1)

if "/full path/to/i3c-basic-automation-demo-capture.sal" in Capture_File_Path:
    print("Please update the path on line #13 to point to valid I3C capture file (.sal)!")
    print("Without it, the script will return an error.")
    exit(1)

print("Connecting to Saleae Logic 2...")

# Connect to the running Logic 2 Application on port `10430`.
# Alternatively you can use automation.Manager.launch() to launch a new Logic 2 process - see
# the API documentation for more details.
# Using the `with` statement will automatically call manager.close() when exiting the scope. If you
# want to use `automation.Manager` outside of a `with` block, you will need to call `manager.close()` manually.
with automation.Manager.connect(port=10430) as manager:

    print("Connected!")
    print()
    print("Configuring the capture settings...")

    # Configure the capturing device to record on digital channels 0, 1, 2, and 3,
    # with a sampling rate of 10 MSa/s, and a logic level of 3.3V.
    # The settings chosen here will depend on your device's capablities wnad what
    # you can configure in the Logic 2 UI.
    device_configuration = automation.LogicDeviceConfiguration(
        enabled_digital_channels=[0, 1],
        digital_sample_rate=10_000_000,
        digital_threshold_volts=3.3,
    )

    print("Configured!")
    print()
    print("Setting the desired capture length...")

    # Record 5 seconds of data before stopping the capture
    capture_configuration = automation.CaptureConfiguration(
        capture_mode=automation.TimedCaptureMode(duration_seconds=5.0)
    )

    print("Ready!")
    print()
    print("Starting the Capture...")
    print()

    # Start a capture - the capture will be automatically closed when leaving the `with` block
    # Note: We are using serial number 'F4241' here, which is the serial number for
    #       the Logic Pro 16 demo device. You can remove the device_id and the first physical
    #       device found will be used, or you can use your device's serial number.
    #       See the "Finding the Serial Number of a Device" section for information on finding your
    #       device's serial number.
    with manager.load_capture(filepath=Capture_File_Path) as capture:

        print("Loading capture file....")
        # Wait until the capture has finished
        # This will take about 5 seconds because we are using a timed capture mode
        capture.wait()
        print("Finished!")
        print()

        print("Adding the I3C Analyzer to the capture session...")
        print("Note: this may take a few seconds, as the license key is verified during this step.")
        print("[This step will be instant if you're using a Node-Locked license].")
        print()

        # Add an analyzer to the capture
        # Note: The simulator output is not actual SPI data
        #print("i3c analyzer config")
        i3c_analyzer = capture.add_analyzer('I3C [4.2.1]', label=f'I3C test', settings={
            'SDA': 1,
            'SCL': 0,
            # Here your I3C analyzer license key must be added for the auotamtion test to be able to start
            'License Key': License_Key
        })
        print("I3C Analyzer setup complete!")
        print()

        ''' 
        print("i3c HLA config")
        i3cTransaction_HLA = capture.add_high_level_analyzer(
            extension_directory=f'DirForTheHLA',
            name=f'I3C Transactions',
            input_analyzer=i3c_analyzer,
            settings=None,
            label=f'I3C transaction HLA'
        )
        '''

        print("Exporting the captured data...")

        # Store output in a timestamped directory
        #print("Createing timestamped directory")
        output_dir = os.path.join(os.getcwd(), f'output-{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}')
        os.makedirs(output_dir)

        # Export analyzer data to a CSV file
        #print("Starting to export csv")
        analyzer_export_filepath = os.path.join(output_dir, 'i3c_export.csv')
        capture.export_data_table(
            filepath=analyzer_export_filepath,
            analyzers=[i3c_analyzer]
        )
        print("Decoded data exported as .csv!")

        # Export raw digital data to a CSV file
        #print("Exporting raw data")
        capture.export_raw_data_csv(directory=output_dir, digital_channels=[0, 1])
        print("Raw digital data exported as .csv!")

        # Finally, save the capture to a file
        #print("Exporting capture")
        capture_filepath = os.path.join(output_dir, 'example_capture.sal')
        capture.save_capture(filepath=capture_filepath)
        print("Captured waveform file saved as .sal!")
        print()

        print("Session ended, closing capture...")

        print("Demo Finished!")
