Metadata-Version: 2.4
Name: ikalogic-at1000
Version: 0.13.0
Summary: Python SDK for Ikalogic AT1000 devices
Keywords: at1000,ikalogic,test-sequencer,automated-testing,hardware,instrumentation,sdk,api
Author: Corentin AZAIS, Vladislav KOSINOV
Author-email: Corentin AZAIS <c.azais@ikalogic.com>, Vladislav KOSINOV <v.kosinov@ikalogic.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Manufacturing
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Embedded Systems
Classifier: Topic :: Scientific/Engineering
Classifier: Typing :: Typed
Requires-Dist: httpx>=0.28.1
Requires-Dist: pydantic>=2.12.5
Requires-Dist: typing-extensions>=4.12
Requires-Dist: websockets>=13.0
Requires-Dist: zeroconf>=0.148.0
Requires-Python: >=3.10
Project-URL: Homepage, https://ikalogic.com/test-sequencers/at1000/intro/
Project-URL: Documentation, https://ikalogic.com/kb/at1000-api/at1000_home/
Description-Content-Type: text/markdown

# ikalogic-at1000

Official Python SDK for the Ikalogic AT1000 Series Test Sequencers.

This package controls and automates the Ikalogic [AT1000](https://ikalogic.com/test-sequencers/at1000/intro/), a test sequencer for functional testing of electronic devices, PCBs, and complex systems. It ships a synchronous client (`ikalogic_at1000`) and an asynchronous client (`ikalogic_at1000.aio`) with the same API.

## Key Features

- **32 Programmable I/Os:** Handle analog and digital signals within a ±25V range.
- **8 Dry Contact Relays:** Control external circuits, with one relay equipped for high-precision current measurement.
- **Programmable Power Supply:** Delivers 0 to 24V at up to 2A with precise current monitoring.
- **Dual USB 3.0 Ports:** Feature power cycling (on/off control) and current measurement for testing USB devices.
- **Communication Interfaces:** Includes Ethernet, RS232, RS485, CAN, SPI, I2C, and UART.
- **Human-Machine Interface (HMI):** Onboard screen, rotary knob, and speaker for standalone operation and feedback.

## Installation

```bash
pip install ikalogic-at1000
```

Or, with [uv](https://docs.astral.sh/uv/):

```bash
uv add ikalogic-at1000
```

Requires Python 3.10 or newer.

Starting a new project? `uvx create-ikalogic-at1000 my-project` scaffolds a ready-to-run demo that depends on this SDK.

## Quick Start

Discover devices on the local network, then open one:

```python
from ikalogic_at1000 import AT1000

# mDNS discovery returns host strings
for host in AT1000.find_devices():
    print(host)

device = AT1000.open("at1000.local")  # hostname or IP
print(device.info.model, device.info.serial_number)

device.reset()  # every subsystem back to its default state
device.close()
```

Inside an AT1000 project container the device resolves its own address without mDNS:

```python
from ikalogic_at1000 import AT1000

if AT1000.is_standalone():
    device_address = AT1000.find_local_device()
else:
    devices = AT1000.find_devices()
    device_address = devices[0] if devices else None

if not device_address:
    raise SystemExit("No devices found")

device = AT1000.open(device_address)
```

## Basic Usage

Resources are attributes of the opened device. Pin, port, and relay numbers start at 0.

```python
from ikalogic_at1000 import AT1000

device = AT1000.open("at1000.local")
try:
    # GPIO: digital input with 0.8 V / 1.5 V thresholds, digital and analog outputs
    test_point = device.gpio.digital(5)
    test_point.configure_input(vil=0.8, vih=1.5)
    print("GPIO 5 high:", test_point.read())

    device.gpio.digital(0).configure_output(value=True, vol=0.0, voh=3.3)
    device.gpio.analog(2).configure_output(1.5)
    print("GPIO 3 voltage:", device.gpio.analog(3).read())

    # Power: DUT supply and USB port power with current measurement
    dut = device.power.dut(0)
    dut.enable(5.0)
    print("DUT current:", dut.read_current())
    device.power.usb(0).disable()

    # Relays
    device.relays.relay(2).close()
    print("Relay 2 closed:", device.relays.relay(2).is_closed())
finally:
    device.reset()
    device.close()
```

`device.com` exposes the CAN, I2C, SPI, UART, RS232, RS485, and USB interfaces.

Both sync and async clients validate communication requests before sending them:

- UART baud rates are the standard rates: 300, 600, 1200, 1800, 2400, 4800, 9600,
  19200, 38400, 57600, 115200, 230400, 460800, 500000, 576000, 921600, 1000000,
  1152000, 1500000, 2000000, 2500000, 3000000, 3500000, and 4000000.
- SPI `trx()` accepts 1–65536 bytes after converting string input to serial data.
  Empty RS232, RS485, UART, and I2C writes remain allowed.
- I2C read lengths are integers from 0 through 65536, inclusive; read and write
  addresses are 7-bit values (0–127).

### Reading the whole device

These reads need no session, so a `readonly=True` client can show the whole device. They need server 0.15.0 or later.

- `gpio.read_all()`: every pin's configuration, state and owner (PWM, I2C, SPI or UART) in one request, as `GpioPinOverview` entries.
- `com.<bus>(id).read_config()` on the six buses: the configuration, plus `rx_started` (whether reception is started) for CAN, UART, RS232 and RS485 (`CanConfigState`, `UartConfigState`, `Rs232ConfigState`, `Rs485ConfigState`). The `com.*_config` events carry `rx_started` too; it is `None` from older servers.
- `hmi.screen().capture(scale=1, etag=None)`: a `ScreenCapture` with a WebP image of what the screen shows, prompts and menus included, each pixel repeated `scale` times (1 to 10), and its `etag`. Pass the `etag` of the last capture and the call returns `None` when the frame is unchanged. The `hmi.screen` event, which carries no data, announces a new frame (at most five per second).

```python
last = device.hmi.screen().capture(scale=2)


def on_frame(event):
    global last
    last = device.hmi.screen().capture(scale=2, etag=last.etag) or last


device.events.subscribe("hmi.screen", on_frame)
```

## Sequences

`device.sequence()` batches GPIO, PWM, relay, power, HMI, and USB enumeration steps into one request that the device runs back to back. Steps are grouped like the API (`gpio`, `gpio.pwm`, `relays`, `power.dut`, `power.usb`, `power.relay`, `hmi.screen`, `hmi.audio`, `com.usb`). Each call returns a new builder, so a sequence can be reused and extended, and `as_(name)` names the preceding step in the report:

```python
report = (
    device.sequence()
    .relays.close(0)
    .power.dut.enable(0, 5.0)
    .power.dut.wait(0, current=(None, 0.2), timeout=2.0, stable_for=0.05)
    .gpio.configure(5, mode="digital", direction="input", vil=0.8, vih=2.5)
    .gpio.read(5, expect=True)
    .power.dut.read(0, repeat=5, delay=0.01)
    .as_("supply")
    .com.usb.wait(0, connected=True, timeout=5.0)
    .run(timeout=10.0)
)
for sample in report.named["supply"].samples:
    print(sample.voltage, sample.current)
```

- Pin, relay, and USB port numbers are checked against the device's capabilities as steps are appended, before anything is sent.
- `report.results` holds the raw step results in command order. A named result in `report.named` is a `SequenceScalarResult` (one reading in `value`), a `SequenceCollectionResult` (every reading in `samples`), or a `SequenceControlResult` (no reading; `config`, `measurement`, or `devices` when its step reported one), discriminated on `kind`. Each carries the ids its step echoed (`io`, `relay`, `dut`, `usb`).
- `run(timeout)` is the budget of the whole sequence in seconds (30 by default, or the file's `timeout` for a sequence loaded from a file). It starts when the device receives the request, so it includes time spent waiting for another sequence to finish; the report's `elapsed` and each step's `elapsed` count from the start of the first step.
- Bounds are a `(min, max)` tuple, with `None` for an open edge, or a `SequenceBounds`.
- `device.gpio.sequence()` and `GpioSequence` are deprecated. They still work: each flat method (`read`, `write`, `wait_voltage`, `wait_level`, `delay`, `hold`, `release`) sends the matching `gpio.*` step, and the report keeps the v0.10 ops (`SequenceOp.READ`, not `SequenceOp.GPIO_READ`). They need firmware with the device-wide sequence endpoint.

### Failed and cancelled runs

A wait past its own `timeout` or a budget spent raises `SEQUENCE_TIMED_OUT`, a failed `expect` raises `SEQUENCE_ASSERTION_FAILED`, and a run ended by `cancel()` raises `SEQUENCE_CANCELLED`. All three raise `SequenceError`, an `ApiError` that also carries `failed_index` (the step that did not complete), `elapsed` and `report`: the results of the steps that ran, then the failing step's readings so far. Nothing after that step runs, and the steps already run are not rolled back. Named results work as in a successful report; a step that has no result gives `None`.

```python
from ikalogic_at1000 import SequenceError

try:
    sequence.run()
except SequenceError as error:
    print(error.code, error.failed_index, error.report.get("supply"))
```

`sequence.cancel()` cancels the sequences the device is running, whichever client started them, and returns once their resources are free. The `sequence.run` event (`SequenceRunEvent`) announces a run starting and how it ended, and `sequence.step` (`SequenceStepEvent`) follows each step. Both carry `run_id`, which tells apart runs that overlap. `failed_index`, the partial report, `cancel()` and these events need server 0.15.0 or later; an older server leaves `failed_index` at `None` and the report empty.

### Sequence files

`to_dict()` turns a sequence into sequence file data, and `device.sequence_from()` builds a runnable sequence from that data or from the path of a JSON file, validated with the same rules as the builder. The layout, shared with the other SDKs, is in [`docs/sequence-file-format.md`](https://github.com/ikalogic/at1000/blob/main/docs/sequence-file-format.md).

```python
import json
from pathlib import Path

Path("check.json").write_text(json.dumps(sequence.to_dict(), indent=2))

loaded = device.sequence_from(Path("check.json"))
report = loaded.run()  # the file's timeout, unless run() is given one
print(report.get("supply"))
```

An invalid file raises `ValueError` naming every problem and its place in the data, before anything is sent. `SequenceFile` is the pydantic model of a file: `SequenceFile.model_validate_json(text, strict=True)` checks a file with the SDK's rules without a device.

## Sessions

`open()` acquires exclusive access to the device. The session is labelled with the `label` argument, or the project id or local hostname when omitted. If another client opens the same device, this client's mutating calls raise `AccessRevokedError` until it calls `open()` again.

Pass `readonly=True` to observe a device without taking control. Reads work, and mutating calls raise `DeviceNotOpenError`:

```python
from ikalogic_at1000 import AT1000

monitor = AT1000.open("at1000.local", readonly=True)
print(monitor.session.state())  # who holds the device, if anyone
monitor.close()
```

## Errors

Every error response from the device raises `ApiError`, with `code`, `suggestion`, and `path` attributes. Specific codes raise subclasses:

- `AccessRevokedError`: another client opened the device. Call `open()` again to take it back.
- `DeviceNotOpenError`: a mutating call was made without a session, for example on a `readonly` client.
- `InsufficientStorageError`: an upload does not fit in the device storage.
- `BundleSourceUnreachableError`: the device cannot reach a streamed firmware bundle source.
- `SequenceError`: a sequence run the device stopped (see [Failed and cancelled runs](#failed-and-cancelled-runs)).

```python
from ikalogic_at1000 import AccessRevokedError, ApiError, AT1000

device = AT1000.open("at1000.local")
try:
    device.relays.relay(0).close()
except AccessRevokedError:
    device = AT1000.open("at1000.local")  # reacquire, then retry
except ApiError as error:
    print(error.code, error.suggestion)
```

Arguments that fail local validation raise `ValueError` (including pydantic's `ValidationError`) before any request is sent.

## Asynchronous Usage

`ikalogic_at1000.aio` exports the same classes and models as coroutines. Close the async client with `aclose()`:

```python
import asyncio

from ikalogic_at1000.aio import AT1000


async def main():
    device = await AT1000.open("at1000.local")
    try:
        await device.gpio.digital(5).configure_input(vil=0.8, vih=1.5)
        print(await device.gpio.digital(5).read())
    finally:
        await device.aclose()


asyncio.run(main())
```

## Real-time Events

Live device state changes arrive over a WebSocket. The synchronous client registers callbacks per event type, or `"*"` for all events:

```python
from ikalogic_at1000 import AT1000

device = AT1000.open("at1000.local", readonly=True)
device.events.connect()


def on_gpio(event):
    print(event.type, event.data)


unsubscribe = device.events.subscribe("gpio.state", on_gpio)

# later
unsubscribe()
device.events.close()
device.close()
```

The async client iterates events instead. `listen()` filters by type and yields everything when called with no types:

```python
from ikalogic_at1000.aio import AT1000


async def watch(host: str):
    device = await AT1000.open(host, readonly=True)
    try:
        async for event in device.events.listen("gpio.state", "relays.state"):
            print(event.type, event.data)
    finally:
        await device.aclose()
```

Both clients reconnect automatically after the first successful connection. `events.close()` stops the stream.

## HMI

`device.hmi` drives the screen, speaker, and knob. `knob().wait_event(timeout_ms)` waits for a press or a turn and returns a `KnobEvent`, or `None` on timeout. Rotation is reported in detent steps, so use a server and SDK release with matching knob handling.

`hmi.prompt()` shows a single-choice prompt and blocks until the operator answers:

```python
from ikalogic_at1000 import AT1000, PromptChoice, PromptRequest

device = AT1000.open("at1000.local")
try:
    result = device.hmi.prompt(
        PromptRequest(
            text="Test failed.\nChoose the next action.",
            choices=[
                PromptChoice(label="Retry", color="#1769AA"),
                "Skip",  # shorthand for PromptChoice(label="Skip")
                PromptChoice(label="Cancel", color="#B3261E"),
            ],
            default_index=2,
            timeout_ms=60_000,
        )
    )
    print(result.status, result.selection.label, result.selection.index)
finally:
    device.close()
```

- `status` is `selected`, `cancelled`, or `timed_out`. `selection` is always set: the chosen choice, or the last highlighted one.
- 1 to 32 choices. Text is at most 256 UTF-8 bytes, each label at most 64 UTF-8 bytes, and neither may be blank.
- `timeout_ms` is 1,000 to 1,800,000 (default 60,000). The first knob turn stops the timeout.
- `default_index` sets the initial highlight. It is not selected automatically on timeout.
- A prompt needs an owning session, and only one can be active. Screen changes and raw knob reads conflict with it while it is pending.

See the [HMI documentation](https://ikalogic.com/kb/at1000-api/hmi/) for the full behaviour.

## Deprecations

A deprecated function, method, or class keeps working and names its replacement, if it has one. It may be removed in a later release: a new minor release while the SDK is 0.x, a new major release from 1.0. Type checkers and IDEs flag it through `typing_extensions.deprecated` (mypy with `--enable-error-code deprecated`, pyright with `reportDeprecated`), and the first use in a process emits one `FutureWarning` per deprecation, naming the replacement (if any) and the version (and its release date) that deprecated it. Set `AT1000_NO_DEPRECATION_WARNINGS=1` to silence these warnings; Python's `warnings` filters work too. The wording of error messages, including the SDK's own argument checks, may change in any release.

Deprecated APIs are implemented over their replacements, so like the rest of the SDK they need device firmware that serves the current device API: update the device firmware when you update the SDK.

## Examples

The SDK source tree has runnable scripts in `examples/`. Each needs a device on the network:

- `discovery.py`: mDNS discovery with the default and a custom timeout.
- `example.py`: async discovery, then print the device information and capabilities.
- `sequence.py`: a sequence mixing relays, DUT power, GPIO, PWM, USB enumeration, and the screen, run in one request.
- `hmi_prompt.py`: a colored-choice prompt, sync or `--async`.
- `i2c_sensor_check.py`: I2C transactions against two sensor breakouts, from both clients.

## Documentation

Full API documentation, with Python snippets for every subsystem, is at <https://ikalogic.com/kb/at1000-api/at1000_home/>.

## License

This package is distributed under the MIT License.
