Metadata-Version: 2.4
Name: knexflow
Version: 0.2.3
Summary: Portable K'NEX Flow program library, controller compiler, and robotics SDK
Author-email: siegzeon0079 <davidg0079@gmail.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/siegzeon0079/knexflow-rework
Project-URL: Repository, https://github.com/siegzeon0079/knexflow-rework
Project-URL: Issues, https://github.com/siegzeon0079/knexflow-rework/issues
Keywords: knex,robotics,stem,education,usb-hid,blockly,compiler
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Education
Classifier: Topic :: Software Development :: Compilers
Classifier: Topic :: System :: Hardware :: Universal Serial Bus (USB) :: Human Interface Device (HID)
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Developers
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: hid
Requires-Dist: pywinusb>=0.4.2; sys_platform == "win32" and extra == "hid"
Requires-Dist: hidapi>=0.14; sys_platform != "win32" and extra == "hid"
Dynamic: license-file

# K'NEX Flow Python library

This package is a cross-platform library and controller compiler for K'NEX Flow programs, validating compiled-package JSON, and uploading compiled packages into stored controller slots. It requires Python 3.10 or later. Library and package validation use only the standard library.

## Install

Install from [PyPI](https://pypi.org/project/knexflow/):

```powershell
pip install knexflow
```

For USB HID uploads to the physical K'NEX Control Box, install the optional `hid` backend:

```powershell
pip install "knexflow[hid]"
```

> [!NOTE]
> On Windows, `knexflow[hid]` uses pure-Python `pywinusb` (no C compiler needed). On Linux and macOS, it uses `hidapi`. The package does not require the vendor Windows desktop application for package validation or upload.

## Command-line interface (`knexflow`)

The CLI provides subcommands for bytecode disassembly, sound bundle management, hardware visualization, diagnostic reporting, backup management, and controller slot uploads:

```powershell
# 1. Disassemble controller bytecode (.knexpackage or compiled JSON):
knexflow disasm path\to\program.knexpackage
knexflow disasm path\to\program.json -o program.asm

# 2. Inspect sound assets or extract audio payloads from .knexsound bundles / packages:
knexflow sounds path\to\robot_audio.knexsound
knexflow sounds path\to\robot_audio.knexsound -x extracted_sounds\

# 3. Render hardware diagrams (terminal Unicode, SVG vector graphic, or HTML5 digital twin):
knexflow visualize path\to\program.json --format terminal
knexflow visualize path\to\program.json --format svg -o hardware.svg
knexflow visualize path\to\program.json --format html --show

# 4. Analyze recorded telemetry runs and generate anomaly diagnostic reports:
knexflow diagnostics path\to\telemetry.json --format terminal
knexflow diagnostics path\to\telemetry.json --format markdown -o report.md
knexflow diagnostics path\to\telemetry.json --format html -o report.html

# 5. Inspect and verify program library backups (legacy positional syntax also supported):
knexflow backup path\to\library-backup.json
knexflow backup path\to\library-backup.json --verify-only

# 6. Upload compiled package to a stored controller slot (0-9):
knexflow upload path\to\compiled-package.json --slot 0 --yes
```

## Program library

The version-1 JSON backup envelope remains compatible with the browser app:

```powershell
knexflow backup path\to\library-backup.json
knexflow backup path\to\library-backup.json --verify-only
```

The API includes `create_text_program`, `create_blocks_program`, `update_program`, `duplicate_program`, `load_backup`, and `save_backup`. Program XML and source text remain user data; backup operations do not parse or execute either language.

## Compiled packages and upload

`CompiledProgram.from_manifest` validates the browser-compatible compiler JSON areas (base64 encoding, fixed area sizes, usable lengths, and sound directory checksums). A `ProgramUploader` accepts a validated package and a `ReportTransport`; it sends the HID download protocol to stored slots 0-9 and checks the controller's slot-presence response. A mock transport can be used for tests or alternative cross-platform HID implementations.

To upload from the CLI, connect the controller and specify the target slot:

```powershell
knexflow upload path\to\compiled-package.json --slot 0
```

The command confirms before replacing a stored slot. `--yes` bypasses that prompt. Upload does **not** start or resume a program; starting remains outside the Python uploader API. Do not confuse a stored-slot upload with temporary development-program staging.

## Compiler status

The pure-Python compiler supports linear Blockly charts and bounded `knex_repeat` blocks, expanded into linear actions, with numeric arithmetic expressions in `knex_wait`, constant-speed `knex_motor_run`, and single-motor `knex_motor_rotations`, plus optional `knex_motor_pair`, `knex_stop_motors` blocks targeting `all`, `knex_output_value` (TriLED channels 0 and 1; off, red, green, yellow, notset), and compile-time sensor configuration blocks `knex_sensor_led` and `knex_sensor_gain` (ports 1-6, LED ON/OFF, gain 0-2). Paired motors support independent ports, directions, and speeds, with continuous or rotation-limited actions. Rotation actions wait for the selected motors to finish. If a motor chart does not end in a stop-all block, a safety stop is appended, matching the official compiler.

Literal rotation counts are limited to 0.1 to 1000. Supported expression operators are `+`, `-`, `*`, `/`, unary minus, and parentheses over numeric literals. Official wait, motor, arithmetic, rotation, coordinated-motor, bounded-repeat, numeric-variable, distance-conditional, sensor-configuration, display block, bounded while loop, and named procedure fixtures match byte-for-byte, including package header and code area when given each fixture timestamp. Repeat counts must be integer literals from 1 to 100, nested repeat depth is limited to 8, and expanded programs are limited to 250 blocks.

Conditional support includes `knex_if_variable`, `knex_if_sensor_distance`, and `knex_if_boolean` (push-button). Numeric conditions may read assigned variables; distance conditions use a port from 1 to 6 and a numeric or previously assigned variable threshold in millimetres. Branches support waits, constant-speed motor runs, single-motor rotations, coordinated-motor actions, output values, and LCD display commands (clear LCD and print text on lines 0-3).

## High-level controller API (`KnexBox`)

For interactive or robotic scripting, `KnexBox` provides a fluent, object-oriented API for building and compiling controller programs:

```python
from knexflow import KnexBox

box = KnexBox("Rover")
box.motor("A", speed=50, direction="forward")
box.wait(1.5)
box.display_text(line=0, text="Moving...")
box.stop_all()

# Or with bounded while loops and variable assignments:
box.assign("count", 3)
with box.while_loop("count > 0", max_iterations=3):
    box.motor("A", speed=40)
    box.wait(1.0)
    box.assign("count", "count - 1")

# Or modular named procedures:
box.call("step", times=2)
box.wait(1.0)
with box.procedure("step"):
    box.motor("A", speed=50)
    box.wait(0.5)
    box.stop_all()

# Compile to validated bytecode
compiled = box.compile()

# Upload directly to slot 0 over USB HID (requires knexflow[hid])
# box.upload(slot=0)
```

## Hardware graphical representation

The library includes a zero-dependency hardware visualization submodule that renders the physical K'NEX Control Box, 4 motor ports (A–D with direction/speed), 6 sensor ports (1–6 with distance/button/color states), 2 TriLED channels, and the 4-line LCD screen:

```python
from knexflow import KnexBox

box = KnexBox("Rover")
box.motor("A", speed=50, direction="forward")
box.wait(1.5)
box.stop_all()

# 1. Console Unicode dashboard (instant view in terminal/PyCharm):
print(box.hardware_dashboard())

# 2. Export vector SVG graphic (previews directly in browser or IDE):
box.hardware_svg("rover_hardware.svg")

# 3. Open interactive digital twin in the default web browser:
box.show_hardware()

# 4. Interactive execution timeline & step-by-step scrubber:
print(box.timeline_dashboard())  # Terminal ASCII/Unicode table
box.show_timeline()              # Browser player with Play/Pause and scrubber
```

## Sound asset management

The package subsystem provides official-compiler parity for inspecting, building, and packing compressed K'NEX sound assets (`131,072`-byte sound area):

```python
from knexflow import KnexBox, build_sound_area, parse_sound_area

# Sample raw sound data (e.g. ISD2130 compressed voice/sfx bytes):
sound1_bytes = bytes([0x55] * 128)
sound2_bytes = bytes([0xAA] * 256)

# Build a sound area from raw compressed audio payloads:
area, length, checksum = build_sound_area([sound1_bytes, sound2_bytes])

# Inspect individual sound directory entries and payloads:
entries = parse_sound_area(area, length, checksum)
for entry in entries:
    print(f"Sound {entry.index}: {entry.length} bytes at [{entry.start_offset}:{entry.end_offset}]")

# Attach sound assets to a KnexBox or compiled package:
box = KnexBox("Sound Demo")
box.wait(1.0)
box.set_sounds([sound1_bytes, sound2_bytes])
compiled = box.compile()
print(f"Compiled sounds: {len(compiled.sounds)}")
sound_blobs = compiled.extract_sounds()

# Export or import portable .knexsound bundles (zip archives with manifest):
box.export_sound_bundle("robot_audio.knexsound")
box.load_sound_bundle("robot_audio.knexsound")
```

## Telemetry replay bridge

Decode raw USB HID telemetry reports and replay recorded runs into the interactive digital twin:

```python
from knexflow import KnexBox

box = KnexBox("Telemetry Replay")
box.motor("A", speed=50)
box.wait(1.0)
box.stop_all()

# Recorded sequence of timestamped raw packets or telemetry dictionaries:
sample_packets = [
    {"timestamp_ms": 0, "motors": {"A": {"speed": 50, "direction": "forward"}}, "sensors": {"1": 150}, "lcd_lines": ["System Boot"]},
    {"timestamp_ms": 500, "motors": {"A": {"speed": 50, "direction": "forward"}}, "sensors": {"1": 80}, "lcd_lines": ["Moving"]},
    {"timestamp_ms": 1000, "motors": {"A": {"speed": 0, "direction": "off"}}, "sensors": {"1": 20}, "lcd_lines": ["Stopped"]},
]

timeline = box.replay_telemetry(sample_packets, title="Diagnostic Run 1")
print(timeline.render_dashboard())
timeline.show()
```

## Offline diagnostic reporting

Analyze recorded controller sessions, detect hardware/interpreter anomalies (low battery, motor stalls, stop codes), and generate structured diagnostic reports in Markdown, HTML, or Terminal formats:

```python
from knexflow import KnexBox

box = KnexBox("Diagnostic Demo")

# Sample recorded session telemetry:
sample_records = [
    {"timestamp_ms": 0, "battery_mv": 7200, "cpu_load": 10, "events": ["BOOT"]},
    {"timestamp_ms": 1000, "battery_mv": 7150, "cpu_load": 25, "events": ["MOTOR_RUN"]},
    {"timestamp_ms": 2000, "battery_mv": 7100, "cpu_load": 15, "events": ["IDLE"]},
]

# 1. Quick terminal summary table:
print(box.diagnostic_summary(sample_records))

# 2. Export full Markdown or HTML report:
box.generate_diagnostic_report(sample_records, output_path="diagnostic_run.md", format="markdown")
box.generate_diagnostic_report(sample_records, output_path="diagnostic_run.html", format="html")
```

## Tone and melody generator

Compose musical tones and melodies with 12-TET note resolution (`C3`–`C6`), standard beat fraction timings (`whole`, `half`, `quarter`, `eighth`, `sixteenth`), and offline WAV generation:

> [!NOTE]
> **Hardware Compatibility**: The K'NEX Control Box firmware does not have a raw tone frequency generator opcode (official audio relies on opcode `0x0A OutputSound` pointing to compressed sound payloads in the ISD2130 chip sound area). Tones preview interactively in the browser timeline player (`box.show_timeline()`) and can be exported to standard WAV files (`generate_tone_wav`). When programs containing tone blocks are compiled to controller packages (`box.compile()`), tone blocks are lowered to equivalent duration pauses (`knex_wait`) to preserve package validity without sending unverified opcodes to the hardware.

```python
from knexflow import KnexBox, generate_tone_wav, generate_melody_wav

box = KnexBox("Audio & Melody Demo")

# 1. Fluent box tone and melody programming:
box.tone("C4", 0.5)                 # Play 261.63 Hz for 0.5s
box.play_note("G4", "quarter")      # Play note G4 at current BPM (default 120 BPM = 0.5s)
box.beep(880, 0.1)                  # Play quick 880 Hz beep
box.play_melody([                   # Play sequenced melody
    ("C4", "quarter"),
    ("E4", "quarter"),
    ("G4", "half"),
    ("rest", "quarter"),
], bpm=120)

# 2. Offline audio synthesis to 16-bit PCM WAV (zero external dependencies):
wav_data = generate_tone_wav("A4", duration_seconds=1.0)
melody_wav = generate_melody_wav([("C4", "quarter"), ("G4", "half")], bpm=120)

# 3. Interactive Web Audio preview:
# Tones play back automatically via the browser Web Audio API in the timeline player:
box.show_timeline()
```

## Bytecode disassembly inspection

Inspect compiled controller p-code with mnemonics, byte addresses, and parameter decoding:

```python
from knexflow import KnexBox

box = KnexBox("Rover")
box.motor("A", speed=50, direction="forward")
box.wait(1.0)
box.stop_all()

# 1. Disassemble directly from KnexBox:
print(box.disassemble())

# 2. Disassemble a compiled package or official fixture:
compiled = box.compile()
print(compiled.disassemble())
```

## Tests

Run the standard-library tests from the repository root:

```powershell
python tools/test_all.py
```
