Metadata-Version: 2.4
Name: knexflow
Version: 0.2.0
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: hidapi>=0.14; extra == "hid"
Dynamic: license-file

# K'NEX Flow Python library



This package is a cross-platform library for editing K'NEX Flow program

libraries, 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



From this directory:



```powershell

python -m pip install .

```



For USB HID uploads, install the optional `hidapi` backend:



```powershell

python -m pip install ".[hid]"

```



The HID backend depends on the operating system's USB HID permissions and

driver configuration. The package does not require the vendor Windows desktop

application for package validation or upload.



## Command-line interface (`python -m knexflow_library` or `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):
python -m knexflow_library disasm path\to\program.knexpackage
python -m knexflow_library disasm path\to\program.json -o program.asm

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

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

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

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

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

## Program library

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

```powershell
python -m knexflow_library path\to\library-backup.json
python -m knexflow_library --verify-only path\to\library-backup.json
```



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

python -m knexflow_library --upload-package 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 experimental 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. That compiler's generated safety

stop also includes Port A when it was not selected; the Python output preserves

that observed behavior.

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. Other variable uses, sensor expressions, and chained

same-precedence operators outside the vendor grammar are rejected. 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.



Official reference fixtures and timestamp/volatile-byte notes are in

`../tests/fixtures/compiler/`. Add a fixture and an exact Python comparison

before extending the compiler with each new instruction family. Other variable

constructs, sensor actions, other conditional forms, loops, procedures, sounds, and

images are not implemented. Repeat blocks are statically expanded; they are

not runtime loops. Conditional support is limited to one `knex_if_variable`,

`knex_if_sensor_distance`, or `knex_if_boolean` (push-button) per chart. 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). Any chart with a motor branch must end with an explicit stop-all

continuation; automatic branch safety stops and unverified motor action types

are not implemented. Rotations use fixture-verified motor completion wait

masks. Branch addresses are linked to fixture-verified native byte offsets.

Unassigned-variable reads, sensor conditions other than distance and button, and

nested/multiple conditionals are rejected. Push-button conditions use `button(port)`

from ports 1 to 6 compared with 0 or 1 using `==` or `!=`. Distance conditions declare the

selected sensor requirement. Current distance fixtures cover ports 1, 2, 3,

4, 5, and 6; all six comparison operators; and literal, arithmetic,

assigned-variable, and variable-arithmetic thresholds. The compiler supports numeric

`knex_variable_set` assignments before the conditional, including reassignments

and arithmetic that reads variables assigned earlier in the chart. Variables

may also appear in either comparison expression. Reading an unassigned

variable, assigning after the conditional, and assignments inside branches

remain unsupported.



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

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

```python
from knexflow_library 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_library[hid])
# box.upload(slot=0)
```

## Hardware graphical representation (`knexflow_library.visual`)

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
# 1. Console Unicode dashboard (instant view in PyCharm/terminal):
print(box.hardware_dashboard())

# 2. Export vector SVG graphic (previews directly in PyCharm):
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 (`knexflow_library.packages`)

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_library import build_sound_area, parse_sound_area

# 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.set_sounds([sound1_bytes, sound2_bytes])
compiled = box.compile()
print(compiled.sounds)           # Tuple of SoundDirectoryEntry
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 (`knexflow_library.visual`)

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

```python
from knexflow_library.visual import TelemetryDecoder, replay_telemetry_to_timeline

# Replay a recorded sequence of timestamped raw packets or telemetry dictionaries:
timeline = box.replay_telemetry(recorded_packets, title="Diagnostic Run 5")
print(timeline.render_dashboard())
timeline.show()
```

## Offline diagnostic reporting (`knexflow_library.visual.diagnostics`)

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_library import analyze_telemetry, generate_diagnostic_report

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

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

## Tone and melody generator (`knexflow_library.audio`)

Compose musical tones and melodies similar to mBot / buzzer APIs 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_library import generate_tone_wav, generate_melody_wav

# 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 (`knexflow_library.disassembler`)

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

```python
# 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 -m unittest discover -s tests\python -v

```

