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:
pip install knexflow
For USB HID uploads to the physical K'NEX Control Box, install the optional hid backend:
pip install "knexflow[hid]"
Command-line interface (knexflow)
The CLI provides subcommands for bytecode disassembly, sound bundle management, hardware visualization, diagnostic reporting, backup management, and controller slot uploads:
# 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:
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:
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:
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:
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):
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:
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:
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:
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:
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:
python tools/test_all.py
Metadata
Release files for knexflow 0.2.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| knexflow-0.2.3.tar.gz | 240.9 kB | With provenance | Details for knexflow-0.2.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| knexflow-0.2.3-py3-none-any.whl | Python 3 | none | any | Details for knexflow-0.2.3-py3-none-any.whl |
Total release size: 510.2 kB
Release files / knexflow-0.2.3.tar.gz
| Download URL | knexflow-0.2.3.tar.gz |
|---|---|
| Size | 240.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
dc316061a64347fcc82f225f5b3b4f246309dc9e0cdf1c38a1fdfb14bbb019eb
|
|
BLAKE2b-256 checksum How to use checksums |
44385a91a50d231d61e76b70bb5f16093425b0ab4e149b5a981112b41dac52f4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.
Transparency logRelease files / knexflow-0.2.3-py3-none-any.whl
| Download URL | knexflow-0.2.3-py3-none-any.whl |
|---|---|
| Size | 269.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
024de2458e5ebc71cacce31dfe6141bccef5e2238ed84836c2b331fa4b4f0bf4
|
|
BLAKE2b-256 checksum How to use checksums |
a98ec195ec9a8d1a5b41a7d59999a8d26e842cf1dce7d146a0df86d6a99ab537
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.
Transparency logSecurity for knexflow 0.2.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for knexflow-0.2.3.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.