import pylink
import time
import sys

# The serial number of your J-Link probe. 
# This is useful if you have multiple J-Link devices connected.
# You can find the serial number using the 'pylink.jlink_list()' function or the J-Link Commander.
JLINK_SERIAL_NO = None # Or provide your serial number here


# Define the device name. For the Thingy:91's nRF9160 SiP, this is 'nRF9160_xxAA'.
TARGET_DEVICE = 'nRF9160_xxAA'

# Initialize and open a connection to the J-Link
try:
    jlink = pylink.JLink()
    # Open a connection to the J-Link. 
    # The serial number is optional but recommended for clarity.
    if JLINK_SERIAL_NO:
        print(f"Connecting to J-Link probe with serial number {JLINK_SERIAL_NO}...")
        jlink.open(serial_no=JLINK_SERIAL_NO)
    else:
        print("Connecting to the first available J-Link probe...")
        jlink.open()
    
    # Connect to the target device (Thingy:91's nRF9160)
    print(f"Connecting to target device: {TARGET_DEVICE}...")
    jlink.connect(TARGET_DEVICE, verbose=True)



    # Wait for RTT to be initialized by the target firmware
    print("Waiting for RTT control block...")
    time.sleep(2)  # Wait for a moment to let RTT initialize on the target

    # Search for and start the RTT control block
    if jlink.rtt_start():
        print("RTT started. Reading RTT data. Press Ctrl+C to exit.")

        while True:
            # Read from RTT buffer 0. Timeout is in milliseconds.
            data = jlink.rtt_read(0, 1024)
            if data:
                # Decode and print the received data
                print(data.decode('utf-8'), end='')
            time.sleep(0.1)  # Poll every 100ms
    else:
        print("RTT control block not found.")

except KeyboardInterrupt:
    print("User interrupted. Exiting.")
finally:
    jlink.close()
