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:
python -m pip install .
For USB HID uploads, install the optional hidapi backend:
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:
# 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:
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:
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:
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:
# 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):
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:
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:
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:
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:
# 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 -m unittest discover -s tests\python -v
Metadata
Release files for knexflow 0.2.0
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.0.tar.gz | 241.3 kB | With provenance | Details for knexflow-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| knexflow-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for knexflow-0.2.0-py3-none-any.whl |
Total release size: 510.6 kB
Release files / knexflow-0.2.0.tar.gz
| Download URL | knexflow-0.2.0.tar.gz |
|---|---|
| Size | 241.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bbb485eef3840581390d7d65732a7dd85233d06f505889a828262ba30fe44c7c
|
|
BLAKE2b-256 checksum How to use checksums |
1bda212cc103c32ccb8ffced935a5e55291ce81c903da6f16b90e7c92f2572fa
|
| 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.0-py3-none-any.whl
| Download URL | knexflow-0.2.0-py3-none-any.whl |
|---|---|
| Size | 269.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
0ae16079849142b94da92f82731e76f30649446ba914341c5794ba3189cdb454
|
|
BLAKE2b-256 checksum How to use checksums |
32ef3e2c84853802e53ea0c3b38433b630c7363b9e30cecaf06fbee45075bd54
|
| 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.0
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.0.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.