Metadata-Version: 2.4
Name: knexflow
Version: 0.3.1
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"
Provides-Extra: desktop
Requires-Dist: pywebview>=5.0; extra == "desktop"
Provides-Extra: esp32
Requires-Dist: pyserial>=3.5; extra == "esp32"
Requires-Dist: bleak>=0.22; extra == "esp32"
Dynamic: license-file

# K'NEX Flow Python Library (`knexflow`)

Cross-platform Python SDK, pure-Python bytecode compiler, Nuvoton ISD2130 ADPCM audio engine, offline Web Studio server, and wired/wireless hardware transport suite for the K'NEX Robotics Control Box (`VID: 0x2A3A`, `PID: 0x03E8`).

Requires **Python 3.10+**. Core compilation, KinexBasic parsing/linting, ISD2130 audio encoding, 128×64 LCD bitmap generation, and `.knexproj` packaging use **only the Python standard library**.

---

## Installation

Install the core library and compiler from [PyPI](https://pypi.org/project/knexflow/):

```powershell
pip install knexflow
```

Optional hardware and desktop extras:

```powershell
# Direct USB HID connection to the K'NEX Control Box (pywinusb on Windows, hidapi on Linux/macOS):
pip install "knexflow[hid]"

# ESP32-S3 USB-Host Serial, Wi-Fi TCP, and BLE GATT wireless bridge support (pyserial + bleak):
pip install "knexflow[esp32]"

# Native standalone desktop window wrapper around Web Studio (pywebview):
pip install "knexflow[desktop]"
```

---

## Command-Line Interface (`knexflow`)

```powershell
# Launch the offline Web Studio IDE (http://127.0.0.1:8765) or native desktop app:
knexflow studio
knexflow app

# Compile, lint, format, profile, or disassemble KinexBasic (.kbas) / Blockly / .knexpackage files:
knexflow compile path\to\program.kbas -o compiled.json
knexflow lint path\to\program.kbas --format
knexflow profile path\to\program.kbas
knexflow disasm path\to\program.knexpackage

# Probe hardware, upload to Stored Slots (0-9), or 1-click stage & run in Dev Slot 255:
knexflow probe --factory --eeprom
knexflow upload path\to\compiled.json --slot 0 --yes
knexflow run path\to\program.kbas

# ESP32-S3 USB-Host bridge discovery, probing, and PlatformIO firmware / LittleFS packaging:
knexflow esp32 --scan
knexflow esp32 --ble-scan
knexflow esp32 --port COM5 --probe
knexflow esp32 --host 192.168.4.1 --probe
knexflow esp32 --ble KNEXFlow-Bridge --probe
knexflow esp32 --build-fw
knexflow esp32 --build-fs

# Inspect sound bundles, render hardware diagrams, or generate telemetry diagnostic reports:
knexflow sounds path\to\robot_audio.knexsound
knexflow visualize path\to\compiled.json --format terminal
knexflow diagnostics path\to\telemetry.json --format markdown -o report.md
knexflow backup path\to\library-backup.json --verify-only
```

---

## High-Level Controller API (`KnexBox`)

`KnexBox` provides a fluent API for authoring standalone controller bytecode programs or running 50 Hz host-tethered RPC loops:

```python
from knexflow import KnexBox

box = KnexBox("Autonomous Rover")

# Parameterized procedures, variables, and smart-lowered math (abs, min, max, clamp, sqrt, pow, log2):
with box.procedure("spin_check", params=["speed"]):
    box.motor("A", speed="speed", direction="forward")
    box.wait(0.5)
    box.stop_all()

box.assign("dist_cm", "distance(1) / 10")
with box.if_sensor_distance(port=1, operator="<", threshold_mm=200):
    box.cue("obstacle", volume=90)
    box.say("obstacle", volume=100)
    box.call("spin_check", args=[60])

# Compile to validated controller package (bytecode + ISD2130 ADPCM soundArea + 128x64 imageArea):
compiled = box.compile()

# 1-Click remote execution on physical hardware via volatile Development Slot 255 (requires knexflow[hid]):
# box.run()

# Or upload to non-volatile Stored Slots 0-9 (started manually via the Control Box keypad):
# box.upload(slot=0)
```

---

## ESP32-S3 Wireless & Serial Bridge (`knexflow_library.esp32`)

Connect to a K'NEX Control Box plugged into an **ESP32-S3-DevKitC-1 N16R8** USB-OTG Host bridge over USB-UART Serial (`115200` baud), Wi-Fi TCP (`:3333`, including the ESP32's standalone `192.168.4.1` SoftAP `KNEXFlow-Bridge-XXXX`), or Bluetooth Low Energy GATT (`bleak`).

All three transports implement the standard `ReportTransport` interface and drop directly into `ProgramUploader`, `DemuxedTransport`, `ControllerDebugger`, and `KnexBox`:

```python
from knexflow_library import (
    ControllerDebugger,
    Esp32BleTransport,
    Esp32SerialTransport,
    Esp32TcpTransport,
    ProgramUploader,
    discover_esp32_ble_devices,
    discover_esp32_ports,
)

# 1. Discover local serial or BLE bridges:
print(discover_esp32_ports())
print(discover_esp32_ble_devices())

# 2. Connect over Serial (DTR/RTS disabled automatically), Wi-Fi SoftAP/STA TCP, or BLE GATT:
transport = Esp32TcpTransport("192.168.4.1", port=3333)
# transport = Esp32SerialTransport("COM5")
# transport = Esp32BleTransport("KNEXFlow-Bridge")

try:
    print(transport.get_status())  # {"board": "ESP32-S3-N16R8", "hid_ready": True, "audio_offload": True, ...}
    uploader = ProgramUploader(transport)
    result = uploader.upload_dev(compiled)
    if result.verified:
        ControllerDebugger(transport).start()
finally:
    transport.close()
```

---

## Pure-Software Nuvoton ISD2130 Audio, Melodies & Voice Synthesis

The library includes a clean-room, zero-dependency Python implementation of the Nuvoton ISD2130 4-bit Enhanced ADPCM codec (`isd2130_encode` / `isd2130_decode`), eliminating any dependency on legacy 32-bit Windows `ISD.dll`:

- **Musical Tones & 17 Built-in RTTTL Melodies:** `box.tone()`, `box.play_note()`, `box.play_melody()`, `box.play_rtttl()`
- **9 Procedural 8-Bit Retro SFX Presets:** `lion_roar`, `jump`, `laser`, `coin`, `alarm`, `siren`, `robot_chirp`, `powerup`, `explosion`
- **Autonomous Audio Telemetry Cues (`box.cue`):** `ready`, `obstacle`, `warning`, `error`, `success`, `scan`, `click`, `low_battery`
- **3-Formant Robotic Voice Prompts (`box.say`):** `"ready"`, `"go"`, `"obstacle"`, `"warning"`, `"stop"`, `"error"`, `"complete"`
- **ESP32-S3 Audio Offload Descriptors:** Compiled manifests (`compile_workspace`) automatically include compact `soundDescriptors` (`M:...`, `N:...`, `S:...`, `P:...`) so Web Studio and ESP32-S3 bridges can synthesize and encode ISD2130 audio directly in the ESP32-S3's 8 MB PSRAM (`AUDIO_STAGE`).

```python
from knexflow import KnexBox, build_sound_area, compile_workspace, isd2130_decode, isd2130_encode

box = KnexBox("Audio Demo")
box.cue("ready", volume=80)
box.say("go", volume=100)
box.play_rtttl("tetris")

compiled = box.compile()
manifest = compile_workspace(box.to_xml(), "Audio Demo", compile_tones=True)
print(f"Sound entries: {len(compiled.sounds)}, Descriptors: {manifest.get('soundDescriptors')}")
```

---

## 128×64 Graphic LCD, Portable `.knexproj` Archives & Robotics Submodules

- **128×64 Monochrome LCD (`knexflow_library.image`):** Page-based bitmap encoder (32 frames in 32 KB `imageArea`), GIF dithering, and procedural animations (`generate_lion_mascot_animation`, `generate_oiia_spinning_cat_animation`, `generate_radar_sweep_animation`, `generate_dashboard_frames`).
- **Portable Project Bundler (`KnexProject`):** Single-file `.knexproj` archives with deterministic CRC32 tamper detection storing KinexBasic source, Blockly XML, LCD frames, audio tracks, and 2D Virtual Arena state (`KnexProject.load("lab01.knexproj").compile()`).
- **In-Flight Hardware Debugger (`ControllerDebugger`):** Hardware PC breakpoint traps (`'CF'`/`'CH'`), pause/resume/single-step (`'CD'`/`'CE'`/`'CC'`), and live PIC float register watch & injection (`'CG'`).
- **Autonomous Navigation, CAD & ROS 2 (`knexflow_library.navigation`, `.cad`, `.ros`):** Shortest-arc 2D PID waypoint controller with Motor Action 4 encoder origin homing, K'NEX Studio `.json` 3D CAD parser & BOM analyzer, and ROS 2 `/odom`, `/tf`, `/range`, `/cmd_vel` bridge.

---

## Documentation & Examples Index

- **Complete Python SDK & AI-Agent Reference:** [`docs/PYTHON_SDK_REFERENCE.md`](../docs/PYTHON_SDK_REFERENCE.md) (also bundled in `knexflow_library/web/docs/PYTHON_SDK_REFERENCE.md`)
- **Python Subsystem Architecture Analysis:** [`docs/PYTHON_SUBSYSTEM_ANALYSIS.md`](../docs/PYTHON_SUBSYSTEM_ANALYSIS.md)
- **Hardware & Bytecode Technical Specification:** [`docs/KNEXFLOW_TECHNICAL_SPECIFICATION.md`](../docs/KNEXFLOW_TECHNICAL_SPECIFICATION.md)
- **KinexBasic EBNF Grammar:** [`docs/grammar_text_dsl.ebnf`](../docs/grammar_text_dsl.ebnf)
- **ESP32-S3 Wireless Bridge Example (with `--dry-run`):** [`examples/esp32_wireless_bridge.py`](../examples/esp32_wireless_bridge.py)

---

## Tests

Run the unified Node.js and Python test suite from the repository root:

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