{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "3b076775",
      "metadata": {},
      "source": [
        "### License\n",
        "Copyright (C) 2021-2022, Xilinx, Inc.\n",
        "<br>\n",
        "Copyright (C) 2022-2024, Advanced Micro Devices, Inc.\n",
        "<p>\n",
        "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "you may not use this file except in compliance with the License.\n",
        "<p>\n",
        "You may obtain a copy of the License at <a href=\"http://www.apache.org/licenses/LICENSE-2.0\"?>http://www.apache.org/licenses/LICENSE-2.0</a><br><br>\n",
        "Unless required by applicable law or agreed to in writing, software\n",
        "distributed under the License is distributed on an \"AS IS\" BASIS, \n",
        "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "See the License for the specific language governing permissions and\n",
        "limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6c3d50fb",
      "metadata": {},
      "source": [
        "ILA Advanced Trigger Example\n",
        "========================="
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1d2a5807",
      "metadata": {},
      "source": [
        "Description\n",
        "-----------\n",
        "This demo shows how to use the ILA Advanced Trigger Mode.\n",
        "In this mode, the trigger setup is described in text using the ILA Trigger State Machine (TSM) language.\n",
        "See UG908 Vivado Design User Guide: Programming and Debugging, Appendix B \"Trigger State Machine Language Description\". \n",
        "\n",
        "\n",
        "Requirements\n",
        "------------\n",
        "The following is required to run this demo:\n",
        "1. Local or remote access to a Versal device\n",
        "2. 2024.1 cs_server and hw_server applications\n",
        "3. Python 3.8 environment\n",
        "4. A clone of the chipscopy git enterprise repository:\n",
        "   - https://github.com/Xilinx/chipscopy\n",
        "\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "73aa520f",
      "metadata": {},
      "source": [
        "## Step 1 - Set up environment"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "4f23a830",
      "metadata": {},
      "outputs": [],
      "source": [
        "import os\n",
        "from enum import Enum\n",
        "import chipscopy\n",
        "from chipscopy import (\n",
        "    create_session,\n",
        "    get_design_files,\n",
        "    null_callback,\n",
        "    report_versions,\n",
        "    delete_session,\n",
        ")\n",
        "from chipscopy.api.ila import ILAStatus, ILAWaveform\n",
        "from io import StringIO\n",
        "from pprint import pformat"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "b2b68657",
      "metadata": {},
      "outputs": [],
      "source": [
        "# Specify locations of the running hw_server and cs_server below.\n",
        "CS_URL = os.getenv(\"CS_SERVER_URL\", \"TCP:localhost:3042\")\n",
        "HW_URL = os.getenv(\"HW_SERVER_URL\", \"TCP:localhost:3121\")\n",
        "\n",
        "# specify hw and if programming is desired\n",
        "HW_PLATFORM = os.getenv(\"HW_PLATFORM\", \"vck190\")\n",
        "PROG_DEVICE = os.getenv(\"PROG_DEVICE\", 'True').lower() in ('true', '1', 't')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "0fe2f208",
      "metadata": {},
      "outputs": [],
      "source": [
        "design_files = get_design_files(f\"{HW_PLATFORM}/production/chipscopy_ced\")\n",
        "PROGRAMMING_FILE = design_files.programming_file\n",
        "PROBES_FILE = design_files.probes_file\n",
        "assert os.path.isfile(PROGRAMMING_FILE)\n",
        "assert os.path.isfile(PROBES_FILE)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "03e7addf",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "HW_URL=TCP:localhost:3121\n",
            "CS_URL=TCP:localhost:3042\n",
            "PDI=/scratch/chipscopy/venv/lib/python3.11/site-packages/chipscopy/examples/designs/vck190/production/chipscopy_ced/chipscopy_wrapper.pdi\n",
            "LTX=/scratch/chipscopy/venv/lib/python3.11/site-packages/chipscopy/examples/designs/vck190/production/chipscopy_ced/chipscopy_wrapper.ltx\n"
          ]
        }
      ],
      "source": [
        "print(f\"HW_URL={HW_URL}\")\n",
        "print(f\"CS_URL={CS_URL}\")\n",
        "print(f\"PDI={PROGRAMMING_FILE}\")\n",
        "print(f\"LTX={PROBES_FILE}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "7dfd328f",
      "metadata": {},
      "source": [
        "## Step 2 - Create a session and connect to the server(s)\n",
        "Here we create a new session and print out some versioning information for diagnostic purposes.\n",
        "The session is a container that keeps track of devices and debug cores."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "13047152",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Using chipscopy api version: 2024.1.1717606426\n"
          ]
        },
        {
          "data": {
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
              "\n",
              "</pre>\n"
            ],
            "text/plain": [
              "\n",
              "\n"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-style: italic\">                      ChipScoPy Version Information                      </span>\n",
              "┌────────────────────────────┬──────────────────────────────────────────┐\n",
              "│<span style=\"font-weight: bold\">                     Entity </span>│<span style=\"font-weight: bold\"> Version                                  </span>│\n",
              "├────────────────────────────┼──────────────────────────────────────────┤\n",
              "│                  ChipScoPy │ ┌───────────┬──────────────────────┐     │\n",
              "│                            │ │<span style=\"font-weight: bold\"> Attribute </span>│<span style=\"font-weight: bold\"> Value                </span>│     │\n",
              "│                            │ ├───────────┼──────────────────────┤     │\n",
              "│                            │ │     Build │ 2024.1.1717606426    │     │\n",
              "│                            │ │ Timestamp │ Jun 05 2024-09:53:46 │     │\n",
              "│                            │ └───────────┴──────────────────────┘     │\n",
              "│                            │                                          │\n",
              "│ hw_server @ localhost:3121 │ ┌───────────┬──────────────────────────┐ │\n",
              "│                            │ │<span style=\"font-weight: bold\"> Attribute </span>│<span style=\"font-weight: bold\"> Value                    </span>│ │\n",
              "│                            │ ├───────────┼──────────────────────────┤ │\n",
              "│                            │ │    Status │ Connected                │ │\n",
              "│                            │ │     Build │ 1716424495               │ │\n",
              "│                            │ │   Version │ 2024.1                   │ │\n",
              "│                            │ │ Timestamp │ Wed May 22 18:34:55 2024 │ │\n",
              "│                            │ └───────────┴──────────────────────────┘ │\n",
              "│                            │                                          │\n",
              "│ cs_server @ localhost:3042 │ ┌───────────────┬──────────────────────┐ │\n",
              "│                            │ │<span style=\"font-weight: bold\">     Attribute </span>│<span style=\"font-weight: bold\"> Value                </span>│ │\n",
              "│                            │ ├───────────────┼──────────────────────┤ │\n",
              "│                            │ │        Status │ Connected            │ │\n",
              "│                            │ │         Build │ 1714182049           │ │\n",
              "│                            │ │       Version │ 2024.1.0             │ │\n",
              "│                            │ │     Timestamp │ Apr 26 2024-18:40:49 │ │\n",
              "│                            │ │       Package │ 2024.1.1714182049    │ │\n",
              "│                            │ │ Artifact type │ pyinstaller          │ │\n",
              "│                            │ └───────────────┴──────────────────────┘ │\n",
              "└────────────────────────────┴──────────────────────────────────────────┘\n",
              "</pre>\n"
            ],
            "text/plain": [
              "\u001b[3m                      ChipScoPy Version Information                      \u001b[0m\n",
              "┌────────────────────────────┬──────────────────────────────────────────┐\n",
              "│\u001b[1m \u001b[0m\u001b[1m                    Entity\u001b[0m\u001b[1m \u001b[0m│\u001b[1m \u001b[0m\u001b[1mVersion                                 \u001b[0m\u001b[1m \u001b[0m│\n",
              "├────────────────────────────┼──────────────────────────────────────────┤\n",
              "│                  ChipScoPy │ ┌───────────┬──────────────────────┐     │\n",
              "│                            │ │\u001b[1m \u001b[0m\u001b[1mAttribute\u001b[0m\u001b[1m \u001b[0m│\u001b[1m \u001b[0m\u001b[1mValue               \u001b[0m\u001b[1m \u001b[0m│     │\n",
              "│                            │ ├───────────┼──────────────────────┤     │\n",
              "│                            │ │     Build │ 2024.1.1717606426    │     │\n",
              "│                            │ │ Timestamp │ Jun 05 2024-09:53:46 │     │\n",
              "│                            │ └───────────┴──────────────────────┘     │\n",
              "│                            │                                          │\n",
              "│ hw_server @ localhost:3121 │ ┌───────────┬──────────────────────────┐ │\n",
              "│                            │ │\u001b[1m \u001b[0m\u001b[1mAttribute\u001b[0m\u001b[1m \u001b[0m│\u001b[1m \u001b[0m\u001b[1mValue                   \u001b[0m\u001b[1m \u001b[0m│ │\n",
              "│                            │ ├───────────┼──────────────────────────┤ │\n",
              "│                            │ │    Status │ Connected                │ │\n",
              "│                            │ │     Build │ 1716424495               │ │\n",
              "│                            │ │   Version │ 2024.1                   │ │\n",
              "│                            │ │ Timestamp │ Wed May 22 18:34:55 2024 │ │\n",
              "│                            │ └───────────┴──────────────────────────┘ │\n",
              "│                            │                                          │\n",
              "│ cs_server @ localhost:3042 │ ┌───────────────┬──────────────────────┐ │\n",
              "│                            │ │\u001b[1m \u001b[0m\u001b[1m    Attribute\u001b[0m\u001b[1m \u001b[0m│\u001b[1m \u001b[0m\u001b[1mValue               \u001b[0m\u001b[1m \u001b[0m│ │\n",
              "│                            │ ├───────────────┼──────────────────────┤ │\n",
              "│                            │ │        Status │ Connected            │ │\n",
              "│                            │ │         Build │ 1714182049           │ │\n",
              "│                            │ │       Version │ 2024.1.0             │ │\n",
              "│                            │ │     Timestamp │ Apr 26 2024-18:40:49 │ │\n",
              "│                            │ │       Package │ 2024.1.1714182049    │ │\n",
              "│                            │ │ Artifact type │ pyinstaller          │ │\n",
              "│                            │ └───────────────┴──────────────────────┘ │\n",
              "└────────────────────────────┴──────────────────────────────────────────┘\n"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
              "\n",
              "</pre>\n"
            ],
            "text/plain": [
              "\n",
              "\n"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "print(f\"Using chipscopy api version: {chipscopy.__version__}\")\n",
        "session = create_session(cs_server_url=CS_URL, hw_server_url=HW_URL)\n",
        "report_versions(session)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "11bdbe6f",
      "metadata": {},
      "source": [
        "## Step 3 - Get our device from the session"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "2968f776",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Device count: 1\n"
          ]
        }
      ],
      "source": [
        "# Use the first available device and setup its debug cores\n",
        "if len(session.devices) == 0:\n",
        "    raise ValueError(\"No devices detected\")\n",
        "print(f\"Device count: {len(session.devices)}\")\n",
        "versal_device = session.devices.get(family=\"versal\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1e02cda8",
      "metadata": {},
      "source": [
        "## Step 4 - Program the device with our example programming file"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "dbca19c3",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Programming /scratch/chipscopy/venv/lib/python3.11/site-packages/chipscopy/examples/designs/vck190/production/chipscopy_ced/chipscopy_wrapper.pdi...\n"
          ]
        },
        {
          "data": {
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
              "<span style=\"font-weight: bold\">--&gt; INFO: </span>Programming device with: \n",
              "/scratch/chipscopy/venv/lib/python3.11/site-packages/chipscopy/examples/designs/vck190/production/chipscopy_ced/chi\n",
              "pscopy_wrapper.pdi\n",
              "    \n",
              "</pre>\n"
            ],
            "text/plain": [
              "\n",
              "\u001b[1m--> INFO: \u001b[0mProgramming device with: \n",
              "/scratch/chipscopy/venv/lib/python3.11/site-packages/chipscopy/examples/designs/vck190/production/chipscopy_ced/chi\n",
              "pscopy_wrapper.pdi\n",
              "    \n"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "91130f5be22a4534a77b4f4d887ee1a8",
              "version_major": 2,
              "version_minor": 0
            },
            "text/plain": [
              "Output()"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
            ],
            "text/plain": []
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
              "</pre>\n"
            ],
            "text/plain": [
              "\n"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "print(f\"Programming {PROGRAMMING_FILE}...\")\n",
        "if PROG_DEVICE:\n",
        "    versal_device.program(PROGRAMMING_FILE)\n",
        "else:\n",
        "    print(\"skipping programming\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0296437b",
      "metadata": {},
      "source": [
        "## Step 5 - Detect Debug Cores"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "4a64cddf",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Discovering debug cores...\n"
          ]
        }
      ],
      "source": [
        "print(f\"Discovering debug cores...\")\n",
        "versal_device.discover_and_setup_cores(ltx_file=PROBES_FILE)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "8403cfb1",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "Found 3 ILA cores in design\n"
          ]
        }
      ],
      "source": [
        "ila_count = len(versal_device.ila_cores)\n",
        "print(f\"\\nFound {ila_count} ILA cores in design\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "7d75fc2f",
      "metadata": {},
      "outputs": [],
      "source": [
        "if ila_count == 0:\n",
        "    print(\"No ILA core found! Exiting...\")\n",
        "    raise ValueError(\"No ILA cores detected\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "895a7c3e",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "    ILA Core #0: NAME=chipscopy_i/counters/ila_fast_counter_0, UUID=D62FB110F1A25D439EB15D9149F450CE\n",
            "    ILA Core #1: NAME=chipscopy_i/counters/ila_slow_counter_0, UUID=9125D1429AD25223AECDD656C2856755\n",
            "    ILA Core #2: NAME=chipscopy_i/noc_tg_bc/noc_bc_axis_ila_0, UUID=C53C0D3572B655B6A8A13A86686D262D\n"
          ]
        }
      ],
      "source": [
        "# List all detected ILA Cores\n",
        "ila_cores = versal_device.ila_cores\n",
        "for index, ila_core in enumerate(ila_cores):\n",
        "    print(f\"    ILA Core #{index}: NAME={ila_core.name}, UUID={ila_core.core_info.uuid}\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "b0c94fd8",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "USING ILA: chipscopy_i/counters/ila_slow_counter_0\n"
          ]
        }
      ],
      "source": [
        "# Get the ILA cores matching a given name. filter_by returns a list, even if just one item is present.\n",
        "my_ila = versal_device.ila_cores.filter_by(name=\"chipscopy_i/counters/ila_slow_counter_0\")[0]\n",
        "\n",
        "print(f\"USING ILA: {my_ila.name}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "863f6d60",
      "metadata": {},
      "source": [
        "## Step 6 - Get Information for this ILA Core\n",
        "Note:\n",
        "- 'has_advanced_trigger' is True. This ILA supports the advanced trigger feature.\n",
        "- 'tsm_counter_widths' shows 4 counters of bit width 16."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "id": "e8bad3fa",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "ILA Name: chipscopy_i/counters/ila_slow_counter_0\n",
            "\n",
            "ILA Core Info { 'core_major_ver': 1,\n",
            "  'core_minor_ver': 0,\n",
            "  'core_type': 1,\n",
            "  'drv_ver': 8,\n",
            "  'tool_major_ver': 19,\n",
            "  'tool_minor_ver': 1,\n",
            "  'uuid': '9125D1429AD25223AECDD656C2856755'}\n",
            "\n",
            "ILA Static Info { 'data_depth': 4096,\n",
            "  'data_width': 105,\n",
            "  'has_advanced_trigger': True,\n",
            "  'has_capture_control': True,\n",
            "  'has_trig_in': True,\n",
            "  'has_trig_out': True,\n",
            "  'match_unit_count': 52,\n",
            "  'port_count': 13,\n",
            "  'tsm_counter_widths': [16, 16, 16, 16]}\n"
          ]
        }
      ],
      "source": [
        "print(\"\\nILA Name:\", my_ila.name)\n",
        "print(\"\\nILA Core Info\", my_ila.core_info)\n",
        "print(\"\\nILA Static Info\", my_ila.static_info)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "72fbd083",
      "metadata": {},
      "source": [
        "## Step 7 -  Trigger Immediately using Advanced Trigger Mode\n",
        "\n",
        "Trigger State Machine trigger descriptions may be in a text file, or in a io.StringIO object.\n",
        "Some of the ILA status information applies only to Advanced Trigger Mode:\n",
        "- tsm_counters\n",
        "- tsm_flags\n",
        "- tsm_state\n",
        "- tsm_state_name"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "id": "5830cb43",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "ILA Status:\n",
            "\n",
            "Trigger State Machine counter values:       [0, 0, 0, 0]\n",
            "Trigger State Machine flags:                [False, False, False, False]\n",
            "Trigger State Machine current state index:  0\n",
            "Trigger State Machine current state name :  my_state0\n"
          ]
        }
      ],
      "source": [
        "TRIGGER_NOW_TSM = StringIO(\n",
        "\"\"\"\n",
        "    state my_state0:\n",
        "        trigger;\n",
        "\"\"\"\n",
        ")\n",
        "\n",
        "# Note, if the TSM text is in a file, you can give the file path string as the first argument.\n",
        "my_ila.run_advanced_trigger(TRIGGER_NOW_TSM, trigger_position=0, window_count=1, window_size=8)\n",
        "\n",
        "\n",
        "my_ila.refresh_status()\n",
        "print(\"\\nILA Status:\\n\")\n",
        "print(\"Trigger State Machine counter values:      \", my_ila.status.tsm_counters)\n",
        "print(\"Trigger State Machine flags:               \", my_ila.status.tsm_flags)\n",
        "print(\"Trigger State Machine current state index: \", my_ila.status.tsm_state)\n",
        "print(\"Trigger State Machine current state name : \", my_ila.status.tsm_state_name)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8052d57f",
      "metadata": {},
      "source": [
        "## Step 8 - Upload Captured Waveform\n",
        "Wait at most half a minutes, for ILA to trigger and capture data."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "id": "b7b92709",
      "metadata": {},
      "outputs": [],
      "source": [
        "my_ila.wait_till_done(max_wait_minutes=0.5)\n",
        "my_ila.upload()\n",
        "if not my_ila.waveform:\n",
        "    print(\"\\nUpload failed!\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dad0811f",
      "metadata": {},
      "source": [
        "## Step 9 - Print samples for probe 'chipscopy_i/counters/slow_counter_0_Q_1'. \n",
        "\n",
        "Using the function ILAWaveform.get_data(), the waveform data is put into a sorted dict.\n",
        "First 4 entries in sorting order are: trigger, sample index, window index, window sample index.\n",
        "Then comes probe values. In this case just one probe."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "id": "ffeb871b",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Window:0  Window Sample:0  dec: 279746541  hex:0x10AC97ED <-- Trigger\n",
            "Window:0  Window Sample:1  dec: 279746542  hex:0x10AC97EE \n",
            "Window:0  Window Sample:2  dec: 279746543  hex:0x10AC97EF \n",
            "Window:0  Window Sample:3  dec: 279746544  hex:0x10AC97F0 \n",
            "Window:0  Window Sample:4  dec: 279746545  hex:0x10AC97F1 \n",
            "Window:0  Window Sample:5  dec: 279746546  hex:0x10AC97F2 \n",
            "Window:0  Window Sample:6  dec: 279746547  hex:0x10AC97F3 \n",
            "Window:0  Window Sample:7  dec: 279746548  hex:0x10AC97F4 \n"
          ]
        }
      ],
      "source": [
        "counter_probe_name = 'chipscopy_i/counters/slow_counter_0_Q_1'\n",
        "\n",
        "def print_probe_values(waveform: ILAWaveform, probe_names: [str]):\n",
        "    samples = waveform.get_data(\n",
        "        probe_names,\n",
        "        include_trigger=True,\n",
        "        include_sample_info=True,\n",
        "    )\n",
        "    for trigger, sample_index, window_index, window_sample_index, value in zip(*samples.values()):\n",
        "        trigger = \"<-- Trigger\" if trigger else \"\"\n",
        "        print(\n",
        "            f\"Window:{window_index}  Window Sample:{window_sample_index}  dec:{value:10}  hex:0x{value:08X} {trigger}\"\n",
        "        )\n",
        "\n",
        "print_probe_values(my_ila.waveform, [counter_probe_name])"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e4794121",
      "metadata": {},
      "source": [
        "## Step 10 - Check if TSM is Valid\n",
        "- The TSM below has undefined probe names and undefined states.\n",
        "- Use \"compile_only=True\" argument when just checking if the TSM text is valid.\n",
        "- The run_advanced_trigger() function returns a tuple with 2 values: \"error_count\" and \"error_message\"."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "id": "14e26710",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "\n",
            "The Advanced Trigger State machine \"TSM_WITH_ERRORS\" has 6 error(s).\n",
            "\n",
            "[Line 3:10] Undefined probe: \"chipscopy_ex_i/counters/slow_counter_0_Q_1\"\n",
            "[Line 8:13] Unknown state \"state_2\".\n",
            "[Line 11:13] Unknown state \"state_3\".\n",
            "[Line 14:10] Undefined probe: \"chipscopy_i/counters23/slow_counter_0_Q_1\"\n",
            "[Line 18:13] Unknown state \"state_2\".\n",
            "[Line 21:11] Unknown state \"state_3\".\n",
            "\n"
          ]
        }
      ],
      "source": [
        "TSM_WITH_ERRORS = StringIO(\n",
        "    \"\"\"\n",
        "    state state_a:\n",
        "      if (chipscopy_ex_i/counters/slow_counter_0_Q_1 == 32'hXX33_0000 &&\n",
        "          chipscopy_i/counters/slow_sine_Dout >= 'habcd) then\n",
        "        trigger;\n",
        "      elseif (chipscopy_i/counters/slow_sine_Dout >= 'habcd) then\n",
        "        reset_counter $counter0;\n",
        "        goto state_2;\n",
        "      else\n",
        "        reset_counter $counter1;\n",
        "        goto state_3;\n",
        "      endif\n",
        "    state state_b:\n",
        "      if (chipscopy_i/counters23/slow_counter_0_Q_1 == 32'h3333_0000) then\n",
        "        trigger;\n",
        "      else\n",
        "        reset_counter $counter3;\n",
        "        goto state_2;\n",
        "      endif\n",
        "    state state_c:\n",
        "      goto state_3;\n",
        "    \"\"\"\n",
        ")\n",
        "\n",
        "# Check the TSM text for errors, using \"compile_only=True\n",
        "#\n",
        "error_count, error_message = my_ila.run_advanced_trigger(TSM_WITH_ERRORS, compile_only=True)\n",
        "print(f'\\n\\nThe Advanced Trigger State machine \"TSM_WITH_ERRORS\" has {error_count} error(s).'\n",
        "      f'\\n\\n{error_message}')"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1cd8b03e",
      "metadata": {},
      "source": [
        "## Step 11 - Define a Status Progress Monitor Function\n",
        "Monitor TSM specific status, when ILA capture is active."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "id": "d112a366",
      "metadata": {},
      "outputs": [],
      "source": [
        "def status_progress(future):\n",
        "    \"\"\"Called in Event Thread\"\"\"\n",
        "    st = future.progress\n",
        "\n",
        "    if st.is_full:\n",
        "        print(f\"\\nAll data has been captured.\")\n",
        "    else:\n",
        "        print(f\"State: {st.tsm_state_name}   Counters: {st.tsm_counters}    Flags: {st.tsm_flags}\")       "
      ]
    },
    {
      "cell_type": "markdown",
      "id": "608960e8",
      "metadata": {},
      "source": [
        "## Step 12 - Run Trigger State Machine with Flags and Counters\n",
        "In STATE_A:\n",
        "- Remain in STATE_A until hex value ending with \"33_0000\", has occurred 8 times (counter values 0-7).\n",
        "- Set \\$flag0\n",
        "- Go to state STATE_B\n",
        "\n",
        "In STATE_B:\n",
        "- Count hex value ending with \"AAA_BBBB\" 10 times (counter values 0-9).\n",
        "- Then set \\$flag1 and trigger."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "id": "154a5a64",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "State: STATE_A   Counters: [1, 0, 0, 0]    Flags: [False, False, False, False]\n",
            "State: STATE_A   Counters: [4, 0, 0, 0]    Flags: [False, False, False, False]\n",
            "State: STATE_A   Counters: [7, 0, 0, 0]    Flags: [False, False, False, False]\n",
            "State: STATE_B   Counters: [7, 1, 0, 0]    Flags: [True, False, False, False]\n",
            "State: STATE_B   Counters: [7, 2, 0, 0]    Flags: [True, False, False, False]\n",
            "State: STATE_B   Counters: [7, 3, 0, 0]    Flags: [True, False, False, False]\n",
            "State: STATE_B   Counters: [7, 4, 0, 0]    Flags: [True, False, False, False]\n",
            "State: STATE_B   Counters: [7, 5, 0, 0]    Flags: [True, False, False, False]\n",
            "State: STATE_B   Counters: [7, 6, 0, 0]    Flags: [True, False, False, False]\n",
            "State: STATE_B   Counters: [7, 7, 0, 0]    Flags: [True, False, False, False]\n",
            "State: STATE_B   Counters: [7, 8, 0, 0]    Flags: [True, False, False, False]\n",
            "State: STATE_B   Counters: [7, 9, 0, 0]    Flags: [True, False, False, False]\n",
            "\n",
            "All data has been captured.\n"
          ]
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "Counters: [7, 9, 0, 0]    Flags: [True, True, False, False]\n"
          ]
        }
      ],
      "source": [
        "TSM_FLAGS_COUNTERS = StringIO(\n",
        "    f\"\"\"\n",
        "    state STATE_A:\n",
        "        if ( {counter_probe_name} == 32'hxx33_0000 && $counter0 == 'u7) then\n",
        "            set_flag $flag0;\n",
        "            goto STATE_B;\n",
        "        elseif ( {counter_probe_name} == 32'hxx33_0000) then\n",
        "            increment_counter $counter0;\n",
        "            goto STATE_A;\n",
        "        else\n",
        "            goto STATE_A;\n",
        "      endif\n",
        "      \n",
        "    state STATE_B:\n",
        "        if ( {counter_probe_name} == 32'hxAAA_BBBB && $counter1 == 'u9) then\n",
        "            set_flag $flag1;\n",
        "            trigger;\n",
        "        elseif ( {counter_probe_name} == 32'hxAAA_BBBB) then\n",
        "            increment_counter $counter1;\n",
        "            goto STATE_B;\n",
        "        else\n",
        "            goto STATE_B;\n",
        "      endif\n",
        "      \n",
        "\"\"\"\n",
        ")\n",
        "\n",
        "my_ila.run_advanced_trigger(TSM_FLAGS_COUNTERS, window_size=8)\n",
        "\n",
        "future = my_ila.monitor_status(max_wait_minutes=1.0, progress=status_progress, done=chipscopy.null_callback)\n",
        "\n",
        "# future.result is blocking, until monitor_status() function has completed or timed-out or been cancelled.\n",
        "# Meanwhile, the status_progress() function is called twice per second to print out status.\n",
        "status = future.result\n",
        "print(f\"\\nCounters: {status.tsm_counters}    Flags: {status.tsm_flags}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c4525266",
      "metadata": {},
      "source": [
        "## Step 13 - Upload Captured Waveform"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "id": "32e7ef66",
      "metadata": {},
      "outputs": [],
      "source": [
        "my_ila.upload()\n",
        "if not my_ila.waveform:\n",
        "    print(\"\\nUpload failed!\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b71d086e",
      "metadata": {},
      "source": [
        "## Step 14 - Print samples for probe 'chipscopy_i/counters/slow_counter_0_Q_1'. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "id": "e23c4865",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Window:0  Window Sample:0  dec:2863315895  hex:0xAAAABBB7 \n",
            "Window:0  Window Sample:1  dec:2863315896  hex:0xAAAABBB8 \n",
            "Window:0  Window Sample:2  dec:2863315897  hex:0xAAAABBB9 \n",
            "Window:0  Window Sample:3  dec:2863315898  hex:0xAAAABBBA \n",
            "Window:0  Window Sample:4  dec:2863315899  hex:0xAAAABBBB <-- Trigger\n",
            "Window:0  Window Sample:5  dec:2863315900  hex:0xAAAABBBC \n",
            "Window:0  Window Sample:6  dec:2863315901  hex:0xAAAABBBD \n",
            "Window:0  Window Sample:7  dec:2863315902  hex:0xAAAABBBE \n"
          ]
        }
      ],
      "source": [
        "print_probe_values(my_ila.waveform, [counter_probe_name])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "id": "f7540911",
      "metadata": {},
      "outputs": [],
      "source": [
        "## When done with testing, close the connection\n",
        "delete_session(session)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "venv",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
