diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 0000000..d2f3cf3 --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,43 @@ +name: Checks + +on: + pull_request: + push: + branches: [work, main] + +jobs: + python: + name: Python syntax and parser smoke + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Compile GUI module + run: python -m py_compile gui/portable_avr_control_studio.py + - name: Parser smoke tests + run: | + python - <<'PY' + from gui.portable_avr_control_studio import parse_serial_line + assert parse_serial_line('OK,PING\n').kind == 'OK' + assert parse_serial_line('ERR,BAD,message\n').kind == 'ERR' + assert parse_serial_line('CONFIG,DEVICE_NAME=Unit,SENSOR_VREF_MV=5000\n').fields['SENSOR_VREF_MV'] == '5000' + assert parse_serial_line('STATUS,SENSOR_RAW=512,SENSOR_MV=2502\n').fields['SENSOR_MV'] == '2502' + assert parse_serial_line('DATA,INFO,protocol=2\n').fields['PROTOCOL'] == '2' + assert parse_serial_line('garbage\n').malformed + PY + + avr-compile: + name: Arduino AVR Uno compile + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install Arduino CLI + uses: arduino/setup-arduino-cli@v2 + - name: Install AVR core + run: | + arduino-cli core update-index + arduino-cli core install arduino:avr + - name: Compile Uno firmware + run: arduino-cli compile --fqbn arduino:avr:uno firmware/PortableAVRControlStudio diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f6a3e7b --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +build/ +dist/ +*.spec diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..5ae19f4 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,9 @@ +# Repository Agent Instructions + +This repository is a draft Portable AVR Control Studio project. Follow these rules for all files in this tree: + +- Keep claims conservative: do not state or imply physical hardware testing unless a human has provided test evidence. +- Treat Arduino Uno / ATmega328P AVR as the primary firmware target unless a documented hardware profile says otherwise; Nano may be referenced only as a compatible secondary option. +- Keep customer-facing runtime settings aligned across firmware, GUI, README, and protocol docs. +- Unknown hardware must be handled through documented profiles, not automatic detection claims. +- Keep the GitHub PR as Draft until Python smoke checks and AVR compile checks are documented, and until AVR compile checks are reproducible in CI or local maintainer notes. diff --git a/README.md b/README.md index 2299379..bac5fac 100644 --- a/README.md +++ b/README.md @@ -1 +1,112 @@ -# Arduino \ No newline at end of file +# Portable AVR Control Studio + +Portable AVR Control Studio is a portable, Windows-centered control and configuration studio for Arduino Uno / ATmega328P AVR deployments. The Arduino Uno already uses an AVR-compatible target; this project compiles firmware for that Uno AVR target and controls/configures it from a portable Tkinter desktop application. + +## Architecture + +```text +Windows GUI (Tkinter + optional pyserial) + | + | newline-delimited 115200 baud ASCII protocol + v +Arduino Uno / ATmega328P AVR firmware + | + | validated Config struct + EEPROM persistence + v +Sensor input + relay / buzzer outputs documented by hardware profile +``` + +### Firmware + +The sketch in `firmware/PortableAVRControlStudio/PortableAVRControlStudio.ino` provides: + +- EEPROM-backed `Config` storage with magic/version validation. +- Factory defaults for the Arduino Uno / ATmega328P AVR primary target. +- Safe fixed-buffer serial command parsing without Arduino `String`. +- Customer-facing runtime settings for device name, sensor VREF, thresholds, relay mode, buzzer enable, eco mode, telemetry interval, and UI language placeholder. +- Separate hardware/profile settings for sensor pin, relay pin, buzzer pin, and output polarity. +- `RELAY_MODE=AUTO` threshold hysteresis based on sensor millivolt readings. +- Clear `OK`, `ERR`, `CONFIG`, `STATUS`, and `DATA` responses. + +Supported commands are documented in [`docs/PROTOCOL.md`](docs/PROTOCOL.md), including `PING`, `INFO`, `GET_CONFIG`, `GET_STATUS`, `SET,,`, `SAVE_CONFIG`, `LOAD_CONFIG`, `FACTORY_RESET`, `RELAY,ON|OFF|TOGGLE`, and `BUZZER,ON|OFF|TOGGLE`. `INFO` intentionally returns `DATA,INFO,...` metadata; command acknowledgements use `OK,`. + +### Windows GUI + +The desktop app in `gui/portable_avr_control_studio.py` is branded as **Portable AVR Control Studio** and includes these areas: + +- Connection +- Firmware +- Settings +- Live Monitor +- Hardware Profiles +- Diagnostics +- Logs +- About / Handoff + +Runtime settings are configurable from the GUI. The Settings tab validates values before sending them to firmware, including device-name length/characters, numeric ranges, threshold ordering, telemetry and VREF ranges, editable pin ranges, and enum values such as `MANUAL`/`AUTO` and `ON`/`OFF`. + +The GUI can read settings from the board, edit settings, send runtime settings, save settings to EEPROM, factory reset the board, test the relay, and test the buzzer. It parses `OK`, `ERR`, `CONFIG`, `STATUS`, and `DATA` lines defensively so malformed serial data is logged instead of crashing the application. + +Demo mode remains available for presentations, but it is explicitly labelled as **simulation only** and does not communicate with physical hardware. + +## Runtime settings and hardware profiles + +Customer-facing runtime settings are listed in [`docs/product_spec.md`](docs/product_spec.md) and [`docs/PROTOCOL.md`](docs/PROTOCOL.md). Use **Save to EEPROM** after a successful configuration update if the settings should persist after reset or power loss. + +Hardware profiles in `docs/profiles/` document expected wiring, output polarity, sensor assumptions, and limitations. Hardware profiles do **not** auto-detect unknown hardware. Driver boards, inverted outputs, sensor circuits, or additional peripherals may require both a matching profile and matching firmware changes. + +## Firmware upload status + +The Firmware tab supports selecting prepared `.hex` firmware artifacts as a placeholder handoff workflow. It must not be presented as a fully validated production uploader until the uploader, target MCU flags, COM-port behavior, hardware profile, and firmware artifact have been packaged and tested together. + +## Firmware compile checks + +Install Arduino CLI and run the compile checks documented in [`docs/ARDUINO_CLI.md`](docs/ARDUINO_CLI.md): + +```bash +arduino-cli core update-index +arduino-cli core install arduino:avr +arduino-cli compile --fqbn arduino:avr:uno firmware/PortableAVRControlStudio +``` + +Optional compatible Nano check (secondary only, not required for merge): + +```bash +arduino-cli compile --fqbn arduino:avr:nano firmware/PortableAVRControlStudio +``` + +These are compile checks only for the Arduino Uno AVR target. This repository does **not** claim physical hardware testing. + +## Python smoke checks + +From the repository root: + +```bash +python -m py_compile gui/portable_avr_control_studio.py +python - <<'PY' +from gui.portable_avr_control_studio import parse_serial_line +assert parse_serial_line('OK,PING\n').kind == 'OK' +assert parse_serial_line('CONFIG,RELAY_MODE=AUTO,SENSOR_VREF_MV=5000\n').fields['RELAY_MODE'] == 'AUTO' +assert parse_serial_line('STATUS,SENSOR_RAW=123,SENSOR_MV=601\n').fields['SENSOR_RAW'] == '123' +assert parse_serial_line('garbage\n').malformed +PY +``` + +Install `pyserial` when using real COM ports: + +```bash +python -m pip install pyserial +``` + +## Portable Windows EXE packaging + +See [`docs/PACKAGING.md`](docs/PACKAGING.md). A typical PyInstaller build is: + +```powershell +py -m pip install pyinstaller pyserial +py -m PyInstaller --noconfirm --onefile --windowed --name PortableAVRControlStudio gui\portable_avr_control_studio.py +``` + +## Draft status and hardware-test limitation + +Keep the PR as a real GitHub Draft until documented checks are passing and any required AVR compile evidence is captured. No physical hardware test has been claimed in this repository; real boards, sensors, relays, buzzers, power, and enclosure hardware must be validated before customer deployment. diff --git a/docs/ARDUINO_CLI.md b/docs/ARDUINO_CLI.md new file mode 100644 index 0000000..2fc5288 --- /dev/null +++ b/docs/ARDUINO_CLI.md @@ -0,0 +1,19 @@ +# Arduino CLI Compile Checks + +Use Arduino CLI to compile the Arduino Uno / ATmega328P AVR primary target before firmware handoff: + +```bash +arduino-cli core update-index +arduino-cli core install arduino:avr +arduino-cli compile --fqbn arduino:avr:uno firmware/PortableAVRControlStudio +``` + +Optional compatible Nano compile check (secondary only, not required for merge): + +```bash +arduino-cli compile --fqbn arduino:avr:nano firmware/PortableAVRControlStudio +``` + +The GitHub Actions workflow in `.github/workflows/checks.yml` runs the required Uno compile using `arduino/setup-arduino-cli`. The Nano command is optional documentation only and is not required for merge. + +These checks verify that the sketch compiles for the Arduino Uno AVR target. They do not prove relay/buzzer wiring, driver polarity, sensor calibration, EEPROM behavior on a specific board, or physical safety. Do not claim physical hardware testing until it has been performed on the target hardware profile. diff --git a/docs/PACKAGING.md b/docs/PACKAGING.md new file mode 100644 index 0000000..7559156 --- /dev/null +++ b/docs/PACKAGING.md @@ -0,0 +1,38 @@ +# Portable Windows Packaging + +The GUI is a standard-library Tkinter application with optional `pyserial` support for real COM ports. + +## Development smoke checks + +```powershell +py -m py_compile gui\portable_avr_control_studio.py +py gui\portable_avr_control_studio.py +``` + +Install serial support when using physical hardware: + +```powershell +py -m pip install pyserial +``` + +## Portable EXE build + +A common Windows handoff package can be built with PyInstaller: + +```powershell +py -m pip install pyinstaller pyserial +py -m PyInstaller --noconfirm --onefile --windowed --name PortableAVRControlStudio gui\portable_avr_control_studio.py +``` + +Copy these items into the customer handoff folder: + +1. `dist\PortableAVRControlStudio.exe` +2. `README.md` +3. `docs\PROTOCOL.md` +4. `docs\product_spec.md` +5. `docs\testing.md` +6. `docs\customer_handoff.md` +7. `docs\profiles\*.json` +8. Prepared `.hex` firmware artifacts, if firmware upload is part of the handoff + +The firmware upload tab is a placeholder workflow for prepared `.hex` artifacts. A production package should bundle and test the selected uploader, target MCU flags, COM-port behavior, and profile-specific firmware before presenting upload as a one-click customer feature. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md new file mode 100644 index 0000000..8972875 --- /dev/null +++ b/docs/PROTOCOL.md @@ -0,0 +1,56 @@ +# Portable AVR Control Studio Serial Protocol + +The firmware exposes a newline-delimited ASCII protocol at `115200` baud for the Arduino Uno / ATmega328P AVR primary target. Commands are intentionally small so they can be parsed without Arduino `String` allocations. + +## Response format + +The protocol consistently uses these prefixes: + +- `OK,` acknowledges commands that only need acknowledgement. +- `ERR,,` reports rejected commands or validation failures. +- `CONFIG,KEY=VALUE,...` reports the complete active configuration. +- `STATUS,KEY=VALUE,...` reports live state and telemetry. +- `DATA,,KEY=VALUE,...` reports informational payloads. `INFO` returns `DATA,INFO,...` because it is metadata rather than a state-changing acknowledgement. + +The GUI parser accepts these prefixes and logs malformed/unknown data instead of crashing. + +## Commands + +| Command | Purpose | +| --- | --- | +| `PING` | Check that firmware is responsive; returns `OK,PING`. | +| `INFO` | Return `DATA,INFO` metadata for app, firmware, board, protocol, and baud. | +| `GET_CONFIG` | Return all runtime and hardware/profile settings. | +| `GET_STATUS` | Return relay, buzzer, sensor raw/mV, threshold, uptime, and active pins. | +| `SET,,` | Validate and apply one runtime or hardware/profile setting in RAM. | +| `SAVE_CONFIG` | Persist the active configuration to EEPROM. | +| `LOAD_CONFIG` | Load a valid EEPROM configuration. | +| `FACTORY_RESET` | Restore factory defaults and save them to EEPROM. | +| `RELAY,ON` / `RELAY,OFF` / `RELAY,TOGGLE` | Drive the configured relay output when `RELAY_MODE=MANUAL`. | +| `BUZZER,ON` / `BUZZER,OFF` / `BUZZER,TOGGLE` | Drive the configured buzzer output when `BUZZER_ENABLED=ON`. | + +## Customer-facing runtime settings + +| Key | Valid values | Notes | +| --- | --- | --- | +| `DEVICE_NAME` | 1-16 printable ASCII characters, no commas | Customer-facing board label. | +| `SENSOR_VREF_MV` | `1000`-`5500` | ADC reference used to convert raw sensor readings to millivolts. | +| `THRESHOLD_LOW` | `0`-`5500`, less than `THRESHOLD_HIGH` | AUTO relay turns on at or below this sensor mV. | +| `THRESHOLD_HIGH` | `0`-`5500`, greater than `THRESHOLD_LOW`, not above `SENSOR_VREF_MV` | AUTO relay turns off at or above this sensor mV. | +| `RELAY_MODE` | `MANUAL` or `AUTO` | AUTO uses threshold hysteresis; manual relay commands are rejected in AUTO. | +| `BUZZER_ENABLED` | `ON` or `OFF` | OFF forces buzzer output off and rejects buzzer test commands. | +| `ECO_MODE` | `ON` or `OFF` | ON enforces an effective telemetry interval of at least 5000 ms. | +| `TELEMETRY_MS` | `250`-`60000` | Periodic `STATUS` interval. | +| `UI_LANGUAGE` | `EN` | Placeholder for future localization. | + +## Hardware/profile settings + +| Key | Valid values | Notes | +| --- | --- | --- | +| `SENSOR_PIN` | `A0`-`A5` or `14`-`19` | Bundled profile default is A0/14. | +| `RELAY_PIN` | Digital pin `2`-`13` | D0/D1 remain reserved for serial. | +| `BUZZER_PIN` | Digital pin `2`-`13` | Must differ from `RELAY_PIN`. | +| `RELAY_ACTIVE_HIGH` | `0`, `1`, `ON`, `OFF`, `TRUE`, `FALSE`, `HIGH`, `LOW` | Controls output polarity. | +| `BUZZER_ACTIVE_HIGH` | Same boolean values | Controls output polarity. | + +Hardware/profile settings should match documented wiring and firmware expectations. They are not automatic hardware detection. diff --git a/docs/customer_handoff.md b/docs/customer_handoff.md new file mode 100644 index 0000000..2095d96 --- /dev/null +++ b/docs/customer_handoff.md @@ -0,0 +1,25 @@ +# Customer Handoff Notes + +## What is included + +- AVR firmware for the Arduino Uno / ATmega328P primary target. +- Windows-centered Tkinter GUI for runtime configuration and monitoring. +- Demo mode for simulation-only presentations. +- Hardware profile documentation for expected wiring and polarity. +- Placeholder prepared `.hex` firmware artifact workflow. + +## What must be confirmed before delivery + +1. Compile firmware for the Arduino Uno / ATmega328P AVR target. +2. Validate the selected hardware profile against real wiring. +3. Test relay and buzzer polarity with the final driver modules. +4. Confirm sensor scaling and thresholds with the actual sensor circuit. +5. Package the GUI as a Windows EXE and include profile/docs files. +6. Validate any firmware upload workflow with the bundled uploader and target hardware. + +## Important limitations to communicate + +- Demo mode is simulation only and does not prove hardware behavior. +- Hardware profiles document assumptions; they do not auto-detect unknown boards or wiring. +- Firmware upload is currently a prepared-artifact placeholder unless an uploader is bundled/configured/tested. +- No physical hardware testing has been claimed in this PR. diff --git a/docs/product_spec.md b/docs/product_spec.md new file mode 100644 index 0000000..4be5313 --- /dev/null +++ b/docs/product_spec.md @@ -0,0 +1,48 @@ +# Portable AVR Control Studio Product Spec + +## Product goal + +Portable AVR Control Studio is a Windows-centered control and configuration studio for Arduino Uno / ATmega328P AVR installations. It combines: + +- EEPROM-backed AVR firmware. +- A Tkinter desktop GUI suitable for portable Windows packaging. +- A documented serial protocol. +- Hardware profiles that describe assumptions without pretending to auto-detect unknown hardware. Arduino Nano may be documented only as a compatible secondary option. + +## Customer-facing runtime settings + +These settings are editable from the GUI and persisted by firmware after `SAVE_CONFIG`: + +| Setting | Purpose | +| --- | --- | +| `DEVICE_NAME` | Human-readable board label, 1-16 printable characters, no commas. | +| `SENSOR_VREF_MV` | ADC reference in millivolts. | +| `THRESHOLD_LOW` | Lower sensor threshold in millivolts. | +| `THRESHOLD_HIGH` | Upper sensor threshold in millivolts. | +| `RELAY_MODE` | `MANUAL` for direct relay commands or `AUTO` for threshold control. | +| `BUZZER_ENABLED` | `ON` enables buzzer commands; `OFF` forces buzzer output off. | +| `ECO_MODE` | `ON` reduces telemetry cadence by enforcing at least 5000 ms. | +| `TELEMETRY_MS` | Periodic status interval, 250-60000 ms. | +| `UI_LANGUAGE` | Placeholder; currently only `EN` is supported. | + +## Hardware/profile settings + +Hardware settings remain editable for controlled handoff scenarios but are separated from customer runtime settings in the GUI: + +- `SENSOR_PIN` +- `RELAY_PIN` +- `BUZZER_PIN` +- `RELAY_ACTIVE_HIGH` +- `BUZZER_ACTIVE_HIGH` + +Changing hardware settings may require matching firmware, wiring, driver polarity, and profile documentation. + +## Relay AUTO behavior + +When `RELAY_MODE=AUTO`, firmware samples the configured analog sensor, converts raw ADC readings to millivolts using `SENSOR_VREF_MV`, and applies simple hysteresis: + +- Relay turns `ON` at or below `THRESHOLD_LOW`. +- Relay turns `OFF` at or above `THRESHOLD_HIGH`. +- Relay keeps its previous state between the thresholds. + +Manual `RELAY,ON|OFF|TOGGLE` commands are rejected while `RELAY_MODE=AUTO` so the GUI cannot fight the threshold controller. diff --git a/docs/profiles/arduino_uno_avr.json b/docs/profiles/arduino_uno_avr.json new file mode 100644 index 0000000..350d4f9 --- /dev/null +++ b/docs/profiles/arduino_uno_avr.json @@ -0,0 +1,32 @@ +{ + "name": "Arduino Uno AVR", + "target": "Arduino Uno / ATmega328P AVR (primary supported profile)", + "serial": { + "baud": 115200, + "notes": "D0/D1 are reserved for USB serial and are not accepted for relay/buzzer outputs." + }, + "runtime_settings": { + "DEVICE_NAME": "Uno AVR Studio", + "SENSOR_VREF_MV": 5000, + "THRESHOLD_LOW": 1200, + "THRESHOLD_HIGH": 2800, + "RELAY_MODE": "MANUAL", + "BUZZER_ENABLED": "ON", + "ECO_MODE": "OFF", + "TELEMETRY_MS": 1000, + "UI_LANGUAGE": "EN" + }, + "hardware_settings": { + "SENSOR_PIN": "A0 / 14", + "RELAY_PIN": 8, + "BUZZER_PIN": 9, + "RELAY_ACTIVE_HIGH": 1, + "BUZZER_ACTIVE_HIGH": 1 + }, + "limitations": [ + "This Arduino Uno profile documents expected wiring; it is not automatic hardware detection.", + "Driver boards with inverted polarity must use matching settings and may require firmware review.", + "AUTO relay mode uses firmware threshold hysteresis and must be validated with the actual sensor circuit.", + "Physical hardware validation has not been claimed by the repository checks." + ] +} diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..af60087 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,46 @@ +# Testing + +## Automated checks in this repository + +GitHub Actions runs `.github/workflows/checks.yml` with: + +```bash +python -m py_compile gui/portable_avr_control_studio.py +python - <<'PY' +from gui.portable_avr_control_studio import parse_serial_line +assert parse_serial_line('OK,PING\n').kind == 'OK' +assert parse_serial_line('ERR,BAD,message\n').kind == 'ERR' +assert parse_serial_line('CONFIG,DEVICE_NAME=Unit,SENSOR_VREF_MV=5000\n').fields['SENSOR_VREF_MV'] == '5000' +assert parse_serial_line('STATUS,SENSOR_RAW=512,SENSOR_MV=2502\n').fields['SENSOR_MV'] == '2502' +assert parse_serial_line('DATA,INFO,protocol=2\n').fields['PROTOCOL'] == '2' +assert parse_serial_line('garbage\n').malformed +PY +``` + +The workflow also attempts an Arduino CLI compile for the Uno target: + +```bash +arduino-cli core update-index +arduino-cli core install arduino:avr +arduino-cli compile --fqbn arduino:avr:uno firmware/PortableAVRControlStudio +``` + +If Arduino CLI or network setup is unavailable in an execution environment, run the same commands locally before removing draft status. + +## Local checks + +```bash +python -m py_compile gui/portable_avr_control_studio.py +python - <<'PY' +from gui.portable_avr_control_studio import parse_serial_line +assert parse_serial_line('OK,PING\n').kind == 'OK' +assert parse_serial_line('CONFIG,RELAY_MODE=AUTO,SENSOR_VREF_MV=5000\n').fields['RELAY_MODE'] == 'AUTO' +assert parse_serial_line('STATUS,SENSOR_RAW=123,SENSOR_MV=601\n').fields['SENSOR_RAW'] == '123' +assert parse_serial_line('garbage\n').malformed +PY +arduino-cli compile --fqbn arduino:avr:uno firmware/PortableAVRControlStudio +``` + +## Physical hardware testing + +No physical hardware test is claimed by this repository. Physical validation must be performed against the final board, wiring, relay/buzzer drivers, power supply, enclosure, and selected hardware profile before customer deployment. diff --git a/firmware/PortableAVRControlStudio/PortableAVRControlStudio.ino b/firmware/PortableAVRControlStudio/PortableAVRControlStudio.ino new file mode 100644 index 0000000..a805c52 --- /dev/null +++ b/firmware/PortableAVRControlStudio/PortableAVRControlStudio.ino @@ -0,0 +1,596 @@ +#include +#include +#include +#include + +// Portable AVR Control Studio firmware +// Primary target: Arduino Uno / ATmega328P AVR. + +static const uint32_t CONFIG_MAGIC = 0x50414353UL; // "PACS" +static const uint16_t CONFIG_VERSION = 2; +static const uint8_t CONFIG_EEPROM_ADDRESS = 0; +static const size_t COMMAND_BUFFER_SIZE = 112; +static const unsigned long SERIAL_BAUD = 115200UL; + +enum RelayMode : uint8_t { + RELAY_MODE_MANUAL = 0, + RELAY_MODE_AUTO = 1 +}; + +struct Config { + uint32_t magic; + uint16_t version; + + // Customer-facing runtime settings. + char deviceName[17]; + uint16_t sensorVrefMv; + uint16_t thresholdLow; + uint16_t thresholdHigh; + uint8_t relayMode; + uint8_t buzzerEnabled; + uint8_t ecoMode; + uint16_t telemetryMs; + char uiLanguage[3]; + + // Hardware/profile settings. These document the bundled profile and should be + // changed only when the firmware and wiring profile match. + uint8_t sensorPin; + uint8_t relayPin; + uint8_t buzzerPin; + uint8_t relayActiveHigh; + uint8_t buzzerActiveHigh; +}; + +Config config; +bool relayOn = false; +bool buzzerOn = false; +char commandBuffer[COMMAND_BUFFER_SIZE]; +size_t commandLength = 0; +unsigned long lastTelemetryMs = 0; + + +static char asciiUpper(char value); +static bool equalsIgnoreCase(const char *left, const char *right); +static bool isAllowedIoPin(uint8_t pin); +static bool isAllowedAnalogPin(uint8_t pin); +static void setFactoryDefaults(Config &target); +static bool validateConfig(const Config &candidate); +static void writeOutput(uint8_t pin, uint8_t activeHigh, bool on); +static void applyHardwareConfig(); +static void saveConfigToEeprom(); +static bool loadConfigFromEeprom(); +static void printOk(const char *command); +static void printErr(const char *code, const char *message); +static const __FlashStringHelper *relayModeName(); +static void printInfo(); +static void printConfig(); +static uint16_t readSensorRaw(); +static uint16_t rawToMillivolts(uint16_t raw); +static void applyAutoRelay(uint16_t sensorMv); +static void printStatus(); +static char *trimInPlace(char *value); +static bool parseUnsignedLong(const char *text, unsigned long &out); +static bool parseBooleanValue(const char *text, uint8_t &out); +static bool parseAnalogPin(const char *text, uint8_t &out); +static bool applySetting(const char *key, const char *value); +static void handleBinaryAction(const char *device, const char *action); +static void processCommand(char *line); +static void readSerialCommands(); + + +static char asciiUpper(char value) { + if (value >= 'a' && value <= 'z') { + return (char)(value - ('a' - 'A')); + } + return value; +} + +static bool equalsIgnoreCase(const char *left, const char *right) { + if (left == NULL || right == NULL) { + return false; + } + while (*left != '\0' && *right != '\0') { + if (asciiUpper(*left) != asciiUpper(*right)) { + return false; + } + left++; + right++; + } + return *left == '\0' && *right == '\0'; +} + +static bool isAllowedIoPin(uint8_t pin) { + // Keep D0/D1 free for serial and avoid unknown board-specific mappings. + return pin >= 2 && pin <= 13; +} + +static bool isAllowedAnalogPin(uint8_t pin) { + // A0-A5 map to 14-19 on Arduino Uno ATmega328P AVR cores. + return pin >= A0 && pin <= A5; +} + +static void setFactoryDefaults(Config &target) { + memset(&target, 0, sizeof(target)); + target.magic = CONFIG_MAGIC; + target.version = CONFIG_VERSION; + strncpy(target.deviceName, "Uno AVR Studio", sizeof(target.deviceName) - 1); + target.sensorVrefMv = 5000; + target.thresholdLow = 1200; + target.thresholdHigh = 2800; + target.relayMode = RELAY_MODE_MANUAL; + target.buzzerEnabled = 1; + target.ecoMode = 0; + target.telemetryMs = 1000; + strncpy(target.uiLanguage, "EN", sizeof(target.uiLanguage) - 1); + target.sensorPin = A0; + target.relayPin = 8; + target.buzzerPin = 9; + target.relayActiveHigh = 1; + target.buzzerActiveHigh = 1; +} + +static bool validateConfig(const Config &candidate) { + if (candidate.magic != CONFIG_MAGIC || candidate.version != CONFIG_VERSION) { + return false; + } + if (candidate.deviceName[sizeof(candidate.deviceName) - 1] != '\0') { + return false; + } + if (strcmp(candidate.uiLanguage, "EN") != 0) { + return false; + } + if (candidate.sensorVrefMv < 1000 || candidate.sensorVrefMv > 5500) { + return false; + } + if (candidate.thresholdLow >= candidate.thresholdHigh || candidate.thresholdHigh > candidate.sensorVrefMv) { + return false; + } + if (candidate.relayMode > RELAY_MODE_AUTO || candidate.buzzerEnabled > 1 || candidate.ecoMode > 1) { + return false; + } + if (candidate.telemetryMs < 250 || candidate.telemetryMs > 60000) { + return false; + } + if (!isAllowedAnalogPin(candidate.sensorPin)) { + return false; + } + if (!isAllowedIoPin(candidate.relayPin) || !isAllowedIoPin(candidate.buzzerPin)) { + return false; + } + if (candidate.relayPin == candidate.buzzerPin) { + return false; + } + if (candidate.relayActiveHigh > 1 || candidate.buzzerActiveHigh > 1) { + return false; + } + return true; +} + +static void writeOutput(uint8_t pin, uint8_t activeHigh, bool on) { + const uint8_t activeLevel = activeHigh ? HIGH : LOW; + const uint8_t inactiveLevel = activeHigh ? LOW : HIGH; + digitalWrite(pin, on ? activeLevel : inactiveLevel); +} + +static void applyHardwareConfig() { + pinMode(config.relayPin, OUTPUT); + pinMode(config.buzzerPin, OUTPUT); + writeOutput(config.relayPin, config.relayActiveHigh, relayOn); + writeOutput(config.buzzerPin, config.buzzerActiveHigh, buzzerOn && config.buzzerEnabled); +} + +static void saveConfigToEeprom() { + EEPROM.put(CONFIG_EEPROM_ADDRESS, config); +} + +static bool loadConfigFromEeprom() { + Config stored; + EEPROM.get(CONFIG_EEPROM_ADDRESS, stored); + if (!validateConfig(stored)) { + return false; + } + config = stored; + return true; +} + +static void printOk(const char *command) { + Serial.print(F("OK,")); + Serial.println(command); +} + +static void printErr(const char *code, const char *message) { + Serial.print(F("ERR,")); + Serial.print(code); + Serial.print(F(",")); + Serial.println(message); +} + +static const __FlashStringHelper *relayModeName() { + return config.relayMode == RELAY_MODE_AUTO ? F("AUTO") : F("MANUAL"); +} + +static void printInfo() { + // DATA,INFO is the documented metadata response. Command acknowledgements use + // OK,; informational payloads use DATA,,key=value pairs. + Serial.print(F("DATA,INFO,app=Portable AVR Control Studio,fw=1.1.0,board=uno-nano-avr,protocol=2,baud=")); + Serial.println(SERIAL_BAUD); +} + +static void printConfig() { + Serial.print(F("CONFIG,DEVICE_NAME=")); + Serial.print(config.deviceName); + Serial.print(F(",SENSOR_VREF_MV=")); + Serial.print(config.sensorVrefMv); + Serial.print(F(",THRESHOLD_LOW=")); + Serial.print(config.thresholdLow); + Serial.print(F(",THRESHOLD_HIGH=")); + Serial.print(config.thresholdHigh); + Serial.print(F(",RELAY_MODE=")); + Serial.print(relayModeName()); + Serial.print(F(",BUZZER_ENABLED=")); + Serial.print(config.buzzerEnabled ? F("ON") : F("OFF")); + Serial.print(F(",ECO_MODE=")); + Serial.print(config.ecoMode ? F("ON") : F("OFF")); + Serial.print(F(",TELEMETRY_MS=")); + Serial.print(config.telemetryMs); + Serial.print(F(",UI_LANGUAGE=")); + Serial.print(config.uiLanguage); + Serial.print(F(",SENSOR_PIN=")); + Serial.print(config.sensorPin); + Serial.print(F(",RELAY_PIN=")); + Serial.print(config.relayPin); + Serial.print(F(",BUZZER_PIN=")); + Serial.print(config.buzzerPin); + Serial.print(F(",RELAY_ACTIVE_HIGH=")); + Serial.print(config.relayActiveHigh); + Serial.print(F(",BUZZER_ACTIVE_HIGH=")); + Serial.println(config.buzzerActiveHigh); +} + +static uint16_t readSensorRaw() { + return (uint16_t)analogRead(config.sensorPin); +} + +static uint16_t rawToMillivolts(uint16_t raw) { + return (uint16_t)(((uint32_t)raw * config.sensorVrefMv) / 1023UL); +} + +static void applyAutoRelay(uint16_t sensorMv) { + if (config.relayMode != RELAY_MODE_AUTO) { + return; + } + if (sensorMv <= config.thresholdLow) { + relayOn = true; + } else if (sensorMv >= config.thresholdHigh) { + relayOn = false; + } + writeOutput(config.relayPin, config.relayActiveHigh, relayOn); +} + +static void printStatus() { + const uint16_t sensorRaw = readSensorRaw(); + const uint16_t sensorMv = rawToMillivolts(sensorRaw); + applyAutoRelay(sensorMv); + + Serial.print(F("STATUS,RELAY=")); + Serial.print(relayOn ? F("ON") : F("OFF")); + Serial.print(F(",BUZZER=")); + Serial.print((buzzerOn && config.buzzerEnabled) ? F("ON") : F("OFF")); + Serial.print(F(",RELAY_MODE=")); + Serial.print(relayModeName()); + Serial.print(F(",SENSOR_RAW=")); + Serial.print(sensorRaw); + Serial.print(F(",SENSOR_MV=")); + Serial.print(sensorMv); + Serial.print(F(",THRESHOLD_LOW=")); + Serial.print(config.thresholdLow); + Serial.print(F(",THRESHOLD_HIGH=")); + Serial.print(config.thresholdHigh); + Serial.print(F(",UPTIME_MS=")); + Serial.print(millis()); + Serial.print(F(",RELAY_PIN=")); + Serial.print(config.relayPin); + Serial.print(F(",BUZZER_PIN=")); + Serial.println(config.buzzerPin); +} + +static char *trimInPlace(char *value) { + while (*value == ' ' || *value == '\t') { + value++; + } + char *end = value + strlen(value); + while (end > value && (end[-1] == ' ' || end[-1] == '\t' || end[-1] == '\r' || end[-1] == '\n')) { + *--end = '\0'; + } + return value; +} + +static bool parseUnsignedLong(const char *text, unsigned long &out) { + if (text == NULL || *text == '\0') { + return false; + } + char *end = NULL; + unsigned long value = strtoul(text, &end, 10); + if (end == text || *end != '\0') { + return false; + } + out = value; + return true; +} + +static bool parseBooleanValue(const char *text, uint8_t &out) { + if (strcmp(text, "1") == 0 || equalsIgnoreCase(text, "ON") || equalsIgnoreCase(text, "TRUE") || equalsIgnoreCase(text, "HIGH")) { + out = 1; + return true; + } + if (strcmp(text, "0") == 0 || equalsIgnoreCase(text, "OFF") || equalsIgnoreCase(text, "FALSE") || equalsIgnoreCase(text, "LOW")) { + out = 0; + return true; + } + return false; +} + +static bool parseAnalogPin(const char *text, uint8_t &out) { + if (equalsIgnoreCase(text, "A0")) { out = A0; return true; } + if (equalsIgnoreCase(text, "A1")) { out = A1; return true; } + if (equalsIgnoreCase(text, "A2")) { out = A2; return true; } + if (equalsIgnoreCase(text, "A3")) { out = A3; return true; } + if (equalsIgnoreCase(text, "A4")) { out = A4; return true; } + if (equalsIgnoreCase(text, "A5")) { out = A5; return true; } + unsigned long parsed = 0; + if (!parseUnsignedLong(text, parsed) || parsed > 255) { + return false; + } + out = (uint8_t)parsed; + return true; +} + +static bool applySetting(const char *key, const char *value) { + Config candidate = config; + + if (equalsIgnoreCase(key, "DEVICE_NAME")) { + const size_t length = strlen(value); + if (length == 0 || length >= sizeof(candidate.deviceName)) { + printErr("BAD_VALUE", "DEVICE_NAME must be 1-16 characters"); + return false; + } + for (size_t i = 0; i < length; i++) { + const char c = value[i]; + if (c == ',' || c < 32 || c > 126) { + printErr("BAD_VALUE", "DEVICE_NAME contains unsupported characters"); + return false; + } + } + memset(candidate.deviceName, 0, sizeof(candidate.deviceName)); + strncpy(candidate.deviceName, value, sizeof(candidate.deviceName) - 1); + } else if (equalsIgnoreCase(key, "SENSOR_VREF_MV") || equalsIgnoreCase(key, "THRESHOLD_LOW") || equalsIgnoreCase(key, "THRESHOLD_HIGH") || equalsIgnoreCase(key, "TELEMETRY_MS")) { + unsigned long parsed = 0; + if (!parseUnsignedLong(value, parsed) || parsed > 65535UL) { + printErr("BAD_VALUE", "numeric setting must be 0-65535"); + return false; + } + if (equalsIgnoreCase(key, "SENSOR_VREF_MV")) { + candidate.sensorVrefMv = (uint16_t)parsed; + } else if (equalsIgnoreCase(key, "THRESHOLD_LOW")) { + candidate.thresholdLow = (uint16_t)parsed; + } else if (equalsIgnoreCase(key, "THRESHOLD_HIGH")) { + candidate.thresholdHigh = (uint16_t)parsed; + } else { + candidate.telemetryMs = (uint16_t)parsed; + } + } else if (equalsIgnoreCase(key, "RELAY_MODE")) { + if (equalsIgnoreCase(value, "MANUAL")) { + candidate.relayMode = RELAY_MODE_MANUAL; + } else if (equalsIgnoreCase(value, "AUTO")) { + candidate.relayMode = RELAY_MODE_AUTO; + } else { + printErr("BAD_VALUE", "RELAY_MODE must be MANUAL or AUTO"); + return false; + } + } else if (equalsIgnoreCase(key, "BUZZER_ENABLED") || equalsIgnoreCase(key, "ECO_MODE") || equalsIgnoreCase(key, "RELAY_ACTIVE_HIGH") || equalsIgnoreCase(key, "BUZZER_ACTIVE_HIGH")) { + uint8_t parsed = 0; + if (!parseBooleanValue(value, parsed)) { + printErr("BAD_VALUE", "boolean value must be ON or OFF"); + return false; + } + if (equalsIgnoreCase(key, "BUZZER_ENABLED")) { + candidate.buzzerEnabled = parsed; + } else if (equalsIgnoreCase(key, "ECO_MODE")) { + candidate.ecoMode = parsed; + } else if (equalsIgnoreCase(key, "RELAY_ACTIVE_HIGH")) { + candidate.relayActiveHigh = parsed; + } else { + candidate.buzzerActiveHigh = parsed; + } + } else if (equalsIgnoreCase(key, "UI_LANGUAGE")) { + if (!equalsIgnoreCase(value, "EN")) { + printErr("BAD_VALUE", "UI_LANGUAGE currently supports EN only"); + return false; + } + memset(candidate.uiLanguage, 0, sizeof(candidate.uiLanguage)); + strncpy(candidate.uiLanguage, "EN", sizeof(candidate.uiLanguage) - 1); + } else if (equalsIgnoreCase(key, "SENSOR_PIN")) { + uint8_t parsed = 0; + if (!parseAnalogPin(value, parsed)) { + printErr("BAD_VALUE", "SENSOR_PIN must be A0-A5 or 14-19"); + return false; + } + candidate.sensorPin = parsed; + } else if (equalsIgnoreCase(key, "RELAY_PIN") || equalsIgnoreCase(key, "BUZZER_PIN")) { + unsigned long parsed = 0; + if (!parseUnsignedLong(value, parsed) || parsed > 255) { + printErr("BAD_VALUE", "pin must be a number"); + return false; + } + if (equalsIgnoreCase(key, "RELAY_PIN")) { + candidate.relayPin = (uint8_t)parsed; + } else { + candidate.buzzerPin = (uint8_t)parsed; + } + } else { + printErr("BAD_KEY", "unknown setting key"); + return false; + } + + if (!validateConfig(candidate)) { + printErr("BAD_CONFIG", "setting rejected by validation"); + return false; + } + + config = candidate; + if (!config.buzzerEnabled) { + buzzerOn = false; + } + applyHardwareConfig(); + return true; +} + +static void handleBinaryAction(const char *device, const char *action) { + bool *state = NULL; + if (equalsIgnoreCase(device, "RELAY")) { + if (config.relayMode == RELAY_MODE_AUTO) { + printErr("RELAY_AUTO", "relay is controlled by thresholds while RELAY_MODE=AUTO"); + printStatus(); + return; + } + state = &relayOn; + } else if (equalsIgnoreCase(device, "BUZZER")) { + if (!config.buzzerEnabled) { + printErr("BUZZER_DISABLED", "set BUZZER_ENABLED=ON before buzzer control"); + return; + } + state = &buzzerOn; + } else { + printErr("BAD_COMMAND", "unknown output device"); + return; + } + + if (equalsIgnoreCase(action, "ON")) { + *state = true; + } else if (equalsIgnoreCase(action, "OFF")) { + *state = false; + } else if (equalsIgnoreCase(action, "TOGGLE")) { + *state = !*state; + } else { + printErr("BAD_ACTION", "expected ON, OFF, or TOGGLE"); + return; + } + + writeOutput(config.relayPin, config.relayActiveHigh, relayOn); + writeOutput(config.buzzerPin, config.buzzerActiveHigh, buzzerOn && config.buzzerEnabled); + printOk(device); + printStatus(); +} + +static void processCommand(char *line) { + char *commandToken = strtok(line, ","); + if (commandToken == NULL) { + return; + } + char *command = trimInPlace(commandToken); + char *arg1 = strtok(NULL, ","); + char *arg2 = strtok(NULL, ","); + char *extra = strtok(NULL, ","); + if (arg1 != NULL) { + arg1 = trimInPlace(arg1); + } + if (arg2 != NULL) { + arg2 = trimInPlace(arg2); + } + + if (*command == '\0') { + return; + } + if (extra != NULL) { + printErr("BAD_ARGS", "too many comma-separated fields"); + return; + } + + if (equalsIgnoreCase(command, "PING")) { + printOk("PING"); + } else if (equalsIgnoreCase(command, "INFO")) { + printInfo(); + } else if (equalsIgnoreCase(command, "GET_CONFIG")) { + printConfig(); + } else if (equalsIgnoreCase(command, "GET_STATUS")) { + printStatus(); + } else if (equalsIgnoreCase(command, "SET")) { + if (arg1 == NULL || arg2 == NULL || *arg1 == '\0' || *arg2 == '\0') { + printErr("BAD_ARGS", "SET requires KEY and VALUE"); + return; + } + if (applySetting(arg1, arg2)) { + printOk("SET"); + printConfig(); + } + } else if (equalsIgnoreCase(command, "SAVE_CONFIG")) { + if (!validateConfig(config)) { + printErr("BAD_CONFIG", "current config is invalid"); + return; + } + saveConfigToEeprom(); + printOk("SAVE_CONFIG"); + } else if (equalsIgnoreCase(command, "LOAD_CONFIG")) { + if (loadConfigFromEeprom()) { + applyHardwareConfig(); + printOk("LOAD_CONFIG"); + printConfig(); + } else { + printErr("EEPROM_INVALID", "stored config failed validation"); + } + } else if (equalsIgnoreCase(command, "FACTORY_RESET")) { + setFactoryDefaults(config); + relayOn = false; + buzzerOn = false; + applyHardwareConfig(); + saveConfigToEeprom(); + printOk("FACTORY_RESET"); + printConfig(); + } else if (equalsIgnoreCase(command, "RELAY") || equalsIgnoreCase(command, "BUZZER")) { + if (arg1 == NULL || *arg1 == '\0') { + printErr("BAD_ARGS", "output command requires action"); + return; + } + handleBinaryAction(command, arg1); + } else { + printErr("UNKNOWN_COMMAND", "command not recognized"); + } +} + +static void readSerialCommands() { + while (Serial.available() > 0) { + char c = (char)Serial.read(); + if (c == '\n' || c == '\r') { + if (commandLength > 0) { + commandBuffer[commandLength] = '\0'; + processCommand(commandBuffer); + commandLength = 0; + } + } else if (commandLength < COMMAND_BUFFER_SIZE - 1) { + commandBuffer[commandLength++] = c; + } else { + commandLength = 0; + printErr("LINE_TOO_LONG", "command buffer overflow avoided"); + } + } +} + +void setup() { + Serial.begin(SERIAL_BAUD); + if (!loadConfigFromEeprom()) { + setFactoryDefaults(config); + saveConfigToEeprom(); + } + applyHardwareConfig(); + printInfo(); + printConfig(); +} + +void loop() { + readSerialCommands(); + const uint16_t effectiveTelemetryMs = config.ecoMode && config.telemetryMs < 5000 ? 5000 : config.telemetryMs; + if (millis() - lastTelemetryMs >= effectiveTelemetryMs) { + lastTelemetryMs = millis(); + printStatus(); + } +} diff --git a/gui/portable_avr_control_studio.py b/gui/portable_avr_control_studio.py new file mode 100644 index 0000000..ce670a7 --- /dev/null +++ b/gui/portable_avr_control_studio.py @@ -0,0 +1,740 @@ +"""Portable AVR Control Studio. + +A Windows-centered Tkinter control/configuration studio for conservative +Arduino Uno / ATmega328P AVR firmware. The application can run with a real +serial port through pyserial or in a clearly labelled simulation-only demo mode. +""" +from __future__ import annotations + +import datetime as _dt +import json +import queue +import subprocess +import sys +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Dict, Iterable, List, Optional, Tuple +import tkinter as tk +from tkinter import filedialog, messagebox, ttk + +try: + import serial # type: ignore + from serial.tools import list_ports # type: ignore +except ImportError: # pragma: no cover - exercised by smoke checks without pyserial + serial = None + list_ports = None + +BAUD_RATE = 115200 +RUNTIME_SETTINGS_KEYS = ( + "DEVICE_NAME", + "SENSOR_VREF_MV", + "THRESHOLD_LOW", + "THRESHOLD_HIGH", + "RELAY_MODE", + "BUZZER_ENABLED", + "ECO_MODE", + "TELEMETRY_MS", + "UI_LANGUAGE", +) +HARDWARE_SETTINGS_KEYS = ( + "SENSOR_PIN", + "RELAY_PIN", + "BUZZER_PIN", + "RELAY_ACTIVE_HIGH", + "BUZZER_ACTIVE_HIGH", +) +SETTINGS_KEYS = RUNTIME_SETTINGS_KEYS + HARDWARE_SETTINGS_KEYS +DEFAULT_SETTINGS = { + "DEVICE_NAME": "Uno AVR Studio", + "SENSOR_VREF_MV": "5000", + "THRESHOLD_LOW": "1200", + "THRESHOLD_HIGH": "2800", + "RELAY_MODE": "MANUAL", + "BUZZER_ENABLED": "ON", + "ECO_MODE": "OFF", + "TELEMETRY_MS": "1000", + "UI_LANGUAGE": "EN", + "SENSOR_PIN": "14", + "RELAY_PIN": "8", + "BUZZER_PIN": "9", + "RELAY_ACTIVE_HIGH": "1", + "BUZZER_ACTIVE_HIGH": "1", +} +ENUM_VALUES = { + "RELAY_MODE": ("MANUAL", "AUTO"), + "BUZZER_ENABLED": ("ON", "OFF"), + "ECO_MODE": ("OFF", "ON"), + "UI_LANGUAGE": ("EN",), + "RELAY_ACTIVE_HIGH": ("1", "0"), + "BUZZER_ACTIVE_HIGH": ("1", "0"), +} +SETTING_HELP = { + "SENSOR_VREF_MV": "ADC reference in millivolts, typically 5000 for USB-powered Arduino Uno boards.", + "THRESHOLD_LOW": "AUTO relay turns ON at or below this sensor millivolt value.", + "THRESHOLD_HIGH": "AUTO relay turns OFF at or above this sensor millivolt value.", + "RELAY_MODE": "MANUAL allows relay test buttons; AUTO uses threshold hysteresis.", + "TELEMETRY_MS": "Periodic status interval. ECO_MODE enforces at least 5000 ms.", + "SENSOR_PIN": "Hardware/profile setting: A0-A5 may be entered as A0 or 14-19.", + "RELAY_PIN": "Hardware/profile setting: D2-D13, matching firmware and wiring.", + "BUZZER_PIN": "Hardware/profile setting: D2-D13, matching firmware and wiring.", +} +def application_root() -> Path: + if getattr(sys, "frozen", False): + return Path(sys.executable).resolve().parent + return Path(__file__).resolve().parent.parent + + +PROFILE_DIR = application_root() / "docs" / "profiles" + + +@dataclass +class ParsedLine: + kind: str + raw: str + fields: Dict[str, str] = field(default_factory=dict) + values: List[str] = field(default_factory=list) + malformed: bool = False + + +def parse_key_values(parts: Iterable[str]) -> Dict[str, str]: + fields: Dict[str, str] = {} + for part in parts: + if "=" not in part: + continue + key, value = part.split("=", 1) + key = key.strip().upper() + if key: + fields[key] = value.strip() + return fields + + +def parse_serial_line(line: str) -> ParsedLine: + raw = line.rstrip("\r\n") + if not raw: + return ParsedLine("EMPTY", raw, malformed=True) + parts = [part.strip() for part in raw.split(",")] + kind = parts[0].upper() if parts else "MALFORMED" + try: + if kind in {"CONFIG", "STATUS"}: + fields = parse_key_values(parts[1:]) + return ParsedLine(kind, raw, fields=fields, malformed=not fields) + if kind == "DATA": + fields = parse_key_values(parts[2:]) if len(parts) > 2 else {} + values = parts[1:] + return ParsedLine(kind, raw, fields=fields, values=values, malformed=len(parts) < 2) + if kind in {"OK", "ERR"}: + return ParsedLine(kind, raw, values=parts[1:], malformed=(kind == "ERR" and len(parts) < 2)) + return ParsedLine("UNKNOWN", raw, values=parts[1:], malformed=True) + except Exception: + return ParsedLine("MALFORMED", raw, malformed=True) + + +class SerialTransport: + def __init__(self, on_line: Callable[[str], None], on_log: Callable[[str], None]) -> None: + self.on_line = on_line + self.on_log = on_log + self._serial = None + self._thread: Optional[threading.Thread] = None + self._stop = threading.Event() + + @property + def is_connected(self) -> bool: + return self._serial is not None and bool(getattr(self._serial, "is_open", False)) + + def connect(self, port: str, baud: int = BAUD_RATE) -> None: + if serial is None: + raise RuntimeError("pyserial is not installed; use demo mode or install pyserial") + self.disconnect() + self._serial = serial.Serial(port=port, baudrate=baud, timeout=0.2) + self._stop.clear() + self._thread = threading.Thread(target=self._reader, name="serial-reader", daemon=True) + self._thread.start() + self.on_log(f"Connected to {port} at {baud} baud") + + def disconnect(self) -> None: + self._stop.set() + if self._serial is not None: + try: + self._serial.close() + except Exception as exc: + self.on_log(f"Serial close warning: {exc}") + self._serial = None + + def write_command(self, command: str) -> None: + if not self.is_connected: + raise RuntimeError("not connected") + payload = (command.strip() + "\n").encode("ascii", errors="replace") + self._serial.write(payload) + self.on_log(f"> {command.strip()}") + + def _reader(self) -> None: + while not self._stop.is_set() and self._serial is not None: + try: + payload = self._serial.readline() + if payload: + self.on_line(payload.decode("utf-8", errors="replace")) + except Exception as exc: + self.on_log(f"Serial read stopped: {exc}") + break + + +class DemoTransport: + """Simulation-only protocol responder used for customer demos without hardware.""" + + def __init__(self, on_line: Callable[[str], None], on_log: Callable[[str], None]) -> None: + self.on_line = on_line + self.on_log = on_log + self.connected = False + self.settings = dict(DEFAULT_SETTINGS) + self.relay = "OFF" + self.buzzer = "OFF" + self.sensor_raw = 256 + self.started = time.monotonic() + + @property + def is_connected(self) -> bool: + return self.connected + + def connect(self) -> None: + self.connected = True + self.on_log("Demo mode connected (simulation only; no hardware I/O)") + self._emit("DATA,INFO,app=Portable AVR Control Studio,fw=demo,board=simulation,protocol=2") + self._emit_config() + + def disconnect(self) -> None: + self.connected = False + self.on_log("Demo mode disconnected") + + def write_command(self, command: str) -> None: + self.on_log(f"> {command.strip()} [demo]") + if not self.connected: + raise RuntimeError("demo mode is not connected") + parts = [part.strip() for part in command.split(",")] + verb = parts[0].upper() if parts else "" + if verb == "PING": + self._emit("OK,PING") + elif verb == "INFO": + self._emit("DATA,INFO,app=Portable AVR Control Studio,fw=demo,board=simulation,protocol=2") + elif verb == "GET_CONFIG": + self._emit_config() + elif verb == "GET_STATUS": + self._emit_status() + elif verb == "SET" and len(parts) >= 3: + key, value = parts[1].upper(), parts[2] + if key in SETTINGS_KEYS: + self.settings[key] = value + self._emit("OK,SET") + self._emit_config() + else: + self._emit("ERR,BAD_KEY,unknown setting key") + elif verb in {"SAVE_CONFIG", "LOAD_CONFIG"}: + self._emit(f"OK,{verb}") + if verb == "LOAD_CONFIG": + self._emit_config() + elif verb == "FACTORY_RESET": + self.settings = dict(DEFAULT_SETTINGS) + self.relay = "OFF" + self.buzzer = "OFF" + self._emit("OK,FACTORY_RESET") + self._emit_config() + elif verb in {"RELAY", "BUZZER"} and len(parts) >= 2: + self._apply_output(verb, parts[1].upper()) + else: + self._emit("ERR,UNKNOWN_COMMAND,command not recognized") + + def _apply_output(self, device: str, action: str) -> None: + if device == "RELAY" and self.settings.get("RELAY_MODE") == "AUTO": + self._emit("ERR,RELAY_AUTO,relay is controlled by thresholds while RELAY_MODE=AUTO") + self._emit_status() + return + if device == "BUZZER" and self.settings.get("BUZZER_ENABLED") == "OFF": + self._emit("ERR,BUZZER_DISABLED,set BUZZER_ENABLED=ON before buzzer control") + return + current = self.relay if device == "RELAY" else self.buzzer + if action == "TOGGLE": + next_value = "OFF" if current == "ON" else "ON" + elif action in {"ON", "OFF"}: + next_value = action + else: + self._emit("ERR,BAD_ACTION,expected ON OFF or TOGGLE") + return + if device == "RELAY": + self.relay = next_value + else: + self.buzzer = next_value + self._emit(f"OK,{device}") + self._emit_status() + + def _emit(self, line: str) -> None: + self.on_line(line + "\n") + + def _emit_config(self) -> None: + payload = ",".join(f"{key}={self.settings[key]}" for key in SETTINGS_KEYS) + self._emit(f"CONFIG,{payload}") + + def _emit_status(self) -> None: + uptime = int((time.monotonic() - self.started) * 1000) + self.sensor_raw = (self.sensor_raw + 37) % 1024 + try: + vref = int(self.settings.get("SENSOR_VREF_MV", "5000")) + low = int(self.settings.get("THRESHOLD_LOW", "1200")) + high = int(self.settings.get("THRESHOLD_HIGH", "2800")) + except ValueError: + self._emit("ERR,BAD_CONFIG,demo settings contain non-numeric telemetry values") + vref, low, high = 5000, 1200, 2800 + sensor_mv = int(self.sensor_raw * vref / 1023) + if self.settings.get("RELAY_MODE") == "AUTO": + if sensor_mv <= low: + self.relay = "ON" + elif sensor_mv >= high: + self.relay = "OFF" + effective_buzzer = self.buzzer if self.settings.get("BUZZER_ENABLED") == "ON" else "OFF" + self._emit( + f"STATUS,RELAY={self.relay},BUZZER={effective_buzzer},RELAY_MODE={self.settings.get('RELAY_MODE', 'MANUAL')}," + f"SENSOR_RAW={self.sensor_raw},SENSOR_MV={sensor_mv}," + f"THRESHOLD_LOW={self.settings['THRESHOLD_LOW']},THRESHOLD_HIGH={self.settings['THRESHOLD_HIGH']}," + f"UPTIME_MS={uptime},RELAY_PIN={self.settings['RELAY_PIN']},BUZZER_PIN={self.settings['BUZZER_PIN']}" + ) + + +class PortableAVRControlStudio(tk.Tk): + def __init__(self) -> None: + super().__init__() + self.title("Portable AVR Control Studio") + self.geometry("1120x760") + self.minsize(980, 640) + self.line_queue: "queue.Queue[str]" = queue.Queue() + self.settings_vars = {key: tk.StringVar(value=DEFAULT_SETTINGS[key]) for key in SETTINGS_KEYS} + self.status_vars = { + "connection": tk.StringVar(value="Disconnected"), + "relay": tk.StringVar(value="Unknown"), + "buzzer": tk.StringVar(value="Unknown"), + "sensor": tk.StringVar(value="Unknown"), + "uptime": tk.StringVar(value="Unknown"), + "profile": tk.StringVar(value="Arduino Uno AVR"), + } + self.demo_mode = tk.BooleanVar(value=True) + self.hex_path = tk.StringVar(value="") + self.port_var = tk.StringVar(value="") + self.command_var = tk.StringVar(value="PING") + self.transport: object = DemoTransport(self._queue_line, self._log) + self._build_ui() + self._refresh_ports() + self.after(100, self._drain_serial_queue) + + def _build_ui(self) -> None: + self.columnconfigure(0, weight=1) + self.rowconfigure(1, weight=1) + title = ttk.Label(self, text="Portable AVR Control Studio", font=("Segoe UI", 18, "bold")) + title.grid(row=0, column=0, sticky="w", padx=14, pady=(10, 2)) + subtitle = ttk.Label( + self, + text="Windows-centered AVR control, runtime configuration, diagnostics, and firmware handoff", + ) + subtitle.grid(row=0, column=0, sticky="e", padx=14, pady=(10, 2)) + self.tabs = ttk.Notebook(self) + self.tabs.grid(row=1, column=0, sticky="nsew", padx=12, pady=8) + for builder in ( + self._tab_connection, + self._tab_firmware, + self._tab_settings, + self._tab_monitor, + self._tab_profiles, + self._tab_diagnostics, + self._tab_logs, + self._tab_about, + ): + builder() + + def _new_tab(self, title: str) -> ttk.Frame: + frame = ttk.Frame(self.tabs, padding=12) + frame.columnconfigure(0, weight=1) + frame.rowconfigure(99, weight=1) + self.tabs.add(frame, text=title) + return frame + + def _tab_connection(self) -> None: + frame = self._new_tab("Connection") + ttk.Checkbutton( + frame, + text="Demo mode (simulation only — no hardware commands are sent)", + variable=self.demo_mode, + command=self._switch_transport, + ).grid(row=0, column=0, sticky="w", pady=4) + row = ttk.Frame(frame) + row.grid(row=1, column=0, sticky="ew", pady=8) + ttk.Label(row, text="Serial port:").pack(side="left") + self.port_combo = ttk.Combobox(row, textvariable=self.port_var, width=28) + self.port_combo.pack(side="left", padx=6) + ttk.Button(row, text="Refresh", command=self._refresh_ports).pack(side="left", padx=4) + ttk.Button(row, text="Connect", command=self._connect).pack(side="left", padx=4) + ttk.Button(row, text="Disconnect", command=self._disconnect).pack(side="left", padx=4) + ttk.Button(row, text="Ping", command=lambda: self._send("PING")).pack(side="left", padx=4) + info = ttk.LabelFrame(frame, text="Connection status", padding=10) + info.grid(row=2, column=0, sticky="ew", pady=8) + ttk.Label(info, textvariable=self.status_vars["connection"], font=("Segoe UI", 11, "bold")).pack(anchor="w") + ttk.Label( + info, + text="Use demo mode for presentations only. Disable demo mode and select a COM port for a physical AVR board.", + wraplength=900, + ).pack(anchor="w", pady=6) + + def _tab_firmware(self) -> None: + frame = self._new_tab("Firmware") + ttk.Label( + frame, + text="Prepared .hex firmware artifacts can be selected for a placeholder handoff workflow only. This is not a validated production uploader unless avrdude, MCU flags, COM-port behavior, and the matching hardware profile have been packaged and tested.", + wraplength=920, + ).grid(row=0, column=0, sticky="w") + chooser = ttk.Frame(frame) + chooser.grid(row=1, column=0, sticky="ew", pady=10) + ttk.Entry(chooser, textvariable=self.hex_path, width=78).pack(side="left", fill="x", expand=True) + ttk.Button(chooser, text="Browse .hex", command=self._browse_hex).pack(side="left", padx=6) + ttk.Button(chooser, text="Placeholder: Upload Prepared HEX", command=self._upload_hex_placeholder).pack(side="left") + ttk.Button(frame, text="Read Board Info", command=lambda: self._send("INFO")).grid(row=2, column=0, sticky="w", pady=4) + + def _tab_settings(self) -> None: + frame = self._new_tab("Settings") + actions = ttk.Frame(frame) + actions.grid(row=0, column=0, sticky="ew", pady=(0, 10)) + ttk.Button(actions, text="Read Settings from Board", command=lambda: self._send("GET_CONFIG")).pack(side="left", padx=4) + ttk.Button(actions, text="Validate + Send to Board", command=self._send_settings).pack(side="left", padx=4) + ttk.Button(actions, text="Save to EEPROM", command=lambda: self._send("SAVE_CONFIG")).pack(side="left", padx=4) + ttk.Button(actions, text="Reload EEPROM", command=lambda: self._send("LOAD_CONFIG")).pack(side="left", padx=4) + ttk.Button(actions, text="Factory Reset", command=self._factory_reset).pack(side="left", padx=4) + + runtime = ttk.LabelFrame(frame, text="Customer-facing runtime settings", padding=10) + runtime.grid(row=1, column=0, sticky="ew", pady=(0, 10)) + for index, key in enumerate(RUNTIME_SETTINGS_KEYS): + self._add_setting_control(runtime, index, key) + + hardware = ttk.LabelFrame(frame, text="Hardware/profile settings", padding=10) + hardware.grid(row=2, column=0, sticky="ew") + ttk.Label( + hardware, + text="Change these only when the wiring, hardware profile, and firmware target are known to match. Profiles document assumptions; they do not auto-detect hardware.", + wraplength=900, + ).grid(row=0, column=0, columnspan=3, sticky="w", pady=(0, 8)) + for index, key in enumerate(HARDWARE_SETTINGS_KEYS, start=1): + self._add_setting_control(hardware, index, key) + + def _add_setting_control(self, parent: ttk.Frame, row: int, key: str) -> None: + ttk.Label(parent, text=key).grid(row=row, column=0, sticky="w", pady=4) + if key in ENUM_VALUES: + widget = ttk.Combobox(parent, textvariable=self.settings_vars[key], values=ENUM_VALUES[key], width=18, state="readonly") + else: + widget = ttk.Entry(parent, textvariable=self.settings_vars[key], width=22) + widget.grid(row=row, column=1, sticky="w", padx=8, pady=4) + ttk.Label(parent, text=SETTING_HELP.get(key, ""), wraplength=560).grid(row=row, column=2, sticky="w", pady=4) + + def _tab_monitor(self) -> None: + frame = self._new_tab("Live Monitor") + cards = ttk.Frame(frame) + cards.grid(row=0, column=0, sticky="ew") + for label, key in (("Relay", "relay"), ("Buzzer", "buzzer"), ("Sensor", "sensor"), ("Uptime", "uptime")): + box = ttk.LabelFrame(cards, text=label, padding=10) + box.pack(side="left", padx=6, pady=4, fill="x", expand=True) + ttk.Label(box, textvariable=self.status_vars[key], font=("Segoe UI", 14, "bold")).pack(anchor="center") + controls = ttk.Frame(frame) + controls.grid(row=1, column=0, sticky="w", pady=10) + ttk.Button(controls, text="Refresh Status", command=lambda: self._send("GET_STATUS")).pack(side="left", padx=4) + ttk.Button(controls, text="Test Relay", command=lambda: self._send("RELAY,TOGGLE")).pack(side="left", padx=4) + ttk.Button(controls, text="Relay ON", command=lambda: self._send("RELAY,ON")).pack(side="left", padx=4) + ttk.Button(controls, text="Relay OFF", command=lambda: self._send("RELAY,OFF")).pack(side="left", padx=4) + ttk.Button(controls, text="Test Buzzer", command=lambda: self._send("BUZZER,TOGGLE")).pack(side="left", padx=4) + ttk.Button(controls, text="Buzzer OFF", command=lambda: self._send("BUZZER,OFF")).pack(side="left", padx=4) + + def _tab_profiles(self) -> None: + frame = self._new_tab("Hardware Profiles") + ttk.Label( + frame, + text="Profiles document expected pins and drivers. Unknown hardware is not auto-detected; select or author a profile and ensure firmware matches it.", + wraplength=920, + ).grid(row=0, column=0, sticky="w") + body = ttk.Frame(frame) + body.grid(row=1, column=0, sticky="nsew", pady=10) + body.columnconfigure(1, weight=1) + self.profile_list = tk.Listbox(body, height=10, exportselection=False) + self.profile_list.grid(row=0, column=0, sticky="ns", padx=(0, 8)) + self.profile_text = tk.Text(body, height=18, wrap="word") + self.profile_text.grid(row=0, column=1, sticky="nsew") + ttk.Button(frame, text="Load Bundled Profiles", command=self._load_profiles).grid(row=2, column=0, sticky="w") + self.profile_list.bind("<>", lambda _event: self._show_selected_profile()) + self._load_profiles() + + def _tab_diagnostics(self) -> None: + frame = self._new_tab("Diagnostics") + ttk.Label(frame, text="Manual command console and parser diagnostics.").grid(row=0, column=0, sticky="w") + row = ttk.Frame(frame) + row.grid(row=1, column=0, sticky="ew", pady=8) + ttk.Entry(row, textvariable=self.command_var, width=60).pack(side="left", fill="x", expand=True) + ttk.Button(row, text="Send Command", command=lambda: self._send(self.command_var.get())).pack(side="left", padx=6) + for command in ("PING", "INFO", "GET_CONFIG", "GET_STATUS"): + ttk.Button(row, text=command, command=lambda c=command: self._send(c)).pack(side="left", padx=2) + self.diagnostic_text = tk.Text(frame, height=22, wrap="word") + self.diagnostic_text.grid(row=2, column=0, sticky="nsew") + + def _tab_logs(self) -> None: + frame = self._new_tab("Logs") + self.log_text = tk.Text(frame, height=28, wrap="word") + self.log_text.grid(row=0, column=0, sticky="nsew") + ttk.Button(frame, text="Save Logs", command=self._save_logs).grid(row=1, column=0, sticky="w", pady=6) + + def _tab_about(self) -> None: + frame = self._new_tab("About / Handoff") + text = ( + "Portable AVR Control Studio packages a conservative AVR firmware protocol, a Windows-friendly Tkinter GUI, " + "hardware profile documentation, and handoff notes for customer delivery.\n\n" + "Handoff checklist:\n" + "• Compile firmware for the Arduino Uno / ATmega328P AVR target.\n" + "• Confirm hardware profile pins and driver polarity.\n" + "• Package the GUI as a portable Windows EXE.\n" + "• Do not claim physical hardware validation until a board has been tested." + ) + ttk.Label(frame, text=text, wraplength=900, justify="left").grid(row=0, column=0, sticky="w") + + def _switch_transport(self) -> None: + self._disconnect() + if self.demo_mode.get(): + self.transport = DemoTransport(self._queue_line, self._log) + self.status_vars["connection"].set("Demo mode ready (simulation only)") + else: + self.transport = SerialTransport(self._queue_line, self._log) + self.status_vars["connection"].set("Serial mode ready") + + def _refresh_ports(self) -> None: + ports = [] + if list_ports is not None: + ports = [port.device for port in list_ports.comports()] + self.port_combo["values"] = ports + if ports and not self.port_var.get(): + self.port_var.set(ports[0]) + if list_ports is None: + self._log("pyserial not installed; COM port discovery unavailable") + + def _connect(self) -> None: + try: + if self.demo_mode.get(): + assert isinstance(self.transport, DemoTransport) + self.transport.connect() + self.status_vars["connection"].set("Connected to simulation-only demo mode") + else: + port = self.port_var.get().strip() + if not port: + messagebox.showwarning("Serial port required", "Select a COM port first.") + return + assert isinstance(self.transport, SerialTransport) + self.transport.connect(port) + self.status_vars["connection"].set(f"Connected to {port}") + except Exception as exc: + self.status_vars["connection"].set("Connection failed") + self._log(f"Connection error: {exc}") + messagebox.showerror("Connection error", str(exc)) + + def _disconnect(self) -> None: + try: + if hasattr(self.transport, "disconnect"): + self.transport.disconnect() + finally: + self.status_vars["connection"].set("Disconnected") + + def _send(self, command: str) -> None: + command = command.strip() + if not command: + return + try: + if not getattr(self.transport, "is_connected", False): + raise RuntimeError("connect before sending commands") + self.transport.write_command(command) # type: ignore[attr-defined] + except Exception as exc: + self._log(f"Send failed: {exc}") + messagebox.showwarning("Command not sent", str(exc)) + + def _send_settings(self) -> None: + valid, errors, normalized = self._validate_settings() + if not valid: + messagebox.showerror("Settings validation failed", "Please fix these settings before sending:\n\n" + "\n".join(f"• {error}" for error in errors)) + return + for key, value in normalized.items(): + self.settings_vars[key].set(value) + for key in SETTINGS_KEYS: + self._send(f"SET,{key},{normalized[key]}") + + def _validate_settings(self) -> Tuple[bool, List[str], Dict[str, str]]: + errors: List[str] = [] + normalized = {key: self.settings_vars[key].get().strip() for key in SETTINGS_KEYS} + + name = normalized["DEVICE_NAME"] + if not 1 <= len(name) <= 16: + errors.append("DEVICE_NAME must be 1-16 characters.") + if any(ord(ch) < 32 or ord(ch) > 126 or ch == "," for ch in name): + errors.append("DEVICE_NAME cannot contain commas or control characters.") + + def parse_int(key: str, low: int, high: int, label: str) -> Optional[int]: + try: + value = int(normalized[key], 10) + except ValueError: + errors.append(f"{key} must be a whole number.") + return None + if not low <= value <= high: + errors.append(f"{key} must be between {low} and {high} {label}.") + normalized[key] = str(value) + return value + + vref = parse_int("SENSOR_VREF_MV", 1000, 5500, "mV") + low_threshold = parse_int("THRESHOLD_LOW", 0, 5500, "mV") + high_threshold = parse_int("THRESHOLD_HIGH", 0, 5500, "mV") + telemetry = parse_int("TELEMETRY_MS", 250, 60000, "ms") + relay_pin = parse_int("RELAY_PIN", 2, 13, "digital pin") + buzzer_pin = parse_int("BUZZER_PIN", 2, 13, "digital pin") + + sensor_pin_text = normalized["SENSOR_PIN"].upper() + analog_aliases = {f"A{i}": str(14 + i) for i in range(6)} + if sensor_pin_text in analog_aliases: + normalized["SENSOR_PIN"] = analog_aliases[sensor_pin_text] + else: + sensor_pin = parse_int("SENSOR_PIN", 14, 19, "analog pin number (A0-A5 / 14-19)") + if sensor_pin is not None: + normalized["SENSOR_PIN"] = str(sensor_pin) + + if vref is not None and high_threshold is not None and high_threshold > vref: + errors.append("THRESHOLD_HIGH cannot exceed SENSOR_VREF_MV.") + if low_threshold is not None and high_threshold is not None and low_threshold >= high_threshold: + errors.append("THRESHOLD_LOW must be less than THRESHOLD_HIGH.") + if relay_pin is not None and buzzer_pin is not None and relay_pin == buzzer_pin: + errors.append("RELAY_PIN and BUZZER_PIN must be different pins.") + if telemetry is not None and normalized["ECO_MODE"].upper() == "ON" and telemetry < 5000: + # This is allowed by firmware, but make the effective behavior visible. + self._log("ECO_MODE is ON; firmware will enforce at least 5000 ms telemetry cadence.") + + for key, allowed in ENUM_VALUES.items(): + value = normalized[key].upper() + if value not in allowed: + errors.append(f"{key} must be one of: {', '.join(allowed)}.") + else: + normalized[key] = value + + return not errors, errors, normalized + + def _factory_reset(self) -> None: + if messagebox.askyesno("Factory reset", "Reset runtime settings to firmware factory defaults and save EEPROM?"): + self._send("FACTORY_RESET") + + def _queue_line(self, line: str) -> None: + self.line_queue.put(line) + + def _drain_serial_queue(self) -> None: + while True: + try: + line = self.line_queue.get_nowait() + except queue.Empty: + break + self._handle_line(line) + self.after(100, self._drain_serial_queue) + + def _handle_line(self, line: str) -> None: + parsed = parse_serial_line(line) + prefix = "!" if parsed.malformed else "<" + self._log(f"{prefix} {parsed.raw}") + self._append_diagnostic(parsed) + if parsed.kind == "CONFIG": + for key, value in parsed.fields.items(): + if key in self.settings_vars: + self.settings_vars[key].set(value) + elif parsed.kind == "STATUS": + self.status_vars["relay"].set(parsed.fields.get("RELAY", "Unknown")) + self.status_vars["buzzer"].set(parsed.fields.get("BUZZER", "Unknown")) + sensor_mv = parsed.fields.get("SENSOR_MV", "Unknown") + sensor_raw = parsed.fields.get("SENSOR_RAW", "Unknown") + self.status_vars["sensor"].set(f"{sensor_mv} mV / raw {sensor_raw}") + self.status_vars["uptime"].set(parsed.fields.get("UPTIME_MS", "Unknown") + " ms") + elif parsed.kind == "ERR": + self.status_vars["connection"].set(f"Board error: {', '.join(parsed.values)}") + elif parsed.kind == "OK" and parsed.values: + self.status_vars["connection"].set(f"OK: {parsed.values[0]}") + + def _append_diagnostic(self, parsed: ParsedLine) -> None: + payload = { + "kind": parsed.kind, + "fields": parsed.fields, + "values": parsed.values, + "malformed": parsed.malformed, + } + self.diagnostic_text.insert("end", json.dumps(payload, sort_keys=True) + "\n") + self.diagnostic_text.see("end") + + def _log(self, message: str) -> None: + timestamp = _dt.datetime.now().strftime("%H:%M:%S") + if hasattr(self, "log_text"): + self.log_text.insert("end", f"[{timestamp}] {message}\n") + self.log_text.see("end") + + def _browse_hex(self) -> None: + path = filedialog.askopenfilename(title="Select prepared firmware HEX", filetypes=[("Intel HEX", "*.hex"), ("All files", "*.*")]) + if path: + self.hex_path.set(path) + + def _upload_hex_placeholder(self) -> None: + path = Path(self.hex_path.get()) + if not path.is_file(): + messagebox.showwarning("HEX required", "Select an existing .hex firmware artifact first.") + return + avrdude = "avrdude" + port = self.port_var.get().strip() or "COMx" + cmd = [avrdude, "-patmega328p", "-carduino", f"-P{port}", "-b115200", "-D", f"-Uflash:w:{path}:i"] + self._log("Prepared upload command: " + " ".join(str(part) for part in cmd)) + try: + completed = subprocess.run(cmd, check=False, capture_output=True, text=True, timeout=60) + self._log(completed.stdout.strip() or "avrdude produced no stdout") + if completed.returncode != 0: + self._log(completed.stderr.strip() or f"avrdude exited with {completed.returncode}") + messagebox.showwarning("Upload did not complete", "See Logs for avrdude output. This feature is a prepared-artifact placeholder.") + except FileNotFoundError: + self._log("avrdude is not bundled/found. Package an uploader before customer delivery.") + messagebox.showinfo("Uploader not bundled", "avrdude was not found. This placeholder documents the upload command for packaging.") + except Exception as exc: + self._log(f"Upload placeholder error: {exc}") + messagebox.showwarning("Upload error", str(exc)) + + def _load_profiles(self) -> None: + self.profile_list.delete(0, "end") + self.profiles: List[Tuple[str, Path]] = [] + if PROFILE_DIR.exists(): + for path in sorted(PROFILE_DIR.glob("*.json")): + self.profiles.append((path.stem, path)) + if not self.profiles: + self.profile_text.delete("1.0", "end") + self.profile_text.insert("end", "No bundled profiles were found. Create JSON profiles in docs/profiles.") + return + for name, _path in self.profiles: + self.profile_list.insert("end", name) + self.profile_list.selection_set(0) + self._show_selected_profile() + + def _show_selected_profile(self) -> None: + selection = self.profile_list.curselection() + if not selection: + return + name, path = self.profiles[selection[0]] + self.status_vars["profile"].set(name) + self.profile_text.delete("1.0", "end") + try: + self.profile_text.insert("end", json.dumps(json.loads(path.read_text(encoding="utf-8")), indent=2)) + except Exception as exc: + self.profile_text.insert("end", f"Could not load profile {path}: {exc}") + + def _save_logs(self) -> None: + path = filedialog.asksaveasfilename(title="Save logs", defaultextension=".log", filetypes=[("Log files", "*.log"), ("Text files", "*.txt")]) + if path: + Path(path).write_text(self.log_text.get("1.0", "end"), encoding="utf-8") + + +def main() -> None: + app = PortableAVRControlStudio() + app.mainloop() + + +if __name__ == "__main__": + main()