Metadata-Version: 2.5
Name: ibm5250
Version: 0.1.6
Summary: IBM 5250 terminal automation library
Project-URL: Repository, https://github.com/bengieeee/python5250
Project-URL: Issues, https://github.com/bengieeee/python5250/issues
Author: Ben Goldsmith
License-Expression: MPL-2.0
License-File: LICENSE
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# python5250

`ibm5250` is a pure-Python library for automating IBM 5250 terminal sessions
against IBM i (AS/400) systems over TN5250/TN5250E. It speaks the Telnet
negotiation, 5250 data stream, and screen/field model directly — no green-screen
emulator or external dependencies required — so you can script sign-on,
navigation, and data entry against a 5250 host from plain Python.

See [`src/ibm5250/data-stream-logic.md`](src/ibm5250/data-stream-logic.md) for
a detailed walkthrough of how the library parses the wire protocol into screen
state.

## Installation

```bash
pip install ibm5250
```

Requires Python >= 3.11.

## Usage

```python
from ibm5250 import Terminal, AID

with Terminal("as400.example.com") as t:
    t.wait_for_text("Sign On")
    t.find_field_by_label("User").value = "MYUSER"
    t.find_field_by_label("Password").value = "SECRET"
    t.send_key(AID.ENTER)
    t.wait_for_text("Main Menu")
    print(t.screen.get_screen_text())
```

`send_key` blocks until the host has finished replying (the keyboard unlocks),
however many records that takes.

### Connection options

```python
Terminal(
    "as400.example.com",
    port=992,
    use_tls=True,               # certificate and hostname are verified by default
    timeout=10.0,               # deadline for send_key / wait_for_* / connect (seconds)
    socket_timeout=30.0,        # connect, negotiation and per-read socket limit
    device_name="MYDEV",        # sent as the DEVNAME NEW-ENVIRON user variable
    terminal_type="IBM-3179-2", # 24x80 colour; default IBM-3477-FG (27x132 mono)
    environ={"CODEPAGE": "37", "CHARSET": "697"},  # extra RFC 4777 user variables
)
```

- **Device name**: the host assigns one (e.g. `QPADEV0008`) unless you pass
  `device_name=`.
- **TLS**: pass your own `tls_context=` (e.g. with a private CA loaded), or
  `tls_verify=False` to skip certificate checks (insecure; logs a warning).
- **Screen size** follows the host: Clear Unit sets 24×80 or 27×132, as the
  terminal type allows.

### Keys and errors

- `send_key(aid)` sends the cursor position and the field data the host's
  read command asks for. Print and Record Backspace send no field data.
- `send_attn()` and `send_sysreq()` send Attn and System Request (header flags,
  not AID keys), so `send_key(AID.ATTN)` / `send_key(AID.SYSREQ)` raise
  `ValueError`.
- When the host shows an operator error on the status line (Write Error Code),
  `send_key` and every `wait_for_*` raise `OperatorError`. The host text is in
  `err.message` (it is kept out of `str(err)`). Call `reset()` — the Reset key —
  to clear it before sending another key.
- Writing text longer than a field raises `FieldOverflow`, and characters the
  code page (CCSID 37) can't encode raise `EncodingError`; nothing is written.
- `type_into` returns `True` when filling an Auto-Enter field sent Enter.
- Every `wait_for_*` method accepts `fail_on_timeout=False` to return `False`
  instead of raising `ScreenWaitTimeout`.
- A `FieldProxy` (from `find_field_by_label` etc.) finds its field again by
  position when the host redraws the screen, and raises `FieldNotFound` if the
  field is gone.

### Capturing host traces

```python
import logging

logging.basicConfig(level=logging.DEBUG)
Terminal("as400.example.com", log_payloads=True)
```

`log_payloads=True` logs each record's 5250 data in hex at DEBUG level
(`← data …` / `→ data …`). Outgoing records that may contain a non-display
(password) field are never logged. Recorded traces can be replayed as tests:
see `src/ibm5250/tests/test_screen_build.py` for the fixture format.

### Upgrading from 0.1.x

These changes can break existing code.

**Behaviour**

- No default device name: it was `PYTERM01`; pass `device_name="PYTERM01"` to
  keep it. It is now actually sent to the host (as the `DEVNAME` NEW-ENVIRON
  user variable); before, it was silently ignored by IBM i.
- TLS verifies certificates by default: pass `tls_verify=False` (or a
  `tls_context`) for hosts with self-signed certificates. `tls_context`
  without `use_tls=True` raises `ValueError`.
- `timeout` is the wait deadline (default now 10 s, was 1 s); the socket uses
  `socket_timeout` (default 30 s).
- `send_key` waits for the keyboard to unlock instead of reading one record,
  and raises `ScreenWaitTimeout` if it stays locked. `connect()` no longer
  raises when the first screen is slow to arrive.
- Over-long field text raises `FieldOverflow` instead of being truncated, and
  shorter text now replaces the whole previous field content. Fields that
  span several rows (such as the IBM i command line) take their full length.
- Modified fields stay modified after a key is sent, until the host resets
  them (CC1), as on a real 5250. A redisplayed screen therefore sends the
  previously typed values again.
- `Terminal.all_fields()` / `Screen.get_all_field_values()` labels are the
  text between the previous field and the field, stripped.
- `wait_for_text` no longer prints the screen.

**API**

- `Terminal(rows=, cols=, poll_interval=, **conn_kwargs)` are gone; the
  connection options are explicit keyword arguments (see above).
- `Terminal.send_raw(data)` sends _data_ as the whole record body
  (`row, col, AID, …`), with optional `opcode=`/`flags=`; it no longer adds a
  cursor/AID prefix.
- Removed: `KeyboardLocked`, `FieldResponse`, the module-level
  `build_aid_response` / `build_save_screen_response`,
  `decode_save_screen_image` / `decode_save_screen_fields`,
  `Screen.from_save_buffer`, `Screen.last_aid`, `Field.data_pos`,
  `Field.writable_length`, `TN5250EHeader`, `TN5250ERecordType`,
  `TN5250EDataType`, `TN5250ESubNeg`, `TelnetOpt.TN5250E`, `AID.NO_AID`,
  `ADDR_ENCODE` / `ADDR_DECODE` and the `use_tn5250e` connection option.
- `TN5250Connection` sends records with
  `send_record(data, *, opcode, flags=0, sensitive=False)`; the
  `send_*_response` helpers and `tn5250e_active` are gone (use
  `build_record`, `RecordOpcode` and `RecordFlag`).
- `Field(start_pos, field_format_word, field_control_words)` is now
  `Field(start, length, ffw, fcws, attribute)`: `start` is the first _data_
  position (was the attribute position), `ffw` is an `int` and `fcws` a tuple
  of `int`s. `Screen.last_start_of_header` is now `Screen.header`.
- `DataStreamParser()` takes no arguments and `parse(data, *, opcode=...)`
  returns a list; `DSEvent` and `DSEventType` were redesigned around 5250
  commands (`CLEAR_UNIT`, `WRITE_TO_DISPLAY`, `READ`, `SAVE_SCREEN`, …).
- `CC1` / `CC2` values were wrong and are replaced (e.g. `CC2.UNLOCK_KEYBOARD`,
  `CC2.ALARM`, `CC1.RESET_MDT_ALL`); `QueryReply.ScreenSize` model values and
  `QueryReply.Capabilities` were corrected; `FCW.CONTINUATION_BIT` is now
  `FCW.CONTINUED_FIRST` / `_MIDDLE` / `_LAST`.
- The table helpers are public: `Screen.get_table_data(start_row, end_row)`,
  `get_table_data_by_positions(...)` and
  `get_mapped_table_data(start_row, end_row, cls, mapper, column_positions=None)`.
- The Save Screen buffer format changed, so a buffer saved by an older
  version can't be restored.

## Contributing

1. Clone the repo and install dependencies with [`uv`](https://docs.astral.sh/uv/):

   ```bash
   uv sync --locked
   ```

2. Make your changes under `src/ibm5250/`.
3. Lint, type-check and run the test suite before opening a PR:

   ```bash
   uv run ruff check .
   uv run mypy
   uv run pytest
   ```

4. Branch off `develop` and open your pull request **against `develop`**
   (not `main` — see [Branching & releases](#branching--releases) below).

There's no separate contribution guide configured in this repo — just make
sure `ruff check`, `mypy` and `pytest` all pass.

## Branching & releases

Every push runs the test suite in CI. What gets built and published to PyPI
depends on the branch:

| Branch           | Tested | Built |    Published to PyPI     | Version format                                           |
| ---------------- | :----: | :---: | :----------------------: | -------------------------------------------------------- |
| `main`           |   ✅   |  ✅   |      ✅ production       | `X.Y.Z` (patch auto-incremented from the latest release) |
| `develop`        |   ✅   |  ✅   |      ✅ development      | `X.Y.Z.devN`                                             |
| any other branch |   ✅   |  ✅   | ❌ (build artifact only) | n/a                                                      |

- Contribute by branching off `develop` and opening PRs into `develop`.
  `develop` publishes `.devN` releases so changes can be tried out before
  they're promoted to `main`.
- `main` is production — merges there are published as real, patch-bumped
  releases on PyPI.
- The version in `pyproject.toml` is a base version only and is **never
  hand-bumped** for a release; `scripts/compute_version.py` computes the
  actual published version from what's already on PyPI at build time. See
  [`.github/workflows/README.md`](.github/workflows/README.md) for the full
  CI/publishing setup.

## License

Licensed under the [Mozilla Public License 2.0](LICENSE).
