Skip to content

A Hardware Hacking Tool with Web-Based CLI That Speaks Every Protocol

first

Geoe9a0ad89e02c
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..3e4c4339
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..52f5bfff
--- /dev/null
+++ b/README.md
@@ -0,0 +1 @@
+IN PROGRESS
\ No newline at end of file
diff --git a/platformio.ini b/platformio.ini
new file mode 100644
index 00000000..adbe811e
--- /dev/null
+++ b/platformio.ini
@@ -0,0 +1,27 @@
+; PlatformIO Project Configuration File
+;
+; Build options: build flags, source filter
+; Upload options: custom upload port, speed and extra flags
+; Library options: dependencies, extra library storages
+; Advanced options: extra scripting
+;
+; Please visit documentation for the other options and examples
+; https://docs.platformio.org/page/projectconf.html
+
+[env:m5stack-stamps3]
+platform = espressif32
+board = m5stack-stamps3
+framework = arduino
+monitor_speed = 115200
+lib_deps =
+ m5stack/M5Cardputer@^1.0.3
+ fastled/FastLED@^3.3.3
+ bblanchon/ArduinoJson@^7.3.0
+ paulstoffregen/OneWire@^2.3.8
+ esp32ping
+build_flags =
+ -D CONFIG_TINYUSB_CDC_ENABLED=1
+ -D ARDUINO_USB_MODE=1
+ -D ARDUINO_USB_CDC_ON_BOOT=1
+ -std=c++17
+
diff --git a/src/Config/TerminalTypeConfigurator.cpp b/src/Config/TerminalTypeConfigurator.cpp
new file mode 100644
index 00000000..cc9c7b58
--- /dev/null
+++ b/src/Config/TerminalTypeConfigurator.cpp
@@ -0,0 +1,25 @@
+#include "TerminalTypeConfigurator.h"
+
+TerminalTypeConfigurator::TerminalTypeConfigurator(HorizontalSelector& selector)
+ : selector(selector) {}
+
+TerminalTypeEnum TerminalTypeConfigurator::configure() {
+ std::vector<std::string> options = {
+ TerminalTypeEnumMapper::toString(TerminalTypeEnum::WiFiClient),
+ TerminalTypeEnumMapper::toString(TerminalTypeEnum::Serial),
+ };
+
+ int selected = selector.select(
+ "ESP32 Bus Pirate",
+ options,
+ "Select terminal type",
+ ""
+ );
+
+ switch (selected) {
+ case 0: return TerminalTypeEnum::WiFiClient;
+ case 1: return TerminalTypeEnum::Serial;
+ case 2: return TerminalTypeEnum::WiFiAp;
+ default: return TerminalTypeEnum::None;
+ }
+}
diff --git a/src/Config/TerminalTypeConfigurator.h b/src/Config/TerminalTypeConfigurator.h
new file mode 100644
index 00000000..dd64da96
--- /dev/null
+++ b/src/Config/TerminalTypeConfigurator.h
@@ -0,0 +1,13 @@
+#pragma once
+
+#include <Selectors/HorizontalSelector.h>
+#include <Enums/TerminalTypeEnum.h>
+
+class TerminalTypeConfigurator {
+public:
+ TerminalTypeConfigurator(HorizontalSelector& selector);
+ TerminalTypeEnum configure();
+
+private:
+ HorizontalSelector& selector;
+};
diff --git a/src/Config/WifiTypeConfigurator.cpp b/src/Config/WifiTypeConfigurator.cpp
new file mode 100644
index 00000000..d58bc298
--- /dev/null
+++ b/src/Config/WifiTypeConfigurator.cpp
@@ -0,0 +1,21 @@
+#include "WifiTypeConfigurator.h"
+
+
+std::string WifiTypeConfigurator::configure(TerminalTypeEnum& terminalType) {
+ switch (terminalType)
+ {
+ case TerminalTypeEnum::WiFiClient:
+ setupWifi();
+ return std::string(WiFi.localIP().toString().c_str());
+
+ case TerminalTypeEnum::WiFiAp: {
+ WiFi.mode(WIFI_AP);
+ WiFi.softAP("buspirate", "averylongpass");
+ return std::string(WiFi.softAPIP().toString().c_str());
+ }
+ default:
+ break;
+ }
+
+ return "";
+}
diff --git a/src/Config/WifiTypeConfigurator.h b/src/Config/WifiTypeConfigurator.h
new file mode 100644
index 00000000..a9c67cf8
--- /dev/null
+++ b/src/Config/WifiTypeConfigurator.h
@@ -0,0 +1,12 @@
+#pragma once
+
+#include <Enums/TerminalTypeEnum.h>
+#include <Vendors/CardWifiSetup.h>
+#include <string>
+#include <WiFi.h>
+
+class WifiTypeConfigurator {
+public:
+ WifiTypeConfigurator() = default;
+ std::string configure(TerminalTypeEnum& terminalType);
+};
diff --git a/src/Controllers/BluetoothController.cpp b/src/Controllers/BluetoothController.cpp
new file mode 100644
index 00000000..614f61c7
--- /dev/null
+++ b/src/Controllers/BluetoothController.cpp
@@ -0,0 +1,266 @@
+#include "Controllers/BluetoothController.h"
+
+/*
+Constructor
+*/
+BluetoothController::BluetoothController(
+ ITerminalView& terminalView,
+ IInput& terminalInput,
+ BluetoothService& bluetoothService,
+ ArgTransformer& argTransformer
+) : terminalView(terminalView),
+ terminalInput(terminalInput),
+ bluetoothService(bluetoothService),
+ argTransformer(argTransformer) {}
+
+/*
+Entry point for BT command
+*/
+void BluetoothController::handleCommand(const TerminalCommand& cmd) {
+ const auto& root = cmd.getRoot();
+
+ if (root == "scan") {
+ handleScan();
+ } else if (root == "pair") {
+ handlePair(cmd);
+ } else if (root == "spoof") {
+ handleSpoof(cmd);
+ } else if (root == "status") {
+ handleStatus();
+ } else if (root == "server") {
+ handleServer(cmd);
+ } else if (root == "keyboard") {
+ handleKeyboard(cmd);
+ } else if (root == "mouse") {
+ handleMouse(cmd);
+ } else if (root == "reset") {
+ handleReset();
+ } else {
+ handleHelp();
+ }
+}
+
+/*
+Scan
+*/
+void BluetoothController::handleScan() {
+ terminalView.println("Bluetooth Scan: In progress for 10 sec...");
+ terminalView.println("");
+
+ bluetoothService.init();
+ auto devices = bluetoothService.scanDevices(10);
+
+ if (devices.empty()) {
+ terminalView.println("Bluetooth Scan: No devices");
+ return;
+ }
+
+ for (size_t i = 0; i < devices.size(); ++i) {
+ const auto& dev = devices[i];
+ terminalView.println(" " + std::to_string(i) + ": " + dev.name + " @ " + dev.address + " RSSI: " + std::to_string(dev.rssi));
+ terminalView.println("");
+ }
+}
+
+/*
+Pair
+*/
+void BluetoothController::handlePair(const TerminalCommand& cmd) {
+ std::string addr = cmd.getSubcommand();
+ if (addr.empty()) {
+ terminalView.println("Usage: pair <mac address>");
+ return;
+ }
+
+ terminalView.println("Bluetooth Pair: Attempting " + addr + "...");
+
+ auto services = bluetoothService.connectTo(addr);
+ if (!services.empty()) {
+ terminalView.println("Bluetooth Pair: Successfully connected.");
+ terminalView.println("Bluetooth Pair: Services discovered:");
+ for (const auto& uuid : services) {
+ terminalView.println(" - " + uuid);
+ }
+ } else {
+ terminalView.println("Bluetooth Pair: Failed to connect to " + addr);
+ }
+}
+
+/*
+Status
+*/
+void BluetoothController::handleStatus() {
+ terminalView.println("Bluetooth Status:");
+
+ if (bluetoothService.getMode() == BluetoothMode::NONE) {
+ terminalView.println(" Mode: Not initialized");
+ return;
+ } else if (bluetoothService.getMode() == BluetoothMode::CLIENT) {
+ terminalView.println(" Mode: Client");
+ } else {
+ terminalView.println(" Mode: Server");
+ }
+
+ terminalView.println(" Connected: " + std::string(bluetoothService.isConnected() ? "Yes" : "No"));
+
+ std::string mac = bluetoothService.getMacAddress();
+ if (!mac.empty()) {
+ terminalView.println(" MAC Address: " + mac);
+ } else {
+ terminalView.println(" MAC Address: Unknown");
+ }
+}
+
+/*
+Server
+*/
+void BluetoothController::handleServer(const TerminalCommand& cmd) {
+ if (bluetoothService.getMode() == BluetoothMode::SERVER && bluetoothService.isConnected()) {
+ terminalView.println("Bluetooth Server: Already Started");
+ return;
+ }
+
+ std::string name = cmd.getSubcommand();
+ if (name.empty()) {
+ name = "Bus-Pirate-Bluetooth";
+ }
+
+ terminalView.println("Bluetooth Server: Starting BLE HID server as \"" + name + "\"...");
+ bluetoothService.begin(name);
+ terminalView.println("→ You can now pair from your phone or computer.");
+}
+
+/*
+Keyboard
+*/
+void BluetoothController::handleKeyboard(const TerminalCommand& cmd) {
+ if (bluetoothService.getMode() != BluetoothMode::SERVER) {
+ terminalView.println("Bluetooth Keyboard: Start the server before sending data");
+ return;
+ }
+
+ auto text = cmd.getSubcommand();
+ if (text.empty()) {
+ terminalView.println("Usage: keyboard <text>");
+ return;
+ }
+
+ bluetoothService.sendKeyboardText(text);
+ terminalView.println("Bluetooth Keyboard: String sent.");
+}
+
+/*
+Mouse
+*/
+void BluetoothController::handleMouse(const TerminalCommand& cmd) {
+ if (bluetoothService.getMode() != BluetoothMode::SERVER) {
+ terminalView.println("Bluetooth Mouse: Start the server before sending data");
+ return;
+ }
+
+ // mouse click
+ if (cmd.getSubcommand() == "click") {
+ bluetoothService.clickMouse();
+ terminalView.println("Bluetooth Mouse: Click sent.");
+ return;
+ }
+
+ auto args = argTransformer.splitArgs(cmd.getArgs());
+
+ // mouse move x y
+ if (args.size() == 2 && cmd.getSubcommand() == "move" &&
+ argTransformer.isValidNumber(args[0]) &&
+ argTransformer.isValidNumber(args[1])) {
+
+ int16_t x = static_cast<int16_t>(std::stoi(args[0]));
+ int16_t y = static_cast<int16_t>(std::stoi(args[1]));
+
+ bluetoothService.mouseMove(x, y);
+ terminalView.println("Bluetooth Mouse: Moved by (" + std::to_string(x) + ", " + std::to_string(y) + ")");
+ return;
+ }
+
+ // mouse x y
+ if (args.size() != 1 || !argTransformer.isValidNumber(cmd.getSubcommand()) || !argTransformer.isValidNumber(args[0])) {
+ terminalView.println("Usage: mouse <x> <y> or mouse click");
+ return;
+ }
+
+ int16_t x = static_cast<int8_t>(std::stoi(cmd.getSubcommand()));
+ int16_t y = static_cast<int8_t>(std::stoi(args[0]));
+
+ bluetoothService.mouseMove(x, y);
+ terminalView.println("Bluetooth Mouse: Moved by (" + std::to_string(x) + ", " + std::to_string(y) + ")");
+}
+
+/*
+Spoof
+*/
+void BluetoothController::handleSpoof(const TerminalCommand& cmd) {
+ std::string mac = cmd.getSubcommand();
+ if (bluetoothService.isConnected()) {
+ terminalView.println("Bluetooth Spoof: You can't spoof mac after bluetooth init");
+ return;
+ }
+
+ if (mac.empty()) {
+ terminalView.println("Usage: spoof <mac address>");
+ return;
+ }
+
+ bool success = bluetoothService.spoofMacAddress(mac);
+ if (success) {
+ terminalView.println("Bluetooth Spoof: MAC address overridden to " + mac);
+ } else {
+ terminalView.println("Bluetooth Spoof: Failed to set MAC address.");
+ }
+}
+
+/*
+Reset
+*/
+void BluetoothController::handleReset() {
+ bluetoothService.end();
+ terminalView.println("Bluetooth: Reset complete.");
+}
+
+/*
+Config
+*/
+void BluetoothController::handleConfig() {
+ // bluetoothService.init();
+}
+
+/*
+Help
+*/
+void BluetoothController::handleHelp() {
+ terminalView.println("Bluetooth commands:");
+ terminalView.println(" scan");
+ terminalView.println(" pair <addr>");
+ terminalView.println(" spoof <mac>");
+ terminalView.println(" sniff");
+ terminalView.println(" status");
+ terminalView.println(" server");
+ terminalView.println(" keyboard <text>");
+ terminalView.println(" mouse <x> <y>");
+ terminalView.println(" mouse click");
+ terminalView.println(" reset");
+}
+
+/*
+Sniff
+*/
+void BluetoothController::handleSniff() {
+ terminalView.println("Bluetooth Sniff: Not Yet Implemented");
+}
+
+/*
+Ensure Config
+*/
+void BluetoothController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
diff --git a/src/Controllers/BluetoothController.h b/src/Controllers/BluetoothController.h
new file mode 100644
index 00000000..ba865da4
--- /dev/null
+++ b/src/Controllers/BluetoothController.h
@@ -0,0 +1,64 @@
+#pragma once
+
+#include <string>
+#include "Views/ITerminalView.h"
+#include "Inputs/IInput.h"
+#include "Services/BluetoothService.h"
+#include "Transformers/ArgTransformer.h"
+#include "Models/TerminalCommand.h"
+
+class BluetoothController {
+public:
+ BluetoothController(
+ ITerminalView& terminalView,
+ IInput& terminalInput,
+ BluetoothService& bluetoothService,
+ ArgTransformer& argTransformer
+ );
+
+ // Entry point for BT command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Ensure BT configuration
+ void ensureConfigured();
+
+private:
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ BluetoothService& bluetoothService;
+ ArgTransformer& argTransformer;
+ bool configured = false;
+
+ // Scan for BT devices
+ void handleScan();
+
+ // Pair with BT device
+ void handlePair(const TerminalCommand& cmd);
+
+ // Spoof mac addr
+ void handleSpoof(const TerminalCommand& cmd);
+
+ // Show BT status
+ void handleStatus();
+
+ // Create BT HID server
+ void handleServer(const TerminalCommand& cmd);
+
+ // Handle KB action
+ void handleKeyboard(const TerminalCommand& cmd);
+
+ // Handle mouse action
+ void handleMouse(const TerminalCommand& cmd);
+
+ // Sniff BT server I/O
+ void handleSniff();
+
+ // Available BT commands
+ void handleHelp();
+
+ // Config BT
+ void handleConfig();
+
+ // Reset BT interface
+ void handleReset();
+};
\ No newline at end of file
diff --git a/src/Controllers/DioController.cpp b/src/Controllers/DioController.cpp
new file mode 100644
index 00000000..c8a91b82
--- /dev/null
+++ b/src/Controllers/DioController.cpp
@@ -0,0 +1,236 @@
+#include "Controllers/DioController.h"
+#include <sstream>
+#include <algorithm>
+
+/*
+Constructor
+*/
+DioController::DioController(ITerminalView& terminalView, IInput& terminalInput, PinService& pinService, ArgTransformer& argTransformer)
+ : terminalView(terminalView), terminalInput(terminalInput), pinService(pinService), argTransformer(argTransformer) {}
+
+/*
+Entry point to handle a DIO command
+*/
+void DioController::handleCommand(const TerminalCommand& cmd) {
+ if (cmd.getRoot() == "sniff") {
+ handleSniff(cmd);
+ }
+
+ else if (cmd.getRoot() == "read") {
+ handleReadPin(cmd);
+ }
+
+ else if (cmd.getRoot() == "set") {
+ handleSetPin(cmd);
+ }
+
+ else if (cmd.getRoot() == "pullup") {
+ handlePullup(cmd);
+ }
+
+ else if (cmd.getRoot() == "pwm") {
+ handlePwm(cmd);
+ }
+
+ else if (cmd.getRoot() == "reset") {
+ handleResetPin(cmd);
+ }
+
+ else {
+ handleHelp();
+ }
+}
+
+/*
+Read
+*/
+void DioController::handleReadPin(const TerminalCommand& cmd) {
+ if (cmd.getSubcommand().empty()) {
+ terminalView.println("Usage: read <pin>");
+ return;
+ }
+
+ int pin = std::stoi(cmd.getSubcommand());
+ int value = pinService.read(pin);
+ terminalView.println("Pin " + std::to_string(pin) + " = " + std::to_string(value));
+}
+
+/*
+Set
+*/
+void DioController::handleSetPin(const TerminalCommand& cmd) {
+ if (cmd.getSubcommand().empty()) {
+ terminalView.println("Usage: set <pin> <IN/OUT/HI/LOW>");
+ return;
+ }
+
+ int pin = std::stoi(cmd.getSubcommand());
+ std::string arg = cmd.getArgs();
+ if (arg.empty()) {
+ terminalView.println("DIO Set: Invalid argument.");
+ return;
+ }
+
+ char c = std::toupper(arg[0]);
+
+ switch (c) {
+ case 'I':
+ pinService.setInput(pin);
+ terminalView.println("DIO Set: Pin " + std::to_string(pin) + " set to INPUT");
+ break;
+ case 'O':
+ pinService.setOutput(pin);
+ terminalView.println("DIO Set: Pin " + std::to_string(pin) + " set to OUTPUT");
+ break;
+ case 'H':
+ pinService.setOutput(pin);
+ pinService.setHigh(pin);
+ terminalView.println("DIO Set: Pin " + std::to_string(pin) + " set to HIGH");
+ break;
+ case 'L':
+ pinService.setOutput(pin);
+ pinService.setLow(pin);
+ terminalView.println("DIO Set: Pin " + std::to_string(pin) + " set to LOW");
+ break;
+ default:
+ terminalView.println("Unknown command. Use I, O, H, or L.");
+ break;
+ }
+}
+
+
+/*
+Pullup
+*/
+void DioController::handlePullup(const TerminalCommand& cmd) {
+ if (cmd.getSubcommand().empty()) {
+ terminalView.println("Usage: pullup <pin>");
+ return;
+ }
+
+ int pin = std::stoi(cmd.getSubcommand());
+ pinService.setInputPullup(pin);
+
+ terminalView.println("DIO Pullup: Set on pin " + std::to_string(pin));
+}
+
+/*
+Sniff
+*/
+void DioController::handleSniff(const TerminalCommand& cmd) {
+ if (cmd.getSubcommand().empty()) {
+ terminalView.println("Usage: sniff <pin>");
+ return;
+ }
+
+ int pin = std::stoi(cmd.getSubcommand());
+ pinService.setInput(pin);
+
+ terminalView.println("DIO Sniff: Pin " + std::to_string(pin) + " (press ENTER to stop)...");
+
+ int last = pinService.read(pin);
+ terminalView.println("Initial state: " + std::to_string(last));
+
+ unsigned long lastCheck = millis();
+ while (true) {
+ // check ENTER press
+ if (millis() - lastCheck > 10) {
+ lastCheck = millis();
+ char c = terminalInput.readChar();
+ if (c == '\r' || c == '\n') {
+ terminalView.println("DIO Sniff: Stopped.");
+ break;
+ }
+ }
+
+ // check pin state
+ int current = pinService.read(pin);
+ if (current != last) {
+ std::string transition = (last == 0 && current == 1)
+ ? "LOW -> HIGH"
+ : "HIGH -> LOW";
+ terminalView.println("Pin " + std::to_string(pin) + ": " + transition);
+ last = current;
+ }
+ }
+}
+
+/*
+Pwm
+*/
+void DioController::handlePwm(const TerminalCommand& cmd) {
+ auto sub = cmd.getSubcommand();
+ auto args = argTransformer.splitArgs(cmd.getArgs());
+
+ if (!sub.empty() && args.size() != 2) {
+ terminalView.println("DIO PWN: Invalid syntax. Use:");
+ terminalView.println(" pwm <pin> <frequency> <duty>");
+ return;
+ }
+
+ if (!argTransformer.isValidNumber(sub) ||
+ !argTransformer.isValidNumber(args[0]) ||
+ !argTransformer.isValidNumber(args[1])) {
+ terminalView.println("DIO PWN: All arguments must be valid numbers.");
+ return;
+ }
+
+ uint8_t pin = argTransformer.toUint8(sub);
+ uint32_t freq = argTransformer.toUint32(args[0]);
+ uint8_t duty = argTransformer.toUint8(args[1]);
+
+ if (duty > 100) {
+ terminalView.println("DIO PWN: Duty cycle must be between 0 and 100.");
+ return;
+ }
+
+ int channel = pin % 16;
+ int resolution = 8;
+
+ ledcSetup(channel, freq, resolution);
+ ledcAttachPin(pin, channel);
+ uint32_t dutyVal = (duty * ((1 << resolution) - 1)) / 100;
+ ledcWrite(channel, dutyVal);
+
+ terminalView.println("DIO PWM: Pin " + std::to_string(pin) +
+ " (" + std::to_string(freq) + "Hz, " +
+ std::to_string(duty) + "% duty).");
+}
+
+/*
+Reset
+*/
+void DioController::handleResetPin(const TerminalCommand& cmd) {
+ if (cmd.getSubcommand().empty()) {
+ terminalView.println("Usage: reset <pin>");
+ return;
+ }
+
+ if (!argTransformer.isValidNumber(cmd.getSubcommand())) {
+ terminalView.println("DIO Reset: Invalid pin number.");
+ return;
+ }
+
+ uint8_t pin = argTransformer.toUint8(cmd.getSubcommand());
+
+ // Detacher PWM
+ ledcDetachPin(pin);
+
+ // Reset Pullup
+ pinService.setInput(pin);
+
+ terminalView.println("DIO Reset: Pin " + std::to_string(pin) + " to INPUT (no pull-up, no PWM).");
+}
+
+/*
+Help
+*/
+void DioController::handleHelp() {
+ terminalView.println("Unknown DIO command. Usage:");
+ terminalView.println(" sniff <pin>");
+ terminalView.println(" read <pin>");
+ terminalView.println(" set <pin> <H/L/I/O>");
+ terminalView.println(" pullup <pin>");
+ terminalView.println(" pwm <pin> <freq> <duty>");
+ terminalView.println(" reset <pin>");
+}
\ No newline at end of file
diff --git a/src/Controllers/DioController.h b/src/Controllers/DioController.h
new file mode 100644
index 00000000..beb64abd
--- /dev/null
+++ b/src/Controllers/DioController.h
@@ -0,0 +1,47 @@
+// DioController.h
+#pragma once
+
+#include <string>
+#include "Views/ITerminalView.h"
+#include "Inputs/IInput.h"
+#include "Services/PinService.h"
+#include "Models/TerminalCommand.h"
+#include "States/GlobalState.h"
+#include "Transformers/ArgTransformer.h"
+
+class DioController {
+public:
+ // Constructor
+ DioController(ITerminalView& terminalView, IInput& terminalInput, PinService& pinService, ArgTransformer& argTransformer);
+
+ // Entry point to handle a DIO command
+ void handleCommand(const TerminalCommand& cmd);
+
+private:
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ PinService& pinService;
+ ArgTransformer& argTransformer;
+ GlobalState& state = GlobalState::getInstance();
+
+ // Read digital value from a pin
+ void handleReadPin(const TerminalCommand& cmd);
+
+ // Set pin high or low, input or output
+ void handleSetPin(const TerminalCommand& cmd);
+
+ // Enable internal pull-up resistor
+ void handlePullup(const TerminalCommand& cmd);
+
+ // Start pin state sniffing
+ void handleSniff(const TerminalCommand& cmd);
+
+ // Configure PWM on a pin
+ void handlePwm(const TerminalCommand& cmd);
+
+ // Reset pin to default state
+ void handleResetPin(const TerminalCommand& cmd);
+
+ // Display DIO help info
+ void handleHelp();
+};
\ No newline at end of file
diff --git a/src/Controllers/HdUartController.cpp b/src/Controllers/HdUartController.cpp
new file mode 100644
index 00000000..fc787d1a
--- /dev/null
+++ b/src/Controllers/HdUartController.cpp
@@ -0,0 +1,168 @@
+#include "HdUartController.h"
+
+/*
+Constructor
+*/
+HdUartController::HdUartController(ITerminalView& terminalView, IInput& terminalInput, IInput& deviceInput,
+ HdUartService& hdUartService, ArgTransformer& argTransformer)
+ : terminalView(terminalView), terminalInput(terminalInput), deviceInput(deviceInput),
+ hdUartService(hdUartService), argTransformer(argTransformer) {}
+
+/*
+Entry point for HDUART commands
+*/
+void HdUartController::handleCommand(const TerminalCommand& cmd) {
+ if (cmd.getRoot() == "bridge") handleBridge();
+ else if (cmd.getRoot() == "config") handleConfig();
+ else handleHelp();
+}
+
+/*
+Entry point for HDUART instructions
+*/
+void HdUartController::handleInstruction(const std::vector<ByteCode>& bytecodes) {
+ auto result = hdUartService.executeByteCode(bytecodes);
+ terminalView.println("");
+ terminalView.print("HDUART Read: ");
+ terminalView.println(result.empty() ? "No data" : "\n\n" + result);
+ terminalView.println("");
+}
+
+/*
+Bridge mode read/write
+*/
+void HdUartController::handleBridge() {
+ terminalView.println("HDUART Bridge: in progress... Press Cardputer key to stop");
+ while (true) {
+ if (hdUartService.available()) {
+ terminalView.print(std::string(1, hdUartService.read()));
+ }
+ char c = terminalInput.readChar();
+ if (c != KEY_NONE) hdUartService.write(c);
+ c = deviceInput.readChar();
+ if (c != KEY_NONE) {
+ terminalView.println("\nHDUART Bridge: Stopped by user.");
+ break;
+ }
+ }
+}
+
+/*
+Config
+*/
+void HdUartController::handleConfig() {
+ terminalView.println("\nHDUART Configuration:");
+
+ uint8_t pin = readValidatedUint8("Shared TX/RX pin", state.getHdUartPin());
+ state.setHdUartPin(pin);
+
+ uint32_t baud = readValidatedUint32("Baud rate", state.getHdUartBaudRate());
+ state.setHdUartBaudRate(baud);
+
+ uint8_t dataBits = readValidatedUint8("Data bits (5-8)", state.getHdUartDataBits(), 5, 8);
+ state.setHdUartDataBits(dataBits);
+
+ char parity = readCharChoice("Parity (N/E/O)", 'N', {'N', 'E', 'O'});
+ state.setHdUartParity(std::string(1, parity));
+
+ uint8_t stopBits = readValidatedUint8("Stop bits (1 or 2)", state.getHdUartStopBits(), 1, 2);
+ state.setHdUartStopBits(stopBits);
+
+ bool inverted = readYesNo("Inverted?", state.isHdUartInverted());
+ state.setHdUartInverted(inverted);
+
+ uint32_t config = buildUartConfig(dataBits, parity, stopBits);
+ state.setHdUartConfig(config);
+
+ hdUartService.configure(baud, config, pin, inverted);
+
+ terminalView.println("HDUART configuration applied.\n");
+}
+
+/*
+Help
+*/
+void HdUartController::handleHelp() {
+ terminalView.println("\nHDUART Commands:\n"
+ " bridge Interactive mode\n"
+ " config Set TX/RX pin, baud etc.\n");
+}
+
+std::string HdUartController::getUserInput() {
+ std::string input;
+ while (true) {
+ char c = terminalInput.handler();
+ if (c == '\r' || c == '\n') break;
+ terminalView.print(std::string(1, c));
+ input += c;
+ }
+ terminalView.println("");
+ return input;
+}
+
+uint8_t HdUartController::readValidatedUint8(const std::string& label, uint8_t def, uint8_t min, uint8_t max) {
+ while (true) {
+ terminalView.print(label + " [" + std::to_string(def) + "]: ");
+ std::string input = getUserInput();
+ if (input.empty()) return def;
+ if (argTransformer.isValidNumber(input)) {
+ uint8_t val = argTransformer.toUint8(input);
+ if (val >= min && val <= max) return val;
+ }
+ terminalView.println("Invalid input. Must be " + std::to_string(min) + "-" + std::to_string(max));
+ }
+}
+
+uint32_t HdUartController::readValidatedUint32(const std::string& label, uint32_t def) {
+ while (true) {
+ terminalView.print(label + " [" + std::to_string(def) + "]: ");
+ std::string input = getUserInput();
+ if (input.empty()) return def;
+ if (argTransformer.isValidNumber(input))
+ return argTransformer.toUint32(input);
+ terminalView.println("Invalid number.");
+ }
+}
+
+char HdUartController::readCharChoice(const std::string& label, char def, const std::vector<char>& allowed) {
+ while (true) {
+ terminalView.print(label + " [" + def + "]: ");
+ std::string input = getUserInput();
+ if (input.empty()) return def;
+ char c = toupper(input[0]);
+ if (std::find(allowed.begin(), allowed.end(), c) != allowed.end()) return c;
+ terminalView.println("Invalid choice.");
+ }
+}
+
+bool HdUartController::readYesNo(const std::string& label, bool def) {
+ while (true) {
+ terminalView.print(label + " [" + (def ? "y" : "n") + "]: ");
+ std::string input = getUserInput();
+ if (input.empty()) return def;
+ char c = tolower(input[0]);
+ if (c == 'y') return true;
+ if (c == 'n') return false;
+ terminalView.println("Please answer y or n.");
+ }
+}
+
+uint32_t HdUartController::buildUartConfig(uint8_t bits, char parity, uint8_t stop) {
+ uint32_t conf = SERIAL_8N1;
+ if (bits == 5) conf = (stop == 2) ? SERIAL_5N2 : SERIAL_5N1;
+ else if (bits == 6) conf = (stop == 2) ? SERIAL_6N2 : SERIAL_6N1;
+ else if (bits == 7) conf = (stop == 2) ? SERIAL_7N2 : SERIAL_7N1;
+ else if (bits == 8) conf = (stop == 2) ? SERIAL_8N2 : SERIAL_8N1;
+
+ if (parity == 'E') conf |= 0x02;
+ else if (parity == 'O') conf |= 0x01;
+
+ return conf;
+}
+
+void HdUartController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
diff --git a/src/Controllers/HdUartController.h b/src/Controllers/HdUartController.h
new file mode 100644
index 00000000..e583d588
--- /dev/null
+++ b/src/Controllers/HdUartController.h
@@ -0,0 +1,51 @@
+#pragma once
+
+#include "Views/ITerminalView.h"
+#include "Inputs/IInput.h"
+#include "Models/ByteCode.h"
+#include "Models/TerminalCommand.h"
+#include "Services/HdUartService.h"
+#include "Transformers/ArgTransformer.h"
+#include "States/GlobalState.h"
+
+
+class HdUartController {
+public:
+ HdUartController(ITerminalView& terminalView, IInput& terminalInput, IInput& deviceInput,
+ HdUartService& hdUartService, ArgTransformer& argTransformer);
+
+ // Entry point for HDUART command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Entry point for HDUART instructions
+ void handleInstruction(const std::vector<ByteCode>& bytecodes);
+
+ // HDUART config check
+ void ensureConfigured();
+
+private:
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ IInput& deviceInput;
+ HdUartService& hdUartService;
+ ArgTransformer& argTransformer;
+ GlobalState& state = GlobalState::getInstance();
+
+ bool configured = false;
+
+ // HDUART Bridge mode read/write on one line
+ void handleBridge();
+
+ // Configure HDUART
+ void handleConfig();
+
+ // HDURT Available commands
+ void handleHelp();
+
+ std::string getUserInput();
+ uint8_t readValidatedUint8(const std::string& label, uint8_t defaultVal, uint8_t min = 0, uint8_t max = 255);
+ uint32_t readValidatedUint32(const std::string& label, uint32_t defaultVal);
+ char readCharChoice(const std::string& label, char defaultVal, const std::vector<char>& allowed);
+ bool readYesNo(const std::string& label, bool defaultVal);
+ uint32_t buildUartConfig(uint8_t dataBits, char parity, uint8_t stopBits);
+};
diff --git a/src/Controllers/I2cController.cpp b/src/Controllers/I2cController.cpp
new file mode 100644
index 00000000..6bb98036
--- /dev/null
+++ b/src/Controllers/I2cController.cpp
@@ -0,0 +1,337 @@
+#include "I2cController.h"
+
+I2cController::I2cController(ITerminalView& terminalView, IInput& terminalInput, I2cService& i2cService, ArgTransformer& argTransformer)
+ : terminalView(terminalView), terminalInput(terminalInput), i2cService(i2cService), argTransformer(argTransformer) {}
+
+/*
+Entry point to handle I2C command
+*/
+void I2cController::handleCommand(const TerminalCommand& cmd) {
+ if (cmd.getRoot() == "scan") {
+ handleScan();
+ }
+
+ else if (cmd.getRoot() == "sniff") {
+ handleSniff();
+ }
+
+ else if (cmd.getRoot() == "ping") {
+ handlePing(cmd);
+ }
+
+ else if (cmd.getRoot() == "write") {
+ handleWrite(cmd);
+ }
+
+ else if (cmd.getRoot() == "read") {
+ handleRead(cmd);
+ }
+
+ else if (cmd.getRoot() == "config") {
+ handleConfig();
+ }
+
+ else {
+ handleHelp();
+ }
+}
+
+/*
+Entry point to handle I2C instruction
+*/
+void I2cController::handleInstruction(const std::vector<ByteCode>& bytecodes) {
+ auto result = i2cService.executeByteCode(bytecodes);
+ if (!result.empty()) {
+ terminalView.println("I2C Read:\n");
+ terminalView.println(result);
+ }
+}
+
+void I2cController::handleScan() {
+ terminalView.println("I2C Scan: Scanning I2C bus...");
+ terminalView.println("");
+ bool found = false;
+
+ for (uint8_t addr = 1; addr < 127; ++addr) {
+ i2cService.beginTransmission(addr);
+ if (i2cService.endTransmission() == 0) {
+ std::stringstream ss;
+ ss << "Found device at 0x" << std::hex << std::uppercase << (int)addr;
+ terminalView.println(ss.str());
+ found = true;
+ }
+ }
+
+ if (!found) {
+ terminalView.println("I2C Scan: No I2C devices found.");
+ }
+ terminalView.println("");
+}
+
+/*
+Sniff
+*/
+void I2cController::handleSniff() {
+ terminalView.println("I2C Sniff Mode: capturing raw bytes.");
+ terminalView.println("Press ENTER to stop.\n");
+ terminalView.println("");
+
+ uint8_t sclPin = state.getI2cSclPin();
+ uint8_t sdaPin = state.getI2cSdaPin();
+ uint32_t freq = state.getI2cFrequency();
+ uint32_t delayUs = 500000 / freq;
+ if (delayUs < 1) delayUs = 1;
+
+ uint8_t bitCount = 0;
+ uint8_t currentByte = 0;
+ int lastSCL = digitalRead(sclPin);
+
+ unsigned long lastCharCheck = millis();
+
+ while (true) {
+
+ lastCharCheck = millis();
+ char c = terminalInput.readChar();
+ if (c == '\r' || c == '\n') break;
+
+ int scl = digitalRead(sclPin);
+ int sda = digitalRead(sdaPin);
+
+ // Detect rising edge on SCL
+ if (lastSCL == LOW && scl == HIGH) {
+ currentByte <<= 1;
+ if (sda) currentByte |= 1;
+ bitCount++;
+
+ if (bitCount == 8) {
+ std::stringstream ss;
+ ss << "0x" << std::hex << std::uppercase << (int)currentByte << " ";
+ terminalView.print(ss.str());
+
+ bitCount = 0;
+ currentByte = 0;
+ }
+ }
+
+ lastSCL = scl;
+ delayMicroseconds(delayUs);
+ }
+
+ terminalView.println("");
+ terminalView.println("I2C Sniff: Exited.");
+}
+
+/*
+Ping
+*/
+void I2cController::handlePing(const TerminalCommand& cmd) {
+ if (cmd.getSubcommand().empty()) {
+ terminalView.println("Usage: ping <I2C address>");
+ return;
+ }
+
+ const std::string& arg = cmd.getSubcommand();
+ uint8_t address = 0;
+
+ std::stringstream ss(arg);
+ int temp = 0;
+
+ // Detect hex prefix
+ if (arg.rfind("0x", 0) == 0 || arg.rfind("0X", 0) == 0) {
+ ss >> std::hex >> temp;
+ } else {
+ ss >> std::dec >> temp;
+ }
+
+ if (ss.fail() || temp < 0 || temp > 127) {
+ terminalView.println("I2C Ping: Invalid address format. Use hex (e.g. 0x3C).");
+ return;
+ }
+
+ address = static_cast<uint8_t>(temp);
+
+ std::stringstream result;
+ result << "Ping 0x" << std::hex << std::uppercase << (int)address << ": ";
+
+ i2cService.beginTransmission(address);
+ uint8_t i2cResult = i2cService.endTransmission();
+
+ if (i2cResult == 0) {
+ result << "I2C Ping: ACK received! Device is present.";
+ } else {
+ result << "I2C Ping: No response (NACK or error).";
+ }
+
+ terminalView.println(result.str());
+}
+
+/*
+Write
+*/
+void I2cController::handleWrite(const TerminalCommand& cmd) {
+ auto args = argTransformer.splitArgs(cmd.getArgs());
+
+ if (args.size() < 2) {
+ terminalView.println("Usage: write <addr> <reg> <val>");
+ return;
+ }
+
+ const std::string& addrStr = cmd.getSubcommand();
+ const std::string& regStr = args[0];
+ const std::string& valStr = args[1];
+
+ if (!argTransformer.isValidNumber(addrStr) ||
+ !argTransformer.isValidNumber(regStr) ||
+ !argTransformer.isValidNumber(valStr)) {
+ terminalView.println("Error: Invalid argument. Use decimal or 0x-prefixed hex values.");
+ return;
+ }
+
+ uint8_t addr = argTransformer.parseHexOrDec(addrStr);
+ uint8_t reg = argTransformer.parseHexOrDec(regStr);
+ uint8_t val = argTransformer.parseHexOrDec(valStr);
+
+ i2cService.beginTransmission(addr);
+ i2cService.write(reg);
+ i2cService.write(val);
+ i2cService.endTransmission();
+
+ terminalView.println("I2C Write: Data Sent.");
+}
+
+/*
+Read
+*/
+void I2cController::handleRead(const TerminalCommand& cmd) {
+ if (cmd.getSubcommand().empty()) {
+ terminalView.println("Usage: read <addr> <reg>");
+ return;
+ }
+
+ if (!argTransformer.isValidNumber(cmd.getSubcommand()) ||
+ !argTransformer.isValidNumber(cmd.getArgs())) {
+ terminalView.println("Error: Invalid argument. Use decimal or 0x-prefixed hex values.");
+ return;
+ }
+
+ uint8_t addr = argTransformer.parseHexOrDec(cmd.getSubcommand());
+ uint8_t reg = argTransformer.parseHexOrDec(cmd.getArgs());
+
+ // Write register address first
+ i2cService.beginTransmission(addr);
+ i2cService.write(reg);
+ i2cService.endTransmission(false);
+
+ i2cService.requestFrom(addr, 1);
+ if (i2cService.available()) {
+ int value = i2cService.read();
+ std::stringstream ss;
+ ss << "0x" << std::hex << std::uppercase << value;
+ terminalView.println("Read: " + ss.str());
+ } else {
+ terminalView.println("I2C Read: No data available.");
+ }
+}
+
+/*
+Config
+*/
+void I2cController::handleConfig() {
+ terminalView.println("");
+ terminalView.println("I2C Configuration:");
+
+ GlobalState& state = GlobalState::getInstance();
+
+ // SDA
+ uint8_t sda = state.getI2cSdaPin();
+ while (true) {
+ terminalView.print("SDA pin [" + std::to_string(sda) + "]: ");
+ std::string sdaInput = getUserInput();
+ if (sdaInput.empty()) break;
+
+ if (argTransformer.isValidNumber(sdaInput)) {
+ sda = argTransformer.toUint8(sdaInput);
+ break;
+ } else {
+ terminalView.println("Invalid value. Please enter a valid number.");
+ }
+ }
+ state.setI2cSdaPin(sda);
+
+ // SCL
+ uint8_t scl = state.getI2cSclPin();
+ while (true) {
+ terminalView.print("SCL pin [" + std::to_string(scl) + "]: ");
+ std::string sclInput = getUserInput();
+ if (sclInput.empty()) break;
+
+ if (argTransformer.isValidNumber(sclInput)) {
+ scl = argTransformer.toUint8(sclInput);
+ break;
+ } else {
+ terminalView.println("Invalid value. Please enter a valid number.");
+ }
+ }
+ state.setI2cSclPin(scl);
+
+ // Frequency
+ uint32_t freq = state.getI2cFrequency();
+ while (true) {
+ terminalView.print("Frequency [" + std::to_string(freq) + "]: ");
+ std::string freqInput = getUserInput();
+ if (freqInput.empty()) break;
+
+ if (argTransformer.isValidNumber(freqInput)) {
+ freq = argTransformer.toUint32(freqInput);
+ break;
+ } else {
+ terminalView.println("Invalid value. Please enter a valid number.");
+ }
+ }
+ state.setI2cFrequency(freq);
+
+ i2cService.configure(sda, scl, freq);
+ terminalView.println("I2C configured.");
+ terminalView.println("");
+}
+
+/*
+Help
+*/
+void I2cController::handleHelp() {
+ terminalView.println("Unknown I2C command. Usage:");
+ terminalView.println(" scan");
+ terminalView.println(" ping <addr>");
+ terminalView.println(" sniff");
+ terminalView.println(" read <addr> <reg>");
+ terminalView.println(" write <addr> <reg> <val>");
+ terminalView.println(" config");
+ terminalView.println(" raw instructions, e.g: [0xA0] [0x01 r:8]");
+}
+
+std::string I2cController::getUserInput() {
+ std::string result;
+ while (true) {
+ char c = terminalInput.handler();
+ if (c == '\r' || c == '\n') break;
+ result += c;
+ terminalView.print(std::string(1, c));
+ }
+ terminalView.println("");
+ return result;
+}
+
+void I2cController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ } else {
+ // Reset I2C
+ i2cService.end();
+ uint8_t sda = state.getI2cSdaPin();
+ uint8_t scl = state.getI2cSclPin();
+ uint32_t freq = state.getI2cFrequency();
+ i2cService.configure(sda, scl, freq);
+
+ }
+}
\ No newline at end of file
diff --git a/src/Controllers/I2cController.h b/src/Controllers/I2cController.h
new file mode 100644
index 00000000..ff336aa5
--- /dev/null
+++ b/src/Controllers/I2cController.h
@@ -0,0 +1,59 @@
+#pragma once
+
+#include <sstream>
+#include <string>
+#include <algorithm>
+#include "Views/ITerminalView.h"
+#include "Inputs/IInput.h"
+#include "Services/I2cService.h"
+#include "Models/TerminalCommand.h"
+#include "Models/ByteCode.h"
+#include "States/GlobalState.h"
+#include "Transformers/ArgTransformer.h"
+
+class I2cController {
+public:
+ // Constructor
+ I2cController(ITerminalView& terminalView, IInput& terminalInput, I2cService& i2cService, ArgTransformer& argTransformer);
+
+ // Entry point for I2C command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Entry point for compiled bytecode instructions
+ void handleInstruction(const std::vector<ByteCode>& bytecodes);
+
+ // Ensure I2C is configured before use
+ void ensureConfigured();
+
+private:
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ I2cService& i2cService;
+ ArgTransformer& argTransformer;
+ bool configured = false;
+ GlobalState& state = GlobalState::getInstance();
+
+ // Ping an I2C address
+ void handlePing(const TerminalCommand& cmd);
+
+ // Scan the I2C bus for devices
+ void handleScan();
+
+ // Start sniffing I2C traffic
+ void handleSniff();
+
+ // Read data from an I2C device
+ void handleRead(const TerminalCommand& cmd);
+
+ // Write data to an I2C device
+ void handleWrite(const TerminalCommand& cmd);
+
+ // Configure I2C parameters
+ void handleConfig();
+
+ // Show I2C help message
+ void handleHelp();
+
+ // Read user input from terminal
+ std::string getUserInput();
+};
diff --git a/src/Controllers/InfraredController.cpp b/src/Controllers/InfraredController.cpp
new file mode 100644
index 00000000..833957d1
--- /dev/null
+++ b/src/Controllers/InfraredController.cpp
@@ -0,0 +1,252 @@
+#include "InfraredController.h"
+
+InfraredController::InfraredController(ITerminalView& view, IInput& terminalInput, InfraredService& service, ArgTransformer& argTransformer)
+ : terminalView(view), terminalInput(terminalInput), infraredService(service), argTransformer(argTransformer) {}
+
+/*
+Entry point to handle Infrared command
+*/
+void InfraredController::handleCommand(const TerminalCommand& command) {
+ if (command.getRoot() == "config") {
+ handleConfig();
+ }
+
+ else if (command.getRoot() == "send") {
+ handleSend(command);
+ }
+
+ else if (command.getRoot() == "receive") {
+ handleReceive();
+ }
+
+ else if (command.getRoot() == "devicebgone") {
+ handleDeviceBgone();
+ }
+
+ else if (command.getRoot() == "setprotocol") {
+ handleSetProtocol();
+ }
+
+ else {
+ handleHelp();
+ }
+}
+
+/*
+Send
+*/
+void InfraredController::handleSend(const TerminalCommand& command) {
+ std::istringstream iss(command.getArgs());
+ std::string subStr, cmdStr;
+ iss >> subStr >> cmdStr;
+ auto addrStr = command.getSubcommand();
+
+ if (addrStr.empty() || subStr.empty() || cmdStr.empty()) {
+ terminalView.println("Missing argument. Usage: send <device> <sub> <cmd>");
+ return;
+ }
+
+ int device, subdevice, function;
+ if (!argTransformer.parseInt(addrStr, device) ||
+ !argTransformer.parseInt(subStr, subdevice) ||
+ !argTransformer.parseInt(cmdStr, function)) {
+ terminalView.println("Invalid number format. Use decimal or hex.");
+ return;
+ }
+
+ InfraredCommand infraredCommand;
+ infraredCommand.setDevice(device);
+ infraredCommand.setSubdevice(subdevice);
+ infraredCommand.setFunction(function);
+ infraredCommand.setProtocol(state.getInfraredProtocol());
+
+ infraredService.sendInfraredCommand(infraredCommand);
+
+ terminalView.println("IR command sent with protocol " + InfraredProtocolMapper::toString(state.getInfraredProtocol()));
+}
+
+/*
+Receive
+*/
+void InfraredController::handleReceive() {
+ terminalView.println("Receiving infrared signal...");
+ terminalView.println("Press ENTER to cancel.\n");
+
+ while (true) {
+ // Check Enter press
+ char c = terminalInput.readChar();
+ if (c == '\r' || c == '\n') {
+ terminalView.println("INFRARED Receive: Cancelled by user.");
+ return;
+ }
+
+ // Try receive and decode signal
+ InfraredCommand cmd = infraredService.receiveInfraredCommand();
+ if (cmd.getProtocol() != RAW) {
+ terminalView.println("");
+ terminalView.println("Infrared signal received:");
+ terminalView.println(" Protocol : " + InfraredProtocolMapper::toString(cmd.getProtocol()));
+ terminalView.println(" Device : " + std::to_string(cmd.getDevice()));
+ terminalView.println(" SubDev : " + std::to_string(cmd.getSubdevice()));
+ terminalView.println(" Command : " + std::to_string(cmd.getFunction()));
+ terminalView.println("");
+ terminalView.println("INFRARED Receive: Waiting for next signal or press ENTER to exit.");
+ delay(200);
+ }
+ }
+}
+
+/*
+DeviceBgone
+*/
+void InfraredController::handleDeviceBgone() {
+ terminalView.println("Sending Device-B-Gone commands...");
+
+ for (const auto& cmd : deviceBgoneCommands) {
+ infraredService.sendInfraredCommand(cmd);
+ terminalView.println(
+ "Sent On/Off to protocol=" + InfraredProtocolMapper::toString(cmd.getProtocol()) +
+ " device=" + std::to_string(cmd.getDevice()) +
+ " sub=" + std::to_string(cmd.getSubdevice()) +
+ " cmd=" + std::to_string(cmd.getFunction())
+ );
+ delay(40); // small delay between signals
+ }
+
+ terminalView.println("Device-B-Gone sequence completed.");
+}
+
+/*
+Set protocol
+*/
+void InfraredController::handleSetProtocol() {
+ terminalView.println("");
+ terminalView.println("Select Infrared Protocol:");
+
+ std::vector<InfraredProtocolEnum> protocols;
+
+ for (int i = 0; i <= static_cast<int>(RAW); ++i) {
+ InfraredProtocolEnum proto = static_cast<InfraredProtocolEnum>(i);
+ std::string name = InfraredProtocolMapper::toString(proto);
+
+ // avoid double name
+ if (!name.empty() &&
+ std::find_if(protocols.begin(), protocols.end(),
+ [proto](InfraredProtocolEnum e) { return InfraredProtocolMapper::toString(e) == InfraredProtocolMapper::toString(proto); }) == protocols.end()) {
+ protocols.push_back(proto);
+ terminalView.println(" " + std::to_string(protocols.size()) + ". " + name);
+ }
+ }
+
+ terminalView.println("");
+ terminalView.print("Protocol Number > ");
+
+ std::string inputStr;
+ while (true) {
+ char c = terminalInput.handler();
+ if (c == '\r' || c == '\n') {
+ terminalView.println("");
+ break;
+ }
+
+ if (std::isdigit(c)) {
+ inputStr += c;
+ terminalView.print(std::string(1, c));
+ } else {
+ terminalView.println("\nInvalid input: only digits allowed.");
+ return;
+ }
+ }
+
+ if (inputStr.empty()) {
+ terminalView.println("No input given.");
+ return;
+ }
+
+ int index = std::stoi(inputStr);
+ if (index >= 1 && index <= static_cast<int>(protocols.size())) {
+ InfraredProtocolEnum selected = protocols[index - 1];
+ GlobalState::getInstance().setInfraredProtocol(selected);
+ terminalView.println("Protocol changed to " + InfraredProtocolMapper::toString(selected));
+ } else {
+ terminalView.println("Invalid protocol number.");
+ }
+}
+
+/*
+Config
+*/
+void InfraredController::handleConfig() {
+ terminalView.println("");
+ terminalView.println("Infrared Configuration:");
+
+ GlobalState& state = GlobalState::getInstance();
+ uint8_t txPin = state.getInfraredTxPin();
+ uint8_t rxPin = state.getInfraredRxPin();
+
+ // TX
+ while (true) {
+ terminalView.print("Infrared TX pin [" + std::to_string(txPin) + "]: ");
+ std::string txStr = getUserInput();
+
+ if (txStr.empty()) break;
+ if (argTransformer.isValidNumber(txStr)) {
+ txPin = argTransformer.toUint8(txStr);
+ break;
+ } else {
+ terminalView.println("Invalid pin value. Please enter a valid number.");
+ }
+ }
+
+ // RX
+ while (true) {
+ terminalView.print("Infrared RX pin [" + std::to_string(rxPin) + "]: ");
+ std::string rxStr = getUserInput();
+
+ if (rxStr.empty()) break;
+ if (argTransformer.isValidNumber(rxStr)) {
+ rxPin = argTransformer.toUint8(rxStr);
+ break;
+ } else {
+ terminalView.println("Invalid pin value. Please enter a valid number.");
+ }
+ }
+
+ state.setInfraredTxPin(txPin);
+ state.setInfraredRxPin(rxPin);
+ infraredService.configure(txPin, rxPin);
+
+ terminalView.println("Infrared configured.");
+ terminalView.println("");
+}
+
+/*
+Help
+*/
+void InfraredController::handleHelp() {
+ terminalView.println("Unknown INFRARED command. Usage:");
+ terminalView.println(" send <addr> <subadd> <cmd>");
+ terminalView.println(" receive");
+ terminalView.println(" setprotocol");
+ terminalView.println(" devicebgone");
+ terminalView.println(" config");
+}
+
+std::string InfraredController::getUserInput() {
+ std::string result;
+ while (true) {
+ char c = terminalInput.handler();
+ if (c == '\r' || c == '\n') break;
+ result += c;
+ terminalView.print(std::string(1, c));
+ }
+ terminalView.println("");
+ return result;
+}
+
+void InfraredController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
\ No newline at end of file
diff --git a/src/Controllers/InfraredController.h b/src/Controllers/InfraredController.h
new file mode 100644
index 00000000..61438349
--- /dev/null
+++ b/src/Controllers/InfraredController.h
@@ -0,0 +1,55 @@
+// InfraredController.h
+#pragma once
+
+#include <sstream>
+#include <string>
+#include <algorithm>
+#include <Arduino.h>
+
+#include "Views/ITerminalView.h"
+#include "Inputs/IInput.h"
+#include "Services/InfraredService.h"
+#include "Models/TerminalCommand.h"
+#include "Transformers/ArgTransformer.h"
+#include "States/GlobalState.h"
+
+class InfraredController {
+public:
+ // Constructor
+ InfraredController(ITerminalView& view, IInput& terminalInput, InfraredService& service, ArgTransformer& ArgTransformer);
+
+ // Entry point for Infraredcommand dispatch
+ void handleCommand(const TerminalCommand& command);
+
+ // Ensure infrared is properly configured
+ void ensureConfigured();
+
+private:
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ InfraredService& infraredService;
+ GlobalState& state = GlobalState::getInstance();
+ ArgTransformer& argTransformer;
+ bool configured = false;
+
+ // Configure IR settings
+ void handleConfig();
+
+ // Send IR command
+ void handleSend(const TerminalCommand& command);
+
+ // Receive IR commands
+ void handleReceive();
+
+ // Send "device-b-gone" style power-off signals
+ void handleDeviceBgone();
+
+ // Set IR protocol
+ void handleSetProtocol();
+
+ // Show help text
+ void handleHelp();
+
+ // Read a line of user input
+ std::string getUserInput();
+};
diff --git a/src/Controllers/JtagController.cpp b/src/Controllers/JtagController.cpp
new file mode 100644
index 00000000..dd49d068
--- /dev/null
+++ b/src/Controllers/JtagController.cpp
@@ -0,0 +1,41 @@
+#include "JtagController.h"
+
+/*
+Constructor
+*/
+JtagController::JtagController(ITerminalView& terminalView, IInput& terminalInput)
+ : terminalView(terminalView), terminalInput(terminalInput) {}
+
+void JtagController::handleCommand(const TerminalCommand& cmd) {
+ if (cmd.getRoot() == "scan") {
+ handleScan();
+ }
+
+ else {
+ terminalView.println("");
+ terminalView.println("Unknown JTAG command. Usage:");
+ terminalView.println(" scan");
+ terminalView.println("");
+ }
+}
+
+/*
+Scan
+*/
+void JtagController::handleScan() {
+ terminalView.println("BlueTag JTAG pinout scan [NYI]");
+}
+
+/*
+Config
+*/
+void JtagController::handleConfig() {
+ terminalView.println("JTAG Configuration[NYI]");
+}
+
+void JtagController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
\ No newline at end of file
diff --git a/src/Controllers/JtagController.h b/src/Controllers/JtagController.h
new file mode 100644
index 00000000..4dceb436
--- /dev/null
+++ b/src/Controllers/JtagController.h
@@ -0,0 +1,30 @@
+#pragma once
+
+// Placeholder implementation for JTAG controller
+
+#include "Views/ITerminalView.h"
+#include "Inputs/IInput.h"
+#include "Models/TerminalCommand.h"
+
+class JtagController {
+public:
+ // Constructor
+ JtagController(ITerminalView& terminalView, IInput& terminalInput);
+
+ // Entry point for dispatch incoming JTAG command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Ensure configuration is done before running commands
+ void ensureConfigured();
+
+private:
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ bool configured;
+
+ // Perform a JTAG device scan (to be implemented)
+ void handleScan();
+
+ // Run JTAG configuration routine (stub)
+ void handleConfig();
+};
diff --git a/src/Controllers/LedController.cpp b/src/Controllers/LedController.cpp
new file mode 100644
index 00000000..96590993
--- /dev/null
+++ b/src/Controllers/LedController.cpp
@@ -0,0 +1,44 @@
+#include "LedController.h"
+
+/*
+Constructor
+*/
+LedController::LedController(ITerminalView& terminalView, IInput& terminalInput, LedService& ledService)
+ : terminalView(terminalView), terminalInput(terminalInput), ledService(ledService) {}
+
+/*
+Entry point for command
+*/
+void LedController::handleCommand(const TerminalCommand& cmd) {
+ if (cmd.getRoot() == "PlaceHolder") {
+ // Nothing
+ }
+
+ else {
+ terminalView.println("");
+ terminalView.println("Unknown LED command. Usage:");
+ terminalView.println(" ???");
+ terminalView.println("");
+ }
+}
+
+/*
+Entry point for instruction
+*/
+void LedController::handleInstruction(const std::vector<ByteCode>& bytecodes) {
+ terminalView.println("Instruction handling not yet implemented");
+}
+
+/*
+Config
+*/
+void LedController::handleConfig() {
+ terminalView.println("LED Configuration [NYI]");
+}
+
+void LedController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
diff --git a/src/Controllers/LedController.h b/src/Controllers/LedController.h
new file mode 100644
index 00000000..a2ef384a
--- /dev/null
+++ b/src/Controllers/LedController.h
@@ -0,0 +1,35 @@
+#pragma once
+
+#include <vector>
+#include "Views/ITerminalView.h"
+#include "Inputs/IInput.h"
+#include "Models/TerminalCommand.h"
+#include "Models/ByteCode.h"
+#include "Services/LedService.h"
+
+// Placeholder implementation for LED controller
+// Future versions may support RGB patterns, animations, or PWM control
+
+class LedController {
+public:
+ // Constructor
+ LedController(ITerminalView& terminalView, IInput& terminalInput, LedService& ledService);
+
+ // Entry point for dispatch incoming LED command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Entry point for handle bytecode-style instructions (parsed instructions)
+ void handleInstruction(const std::vector<ByteCode>& bytecodes);
+
+ // Ensure LED is properly configured before executing commands
+ void ensureConfigured();
+
+private:
+ // Run LED configuration routine (e.g. default pin setup)
+ void handleConfig();
+
+ ITerminalView& terminalView; // Output view for terminal
+ IInput& terminalInput; // Input handler
+ LedService& ledService; // Service for low-level LED operations
+ bool configured = false; // Whether the controller is configured
+};
diff --git a/src/Controllers/OneWireController.cpp b/src/Controllers/OneWireController.cpp
new file mode 100644
index 00000000..5bf6cec7
--- /dev/null
+++ b/src/Controllers/OneWireController.cpp
@@ -0,0 +1,330 @@
+// OneWireController.cpp
+#include "OneWireController.h"
+
+/*
+Constructor
+*/
+OneWireController::OneWireController(ITerminalView& terminalView, IInput& terminalInput, OneWireService& service, ArgTransformer& argTransformer)
+ : terminalView(terminalView), terminalInput(terminalInput), oneWireService(service), argTransformer(argTransformer) {
+}
+
+/*
+Entry point for command
+*/
+void OneWireController::handleCommand(const TerminalCommand& command) {
+ if (command.getRoot() == "scan") {
+ handleScan();
+ }
+
+ else if (command.getRoot() == "ping") {
+ handlePing();
+ }
+
+ else if (command.getRoot() == "sniff") {
+ handleSniff();
+ }
+
+ else if (command.getRoot() == "read") {
+ handleRead();
+ }
+
+ else if (command.getRoot() == "write") {
+ handleWrite(command);
+ }
+
+ else if (command.getRoot() == "config") {
+ handleConfig();
+ }
+
+ else {
+ handleHelp();
+ }
+}
+
+/*
+Entry point for instructions
+*/
+void OneWireController::handleInstruction(std::vector<ByteCode>& bytecodes) {
+ auto result = oneWireService.executeByteCode(bytecodes);
+ if (!result.empty()) {
+ terminalView.println("OneWire Read:\n");
+ terminalView.println(result);
+ }
+}
+
+/*
+Scan
+*/
+void OneWireController::handleScan() {
+ terminalView.println("OneWire Scan: in progress...");
+
+ oneWireService.resetSearch();
+
+ uint8_t rom[8];
+ int deviceCount = 0;
+
+ while (oneWireService.search(rom)) {
+ std::ostringstream oss;
+ oss << "Device " << (++deviceCount) << ": ";
+ for (int i = 0; i < 8; ++i) {
+ oss << std::hex << std::uppercase << std::setfill('0') << std::setw(2)
+ << static_cast<int>(rom[i]) << " ";
+ }
+
+ uint8_t crc = oneWireService.crc8(rom, 7);
+ if (crc != rom[7]) {
+ oss << "(CRC error)";
+ }
+
+ terminalView.println(oss.str());
+ }
+
+ if (deviceCount == 0) {
+ terminalView.println("OneWire Scan: No devices found.");
+ }
+}
+
+/*
+Ping
+*/
+void OneWireController::handlePing() {
+ bool devicePresent = oneWireService.reset();
+ if (devicePresent) {
+ terminalView.println("OneWire Ping: Device present.");
+ } else {
+ terminalView.println("OneWire Ping: No device found.");
+ }
+}
+
+/*
+Read
+*/
+void OneWireController::handleRead() {
+ handleIdRead();
+ handleScratchpadRead();
+}
+
+/*
+ID Read
+*/
+void OneWireController::handleIdRead() {
+ uint8_t buffer[8];
+
+ terminalView.println("OneWire Read: in progress.");
+ if (!oneWireService.reset()) {
+ terminalView.println("OneWire Read: No device found.");
+ return;
+ }
+
+ oneWireService.write(0x33); // Read ROM
+ oneWireService.readBytes(buffer, 8);
+
+ std::ostringstream oss;
+ oss << std::uppercase << std::hex << std::setfill('0');
+ for (int i = 0; i < 8; ++i) {
+ oss << std::setw(2) << static_cast<int>(buffer[i]);
+ if (i < 7) oss << " ";
+ }
+
+ terminalView.println("ROM ID: " + oss.str());
+
+ uint8_t crc = oneWireService.crc8(buffer, 7);
+ if (crc != buffer[7]) {
+ terminalView.println("OneWire Read:: CRC error on ROM ID.");
+ }
+}
+
+/*
+Scratchpad Read
+*/
+void OneWireController::handleScratchpadRead() {
+ uint8_t scratchpad[8];
+ if (!oneWireService.reset()) {
+ terminalView.println("OneWire Read: No device found.");
+ return;
+ }
+
+ oneWireService.write(0xAA); // Read Scratchpad
+ oneWireService.readBytes(scratchpad, 8);
+
+ std::ostringstream oss;
+ oss << "Scratchpad: ";
+ for (int i = 0; i < 8; ++i) {
+ oss << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << (int)scratchpad[i];
+ if (i < 8) oss << " ";
+ }
+ terminalView.println(oss.str());
+
+ // CRC (last byte)
+ uint8_t crc = oneWireService.crc8(scratchpad, 8);
+ if (crc != scratchpad[8]) {
+ terminalView.println("CRC error on scratchpad.");
+ }
+}
+
+/*
+Write
+*/
+void OneWireController::handleWrite(const TerminalCommand& cmd) {
+ std::string sub = cmd.getSubcommand();
+
+ if (sub == "id") {
+ std::vector<uint8_t> idBytes = argTransformer.parseByteList(cmd.getArgs());
+
+ if (idBytes.size() != 8) {
+ terminalView.println("OneWire Write: ID must be exactly 8 bytes.");
+ return;
+ }
+
+ handleIdWrite(idBytes);
+ }
+
+ else if (sub == "sp") {
+ std::vector<uint8_t> spBytes = argTransformer.parseByteList(cmd.getArgs());
+
+ if (spBytes.size() != 8) {
+ terminalView.println("OneWire Write: Scratchpad must be exactly 8 bytes.");
+ return;
+ }
+
+ handleScratchpadWrite(spBytes);
+ }
+
+ else {
+ terminalView.println("OneWire Write: Invalid syntax. Use:");
+ terminalView.println(" write id <8 bytes>");
+ terminalView.println(" write sp <8 bytes>");
+ }
+}
+
+/*
+ID Write
+*/
+void OneWireController::handleIdWrite(std::vector<uint8_t> idBytes) {
+ if (!oneWireService.reset()) {
+ terminalView.println("OneWire Write: No device found.");
+ return;
+ }
+
+ oneWireService.writeRw1990(state.getOneWirePin(), idBytes.data(), idBytes.size());
+ terminalView.println("OneWire Write: ID write completed.");
+}
+
+/*
+Scratchpad Write
+*/
+void OneWireController::handleScratchpadWrite(std::vector<uint8_t> scratchpadBytes) {
+ if (!oneWireService.reset()) {
+ terminalView.println("OneWire Write: No device found.");
+ return;
+ }
+
+ oneWireService.skip();
+ oneWireService.write(0x0F); // Scratchpad write command
+ delayMicroseconds(20);
+ oneWireService.writeBytes(scratchpadBytes.data(), 8);
+ oneWireService.reset();
+
+ terminalView.println("OneWire Write: Scratchpad write completed.");
+}
+
+/*
+Config
+*/
+void OneWireController::handleConfig() {
+ terminalView.println("");
+ terminalView.println("OneWire Configuration:");
+
+ GlobalState& state = GlobalState::getInstance();
+ uint8_t pin = state.getOneWirePin();
+
+ while (true) {
+ terminalView.print("Data pin [" + std::to_string(pin) + "]: ");
+ std::string pinInput = getUserInput();
+ if (pinInput.empty()) break;
+
+ if (argTransformer.isValidNumber(pinInput)) {
+ pin = argTransformer.toUint8(pinInput);
+ break;
+ } else {
+ terminalView.println("Invalid value. Please enter a valid number.");
+ }
+ }
+
+ state.setOneWirePin(pin);
+ oneWireService.configure(pin);
+
+ terminalView.println("OneWire configured.");
+ terminalView.println("");
+}
+
+/*
+Sniff
+*/
+void OneWireController::handleSniff() {
+ terminalView.println("OneWire Sniff Mode: observing data line.");
+ terminalView.println("Press ENTER to stop.\n");
+
+ uint8_t pin = state.getOneWirePin();
+ pinMode(pin, INPUT);
+
+ uint8_t bitCount = 0;
+ uint8_t currentByte = 0;
+ int lastState = 0;
+ unsigned long lastTransition = micros();
+
+ while (true) {
+ char c = terminalInput.readChar();
+ if (c == '\r' || c == '\n') break;
+
+ int state = digitalRead(pin);
+ if (state != lastState) {
+ unsigned long now = micros();
+ unsigned long duration = now - lastTransition;
+ lastTransition = now;
+
+ std::stringstream ss;
+ ss << "Transition to " << state << " after " << duration << " us";
+ terminalView.println(ss.str());
+
+ lastState = state;
+ }
+ }
+ terminalView.println("");
+ terminalView.println("OneWire Sniff Mode: Exited");
+}
+
+/*
+Help
+*/
+void OneWireController::handleHelp() {
+ terminalView.println("Unknown 1Wire command. Usage:");
+ terminalView.println(" scan");
+ terminalView.println(" ping");
+ terminalView.println(" sniff");
+ terminalView.println(" read");
+ terminalView.println(" write id <8 bytes>");
+ terminalView.println(" write sp <8 bytes>");
+ terminalView.println(" config");
+ terminalView.println(" raw instructions, [0X33 r:8] ...");
+}
+
+
+std::string OneWireController::getUserInput() {
+ std::string result;
+ while (true) {
+ char c = terminalInput.handler();
+ if (c == '\r' || c == '\n') break;
+ result += c;
+ terminalView.print(std::string(1, c));
+ }
+ terminalView.println("");
+ return result;
+}
+
+void OneWireController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
\ No newline at end of file
diff --git a/src/Controllers/OneWireController.h b/src/Controllers/OneWireController.h
new file mode 100644
index 00000000..70a72d01
--- /dev/null
+++ b/src/Controllers/OneWireController.h
@@ -0,0 +1,69 @@
+#include <string>
+#include <sstream>
+#include <iomanip>
+
+#include "Services/OneWireService.h"
+#include "Inputs/IInput.h"
+#include "Views/ITerminalView.h"
+#include "Models/TerminalCommand.h"
+#include "States/GlobalState.h"
+#include "Transformers/ArgTransformer.h"
+
+class OneWireController {
+public:
+ // Constructor
+ OneWireController(ITerminalView& terminalView, IInput& terminalInput, OneWireService& service, ArgTransformer& argTransformer);
+
+ // Entry point for handle command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Entry point for handle parsed bytecode instructions
+ void handleInstruction(std::vector<ByteCode>& bytecodes);
+
+ // Ensure initialized/configured
+ void ensureConfigured();
+
+private:
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ OneWireService& oneWireService;
+ ArgTransformer& argTransformer;
+ bool configured = false;
+ GlobalState& state = GlobalState::getInstance();
+
+ // Configure 1-Wire bus parameters
+ void handleConfig();
+
+ // Send reset pulse and check device presence
+ void handlePing();
+
+ // Scan the bus for all devices
+ void handleScan();
+
+ // Listen to bus traffic passively
+ void handleSniff();
+
+ // Read a byte or data block from the bus
+ void handleRead();
+
+ // Print available 1-Wire commands
+ void handleHelp();
+
+ // Read and display a device's ROM ID
+ void handleIdRead();
+
+ // Read device scratchpad memory
+ void handleScratchpadRead();
+
+ // Write raw data to the bus
+ void handleWrite(const TerminalCommand& command);
+
+ // Write a ROM ID to a device (e.g. iButton emulator)
+ void handleIdWrite(std::vector<uint8_t> idBytes);
+
+ // Write to scratchpad memory
+ void handleScratchpadWrite(std::vector<uint8_t> scratchpadBytes);
+
+ // Get user input from the terminal
+ std::string getUserInput();
+};
diff --git a/src/Controllers/SpiController.cpp b/src/Controllers/SpiController.cpp
new file mode 100644
index 00000000..7f670cec
--- /dev/null
+++ b/src/Controllers/SpiController.cpp
@@ -0,0 +1,113 @@
+#include "SpiController.h"
+
+SpiController::SpiController(ITerminalView& terminalIiew, IInput& terminalInput, SpiService& service, ArgTransformer& argTransformer)
+ : terminalView(terminalView), terminalInput(terminalInput), spiService(service), argTransformer(argTransformer) {}
+
+/*
+Entry point for command
+*/
+void SpiController::handleCommand(const TerminalCommand& cmd) {
+
+ if (cmd.getRoot() == "sniff") {
+ handleSniff();
+ }
+
+ else if (cmd.getRoot() == "flash") {
+ if (cmd.getSubcommand() == "probe") {
+ handleFlashProbe();
+ } else if (cmd.getSubcommand() == "read") {
+ handleFlashRead();
+ } else if (cmd.getSubcommand() == "write") {
+ handleFlashWrite();
+ } else if (cmd.getSubcommand() == "erase") {
+ handleFlashErase();
+ } else {
+ terminalView.println("Unknown SPI flash command. Use: probe, read, write, erase");
+ }
+ }
+
+ else if (cmd.getRoot() == "config") {
+ handleConfig();
+ }
+
+ else {
+ terminalView.println("");
+ terminalView.println("Unknown SPI command. Usage:");
+ terminalView.println(" sniff");
+ terminalView.println(" flash probe");
+ terminalView.println(" flash read");
+ terminalView.println(" flash write");
+ terminalView.println(" flash erase");
+ terminalView.println(" config");
+ terminalView.println(" [..] - Instruction syntax supported [NYI]");
+ terminalView.println("");
+ }
+}
+
+/*
+Entry point for instructions
+*/
+void SpiController::handleInstruction(const std::vector<ByteCode>& bytecodes) {
+ terminalView.println("SPI Instruction [NYI]");
+}
+
+/*
+Sniff
+*/
+void SpiController::handleSniff() {
+ terminalView.println("SPI sniff [NYI]");
+}
+
+/*
+Flash Probe
+*/
+void SpiController::handleFlashProbe() {
+ terminalView.println("SPI flash probe [NYI]");
+}
+
+/*
+Flash Read
+*/
+void SpiController::handleFlashRead() {
+ terminalView.println("SPI flash read [NYI]");
+}
+
+/*
+Flash Write
+*/
+void SpiController::handleFlashWrite() {
+ terminalView.println("SPI flash write [NYI]");
+}
+
+/*
+Flash Erase
+*/
+void SpiController::handleFlashErase() {
+ terminalView.println("SPI flash erase [NYI]");
+}
+
+/*
+Config
+*/
+void SpiController::handleConfig() {
+ terminalView.println("SPI config [NYI]");
+}
+
+std::string SpiController::getUserInput() {
+ std::string result;
+ while (true) {
+ char c = terminalInput.handler();
+ if (c == '\r' || c == '\n') break;
+ result += c;
+ terminalView.print(std::string(1, c));
+ }
+ terminalView.println("");
+ return result;
+}
+
+void SpiController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
diff --git a/src/Controllers/SpiController.h b/src/Controllers/SpiController.h
new file mode 100644
index 00000000..9994d5f3
--- /dev/null
+++ b/src/Controllers/SpiController.h
@@ -0,0 +1,57 @@
+#pragma once
+
+// Placeholder implementation for SPI controller
+
+#include <vector>
+#include "Views/ITerminalView.h"
+#include "Services/SpiService.h"
+#include "Inputs/IInput.h"
+#include "Models/TerminalCommand.h"
+#include "Models/ByteCode.h"
+#include "Transformers/ArgTransformer.h"
+#include "States/GlobalState.h"
+
+class SpiController {
+public:
+ // Constructor
+ SpiController(ITerminalView& terminalView, IInput& terminalInput, SpiService& service, ArgTransformer& argTransformer);
+
+ // Entry point for handle raw user command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Entry point for handle parsed instruction bytecodes
+ void handleInstruction(const std::vector<ByteCode>& bytecodes);
+
+ // Ensure SPI is properly configured before use
+ void ensureConfigured();
+
+private:
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ SpiService& spiService;
+ ArgTransformer& argTransformer;
+ GlobalState& state = GlobalState::getInstance();
+
+ bool configured = false;
+
+ // Passive bus monitor
+ void handleSniff();
+
+ // Probe flash chip and identify it
+ void handleFlashProbe();
+
+ // Read data from flash memory
+ void handleFlashRead();
+
+ // Write data to flash memory
+ void handleFlashWrite();
+
+ // Erase flash memory
+ void handleFlashErase();
+
+ // Configure SPI bus parameters
+ void handleConfig();
+
+ // Read input from user
+ std::string getUserInput();
+};
diff --git a/src/Controllers/ThreeWireController.cpp b/src/Controllers/ThreeWireController.cpp
new file mode 100644
index 00000000..b8a4d360
--- /dev/null
+++ b/src/Controllers/ThreeWireController.cpp
@@ -0,0 +1,42 @@
+#include "ThreeWireController.h"
+
+/*
+Constructor
+*/
+ThreeWireController::ThreeWireController(ITerminalView& terminalView, IInput& terminalInput)
+ : terminalView(terminalView), terminalInput(terminalInput) {}
+
+/*
+Entry point for command
+*/
+void ThreeWireController::handleCommand(const TerminalCommand& cmd) {
+ if (cmd.getRoot() == "config") {
+ handleConfig();
+ } else {
+ terminalView.println("");
+ terminalView.println("Unknown 3WIRE command. Usage:");
+ terminalView.println(" [..] - [NYI]");
+ terminalView.println("");
+ }
+}
+
+/*
+Entry point for instructions
+*/
+void ThreeWireController::handleInstruction(const std::vector<ByteCode>& bytecodes) {
+ terminalView.println("Instruction handling not yet implemented");
+}
+
+/*
+Config
+*/
+void ThreeWireController::handleConfig() {
+ terminalView.println("3WIRE config [NYI]");
+}
+
+void ThreeWireController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
\ No newline at end of file
diff --git a/src/Controllers/ThreeWireController.h b/src/Controllers/ThreeWireController.h
new file mode 100644
index 00000000..903a9177
--- /dev/null
+++ b/src/Controllers/ThreeWireController.h
@@ -0,0 +1,34 @@
+#pragma once
+
+// Placeholder implementation for 3WIRE controller
+// Functionality to be added in future versions
+
+#include <vector>
+#include "Views/ITerminalView.h"
+#include "Services/SpiService.h"
+#include "Inputs/IInput.h"
+#include "Models/TerminalCommand.h"
+#include "Models/ByteCode.h"
+
+class ThreeWireController {
+public:
+ // Constructor
+ ThreeWireController(ITerminalView& terminalIiew, IInput& terminalInput);
+
+ // Entry point for handle raw user command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Handle compiled bytecode instructions
+ void handleInstruction(const std::vector<ByteCode>& bytecodes);
+
+ // Ensure 3WIRE is configured before use
+ void ensureConfigured();
+
+private:
+ ITerminalView& terminalView; // Terminal output
+ IInput& terminalInput; // User input
+ bool configured = false; // Init state
+
+ // Set up 3WIRE parameters
+ void handleConfig();
+};
diff --git a/src/Controllers/TwoWireController.cpp b/src/Controllers/TwoWireController.cpp
new file mode 100644
index 00000000..ee815d49
--- /dev/null
+++ b/src/Controllers/TwoWireController.cpp
@@ -0,0 +1,58 @@
+#include "TwoWireController.h"
+
+/*
+Constructor
+*/
+TwoWireController::TwoWireController(ITerminalView& terminalView, IInput& terminalInput)
+ : terminalView(terminalView), terminalInput(terminalInput) {}
+
+
+/*
+Entry point for command
+*/
+void TwoWireController::handleCommand(const TerminalCommand& cmd) {
+ if (cmd.getRoot() == "sniff") {
+ handleSniff();
+ } else if (cmd.getRoot() == "config") {
+ handleConfig();
+ } else {
+ terminalView.println("");
+ terminalView.println("Unknown 2WIRE command. Usage:");
+ terminalView.println(" sniff - Sniff 8-bit data with start/stop bits [NYI]");
+ terminalView.println(" config - Configure 2WIRE settings [NYI]");
+ terminalView.println(" [..] - Instruction syntax supported [NYI]");
+ terminalView.println("");
+ }
+}
+
+
+/*
+Entry point for instruction
+*/
+void TwoWireController::handleInstruction(const std::vector<ByteCode>& bytecodes) {
+ terminalView.println("Instruction handling not yet implemented");
+}
+
+
+/*
+Sniff
+*/
+void TwoWireController::handleSniff() {
+ terminalView.println("2WIRE sniff [NYI]");
+}
+
+
+/*
+Config
+*/
+void TwoWireController::handleConfig() {
+ terminalView.println("2WIRE Configuration [NYI]");
+}
+
+
+void TwoWireController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
\ No newline at end of file
diff --git a/src/Controllers/TwoWireController.h b/src/Controllers/TwoWireController.h
new file mode 100644
index 00000000..3cb8d029
--- /dev/null
+++ b/src/Controllers/TwoWireController.h
@@ -0,0 +1,36 @@
+#pragma once
+
+// Placeholder implementation for 2WIRE controller
+
+#include <vector>
+#include "Views/ITerminalView.h"
+#include "Services/SpiService.h"
+#include "Inputs/IInput.h"
+#include "Models/TerminalCommand.h"
+#include "Models/ByteCode.h"
+
+class TwoWireController {
+public:
+ // Constructor
+ TwoWireController(ITerminalView& terminalView, IInput& terminalInput);
+
+ // Entry point for handle raw user command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Entry point for handle compiled bytecode instructions
+ void handleInstruction(const std::vector<ByteCode>& bytecodes);
+
+ // Ensure 2WIRE is configured before use
+ void ensureConfigured();
+
+private:
+ ITerminalView& terminalView; // Terminal output
+ IInput& terminalInput; // User input
+ bool configured = false; // Init state
+
+ // Start sniffing 2WIRE bus
+ void handleSniff();
+
+ // Set up 2WIRE parameters
+ void handleConfig();
+};
diff --git a/src/Controllers/UartController.cpp b/src/Controllers/UartController.cpp
new file mode 100644
index 00000000..4525a59f
--- /dev/null
+++ b/src/Controllers/UartController.cpp
@@ -0,0 +1,399 @@
+#include "UartController.h"
+
+/*
+Constructor
+*/
+UartController::UartController(ITerminalView& terminalView, IInput& terminalInput, IInput& deviceInput, UartService& uartService, ArgTransformer& argTransformer)
+ : terminalView(terminalView), terminalInput(terminalInput), deviceInput(deviceInput), uartService(uartService), argTransformer(argTransformer) {}
+
+
+/*
+Entry point for command
+*/
+void UartController::handleCommand(const TerminalCommand& cmd) {
+ if (cmd.getRoot() == "scan") {
+ handleScan();
+ }
+
+ else if (cmd.getRoot() == "ping") {
+ handlePing();
+ }
+
+ else if (cmd.getRoot() == "read") {
+ handleRead();
+ }
+
+ else if (cmd.getRoot() == "write") {
+ handleWrite(cmd);
+ }
+
+ else if (cmd.getRoot() == "bridge") {
+ handleBridge();
+ }
+
+ else if (cmd.getRoot() == "glitch") {
+ handleGlitch();
+ }
+
+ else if (cmd.getRoot() == "config") {
+ handleConfig();
+ }
+
+ else {
+ handleHelp();
+ }
+}
+
+/*
+Entry point for instructions
+*/
+void UartController::handleInstruction(const std::vector<ByteCode>& bytecodes) {
+ auto result = uartService.executeByteCode(bytecodes);
+ terminalView.println("");
+ terminalView.print("UART Read: ");
+ if (!result.empty()) {
+ terminalView.println("");
+ terminalView.println("");
+ terminalView.println(result);
+ uartService.clearUartBuffer();
+ } else {
+ terminalView.print("No data");
+ }
+ terminalView.println("");
+}
+
+/*
+Bridge
+*/
+void UartController::handleBridge() {
+ terminalView.println("Uart Bridge: in progress... Press Cardputer key to stop");
+ while (true) {
+ // Read from UART and print to terminal
+ if (uartService.available()) {
+ char c = uartService.read();
+ if (c == '\n') {
+ terminalView.println(""); // saut de ligne
+ } else {
+ terminalView.print(std::string(1, c));
+ }
+ }
+
+ // Read from user input and write to UART
+ char c = terminalInput.readChar();
+ if (c != KEY_NONE) {
+ uartService.write(c);
+ }
+
+ // Read from device input and stop bridge if any
+ c = deviceInput.readChar();
+ if (c != KEY_NONE) {
+ terminalView.println("Uart Bridge: Stopped by user.");
+ break;
+ }
+ }
+}
+
+/*
+Read
+*/
+void UartController::handleRead() {
+ terminalView.println("UART Read: Streaming until ENTER is pressed...");
+ uartService.flush();
+
+ while (true) {
+ // Stop if ENTER is pressed
+ char key = terminalInput.readChar();
+ if (key == '\r' || key == '\n') {
+ terminalView.println("");
+ terminalView.println("UART Read: Stopped by user.");
+ break;
+ }
+
+ // Print UART data as it comes
+ while (uartService.available() > 0) {
+ char c = uartService.read();
+ terminalView.print(std::string(1, c));
+ }
+ }
+}
+
+/*
+Write
+*/
+void UartController::handleWrite(TerminalCommand cmd) {
+ uartService.print(cmd.getSubcommand() + cmd.getArgs());
+ terminalView.println("UART Write: Text sent at baud " + std::to_string(state.getUartBaudRate()));
+}
+
+/*
+Ping
+*/
+void UartController::handlePing() {
+ std::string response;
+ unsigned long start = millis();
+ size_t probeIndex = 0;
+
+ terminalView.println("UART Ping: probing for 5 seconds...");
+ uartService.clearUartBuffer();
+
+ while (millis() - start < 5000) {
+ // Envoi progressif
+ if (probeIndex < probes.size()) {
+ uartService.write(probes[probeIndex]);
+ probeIndex++;
+ }
+
+ // Lecture continue
+ char c;
+ while (uartService.available() > 0) {
+ c = uartService.read();
+ response += c;
+ }
+
+ delay(10);
+ }
+
+ // Analyse ASCII simple
+ size_t asciiCount = 0;
+ std::string result = "";
+ for (char c : response)
+ if (isprint(static_cast<unsigned char>(c)) || isspace(c)) {
+ asciiCount++;
+ result += c;
+ }
+
+ if (asciiCount < 5) {
+ terminalView.println("UART Ping: No response.");
+ return;
+ }
+
+ terminalView.println("UART Response: ");
+ terminalView.println("");
+ terminalView.println(result);
+ terminalView.println("");
+
+ terminalView.println("UART Ping: Device detected");
+}
+
+/*
+Scan
+*/
+void UartController::handleScan() {
+ std::vector<int> baudrates = {9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600};
+
+ terminalView.println("UART Scan: in progress... (press ENTER to cancel)");
+ uartService.clearUartBuffer();
+
+ for (int baud : baudrates) {
+ uartService.switchBaudrate(baud);
+ terminalView.println("→ Testing baudrate " + std::to_string(baud));
+
+ std::string response;
+ size_t asciiCount = 0;
+ size_t probeIndex = 0;
+ unsigned long start = millis();
+ unsigned long lastSend = 0;
+
+ uartService.flush();
+ while (millis() - start < 1000) {
+ // Cancel if user presses Enter
+ char key = terminalInput.readChar();
+ if (key == '\r' || key == '\n') {
+ terminalView.println("UART Scan: Cancelled by user.");
+ return;
+ }
+
+ // Send probes to get uart data
+ if (probeIndex < probes.size()) {
+ uartService.write(probes[probeIndex]);
+ probeIndex++;
+ lastSend = millis();
+ }
+
+ // Read incoming UART data
+ while (uartService.available() > 0) {
+ char c = uartService.read();
+ response += c;
+
+ if (isprint(c) || isspace(c))
+ asciiCount++;
+ }
+
+ float asciiRatio = response.empty() ? 0.0f : (float)asciiCount / response.size();
+
+ // Accept short but readable responses (e.g., "AT+OK\r\n")
+ bool validShort = response.length() >= 10 && asciiRatio >= 0.95f;
+
+ // Accept long and mostly printable responses
+ bool validLong = response.length() > 60 && asciiCount > 20 && asciiRatio >= 0.9f;
+
+ // Baudrate detected
+ if (validShort || validLong) {
+ terminalView.println("");
+ terminalView.println("Preview:");
+ terminalView.println(response.substr(0, 100) + "...");
+ uartService.switchBaudrate(baud);
+ state.setUartBaudRate(baud);
+ terminalView.println("");
+ terminalView.println("UART Scan: Setting baudrate to UART config.");
+ terminalView.println("UART Scan: Baudrate detected " + std::to_string(baud));
+ return;
+ }
+
+ delay(10);
+ }
+ }
+
+ terminalView.println("Uart Scan: No device detected.");
+}
+
+/*
+Config
+*/
+void UartController::handleConfig() {
+ terminalView.println("");
+ terminalView.println("UART Configuration:");
+
+ GlobalState& state = GlobalState::getInstance();
+
+ uint8_t rxPin = readValidatedUint8("RX pin number", state.getUartRxPin());
+ state.setUartRxPin(rxPin);
+
+ uint8_t txPin = readValidatedUint8("TX pin number", state.getUartTxPin());
+ state.setUartTxPin(txPin);
+
+ uint32_t baud = readValidatedUint32("Baud rate", state.getUartBaudRate());
+ state.setUartBaudRate(baud);
+
+ uint8_t dataBits = readValidatedUint8("Data bits (5-8)", state.getUartDataBits(), 5, 8);
+ state.setUartDataBits(dataBits);
+
+ char defaultParity = state.getUartParity().empty() ? 'N' : state.getUartParity()[0];
+ char parityChar = readCharChoice("Parity (N/E/O)", defaultParity, {'N', 'E', 'O'});
+ state.setUartParity(std::string(1, parityChar));
+
+ uint8_t stopBits = readValidatedUint8("Stop bits (1 or 2)", state.getUartStopBits(), 1, 2);
+ state.setUartStopBits(stopBits);
+
+ bool inverted = readYesNo("Inverted?", state.isUartInverted());
+ state.setUartInverted(inverted);
+
+ uint32_t config = buildUartConfig(dataBits, parityChar, stopBits);
+ state.setUartConfig(config);
+
+ uartService.configure(baud, config, rxPin, txPin, inverted);
+
+ terminalView.println("UART configuration applied.");
+ terminalView.println("");
+}
+
+/*
+Help
+*/
+void UartController::handleHelp() {
+ terminalView.println("");
+ terminalView.println("Unknown UART command. Usage:");
+ terminalView.println(" scan");
+ terminalView.println(" ping");
+ terminalView.println(" read");
+ terminalView.println(" write <text>");
+ terminalView.println(" bridge");
+ terminalView.println(" glitch");
+ terminalView.println(" config");
+ terminalView.println(" raw instructions, ['AT' D:100 r:128]");
+ terminalView.println("");
+}
+
+/*
+Glitch
+*/
+void UartController::handleGlitch() {
+ terminalView.println("Uart Glicher: Not Yet Implemented");
+}
+
+std::string UartController::getUserInput() {
+ std::string result;
+ while (true) {
+ char c = terminalInput.handler();
+ if (c == '\r' || c == '\n') break;
+ result += c;
+ terminalView.print(std::string(1, c));
+ }
+ terminalView.println("");
+ return result;
+}
+
+void UartController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
+
+/*
+Utils
+*/
+uint8_t UartController::readValidatedUint8(const std::string& label, uint8_t defaultVal, uint8_t min, uint8_t max) {
+ while (true) {
+ terminalView.print(label + " [" + std::to_string(defaultVal) + "]: ");
+ std::string input = getUserInput();
+ if (input.empty()) return defaultVal;
+ if (argTransformer.isValidNumber(input)) {
+ uint8_t value = argTransformer.toUint8(input);
+ if (value >= min && value <= max) return value;
+ }
+ terminalView.println("Invalid value. Must be between " + std::to_string(min) + " and " + std::to_string(max));
+ }
+}
+
+uint8_t UartController::readValidatedUint8(const std::string& label, uint8_t defaultVal) {
+ return readValidatedUint8(label, defaultVal, 0, 255);
+}
+
+uint32_t UartController::readValidatedUint32(const std::string& label, uint32_t defaultVal) {
+ while (true) {
+ terminalView.print(label + " [" + std::to_string(defaultVal) + "]: ");
+ std::string input = getUserInput();
+ if (input.empty()) return defaultVal;
+ if (argTransformer.isValidNumber(input)) {
+ return argTransformer.toUint32(input);
+ }
+ terminalView.println("Invalid number.");
+ }
+}
+
+char UartController::readCharChoice(const std::string& label, char defaultVal, const std::vector<char>& allowed) {
+ while (true) {
+ terminalView.print(label + " [" + std::string(1, defaultVal) + "]: ");
+ std::string input = getUserInput();
+ if (input.empty()) return defaultVal;
+ char c = std::toupper(input[0]);
+ if (std::find(allowed.begin(), allowed.end(), c) != allowed.end()) return c;
+ terminalView.println("Invalid choice.");
+ }
+}
+
+bool UartController::readYesNo(const std::string& label, bool defaultVal) {
+ while (true) {
+ terminalView.print(label + " [" + std::string(defaultVal ? "y" : "n") + "]: ");
+ std::string input = getUserInput();
+ if (input.empty()) return defaultVal;
+ char c = std::tolower(input[0]);
+ if (c == 'y') return true;
+ if (c == 'n') return false;
+ terminalView.println("Please answer y or n.");
+ }
+}
+
+uint32_t UartController::buildUartConfig(uint8_t dataBits, char parity, uint8_t stopBits) {
+ uint32_t config = SERIAL_8N1;
+ if (dataBits == 5) config = (stopBits == 2) ? SERIAL_5N2 : SERIAL_5N1;
+ else if (dataBits == 6) config = (stopBits == 2) ? SERIAL_6N2 : SERIAL_6N1;
+ else if (dataBits == 7) config = (stopBits == 2) ? SERIAL_7N2 : SERIAL_7N1;
+ else if (dataBits == 8) config = (stopBits == 2) ? SERIAL_8N2 : SERIAL_8N1;
+
+ if (parity == 'E') config |= 0x02;
+ else if (parity == 'O') config |= 0x01;
+
+ return config;
+}
diff --git a/src/Controllers/UartController.h b/src/Controllers/UartController.h
new file mode 100644
index 00000000..a9df53f1
--- /dev/null
+++ b/src/Controllers/UartController.h
@@ -0,0 +1,104 @@
+#pragma once
+
+#include <vector>
+#include <string>
+#include "HardwareSerial.h"
+#include "Models/TerminalCommand.h"
+#include "Models/ByteCode.h"
+#include "Services/UartService.h"
+#include "Views/ITerminalView.h"
+#include "Inputs/IInput.h"
+#include "States/GlobalState.h"
+#include "Transformers/ArgTransformer.h"
+
+class UartController {
+public:
+ // Constructor
+ UartController(ITerminalView& terminalView,
+ IInput& terminalInput,
+ IInput& deviceInput,
+ UartService& uartService,
+ ArgTransformer& argTransformer);
+
+ // Entry pooint for UART command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Entry point for handle parsed bytecode instructions
+ void handleInstruction(const std::vector<ByteCode>& bytecodes);
+
+ // Ensure UART is configured before use
+ void ensureConfigured();
+
+ private:
+ // Start bidirectional UART bridge
+ void handleBridge();
+
+ // Perform a simple read
+ void handleRead();
+
+ // Probe known devices
+ void handleScan();
+
+ // Send simple ping command
+ void handlePing();
+
+ // Write data to UART
+ void handleWrite(TerminalCommand cmd);
+
+ // Configure UART settings
+ void handleConfig();
+
+ // Display available commands
+ void handleHelp();
+
+ // Send glitch pattern over uart
+ void handleGlitch();
+
+ // Read validated uint8 with default
+ uint8_t readValidatedUint8(const std::string& label, uint8_t defaultVal);
+
+ // Read validated uint8 within range
+ uint8_t readValidatedUint8(const std::string& label, uint8_t defaultVal, uint8_t min, uint8_t max);
+
+ // Read validated uint32 with default
+ uint32_t readValidatedUint32(const std::string& label, uint32_t defaultVal);
+
+ // Read single char among allowed values
+ char readCharChoice(const std::string& label, char defaultVal, const std::vector<char>& allowed);
+
+ // Read boolean yes/no input
+ bool readYesNo(const std::string& label, bool defaultVal);
+
+ // Encode UART config bits
+ uint32_t buildUartConfig(uint8_t dataBits, char parity, uint8_t stopBits);
+
+ // Get full user input string
+ std::string getUserInput();
+
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ IInput& deviceInput;
+ UartService& uartService;
+ ArgTransformer& argTransformer;
+ GlobalState& state = GlobalState::getInstance();
+ bool configured = false;
+
+ // Predefined probe commands for scan()
+ std::vector<std::string> probes = {
+ // Generic AT commands
+ "AT\r\n",
+ "ATE0\r\n", "ATE1\r\n", "ATI\r\n", "ATI0\r\n", "ATI1\r\n", "ATI2\r\n",
+ "AT+GMR\r\n", "AT+VERSION?\r\n", "AT+HELP\r\n",
+
+ // Modem/GSM specific
+ "AT+CSQ\r\n", "AT+CREG?\r\n", "AT+CGMI\r\n", "AT+CGMM\r\n",
+ "AT+CGMR\r\n", "AT+CGSN\r\n",
+
+ // GPS modules
+ "$PMTK?\r\n", "$GPTXT\r\n",
+
+ // Miscellaneous
+ "help\r\n", "?\r\n", "\r\n",
+ "\x1B", "\x03", "\x04", "\x1A", "\x11", "\x13" // ESC, Ctrl+C/Z/D, XON/XOFF
+ };
+};
diff --git a/src/Controllers/UsbController.cpp b/src/Controllers/UsbController.cpp
new file mode 100644
index 00000000..0e7a2966
--- /dev/null
+++ b/src/Controllers/UsbController.cpp
@@ -0,0 +1,194 @@
+#include "UsbController.h"
+
+/*
+Constructor
+*/
+UsbController::UsbController(ITerminalView& terminalView, IInput& terminalInput, UsbService& usbService, ArgTransformer& argTransformer)
+ : terminalView(terminalView), terminalInput(terminalInput), usbService(usbService), argTransformer(argTransformer) {}
+
+/*
+Entry point for command
+*/
+void UsbController::handleCommand(const TerminalCommand& cmd) {
+
+ if (cmd.getRoot() == "stick") {
+ handleUsbStick();
+ }
+
+ else if (cmd.getRoot() == "keyboard") {
+ handleKeyboardSend(cmd);
+ }
+
+ else if (cmd.getRoot() == "mouse") {
+ handleMouse(cmd);
+ }
+
+ else if (cmd.getRoot() == "gamepad") {
+ handleGamepad(cmd);
+ }
+
+ else if (cmd.getRoot() == "reset") {
+ handleReset();
+ }
+
+ else if (cmd.getRoot() == "config") {
+ handleConfig();
+ }
+
+ else {
+ handleHelp();
+ }
+}
+
+/*
+Keyboard Send
+*/
+void UsbController::handleKeyboardSend(const TerminalCommand& cmd) {
+ terminalView.println("USB Keyboard: Configuring...");
+ usbService.keyboardBegin();
+ terminalView.println("USB Keyboard: Initialize...");
+ usbService.keyboardSendString(cmd.getSubcommand());
+ // usbService.reset();
+ terminalView.println("USB Keyboard: String sent.");
+}
+
+/*
+Mouse Move
+*/
+void UsbController::handleMouseMove(const TerminalCommand& cmd) {
+ int x, y = 0;
+
+ if (cmd.getSubcommand() == "move") {
+ auto args = argTransformer.splitArgs(cmd.getArgs());
+ x = argTransformer.parseHexOrDec(args[0]);
+ y = argTransformer.parseHexOrDec(args[1]);;
+ } else {
+ x = argTransformer.parseHexOrDec(cmd.getSubcommand());
+ y = argTransformer.parseHexOrDec(cmd.getArgs());
+ }
+
+ usbService.mouseMove(x, y);
+ terminalView.println("USB Mouse: Moved by (" + std::to_string(x) + ", " + std::to_string(y) + ")");
+}
+
+/*
+Mouse Click
+*/
+void UsbController::handleMouseClick() {
+ // Left click
+ usbService.mouseClick(1);
+ delay(100);
+ usbService.mouseRelease(1);
+}
+
+/*
+Mouse
+*/
+void UsbController::handleMouse(const TerminalCommand& cmd) {
+ terminalView.println("USB Mouse: Configuring HID...");
+ usbService.mouseBegin();
+ terminalView.println("USB Mouse: Initialize HID...");
+
+ if (cmd.getSubcommand() == "click") {
+ handleMouseClick();
+ } else {
+ handleMouseMove(cmd);
+ }
+}
+
+/*
+Gamepad
+*/
+void UsbController::handleGamepad(const TerminalCommand& cmd) {
+ terminalView.println("USB Gamepad: Configuring HID...");
+ usbService.gamepadBegin();
+ terminalView.println("USB Gamepad: Initialize HID...");
+ usbService.gamepadPress(cmd.getSubcommand());
+ terminalView.println("USB Gamepad: Key sent.");
+}
+
+/*
+Stick
+*/
+void UsbController::handleUsbStick() {
+ usbService.storageBegin(state.getSdCardCSPin(), state.getSdCardCLKPin(),
+ state.getSdCardMISOPin(), state.getSdCardMOSIPin());
+}
+
+/*
+Config
+*/
+void UsbController::handleConfig() {
+ terminalView.println("");
+ terminalView.println("USB Configuration:");
+
+ terminalView.print("SD Card CS pin [" + std::to_string(state.getSdCardCSPin()) + "]: ");
+ std::string csInput = getUserInput();
+ uint8_t cs = csInput.empty() ? state.getSdCardCSPin() : static_cast<uint8_t>(std::stoi(csInput));
+ state.setSdCardCSPin(cs);
+
+ terminalView.print("SD Card CLK pin [" + std::to_string(state.getSdCardCLKPin()) + "]: ");
+ std::string clkInput = getUserInput();
+ uint8_t clk = clkInput.empty() ? state.getSdCardCLKPin() : static_cast<uint8_t>(std::stoi(clkInput));
+ state.setSdCardCLKPin(clk);
+
+ terminalView.print("SD Card MISO pin [" + std::to_string(state.getSdCardMISOPin()) + "]: ");
+ std::string misoInput = getUserInput();
+ uint8_t miso = misoInput.empty() ? state.getSdCardMISOPin() : static_cast<uint8_t>(std::stoi(misoInput));
+ state.setSdCardMISOPin(miso);
+
+ terminalView.print("SD Card MOSI pin [" + std::to_string(state.getSdCardMOSIPin()) + "]: ");
+ std::string mosiInput = getUserInput();
+ uint8_t mosi = mosiInput.empty() ? state.getSdCardMOSIPin() : static_cast<uint8_t>(std::stoi(mosiInput));
+ state.setSdCardMOSIPin(mosi);
+
+ terminalView.println("USB Configured.");
+
+ terminalView.println("\n[WARNING] If you're using USB Serial terminal mode,");
+ terminalView.println(" using USB commands may interrupt the session.");
+ terminalView.println(" Use Web UI or restart if connection is lost.\n");
+}
+
+/*
+Reset
+*/
+void UsbController::handleReset() {
+ usbService.reset();
+ terminalView.println("USB mode: Resetting");
+}
+
+/*
+Help
+*/
+void UsbController::handleHelp() {
+ terminalView.println("Unknown command.");
+ terminalView.println("Usage:");
+ terminalView.println(" stick");
+ terminalView.println(" keyboard <text>");
+ terminalView.println(" mouse <x> <y>");
+ terminalView.println(" mouse click");
+ terminalView.println(" gamepad <key>, eg. A, B, LEFT...");
+ terminalView.println(" reset");
+ terminalView.println(" config");
+}
+
+std::string UsbController::getUserInput() {
+ std::string inputStr;
+ while (true) {
+ char c = terminalInput.handler();
+ if (c == '\r' || c == '\n') {
+ terminalView.println("");
+ break;
+ }
+ inputStr += c;
+ terminalView.print(std::string(1, c));
+ }
+ return inputStr;
+}
+
+void UsbController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
diff --git a/src/Controllers/UsbController.h b/src/Controllers/UsbController.h
new file mode 100644
index 00000000..27ca1b17
--- /dev/null
+++ b/src/Controllers/UsbController.h
@@ -0,0 +1,60 @@
+#pragma once
+
+#include <sstream>
+#include "Views/ITerminalView.h"
+#include "Inputs/IInput.h"
+#include "Services/UsbService.h"
+#include "Models/TerminalCommand.h"
+#include "Models/ByteCode.h"
+#include "States/GlobalState.h"
+#include "Transformers/ArgTransformer.h"
+
+class UsbController {
+public:
+ // Constructor
+ UsbController(ITerminalView& terminalView, IInput& terminalInput, UsbService& usbService, ArgTransformer& argTransformer);
+
+ // Entry point for handle raw terminal command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Ensure USB is configured before any action
+ void ensureConfigured();
+
+private:
+ // Simulate USB mass storage mount
+ void handleUsbStick();
+
+ // Send keyboard input via HID
+ void handleKeyboardSend(const TerminalCommand& cmd);
+
+ // Move the HID mouse cursor
+ void handleMouseMove(const TerminalCommand& cmd);
+
+ // Perform HID mouse click
+ void handleMouseClick();
+
+ // High-level mouse handler
+ void handleMouse(const TerminalCommand& cmd);
+
+ // Emulate gamepad events
+ void handleGamepad(const TerminalCommand& cmd);
+
+ // Reset all USB states
+ void handleReset();
+
+ // Configure USB behavior
+ void handleConfig();
+
+ // Display help for USB commands
+ void handleHelp();
+
+ // Prompt user input via terminal
+ std::string getUserInput();
+
+ bool configured = false;
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ UsbService& usbService;
+ ArgTransformer& argTransformer;
+ GlobalState& state = GlobalState::getInstance();
+};
diff --git a/src/Controllers/UtilityController.cpp b/src/Controllers/UtilityController.cpp
new file mode 100644
index 00000000..9f11d7ed
--- /dev/null
+++ b/src/Controllers/UtilityController.cpp
@@ -0,0 +1,367 @@
+#include "Controllers/UtilityController.h"
+
+/*
+Constructor
+*/
+UtilityController::UtilityController(ITerminalView& terminalView, IInput& terminalInput, PinService& pinService)
+ : terminalView(terminalView), terminalInput(terminalInput), pinService(pinService) {}
+
+/*
+Entry point for command
+*/
+void UtilityController::handleCommand(const TerminalCommand& cmd) {
+ if (cmd.getRoot() == "help" || cmd.getRoot() == "h" || cmd.getRoot() == "?") {
+ handleHelp();
+ }
+
+ else if (cmd.getRoot() == "P") {
+ handleEnablePullups();
+ }
+
+ else if (cmd.getRoot() == "p") {
+ handleDisablePullups();
+ }
+
+ else {
+ terminalView.println("Unknown command. Try 'help'.");
+ }
+}
+
+/*
+Mode Change
+*/
+ModeEnum UtilityController::handleModeChangeCommand(const TerminalCommand& cmd) {
+ if (cmd.getRoot() != "mode" && cmd.getRoot() != "m") {
+ terminalView.println("Invalid command for mode change.");
+ return ModeEnum::None;
+ }
+
+ if (!cmd.getSubcommand().empty()) {
+ ModeEnum newMode = ModeEnumMapper::fromString(cmd.getSubcommand());
+ if (newMode != ModeEnum::None) {
+ terminalView.println("Mode changed to " + ModeEnumMapper::toString(newMode));
+ terminalView.println("");
+ return newMode;
+ } else {
+ terminalView.println("Unknown mode: " + cmd.getSubcommand());
+ return ModeEnum::None;
+ }
+ }
+
+ return handleModeSelect();
+}
+
+/*
+Mode Select
+*/
+ModeEnum UtilityController::handleModeSelect() {
+ terminalView.println("");
+ terminalView.println("Select mode:");
+ std::vector<ModeEnum> modes;
+
+ for (int i = 0; i <= static_cast<int>(ModeEnum::JTAG); ++i) {
+ ModeEnum mode = static_cast<ModeEnum>(i);
+ std::string name = ModeEnumMapper::toString(mode);
+ if (!name.empty()) {
+ modes.push_back(mode);
+ terminalView.println(" " + std::to_string(modes.size()) + ". " + name);
+ }
+ }
+
+ terminalView.println("");
+ terminalView.print("Mode Number > ");
+ auto modeNumber = getModeNumber();
+
+ if (modeNumber == -1) {
+ terminalView.println("");
+ terminalView.println("");
+ terminalView.println("Invalid input.");
+ return ModeEnum::None;
+ } else if (modeNumber >= 1 && modeNumber <= modes.size()) {
+ ModeEnum selected = modes[modeNumber - 1];
+ if (static_cast<int>(selected) > 9) {
+ terminalView.println(""); // Hack to render correctly on web terminal
+ }
+ terminalView.println("");
+ terminalView.println("Mode changed to " + ModeEnumMapper::toString(selected));
+ terminalView.println("");
+ return selected;
+ } else {
+ terminalView.println("");
+ terminalView.println("Invalid mode number.");
+ terminalView.println("");
+ return ModeEnum::None;
+ }
+}
+
+/*
+Input Mode Number
+*/
+uint8_t UtilityController::getModeNumber() {
+ std::string inputStr;
+ std::string inputDigit;
+
+ while (true) {
+ char c = terminalInput.handler();
+
+ if (c == '\r' || c == '\n') {
+ terminalView.println("");
+ break;
+ }
+
+ if (std::isdigit(c)) {
+ inputDigit += c;
+ }
+
+ inputStr += c;
+ }
+
+ if (inputStr.empty()) {
+ return -1;
+ }
+
+ // try mode name
+ ModeEnum mode = ModeEnumMapper::fromString(inputStr);
+ if (mode != ModeEnum::None) {
+ return static_cast<uint8_t>(mode) + 1;
+ }
+
+ if (inputDigit.empty()) {
+ return -1;
+ }
+
+ return std::stoi(inputDigit);
+}
+
+/*
+Pullup: p
+*/
+void UtilityController::handleDisablePullups() {
+ auto mode = state.getCurrentMode();
+ switch (mode) {
+ case ModeEnum::SPI:
+ pinService.setInput(state.getSdCardMISOPin());
+ terminalView.println("SPI: Pull-ups disabled on MISO");
+ break;
+
+ case ModeEnum::I2C:
+ pinService.setInput(state.getI2cSdaPin());
+ pinService.setInput(state.getI2cSclPin());
+ terminalView.println("I2C: Pull-ups disabled on SDA, SCL.");
+ break;
+
+ case ModeEnum::OneWire:
+ pinService.setInput(state.getOneWirePin());
+ terminalView.println("1-Wire: Pull-up disabled on DQ.");
+ break;
+
+ case ModeEnum::UART:
+ pinService.setInput(state.getUartRxPin());
+ terminalView.println("UART: Pull-ups disabled on RX.");
+ break;
+
+ case ModeEnum::HDUART:
+ pinService.setInput(state.getHdUartPin());
+ terminalView.println("HDUART: Pull-up disabled on IO pin.");
+ break;
+
+ default:
+ terminalView.println("Pull-ups not applicable for this mode.");
+ break;
+ }
+}
+
+/*
+Pullup P
+*/
+void UtilityController::handleEnablePullups() {
+ auto mode = state.getCurrentMode();
+ switch (mode) {
+ case ModeEnum::SPI:
+ pinService.setInput(state.getSdCardMISOPin());
+ pinService.setInputPullup(state.getSdCardMISOPin());
+ terminalView.println("SPI: Pull-up enabled on MISO.");
+ break;
+
+ case ModeEnum::I2C:
+ pinService.setInputPullup(state.getI2cSdaPin());
+ pinService.setInputPullup(state.getI2cSclPin());
+ terminalView.println("I2C: Pull-ups enabled on SDA, SCL.");
+ break;
+
+ case ModeEnum::OneWire:
+ pinService.setInputPullup(state.getOneWirePin());
+ terminalView.println("1-Wire: Pull-up enabled on DQ.");
+ break;
+
+ case ModeEnum::UART:
+ pinService.setInputPullup(state.getUartRxPin());
+ terminalView.println("UART: Pull-up enabled on RX.");
+ break;
+
+ case ModeEnum::HDUART:
+ pinService.setInputPullup(state.getHdUartPin());
+ terminalView.println("HDUART: Pull-up enabled on IO pin.");
+ break;
+
+ default:
+ terminalView.println("Pull-ups not applicable for this mode.");
+ break;
+ }
+}
+
+/*
+Help
+*/
+void UtilityController::handleHelp() {
+ terminalView.println("");
+ terminalView.println(" +=== Help: Available Commands ===+");
+ terminalView.println("");
+
+ terminalView.println(" General:");
+ terminalView.println(" help - Show this help message");
+ terminalView.println(" mode <name> - Change or select active mode");
+ terminalView.println(" P - Enable pull-up resistors");
+ terminalView.println(" p - Disable pull-up resistors");
+
+ terminalView.println("");
+ terminalView.println(" 1. HiZ:");
+ terminalView.println(" (default mode) - All interfaces disabled");
+
+ terminalView.println("");
+ terminalView.println(" 2. 1WIRE:");
+ terminalView.println(" scan - Scan for 1-Wire devices");
+ terminalView.println(" ping - Ping for 1-Wire device");
+ terminalView.println(" sniff - Sniff for 1-Wire raw bytes traffic");
+ terminalView.println(" read - Read ID and scratchpad");
+ terminalView.println(" write id <8 bytes> - Write the ibutton ID");
+ terminalView.println(" write sp <8 bytes> - Write scratchpad (No ID Check)");
+ terminalView.println(" config - Configure 1WIRE settings");
+ terminalView.println(" [0xAA r:8] ... - Instruction syntax supported");
+
+ terminalView.println("");
+ terminalView.println(" 3. UART:");
+ terminalView.println(" scan - Try to detect UART baudrate automatically");
+ terminalView.println(" ping - Send commands to UART device for a response");
+ terminalView.println(" read - Read data from UART device at current baud");
+ terminalView.println(" write <text> - Send data to UART device at current baud");
+ terminalView.println(" bridge - Enable UART bridge mode (Read/Write)");
+ terminalView.println(" glitch - UART timing voltage glitcher [NYI]");
+ terminalView.println(" config - Configure UART settings");
+ terminalView.println(" ['Hello] [r:64]... - Instruction syntax supported");
+
+ terminalView.println("");
+ terminalView.println(" 4. HDUART:");
+ terminalView.println(" bridge - Open HDUART bridge mode (Read/Write)");
+ terminalView.println(" config - Configure HDUART settings");
+ terminalView.println(" [0x1 D:10 r:255] - Instruction syntax supported");
+
+ terminalView.println("");
+ terminalView.println(" 5. I2C:");
+ terminalView.println(" scan - Scan for I2C devices");
+ terminalView.println(" ping <addr> - Ping an I2C address (check ACK)");
+ terminalView.println(" sniff - Sniff for I2C raw bytes traffic");
+ terminalView.println(" read <addr> <reg> - Read 1 byte from a register");
+ terminalView.println(" write <addr reg val> - Write 1 byte to a register");
+ terminalView.println(" config - Configure I2C settings");
+ terminalView.println(" [0x13 0x4B 0x1] ... - Instruction syntax supported");
+
+ terminalView.println("");
+ terminalView.println(" 6. SPI:");
+ terminalView.println(" sniff - Sniff for SPI raw bytes traffic [NYI]");
+ terminalView.println(" sdcard - Perform operations on SD cards [NYI]");
+ terminalView.println(" flash probe - Identify SPI chip [NYI]");
+ terminalView.println(" flash read - Read the content of SPI flash [NYI]");
+ terminalView.println(" flash write - Write to SPI flash [NYI]");
+ terminalView.println(" flash erase - Erase SPI flash [NYI]");
+ terminalView.println(" config - Configure SPI settings [NYI]");
+ terminalView.println(" [..] - Instruction syntax supported [NYI]");
+
+ terminalView.println("");
+ terminalView.println(" 7. 2WIRE:");
+ terminalView.println(" sniff - Sniff for 2WIRE raw bytes traffic [NYI]");
+ terminalView.println(" [..] - Instruction syntax supported [NYI]");
+
+ terminalView.println("");
+ terminalView.println(" 8. 3WIRE:");
+ terminalView.println(" [..] - Instruction syntax supported [NYI]");
+
+ terminalView.println("");
+ terminalView.println(" 9. DIO:");
+ terminalView.println(" sniff <pin> - Sniff pin toggle states High/Low");
+ terminalView.println(" read <pin> - Get pin state High/Low");
+ terminalView.println(" set <pin> <H/L/I/O> - Set pin state High/Low, Input/Output");
+ terminalView.println(" pullup <pin> - Set pin pullup resistor");
+ terminalView.println(" pwm <pin> freq <dut> - Set PWM (freq Hz, duty %) on pin");
+ terminalView.println(" reset <pin> - Reset pin to default mode");
+
+ terminalView.println("");
+ terminalView.println(" 10. LED:");
+ terminalView.println(" write <i> <r> <g> <b> - Set color of LED i (RGB, 0-255) [NYI]");
+ terminalView.println(" setprotocol - Select LED type (WS2801, APA102, SK6812...) [NYI]");
+ terminalView.println(" test - Animate test sequence on LEDs [NYI]");
+ terminalView.println(" config - Configure LED settings [NYI]");
+ terminalView.println(" reset - Turn off all LEDs (0,0,0) [NYI]");
+
+ terminalView.println("");
+ terminalView.println(" 11. INFRARED:");
+ terminalView.println(" send <dev> sub <cmd> - Send IR signal");
+ terminalView.println(" receive - Receive and decode IR signal");
+ terminalView.println(" setprotocol - Set IR protocol type (for send)");
+ terminalView.println(" devicebgone - Blasting OFF for TVs, projectors, boxes...");
+ terminalView.println(" config - Configure IR settings");
+
+ terminalView.println("");
+ terminalView.println(" 12. USB:");
+ terminalView.println(" stick - Mount SD card as a USB stick");
+ terminalView.println(" keyboard <text> - Simulate keyboard and type <text>");
+ terminalView.println(" mouse <x> <y> - Simulate mouse move by <x>, <y> pixels");
+ terminalView.println(" mouse click - Simulate mouse left click");
+ terminalView.println(" gamepad <key> - Simulate a gamepad press (A, B, UP...)");
+ terminalView.println(" reset - Reset the USB interface");
+ terminalView.println(" config - Configure USB settings");
+
+ terminalView.println("");
+ terminalView.println(" 13. BLUETOOTH:");
+ terminalView.println(" scan - Scan for nearby devices and explore services");
+ terminalView.println(" pair <addr> - Pair with a device and explore services");
+ terminalView.println(" sniff - Sniff Bluetooth data on server [NYI]");
+ terminalView.println(" spoof <addr> - Set the Bluetooth mac address (before init)");
+ terminalView.println(" status - Show current Bluetooth status");
+ terminalView.println(" server - Create an HID server and start advertising");
+ terminalView.println(" keyboard <text> - Emulate a Bluetooth keyboard and send <text>");
+ terminalView.println(" mouse <x> <y> - Emulate a Bluetooth mouse move");
+ terminalView.println(" mouse click - Emulate Blutooth mouse left click");
+ terminalView.println(" reset - Reset the Bluetooth interface");
+
+ terminalView.println("");
+ terminalView.println(" 14. WIFI:");
+ terminalView.println(" scan - List nearby Wi-Fi networks");
+ terminalView.println(" ping <host> - Ping a remote host");
+ terminalView.println(" sniff - Monitor nearby Wi-Fi packets [NYI]");
+ terminalView.println(" connect <ssid> <pw> - Connect to a Wi-Fi network");
+ terminalView.println(" status - Show current Wi-Fi status");
+ terminalView.println(" disconnect - Disconnect from Wi-Fi");
+ terminalView.println(" ap <ssid> <password> - Set a Wi-Fi access point");
+ terminalView.println(" webui - Show the web UI IP");
+ terminalView.println(" reset - Reset Wi-Fi interface");
+ terminalView.println(" config - Configure Wi-Fi settings");
+
+ terminalView.println("");
+ terminalView.println(" 15. JTAG:");
+ terminalView.println(" scan - Scan for JTAG/SWD pinouts [NYI]");
+
+ terminalView.println("");
+ terminalView.println(" Instructions (available in most modes):");
+ terminalView.println(" See documentation for instruction syntax.");
+ terminalView.println("");
+ terminalView.println(" Note: Use 'mode' to switch between I2C, UART, SPI, etc.");
+ terminalView.println("");
+}
+
+bool UtilityController::isGlobalCommand(const TerminalCommand& cmd) {
+ std::string root = cmd.getRoot();
+ return (root == "help" || root == "h" || root == "?" ||
+ root == "mode" || root == "m" || root == "l"
+ || root == "P" || root == "p");
+}
\ No newline at end of file
diff --git a/src/Controllers/UtilityController.h b/src/Controllers/UtilityController.h
new file mode 100644
index 00000000..1ee18eee
--- /dev/null
+++ b/src/Controllers/UtilityController.h
@@ -0,0 +1,49 @@
+#pragma once
+
+#include <vector>
+#include <Arduino.h>
+#include <string>
+#include <sstream>
+#include <algorithm>
+#include "Models/TerminalCommand.h"
+#include "Views/ITerminalView.h"
+#include "Inputs/IInput.h"
+#include "States/GlobalState.h"
+#include "Enums/ModeEnum.h"
+#include "Services/PinService.h"
+
+class UtilityController {
+public:
+ // Constructor
+ UtilityController(ITerminalView& terminalView, IInput& terminalInput, PinService& pinService);
+
+ // Entry point for global utility commands
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Process mode change command and return new mode
+ ModeEnum handleModeChangeCommand(const TerminalCommand& cmd);
+
+ // Check if a command is a global utility command
+ bool isGlobalCommand(const TerminalCommand& cmd);
+
+private:
+ // Display help for utility commands
+ void handleHelp();
+
+ // Ask user to select a mode
+ ModeEnum handleModeSelect();
+
+ // Enable internal pull-up resistors
+ void handleEnablePullups();
+
+ // Disable internal pull-up resistors
+ void handleDisablePullups();
+
+ // Prompt and validate mode selection from user
+ uint8_t getModeNumber();
+
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ PinService& pinService;
+ GlobalState& state = GlobalState::getInstance();
+};
\ No newline at end of file
diff --git a/src/Controllers/WifiController.cpp b/src/Controllers/WifiController.cpp
new file mode 100644
index 00000000..083e8ffb
--- /dev/null
+++ b/src/Controllers/WifiController.cpp
@@ -0,0 +1,222 @@
+#include "Controllers/WifiController.h"
+
+/*
+Constructor
+*/
+WifiController::WifiController(ITerminalView& terminalView, IInput& terminalInput, WifiService& wifiService, NvsService& nvsService, ArgTransformer& argTransformer)
+ : terminalView(terminalView), terminalInput(terminalInput), wifiService(wifiService), nvsService(nvsService), argTransformer(argTransformer) {}
+
+/*
+Entry point for command
+*/
+void WifiController::handleCommand(const TerminalCommand& cmd) {
+ const auto& root = cmd.getRoot();
+
+ if (root == "connect") {
+ handleConnect(cmd);
+ } else if (root == "disconnect") {
+ handleDisconnect(cmd);
+ } else if (root == "status") {
+ handleStatus(cmd);
+ } else if (root == "ap") {
+ handleAp(cmd);
+ } else if (root == "scan") {
+ handleScan(cmd);
+ } else if (root == "ping") {
+ handlePing(cmd);
+ } else if (root == "sniff") {
+ handleSniff(cmd);
+ } else if (root == "webui") {
+ handleWebUi(cmd);
+ } else if (root == "reset") {
+ handleReset();
+ } else {
+ handleHelp();
+ }
+}
+
+/*
+Connect
+*/
+void WifiController::handleConnect(const TerminalCommand& cmd) {
+ auto args = argTransformer.splitArgs(cmd.getSubcommand());
+
+ if (cmd.getSubcommand().empty()) {
+ terminalView.println("Usage: connect <ssid> <password>");
+ return;
+ }
+
+ std::string ssid = cmd.getSubcommand();
+ std::string password = cmd.getArgs();
+
+ terminalView.println("WiFi: Connecting to " + ssid + "...");
+
+ wifiService.setModeApSta();
+ wifiService.connect(ssid, password);
+ if (wifiService.isConnected()) {
+ terminalView.println("WiFi: Connected! IP " + wifiService.getLocalIP());
+ } else {
+ terminalView.println("WiFi: Connection failed.");
+ }
+}
+
+/*
+Disconnect
+*/
+void WifiController::handleDisconnect(const TerminalCommand& cmd) {
+ wifiService.disconnect();
+ terminalView.println("WiFi: Disconnected.");
+}
+
+void WifiController::handleStatus(const TerminalCommand& cmd) {
+ if (wifiService.isConnected()) {
+ terminalView.println("WiFi: Connected");
+ terminalView.println(" IP: " + wifiService.getLocalIP());
+ terminalView.println(" MAC: " + wifiService.getMacAddress());
+ } else {
+ terminalView.println("WiFi: Not connected.");
+ }
+}
+
+/*
+Access Point
+*/
+void WifiController::handleAp(const TerminalCommand& cmd) {
+ auto ssid = cmd.getSubcommand();
+
+ if (ssid.empty()) {
+ terminalView.println("Usage: ap <ssid> <password>");
+ return;
+ }
+
+ std::string password = cmd.getArgs();
+
+ // Already connected, mode AP+STA
+ if (wifiService.isConnected()) {
+ wifiService.setModeApSta();
+ } else {
+ wifiService.setModeApOnly();
+ }
+
+ if (wifiService.startAccessPoint(ssid, password)) {
+ terminalView.println("WiFi: Access Point started with SSID = " + ssid);
+ terminalView.println("AP IP: " + wifiService.getApIp());
+
+ auto nvsSsidField = state.getNvsSsidField();
+ auto nvsPasswordField = state.getNvsPasswordField();
+ auto ssid = nvsService.getString(nvsSsidField, "");
+ auto password = nvsService.getString(nvsPasswordField, "");
+
+ // Try to reconnect to saved WiFi
+ if (!ssid.empty() && !password.empty()) {
+ wifiService.connect(ssid, password);
+ }
+
+ if (wifiService.isConnected()) {
+ terminalView.println("STA IP: " + wifiService.getLocalIp());
+ }
+ } else {
+ terminalView.println("WiFi: Failed to start Access Point.");
+ }
+}
+
+/*
+Scan
+*/
+void WifiController::handleScan(const TerminalCommand&) {
+ terminalView.println("WiFi: Scanning for networks...");
+
+ auto results = wifiService.scanNetworks();
+ for (const auto& network : results) {
+ terminalView.println(" SSID: " + network);
+ }
+
+ if (results.empty()) {
+ terminalView.println("WiFi: No networks found.");
+ }
+}
+
+/*
+Ping
+*/
+void WifiController::handlePing(const TerminalCommand& cmd) {
+ std::string host = cmd.getSubcommand();
+
+ if (host.empty()) {
+ terminalView.println("Usage: ping <host>");
+ return;
+ }
+
+ if (!wifiService.isConnected()) {
+ terminalView.println("WiFi: Not connected.");
+ return;
+ }
+
+ terminalView.println("WiFi: Pinging " + host + "...");
+
+ if (wifiService.ping(host)) {
+ terminalView.println("WiFi: Ping successful.");
+ } else {
+ terminalView.println("WiFi: Ping failed.");
+ }
+}
+
+/*
+Sniff
+*/
+void WifiController::handleSniff(const TerminalCommand& cmd) {
+ terminalView.println("WiFi Sniff: Not implemented yet.");
+}
+
+/*
+Reset
+*/
+void WifiController::handleReset() {
+ wifiService.reset();
+ terminalView.println("WiFi: Interface reset. Disconnected.");
+}
+
+/*
+Web Interface
+*/
+void WifiController::handleWebUi(const TerminalCommand&) {
+ if (wifiService.isConnected()) {
+ auto ip = wifiService.getCurrentIP();
+ terminalView.println("WiFi: http://" + ip);
+ } else {
+ terminalView.println("WiFi: Not connected. Connect first to see Web UI address.");
+ }
+}
+
+/*
+Config
+*/
+void WifiController::handleConfig() {
+ terminalView.println("[WARNING] If you're connected via Wi-Fi,");
+ terminalView.println(" executing Wi-Fi configuration commands may");
+ terminalView.println(" cause the terminal session to disconnect.");
+ terminalView.println(" Use USB serial or restart if connection is lost.\n");
+}
+
+/*
+Help
+*/
+void WifiController::handleHelp() {
+ terminalView.println("WiFi commands:");
+ terminalView.println(" scan");
+ terminalView.println(" ping <host>");
+ terminalView.println(" sniff");
+ terminalView.println(" connect <ssid> <password>");
+ terminalView.println(" status");
+ terminalView.println(" disconnect");
+ terminalView.println(" ap <ssid> <password>");
+ terminalView.println(" webui");
+ terminalView.println(" reset");
+}
+
+void WifiController::ensureConfigured() {
+ if (!configured) {
+ handleConfig();
+ configured = true;
+ }
+}
\ No newline at end of file
diff --git a/src/Controllers/WifiController.h b/src/Controllers/WifiController.h
new file mode 100644
index 00000000..006f6297
--- /dev/null
+++ b/src/Controllers/WifiController.h
@@ -0,0 +1,64 @@
+#pragma once
+
+#include <Views/ITerminalView.h>
+#include <Inputs/IInput.h>
+#include <Services/WifiService.h>
+#include <Services/NvsService.h>
+#include <Transformers/ArgTransformer.h>
+#include <Models/TerminalCommand.h>
+#include <States/GlobalState.h>
+
+class WifiController {
+public:
+ // Constructor
+ WifiController(ITerminalView& terminalView, IInput& terminalInput, WifiService& wifiService, NvsService& nvsService, ArgTransformer& argTransformer);
+
+ // Entry point for Wi-Fi command
+ void handleCommand(const TerminalCommand& cmd);
+
+ // Ensure WiFi is configured before any action
+ void ensureConfigured();
+
+private:
+ ITerminalView& terminalView;
+ IInput& terminalInput;
+ WifiService& wifiService;
+ NvsService& nvsService;
+ ArgTransformer& argTransformer;
+ GlobalState& state = GlobalState::getInstance();
+ bool configured = false;
+
+ // Handle connection to a Wi-Fi network
+ void handleConnect(const TerminalCommand& cmd);
+
+ // Handle disconnection from current Wi-Fi
+ void handleDisconnect(const TerminalCommand& cmd);
+
+ // Display current Wi-Fi status
+ void handleStatus(const TerminalCommand& cmd);
+
+ // Configure and start Access Point mode
+ void handleAp(const TerminalCommand& cmd);
+
+ // Perform Wi-Fi network scan
+ void handleScan(const TerminalCommand& cmd);
+
+ // Ping a target over Wi-Fi
+ void handlePing(const TerminalCommand& cmd);
+
+ // Start packet sniffing
+ void handleSniff(const TerminalCommand& cmd);
+
+ // Show WebUI IP
+ void handleWebUi(const TerminalCommand& cmd);
+
+ // Reset Wi-Fi configuration
+ void handleReset();
+
+ // Ask config for Wi-Fi
+ void handleConfig();
+
+ // Show help for Wi-Fi commands
+ void handleHelp();
+
+};
diff --git a/src/Data/AsciiHid.h b/src/Data/AsciiHid.h
new file mode 100644
index 00000000..4b832625
--- /dev/null
+++ b/src/Data/AsciiHid.h
@@ -0,0 +1,74 @@
+#pragma once
+#include <stdint.h>
+
+struct AsciiHid {
+ uint8_t keycode;
+ bool requiresShift;
+};
+
+// Table ASCII (0x00 à 0x7F) to HID
+static const AsciiHid asciiHid[128] = {
+ {0, false}, {0, false}, {0, false}, {0, false}, // 0x00 – 0x03
+ {0, false}, {0, false}, {0, false}, {0, false}, // 0x04 – 0x07
+ {0x2a, false}, {0x2b, false}, {0x28, false}, {0, false}, // BS, TAB, LF
+ {0, false}, {0, false}, {0, false}, {0, false},
+ {0, false}, {0, false}, {0, false}, {0, false}, {0, false}, {0, false}, {0, false}, {0, false},
+ {0, false}, {0, false}, {0, false}, {0, false}, {0, false}, {0, false}, {0, false}, {0, false},
+
+ {0x2c, false}, // ' '
+ {0x1e, true}, // !
+ {0x34, true}, // "
+ {0x20, true}, // #
+ {0x21, true}, // $
+ {0x22, true}, // %
+ {0x24, true}, // &
+ {0x34, false}, // '
+ {0x26, true}, // (
+ {0x27, true}, // )
+ {0x25, true}, // *
+ {0x2e, true}, // +
+ {0x36, false}, // ,
+ {0x2d, false}, // -
+ {0x37, false}, // .
+ {0x38, false}, // /
+
+ {0x27, false}, {0x1e, false}, {0x1f, false}, {0x20, false}, {0x21, false}, // 0–4
+ {0x22, false}, {0x23, false}, {0x24, false}, {0x25, false}, {0x26, false}, // 5–9
+
+ {0x33, true}, // :
+ {0x33, false}, // ;
+ {0x36, true}, // <
+ {0x2e, false}, // =
+ {0x37, true}, // >
+ {0x38, true}, // ?
+ {0x1f, true}, // @
+
+ // A–Z
+ {0x04, true}, {0x05, true}, {0x06, true}, {0x07, true}, {0x08, true},
+ {0x09, true}, {0x0a, true}, {0x0b, true}, {0x0c, true}, {0x0d, true},
+ {0x0e, true}, {0x0f, true}, {0x10, true}, {0x11, true}, {0x12, true},
+ {0x13, true}, {0x14, true}, {0x15, true}, {0x16, true}, {0x17, true},
+ {0x18, true}, {0x19, true}, {0x1a, true}, {0x1b, true}, {0x1c, true},
+ {0x1d, true},
+
+ {0x2f, false}, // [
+ {0x31, false}, // '\'
+ {0x30, false}, // ]
+ {0x23, true}, // ^
+ {0x2d, true}, // _
+
+ {0x35, false}, // `
+
+ // a–z
+ {0x04, false}, {0x05, false}, {0x06, false}, {0x07, false}, {0x08, false},
+ {0x09, false}, {0x0a, false}, {0x0b, false}, {0x0c, false}, {0x0d, false},
+ {0x0e, false}, {0x0f, false}, {0x10, false}, {0x11, false}, {0x12, false},
+ {0x13, false}, {0x14, false}, {0x15, false}, {0x16, false}, {0x17, false},
+ {0x18, false}, {0x19, false}, {0x1a, false}, {0x1b, false}, {0x1c, false},
+ {0x1d, false},
+
+ // { | } ~
+ {0x2f, true}, {0x31, true}, {0x30, true}, {0x35, true},
+
+ {0, false} // DEL
+};
diff --git a/src/Data/DeviceBgoneCommands.h b/src/Data/DeviceBgoneCommands.h
new file mode 100644
index 00000000..ffad5d6a
--- /dev/null
+++ b/src/Data/DeviceBgoneCommands.h
@@ -0,0 +1,158 @@
+#pragma once
+
+#include <vector>
+#include "Enums/InfraredProtocolEnum.h"
+#include "Models/InfraredCommand.h"
+
+inline const std::vector<InfraredCommand> deviceBgoneCommands = {
+ {NECX2, 7, 7, 2},
+ {NECX2, 7, -1, 2},
+ {NECX2, 4, -1, 8},
+ {_RC5, 0, 0, 12},
+ {SONY20, 1, 0, 21},
+ {SONY20, 2, 0, 21},
+ {_NEC2, 4, 0, 8},
+ {_RC5, 1, 0, 12},
+ {_NEC, 4, 0, 8},
+ {_RC6, 0, 0, 12},
+ {_NEC, 25, 0, 24},
+ {_NEC2, 2, 125, 70},
+ {_NEC2, 4, -1, 8},
+ {_NEC2, 64, -1, 18},
+ {_NEC2, 80, -1, 63},
+ {_NEC2, 210, 109, 4},
+ {FUJITSU, 64, 8, 2},
+ {AIWA, 110, 0, 0},
+ {_NEC2, 80, -1, 63},
+ {_RC5, 0, -1, 32},
+ {_NEC2, 234, 199, 33},
+ {_NEC, 73, 0, 26},
+ {_NEC2, 100, 70, 93},
+ {_NEC2, 0, 127, 10},
+ {_NEC2, 128, 216, 47},
+ {SONY20, 90, 27, 21},
+ {_NEC2, 0, 127, 21},
+ {_NEC2, 0, 191, 13},
+ {_NEC2, 0, 127, 21},
+ {_PANASONIC, 8, 0, 61},
+ {_JVC, 0, 31, 218},
+ {_DENON, 4, -1, 8},
+ {_NEC2, 120, -1, 204},
+ {_NEC2, 231, -1, 24},
+ {_NEC2, 170, -1, 72},
+ {MITSUBISHI, 71, -1, 2},
+ {_SHARP, 1, -1, 233},
+ {_NEC2, 32, -1, 65},
+ {_NEC, 60, -1, 204},
+ {_NEC2, 186, 160, 76},
+ {_NEC, 56, 0, 18},
+ {RC6_6_20, 0, 0, 12},
+ {NEC1, 0, -1, 32},
+ {SAMSUNG32, 0, -1, 44},
+ {SONY12, 1, 0, 21},
+ {JVC_48, 0, 0, 12},
+ {_APPLE, 238, 0, 126},
+ {LOGITECH, 0, 0, 12},
+ {PANASONIC2, 1, 1, 30},
+ {SHARP_2_, 1, 0, 169},
+ {BOSE, 1, -1, 10},
+ {DIRECTV, 0, 0, 15},
+ {MCE, 0, 0, 1},
+ {ZENITH, 1, 0, 7},
+ {RCA, 0, -1, 12},
+ {GRUNDIG16, 0, 0, 10},
+ {TIVO_UNIT_0, 0, -1, 45},
+ {STREAMZAP, 0, 0, 1},
+ {PIONEER, 1, 0, 64},
+ {AKAI, 0, -1, 14},
+ {THOMSON, 0, 0, 6},
+ {XMP, 0, -1, 22},
+ {ZAPTOR_56, 0, 0, 5},
+ {BARCO, 0, 0, 66},
+ {BOSE, 0, -1, 71},
+ {PIONEER, 0, -1, 1260},
+ {AKAI, 0, -1, 9},
+ {AIWA, 0, -1, 705},
+ {PANASONIC2, 0, -1, 51},
+ {BOSE, 0, -1, 71},
+ {PANASONIC2, 0, -1, 9},
+ {LOGITECH, 0, -1, 1},
+ {BOSE, 0, -1, 11},
+ {BOSE, 0, -1, 16},
+ {BOSE, 0, -1, 17},
+ {PIONEER, 0, -1, 12},
+ {AIWA, 0, -1, 705},
+ {AKAI, 0, -1, 9},
+ {PANASONIC2, 0, -1, 51},
+ {DIRECTV, 0, -1, 9},
+ {ZENITH, 0, -1, 9},
+ {RCA, 0, -1, 392},
+ {GRUNDIG16, 0, -1, 398},
+ {TIVO_UNIT_0, 0, -1, 45},
+ {STREAMZAP, 0, -1, 1},
+ {XMP, 0, -1, 22},
+ {ZAPTOR_56, 0, -1, 5},
+ {BARCO, 0, -1, 66},
+ { _NEC, 0, -1, 57 },
+ { _NEC, 0, -1, 135 },
+ { F12, 0, -1, 128 },
+
+ // NEC‑based universal power codes
+ { _NEC2, 0, -1, 16 }, // NEC generic power
+ { _NEC2, 32, -1, 65 }, // NEC power variant
+ { _NEC2, 128, 216, 47 }, // NEC power (obsure)
+ { _NEC2, 80, -1, 63 }, // NEC power (alt)
+ { _NEC2, 210, 109, 4 }, // NEC power (alt2)
+
+ // Samsung power
+ { SAMSUNG32, 0, -1, 44 }, // Samsung 32bit power
+ { SAMSUNG36, 0, -1, 44 }, // Samsung 36bit variant
+
+ // Sony
+ { SONY20, 1, 0, 21 }, // Sony20 standard power
+ { SONY12, 1, 0, 21 }, // Sony12 standard power
+
+ // Panasonic / Kaseikyo
+ { _PANASONIC, 8, 0, 61 }, // Panasonic power
+ { PANASONIC2, 1, 1, 30 }, // Panasonic2 variant
+ { PANASONIC2, 0, -1, 51 }, // Panasonic2 alt
+
+ // JVC
+ { JVC_48, 0, 0, 12 }, // JVC basic power
+
+ // Philips RC‑5 / RC‑6 standards
+ { _RC5, 0, -1, 32 }, // RC‑5 power (Philips)
+ { RC6_6_20, 0, 0, 12 }, // RC‑6 power
+
+ // RCA
+ { RCA, 0, -1, 12 }, // RCA power
+
+ // Toshiba/Zenith
+ { ZENITH, 1, 0, 7 }, // Zenith power
+
+ // Bose
+ { BOSE, 1, -1, 10 }, // Bose power
+
+ // Pioneer
+ { PIONEER, 0, -1, 1260 }, // Pioneer power
+
+ // Directv, MCE
+ { DIRECTV, 0, -1, 9 }, // DirecTV power
+ { MCE, 0, 0, 1 }, // MCE / Media Center power
+
+ // Aiwa, Akai
+ { AIWA, 0, -1, 705 }, // Aiwa power<z
+ { AKAI, 0, -1, 9 }, // Akai power
+
+ // Sharp
+ { _SHARP, 1, -1, 233 }, // Sharp power
+ { SHARP_2_, 1, 0, 169 }, // Sharp2 power
+
+ // One‑For‑All / Streamzap
+ { STREAMZAP, 0, 0, 1 }, // StreamZap power
+ { LOGITECH, 0, 0, 12 }, // Logitech / universal
+
+ // Pioneer / Bose duplicates for universality
+ { PIONEER, 1, 0, 64 }, // Pioneer alt
+ { BOSE, 0, -1, 71 } // Bose alt
+};
\ No newline at end of file
diff --git a/src/Data/InfraredProtocolDefinitions.h b/src/Data/InfraredProtocolDefinitions.h
new file mode 100644
index 00000000..9ebe42e1
--- /dev/null
+++ b/src/Data/InfraredProtocolDefinitions.h
@@ -0,0 +1,700 @@
+/*
+
+########################################################################################################################
+# #
+# #
+# This file was adapted from https://github.com/probonopd/MakeHex/. #
+# It takes an IRP string and return the raw IR sequence. By John Fine #
+# #
+# #
+########################################################################################################################
+
+*/
+
+// Copyright 2005 John S. Fine
+
+// You may use, copy, modify and/or distribute this program for private or commercial use provided that:
+// 1) You do not hold me responsible for any damage or negative consequences resulting from those activities.
+// 2) You include this copyright notice and disclaimer in any copy of any part or all of this program.
+// I do not provide any warranty of the correctness, safety, or suitibility of this program for any purpose.
+// If you do not agree to these conditions, you have no permission to use, copy, modify or distribute this program.
+
+#pragma once
+
+#include <Models/InfraredProtocol.h>
+
+const InfraredProtocol protocolDefinitions[] = {
+ { "DAC4",
+ "Frequency=38000\n"
+ "Zero=500,-1000\n"
+ "One=500,-500\n"
+ "define X=(D+F)^1\n"
+ "define Y=(1+D+F)^1\n"
+ "First Bit=MSB\n"
+ "Form=7000,-2800,0:1,D:8,F:8,X:8,500,-60m;7000,-2800,1:1,D:8,F:8,Y:8,500,-60m\n"
+ },
+ { "Dell",
+ "Define C=32796\n"
+ "Frequency=36000\n"
+ "Time Base=444\n"
+ "Message Time=107m\n"
+ "Zero=-1,1\n"
+ "One=1,-1\n"
+ "Prefix=6,-2,1,-1\n"
+ "First Bit=MSB\n"
+ "Form=;*,M:3,-2,2,C:16,T:1,D:7,F:8\n"
+ },
+ { "Denon-K",
+ "Frequency=37000\n"
+ "Time Base=432\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=8,-4\n"
+ "Default S=0\n"
+ "Define C=(D*16)^S^(F*16)^(F:8:4)\n"
+ "Suffix=1,-173\n"
+ "Form=;*,84:8,50:8,0:4,D:4,S:4,F:12,C:8,_\n"
+ },
+ { "Dgtec",
+ "Frequency=38000\n"
+ "Time Base=560\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Form=;16,-8,D:8,F:8,~F:8,1,^108m\n"
+ },
+ { "DishPlayer_Network",
+ "Protocol=DishPlayer_Network\n"
+ "Frequency=57600\n"
+ "Time Base=410\n"
+ "Zero=1,-7\n"
+ "One=1,-4\n"
+ "Suffix=1,-15\n"
+ "Form=_;F:-6,S:5,D:5,_\n"
+ },
+ { "Dreambox",
+ "Define A=0\n"
+ "Define B=3908\n"
+ "Define G=0\n"
+ "Define H=8\n"
+ "Define J=0\n"
+ "Frequency=38000\n"
+ "First Bit=MSB\n"
+ "0=210,-760\n"
+ "1=210,-896\n"
+ "2=210,-1032\n"
+ "3=210,-1168\n"
+ "4=210,-1304\n"
+ "5=210,-1440\n"
+ "6=210,-1576\n"
+ "7=210,-1712\n"
+ "8=210,-1848\n"
+ "9=210,-1984\n"
+ "10=210,-2120\n"
+ "11=210,-2256\n"
+ "12=210,-2392\n"
+ "13=210,-2528\n"
+ "14=210,-2664\n"
+ "15=210,-2800\n"
+ "Define C=0-A-S-B-(B:4:4)-(B:4:8)-D-(D:4:4)\n"
+ "Define X=0-A-G-J-F-(F:4:4)-(F:4:8)-(F:4:12)\n"
+ "Define Y=X+G-H\n"
+ "Form=A:4,C:4,S:4,B:12,D:8,210,-13800,A:4,X:4,G:4,J:4,F:16,210,-80400;A:4,C:4,S:4,B:12,D:8,210,-13800,A:4,Y:4,H:4,J:4,F:16,210,-80400\n"
+ },
+ { "Furby",
+ "Protocol=Furby\n"
+ "Frequency=40000\n"
+ "Time Base=125\n"
+ "Zero=1,-1,1,-5\n"
+ "One=1,-1,1,-13\n"
+ "Suffix=1,-1,1,-890\n"
+ "Form=;D:5,F:8,_\n"
+ },
+ { "GI4dtv",
+ "Protocol=G.I.4dtv\n"
+ "Frequency=37700\n"
+ "Time Base=992\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=5,-2\n"
+ "SUFFIX=1,-60\n"
+ "Define B=D*64+F\n"
+ "Define C=B^B*2^B*4^B*16^B*64^B*128^B*1024\n"
+ "Form=;*,B:8,C:1:10,C:3:7,_\n"
+ },
+ { "GI_cable",
+ "Protocol=G.I.cable\n"
+ "Frequency=38400\n"
+ "Time Base=245\n"
+ "Zero=2,-9\n"
+ "One=2,-18\n"
+ "Define C=-(D+(F:4)+(F:4:4))\n"
+ "Form=36,-18,F:8,D:4,C:4,2,-120;36,-9,2,-356\n"
+ },
+ { "Jerrold",
+ "Protocol=Jerrold\n"
+ "Frequency=0\n"
+ "Zero=44,-7500\n"
+ "One=44,-11000\n"
+ "Suffix=44,-22500\n"
+ "Form=;F:5,_\n"
+ },
+ { "Kaseikyo",
+ "define N=90\n"
+ "define E=1\n"
+ "Frequency=37000\n"
+ "Time Base=432\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=8,-4\n"
+ "Default S=0\n"
+ "Define X=M^N^(M:4:4)^(N:4:4)\n"
+ "Define C=D^S^F^E^(S:4:4)^(F:4:4)\n"
+ "Suffix=1,-173\n"
+ "Form=;*,M:8,N:8,X:4,D:4,S:8,F:8,E:4,C:4,_\n"
+ },
+ { "Kramer",
+ "Frequency=38462\n"
+ "Zero=-1m,1m\n"
+ "One=-1m,2m\n"
+ "Form=4m,D:8,-2m,4500u,F:8,-33m\n"
+ },
+ { "Mitsubishi",
+ "Protocol= Mitsubishi\n"
+ "Frequency=32600\n"
+ "Time Base=300\n"
+ "Zero=1,-3\n"
+ "One=1,-7\n"
+ "Suffix=1,-80\n"
+ "Form=;D:8,F:8,_\n"
+ },
+ { "NECx1",
+ "Protocol=NECx1\n"
+ "Frequency=38000\n"
+ "Time Base=564\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Prefix=8,-8\n"
+ "Suffix=1,-78\n"
+ "Default S=D\n"
+ "R-Suffix=~D:1,1,-170\n"
+ "Form=*,D:8,S:8,F:8,~F:8,_;*,_\n"
+ },
+ { "NECx2",
+ "Protocol=NECx2\n"
+ "Frequency=38000\n"
+ "Time Base=564\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Prefix=8,-8\n"
+ "Suffix=1,-78\n"
+ "Default S=D\n"
+ "Form=;*,D:8,S:8,F:8,~F:8,_\n"
+ },
+ { "Nokia32",
+ "Define X=38\n"
+ "Default S=0\n"
+ "Protocol=Nokia32\n"
+ "Frequency=36000\n"
+ "First Bit=MSB\n"
+ "Zero=164,-276\n"
+ "One=164,-445\n"
+ "TWO=164,-614\n"
+ "THREE=164,-783\n"
+ "Form=;412,-276,D:8,S:8,X:8,F:8,164,^100m\n"
+ },
+ { "Nokia32single",
+ "Define X=38\n"
+ "Frequency=36000\n"
+ "First Bit=MSB\n"
+ "Zero=164,-276\n"
+ "One=164,-445\n"
+ "TWO=164,-614\n"
+ "THREE=164,-783\n"
+ "Form=412,-276,D:8,S:8,X:8,F:8,164,^100m,412,-276,D:8,S:8,(X+128):8,F:8,164,-10m\n"
+ },
+ { "Polycom",
+ "Protocol=Polycom\n"
+ "Frequency=38740\n"
+ "Zero=880,-1200\n"
+ "One=580,-880\n"
+ "Prefix=2600,-2600\n"
+ "Suffix=580,-60000\n"
+ "Form=*,D:-8,F:-6,0:2,_,*,D:-8,3:-8,_\n"
+ },
+ { "Proton",
+ "Protocol=Proton\n"
+ "Frequency=38000\n"
+ "Time Base=500\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=16,-8\n"
+ "Suffix=1,-45\n"
+ "Form=;*,D:8,1,-8,F:8,_\n"
+ },
+ { "Samsung20",
+ "Protocol=Samsung20\n"
+ "Frequency=38400\n"
+ "Time Base=564\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Default S=0\n"
+ "Form=;8,-8,D:6,S:6,F:8,1,-44\n"
+ },
+ { "Samsung36",
+ "define E=1\n"
+ "Frequency=38000\n"
+ "One=498,-1498\n"
+ "Zero=498,-498\n"
+ "Form=;4488,-4492,d:8,s:8,498,-4498,e:4,f:8,-68,~f:8,498,-59154\n"
+ },
+ { "TViX",
+ "Protocol=NEC\n"
+ "Frequency=38000\n"
+ "Time Base=564\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Prefix=16,-8\n"
+ "Suffix=1,-78\n"
+ "R-Prefix=16,-4\n"
+ "R-Suffix=1,-174\n"
+ "Default S=~D\n"
+ "Form=*,D:8,F:8,0:8,0:8,_;*,_\n"
+ },
+ { "Teac-K",
+ "define N=83\n"
+ "Frequency=37900\n"
+ "Time Base=432\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Default S=0\n"
+ "Define X=M^N^(M:4:4)^(N:4:4)\n"
+ "Form=8,-4,M:8,N:8,X:4,D:4,S:8,F:8,T:8,1,-100;8,-8,1,-100\n"
+ },
+ { "Thomson",
+ "Protocol=Thomson\n"
+ "Frequency=33000\n"
+ "Time Base=500\n"
+ "Zero=1,-4\n"
+ "One=1,-9\n"
+ "Suffix=1\n"
+ "Message Time=80m\n"
+ "Form=;D:4,T:1,D:1:5,F:6,1\n"
+ },
+ { "Tivo-Nec1",
+ "define U=0\n"
+ "Protocol=TivoNec\n"
+ "Frequency=38000\n"
+ "Time Base=564\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Prefix=16,-8\n"
+ "Suffix=1,-78\n"
+ "R-Prefix=16,-4\n"
+ "R-Suffix=1,-174\n"
+ "Default S=~D\n"
+ "Form=*,D:8,S:8,F:8,U:4,~F:4:4,_;*,_\n"
+ },
+ { "XMP",
+ "Define A=S:4:4\n"
+ "Define B=3908\n"
+ "Define G=0\n"
+ "Define H=8\n"
+ "Define J=S\n"
+ "Frequency=38000\n"
+ "First Bit=MSB\n"
+ "0=210,-760\n"
+ "1=210,-896\n"
+ "2=210,-1032\n"
+ "3=210,-1168\n"
+ "4=210,-1304\n"
+ "5=210,-1440\n"
+ "6=210,-1576\n"
+ "7=210,-1712\n"
+ "8=210,-1848\n"
+ "9=210,-1984\n"
+ "10=210,-2120\n"
+ "11=210,-2256\n"
+ "12=210,-2392\n"
+ "13=210,-2528\n"
+ "14=210,-2664\n"
+ "15=210,-2800\n"
+ "Define C=0-A-S-B-(B:4:4)-(B:4:8)-D-(D:4:4)\n"
+ "Define X=0-A-G-J-F-(F:4:4)-(F:4:8)-(F:4:12)\n"
+ "Define Y=X+G-H\n"
+ "Form=A:4,C:4,S:4,B:12,D:8,210,-13800,A:4,X:4,G:4,J:4,F:8,F:8:8,210,-80400;A:4,C:4,S:4,B:12,D:8,210,-13800,A:4,Y:4,H:4,J:4,F:8,F:8:8,210,-80400\n"
+ },
+ { "aiwa",
+ "Protocol=Aiwa\n"
+ "Frequency=38000\n"
+ "Time Base=550\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Prefix=16,-8\n"
+ "Suffix=1,-42\n"
+ "R-Prefix=16,-8\n"
+ "R-Suffix=1,-165\n"
+ "Form=*,D:8,S:5,~D:8,~S:5,F:8,~F:8,_;*,_\n"
+ },
+ { "async",
+ "Protocol=Async\n"
+ "Frequency=43600\n"
+ "Time Base=833\n"
+ "Zero=1\n"
+ "One=-1\n"
+ "Prefix=1,-9,1\n"
+ "Suffix=-1,1,-9\n"
+ "First Bit=LSB\n"
+ "Form=*,1:8,1:2,D:8,1:2,F:8,1:2,F:8,1:2,1:8,_\n"
+ },
+ { "blaupunkt",
+ "Protocol=Blaupunkt\n"
+ "Frequency=30500\n"
+ "Time Base=500\n"
+ "Zero=-1,1\n"
+ "One=1,-1\n"
+ "Prefix=1,-5\n"
+ "Suffix=-27\n"
+ "Form=*,1023:10,_;*,1:1,F:7,D:2,_\n"
+ },
+ { "denon",
+ "Protocol=Denon\n"
+ "Frequency=37917\n"
+ "Time Base=264\n"
+ "Zero=1,-3\n"
+ "One=1,-7\n"
+ "Suffix=1,-165\n"
+ "Form=;D:5,F:8,0:2,_,D:5,~F:8,3:2,_\n"
+ },
+ { "emerson",
+ "Protocol=EMERSON\n"
+ "Frequency=36700\n"
+ "Time Base=872\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=4,-4\n"
+ "Suffix=1,-39\n"
+ "Form=;*,D:6,F:6,~D:6,~F:6,_\n"
+ },
+ { "f12",
+ "Protocol=F12\n"
+ "Frequency=38000\n"
+ "Time Base=425\n"
+ "Zero=1,-3\n"
+ "One=3,-1\n"
+ "Form=D:3,S:1,F:8,-80,D:3,S:1,F:8,-80\n"
+ },
+ { "fujitsu",
+ "Define E=0\n"
+ "Define X=0\n"
+ "Protocol= Fujitsu\n"
+ "Frequency=38000\n"
+ "Time Base=400\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=8,-4\n"
+ "Suffix=1,-110\n"
+ "Form=;*,20:8,99:8,X:4,E:4,D:8,S:8,F:8,_\n"
+ },
+ { "iPod",
+ "Protocol=NEC\n"
+ "Frequency=38000\n"
+ "Time Base=564\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Prefix=16,-8\n"
+ "Suffix=1,-78\n"
+ "R-Prefix=16,-4\n"
+ "R-Suffix=1,-174\n"
+ "Default S=~D\n"
+ "Form=*,D:8,S:8,F:8,63:8,_;*,_\n"
+ },
+ { "imonpc",
+ "Frequency=39700\n"
+ "First Bit=MSB\n"
+ "Define A=840\n"
+ "Define B=300\n"
+ "Message Time=200m\n"
+ "0=(3*A-B),-(A+B)\n"
+ "1=(2*A-B),-(2*A+B)\n"
+ "2=(A-B),-(A+B),(A-B),-(A+B)\n"
+ "3=(A-B),-(3*A+B)\n"
+ "Form=;F:8,~F:8\n"
+ },
+ { "jvc",
+ "Protocol=JVC\n"
+ "Frequency=37900\n"
+ "Time Base=527\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=16,-8\n"
+ "Form=*;D:8,F:8,1,^88\n"
+ },
+ { "jvc_two_frames",
+ "Frequency=37900\n"
+ "Time Base=527\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=16,-8\n"
+ "Form=*,D:8,F:8,1,^88;D:8,F:8,1,^88\n"
+ },
+ { "lumagen",
+ "Frequency=38000\n"
+ "Time Base=416\n"
+ "First Bit=MSB\n"
+ "Zero=1,-6\n"
+ "One=1,-12\n"
+ "define X=F^(F:4:4)\n"
+ "define C=X^(X:1:1)^(X:1:2)^(X:1:3)\n"
+ "Form=;D:4,~C:1,F:7,1,-26\n"
+ },
+ { "mce",
+ "Frequency=36000\n"
+ "Time Base=444\n"
+ "Message Time=106m\n"
+ "Zero=-1,1\n"
+ "One=1,-1\n"
+ "First Bit=MSB\n"
+ "Form=;6,-2,1:1,M:3,-2,2,128:8,S:8,T:1,D:7,F:8\n"
+ },
+ { "nec1",
+ "Protocol=NEC\n"
+ "Frequency=38000\n"
+ "Time Base=564\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Prefix=16,-8\n"
+ "Suffix=1,-78\n"
+ "R-Prefix=16,-4\n"
+ "R-Suffix=1,-174\n"
+ "Default S=~D\n"
+ "Form=*,D:8,S:8,F:8,~F:8,_;*,_\n"
+ },
+ { "nec2",
+ "Protocol=NEC2\n"
+ "Frequency=38000\n"
+ "Time Base=564\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Prefix=16,-8\n"
+ "Suffix=1,-78\n"
+ "Default S=~D\n"
+ "Form=;*,D:8,S:8,F:8,~F:8,_\n"
+ },
+ { "panasonic",
+ "Protocol= Panasonic\n"
+ "Frequency=37000\n"
+ "Time Base=432\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=8,-4\n"
+ "Default S=0\n"
+ "Define C=D^S^F\n"
+ "Suffix=1,-173\n"
+ "Form=;*,2:8,32:8,D:8,S:8,F:8,C:8,_\n"
+ },
+ {
+ "panasonic_old",
+ "Protocol=Panasonic_Old\n"
+ "Frequency=57600\n"
+ "Time Base=833\n"
+ "Message Time=100m\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=4,-4\n"
+ "Suffix=1\n"
+ "Form=;*,D:5,F:6,~D:5,~F:6,_\n"
+ },
+ { "panasonic2",
+ "Define X=0\n"
+ "Frequency=37000\n"
+ "Time Base=432\n"
+ "Zero=1,-1\n"
+ "One=1,-3\n"
+ "Prefix=8,-4\n"
+ "Default S=0\n"
+ "Define C=D^S^X^F\n"
+ "Suffix=1,-173\n"
+ "Form=;*,2:8,32:8,D:8,S:8,X:8,F:8,C:8,_\n"
+ },
+ { "pioneer",
+ "Protocol=Pioneer\n"
+ "Frequency=40000\n"
+ "Time Base=564\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Prefix=16,-8\n"
+ "Suffix=1,-78\n"
+ "Default S=~D\n"
+ "Form=;*,D:8,S:8,F:8,~F:8,_\n"
+ },
+ { "pioneer2",
+ "Define P=86\n"
+ "Protocol=Pioneer2\n"
+ "Frequency=40000\n"
+ "Time Base=564\n"
+ "One=1,-3\n"
+ "Zero=1,-1\n"
+ "Prefix=16,-8\n"
+ "Suffix=1,-78\n"
+ "Form=;*,D:8,~D:8,P:8,~P:8,_,*,S:8,~S:8,F:8,~F:8,_\n"
+ },
+ { "rc5",
+ "Protocol=RC5\n"
+ "Frequency=36000\n"
+ "Time Base=889\n"
+ "Message Time=128\n"
+ "Zero=1,-1\n"
+ "One=-1,1\n"
+ "Prefix=1\n"
+ "First Bit=MSB\n"
+ "Form=;*,~F:1:6,T:1,D:5,F:6\n"
+ },
+ { "rc5odd",
+ "Protocol=RC5\n"
+ "Frequency=36000\n"
+ "Time Base=889\n"
+ "Message Time=128\n"
+ "Zero=1,-1\n"
+ "One=-1,1\n"
+ "Prefix=1\n"
+ "First Bit=MSB\n"
+ "Form=;*,~F:1:6,1:1,D:5,F:6\n"
+ },
+ { "rc5x",
+ "Protocol=RC5x\n"
+ "Frequency=36000\n"
+ "Time Base=889\n"
+ "Message Time=128\n"
+ "Zero=1,-1\n"
+ "One=-1,1\n"
+ "First Bit=MSB\n"
+ "Form=;1,~S:1:6,T:1,D:5,-4,S:6,F:6\n"
+ },
+ { "rc6-M-L",
+ "Protocol=RC6\n"
+ "Frequency=36000\n"
+ "Time Base=444\n"
+ "Message Time=107m\n"
+ "Zero=-1,1\n"
+ "One=1,-1\n"
+ "Prefix=6,-2,1,-1\n"
+ "First Bit=MSB\n"
+ "Default S=0\n"
+ "Form=;*,M:3,(4*T-2),(2-4*T),D:8,S:(L-16),F:8\n"
+ },
+ { "rc6",
+ "Protocol=RC6\n"
+ "Frequency=36000\n"
+ "Time Base=444\n"
+ "Message Time=107m\n"
+ "Zero=-1,1\n"
+ "One=1,-1\n"
+ "Prefix=6,-2,1,-1\n"
+ "First Bit=MSB\n"
+ "Form=;*,M:3,(4*T-2),(2-4*T),D:8,F:8\n"
+ },
+ { "rca",
+ "Protocol=RCA\n"
+ "Frequency=58000\n"
+ "Time Base=460\n"
+ "Zero=1,-2\n"
+ "One=1,-4\n"
+ "Prefix=8,-8\n"
+ "Suffix=1,-15\n"
+ "First Bit=MSB\n"
+ "Form=;*,D:4,F:8,~D:4,~F:8,_\n"
+ },
+ { "recs80_45",
+ "Frequency=38000\n"
+ "Zero=170,-4900\n"
+ "One=170,-7425\n"
+ "MESSAGETIME=121000\n"
+ "First Bit=MSB\n"
+ "Form=;1:1,T:1,D:3,F:6,170\n"
+ },
+ { "recs80_68",
+ "Frequency=36400\n"
+ "Zero=170,-5580\n"
+ "One=170,-8440\n"
+ "MESSAGETIME=138000\n"
+ "First Bit=MSB\n"
+ "Form=;1:1,T:1,D:3,F:6,170\n"
+ },
+ { "russound",
+ "Frequency=38400\n"
+ "Time Base=601\n"
+ "Zero=1,-1\n"
+ "One=1,-2\n"
+ "Two=2,-1\n"
+ "Three=2,-2\n"
+ "First Bit=MSB\n"
+ "Define C=7*(F:2:6)+5*(F:2:4)+3*(F:2:2)+(F:2)\n"
+ "Form=10,-2,D:4,F:8,C:4,1,-50;5,-2,D:4,F:8,C:4,1,-50\n"
+ },
+ { "sagem",
+ "Frequency=56000\n"
+ "Time Base=250\n"
+ "Zero=-1,1\n"
+ "One=1,-1\n"
+ "First Bit=MSB\n"
+ "Form=1:1,D:6,S:7,0:1,F:8,-350;1:1,D:6,S:7,1:1,F:8,-350\n"
+ },
+ { "sharp",
+ "Protocol=SHARP\n"
+ "Frequency=37917\n"
+ "Time Base=264\n"
+ "Zero=1,-3\n"
+ "One=1,-7\n"
+ "Suffix=1,-165\n"
+ "Form=;D:5,F:8,1:2,_,D:5,~F:8,2:2,_\n"
+ },
+ { "sony20",
+ "Protocol=Sony20\n"
+ "Frequency=40000\n"
+ "Time Base=600\n"
+ "Zero=1,-1\n"
+ "One=2,-1\n"
+ "Prefix=4,-1\n"
+ "Message Time=45m\n"
+ "Form=;*,f:7,d:5,s:8\n"
+ },
+ { "sony15",
+ "Protocol=Sony15\n"
+ "Frequency=40000\n"
+ "Time Base=600\n"
+ "Zero=1,-1\n"
+ "One=2,-1\n"
+ "Prefix=4,-1\n"
+ "Message Time=45m\n"
+ "Form=;*,f:7,d:8\n"
+ },
+ { "sony12",
+ "Protocol=Sony12\n"
+ "Frequency=40000\n"
+ "Time Base=600\n"
+ "Zero=1,-1\n"
+ "One=2,-1\n"
+ "Prefix=4,-1\n"
+ "Message Time=45m\n"
+ "Form=;*,f:7,d:5\n"
+ },
+ { "streamzap",
+ "Frequency=59000\n"
+ "Time Base=889\n"
+ "Zero=1,-1\n"
+ "One=-1,1\n"
+ "Message Time=114\n"
+ "First Bit=MSB\n"
+ "Form=;1:1,~F:1:6,T:1,D:6,F:6\n"
+ },
+ { "x10ir",
+ "Protocol=X10IR\n"
+ "Frequency=40000\n"
+ "Time Base=650\n"
+ "One=7,-7\n"
+ "Zero=2,-13\n"
+ "Form=;*,F:5,~F:5,_\n"
+ "Prefix=8,-8\n"
+ "suffix=23,-8\n"
+ }
+};
diff --git a/src/Dispatchers/ActionDispatcher.cpp b/src/Dispatchers/ActionDispatcher.cpp
new file mode 100644
index 00000000..73ed7edf
--- /dev/null
+++ b/src/Dispatchers/ActionDispatcher.cpp
@@ -0,0 +1,370 @@
+#include "ActionDispatcher.h"
+
+/*
+Constructor
+*/
+ActionDispatcher::ActionDispatcher(DependencyProvider& provider)
+ : provider(provider) {}
+
+void ActionDispatcher::setup(TerminalTypeEnum terminalType, std::string terminalInfos) {
+ provider.getDeviceView().initialize();
+ provider.getDeviceView().welcome(terminalType, terminalInfos);
+ provider.getTerminalView().initialize();
+ provider.getTerminalView().welcome(terminalType, terminalInfos);
+}
+
+/*
+Run loop
+*/
+void ActionDispatcher::run() {
+ while (true) {
+ auto protocol = ModeEnumMapper::toString(state.getCurrentMode());
+ provider.getTerminalView().printPrompt(protocol);
+ std::string action = getUserAction();
+ if (action.empty()) {
+ continue;
+ }
+ dispatch(action);
+ }
+}
+
+/*
+Dispatch
+*/
+void ActionDispatcher::dispatch(const std::string& raw) {
+ if (raw.empty()) return;
+
+ char first = raw[0];
+
+ // Instructions
+ if (first == '[' || first == '>' || first == '{') {
+ std::vector<Instruction> instructions = provider.getInstructionTransformer().transform(raw);
+ dispatchInstructions(instructions);
+ return;
+ }
+
+ // Macros
+ if (first == '(') {
+ provider.getTerminalView().println("Macros Not Yet Implemented.");
+ return;
+ }
+
+ // Terminal Command
+ TerminalCommand cmd = provider.getCommandTransformer().transform(raw);
+ dispatchCommand(cmd);
+}
+
+/*
+Dispatch Command
+*/
+void ActionDispatcher::dispatchCommand(const TerminalCommand& cmd) {
+ // Mode change command
+ if (cmd.getRoot() == "mode" || cmd.getRoot() == "m") {
+ ModeEnum maybeNewMode = provider.getUtilityController().handleModeChangeCommand(cmd);
+ if (maybeNewMode != ModeEnum::None) {
+ setCurrentMode(maybeNewMode);
+ }
+ return;
+ }
+
+ // Global command (help, P, p...)
+ if (provider.getUtilityController().isGlobalCommand(cmd)) {
+ provider.getUtilityController().handleCommand(cmd);
+ return;
+ }
+
+ // Mode specific command
+ switch (state.getCurrentMode()) {
+ case ModeEnum::HIZ:
+ provider.getUtilityController().handleCommand(cmd);
+ break;
+ case ModeEnum::OneWire:
+ provider.getOneWireController().handleCommand(cmd);
+ break;
+ case ModeEnum::UART:
+ provider.getUartController().handleCommand(cmd);
+ break;
+ case ModeEnum::HDUART:
+ provider.getHdUartController().handleCommand(cmd);
+ break;
+ case ModeEnum::I2C:
+ provider.getI2cController().handleCommand(cmd);
+ break;
+ case ModeEnum::SPI:
+ provider.getSpiController().handleCommand(cmd);
+ break;
+ case ModeEnum::TwoWire:
+ provider.getTwoWireController().handleCommand(cmd);
+ break;
+ case ModeEnum::ThreeWire:
+ provider.getThreeWireController().handleCommand(cmd);
+ break;
+ case ModeEnum::DIO:
+ provider.getDioController().handleCommand(cmd);
+ break;
+ case ModeEnum::LED:
+ provider.getLedController().handleCommand(cmd);
+ break;
+ case ModeEnum::Infrared:
+ provider.getInfraredController().handleCommand(cmd);
+ break;
+ case ModeEnum::USB:
+ provider.getUsbController().handleCommand(cmd);
+ break;
+ case ModeEnum::Bluetooth:
+ provider.getBluetoothController().handleCommand(cmd);
+ break;
+ case ModeEnum::WiFi:
+ provider.getWifiController().handleCommand(cmd);
+ break;
+ case ModeEnum::JTAG:
+ provider.getJtagController().handleCommand(cmd);
+ break;
+ }
+
+ // Config was handled in specific mode, we need to rerender the pinout view
+ if (cmd.getRoot() == "config") {
+ setCurrentMode(state.getCurrentMode());
+ }
+}
+
+/*
+Dispatch Instructions
+*/
+void ActionDispatcher::dispatchInstructions(const std::vector<Instruction>& instructions) {
+ // Convert raw instructions into bytecodes vector
+ auto bytecodes = provider.getInstructionTransformer().transformByteCodes(instructions);
+
+ switch (state.getCurrentMode()) {
+ case ModeEnum::OneWire:
+ provider.getOneWireController().handleInstruction(bytecodes);
+ break;
+ case ModeEnum::UART:
+ provider.getUartController().handleInstruction(bytecodes);
+ break;
+ case ModeEnum::HDUART:
+ provider.getHdUartController().handleInstruction(bytecodes);
+ break;
+ case ModeEnum::I2C:
+ provider.getI2cController().handleInstruction(bytecodes);
+ break;
+ case ModeEnum::SPI:
+ provider.getSpiController().handleInstruction(bytecodes);
+ break;
+ case ModeEnum::TwoWire:
+ provider.getTwoWireController().handleInstruction(bytecodes);
+ break;
+ case ModeEnum::ThreeWire:
+ provider.getThreeWireController().handleInstruction(bytecodes);
+ break;
+ case ModeEnum::LED:
+ provider.getLedController().handleInstruction(bytecodes);
+ break;
+ default:
+ provider.getTerminalView().println("Cannot execute instruction in this mode.");
+ return;
+ }
+
+ // Line by line bytecode
+ provider.getTerminalView().println("");
+ provider.getTerminalView().println("ByteCode Sequence:");
+ for (const auto& code : bytecodes) {
+ provider.getTerminalView().println(
+ ByteCodeEnumMapper::toString(code.getCommand()) +
+ " | data=" + std::to_string(code.getData()) +
+ " | bits=" + std::to_string(code.getBits()) +
+ " | repeat=" + std::to_string(code.getRepeat())
+ );
+ }
+ provider.getTerminalView().println("");
+}
+
+/*
+User Action
+*/
+std::string ActionDispatcher::getUserAction() {
+ std::string inputLine;
+ auto mode = ModeEnumMapper::toString(state.getCurrentMode());
+ size_t cursorIndex = 0;
+
+ while (true) {
+ char c = provider.getTerminalInput().handler();
+
+ if (handleEscapeSequence(c, inputLine, cursorIndex, mode)) continue;
+ if (handleEnterKey(c, inputLine)) return inputLine;
+ if (handleBackspace(c, inputLine, cursorIndex, mode)) continue;
+ if (handlePrintableChar(c, inputLine, cursorIndex, mode));
+ }
+}
+
+/*
+User Action: Escape
+*/
+bool ActionDispatcher::handleEscapeSequence(char c, std::string& inputLine, size_t& cursorIndex, const std::string& mode) {
+ if (c != '\x1B') return false;
+
+ if (provider.getTerminalInput().readChar() == '[') {
+ char next = provider.getTerminalInput().readChar();
+
+ if (next == 'A') {
+ inputLine = provider.getCommandHistoryManager().up();
+ cursorIndex = inputLine.length();
+ } else if (next == 'B') {
+ inputLine = provider.getCommandHistoryManager().down();
+ cursorIndex = inputLine.length();
+ } else if (next == 'C') {
+ if (cursorIndex < inputLine.length()) {
+ cursorIndex++;
+ provider.getTerminalView().print("\x1B[C");
+ }
+ return true;
+ } else if (next == 'D') {
+ if (cursorIndex > 0) {
+ cursorIndex--;
+ provider.getTerminalView().print("\x1B[D");
+ }
+ return true;
+ } else {
+ return false;
+ }
+
+ provider.getTerminalView().print("\r" + mode + "> " + inputLine + "\033[K");
+ return true;
+ }
+
+ return false;
+}
+
+/*
+User Action: Enter
+*/
+bool ActionDispatcher::handleEnterKey(char c, const std::string& inputLine) {
+ if (c != '\r' && c != '\n') return false;
+
+ provider.getTerminalView().println("");
+ provider.getCommandHistoryManager().add(inputLine);
+ return true;
+}
+
+/*
+User Action: Backspace
+*/
+bool ActionDispatcher::handleBackspace(char c, std::string& inputLine, size_t& cursorIndex, const std::string& mode) {
+ if (c != '\b' && c != 127) return false;
+ if (cursorIndex == 0) return true;
+
+ cursorIndex--;
+ inputLine.erase(cursorIndex, 1);
+
+ provider.getTerminalView().print("\r" + mode + "> " + inputLine + " \033[K");
+
+ int moveBack = inputLine.length() - cursorIndex;
+ for (int i = 0; i <= moveBack; ++i) {
+ provider.getTerminalView().print("\x1B[D");
+ }
+
+ return true;
+}
+
+/*
+User Action: Printable
+*/
+bool ActionDispatcher::handlePrintableChar(char c, std::string& inputLine, size_t& cursorIndex, const std::string& mode) {
+ if (!isprint(c)) return false;
+
+ inputLine.insert(cursorIndex, 1, c);
+ cursorIndex++;
+
+ provider.getTerminalView().print("\r" + mode + "> " + inputLine + "\033[K");
+
+ int moveBack = inputLine.length() - cursorIndex;
+ for (int i = 0; i < moveBack; ++i) {
+ provider.getTerminalView().print("\x1B[D");
+ }
+
+ return true;
+}
+
+/*
+Set Mode
+*/
+void ActionDispatcher::setCurrentMode(ModeEnum newMode) {
+ state.setCurrentMode(newMode);
+
+ PinoutConfig config;
+ config.setMode(ModeEnumMapper::toString(newMode));
+
+ switch (newMode) {
+ case ModeEnum::OneWire:
+ provider.getOneWireController().ensureConfigured();
+ config.setMappings({ "DATA GPIO " + std::to_string(state.getOneWirePin()) });
+ break;
+ case ModeEnum::UART:
+ provider.getUartController().ensureConfigured();
+ config.setMappings({
+ "TX GPIO " + std::to_string(state.getUartTxPin()),
+ "RX GPIO " + std::to_string(state.getUartRxPin()),
+ "BAUD " + std::to_string(state.getUartBaudRate()),
+ "BITS " + std::to_string(state.getUartDataBits()),
+ });
+ break;
+ case ModeEnum::HDUART:
+ config.setMappings({
+ "RX/TX GPIO " + std::to_string(state.getHdUartPin()),
+ "BAUD " + std::to_string(state.getHdUartBaudRate())
+ });
+ provider.getHdUartController().ensureConfigured();
+ break;
+ case ModeEnum::I2C:
+ config.setMappings({
+ "SDA GPIO " + std::to_string(state.getI2cSdaPin()),
+ "SCL GPIO " + std::to_string(state.getI2cSclPin()),
+ "FREQ " + std::to_string(state.getI2cFrequency())
+ });
+ provider.getI2cController().ensureConfigured();
+ break;
+ case ModeEnum::SPI:
+ config.setMappings({
+ "MOSI GPIO " + std::to_string(state.getSdCardMOSIPin()),
+ "MISO GPIO " + std::to_string(state.getSdCardMISOPin()),
+ "SCLK GPIO " + std::to_string(state.getSdCardCLKPin()),
+ "CS GPIO " + std::to_string(state.getSdCardCSPin())
+ });
+ provider.getSpiController().ensureConfigured();
+ break;
+ case ModeEnum::TwoWire:
+ config.setMappings({"DATA GPIO", "CLK GPIO", "FREQ"}); // TODO
+ provider.getTwoWireController().ensureConfigured();
+ break;
+ case ModeEnum::ThreeWire:
+ provider.getThreeWireController().ensureConfigured();
+ config.setMappings({"DATA GPIOX","CLK GPIOX","ENABLE GPIOX"}); // TODO
+ break;
+ case ModeEnum::LED:
+ provider.getLedController().ensureConfigured();
+ break;
+ case ModeEnum::Infrared:
+ provider.getInfraredController().ensureConfigured();
+ config.setMappings(
+ {"IR TX GPIO " + std::to_string(state.getInfraredTxPin()),
+ "IR RX GPIO " + std::to_string(state.getInfraredRxPin())
+ });
+ break;
+ case ModeEnum::USB:
+ provider.getUsbController().ensureConfigured();
+ break;
+ case ModeEnum::Bluetooth:
+ provider.getBluetoothController().ensureConfigured();
+ break;
+ case ModeEnum::WiFi:
+ provider.getWifiController().ensureConfigured();
+ break;
+ case ModeEnum::JTAG:
+ config.setMappings({ "TCK GPIOX", "TMS GPIOY", "TDO GPIOZ", "TDI GPIOW" }); // TODO
+ provider.getJtagController().ensureConfigured();
+ break;
+ }
+
+ // Show the new mode pinout
+ provider.getDeviceView().show(config);
+}
diff --git a/src/Dispatchers/ActionDispatcher.h b/src/Dispatchers/ActionDispatcher.h
new file mode 100644
index 00000000..7eed4c40
--- /dev/null
+++ b/src/Dispatchers/ActionDispatcher.h
@@ -0,0 +1,55 @@
+#pragma once
+
+#include <string>
+#include <vector>
+#include "Models/TerminalCommand.h"
+#include "Models/ByteCode.h"
+#include "Transformers/InstructionTransformer.h"
+#include "Enums/ModeEnum.h"
+#include "Providers/DependencyProvider.h"
+#include "Enums/ByteCodeEnum.h"
+#include "Enums/TerminalTypeEnum.h"
+#include "Views/ITerminalView.h"
+
+class ActionDispatcher {
+public:
+ // Constructor with dependency injection
+ explicit ActionDispatcher(DependencyProvider& provider);
+
+ // Initialize
+ void setup(TerminalTypeEnum terminalType, std::string terminaInfos);
+
+ // Main loop that handles user input
+ void run();
+
+ // Process raw user action
+ void dispatch(const std::string& raw);
+
+private:
+ DependencyProvider& provider;
+ GlobalState& state = GlobalState::getInstance();
+
+ // Handle a command
+ void dispatchCommand(const TerminalCommand& cmd);
+
+ // Handle a sequence of bytecode instructions
+ void dispatchInstructions(const std::vector<Instruction>& instructions);
+
+ // Read user input with cursor support
+ std::string getUserAction();
+
+ // Handle ANSI escape sequences (arrows, etc.)
+ bool handleEscapeSequence(char c, std::string& inputLine, size_t& cursorIndex, const std::string& mode);
+
+ // Handle backspace logic
+ bool handleBackspace(char c, std::string& inputLine, size_t& cursorIndex, const std::string& mode);
+
+ // Handle printable characters insertion
+ bool handlePrintableChar(char c, std::string& inputLine, size_t& cursorIndex, const std::string& mode);
+
+ // Handle Enter key and dispatch line
+ bool handleEnterKey(char c, const std::string& inputLine);
+
+ // Switch to a different input mode
+ void setCurrentMode(ModeEnum newMode);
+};
diff --git a/src/Enums/ByteCodeEnum.h b/src/Enums/ByteCodeEnum.h
new file mode 100644
index 00000000..0ee2efd7
--- /dev/null
+++ b/src/Enums/ByteCodeEnum.h
@@ -0,0 +1,52 @@
+#pragma once
+#include <string>
+
+enum class ByteCodeEnum {
+ Write,
+ Read,
+ Start,
+ Stop,
+ DelayUs,
+ DelayMs,
+ SetClkHigh,
+ SetClkLow,
+ SetDatHigh,
+ SetDatLow,
+ AuxHigh,
+ AuxLow,
+ AuxInput,
+ Adc,
+ ReadDat,
+ TickClock,
+ StartAlt,
+ StopAlt,
+ None
+};
+
+class ByteCodeEnumMapper {
+public:
+ static std::string toString(ByteCodeEnum code) {
+ switch (code) {
+ case ByteCodeEnum::Write: return "Write ";
+ case ByteCodeEnum::Read: return "Read ";
+ case ByteCodeEnum::Start: return "Start ";
+ case ByteCodeEnum::Stop: return "Stop ";
+ case ByteCodeEnum::DelayUs: return "DelayUs ";
+ case ByteCodeEnum::DelayMs: return "DelayMs ";
+ case ByteCodeEnum::SetClkHigh: return "SetClkHigh";
+ case ByteCodeEnum::SetClkLow: return "SetClkLow ";
+ case ByteCodeEnum::SetDatHigh: return "SetDatHigh";
+ case ByteCodeEnum::SetDatLow: return "SetDatLow ";
+ case ByteCodeEnum::AuxHigh: return "AuxHigh ";
+ case ByteCodeEnum::AuxLow: return "AuxLow ";
+ case ByteCodeEnum::AuxInput: return "AuxInput ";
+ case ByteCodeEnum::Adc: return "Adc ";
+ case ByteCodeEnum::ReadDat: return "ReadDat ";
+ case ByteCodeEnum::TickClock: return "TickClock ";
+ case ByteCodeEnum::StartAlt: return "StartAlt ";
+ case ByteCodeEnum::StopAlt: return "StopAlt ";
+ case ByteCodeEnum::None: return "None ";
+ default: return "Unknown ";
+ }
+ }
+};
\ No newline at end of file
diff --git a/src/Enums/InfraredProtocolEnum.h b/src/Enums/InfraredProtocolEnum.h
new file mode 100644
index 00000000..93be2a9e
--- /dev/null
+++ b/src/Enums/InfraredProtocolEnum.h
@@ -0,0 +1,244 @@
+#pragma once
+
+#include <string>
+
+typedef enum InfraredProtocolEnum {
+ _48_NEC1 = 0,
+ _48_NEC2 = 1,
+ AIWA = 2,
+ AKAI = 3,
+ _APPLE = 4,
+ BARCO = 5,
+ BLAUPUNKT = 6,
+ BOSE = 7,
+ CANALSAT = 8,
+ _DENON = 9,
+ DENON_K = 10,
+ DENON_1_ = 11,
+ DENON_2_ = 12,
+ DGTEC = 13,
+ DIRECTV = 14,
+ DISH_NETWORK = 15,
+ DISHPLAYER = 16,
+ EMERSON = 17,
+ F12 = 18,
+ FUJITSU = 19,
+ G_I_4DTV = 20,
+ G_I_CABLE = 21,
+ GXB = 22,
+ GRUNDIG16 = 23,
+ GRUNDIG16_30 = 24,
+ _JVC = 25,
+ JVC_48 = 26,
+ JVC_2_ = 27,
+ JERROLD = 28,
+ KATHREIN = 29,
+ KONKA = 30,
+ LOGITECH = 31,
+ LUMAGEN = 32,
+ MCE = 33,
+ MITSUBISHI = 34,
+ _NEC = 35,
+ NEC1 = 36,
+ NEC1_F16 = 37,
+ NEC1_RNC = 38,
+ NEC1_Y1 = 39,
+ NEC1_Y2 = 40,
+ NEC1_Y3 = 41,
+ _NEC2 = 42,
+ NEC2_F16 = 43,
+ NECX1 = 44,
+ NECX2 = 45,
+ NRC16 = 46,
+ NRC17 = 47,
+ NOKIA = 48,
+ NOKIA12 = 49,
+ NOKIA32 = 50,
+ PACEMSS = 51,
+ _PANASONIC = 52,
+ PANASONIC2 = 53,
+ PANASONIC_OLD = 54,
+ PIONEER = 55,
+ PROTON = 56,
+ _RC5 = 57,
+ RC5_7F = 58,
+ _RC6 = 59,
+ RC6_6_20 = 60,
+ RCA = 61,
+ RCA_OLD_ = 62,
+ RCA_38 = 63,
+ RCA_38_OLD_ = 64,
+ RECS80 = 65,
+ REPLAY = 66,
+ SAMSUNG20 = 67,
+ SAMSUNG36 = 68,
+ SCATL_6 = 69,
+ SEJIN_1_38 = 70,
+ SEJIN_1_56 = 71,
+ _SHARP = 72,
+ SHARPDVD = 73,
+ SHARP_1_ = 74,
+ SHARP_2_ = 75,
+ SONY12 = 76,
+ SONY15 = 77,
+ SONY20 = 78,
+ STREAMZAP = 79,
+ TEAC_K = 80,
+ THOMSON = 81,
+ THOMSON7 = 82,
+ TIVO_UNIT_0 = 83,
+ TIVO_UNIT_1 = 84,
+ TIVO_UNIT_2 = 85,
+ TIVO_UNIT_3 = 86,
+ TIVO_UNIT_4 = 87,
+ TIVO_UNIT_5 = 88,
+ TIVO_UNIT_6 = 89,
+ TIVO_UNIT_7 = 90,
+ TIVO_UNIT_8 = 91,
+ TIVO_UNIT_9 = 92,
+ VELLEMAN = 93,
+ XMP = 94,
+ XMP_1 = 95,
+ XMP_2 = 96,
+ ZAPTOR_56 = 97,
+ ZENITH = 98,
+ DISH_NETWO = 99,
+ PANASONIC_ = 100,
+ TIVO_UNIT = 101,
+ RCA_38_OLD = 102,
+ _KASEIKYO = 103,
+ _SAMSUNG = 104,
+ NECext = 105,
+ SIRC = 106,
+ SIRC15 = 107,
+ SIRC20 = 108,
+ NEC42 = 109,
+ NEC42ext = 110,
+ RC5X = 111,
+ SAMSUNG32 = 112,
+ RAW = 113,
+} InfraredProtocolEnum;
+
+class InfraredProtocolMapper {
+public:
+ static const std::string toString(InfraredProtocolEnum protocol) {
+ switch (protocol) {
+ case _48_NEC1: return "nec1";
+ case _48_NEC2: return "nec2";
+ case AIWA: return "aiwa";
+ case AKAI: return "akai";
+ case _APPLE: return "apple";
+ case BARCO: return "barco";
+ case BLAUPUNKT: return "blaupunkt";
+ case BOSE: return "bose";
+ case CANALSAT: return "canalsat";
+ case _DENON: return "denon";
+ case DENON_K: return "Denon-K";
+ case DENON_1_: return "denon";
+ case DENON_2_: return "denon";
+ case DGTEC: return "Dgtec";
+ case DIRECTV: return "directv";
+ case DISH_NETWORK:
+ case DISHPLAYER:
+ case DISH_NETWO: return "DishPlayer_Network";
+ case EMERSON: return "emerson";
+ case F12: return "f12";
+ case FUJITSU: return "fujitsu";
+ case G_I_4DTV: return "GI4dtv";
+ case G_I_CABLE: return "GI_cable";
+ case GXB: return "gxb";
+ case GRUNDIG16: return "grundig16";
+ case GRUNDIG16_30: return "grundig16_30";
+ case _JVC:
+ case JVC_48: return "jvc";
+ case JVC_2_: return "jvc_two_frames";
+ case JERROLD: return "Jerrold";
+ case KATHREIN: return "kathrein";
+ case KONKA: return "konka";
+ case LOGITECH: return "logitech";
+ case LUMAGEN: return "lumagen";
+ case MCE: return "mce";
+ case MITSUBISHI: return "Mitsubishi";
+ case _NEC:
+ case NEC1: return "nec1";
+ case NEC1_F16: return "nec1_f16";
+ case NEC1_RNC: return "nec1_rnc";
+ case NEC1_Y1: return "nec1_y1";
+ case NEC1_Y2: return "nec1_y2";
+ case NEC1_Y3: return "nec1_y3";
+ case _NEC2: return "nec2";
+ case NEC2_F16: return "nec2_f16";
+ case NECX1: return "NECx1";
+ case NECX2:
+ case NECext: return "NECx2";
+ case NEC42: return "NEC42";
+ case NEC42ext: return "NEC42ext";
+ case NRC16: return "nrc16";
+ case NRC17: return "nrc17";
+ case NOKIA:
+ case NOKIA32: return "Nokia32";
+ case NOKIA12: return "Nokia32single";
+ case PACEMSS: return "pacemss";
+ case _PANASONIC:
+ case PANASONIC_:
+ case PANASONIC2: return "panasonic";
+ case PANASONIC_OLD: return "panasonic_old";
+ case PIONEER: return "pioneer";
+ case PROTON: return "Proton";
+ case _RC5: return "rc5";
+ case RC5_7F: return "rc5odd";
+ case RC5X: return "rc5x";
+ case _RC6: return "rc6";
+ case RC6_6_20: return "rc6-6-20";
+ case RCA:
+ case RCA_OLD_:
+ case RCA_38:
+ case RCA_38_OLD_:
+ case RCA_38_OLD: return "rca";
+ case RECS80: return "recs80_45";
+ case REPLAY: return "replay";
+ case SAMSUNG20: return "Samsung20";
+ case SAMSUNG32: return "Samsung32";
+ case SAMSUNG36: return "Samsung36";
+ case SCATL_6: return "scatl_6";
+ case SEJIN_1_38: return "sejin_1_38";
+ case SEJIN_1_56: return "sejin_1_56";
+ case _SHARP:
+ case SHARPDVD:
+ case SHARP_1_:
+ case SHARP_2_: return "sharp";
+ case SIRC: return "SIRC";
+ case SIRC15: return "SIRC15";
+ case SIRC20: return "SIRC20";
+ case SONY12: return "sony12";
+ case SONY15: return "sony15";
+ case SONY20: return "sony20";
+ case STREAMZAP: return "streamzap";
+ case TEAC_K: return "Teac-K";
+ case THOMSON:
+ case THOMSON7: return "Thomson";
+ case TIVO_UNIT_0:
+ case TIVO_UNIT_1:
+ case TIVO_UNIT_2:
+ case TIVO_UNIT_3:
+ case TIVO_UNIT_4:
+ case TIVO_UNIT_5:
+ case TIVO_UNIT_6:
+ case TIVO_UNIT_7:
+ case TIVO_UNIT_8:
+ case TIVO_UNIT_9:
+ case TIVO_UNIT: return "Tivo-Nec1";
+ case VELLEMAN: return "velleman";
+ case XMP:
+ case XMP_1:
+ case XMP_2: return "XMP";
+ case ZAPTOR_56: return "zaptor_56";
+ case ZENITH: return "zenith";
+ case _KASEIKYO: return "Kaseikyo";
+ case _SAMSUNG: return "Samsung";
+ case RAW: return "raw";
+
+ default: return "nec2";
+ }
+ }
+};
diff --git a/src/Enums/ModeEnum.h b/src/Enums/ModeEnum.h
new file mode 100644
index 00000000..b0452a14
--- /dev/null
+++ b/src/Enums/ModeEnum.h
@@ -0,0 +1,89 @@
+#pragma once
+
+#include <unordered_map>
+#include <string>
+#include <vector>
+#include <algorithm>
+
+enum class ModeEnum {
+ None = -1,
+ HIZ,
+ OneWire,
+ UART,
+ HDUART,
+ I2C,
+ SPI,
+ TwoWire,
+ ThreeWire,
+ DIO,
+ LED,
+ Infrared,
+ USB,
+ Bluetooth,
+ WiFi,
+ JTAG,
+};
+
+class ModeEnumMapper {
+public:
+ static std::string toString(ModeEnum proto) {
+ static const std::unordered_map<ModeEnum, std::string> map = {
+ {ModeEnum::None, "None"},
+ {ModeEnum::HIZ, "HIZ"},
+ {ModeEnum::OneWire, "1WIRE"},
+ {ModeEnum::UART, "UART"},
+ {ModeEnum::HDUART, "HDUART"},
+ {ModeEnum::I2C, "I2C"},
+ {ModeEnum::SPI, "SPI"},
+ {ModeEnum::TwoWire, "2WIRE"},
+ {ModeEnum::ThreeWire, "3WIRE"},
+ {ModeEnum::DIO, "DIO"},
+ {ModeEnum::LED, "LED"},
+ {ModeEnum::Infrared, "INFRARED"},
+ {ModeEnum::USB, "USB"},
+ {ModeEnum::Bluetooth, "BLUETOOTH"},
+ {ModeEnum::WiFi, "WIFI"},
+ {ModeEnum::JTAG, "JTAG"}
+ };
+
+ auto it = map.find(proto);
+ return it != map.end() ? it->second : "Unknown Protocol";
+ }
+
+ static std::vector<std::string> getProtocolNames(const std::vector<ModeEnum>& protocols) {
+ std::vector<std::string> names;
+ for (const auto& proto : protocols) {
+ names.push_back(toString(proto));
+ }
+ return names;
+ }
+
+ static ModeEnum fromString(const std::string& name) {
+ static const std::unordered_map<std::string, ModeEnum> reverseMap = {
+ {"HIZ", ModeEnum::HIZ},
+ {"1WIRE", ModeEnum::OneWire},
+ {"UART", ModeEnum::UART},
+ {"HDUART", ModeEnum::HDUART},
+ {"I2C", ModeEnum::I2C},
+ {"SPI", ModeEnum::SPI},
+ {"2WIRE", ModeEnum::TwoWire},
+ {"3WIRE", ModeEnum::ThreeWire},
+ {"DIO", ModeEnum::DIO},
+ {"LED", ModeEnum::LED},
+ {"INFRARED", ModeEnum::Infrared},
+ {"USB", ModeEnum::USB},
+ {"BLUETOOTH", ModeEnum::Bluetooth},
+ {"WIFI", ModeEnum::WiFi},
+ {"JTAG", ModeEnum::JTAG}
+ };
+
+ std::string upper;
+ upper.reserve(name.size());
+ for (char c : name) {
+ upper += std::toupper(static_cast<unsigned char>(c));
+ }
+
+ auto it = reverseMap.find(upper);
+ return it != reverseMap.end() ? it->second : ModeEnum::None;
+ }
+};
diff --git a/src/Enums/TerminalModeEnum.h b/src/Enums/TerminalModeEnum.h
new file mode 100644
index 00000000..c71e356f
--- /dev/null
+++ b/src/Enums/TerminalModeEnum.h
@@ -0,0 +1,20 @@
+#pragma once
+#include <string>
+
+enum class TerminalMode {
+ Serial,
+ Web,
+ None
+};
+
+class TerminalModeEnumMapper {
+public:
+ static std::string toString(TerminalMode mode) {
+ switch (mode) {
+ case TerminalMode::Serial: return "Serial";
+ case TerminalMode::Web: return "Web ";
+ case TerminalMode::None: return "None ";
+ default: return "Unknown";
+ }
+ }
+};
diff --git a/src/Enums/TerminalTypeEnum.h b/src/Enums/TerminalTypeEnum.h
new file mode 100644
index 00000000..c383b9dd
--- /dev/null
+++ b/src/Enums/TerminalTypeEnum.h
@@ -0,0 +1,22 @@
+#pragma once
+#include <string>
+
+enum class TerminalTypeEnum {
+ Serial,
+ WiFiAp,
+ WiFiClient,
+ None
+};
+
+class TerminalTypeEnumMapper {
+public:
+ static std::string toString(TerminalTypeEnum type) {
+ switch (type) {
+ case TerminalTypeEnum::Serial: return "USB Serial";
+ case TerminalTypeEnum::WiFiAp: return "WiFi AP";
+ case TerminalTypeEnum::WiFiClient: return "WiFi Web";
+ case TerminalTypeEnum::None: return "None";
+ default: return "Unknown";
+ }
+ }
+};
diff --git a/src/Inputs/CardputerInput.cpp b/src/Inputs/CardputerInput.cpp
new file mode 100644
index 00000000..2dde35fc
--- /dev/null
+++ b/src/Inputs/CardputerInput.cpp
@@ -0,0 +1,94 @@
+#include "CardputerInput.h"
+
+char CardputerInput::handler() {
+ while(true) {
+ // Update keyboard state
+ M5Cardputer.update();
+
+ if (!M5Cardputer.Keyboard.isChange()) {
+ continue;
+ }
+
+ if (!M5Cardputer.Keyboard.isPressed()) {
+ continue;
+ }
+
+ Keyboard_Class::KeysState status = M5Cardputer.Keyboard.keysState();
+
+ if (status.enter) { // go to next menu
+ return KEY_OK;
+ }
+ if (status.del) {
+ return KEY_DEL;
+ }
+
+ if(M5Cardputer.Keyboard.isKeyPressed(KEY_ARROW_LEFT)) { // go back to previous menu
+ return KEY_ARROW_LEFT;
+ }
+
+ if(M5Cardputer.Keyboard.isKeyPressed(KEY_ARROW_RIGHT)) { // go to next menu
+ return KEY_ARROW_RIGHT;
+ }
+
+ for (auto c : status.word) {
+ // Issue with %, the only key that requires 2 inputs to display
+ if (c == '%') {
+ return '5';
+ }
+ return c; // retourner le premier char saisi
+ }
+
+ delay(10); // debounce
+ return KEY_NONE;
+ }
+}
+
+void CardputerInput::waitPress() {
+ while(true){
+ M5Cardputer.update();
+ if (M5Cardputer.Keyboard.isChange()) {
+ if (M5Cardputer.Keyboard.isPressed()) {
+ Keyboard_Class::KeysState status = M5Cardputer.Keyboard.keysState();
+ return;
+ }
+ }
+ delay(10);
+ }
+}
+
+char CardputerInput::readChar() {
+ M5Cardputer.update();
+
+ if (!M5Cardputer.Keyboard.isChange()) {
+ return KEY_NONE;
+ }
+
+ if (!M5Cardputer.Keyboard.isPressed()) {
+ return KEY_NONE;
+ }
+
+ Keyboard_Class::KeysState status = M5Cardputer.Keyboard.keysState();
+
+ if (status.enter) {
+ return KEY_OK;
+ }
+ if (status.del) {
+ return KEY_DEL;
+ }
+
+ if(M5Cardputer.Keyboard.isKeyPressed(KEY_ARROW_LEFT)) { // go back to previous menu
+ return KEY_ARROW_LEFT;
+ }
+
+ if(M5Cardputer.Keyboard.isKeyPressed(KEY_ARROW_RIGHT)) { // go to next menu
+ return KEY_ARROW_RIGHT;
+ }
+
+ for (auto c : status.word) {
+ // Issue with %, the only key that requires 2 inputs to display
+ if (c == '%') {
+ return '5';
+ }
+ return c; // retourner le premier char saisi
+ }
+}
\ No newline at end of file
diff --git a/src/Inputs/CardputerInput.h b/src/Inputs/CardputerInput.h
new file mode 100644
index 00000000..609f1281
--- /dev/null
+++ b/src/Inputs/CardputerInput.h
@@ -0,0 +1,14 @@
+#pragma once
+
+#include <map>
+#include <M5Cardputer.h>
+#include "IInput.h"
+#include "InputKeys.h"
+
+
+class CardputerInput : public IInput {
+public:
+ char handler() override;
+ void waitPress() override;
+ char readChar() override;
+};
diff --git a/src/Inputs/IInput.h b/src/Inputs/IInput.h
new file mode 100644
index 00000000..811dd5aa
--- /dev/null
+++ b/src/Inputs/IInput.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include <string>
+#include "InputKeys.h"
+
+// Interface for terminal input
+// This is the interface expected by the ActionDispatcher to handle user input.
+// It abstracts how input is received (from keyboard, serial, web, etc.).
+
+class IInput {
+public:
+ virtual ~IInput() = default;
+
+ // Blocking read
+ virtual char handler() = 0;
+
+ // Non blocking read
+ virtual char readChar() = 0;
+
+ // Wait an inpout
+ virtual void waitPress() = 0;
+
+};
\ No newline at end of file
diff --git a/src/Inputs/InputKeys.h b/src/Inputs/InputKeys.h
new file mode 100644
index 00000000..9c6b7f2a
--- /dev/null
+++ b/src/Inputs/InputKeys.h
@@ -0,0 +1,14 @@
+#ifndef INPUT_KEYS_H
+#define INPUT_KEYS_H
+
+#define KEY_OK '\n'
+#define KEY_DEL '\b'
+#define KEY_ESC_CUSTOM '`'
+#define KEY_NONE '\0'
+#define KEY_RETURN_CUSTOM '\r'
+#define KEY_ARROW_UP ';'
+#define KEY_ARROW_DOWN '.'
+#define KEY_ARROW_LEFT ','
+#define KEY_ARROW_RIGHT '/'
+
+#endif // INPUT_KEYS_H
diff --git a/src/Inputs/SerialTerminalInput.cpp b/src/Inputs/SerialTerminalInput.cpp
new file mode 100644
index 00000000..3e208715
--- /dev/null
+++ b/src/Inputs/SerialTerminalInput.cpp
@@ -0,0 +1,18 @@
+#include "SerialTerminalInput.h"
+
+char SerialTerminalInput::handler() {
+ while (!Serial.available()) {}
+ return Serial.read();
+}
+
+void SerialTerminalInput::waitPress() {
+ while (!Serial.available()) {}
+ Serial.read(); // discard
+}
+
+char SerialTerminalInput::readChar() {
+ if (Serial.available()) {
+ return Serial.read();
+ }
+ return KEY_NONE;
+}
\ No newline at end of file
diff --git a/src/Inputs/SerialTerminalInput.h b/src/Inputs/SerialTerminalInput.h
new file mode 100644
index 00000000..3045f4db
--- /dev/null
+++ b/src/Inputs/SerialTerminalInput.h
@@ -0,0 +1,12 @@
+#pragma once
+
+#include <Inputs/IInput.h>
+#include <Arduino.h>
+#include <vector>
+
+class SerialTerminalInput : public IInput {
+public:
+ char handler() override;
+ void waitPress() override;
+ char readChar() override;
+};
diff --git a/src/Inputs/WebTerminalInput.cpp b/src/Inputs/WebTerminalInput.cpp
new file mode 100644
index 00000000..01ccb731
--- /dev/null
+++ b/src/Inputs/WebTerminalInput.cpp
@@ -0,0 +1,15 @@
+#include "WebTerminalInput.h"
+
+WebTerminalInput::WebTerminalInput(WebSocketServer& server) : server(server) {}
+
+char WebTerminalInput::handler() {
+ return server.readCharBlocking();
+}
+
+char WebTerminalInput::readChar() {
+ return server.readCharNonBlocking();
+}
+
+void WebTerminalInput::waitPress() {
+ server.readCharBlocking();
+}
diff --git a/src/Inputs/WebTerminalInput.h b/src/Inputs/WebTerminalInput.h
new file mode 100644
index 00000000..a792ad5d
--- /dev/null
+++ b/src/Inputs/WebTerminalInput.h
@@ -0,0 +1,15 @@
+#pragma once
+#include "IInput.h"
+#include "Servers/WebSocketServer.h"
+
+class WebTerminalInput : public IInput {
+public:
+ WebTerminalInput(WebSocketServer& server);
+
+ char handler() override;
+ char readChar() override;
+ void waitPress() override;
+
+private:
+ WebSocketServer& server;
+};
diff --git a/src/Managers/CommandHistoryManager.cpp b/src/Managers/CommandHistoryManager.cpp
new file mode 100644
index 00000000..fe94ec61
--- /dev/null
+++ b/src/Managers/CommandHistoryManager.cpp
@@ -0,0 +1,54 @@
+#include "CommandHistoryManager.h"
+
+/*
+Add
+*/
+void CommandHistoryManager::add(const std::string& line) {
+ if (!line.empty() && (history.empty() || history.back() != line)) {
+ history.push_back(line);
+
+ if (history.size() > maxHistory) {
+ history.erase(history.begin());
+ }
+ }
+ index = history.size();
+}
+
+/*
+Up History
+*/
+const std::string& CommandHistoryManager::up() {
+ if (index > 0) {
+ --index;
+ }
+ currentLine = (index < history.size()) ? history[index] : "";
+ return currentLine;
+}
+
+/*
+Down History
+*/
+const std::string& CommandHistoryManager::down() {
+ if (index < history.size() - 1) {
+ ++index;
+ } else {
+ index = history.size();
+ currentLine.clear();
+ }
+ currentLine = (index < history.size()) ? history[index] : "";
+ return currentLine;
+}
+
+/*
+Reset History
+*/
+void CommandHistoryManager::reset() {
+ index = history.size();
+}
+
+/*
+Size
+*/
+size_t CommandHistoryManager::size() const {
+ return history.size();
+}
diff --git a/src/Managers/CommandHistoryManager.h b/src/Managers/CommandHistoryManager.h
new file mode 100644
index 00000000..38984d99
--- /dev/null
+++ b/src/Managers/CommandHistoryManager.h
@@ -0,0 +1,27 @@
+#pragma once
+
+#include <vector>
+#include <string>
+
+class CommandHistoryManager {
+public:
+ // Adds a new line to the history (unless it's empty or duplicate of last)
+ void add(const std::string& line);
+
+ // Moves up in history and returns the previous command
+ const std::string& up();
+
+ // Moves down in history and returns the next command
+ const std::string& down();
+
+ // Resets the navigation index to the end of the history
+ void reset();
+
+ // Returns total number of stored history entries
+ size_t size() const;
+private:
+ std::vector<std::string> history;
+ std::string currentLine;
+ size_t index = 0;
+ static constexpr size_t maxHistory = 50;
+};
\ No newline at end of file
diff --git a/src/Models/ByteCode.h b/src/Models/ByteCode.h
new file mode 100644
index 00000000..1abe0ca4
--- /dev/null
+++ b/src/Models/ByteCode.h
@@ -0,0 +1,40 @@
+#pragma once
+
+#include "Enums/ByteCodeEnum.h"
+#include <cstdint>
+
+class ByteCode {
+public:
+ ByteCode(ByteCodeEnum command = ByteCodeEnum::None, uint32_t data = 0)
+ : command(command), data(data), bits(8), repeat(1), hasBits(false), hasRepeat(false) {}
+
+ ByteCode(ByteCodeEnum command, uint32_t data, uint8_t bits, uint32_t repeat)
+ : command(command), data(data), bits(bits), repeat(repeat), hasBits(true), hasRepeat(true) {}
+
+
+ ByteCodeEnum getCommand() const { return command; }
+ void setCommand(ByteCodeEnum cmd) { command = cmd; }
+
+ uint32_t getData() const { return data; }
+ void setData(uint32_t value) { data = value; }
+
+ uint8_t getBits() const { return bits; }
+ void setBits(uint8_t b) { bits = b; }
+
+ uint32_t getRepeat() const { return repeat; }
+ void setRepeat(uint32_t r) { repeat = r; }
+
+ bool hasBitsSet() const { return hasBits; }
+ void setHasBits(bool flag) { hasBits = flag; }
+
+ bool hasRepeatSet() const { return hasRepeat; }
+ void setHasRepeat(bool flag) { hasRepeat = flag; }
+
+private:
+ ByteCodeEnum command;
+ uint32_t data;
+ uint8_t bits;
+ uint32_t repeat;
+ bool hasBits;
+ bool hasRepeat;
+};
diff --git a/src/Models/InfraredCommand.h b/src/Models/InfraredCommand.h
new file mode 100644
index 00000000..79374db2
--- /dev/null
+++ b/src/Models/InfraredCommand.h
@@ -0,0 +1,49 @@
+#pragma once
+
+#include <string>
+#include <cstring>
+#include <Enums/InfraredProtocolEnum.h>
+
+class InfraredCommand {
+public:
+ InfraredCommand()
+ : functionName(""), protocol(InfraredProtocolEnum::RAW),
+ device(0), subdevice(0), function(0) {}
+
+ InfraredCommand(InfraredProtocolEnum proto, int device, int subdevice, int function)
+ : protocol(proto), device(device), subdevice(subdevice), function(function) {}
+
+
+ InfraredCommand(const char* functionName, InfraredProtocolEnum protocol, int16_t device, int16_t subdevice, int16_t function)
+ : functionName(functionName), protocol(protocol), device(device), subdevice(subdevice), function(function) {}
+
+ const char* getFunctionName() const { return functionName; }
+ InfraredProtocolEnum getProtocol() const { return protocol; }
+ int16_t getDevice() const { return device; }
+ int16_t getSubdevice() const { return subdevice; }
+ int16_t getFunction() const { return function; }
+
+ void setDevice(int16_t value) { device = value; }
+ void setSubdevice(int16_t value) { subdevice = value; }
+ void setFunction(int16_t value) { function = value; }
+ void setProtocol(InfraredProtocolEnum prot) {protocol = prot; }
+
+ bool operator==(const InfraredCommand& other) const {
+ return (std::strcmp(functionName, other.functionName) == 0) &&
+ (protocol == other.protocol) &&
+ (device == other.device) &&
+ (subdevice == other.subdevice) &&
+ (function == other.function);
+ }
+
+ bool operator!=(const InfraredCommand& other) const {
+ return !(*this == other);
+ }
+
+private:
+ const char* functionName;
+ InfraredProtocolEnum protocol;
+ int16_t device;
+ int16_t subdevice;
+ int16_t function;
+};
diff --git a/src/Models/InfraredProtocol.h b/src/Models/InfraredProtocol.h
new file mode 100644
index 00000000..12ffd74a
--- /dev/null
+++ b/src/Models/InfraredProtocol.h
@@ -0,0 +1,6 @@
+#pragma once
+
+typedef struct {
+ const char* name;
+ const char* def;
+} InfraredProtocol;
diff --git a/src/Models/Instruction.h b/src/Models/Instruction.h
new file mode 100644
index 00000000..ee8923d8
--- /dev/null
+++ b/src/Models/Instruction.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include <string>
+#include <vector>
+
+class Instruction {
+public:
+ std::string raw; // Texte brut "[0xA5 r]"
+ char prefix; // '[', '>', '{' ...
+ std::vector<std::string> tokens; // Liste elements : "0xA5", "r", ...
+
+ Instruction(const std::string& rawInput)
+ : raw(rawInput), prefix(rawInput.empty() ? '\0' : rawInput[0]) {}
+
+ void addToken(const std::string& token) {
+ tokens.push_back(token);
+ }
+};
diff --git a/src/Models/PinoutConfig.h b/src/Models/PinoutConfig.h
new file mode 100644
index 00000000..5b81e8aa
--- /dev/null
+++ b/src/Models/PinoutConfig.h
@@ -0,0 +1,49 @@
+#pragma once
+
+#include <vector>
+#include <string>
+
+class PinoutConfig {
+public:
+ // Set the current mode (e.g. "I2C", "SPI", "UART"...)
+ void setMode(const std::string& newMode) {
+ mode = newMode;
+ }
+
+ // Get the current mode
+ const std::string& getMode() const {
+ return mode;
+ }
+
+ // Set all mappings at once
+ void setMappings(const std::vector<std::string>& newMappings) {
+ mappings = newMappings;
+ }
+
+ // Add a single mapping like "1 RX"
+ void addMapping(const std::string& mapping) {
+ mappings.push_back(mapping);
+ }
+
+ // Get all mappings
+ const std::vector<std::string>& getMappings() const {
+ return mappings;
+ }
+
+ // Get a specific mapping by index
+ std::string getMappingAt(size_t index) const {
+ if (index < mappings.size()) {
+ return mappings[index];
+ }
+ return "";
+ }
+
+ // Clear all mappings
+ void clearMappings() {
+ mappings.clear();
+ }
+
+private:
+ std::string mode = "None";
+ std::vector<std::string> mappings;
+};
diff --git a/src/Models/TerminalCommand.h b/src/Models/TerminalCommand.h
new file mode 100644
index 00000000..b4bcc18b
--- /dev/null
+++ b/src/Models/TerminalCommand.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include <string>
+
+class TerminalCommand {
+public:
+ TerminalCommand(const std::string& root = "", const std::string& sub = "", const std::string& args = "")
+ : root(root), subcommand(sub), args(args) {}
+
+ std::string getRoot() const { return root; }
+ void setRoot(const std::string& r) { root = r; }
+
+ std::string getSubcommand() const { return subcommand; }
+ void setSubcommand(const std::string& s) { subcommand = s; }
+
+ std::string getArgs() const { return args; }
+ void setArgs(const std::string& a) { args = a; }
+
+private:
+ std::string root;
+ std::string subcommand;
+ std::string args;
+};
diff --git a/src/Providers/DependencyProvider.cpp b/src/Providers/DependencyProvider.cpp
new file mode 100644
index 00000000..f8a04a00
--- /dev/null
+++ b/src/Providers/DependencyProvider.cpp
@@ -0,0 +1,97 @@
+#include "DependencyProvider.h"
+
+DependencyProvider::DependencyProvider(ITerminalView& terminalView, IDeviceView& deviceView,
+ IInput& terminalInput, IInput& deviceInput)
+ : terminalView(terminalView),
+ deviceView(deviceView),
+ terminalInput(terminalInput),
+ deviceInput(deviceInput),
+ sdService(),
+ nvsService(),
+ ledService(),
+ uartService(),
+ i2cService(),
+ oneWireService(),
+ infraredService(),
+ usbService(),
+ spiService(),
+ pinService(),
+ bluetoothService(),
+ wifiService(),
+ commandTransformer(),
+ instructionTransformer(),
+ argTransformer(),
+ webRequestTransformer(),
+ commandHistoryManager(),
+ horizontalSelector(deviceView, deviceInput),
+ terminalTypeConfigurator(horizontalSelector),
+ uartController(terminalView, terminalInput, deviceInput, uartService, argTransformer),
+ i2cController(terminalView, terminalInput, i2cService, argTransformer),
+ oneWireController(terminalView, terminalInput, oneWireService, argTransformer),
+ infraredController(terminalView, terminalInput, infraredService, argTransformer),
+ usbController(terminalView, terminalInput, usbService, argTransformer),
+ utilityController(terminalView, terminalInput, pinService),
+ hdUartController(terminalView, terminalInput, deviceInput, hdUartService, argTransformer),
+ spiController(terminalView, terminalInput, spiService, argTransformer),
+ jtagController(terminalView, terminalInput),
+ twoWireController(terminalView, terminalInput),
+ threeWireController(terminalView, terminalInput),
+ dioController(terminalView, terminalInput, pinService, argTransformer),
+ ledController(terminalView, terminalInput, ledService),
+ bluetoothController(terminalView, terminalInput, bluetoothService, argTransformer),
+ wifiController(terminalView, terminalInput, wifiService, nvsService, argTransformer)
+{}
+
+// Accessors for core components
+ITerminalView& DependencyProvider::getTerminalView() { return terminalView; }
+void DependencyProvider::setTerminalView(ITerminalView& view) { terminalView = view; };
+IDeviceView& DependencyProvider::getDeviceView() { return deviceView; }
+IInput& DependencyProvider::getTerminalInput() { return terminalInput; }
+IInput& DependencyProvider::getDeviceInput() { return deviceInput; }
+
+// Services
+SdService& DependencyProvider::getSdService() { return sdService; }
+NvsService& DependencyProvider::getNvsService() { return nvsService; }
+LedService& DependencyProvider::getLedService() { return ledService; }
+I2cService& DependencyProvider::getI2cService() { return i2cService; }
+UartService& DependencyProvider::getUartService() { return uartService; }
+OneWireService& DependencyProvider::getOneWireService() { return oneWireService; }
+InfraredService& DependencyProvider::getInfraredService() { return infraredService; }
+UsbService& DependencyProvider::getUsbService() { return usbService; }
+SpiService& DependencyProvider::getSpiService() { return spiService; }
+HdUartService& DependencyProvider::getHdUartService() { return hdUartService; }
+PinService& DependencyProvider::getPinService() { return pinService; }
+WifiService& DependencyProvider::getWifiService() { return wifiService; }
+BluetoothService& DependencyProvider::getBluetoothService() { return bluetoothService; }
+
+// Controllers
+UartController& DependencyProvider::getUartController() { return uartController; }
+I2cController& DependencyProvider::getI2cController() { return i2cController; }
+OneWireController& DependencyProvider::getOneWireController() { return oneWireController; }
+UtilityController& DependencyProvider::getUtilityController() { return utilityController; }
+InfraredController& DependencyProvider::getInfraredController() { return infraredController; }
+UsbController& DependencyProvider::getUsbController() { return usbController; }
+HdUartController& DependencyProvider::getHdUartController() { return hdUartController; }
+SpiController& DependencyProvider::getSpiController() { return spiController; }
+JtagController& DependencyProvider::getJtagController() { return jtagController; }
+TwoWireController& DependencyProvider::getTwoWireController() { return twoWireController; }
+ThreeWireController& DependencyProvider::getThreeWireController() { return threeWireController; }
+DioController& DependencyProvider::getDioController() { return dioController; }
+LedController& DependencyProvider::getLedController() { return ledController; }
+WifiController& DependencyProvider::getWifiController() { return wifiController; }
+BluetoothController& DependencyProvider::getBluetoothController() { return bluetoothController; }
+
+// Transformers
+TerminalCommandTransformer& DependencyProvider::getCommandTransformer() { return commandTransformer; }
+InstructionTransformer& DependencyProvider::getInstructionTransformer() { return instructionTransformer; }
+ArgTransformer& DependencyProvider::getArgTransformer() { return argTransformer; }
+WebRequestTransformer& DependencyProvider::getWebRequestTransformer() {return webRequestTransformer; }
+
+// Managers
+CommandHistoryManager& DependencyProvider::getCommandHistoryManager() { return commandHistoryManager ;}
+
+// Selectors
+HorizontalSelector& DependencyProvider::getHorizontalSelector() { return horizontalSelector ;}
+
+// Config
+TerminalTypeConfigurator& DependencyProvider::getTerminalTypeConfigurator() { return terminalTypeConfigurator ;}
diff --git a/src/Providers/DependencyProvider.h b/src/Providers/DependencyProvider.h
new file mode 100644
index 00000000..90537fff
--- /dev/null
+++ b/src/Providers/DependencyProvider.h
@@ -0,0 +1,160 @@
+#pragma once
+
+/*
+The DependencyProvider is responsible for creating, holding,
+and injecting shared instances of core components
+(such as services, controllers, etc) throughout the application.
+*/
+
+#include "Views/ITerminalView.h"
+#include "Views/IDeviceView.h"
+#include "Inputs/IInput.h"
+#include "Services/SdService.h"
+#include "Services/NvsService.h"
+#include "Services/LedService.h"
+#include "Services/UartService.h"
+#include "Services/I2cService.h"
+#include "Services/OneWireService.h"
+#include "Services/InfraredService.h"
+#include "Services/UsbService.h"
+#include "Services/HdUartService.h"
+#include "Services/SpiService.h"
+#include "Services/PinService.h"
+#include "Services/BluetoothService.h"
+#include "Services/WifiService.h"
+#include "Controllers/UartController.h"
+#include "Controllers/I2cController.h"
+#include "Controllers/OneWireController.h"
+#include "Controllers/UtilityController.h"
+#include "Controllers/UsbController.h"
+#include "Controllers/HdUartController.h"
+#include "Controllers/JtagController.h"
+#include "Controllers/SpiController.h"
+#include "Controllers/TwoWireController.h"
+#include "Controllers/ThreeWireController.h"
+#include "Controllers/InfraredController.h"
+#include "Controllers/DioController.h"
+#include "Controllers/LedController.h"
+#include "Controllers/BluetoothController.h"
+#include "Controllers/WifiController.h"
+#include "Transformers/TerminalCommandTransformer.h"
+#include "Transformers/InstructionTransformer.h"
+#include "Transformers/ArgTransformer.h"
+#include "Transformers/WebRequestTransformer.h"
+#include "Managers/CommandHistoryManager.h"
+#include "Config/TerminalTypeConfigurator.h"
+
+
+class DependencyProvider {
+public:
+ DependencyProvider(ITerminalView& terminalView, IDeviceView& deviceView,
+ IInput& terminalInput, IInput& deviceInput);
+
+ // Core Components
+ ITerminalView& getTerminalView();
+ void setTerminalView(ITerminalView& view);
+ IDeviceView& getDeviceView();
+ IInput& getTerminalInput();
+ IInput& getDeviceInput();
+
+ // Services
+ SdService& getSdService();
+ NvsService& getNvsService();
+ LedService& getLedService();
+ UartService& getUartService();
+ I2cService& getI2cService();
+ OneWireService& getOneWireService();
+ InfraredService& getInfraredService();
+ UsbService& getUsbService();
+ SpiService& getSpiService();
+ HdUartService& getHdUartService();
+ PinService& getPinService();
+ BluetoothService& getBluetoothService();
+ WifiService& getWifiService();
+
+ // Controllers
+ UartController& getUartController();
+ I2cController& getI2cController();
+ UtilityController& getUtilityController();
+ OneWireController& getOneWireController();
+ InfraredController& getInfraredController();
+ UsbController& getUsbController();
+ HdUartController& getHdUartController();
+ SpiController& getSpiController();
+ JtagController& getJtagController();
+ TwoWireController& getTwoWireController();
+ ThreeWireController& getThreeWireController();
+ DioController& getDioController();
+ LedController& getLedController();
+ BluetoothController& getBluetoothController();
+ WifiController& getWifiController();
+
+ // Transformers
+ TerminalCommandTransformer& getCommandTransformer();
+ InstructionTransformer& getInstructionTransformer();
+ ArgTransformer& getArgTransformer();
+ WebRequestTransformer& getWebRequestTransformer();
+
+ // Managers
+ CommandHistoryManager& getCommandHistoryManager();
+
+ // Selectors
+ HorizontalSelector& getHorizontalSelector();
+
+ // Config
+ TerminalTypeConfigurator& getTerminalTypeConfigurator();
+
+private:
+ // Core Components
+ ITerminalView& terminalView;
+ IDeviceView& deviceView;
+ IInput& terminalInput;
+ IInput& deviceInput;
+
+ // Services
+ SdService sdService;
+ NvsService nvsService;
+ LedService ledService;
+ UartService uartService;
+ I2cService i2cService;
+ OneWireService oneWireService;
+ InfraredService infraredService;
+ UsbService usbService;
+ HdUartService hdUartService;
+ SpiService spiService;
+ PinService pinService;
+ WifiService wifiService;
+ BluetoothService bluetoothService;
+
+ // Controllers
+ UartController uartController;
+ I2cController i2cController;
+ OneWireController oneWireController;
+ UtilityController utilityController;
+ InfraredController infraredController;
+ UsbController usbController;
+ HdUartController hdUartController;
+ SpiController spiController;
+ JtagController jtagController;
+ TwoWireController twoWireController;
+ ThreeWireController threeWireController;
+ DioController dioController;
+ LedController ledController;
+ WifiController wifiController;
+ BluetoothController bluetoothController;
+
+ // Transformers
+ TerminalCommandTransformer commandTransformer;
+ InstructionTransformer instructionTransformer;
+ ArgTransformer argTransformer;
+ WebRequestTransformer webRequestTransformer;
+
+ // Managers
+ CommandHistoryManager commandHistoryManager;
+
+ // Selectors
+ HorizontalSelector horizontalSelector;
+
+ // Config
+ TerminalTypeConfigurator terminalTypeConfigurator;
+};
\ No newline at end of file
diff --git a/src/Selectors/HorizontalSelector.cpp b/src/Selectors/HorizontalSelector.cpp
new file mode 100644
index 00000000..8220ebd4
--- /dev/null
+++ b/src/Selectors/HorizontalSelector.cpp
@@ -0,0 +1,40 @@
+#include "HorizontalSelector.h"
+
+HorizontalSelector::HorizontalSelector(IDeviceView& display, IInput& input)
+ : display(display), input(input) {}
+
+int HorizontalSelector::select(
+ const std::string& title,
+ const std::vector<std::string>& options,
+ const std::string& description1,
+ const std::string& description2) {
+
+ int currentIndex = 0;
+ int lastIndex = -1;
+
+ display.topBar(title, false, false);
+
+ while (true) {
+ if (lastIndex != currentIndex) {
+ display.horizontalSelection(options, currentIndex, description1, description2);
+ lastIndex = currentIndex;
+ }
+
+ char key = input.handler();
+
+ switch (key) {
+ case KEY_ARROW_LEFT:
+ currentIndex = (currentIndex > 0) ? currentIndex - 1 : options.size() - 1;
+ break;
+ case KEY_ARROW_RIGHT:
+ currentIndex = (currentIndex < options.size() - 1) ? currentIndex + 1 : 0;
+ break;
+ case KEY_OK:
+ return currentIndex;
+ case KEY_ESC_CUSTOM:
+ return -1;
+ default:
+ break;
+ }
+ }
+}
diff --git a/src/Selectors/HorizontalSelector.h b/src/Selectors/HorizontalSelector.h
new file mode 100644
index 00000000..94c2849b
--- /dev/null
+++ b/src/Selectors/HorizontalSelector.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include <string>
+#include <vector>
+#include "Views/IDeviceView.h"
+#include "Inputs/IInput.h"
+#include "Inputs/CardputerInput.h"
+
+class HorizontalSelector {
+public:
+ HorizontalSelector(IDeviceView& display, IInput& input);
+
+ int select(
+ const std::string& title,
+ const std::vector<std::string>& options,
+ const std::string& description1 = "",
+ const std::string& description2 = ""
+ );
+
+private:
+ IDeviceView& display;
+ IInput& input;
+};
diff --git a/src/Servers/HttpServer.cpp b/src/Servers/HttpServer.cpp
new file mode 100644
index 00000000..22b3f03d
--- /dev/null
+++ b/src/Servers/HttpServer.cpp
@@ -0,0 +1,76 @@
+#include "HttpServer.h"
+
+
+HttpServer::HttpServer(httpd_handle_t sharedServer)
+ : server(sharedServer) {}
+
+
+void HttpServer::begin() {
+ httpd_config_t config = HTTPD_DEFAULT_CONFIG();
+ config.server_port = 80;
+
+ if (httpd_start(&server, &config) == ESP_OK) {
+ setupRoutes();
+ }
+}
+
+void HttpServer::setupRoutes() {
+ // Page HTML
+ static httpd_uri_t root_uri;
+ root_uri.uri = "/";
+ root_uri.method = HTTP_GET;
+ root_uri.handler = [](httpd_req_t *req) -> esp_err_t {
+ HttpServer* self = static_cast<HttpServer*>(req->user_ctx);
+ return self->handleRootRequest(req);
+ };
+ root_uri.user_ctx = this;
+ httpd_register_uri_handler(server, &root_uri);
+
+ // CSS
+ static httpd_uri_t css_uri;
+ css_uri.uri = "/style.css";
+ css_uri.method = HTTP_GET;
+ css_uri.handler = [](httpd_req_t *req) -> esp_err_t {
+ HttpServer* self = static_cast<HttpServer*>(req->user_ctx);
+ return self->handleCssRequest(req);
+ };
+ css_uri.user_ctx = this;
+ httpd_register_uri_handler(server, &css_uri);
+
+ // JavaScript
+ static httpd_uri_t js_uri;
+ js_uri.uri = "/scripts.js";
+ js_uri.method = HTTP_GET;
+ js_uri.handler = [](httpd_req_t *req) -> esp_err_t {
+ HttpServer* self = static_cast<HttpServer*>(req->user_ctx);
+ return self->handleJsRequest(req);
+ };
+ js_uri.user_ctx = this;
+ httpd_register_uri_handler(server, &js_uri);
+
+ // Route test ping
+ static httpd_uri_t ping_uri;
+ ping_uri.uri = "/ping";
+ ping_uri.method = HTTP_GET;
+ ping_uri.handler = [](httpd_req_t *req) -> esp_err_t {
+ return httpd_resp_send(req, "pong", HTTPD_RESP_USE_STRLEN);
+ };
+ ping_uri.user_ctx = nullptr;
+ httpd_register_uri_handler(server, &ping_uri);
+
+}
+
+esp_err_t HttpServer::handleRootRequest(httpd_req_t *req) {
+ httpd_resp_set_type(req, "text/html");
+ return httpd_resp_send(req, (const char*)index_html, strlen((const char*)index_html));
+}
+
+esp_err_t HttpServer::handleCssRequest(httpd_req_t *req) {
+ httpd_resp_set_type(req, "text/css");
+ return httpd_resp_send(req, (const char*)style_css, strlen((const char*)style_css));
+}
+
+esp_err_t HttpServer::handleJsRequest(httpd_req_t *req) {
+ httpd_resp_set_type(req, "application/javascript");
+ return httpd_resp_send(req, (const char*)scripts_js, strlen((const char*)scripts_js));
+}
\ No newline at end of file
diff --git a/src/Servers/HttpServer.h b/src/Servers/HttpServer.h
new file mode 100644
index 00000000..5ec560d3
--- /dev/null
+++ b/src/Servers/HttpServer.h
@@ -0,0 +1,22 @@
+#pragma once
+
+#include <Arduino.h>
+#include <cstring>
+#include <string>
+#include <esp_http_server.h>
+#include "../webui/index.h"
+#include "../webui/scripts.h"
+#include "../webui/style.h"
+
+class HttpServer {
+public:
+ HttpServer(httpd_handle_t sharedServer);
+ void begin();
+ void setupRoutes();
+
+private:
+ httpd_handle_t server;
+ esp_err_t handleRootRequest(httpd_req_t *req);
+ esp_err_t handleCssRequest(httpd_req_t *req);
+ esp_err_t handleJsRequest(httpd_req_t *req);
+};
diff --git a/src/Servers/WebSocketServer.cpp b/src/Servers/WebSocketServer.cpp
new file mode 100644
index 00000000..0e1e663d
--- /dev/null
+++ b/src/Servers/WebSocketServer.cpp
@@ -0,0 +1,104 @@
+#include "WebSocketServer.h"
+#include <esp_log.h>
+#include <esp_http_server.h>
+#include <cstring>
+
+static const char* TAG = "WebSocketServer";
+
+WebSocketServer::WebSocketServer(httpd_handle_t sharedServer)
+ : server(sharedServer) {}
+
+void WebSocketServer::setupRoutes() {
+ static httpd_uri_t ws_uri = {
+ .uri = "/ws",
+ .method = HTTP_GET,
+ .handler = WebSocketServer::wsHandler,
+ .user_ctx = this,
+ .is_websocket = true
+ };
+
+ httpd_register_uri_handler(server, &ws_uri);
+}
+
+
+void WebSocketServer::begin() {
+ httpd_config_t config = HTTPD_DEFAULT_CONFIG();
+ config.server_port = 80;
+
+ if (httpd_start(&server, &config) == ESP_OK) {
+ setupRoutes();
+ }
+}
+
+esp_err_t WebSocketServer::wsHandler(httpd_req_t *req) {
+ WebSocketServer* self = static_cast<WebSocketServer*>(req->user_ctx);
+
+ if (req->method == HTTP_GET) {
+ clientFd = httpd_req_to_sockfd(req); // Capture le socket client
+ return ESP_OK;
+ }
+
+
+ httpd_ws_frame_t frame = {};
+ frame.type = HTTPD_WS_TYPE_TEXT;
+ frame.payload = nullptr;
+
+ esp_err_t ret = httpd_ws_recv_frame(req, &frame, 0);
+ if (ret != ESP_OK) {
+ return ret;
+ }
+
+ frame.payload = (uint8_t*)malloc(frame.len + 1);
+ if (!frame.payload) return ESP_ERR_NO_MEM;
+
+ ret = httpd_ws_recv_frame(req, &frame, frame.len);
+ if (ret != ESP_OK) {
+ free(frame.payload);
+ return ret;
+ }
+ frame.payload[frame.len] = '\0';
+
+ // Push chars one by one into buffer
+ for (size_t i = 0; i < frame.len; ++i) {
+ self->buffer.push_back(((char*)frame.payload)[i]);
+ }
+
+ free(frame.payload);
+ return ESP_OK;
+}
+
+char WebSocketServer::readCharBlocking() {
+ while (buffer.empty()) {
+ delay(10);
+ }
+ char c = buffer.front();
+ buffer.pop_front();
+ return c;
+}
+
+char WebSocketServer::readCharNonBlocking() {
+ const unsigned long timeout = millis() + 20; // some time for websocket
+
+ while (buffer.empty() && millis() < timeout) {
+ delay(1); // laisse tourner la loop
+ }
+
+ if (buffer.empty()) return KEY_NONE;
+
+ char c = buffer.front();
+ buffer.pop_front();
+
+ return c;
+}
+
+void WebSocketServer::sendText(const std::string& msg) {
+ if (clientFd < 0) return;
+
+ httpd_ws_frame_t ws_pkt;
+ memset(&ws_pkt, 0, sizeof(ws_pkt));
+ ws_pkt.type = HTTPD_WS_TYPE_TEXT;
+ ws_pkt.payload = (uint8_t*) msg.c_str();
+ ws_pkt.len = msg.length();
+
+ esp_err_t ret = httpd_ws_send_frame_async(server, clientFd, &ws_pkt);
+}
diff --git a/src/Servers/WebSocketServer.h b/src/Servers/WebSocketServer.h
new file mode 100644
index 00000000..3b28d27e
--- /dev/null
+++ b/src/Servers/WebSocketServer.h
@@ -0,0 +1,25 @@
+#pragma once
+#include <deque>
+#include <esp_http_server.h>
+#include <vector>
+#include <string>
+#include <Inputs/InputKeys.h>
+#include <Arduino.h>
+#include <M5Cardputer.h>
+
+class WebSocketServer {
+public:
+ WebSocketServer(httpd_handle_t sharedServer);
+ void begin();
+ void setupRoutes();
+
+ char readCharBlocking();
+ char readCharNonBlocking();
+ void sendText(const std::string& msg);
+
+private:
+ static esp_err_t wsHandler(httpd_req_t *req);
+ httpd_handle_t server;
+ static inline std::deque<char> buffer;
+ static inline int clientFd = -1;
+};
diff --git a/src/Services/BluetoothService.cpp b/src/Services/BluetoothService.cpp
new file mode 100644
index 00000000..592eab02
--- /dev/null
+++ b/src/Services/BluetoothService.cpp
@@ -0,0 +1,318 @@
+#include "BluetoothService.h"
+
+class BluetoothServerCallbacks : public BLEServerCallbacks {
+private:
+ BluetoothService& service;
+
+public:
+ BluetoothServerCallbacks(BluetoothService& svc) : service(svc) {}
+
+ void onConnect(BLEServer* pServer) override {
+ service.onConnect();
+ }
+
+ void onDisconnect(BLEServer* pServer) override {
+ service.onDisconnect();
+ pServer->startAdvertising();
+ }
+};
+
+void BluetoothService::begin(const std::string& deviceName) {
+ end();
+ delay(200);
+ BLEDevice::init(deviceName);
+ BLEServer* server = BLEDevice::createServer();
+ server->setCallbacks(new BluetoothServerCallbacks(*this));
+
+ hid = new BLEHIDDevice(server);
+ mouseInput = hid->inputReport(1);
+ keyboardInput = hid->inputReport(2);
+
+ hid->manufacturer()->setValue("M5Stack");
+ hid->pnp(0x02, 0x1234, 0x5678, 0x0100);
+ hid->hidInfo(0x00, 0x01);
+ hid->reportMap((uint8_t*)HID_REPORT_MAP, 117);
+ hid->startServices();
+
+ BLEAdvertising* advertising = server->getAdvertising();
+ advertising->addServiceUUID(hid->hidService()->getUUID());
+ advertising->start();
+
+ BLESecurity* security = new BLESecurity();
+ security->setAuthenticationMode(ESP_LE_AUTH_BOND);
+ security->setCapability(ESP_IO_CAP_NONE);
+ security->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);
+ mode = BluetoothMode::SERVER;
+ connected = true;
+}
+
+void BluetoothService::end() {
+ if (hid) {
+ delete hid;
+ hid = nullptr;
+ }
+
+ mouseInput = nullptr;
+ keyboardInput = nullptr;
+
+ if (BLEDevice::getInitialized()) {
+ BLEDevice::deinit();
+ delay(100);
+ }
+
+
+ connected = false;
+ mode = BluetoothMode::NONE;
+}
+
+void BluetoothService::onConnect() {
+ connected = true;
+}
+
+void BluetoothService::onDisconnect() {
+ connected = false;
+}
+
+bool BluetoothService::isConnected() const {
+ return connected;
+}
+
+void BluetoothService::mouseMove(int16_t x, int16_t y) {
+ if (mode != BluetoothMode::SERVER) return;
+ if (!connected || !mouseInput) return;
+ sendMouseReport(x, y, 0x0);
+}
+
+void BluetoothService::sendKeyboardReport(uint8_t modifier, const std::array<uint8_t, 6>& keys) {
+ if (mode != BluetoothMode::SERVER) return;
+ if (!connected || !keyboardInput) return;
+ uint8_t report[8] = {modifier, 0, keys[0], keys[1], keys[2], keys[3], keys[4], keys[5]};
+ keyboardInput->setValue(report, sizeof(report));
+ keyboardInput->notify();
+}
+
+void BluetoothService::sendKeyboardText(const std::string& text) {
+ if (mode != BluetoothMode::SERVER) return;
+ if (!connected || !keyboardInput) return;
+
+ for (char c : text) {
+ if (c < 0 || c > 127) continue;
+
+ AsciiHid entry = asciiHid[(uint8_t)c];
+ if (entry.keycode == 0) continue;
+
+ uint8_t modifier = entry.requiresShift ? 0x02 : 0x00; // Shift
+
+ std::array<uint8_t, 6> keys = {0};
+ keys[0] = entry.keycode;
+
+ sendKeyboardReport(modifier, keys);
+ delay(10);
+
+ std::array<uint8_t, 6> emptyKeys = {0};
+ sendKeyboardReport(0, emptyKeys);
+ delay(10);
+ }
+}
+
+std::string BluetoothService::getMacAddress() {
+ uint8_t mac[6];
+ if (esp_read_mac(mac, ESP_MAC_BT) != ESP_OK) {
+ return "Unavailable";
+ }
+
+ char macStr[18];
+ snprintf(macStr, sizeof(macStr), "%02X:%02X:%02X:%02X:%02X:%02X",
+ mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
+
+ return std::string(macStr);
+}
+
+void BluetoothService::sendEmptyReports() {
+ if (mode != BluetoothMode::SERVER) return;
+ if (mouseInput) {
+ uint8_t emptyMouseReport[4] = {0, 0, 0, 0};
+ mouseInput->setValue(emptyMouseReport, sizeof(emptyMouseReport));
+ mouseInput->notify();
+ }
+ if (keyboardInput) {
+ uint8_t emptyKeyboardReport[8] = {0};
+ keyboardInput->setValue(emptyKeyboardReport, sizeof(emptyKeyboardReport));
+ keyboardInput->notify();
+ }
+}
+
+void BluetoothService::pairWithAddress(const std::string& addrStr) {
+ BLEAddress addr(addrStr);
+ BLEDevice::whiteListAdd(addr); // Optionnel ?
+}
+
+void BluetoothService::sendMouseReport(int16_t x, int16_t y, uint8_t buttons) {
+ if (mode != BluetoothMode::SERVER) return;
+ if (!connected || !mouseInput) return;
+ uint8_t report[4] = {buttons, (uint8_t)x, (uint8_t)y, 0};
+ mouseInput->setValue(report, sizeof(report));
+ mouseInput->notify();
+}
+
+void BluetoothService::clickMouse() {
+ sendMouseReport(0, 0, 0x01); // Left click
+ delay(50);
+ sendMouseReport(0, 0, 0x00); // Release
+}
+
+std::vector<ScannedDevice> BluetoothService::scanDevices(int seconds) {
+ auto scan = BLEDevice::getScan();
+ scan->setActiveScan(true);
+
+ auto results = scan->start(seconds);
+ std::vector<ScannedDevice> devices;
+
+ for (int i = 0; i < results.getCount(); ++i) {
+ BLEAdvertisedDevice device = results.getDevice(i);
+ devices.push_back({
+ device.getName().empty() ? "(unknown)" : device.getName(),
+ device.getAddress().toString(),
+ device.getRSSI()
+ });
+ }
+
+ scan->clearResults();
+ return devices;
+}
+
+std::vector<std::string> BluetoothService::connectTo(const std::string& addr) {
+ std::vector<std::string> serviceUUIDs;
+
+ if (mode != BluetoothMode::CLIENT) {
+ BLEDevice::init("BLE-Client");
+ mode = BluetoothMode::CLIENT;
+ }
+
+ BLEAddress address(addr);
+ BLEClient* client = BLEDevice::createClient();
+
+ if (!client->connect(address)) {
+ return serviceUUIDs;
+ }
+
+ auto* services = client->getServices();
+ if (services) {
+ for (const auto& pair : *services) {
+ serviceUUIDs.push_back(pair.first);
+ }
+ }
+
+ client->disconnect();
+ return serviceUUIDs;
+}
+
+void BluetoothService::init(const std::string& deviceName) {
+ if (mode == BluetoothMode::CLIENT && BLEDevice::getInitialized()) {
+ // Already init
+ return;
+ }
+
+ BLEDevice::init(deviceName);
+ mode = BluetoothMode::CLIENT;
+}
+
+BluetoothMode BluetoothService::getMode() {
+ return mode;
+}
+
+bool BluetoothService::spoofMacAddress(const std::string& macStr) {
+ if (BLEDevice::getInitialized()) {
+ return false;
+ }
+
+ esp_bd_addr_t addr;
+ int values[6];
+
+ if (sscanf(macStr.c_str(), "%x:%x:%x:%x:%x:%x",
+ &values[0], &values[1], &values[2],
+ &values[3], &values[4], &values[5]) != 6) {
+ return false; // invalide
+ }
+
+ for (int i = 0; i < 6; i++) {
+ if (values[i] < 0 || values[i] > 0xFF) {
+ return false; // out of range
+ }
+ addr[i] = static_cast<uint8_t>(values[i] & 0xFF); // secure
+ }
+
+ // for some reason the last byte is always inc by 1 when set
+ if (addr[5] != 0x00) {
+ addr[5] -= 1;
+ }
+
+ esp_err_t err = esp_base_mac_addr_set(addr);
+ return err == ESP_OK;
+}
+
+const uint8_t BluetoothService::HID_REPORT_MAP[] = {
+ // Mouse report
+ 0x05, 0x01, // Usage Page (Generic Desktop)
+ 0x09, 0x02, // Usage (Mouse)
+ 0xA1, 0x01, // Collection (Application)
+ 0x09, 0x01, // Usage (Pointer)
+ 0xA1, 0x00, // Collection (Physical)
+ 0x85, 0x01, // Report ID (1)
+ 0x05, 0x09, // Usage Page (Button)
+ 0x19, 0x01, // Usage Minimum (0x01)
+ 0x29, 0x03, // Usage Maximum (0x03)
+ 0x15, 0x00, // Logical Minimum (0)
+ 0x25, 0x01, // Logical Maximum (1)
+ 0x95, 0x03, // Report Count (3)
+ 0x75, 0x01, // Report Size (1)
+ 0x81, 0x02, // Input (Data,Var,Abs)
+ 0x95, 0x01, // Report Count (1)
+ 0x75, 0x05, // Report Size (5)
+ 0x81, 0x01, // Input (Cnst,Var,Abs)
+ 0x05, 0x01, // Usage Page (Generic Desktop)
+ 0x09, 0x30, // Usage (X)
+ 0x09, 0x31, // Usage (Y)
+ 0x15, 0x81, // Logical Minimum (-127)
+ 0x25, 0x7F, // Logical Maximum (127)
+ 0x75, 0x08, // Report Size (8)
+ 0x95, 0x02, // Report Count (2)
+ 0x81, 0x06, // Input (Data,Var,Rel)
+ 0xC0, // End Collection
+ 0xC0, // End Collection
+
+ // Keyboard report
+ 0x05, 0x01, // Usage Page (Generic Desktop)
+ 0x09, 0x06, // Usage (Keyboard)
+ 0xA1, 0x01, // Collection (Application)
+ 0x85, 0x02, // Report ID (2)
+ 0x05, 0x07, // Usage Page (Key Codes)
+ 0x19, 0xE0, // Usage Minimum (224)
+ 0x29, 0xE7, // Usage Maximum (231)
+ 0x15, 0x00, // Logical Minimum (0)
+ 0x25, 0x01, // Logical Maximum (1)
+ 0x75, 0x01, // Report Size (1)
+ 0x95, 0x08, // Report Count (8)
+ 0x81, 0x02, // Input (Data,Var,Abs)
+ 0x95, 0x01, // Report Count (1)
+ 0x75, 0x08, // Report Size (8)
+ 0x81, 0x01, // Input (Cnst,Var,Abs)
+ 0x95, 0x05, // Report Count (5)
+ 0x75, 0x01, // Report Size (1)
+ 0x05, 0x08, // Usage Page (LEDs)
+ 0x19, 0x01, // Usage Minimum (1)
+ 0x29, 0x05, // Usage Maximum (5)
+ 0x91, 0x02, // Output (Data,Var,Abs)
+ 0x95, 0x01, // Report Count (1)
+ 0x75, 0x03, // Report Size (3)
+ 0x91, 0x01, // Output (Cnst,Var,Abs)
+ 0x95, 0x06, // Report Count (6)
+ 0x75, 0x08, // Report Size (8)
+ 0x15, 0x00, // Logical Minimum (0)
+ 0x25, 0x65, // Logical Maximum (101)
+ 0x05, 0x07, // Usage Page (Key Codes)
+ 0x19, 0x00, // Usage Minimum (0)
+ 0x29, 0x65, // Usage Maximum (101)
+ 0x81, 0x00, // Input (Data,Array)
+ 0xC0 // End Collection
+};
\ No newline at end of file
diff --git a/src/Services/BluetoothService.h b/src/Services/BluetoothService.h
new file mode 100644
index 00000000..18af8647
--- /dev/null
+++ b/src/Services/BluetoothService.h
@@ -0,0 +1,67 @@
+#pragma once
+
+#include <Arduino.h>
+#include <BLEDevice.h>
+#include <BLEUtils.h>
+#include <BLEServer.h>
+#include "BLEHIDDevice.h"
+#include "HIDTypes.h"
+#include "Data/AsciiHid.h"
+// #include <esp_system.h> // pour esp_read_mac
+// #include <esp_mac.h> // pour ESP_MAC_BT
+
+enum class BluetoothMode {
+ NONE,
+ SERVER,
+ CLIENT
+};
+
+struct ScannedDevice {
+ std::string name;
+ std::string address;
+ int rssi;
+};
+
+class BluetoothService {
+private:
+ BLEHIDDevice* hid = nullptr;
+ BLECharacteristic* mouseInput = nullptr;
+ BLECharacteristic* keyboardInput = nullptr;
+ bool connected = false;
+ static const uint8_t HID_REPORT_MAP[];
+ BluetoothMode mode = BluetoothMode::NONE;
+public:
+ // begin / end server BT
+ void begin(const std::string& deviceName = "Bus-Pirate-Blueooth");
+ void end();
+
+ // Init client
+ void init(const std::string& deviceName = "Bus-Pirate-Bluetooth");
+
+ // Pair as client
+ void pairWithAddress(const std::string& addrStr); // pair <addr>
+
+ // Connexion
+ void onConnect();
+ void onDisconnect();
+ bool isConnected() const;
+
+ // HID – Kb
+ void sendKeyboardText(const std::string& text);
+ void sendKeyboardReport(uint8_t modifier, const std::array<uint8_t, 6>& keys);
+
+ // HID – Mouse
+ void mouseMove(int16_t x, int16_t y);
+ void clickMouse(); // Simule un clic
+ void sendMouseReport(int16_t x, int16_t y, uint8_t buttons);
+
+ // Utils
+ void sendEmptyReports();
+ bool spoofMacAddress(const std::string& macStr);
+ std::string getMacAddress();
+ BluetoothMode getMode();
+
+ std::vector<ScannedDevice> scanDevices(int seconds = 10);
+ std::vector<std::string> connectTo(const std::string& addr);
+};
+
diff --git a/src/Services/HdUartService.cpp b/src/Services/HdUartService.cpp
new file mode 100644
index 00000000..391b7fee
--- /dev/null
+++ b/src/Services/HdUartService.cpp
@@ -0,0 +1,86 @@
+#include "HdUartService.h"
+
+void HdUartService::configure(unsigned long baud, uint32_t config, uint8_t pin, bool inverted) {
+ ioPin = pin;
+ baudRate = baud;
+ serialConfig = config;
+ isInverted = inverted;
+
+ Serial1.end();
+ Serial1.begin(baudRate, serialConfig, ioPin, ioPin, isInverted); // meme pin RX/TX
+}
+
+void HdUartService::switchToWrite() {
+ pinMode(ioPin, OUTPUT);
+ delayMicroseconds(10);
+}
+
+void HdUartService::switchToRead() {
+ pinMode(ioPin, INPUT);
+ delayMicroseconds(10);
+}
+
+void HdUartService::write(uint8_t data) {
+ switchToWrite();
+ Serial1.write(data);
+ Serial1.flush();
+ switchToRead();
+}
+
+void HdUartService::write(const std::string& str) {
+ switchToWrite();
+ Serial1.write(reinterpret_cast<const uint8_t*>(str.c_str()), str.length());
+ Serial1.flush();
+ switchToRead();
+}
+
+bool HdUartService::available() const {
+ return Serial1.available();
+}
+
+char HdUartService::read() {
+ return Serial1.read();
+}
+
+std::string HdUartService::executeByteCode(const std::vector<ByteCode>& bytecodes) {
+ std::string result;
+ uint32_t timeout = 2000;
+ uint32_t received = 0;
+ uint32_t start;
+
+ for (const ByteCode& code : bytecodes) {
+ switch (code.getCommand()) {
+ case ByteCodeEnum::Write:
+ for (uint32_t i = 0; i < code.getRepeat(); ++i) {
+ write(code.getData());
+ }
+ break;
+
+ case ByteCodeEnum::Read:
+ start = millis();
+ while (received < code.getRepeat() && (millis() - start < timeout)) {
+ if (available()) {
+ char c = read();
+ result += c;
+ received++;
+ } else {
+ delay(10);
+ }
+ }
+ break;
+
+ case ByteCodeEnum::DelayMs:
+ delay(code.getRepeat());
+ break;
+
+ case ByteCodeEnum::DelayUs:
+ delayMicroseconds(code.getRepeat());
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ return result;
+}
diff --git a/src/Services/HdUartService.h b/src/Services/HdUartService.h
new file mode 100644
index 00000000..53bed065
--- /dev/null
+++ b/src/Services/HdUartService.h
@@ -0,0 +1,25 @@
+#pragma once
+
+#include <vector>
+#include "Models/ByteCode.h"
+#include <Arduino.h>
+class HdUartService {
+public:
+ void configure(unsigned long baud, uint32_t config, uint8_t pin, bool inverted);
+ void write(uint8_t data);
+ void write(const std::string& str);
+ bool available() const;
+ char read();
+ std::string readLine();
+ std::string executeByteCode(const std::vector<ByteCode>& bytecodes);
+ void flush();
+
+private:
+ uint8_t ioPin;
+ unsigned long baudRate;
+ uint32_t serialConfig;
+ bool isInverted;
+
+ void switchToRead();
+ void switchToWrite();
+};
diff --git a/src/Services/I2cService.cpp b/src/Services/I2cService.cpp
new file mode 100644
index 00000000..b25d0421
--- /dev/null
+++ b/src/Services/I2cService.cpp
@@ -0,0 +1,112 @@
+#include "I2cService.h"
+
+void I2cService::configure(uint8_t sda, uint8_t scl, uint32_t frequency) {
+ Wire.end();
+ Wire.begin(sda, scl, frequency);
+}
+
+void I2cService::beginTransmission(uint8_t address) {
+ Wire.beginTransmission(address);
+}
+
+void I2cService::write(uint8_t data) {
+ Wire.write(data);
+}
+
+bool I2cService::endTransmission(bool sendStop) {
+ return Wire.endTransmission(sendStop);
+}
+
+uint8_t I2cService::requestFrom(uint8_t address, uint8_t quantity, bool sendStop) {
+ return Wire.requestFrom(address, quantity, sendStop);
+}
+
+int I2cService::read() {
+ return Wire.read();
+}
+
+bool I2cService::available() const {
+ return Wire.available();
+}
+
+bool I2cService::end() const {
+ return Wire.end();
+}
+
+std::string I2cService::executeByteCode(const std::vector<ByteCode>& bytecodes) {
+ std::string result;
+ uint8_t currentAddress = 0;
+ bool transmissionStarted = false;
+ bool expectAddress = false;
+
+ for (const auto& code : bytecodes) {
+ switch (code.getCommand()) {
+ case ByteCodeEnum::Start:
+ expectAddress = true;
+ break;
+
+ case ByteCodeEnum::Stop:
+ if (transmissionStarted) {
+ Wire.endTransmission();
+ transmissionStarted = false;
+ }
+ break;
+
+ case ByteCodeEnum::Write:
+ if (expectAddress) {
+ currentAddress = code.getData();
+ Wire.beginTransmission(currentAddress);
+ transmissionStarted = true;
+ expectAddress = false;
+ } else {
+ if (!transmissionStarted) {
+ Wire.beginTransmission(currentAddress);
+ transmissionStarted = true;
+ }
+ for (uint32_t i = 0; i < code.getRepeat(); ++i) {
+ Wire.write(code.getData());
+ }
+ }
+ break;
+
+ case ByteCodeEnum::Read: {
+ if (transmissionStarted) {
+ Wire.endTransmission(false); // release bus
+ transmissionStarted = false;
+ }
+
+ uint8_t toRead = code.getRepeat();
+ uint8_t readAddr = currentAddress;
+
+ Wire.requestFrom(readAddr, toRead);
+
+ for (uint8_t i = 0; i < toRead && Wire.available(); ++i) {
+ uint8_t val = Wire.read();
+ char hex[5];
+ snprintf(hex, sizeof(hex), "%02X ", val);
+ result += hex;
+ }
+ break;
+ }
+
+ case ByteCodeEnum::DelayMs:
+ delay(code.getRepeat());
+ break;
+
+ case ByteCodeEnum::DelayUs:
+ delayMicroseconds(code.getRepeat());
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ // If no end stop
+ if (transmissionStarted) {
+ Wire.endTransmission();
+ }
+
+ return result;
+}
+
diff --git a/src/Services/I2cService.h b/src/Services/I2cService.h
new file mode 100644
index 00000000..0ecd1614
--- /dev/null
+++ b/src/Services/I2cService.h
@@ -0,0 +1,22 @@
+#pragma once
+
+#include <Arduino.h>
+#include <Wire.h>
+#include <vector>
+#include "Models/ByteCode.h"
+
+class I2cService {
+public:
+ void configure(uint8_t sda, uint8_t scl, uint32_t frequency = 100000);
+
+ void beginTransmission(uint8_t address);
+ void write(uint8_t data);
+ bool endTransmission(bool sendStop = true);
+ uint8_t requestFrom(uint8_t address, uint8_t quantity, bool sendStop = true);
+
+ int read();
+ bool available() const;
+ bool end() const;
+
+ std::string executeByteCode(const std::vector<ByteCode>& bytecodes);
+};
diff --git a/src/Services/InfraredService.cpp b/src/Services/InfraredService.cpp
new file mode 100644
index 00000000..59ca398f
--- /dev/null
+++ b/src/Services/InfraredService.cpp
@@ -0,0 +1,167 @@
+#include <IRremote.hpp> // defined here to avoid conflicts
+#include "InfraredService.h"
+
+void InfraredService::configure(uint8_t tx, uint8_t rx) {
+ IrSender.begin(tx);
+ IrReceiver.begin(rx, ENABLE_LED_FEEDBACK);
+}
+
+void InfraredService::sendInfraredCommand(InfraredCommand command) {
+ uint8_t subdevice;
+ uint16_t address;
+ uint16_t vendorCode;
+ std::string protocolString = InfraredProtocolMapper::toString(command.getProtocol());
+
+ switch (command.getProtocol()) {
+ // Makehex seems to not handle Panasonic correctly, we use IRemote instead
+ case InfraredProtocolEnum::_PANASONIC:
+ case InfraredProtocolEnum::PANASONIC2: {
+ subdevice = command.getSubdevice() == -1 ? 0 : command.getSubdevice(); // -1 to 0 if needed
+
+ // Combine device and subdevice into a 16-bit integer
+ uint16_t address = (static_cast<uint16_t>(command.getSubdevice()) << 8) | command.getDevice();
+
+ // Panasonic can be used by many manufacturers in the IRDB format, we check for vendor name
+ vendorCode = getKaseikyoVendorIdCode(protocolString);
+
+ IrSender.sendKaseikyo(address, command.getFunction(), 0, vendorCode);
+ break;
+ }
+ // Same for Sony20
+ case InfraredProtocolEnum::SONY20: {
+ subdevice = command.getSubdevice() == -1 ? 0 : command.getSubdevice();
+
+ // Combine device and subdevice into a 16-bit integer
+ uint16_t address = (static_cast<uint16_t>(command.getSubdevice()) << 8) | command.getDevice();
+
+ IrSender.sendSony(address, command.getFunction(), 0, SIRCS_20_PROTOCOL);
+ break;
+ }
+ // Handle by MakeHex
+ default: {
+ int frequency = 38; // Default frequency, passed by reference to encodeRemoteCommand
+ std::vector<float> sequence = encodeRemoteCommand(command, protocolString.c_str(), frequency);
+
+ // Convert the sequence to uint16_t format as required by sendRaw
+ uint16_t raw[sequence.size()];
+ for (size_t i = 0; i < sequence.size(); ++i) {
+ raw[i] = static_cast<uint16_t>(sequence[i]);
+ }
+
+ // Send the raw generated sequence with the correct frequency
+ IrSender.sendRaw(raw, sequence.size(), frequency);
+ }
+ }
+}
+
+InfraredCommand InfraredService::receiveInfraredCommand() {
+ IrReceiver.start();
+ InfraredCommand command;
+
+ if (!IrReceiver.decode()) {
+ return command;
+ }
+
+ const IRData& data = IrReceiver.decodedIRData;
+ IrReceiver.resume();
+
+ // Ignore invalid
+ if (data.numberOfBits == 0 || data.protocol == UNKNOWN) {
+ return command;
+ }
+
+ // Mapping protocols
+ switch (data.protocol) {
+ case NEC:
+ case NEC2:
+ case ONKYO:
+ command.setProtocol(_NEC);
+ break;
+
+ case DENON:
+ command.setProtocol(_DENON);
+ break;
+
+ case APPLE:
+ command.setProtocol(_APPLE);
+ break;
+
+ case SONY:
+ command.setProtocol(SONY20);
+ break;
+
+ case JVC:
+ command.setProtocol(_JVC);
+ break;
+
+ case RC5:
+ command.setProtocol(_RC5);
+ break;
+
+ case RC6:
+ case RC6_6_20:
+ command.setProtocol(_RC6);
+ break;
+
+ case LG:
+ case LG2:
+ case SAMSUNG:
+ case SAMSUNGLG:
+ case SAMSUNG48:
+ command.setProtocol(_SAMSUNG);
+ break;
+
+ case PANASONIC:
+ case KASEIKYO:
+ case KASEIKYO_DENON:
+ case KASEIKYO_SHARP:
+ case KASEIKYO_JVC:
+ case KASEIKYO_MITSUBISHI:
+ command.setProtocol(_PANASONIC);
+ break;
+
+ default:
+ return InfraredCommand();
+ }
+
+ // Extraction device et subdevice selon protocole
+ if (data.protocol == PANASONIC || data.protocol == KASEIKYO || data.protocol == KASEIKYO_JVC ||
+ data.protocol == KASEIKYO_SHARP || data.protocol == KASEIKYO_MITSUBISHI || data.protocol == KASEIKYO_DENON) {
+ // PANASONIC: 16 bits = 8b subdevice + 8b device
+ command.setDevice((data.address >> 8) & 0xFF);
+ command.setSubdevice(data.address & 0xFF);
+ } else {
+ // que l'adresse
+ int device = data.address & 0xFF;
+ int subdevice = (data.address >> 8) & 0xFF;
+
+ // Si subdevice est 0, ignore
+ command.setDevice(device);
+ command.setSubdevice(subdevice == 0 ? -1 : subdevice);
+ }
+
+ // Commande principale
+ command.setFunction(data.command);
+
+ IrReceiver.stop();
+ return command;
+}
+
+uint16_t InfraredService::getKaseikyoVendorIdCode(const std::string& input) {
+ std::string lowerInput = input;
+ std::transform(lowerInput.begin(), lowerInput.end(), lowerInput.begin(), ::tolower);
+
+ if (lowerInput.find("panasonic") != std::string::npos) {
+ return PANASONIC_VENDOR_ID_CODE;
+ } else if (lowerInput.find("denon") != std::string::npos) {
+ return DENON_VENDOR_ID_CODE;
+ } else if (lowerInput.find("mitsubishi") != std::string::npos) {
+ return MITSUBISHI_VENDOR_ID_CODE;
+ } else if (lowerInput.find("sharp") != std::string::npos) {
+ return SHARP_VENDOR_ID_CODE;
+ } else if (lowerInput.find("jvc") != std::string::npos) {
+ return JVC_VENDOR_ID_CODE;
+ } else {
+ return PANASONIC_VENDOR_ID_CODE; // default
+ }
+}
\ No newline at end of file
diff --git a/src/Services/InfraredService.h b/src/Services/InfraredService.h
new file mode 100644
index 00000000..85d395c0
--- /dev/null
+++ b/src/Services/InfraredService.h
@@ -0,0 +1,19 @@
+#pragma once
+
+#include <vector>
+#include <Models/InfraredCommand.h>
+#include <Vendors/MakeHex.h>
+#include "Enums/InfraredProtocolEnum.h"
+#include "Data/DeviceBgoneCommands.h"
+
+class InfraredService {
+public:
+ void configure(uint8_t tx, uint8_t rx);
+ void sendInfraredCommand(InfraredCommand command);
+ InfraredCommand receiveInfraredCommand();
+private:
+ uint16_t getKaseikyoVendorIdCode(const std::string& input);
+};
+
+
+
diff --git a/src/Services/LedService.cpp b/src/Services/LedService.cpp
new file mode 100644
index 00000000..0d6a335e
--- /dev/null
+++ b/src/Services/LedService.cpp
@@ -0,0 +1,17 @@
+#include "LedService.h"
+
+void LedService::blink() {
+ showLed();
+ delay(30);
+ clearLed();
+}
+
+void LedService::showLed() {
+ FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, 1); // we use define LED_PIN Builtin for now
+ leds[0] = CRGB::OrangeRed;
+ FastLED.show();
+}
+
+void LedService::clearLed() {
+ FastLED.clear(true);
+}
\ No newline at end of file
diff --git a/src/Services/LedService.h b/src/Services/LedService.h
new file mode 100644
index 00000000..355502e2
--- /dev/null
+++ b/src/Services/LedService.h
@@ -0,0 +1,20 @@
+#ifndef LED_SERVICE_H
+#define LED_SERVICE_H
+
+#include <FastLED.h>
+#include <States/GlobalState.h>
+
+#define LED_PIN 21 // Builtin, TODO: use context
+
+class LedService {
+public:
+ void blink();
+ void showLed();
+ void clearLed();
+
+private:
+ CRGB leds[1];
+};
+
+
+#endif
diff --git a/src/Services/NvsService.cpp b/src/Services/NvsService.cpp
new file mode 100644
index 00000000..23903ebe
--- /dev/null
+++ b/src/Services/NvsService.cpp
@@ -0,0 +1,38 @@
+#include "NvsService.h"
+
+NvsService::~NvsService() {
+ preferences.end(); // Close namespace
+}
+
+void NvsService::open() {
+ // Open nvs namespace
+ preferences.begin(globalState.getNvsNamespace().c_str(), false);
+}
+
+void NvsService::close() {
+ preferences.end(); // Close namespace
+}
+
+void NvsService::saveString(const std::string& key, const std::string& value) {
+ preferences.putString(key.c_str(), value.c_str());
+}
+
+std::string NvsService::getString(const std::string& key, const std::string& defaultValue) {
+ return preferences.getString(key.c_str(), defaultValue.c_str()).c_str();
+}
+
+void NvsService::saveInt(const std::string& key, int value) {
+ preferences.putInt(key.c_str(), value);
+}
+
+int NvsService::getInt(const std::string& key, int defaultValue) {
+ return preferences.getInt(key.c_str(), defaultValue);
+}
+
+void NvsService::remove(const std::string& key) {
+ preferences.remove(key.c_str());
+}
+
+void NvsService::clearNamespace() {
+ preferences.clear();
+}
diff --git a/src/Services/NvsService.h b/src/Services/NvsService.h
new file mode 100644
index 00000000..78e88d97
--- /dev/null
+++ b/src/Services/NvsService.h
@@ -0,0 +1,33 @@
+#ifndef NVS_SERVICE_H
+#define NVS_SERVICE_H
+
+#include <Preferences.h>
+#include <string>
+#include "States/GlobalState.h"
+
+class NvsService {
+public:
+ ~NvsService();
+
+ // Open/Close namespace
+ void open();
+ void close();
+
+ // Read/write string
+ void saveString(const std::string& key, const std::string& value);
+ std::string getString(const std::string& key, const std::string& defaultValue = "");
+
+ // Read/write int
+ void saveInt(const std::string& key, int value);
+ int getInt(const std::string& key, int defaultValue = 0);
+
+ // Utils
+ void remove(const std::string& key);
+ void clearNamespace();
+
+private:
+ Preferences preferences;
+ GlobalState& globalState = GlobalState::getInstance();
+};
+
+#endif // NVS_SERVICE_H
diff --git a/src/Services/OneWireService.cpp b/src/Services/OneWireService.cpp
new file mode 100644
index 00000000..15b348ad
--- /dev/null
+++ b/src/Services/OneWireService.cpp
@@ -0,0 +1,166 @@
+// OneWireService.cpp
+
+#include "OneWireService.h"
+
+OneWireService::OneWireService() {}
+
+void OneWireService::configure(uint8_t pin) {
+ if (oneWire != nullptr) {
+ delete oneWire;
+ oneWire = nullptr;
+ }
+ oneWirePin = pin;
+ oneWire = new OneWire(pin);
+}
+
+bool OneWireService::reset() {
+ if (oneWire) return oneWire->reset();
+}
+
+void OneWireService::write(uint8_t data) {
+ if (oneWire) oneWire->write(data);
+}
+
+void OneWireService::writeBytes(const uint8_t* data, uint8_t len) {
+ if (oneWire) oneWire->write_bytes(data, len);
+}
+
+void OneWireService::writeByteRw1990(uint8_t pin, uint8_t data) {
+ int data_bit;
+ for (data_bit = 0; data_bit < 8; data_bit++) {
+ if (data & 1) {
+ digitalWrite(pin, LOW);
+ pinMode(pin, OUTPUT);
+ delayMicroseconds(60);
+ pinMode(pin, INPUT);
+ digitalWrite(pin, HIGH);
+ } else {
+ digitalWrite(pin, LOW);
+ pinMode(pin, OUTPUT);
+ pinMode(pin, INPUT);
+ digitalWrite(pin, HIGH);
+ }
+ delay(10);
+ data = data >> 1;
+ }
+}
+
+void OneWireService::writeRw1990(uint8_t pin, uint8_t* data, size_t len) {
+ if (!reset()) return;
+
+ // Prepare
+ oneWire->skip();
+ oneWire->reset();
+ oneWire->write(0x33); // Read ROM
+
+ // Write mode
+ oneWire->skip();
+ oneWire->reset();
+ oneWire->write(0x3C); // Set write mode for some models
+ delay(50);
+
+ // Write Command ?
+ oneWire->skip();
+ oneWire->reset();
+ oneWire->write(0xD1); // Write command
+ delay(50);
+
+ // Write don't work without this code
+ digitalWrite(pin, LOW);
+ pinMode(pin, OUTPUT);
+ delayMicroseconds(60);
+ pinMode(pin, INPUT);
+ digitalWrite(pin, HIGH);
+ delay(10);
+
+ oneWire->skip();
+ oneWire->reset();
+ oneWire->write(0xD5); // Enter write mode
+ delay(50);
+
+ // Write
+ for (size_t i = 0; i < len; ++i) {
+ writeByteRw1990(pin, data[i]);
+ delayMicroseconds(25);
+ }
+
+ oneWire->reset(); // Reset bus
+ oneWire->skip();
+
+ // Finalise
+ oneWire->write(0xD1); // End of write command
+ delayMicroseconds(16);
+ oneWire->reset(); // Reset bus
+}
+
+uint8_t OneWireService::read() {
+ return oneWire ? oneWire->read() : 0;
+}
+
+void OneWireService::readBytes(uint8_t* buffer, uint8_t length) {
+ oneWire->read_bytes(buffer, length);
+}
+
+void OneWireService::skip() {
+ if (oneWire) oneWire->skip();
+}
+
+void OneWireService::select(const uint8_t rom[8]) {
+ if (oneWire) oneWire->select(rom);
+}
+
+uint8_t OneWireService::crc8(const uint8_t* data, uint8_t len) {
+ if (!oneWire) return 0;
+ return OneWire::crc8(data, len);
+}
+
+std::string OneWireService::executeByteCode(const std::vector<ByteCode>& bytecodes) {
+ std::string result;
+
+ for (const auto& code : bytecodes) {
+ switch (code.getCommand()) {
+ case ByteCodeEnum::Start:
+ case ByteCodeEnum::Stop:
+ reset();
+ break;
+
+ case ByteCodeEnum::Write: {
+ uint8_t byte = static_cast<uint8_t>(code.getData());
+ oneWire->write(byte);
+ break;
+ }
+
+ case ByteCodeEnum::Read: {
+ for (uint32_t i = 0; i < code.getRepeat(); ++i) {
+ uint8_t value = read();
+ char hex[4];
+ snprintf(hex, sizeof(hex), "%02X ", value);
+ result += hex;
+ }
+ break;
+ }
+
+ case ByteCodeEnum::DelayMs:
+ delay(code.getRepeat());
+ break;
+
+ case ByteCodeEnum::DelayUs:
+ delayMicroseconds(code.getRepeat());
+ break;
+
+ default:
+ break;
+ }
+ }
+ return result;
+}
+
+void OneWireService::resetSearch() {
+ if (oneWire) oneWire->reset_search();
+}
+
+bool OneWireService::search(uint8_t* rom) {
+ if (!oneWire) return false;
+ return oneWire->search(rom);
+}
+
diff --git a/src/Services/OneWireService.h b/src/Services/OneWireService.h
new file mode 100644
index 00000000..acf30bfc
--- /dev/null
+++ b/src/Services/OneWireService.h
@@ -0,0 +1,29 @@
+#pragma once
+
+#include <OneWire.h>
+#include <vector>
+#include "Models/ByteCode.h"
+
+class OneWireService {
+public:
+ OneWireService();
+
+ void configure(uint8_t pin);
+ bool reset();
+ void write(uint8_t data);
+ void writeBytes(const uint8_t* data, uint8_t len);
+ void writeByteRw1990(uint8_t pin, uint8_t data);
+ void writeRw1990(uint8_t pin, uint8_t* data, size_t len);
+ uint8_t read();
+ void readBytes(uint8_t* buffer, uint8_t length);
+ void skip();
+ void select(const uint8_t rom[8]);
+ uint8_t crc8(const uint8_t* data, uint8_t len);
+ std::string executeByteCode(const std::vector<ByteCode>& bytecodes);
+ void resetSearch();
+ bool search(uint8_t* rom);
+
+private:
+ OneWire* oneWire = nullptr;
+ uint8_t oneWirePin = 0;
+};
diff --git a/src/Services/PinService.cpp b/src/Services/PinService.cpp
new file mode 100644
index 00000000..d1b48fb6
--- /dev/null
+++ b/src/Services/PinService.cpp
@@ -0,0 +1,39 @@
+#include "PinService.h"
+
+void PinService::setInput(uint8_t pin) {
+ pinMode(pin, INPUT);
+}
+
+void PinService::setInputPullup(uint8_t pin) {
+ pinMode(pin, INPUT_PULLUP);
+}
+
+void PinService::setOutput(uint8_t pin) {
+ pinMode(pin, OUTPUT);
+}
+
+void PinService::setHigh(uint8_t pin) {
+ setOutput(pin); // force OUTPUT
+ digitalWrite(pin, HIGH);
+}
+
+void PinService::setLow(uint8_t pin) {
+ setOutput(pin); // force OUTPUT
+ digitalWrite(pin, LOW);
+}
+
+bool PinService::read(uint8_t pin) {
+ return digitalRead(pin);
+}
+
+void PinService::togglePullup(uint8_t pin) {
+ bool enabled = pullupState[pin]; // default false if not set
+
+ if (enabled) {
+ setInput(pin);
+ pullupState[pin] = false;
+ } else {
+ setInputPullup(pin);
+ pullupState[pin] = true;
+ }
+}
diff --git a/src/Services/PinService.h b/src/Services/PinService.h
new file mode 100644
index 00000000..a265215e
--- /dev/null
+++ b/src/Services/PinService.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include <Arduino.h>
+#include <unordered_map>
+
+class PinService {
+public:
+ void setInput(uint8_t pin);
+ void setInputPullup(uint8_t pin);
+ void setOutput(uint8_t pin);
+ void setHigh(uint8_t pin);
+ void setLow(uint8_t pin);
+ bool read(uint8_t pin);
+ void togglePullup(uint8_t pin);
+
+private:
+ std::unordered_map<uint8_t, bool> pullupState; // true = INPUT_PULLUP, false = INPUT
+};
diff --git a/src/Services/SdService.cpp b/src/Services/SdService.cpp
new file mode 100644
index 00000000..ba8477ba
--- /dev/null
+++ b/src/Services/SdService.cpp
@@ -0,0 +1,226 @@
+#include "SdService.h"
+
+SdService::SdService() {}
+
+bool SdService::configure(uint8_t clkPin, uint8_t misoPin, uint8_t mosiPin, uint8_t csPin) {
+ sdCardSPI.begin(clkPin, misoPin, mosiPin, csPin);
+ delay(10);
+
+ if (!SD.begin(csPin, sdCardSPI)) {
+ sdCardMounted = false;
+ return false;
+ }
+
+ sdCardMounted = true;
+ return sdCardMounted;
+}
+
+void SdService::close() {
+ SD.end();
+ sdCardMounted = false;
+}
+
+bool SdService::isFile(const std::string& filePath) {
+ File f = SD.open(filePath.c_str());
+ if (f && !f.isDirectory()) {
+ f.close();
+ return true;
+ }
+ return false;
+}
+
+bool SdService::isDirectory(const std::string& path) {
+ File f = SD.open(path.c_str());
+ if (f && f.isDirectory()) {
+ f.close();
+ return true;
+ }
+ return false;
+}
+
+bool SdService::getSdState() {
+ return sdCardMounted;
+}
+
+std::vector<std::string> SdService::listElements(const std::string& dirPath, size_t limit) {
+ if (limit == 0) {
+ limit = 256;
+ }
+
+ std::vector<std::string> filesList;
+ std::vector<std::string> foldersList;
+
+ if (!sdCardMounted) {
+ return filesList;
+ }
+
+ File dir = SD.open(dirPath.c_str());
+ if (!dir || !dir.isDirectory()) {
+ return filesList;
+ }
+
+ File file = dir.openNextFile();
+ size_t i = 0;
+ while (file) {
+ if (file.name()[0] != '.') { // Exclude hidden files
+ if (file.isDirectory()) {
+ foldersList.push_back(file.name());
+ } else {
+ filesList.push_back(file.name());
+ }
+ i++;
+ }
+
+ if (i > limit) {
+ break;
+ }
+
+ file = dir.openNextFile();
+ }
+
+ std::sort(foldersList.begin(), foldersList.end());
+ std::sort(filesList.begin(), filesList.end());
+ foldersList.insert(foldersList.end(), filesList.begin(), filesList.end());
+
+ return foldersList;
+}
+
+std::vector<uint8_t> SdService::readBinaryFile(const std::string& filePath) {
+ std::vector<uint8_t> content;
+ if (!sdCardMounted) {
+ return content;
+ }
+
+ File file = SD.open(filePath.c_str(), FILE_READ);
+ if (file) {
+ content.reserve(file.size());
+ while (file.available()) {
+ content.push_back(file.read());
+ }
+ file.close();
+ }
+ return content;
+}
+
+std::string SdService::readFile(const std::string& filePath) {
+ std::string content;
+ if (!sdCardMounted) {
+ return content;
+ }
+
+ File file = SD.open(filePath.c_str());
+ if (file) {
+ while (file.available()) {
+ content += static_cast<char>(file.read());
+ }
+ file.close();
+ }
+ return content;
+}
+
+bool SdService::writeFile(const std::string& filePath, const std::string& data) {
+ if (!sdCardMounted) {
+ return false;
+ }
+
+ File file = SD.open(filePath.c_str(), FILE_WRITE);
+ if (file) {
+ file.write(reinterpret_cast<const uint8_t*>(data.c_str()), data.size());
+ file.close();
+ return true;
+ }
+ return false;
+}
+
+bool SdService::writeBinaryFile(const std::string& filePath, const std::vector<uint8_t>& data) {
+ if (!sdCardMounted) {
+ return false;
+ }
+
+ File file = SD.open(filePath.c_str(), FILE_WRITE);
+ if (file) {
+ file.write(data.data(), data.size());
+ file.close();
+ return true;
+ }
+ return false;
+}
+
+bool SdService::appendToFile(const std::string& filePath, const std::string& data) {
+ if (!sdCardMounted) {
+ return false;
+ }
+
+ File file = SD.open(filePath.c_str(), FILE_APPEND);
+ if (file) {
+ file.write(reinterpret_cast<const uint8_t*>(data.c_str()), data.size());
+ file.close();
+ return true;
+ }
+ return false;
+}
+
+bool SdService::deleteFile(const std::string& filePath) {
+ if (!sdCardMounted) {
+ return false;
+ }
+
+ if (SD.exists(filePath.c_str())) {
+ return SD.remove(filePath.c_str());
+ }
+ return false;
+}
+
+std::string SdService::getFileExt(const std::string& path) {
+ size_t pos = path.find_last_of('.');
+ return (pos != std::string::npos && pos < path.length() - 1) ? path.substr(pos + 1) : "";
+}
+
+std::string SdService::getParentDirectory(const std::string& path) {
+ size_t pos = path.find_last_of('/');
+ return (pos != std::string::npos && pos > 0) ? path.substr(0, pos) : "/";
+}
+
+std::vector<std::string> SdService::getCachedDirectoryElements(const std::string& path) {
+ if (cachedDirectoryElements.find(path) != cachedDirectoryElements.end()) {
+ return cachedDirectoryElements[path];
+ }
+
+ std::vector<std::string> elements = listElements(path);
+ if (elements.size() > 4) {
+ if (cachedDirectoryElements.size() >= 50) {
+ cachedDirectoryElements.erase(cachedDirectoryElements.begin());
+ }
+ cachedDirectoryElements[path] = elements;
+ }
+ return elements;
+}
+
+void SdService::setCachedDirectoryElements(const std::string& path, const std::vector<std::string>& elements) {
+ cachedDirectoryElements[path] = elements;
+}
+
+void SdService::removeCachedPath(const std::string& path) {
+ cachedDirectoryElements.erase(path);
+}
+
+std::string SdService::getFileName(const std::string& path) {
+ size_t lastSlash = path.find_last_of('/');
+ size_t lastDot = path.find_last_of('.');
+ if (lastDot == std::string::npos || lastDot < lastSlash) {
+ lastDot = path.length(); // Not ext, get end of path
+ }
+ size_t start = (lastSlash != std::string::npos) ? lastSlash + 1 : 0;
+ return path.substr(start, lastDot - start);
+}
+
+bool SdService::ensureDirectory(const std::string& directory) {
+ if (!sdCardMounted) {
+ return false;
+ }
+
+ if (!SD.exists(directory.c_str())) {
+ return SD.mkdir(directory.c_str()); // Create forlder
+ }
+ return true; // Folder already exists
+}
\ No newline at end of file
diff --git a/src/Services/SdService.h b/src/Services/SdService.h
new file mode 100644
index 00000000..6a813eb2
--- /dev/null
+++ b/src/Services/SdService.h
@@ -0,0 +1,43 @@
+#ifndef SD_SERVICE_H
+#define SD_SERVICE_H
+
+#include <SD.h>
+#include <SPI.h>
+#include <vector>
+#include <string>
+#include <unordered_map>
+
+class SdService {
+private:
+ SPIClass sdCardSPI;
+ bool sdCardMounted = false;
+ std::unordered_map<std::string, std::vector<std::string>> cachedDirectoryElements;
+public:
+ SdService();
+
+ bool configure(uint8_t clkPin, uint8_t misoPin, uint8_t mosiPin, uint8_t csPin);
+ void close();
+ bool isFile(const std::string& filePath);
+ bool isDirectory(const std::string& path);
+ bool getSdState();
+
+ std::vector<std::string> listElements(const std::string& dirPath, size_t limit = 0);
+ std::vector<uint8_t> readBinaryFile(const std::string& filePath);
+ std::string readFile(const std::string& filePath);
+
+ bool writeFile(const std::string& filePath, const std::string& data);
+ bool writeBinaryFile(const std::string& filePath, const std::vector<uint8_t>& data);
+ bool appendToFile(const std::string& filePath, const std::string& data);
+ bool deleteFile(const std::string& filePath);
+ bool validateVaultFile(const std::string& filePath);
+ bool ensureDirectory(const std::string& directory);
+
+ std::string getFileExt(const std::string& path);
+ std::string getParentDirectory(const std::string& path);
+ std::string getFileName(const std::string& path);
+ std::vector<std::string> getCachedDirectoryElements(const std::string& path);
+ void setCachedDirectoryElements(const std::string& path, const std::vector<std::string>& elements);
+ void removeCachedPath(const std::string& path);
+};
+
+#endif // SD_SERVICE_H
diff --git a/src/Services/SpiService.cpp b/src/Services/SpiService.cpp
new file mode 100644
index 00000000..6a7aa168
--- /dev/null
+++ b/src/Services/SpiService.cpp
@@ -0,0 +1,45 @@
+#include "Services/SpiService.h"
+
+void SpiService::configure(uint8_t mosi, uint8_t miso, uint8_t sclk, uint8_t cs, uint32_t frequency) {
+ this->csPin = cs;
+ SPI.begin(sclk, miso, mosi, cs);
+ SPI.beginTransaction(SPISettings(frequency, MSBFIRST, SPI_MODE0));
+ pinMode(cs, OUTPUT);
+ digitalWrite(cs, HIGH);
+}
+
+void SpiService::beginTransaction() {
+ SPI.beginTransaction(SPISettings(spiFrequency, MSBFIRST, SPI_MODE0));
+ digitalWrite(csPin, LOW);
+}
+
+void SpiService::endTransaction() {
+ digitalWrite(csPin, HIGH);
+ SPI.endTransaction();
+}
+
+uint8_t SpiService::transfer(uint8_t data) {
+ return SPI.transfer(data);
+}
+
+void SpiService::readFlashID(uint8_t* buffer, size_t length) {
+ beginTransaction();
+ SPI.transfer(0x9F); // JEDEC ID command
+ for (size_t i = 0; i < length; ++i) {
+ buffer[i] = SPI.transfer(0x00);
+ }
+ endTransaction();
+}
+
+void SpiService::readFlashData(uint32_t address, uint8_t* buffer, size_t length) {
+ beginTransaction();
+ SPI.transfer(0x03); // Read Data command
+ SPI.transfer((address >> 16) & 0xFF);
+ SPI.transfer((address >> 8) & 0xFF);
+ SPI.transfer(address & 0xFF);
+
+ for (size_t i = 0; i < length; ++i) {
+ buffer[i] = SPI.transfer(0x00);
+ }
+ endTransaction();
+}
diff --git a/src/Services/SpiService.h b/src/Services/SpiService.h
new file mode 100644
index 00000000..17d9cf7f
--- /dev/null
+++ b/src/Services/SpiService.h
@@ -0,0 +1,21 @@
+#pragma once
+
+#include <Arduino.h>
+#include <SPI.h>
+
+class SpiService {
+public:
+ void configure(uint8_t mosi, uint8_t miso, uint8_t sclk, uint8_t cs, uint32_t frequency = 1000000);
+
+ void beginTransaction();
+ void endTransaction();
+
+ uint8_t transfer(uint8_t data);
+
+ void readFlashID(uint8_t* buffer, size_t length);
+ void readFlashData(uint32_t address, uint8_t* buffer, size_t length);
+
+private:
+ uint8_t csPin;
+ uint32_t spiFrequency = 1000000;
+};
diff --git a/src/Services/UartService.cpp b/src/Services/UartService.cpp
new file mode 100644
index 00000000..73164deb
--- /dev/null
+++ b/src/Services/UartService.cpp
@@ -0,0 +1,128 @@
+#include "UartService.h"
+
+void UartService::configure(unsigned long baud, uint32_t config, uint8_t rx, uint8_t tx, bool inverted) {
+ Serial1.end(); // stop before reconfigure
+ Serial1.begin(baud, config, rx, tx, inverted);
+}
+
+std::string UartService::readLine() {
+ std::string input;
+ bool lastWasCR = false;
+
+ while (true) {
+ if (!Serial1.available()) continue;
+
+ char c = Serial1.read();
+
+ if (c == '\r') {
+ lastWasCR = true;
+ Serial1.println();
+ break;
+ }
+
+ if (c == '\n') {
+ if (!lastWasCR) {
+ Serial1.println();
+ break;
+ }
+ continue;
+ }
+
+ if (c == '\b' || c == 127) {
+ if (!input.empty()) {
+ input.pop_back();
+ Serial1.print("\b \b");
+ }
+ } else {
+ input += c;
+ Serial1.print(c);
+ lastWasCR = false;
+ }
+ }
+
+ return input;
+}
+
+void UartService::print(const std::string& msg) {
+ Serial1.print(msg.c_str());
+}
+
+void UartService::println(const std::string& msg) {
+ Serial1.println(msg.c_str());
+}
+
+bool UartService::available() const {
+ return Serial1.available();
+}
+
+char UartService::read() {
+ return Serial1.read();
+}
+
+void UartService::write(char c) {
+ Serial1.write(c);
+}
+
+void UartService::write(const std::string& str) {
+ Serial1.write(reinterpret_cast<const uint8_t*>(str.c_str()), str.length());
+}
+
+std::string UartService::executeByteCode(const std::vector<ByteCode>& bytecodes) {
+ std::string result;
+ uint32_t timeout = 2000; // 2 secondes
+ uint32_t start;
+ uint32_t received = 0;
+
+ for (const ByteCode& code : bytecodes) {
+ switch (code.getCommand()) {
+ case ByteCodeEnum::Write:
+ for (uint32_t i = 0; i < code.getRepeat(); ++i) {
+ Serial1.write(code.getData());
+ }
+ break;
+
+ case ByteCodeEnum::Read:
+ start = millis();
+ while (received < code.getRepeat() && (millis() - start < timeout)) {
+ if (Serial1.available()) {
+ char c = Serial1.read();
+ result += c;
+ ++received;
+ } else {
+ delay(10);
+ }
+ }
+ break;
+
+ case ByteCodeEnum::DelayMs:
+ delay(code.getRepeat());
+ break;
+
+ case ByteCodeEnum::DelayUs:
+ delayMicroseconds(code.getRepeat());
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ return result;
+}
+
+void UartService::switchBaudrate(unsigned long newBaud) {
+ Serial1.updateBaudRate(newBaud);
+}
+
+void UartService::flush() {
+ Serial.flush();
+}
+
+void UartService::clearUartBuffer() {
+ const size_t maxBytes = 512; // uart buffer size ?
+ size_t count = 0;
+ while (count < maxBytes && available()) {
+ read();
+ count++;
+ }
+}
diff --git a/src/Services/UartService.h b/src/Services/UartService.h
new file mode 100644
index 00000000..8909a771
--- /dev/null
+++ b/src/Services/UartService.h
@@ -0,0 +1,21 @@
+#pragma once
+#include <string>
+#include <vector>
+#include "Models/ByteCode.h"
+#include "Arduino.h"
+
+class UartService {
+public:
+ void configure(unsigned long baud, uint32_t config, uint8_t rx, uint8_t tx, bool inverted);
+ void print(const std::string& msg);
+ void println(const std::string& msg);
+ char read();
+ std::string readLine();
+ bool available() const;
+ void write(char c);
+ void write(const std::string& str);
+ std::string executeByteCode(const std::vector<ByteCode>& bytecodes);
+ void switchBaudrate(unsigned long newBaud);
+ void flush();
+ void clearUartBuffer();
+};
diff --git a/src/Services/UsbService.cpp b/src/Services/UsbService.cpp
new file mode 100644
index 00000000..0e058618
--- /dev/null
+++ b/src/Services/UsbService.cpp
@@ -0,0 +1,241 @@
+
+// Implementation file: UsbService.cpp
+
+#include "UsbService.h"
+#include <M5Unified.h>
+
+UsbService::UsbService()
+ : keyboardActive(false), storageActive(false), initialized(false) {}
+
+void UsbService::keyboardBegin() {
+ if (keyboardActive) return;
+
+ USB.begin();
+ keyboard.begin();
+ hidInitTime = millis();
+ keyboardActive = true;
+}
+
+void UsbService::storageBegin(uint8_t cs, uint8_t clk, uint8_t miso, uint8_t mosi) {
+ if (initialized) return;
+
+ sdSPI.begin(clk, miso, mosi, cs);
+ if (!SD.begin(cs, sdSPI)) {
+ storageActive = false;
+ return;
+ }
+
+ // Setup MSC
+ uint32_t secSize = SD.sectorSize();
+ uint32_t numSectors = SD.numSectors();
+
+ msc.vendorID("ESP32");
+ msc.productID("USB_MSC");
+ msc.productRevision("1.0");
+ msc.onRead(storageReadCallback);
+ msc.onWrite(storageWriteCallback);
+ msc.onStartStop(usbStartStopCallback);
+ msc.mediaPresent(true);
+ msc.begin(numSectors, secSize);
+
+ // Setup USB events
+ setupStorageEvent();
+
+ USB.begin();
+ storageActive = true;
+ initialized = true;
+}
+
+void UsbService::keyboardSendString(const std::string& text) {
+ if (!keyboardActive) return;
+
+ // Wait HID init
+ while (millis() - hidInitTime < 1500) {
+ delay(10);
+ }
+
+ keyboard.releaseAll();
+ for (char c : text) {
+ keyboard.write(c);
+ }
+}
+
+void UsbService::keyboardSendChunkedString(const std::string& data, size_t chunkSize, unsigned long delayBetweenChunks) {
+ if (!keyboardActive) return;
+
+ size_t totalLength = data.length();
+ size_t sentLength = 0;
+
+ while (sentLength < totalLength) {
+ size_t currentChunkSize = std::min(chunkSize, totalLength - sentLength);
+ std::string chunk = data.substr(sentLength, currentChunkSize);
+ keyboardSendString(chunk);
+ sentLength += currentChunkSize;
+ delay(delayBetweenChunks);
+ }
+}
+
+void UsbService::mouseBegin() {
+ if (mouseActive) return;
+
+ USB.begin();
+ mouse.begin();
+ mouseActive = true;
+ hidInitTime = millis();
+}
+
+void UsbService::mouseMove(int x, int y) {
+ // Wait HID init
+ while (millis() - hidInitTime < 1500) {
+ delay(10);
+ }
+
+ mouse.move(x, y);
+}
+
+void UsbService::mouseClick(int button) {
+ // Wait HID init
+ while (millis() - hidInitTime < 1500) {
+ delay(10);
+ }
+
+ mouse.press(button);
+ delay(50);
+ mouse.release(button);
+}
+
+void UsbService::mouseRelease(int button) {
+ if (!mouseActive) return;
+ mouse.release(button);
+}
+
+void UsbService::gamepadBegin() {
+ if (gamepadActive) return;
+
+ USB.begin();
+ gamepad.begin();
+ gamepadActive = true;
+ hidInitTime = millis();
+}
+
+void UsbService::gamepadPress(const std::string& name) {
+ if (!gamepadActive) return;
+
+ // Wait HID init
+ while (millis() - hidInitTime < 1500) {
+ delay(10);
+ }
+
+ // Valeurs par défaut (repos)
+ int8_t x = 0, y = 0, z = 0, rz = 0, rx = 0, ry = 0;
+ uint8_t hat = HAT_CENTER;
+ uint32_t buttons = 0;
+
+ // Interprétation de la commande
+ if (name == "up") {
+ hat = HAT_UP;
+ } else if (name == "down") {
+ hat = HAT_DOWN;
+ } else if (name == "left") {
+ hat = HAT_LEFT;
+ } else if (name == "right") {
+ hat = HAT_RIGHT;
+ } else if (name == "a") {
+ buttons = (1 << BUTTON_A);
+ } else if (name == "b") {
+ buttons = (1 << BUTTON_B);
+ } else {
+ return; // commande inconnue
+ }
+
+ // Envoie de l'état
+ gamepad.send(x, y, z, rz, rx, ry, hat, buttons);
+ delay(100); // Simule une pression courte
+ gamepad.send(0, 0, 0, 0, 0, 0, HAT_CENTER, 0); // Relâche tout
+}
+
+bool UsbService::isKeyboardActive() const {
+ return keyboardActive;
+}
+
+bool UsbService::isStorageActive() const {
+ return storageActive;
+}
+
+bool UsbService::isMouseActive() const {
+ return mouseActive;
+}
+
+
+int32_t UsbService::storageReadCallback(uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) {
+ const uint32_t secSize = SD.sectorSize();
+ if (secSize == 0) return -1;
+
+ uint8_t* buf = reinterpret_cast<uint8_t*>(buffer);
+ for (uint32_t i = 0; i < bufsize / secSize; ++i) {
+ if (!SD.readRAW(buf + i * secSize, lba + i)) {
+ return -1;
+ }
+ }
+ return bufsize;
+}
+
+int32_t UsbService::storageWriteCallback(uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize) {
+ const uint32_t secSize = SD.sectorSize();
+ if (secSize == 0) return -1;
+
+ uint64_t freeSpace = SD.totalBytes() - SD.usedBytes();
+ if (bufsize > freeSpace) {
+ return -1;
+ }
+
+ for (uint32_t i = 0; i < bufsize / secSize; ++i) {
+ uint8_t blk[secSize];
+ memcpy(blk, buffer + i * secSize, secSize);
+ if (!SD.writeRAW(blk, lba + i)) {
+ return -1;
+ }
+ }
+ return bufsize;
+}
+
+bool UsbService::usbStartStopCallback(uint8_t power_condition, bool start, bool load_eject) {
+ return true;
+}
+
+void UsbService::setupStorageEvent() {
+ USB.onEvent([](void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
+ if (event_base == ARDUINO_USB_EVENTS) {
+ auto* data = reinterpret_cast<arduino_usb_event_data_t*>(event_data);
+ switch (event_id) {
+ case ARDUINO_USB_STARTED_EVENT:
+ M5.Lcd.fillRoundRect(54, 60, 5, 30, 5, GREEN);
+ break;
+ case ARDUINO_USB_STOPPED_EVENT:
+ M5.Lcd.fillRoundRect(54, 60, 5, 30, 5, RED);
+ break;
+ case ARDUINO_USB_SUSPEND_EVENT:
+ // Display a message or icon
+ break;
+ case ARDUINO_USB_RESUME_EVENT:
+ // Display a message or icon
+ break;
+ default:
+ break;
+ }
+ }
+ });
+}
+
+void UsbService::reset() {
+ if (initialized) {
+ keyboard.releaseAll(); // si clavier actif
+ msc.end(); // si stockage actif
+ USB.~ESPUSB(); // force la destruction de l'instance USB
+ USB.enableDFU(); // réinitialise le contrôleur USB (important)
+ initialized = false;
+ keyboardActive = false;
+ storageActive = false;
+ mouseActive = false;
+ }
+}
diff --git a/src/Services/UsbService.h b/src/Services/UsbService.h
new file mode 100644
index 00000000..5ea4b737
--- /dev/null
+++ b/src/Services/UsbService.h
@@ -0,0 +1,73 @@
+#pragma once
+
+#include <Arduino.h>
+#include <USB.h>
+#include <USBMSC.h>
+#include <SPI.h>
+#include <SD.h>
+#include <string>
+#include <USBHIDMouse.h>
+#include <USBHIDKeyboard.h>
+#include <USBHIDGamepad.h>
+
+// ###############################################################################
+// ⚠️ USB CDC (Serial over USB) can't be used at the same time as other USB modes
+// (like Mass Storage, HID, MIDI, etc).
+// ➤ If you enable any other USB mode, USB CDC will automatically stop.
+// ###############################################################################
+
+class UsbService {
+public:
+ UsbService();
+
+ // Begin USB HID keyboard mode
+ void keyboardBegin();
+ void keyboardSendString(const std::string& text);
+ void keyboardSendChunkedString(const std::string& data, size_t chunkSize, unsigned long delayBetweenChunks);
+
+ // Begin USB Mass Storage mode
+ void storageBegin(uint8_t cs, uint8_t clk, uint8_t miso, uint8_t mosi);
+
+ // Mouse actions
+ void mouseBegin();
+ void mouseMove(int x, int y);
+ void mouseClick(int button);
+ void mouseRelease(int button);
+
+ // Gamepad Actions
+ void gamepadBegin();
+ void gamepadPress(const std::string& name);
+
+ // Status
+ bool isKeyboardActive() const;
+ bool isStorageActive() const;
+ bool isMouseActive() const;
+ bool isGamepadActive() const;
+
+ void reset();
+
+private:
+ // HID
+ USBHIDKeyboard keyboard;
+ USBHIDMouse mouse;
+ USBHIDGamepad gamepad;
+ bool gamepadActive = false;
+ bool keyboardActive = false;
+ bool mouseActive = false;
+ unsigned long hidInitTime;
+
+
+ // Mass Storage
+ USBMSC msc;
+ SPIClass sdSPI;
+ bool storageActive;
+
+ bool initialized;
+
+ // USB MSC callbacks
+ static int32_t storageReadCallback(uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize);
+ static int32_t storageWriteCallback(uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize);
+ static bool usbStartStopCallback(uint8_t power_condition, bool start, bool load_eject);
+
+ void setupStorageEvent();
+};
diff --git a/src/Services/WifiService.cpp b/src/Services/WifiService.cpp
new file mode 100644
index 00000000..c6db2730
--- /dev/null
+++ b/src/Services/WifiService.cpp
@@ -0,0 +1,99 @@
+#include "WifiService.h"
+
+WifiService::WifiService() : connected(false) {
+ WiFi.mode(WIFI_STA);
+}
+
+bool WifiService::connect(const std::string& ssid, const std::string& password, unsigned long timeoutMs) {
+ WiFi.begin(ssid.c_str(), password.c_str());
+
+ unsigned long startAttemptTime = millis();
+ while (WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < timeoutMs) {
+ delay(100);
+ }
+
+ connected = WiFi.status() == WL_CONNECTED;
+ return connected;
+}
+
+void WifiService::disconnect() {
+ WiFi.disconnect(true);
+ connected = false;
+}
+
+bool WifiService::isConnected() const {
+ return WiFi.status() == WL_CONNECTED;
+}
+
+std::string WifiService::getLocalIP() const {
+ if (!isConnected()) return "";
+ return WiFi.localIP().toString().c_str();
+}
+
+std::string WifiService::getCurrentIP() const {
+ if (WiFi.getMode() == WIFI_AP || WiFi.getMode() == WIFI_AP_STA) {
+ return WiFi.softAPIP().toString().c_str();
+ }
+ return WiFi.localIP().toString().c_str();
+}
+
+std::string WifiService::getMacAddress() const {
+ return WiFi.macAddress().c_str();
+}
+
+bool WifiService::startAccessPoint(const std::string& ssid, const std::string& password, int channel, int maxConn) {
+ // WiFi.mode(WIFI_AP);
+ if (password.empty()) {
+ return WiFi.softAP(ssid.c_str(), nullptr, channel, false, maxConn);
+ } else {
+ return WiFi.softAP(ssid.c_str(), password.c_str(), channel, false, maxConn);
+ }
+}
+
+bool WifiService::ping(const std::string& host) {
+ IPAddress ip;
+ if (!WiFi.hostByName(host.c_str(), ip)) return false;
+ return Ping.ping(ip, 1); // 1 ping
+}
+
+
+std::vector<std::string> WifiService::scanNetworks() {
+ std::vector<std::string> results;
+
+ int n = WiFi.scanNetworks(/*async=*/false, /*hidden=*/true);
+
+ for (int i = 0; i < n; ++i) {
+ std::stringstream ss;
+ ss << " SSID: " << WiFi.SSID(i).c_str()
+ << " | RSSI: " << WiFi.RSSI(i)
+ << " dBm | Sec: "
+ << (WiFi.encryptionType(i) == WIFI_AUTH_OPEN ? "Open" : "Secured");
+ results.push_back(ss.str());
+ }
+
+ return results;
+}
+
+void WifiService::reset() {
+ disconnect();
+ WiFi.mode(WIFI_STA);
+ connected = false;
+}
+
+void WifiService::setModeApSta() {
+ WiFi.mode(WIFI_AP_STA);
+}
+
+void WifiService::setModeApOnly() {
+ WiFi.mode(WIFI_AP);
+}
+
+std::string WifiService::getApIp() const {
+ String ip = WiFi.softAPIP().toString();
+ return std::string(ip.c_str());
+}
+
+std::string WifiService::getLocalIp() const {
+ String ip = WiFi.localIP().toString();
+ return std::string(ip.c_str());
+}
diff --git a/src/Services/WifiService.h b/src/Services/WifiService.h
new file mode 100644
index 00000000..7da53d35
--- /dev/null
+++ b/src/Services/WifiService.h
@@ -0,0 +1,33 @@
+#pragma once
+
+#include <WiFi.h>
+#include <ESP32Ping.h>
+#include <string>
+#include <vector>
+#include <sstream>
+
+class WifiService {
+public:
+ WifiService();
+
+ bool connect(const std::string& ssid, const std::string& password, unsigned long timeoutMs = 10000);
+ void disconnect();
+ bool isConnected() const;
+
+ std::string getLocalIP() const;
+ std::string getCurrentIP() const;
+ std::string getMacAddress() const;
+
+ bool startAccessPoint(const std::string& ssid, const std::string& password = "", int channel = 1, int maxConn = 4);
+
+ std::vector<std::string> scanNetworks();
+ bool ping(const std::string& host);
+ void reset();
+ void setModeApSta();
+ void setModeApOnly();
+ std::string getApIp() const;
+ std::string getLocalIp() const;
+
+private:
+ bool connected;
+};
\ No newline at end of file
diff --git a/src/States/GlobalState.h b/src/States/GlobalState.h
new file mode 100644
index 00000000..81aa205a
--- /dev/null
+++ b/src/States/GlobalState.h
@@ -0,0 +1,201 @@
+#pragma once
+
+#include <cstdint>
+#include <string>
+#include "Enums/InfraredProtocolEnum.h"
+#include "Enums/ModeEnum.h"
+#include "Enums/TerminalTypeEnum.h"
+
+class GlobalState {
+private:
+ // Device Pinout
+ uint8_t ledPin = 21;
+ uint8_t sdCardCSPin = 12;
+ uint8_t sdCardCLKPin = 40;
+ uint8_t sdCardMISOPin = 39;
+ uint8_t sdCardMOSIPin = 14;
+
+ // WiFi AP Credentials
+ std::string apName = "ESP32-Bus-Pirate";
+ std::string apPassword = "readytoboard";
+
+ // NVS
+ std::string nvsNamespace = "wifi_settings";
+ std::string nvsSsidField = "wifi_ssid";
+ std::string nvsPasswordField = "wifi_password";
+
+ // Terminal Web UI
+ std::string terminalIp = "0.0.0.0";
+
+ // Terminal transmission mode
+ TerminalTypeEnum terminalMode = TerminalTypeEnum::Serial;
+
+ // Current selected mode
+ ModeEnum currentMode = ModeEnum::HIZ;
+
+ // PC Terminal Serial Configuration
+ unsigned long serialTerminalBaudRate = 115200;
+
+ // OneWire Default Pin
+ uint8_t oneWirePin = 1; // pin par défaut
+
+ // UART Default Configuration
+ unsigned long uartBaudRate = 9600;
+ uint32_t uartConfig = 0x800001c; // SERIAL_8N1 by default
+ bool uartInverted = false;
+ uint8_t uartRxPin = 1;
+ uint8_t uartTxPin = 2;
+ uint8_t uartDataBits = 8;
+ std::string uartParity = "None";
+ bool uartFlowControl = false;
+ uint8_t uartStopBits = 1;
+
+ // HDUART Default Configuration
+ unsigned long hdUartBaudRate = 9600;
+ uint32_t hdUartConfig = 0x800001c; // SERIAL_8N1
+ bool hdUartInverted = false;
+ uint8_t hdUartPin = 1;
+ uint8_t hdUartDataBits = 8;
+ std::string hdUartParity = "None";
+ bool hdUartFlowControl = false;
+ uint8_t hdUartStopBits = 1;
+
+ // I2C Default Configuration
+ uint8_t i2cSclPin = 1;
+ uint8_t i2cSdaPin = 2;
+ uint32_t i2cFrequency = 100000;
+
+ // Infrared Default Configuration
+ uint8_t infraredPin = 44;
+ uint8_t infraredRxPin = 1;
+ InfraredProtocolEnum infraredProtocol = InfraredProtocolEnum::_NEC;
+
+ // SD Card File Limits
+ size_t fileCountLimit = 512;
+ size_t fileCacheLimit = 64;
+
+ // Private constructor
+ GlobalState() = default;
+
+public:
+ GlobalState(const GlobalState&) = delete;
+ GlobalState& operator=(const GlobalState&) = delete;
+
+ static GlobalState& getInstance() {
+ static GlobalState instance;
+ return instance;
+ }
+
+ // Accessors for Device Pinout
+ uint8_t getLedPin() const { return ledPin; }
+ uint8_t getSdCardCSPin() const { return sdCardCSPin; }
+ uint8_t getSdCardCLKPin() const { return sdCardCLKPin; }
+ uint8_t getSdCardMISOPin() const { return sdCardMISOPin; }
+ uint8_t getSdCardMOSIPin() const { return sdCardMOSIPin; }
+
+ void setSdCardCSPin(uint8_t pin) { sdCardCSPin = pin; }
+ void setSdCardCLKPin(uint8_t pin) { sdCardCLKPin = pin; }
+ void setSdCardMISOPin(uint8_t pin) { sdCardMISOPin = pin; }
+ void setSdCardMOSIPin(uint8_t pin) { sdCardMOSIPin = pin; }
+
+ // AP WiFi
+ const std::string& getApName() const { return apName; }
+ const std::string& getApPassword() const { return apPassword; }
+
+ void setApName(const std::string& name) { apName = name; }
+ void setApPassword(const std::string& pass) { apPassword = pass; }
+
+ // Terminal IP
+ const std::string& getTerminalIp() const { return terminalIp; }
+ void setTerminalIp(const std::string& ip) { terminalIp = ip; }
+
+ // Terminal transmission mode
+ TerminalTypeEnum getTerminalMode() const { return terminalMode; }
+ void setTerminalMode(TerminalTypeEnum mode) { terminalMode = mode; }
+
+ // Current Mode
+ ModeEnum getCurrentMode() const { return currentMode; }
+ void setCurrentMode(ModeEnum mode) { currentMode = mode; }
+
+ // Serial Terminal Baud
+ unsigned long getSerialTerminalBaudRate() const { return serialTerminalBaudRate; }
+ void setSerialTerminalBaudRate(unsigned long rate) { serialTerminalBaudRate = rate; }
+
+ // OneWire
+ uint8_t getOneWirePin() const { return oneWirePin; }
+ void setOneWirePin(uint8_t pin) { oneWirePin = pin; }
+
+ // UART
+ unsigned long getUartBaudRate() const { return uartBaudRate; }
+ uint32_t getUartConfig() const { return uartConfig; }
+ uint8_t getUartRxPin() const { return uartRxPin; }
+ uint8_t getUartTxPin() const { return uartTxPin; }
+ uint8_t getUartDataBits() const { return uartDataBits; }
+ const std::string& getUartParity() const { return uartParity; }
+ uint8_t getUartStopBits() const { return uartStopBits; }
+ bool isUartInverted() const { return uartInverted; }
+ bool isUartFlowControl() const { return uartFlowControl; }
+
+ void setUartBaudRate(unsigned long b) { uartBaudRate = b; }
+ void setUartConfig(uint32_t c) { uartConfig = c; }
+ void setUartInverted(bool inv) { uartInverted = inv; }
+ void setUartRxPin(uint8_t pin) { uartRxPin = pin; }
+ void setUartTxPin(uint8_t pin) { uartTxPin = pin; }
+ void setUartDataBits(uint8_t bits) { uartDataBits = bits; }
+ void setUartParity(const std::string& parityVal) { uartParity = parityVal; }
+ void setUartFlowControl(bool enabled) { uartFlowControl = enabled; }
+ void setUartStopBits(uint8_t bits) { uartStopBits = bits; }
+
+ // HDUART
+ unsigned long getHdUartBaudRate() const { return hdUartBaudRate; }
+ uint32_t getHdUartConfig() const { return hdUartConfig; }
+ uint8_t getHdUartPin() const { return hdUartPin; }
+ uint8_t getHdUartDataBits() const { return hdUartDataBits; }
+ const std::string& getHdUartParity() const { return hdUartParity; }
+ uint8_t getHdUartStopBits() const { return hdUartStopBits; }
+ bool isHdUartInverted() const { return hdUartInverted; }
+ bool isHdUartFlowControl() const { return hdUartFlowControl; }
+
+ void setHdUartBaudRate(unsigned long b) { hdUartBaudRate = b; }
+ void setHdUartConfig(uint32_t c) { hdUartConfig = c; }
+ void setHdUartInverted(bool inv) { hdUartInverted = inv; }
+ void setHdUartPin(uint8_t pin) { hdUartPin = pin; }
+ void setHdUartDataBits(uint8_t bits) { hdUartDataBits = bits; }
+ void setHdUartParity(const std::string& parityVal) { hdUartParity = parityVal; }
+ void setHdUartFlowControl(bool enabled) { hdUartFlowControl = enabled; }
+ void setHdUartStopBits(uint8_t bits) { hdUartStopBits = bits; }
+
+ // I2C
+ uint8_t getI2cSdaPin() const { return i2cSdaPin; }
+ uint8_t getI2cSclPin() const { return i2cSclPin; }
+ uint32_t getI2cFrequency() const { return i2cFrequency; }
+
+ void setI2cSdaPin(uint8_t pin) { i2cSdaPin = pin; }
+ void setI2cSclPin(uint8_t pin) { i2cSclPin = pin; }
+ void setI2cFrequency(uint32_t freq) { i2cFrequency = freq; }
+
+ // Infrared
+ uint8_t getInfraredTxPin() const { return infraredPin; }
+ uint8_t getInfraredRxPin() const { return infraredRxPin; }
+ void setInfraredTxPin(uint8_t pin) { infraredPin = pin; }
+ void setInfraredRxPin(uint8_t pin) { infraredRxPin = pin; }
+ InfraredProtocolEnum getInfraredProtocol() const { return infraredProtocol ; }
+ void setInfraredProtocol(InfraredProtocolEnum prot) { infraredProtocol = prot; }
+
+ // SD File Limits
+ size_t getFileCountLimit() const { return fileCountLimit; }
+ size_t getFileCacheLimit() const { return fileCacheLimit; }
+
+ void setFileCountLimit(size_t count) { fileCountLimit = count; }
+ void setFileCacheLimit(size_t cache) { fileCacheLimit = cache; }
+
+ // NVS
+ const std::string& getNvsNamespace() const { return nvsNamespace; }
+ void setNvsNamespace(const std::string& ns) { nvsNamespace = ns; }
+
+ const std::string& getNvsPasswordField() const { return nvsPasswordField; }
+ void setNvsPasswordField(const std::string& f) { nvsPasswordField = f; }
+
+ const std::string& getNvsSsidField() const { return nvsSsidField; }
+ void setNvsSsidField(const std::string& f) { nvsSsidField = f; }
+};
diff --git a/src/Transformers/ArgTransformer.cpp b/src/Transformers/ArgTransformer.cpp
new file mode 100644
index 00000000..0cd4d81d
--- /dev/null
+++ b/src/Transformers/ArgTransformer.cpp
@@ -0,0 +1,131 @@
+#include "ArgTransformer.h"
+
+
+uint8_t ArgTransformer::parseByte(const std::string& str, int index) const {
+ std::istringstream ss(str);
+ int value = 0;
+
+ if (str.rfind("0x", 0) == 0 || str.rfind("0X", 0) == 0)
+ ss >> std::hex >> value;
+ else
+ ss >> std::dec >> value;
+
+ if (ss.fail() || value < 0 || value > 255) {
+ return 0xFF;
+ }
+
+ return static_cast<uint8_t>(value);
+}
+
+std::vector<uint8_t> ArgTransformer::parseByteList(const std::string& input) const {
+ std::istringstream iss(input);
+ std::string token;
+ std::vector<uint8_t> bytes;
+
+ int index = 0;
+ while (iss >> token) {
+ uint8_t parsed = parseByte(token, index);
+ if (parsed == 0xFF && token != "0xFF" && token != "255") {
+ continue; // ignore
+ }
+ bytes.push_back(parsed);
+ index++;
+ }
+
+ return bytes;
+}
+
+uint8_t ArgTransformer::parseHexOrDec(const std::string& str) const {
+ if (str.empty()) return 0;
+
+ int base = 10;
+ const char* cstr = str.c_str();
+
+ // Check Hex format
+ if (str.size() > 2 && (str[0] == '0') && (str[1] == 'x' || str[1] == 'X')) {
+ base = 16;
+ cstr += 2; // saute le prefixe 0x
+ }
+
+ // Verifier tous les char
+ for (size_t i = 0; i < strlen(cstr); ++i) {
+ char c = cstr[i];
+ if (base == 10 && !isdigit(c)) return 0;
+ if (base == 16 && !isxdigit(c)) return 0;
+ }
+
+ long value = strtol(str.c_str(), nullptr, base);
+ if (value < 0 || value > 255) return 0;
+
+ return static_cast<uint8_t>(value);
+}
+
+
+std::vector<std::string> ArgTransformer::splitArgs(const std::string& input) {
+ std::vector<std::string> result;
+ std::istringstream iss(input);
+ std::string token;
+ while (iss >> token) {
+ result.push_back(token);
+ }
+ return result;
+}
+
+bool ArgTransformer::parseInt(const std::string& input, int& output) {
+ const char* str = input.c_str();
+ char* end = nullptr;
+ int base = 10;
+
+ if (input.rfind("0x", 0) == 0 || input.rfind("0X", 0) == 0) {
+ base = 16;
+ str += 2;
+ } else if (!input.empty() && (input.back() == 'h' || input.back() == 'H')) {
+ base = 16;
+ std::string trimmed = input.substr(0, input.size() - 1);
+ str = trimmed.c_str();
+ }
+
+ long result = strtol(str, &end, base);
+ if (*end != '\0') return false; // invalid characters found
+
+ output = static_cast<int>(result);
+ return true;
+}
+
+bool ArgTransformer::isValidNumber(const std::string& input) {
+ std::string s = input;
+ int base = 10;
+ if (s.empty()) return false;
+
+ if (s.rfind("0x", 0) == 0 || s.rfind("0X", 0) == 0) {
+ base = 16;
+ s = s.substr(2);
+ }
+
+ for (char c : s) {
+ if ((base == 10 && !isdigit(c)) ||
+ (base == 16 && !isxdigit(c))) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+uint8_t ArgTransformer::toUint8(const std::string& input) {
+ return static_cast<uint8_t>(std::stoi(input));
+}
+
+uint32_t ArgTransformer::toUint32(const std::string& input) {
+ return static_cast<uint32_t>(std::stoul(input));
+}
+
+std::string ArgTransformer::toLower(const std::string& input) {
+ std::string result = input;
+ std::transform(
+ result.begin(), result.end(), result.begin(),
+ [](unsigned char c) { return std::tolower(c); }
+ );
+ return result;
+}
+
diff --git a/src/Transformers/ArgTransformer.h b/src/Transformers/ArgTransformer.h
new file mode 100644
index 00000000..37e2a853
--- /dev/null
+++ b/src/Transformers/ArgTransformer.h
@@ -0,0 +1,25 @@
+#pragma once
+
+#include <string>
+#include <vector>
+#include <cstdint>
+#include <cstring>
+#include <sstream>
+#include <iomanip>
+#include <stdexcept>
+#include <string>
+#include <algorithm>
+
+class ArgTransformer {
+public:
+ std::vector<uint8_t> parseByteList(const std::string& input) const;
+ uint8_t parseByte(const std::string& str, int index = -1) const;
+ uint8_t parseHexOrDec(const std::string& s) const ;
+ bool parseInt(const std::string& input, int& output);
+ std::vector<std::string> splitArgs(const std::string& input);
+ bool isValidNumber(const std::string& input);
+ uint8_t toUint8(const std::string& input);
+ uint32_t toUint32(const std::string& input);
+ std::string toLower(const std::string& input);
+
+};
diff --git a/src/Transformers/InstructionTransformer.cpp b/src/Transformers/InstructionTransformer.cpp
new file mode 100644
index 00000000..11c87e24
--- /dev/null
+++ b/src/Transformers/InstructionTransformer.cpp
@@ -0,0 +1,277 @@
+#include "InstructionTransformer.h"
+
+std::vector<Instruction> InstructionTransformer::transform(const std::string& raw) {
+ std::vector<Instruction> instructions;
+ if (raw.empty()) return instructions;
+
+ bool inChar = false;
+ bool inBlock = false;
+ bool inString = false;
+ std::string token;
+ std::string currentRaw;
+ Instruction* currentInstruction = nullptr;
+
+ for (char c : raw) {
+ if (inChar) {
+ token += c;
+ currentRaw += c;
+ if (c == '\'') {
+ if (currentInstruction) {
+ currentInstruction->addToken(token);
+ }
+ token.clear();
+ inChar = false;
+ }
+ continue;
+ }
+
+ if (inString) {
+ token += c;
+ currentRaw += c;
+ if (c == '"') {
+ if (currentInstruction) {
+ currentInstruction->addToken(token);
+ }
+ token.clear();
+ inString = false;
+ continue;
+ }
+ continue;
+ }
+
+
+ if (c == '\'') {
+ token = "'";
+ currentRaw += c;
+ inChar = true;
+ continue;
+ }
+
+ if (c == '"') {
+ token = "\"";
+ currentRaw += c;
+ inString = true;
+ continue;
+ }
+
+ if (c == '[' || c == '{' || c == '>') {
+ inBlock = true;
+ currentRaw = std::string(1, c);
+ currentInstruction = new Instruction(currentRaw);
+ currentInstruction->prefix = c;
+ continue;
+ }
+
+ if (c == ']') {
+ if (!token.empty() && currentInstruction) {
+ currentInstruction->addToken(token);
+ token.clear();
+ }
+ if (currentInstruction) {
+ currentRaw += c;
+ currentInstruction->raw = currentRaw;
+ instructions.push_back(*currentInstruction);
+ delete currentInstruction;
+ currentInstruction = nullptr;
+ }
+ inBlock = false;
+ continue;
+ }
+
+ if (inBlock) {
+ currentRaw += c;
+ if (std::isspace(c)) {
+ if (!token.empty() && currentInstruction) {
+ currentInstruction->addToken(token);
+ token.clear();
+ }
+ } else {
+ token += c;
+ }
+ }
+ }
+
+ return instructions;
+}
+
+std::vector<ByteCode> InstructionTransformer::transformByteCode(const Instruction& instruction) {
+ std::vector<ByteCode> bytecodes;
+
+ if (instruction.prefix == '[') {
+ bytecodes.emplace_back(ByteCodeEnum::Start);
+ }
+
+ for (const auto& tok : instruction.tokens) {
+ if (isCharLiteral(tok)) {
+ bytecodes.emplace_back(ByteCodeEnum::Write, parseCharLiteral(tok));
+ }
+
+ else if (isStringLiteral(tok)) {
+ for (char c : tok.substr(1, tok.size() - 2)) {
+ bytecodes.emplace_back(ByteCodeEnum::Write, static_cast<uint8_t>(c));
+ }
+ }
+
+ else if (isHex(tok)) {
+ bytecodes.emplace_back(ByteCodeEnum::Write, parseHex(tok));
+ }
+
+ else if (isDecimal(tok)) {
+ bytecodes.emplace_back(ByteCodeEnum::Write, parseDecimal(tok));
+ }
+
+ else if (isSymbolWithRepeat(tok)) {
+ std::pair<ByteCodeEnum, uint8_t> result = parseSymbolWithRepeat(tok);
+ ByteCodeEnum sym = result.first;
+ uint8_t repeat = result.second;
+ bytecodes.emplace_back(sym, 0, 8, repeat);
+ }
+
+ else if (isRepeatedSymbol(tok)) {
+ char symbol = tok[0];
+ uint8_t repeat = tok.size();
+ bytecodes.emplace_back(parseSymbol(symbol).getCommand(), 0, 8, repeat);
+ }
+
+ else if (isSymbol(tok)) {
+ bytecodes.push_back(parseSymbol(tok[0]));
+ }
+ }
+
+ if (instruction.prefix == '[') {
+ bytecodes.emplace_back(ByteCodeEnum::Stop);
+ }
+
+ return bytecodes;
+}
+
+std::vector<ByteCode> InstructionTransformer::transformByteCodes(const std::vector<Instruction>& instructions) {
+ std::vector<ByteCode> allByteCodes;
+
+ for (auto& inst : instructions) {
+ std::vector<ByteCode> bytecodes = transformByteCode(inst);
+ allByteCodes.insert(allByteCodes.end(), bytecodes.begin(), bytecodes.end());
+ }
+
+ return allByteCodes;
+}
+
+bool InstructionTransformer::isHex(const std::string& token) const {
+ return token.size() > 2 &&
+ token[0] == '0' &&
+ std::tolower(token[1]) == 'x';
+}
+
+bool InstructionTransformer::isDecimal(const std::string& token) const {
+ return !token.empty() && std::all_of(token.begin(), token.end(), ::isdigit);
+}
+
+bool InstructionTransformer::isCharLiteral(const std::string& token) const {
+ return token.size() == 3 && token.front() == '\'' && token.back() == '\'';
+}
+
+bool InstructionTransformer::isStringLiteral(const std::string& token) const {
+ return token.size() >= 2 &&
+ ((token.front() == '"' && token.back() == '"') ||
+ (token.front() == '\'' && token.back() == '\''));
+}
+
+bool InstructionTransformer::isSymbol(const std::string& token) const {
+ if (token.size() != 1) return false;
+ char c = token[0];
+ switch (c) {
+ case 'r':
+ case 'd':
+ case 'D':
+ case 's':
+ case 'S':
+ case 'h':
+ case 'l':
+ return true;
+ default:
+ return std::ispunct(c);
+ }
+}
+
+bool InstructionTransformer::isSymbolWithRepeat(const std::string& token) const {
+ auto pos = token.find(':');
+ if (pos == std::string::npos) return false;
+ if (pos == 0 || pos == token.size() - 1) return false;
+
+ char symbol = token[0];
+ switch (symbol) {
+ case 'r':
+ case 'd':
+ case 'D':
+ case 's':
+ case 'S':
+ case 'h':
+ case 'l':
+ break;
+ default:
+ return false;
+ }
+
+ std::string repeatStr = token.substr(pos + 1);
+ return std::all_of(repeatStr.begin(), repeatStr.end(), ::isdigit);
+}
+
+
+uint8_t InstructionTransformer::parseHex(const std::string& token) const {
+ return static_cast<uint8_t>(std::stoul(token, nullptr, 16));
+}
+
+uint8_t InstructionTransformer::parseDecimal(const std::string& token) const {
+ return static_cast<uint8_t>(std::stoul(token));
+}
+
+uint8_t InstructionTransformer::parseCharLiteral(const std::string& token) const {
+ return static_cast<uint8_t>(token[1]);
+}
+
+ByteCode InstructionTransformer::parseSymbol(char c) const {
+ switch (c) {
+ case 'r': return ByteCode(ByteCodeEnum::Read, 0, 8, 1);
+ case 'd': return ByteCode(ByteCodeEnum::DelayUs, 0, 8, 1);
+ case 'D': return ByteCode(ByteCodeEnum::DelayMs, 0, 8, 1);
+ case 's': return ByteCode(ByteCodeEnum::Start);
+ case 'S': return ByteCode(ByteCodeEnum::Stop);
+ case 'h': return ByteCode(ByteCodeEnum::AuxHigh);
+ case 'l': return ByteCode(ByteCodeEnum::AuxLow);
+ default: return ByteCode(ByteCodeEnum::None);
+ }
+}
+
+std::pair<ByteCodeEnum, uint8_t> InstructionTransformer::parseSymbolWithRepeat(const std::string& token) const {
+ char symbol = token[0];
+ size_t colonPos = token.find(':');
+ unsigned long parsed = std::stoul(token.substr(colonPos + 1));
+ uint8_t repeat = std::min(parsed, 255ul);
+
+ return { parseSymbol(symbol).getCommand(), repeat };
+}
+
+bool InstructionTransformer::isRepeatedSymbol(const std::string& token) const {
+ if (token.empty()) return false;
+ char first = token[0];
+
+ // repeat available on
+ switch (first) {
+ case 'r':
+ case 'd':
+ case 'D':
+ case 'h':
+ case 'l':
+ case 's':
+ case 'S':
+ break;
+ default:
+ return false;
+ }
+
+ // verify each char
+ return std::all_of(token.begin(), token.end(), [first](char c) {
+ return c == first;
+ });
+}
+
diff --git a/src/Transformers/InstructionTransformer.h b/src/Transformers/InstructionTransformer.h
new file mode 100644
index 00000000..df251361
--- /dev/null
+++ b/src/Transformers/InstructionTransformer.h
@@ -0,0 +1,31 @@
+#pragma once
+
+#include <string>
+#include <vector>
+#include <cctype>
+#include <sstream>
+#include <algorithm>
+#include "Models/ByteCode.h"
+#include "Models/Instruction.h"
+#include "Arduino.h"
+
+class InstructionTransformer {
+public:
+ std::vector<Instruction> transform(const std::string& raw);
+ std::vector<ByteCode> transformByteCode(const Instruction& instruction);
+ std::vector<ByteCode> transformByteCodes(const std::vector<Instruction>& instructions);
+
+private:
+ bool isHex(const std::string& token) const;
+ bool isDecimal(const std::string& token) const;
+ bool isCharLiteral(const std::string& token) const;
+ bool isSymbol(const std::string& token) const;
+ bool isRepeatedSymbol(const std::string& token) const;
+ bool isSymbolWithRepeat(const std::string& token) const;
+ bool isStringLiteral(const std::string& token) const;
+ uint8_t parseHex(const std::string& token) const;
+ uint8_t parseDecimal(const std::string& token) const;
+ uint8_t parseCharLiteral(const std::string& token) const;
+ ByteCode parseSymbol(char c) const;
+ std::pair<ByteCodeEnum, uint8_t> parseSymbolWithRepeat(const std::string& token) const;
+};
diff --git a/src/Transformers/TerminalCommandTransformer.cpp b/src/Transformers/TerminalCommandTransformer.cpp
new file mode 100644
index 00000000..a683ab3f
--- /dev/null
+++ b/src/Transformers/TerminalCommandTransformer.cpp
@@ -0,0 +1,21 @@
+#include "TerminalCommandTransformer.h"
+#include <sstream>
+
+TerminalCommand TerminalCommandTransformer::transform(const std::string& raw) const {
+ std::istringstream iss(raw);
+
+ std::string root, subcommand, args;
+ iss >> root >> subcommand;
+ std::getline(iss, args);
+
+ if (!args.empty() && args[0] == ' ') {
+ args.erase(0, 1);
+ }
+
+ TerminalCommand cmd;
+ cmd.setRoot(root);
+ cmd.setSubcommand(subcommand);
+ cmd.setArgs(args);
+
+ return cmd;
+}
diff --git a/src/Transformers/TerminalCommandTransformer.h b/src/Transformers/TerminalCommandTransformer.h
new file mode 100644
index 00000000..31b8ce25
--- /dev/null
+++ b/src/Transformers/TerminalCommandTransformer.h
@@ -0,0 +1,8 @@
+#pragma once
+#include <string>
+#include <Models/TerminalCommand.h>
+
+class TerminalCommandTransformer {
+public:
+ TerminalCommand transform(const std::string& raw) const;
+};
diff --git a/src/Transformers/WebRequestTransformer.cpp b/src/Transformers/WebRequestTransformer.cpp
new file mode 100644
index 00000000..807e8244
--- /dev/null
+++ b/src/Transformers/WebRequestTransformer.cpp
@@ -0,0 +1,35 @@
+#include "WebRequestTransformer.h"
+
+TerminalCommand WebRequestTransformer::toTerminalCommand(const std::string& body) {
+ JsonDocument doc;
+
+ DeserializationError err = deserializeJson(doc, body);
+ if (!err && doc.containsKey("command")) {
+ std::string commandStr = doc["command"].as<std::string>();
+ return TerminalCommand(commandStr);
+ }
+
+ return TerminalCommand(body);
+}
+
+std::string WebRequestTransformer::toTerminalCommandRaw(const std::string& body) {
+ JsonDocument doc;
+
+ DeserializationError err = deserializeJson(doc, body);
+ if (!err && doc.containsKey("command")) {
+ std::string commandStr = doc["command"].as<std::string>();
+ return commandStr;
+ }
+
+ return body;
+}
+
+std::string WebRequestTransformer::toJsonResponse(const std::string& cliOutput) {
+ JsonDocument doc;
+
+ doc["result"] = cliOutput;
+
+ std::string output;
+ serializeJson(doc, output);
+ return output;
+}
diff --git a/src/Transformers/WebRequestTransformer.h b/src/Transformers/WebRequestTransformer.h
new file mode 100644
index 00000000..83293c9e
--- /dev/null
+++ b/src/Transformers/WebRequestTransformer.h
@@ -0,0 +1,11 @@
+#pragma once
+#include <string>
+#include "Models/TerminalCommand.h"
+#include <ArduinoJson.h>
+
+class WebRequestTransformer {
+public:
+ TerminalCommand toTerminalCommand(const std::string& body);
+ std::string toTerminalCommandRaw(const std::string& body);
+ std::string toJsonResponse(const std::string& cliOutput);
+};
diff --git a/src/Vendors/CardWifiSetup.cpp b/src/Vendors/CardWifiSetup.cpp
new file mode 100644
index 00000000..e960b587
--- /dev/null
+++ b/src/Vendors/CardWifiSetup.cpp
@@ -0,0 +1,201 @@
+/**
+ * @file CardWifiSetup.h
+ * @author Aurélio Avanzi Dutch version Roland Breedveld adapted by Milton Matuda for Mic WebServer
+ * @brief https://github.com/cyberwisk/M5Card_Wifi_KeyBoard_Setup/tree/main/M5Card_Wifi_KeyBoard_Setup
+ * @version Apha 0.4BR
+ * @date 2024-11-14
+ *
+ * @Hardwares: M5Cardputer - https://docs.m5stack.com/en/core/Cardputer
+ * @Dependent Librarys:
+ * M5Cardputer: https://github.com/m5stack/M5Cardputer
+ * WiFi: https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFi
+ **/
+
+
+#include "CardWifiSetup.h"
+
+String inputText(const String& prompt, int x, int y) {
+ String data = "> ";
+
+ M5Cardputer.Display.setTextColor(TFT_LIGHTGRAY);
+ M5Cardputer.Display.setRotation(1);
+ M5Cardputer.Display.setTextScroll(true);
+ M5Cardputer.Display.drawString(prompt, x, y);
+
+ while (1) {
+ M5Cardputer.update();
+ if (M5Cardputer.Keyboard.isChange()) {
+ if (M5Cardputer.Keyboard.isPressed()) {
+ M5Cardputer.Speaker.tone(1437, 20);
+ Keyboard_Class::KeysState status = M5Cardputer.Keyboard.keysState();
+ for (auto i : status.word) {
+ data += i;
+ }
+ if (status.del && data.length() > 2) {
+ data.remove(data.length() - 1);
+ }
+ if (status.enter) {
+ data.remove(0, 2);
+ return data;
+ }
+ M5Cardputer.Display.fillRect(0, y - 4, M5Cardputer.Display.width(), 25, BLACK);
+ M5Cardputer.Display.drawString(data, 4, y);
+ }
+ }
+ delay(20);
+ }
+}
+
+int scanWifiNetworks() {
+ int networksCount = 0;
+
+ while (networksCount == 0) {
+ M5Cardputer.Display.fillScreen(TFT_BLACK);
+ M5Cardputer.Display.setTextColor(0x05A3);
+ M5Cardputer.Display.setTextSize(1.5);
+ M5Cardputer.Display.drawString("Scanning Networks...", 28, 60);
+ networksCount = WiFi.scanNetworks();
+
+ if (networksCount == 0) {
+ M5Cardputer.Display.drawString("No networks found", 45, 95);
+ delay(2000);
+ }
+ }
+
+ return networksCount;
+}
+
+String selectWifiNetwork(int numNetworks) {
+ int selectedNetwork = 0;
+
+ M5Cardputer.Display.fillScreen(TFT_BLACK);
+ M5Cardputer.Display.setTextColor(0x05A3);
+ M5Cardputer.Display.setTextSize(1.6);
+ M5Cardputer.Display.drawString("Select Network", 1, 1);
+ M5Cardputer.Display.setTextColor(TFT_LIGHTGRAY);
+
+ while (1) {
+ for (int i = 0; i < 7 && i < numNetworks; ++i) {
+ String ssid = WiFi.SSID(i);
+ if (i == selectedNetwork) {
+ M5Cardputer.Display.drawString("-> " + ssid, 1, 18 + i * 18);
+ } else {
+ M5Cardputer.Display.drawString(" " + ssid, 1, 18 + i * 18);
+ }
+ }
+
+ M5Cardputer.update();
+ if (M5Cardputer.Keyboard.isChange()) {
+ if (M5Cardputer.Keyboard.isPressed()) {
+ M5Cardputer.Speaker.tone(1437, 20);
+ M5Cardputer.Display.fillRect(0, 11, 20, 75, BLACK);
+ Keyboard_Class::KeysState status = M5Cardputer.Keyboard.keysState();
+
+ if (M5Cardputer.Keyboard.isKeyPressed(';') && selectedNetwork > 0) {
+ selectedNetwork--;
+ }
+ if (M5Cardputer.Keyboard.isKeyPressed('.') && selectedNetwork < min(4, numNetworks - 1)) {
+ selectedNetwork++;
+ }
+ if (status.enter) {
+ return WiFi.SSID(selectedNetwork);
+ }
+ }
+ }
+ delay(20);
+ }
+}
+
+void setWifiCredentials(String ssid, String password) {
+ Preferences& preferences = getPreferences();
+ preferences.begin("wifi_settings", false);
+ preferences.putString(NVS_SSID_KEY, ssid);
+ preferences.putString(NVS_PASS_KEY, password);
+ preferences.end();
+}
+
+void getWifiCredentials(String &ssid, String &password) {
+ Preferences& preferences = getPreferences();
+ preferences.begin("wifi_settings", false);
+ ssid = preferences.getString(NVS_SSID_KEY, "");
+ password = preferences.getString(NVS_PASS_KEY, "");
+ preferences.end();
+}
+
+bool connectToWifi(String wifiSSID, String wifiPassword) {
+ int tm = 0;
+
+ WiFi.disconnect();
+ WiFi.begin(wifiSSID.c_str(), wifiPassword.c_str());
+
+ M5Cardputer.Display.fillScreen(TFT_BLACK);
+ M5Cardputer.Display.setTextColor(0x05A3);
+ M5Cardputer.Display.drawString("Connecting", 70, 55);
+ M5Cardputer.Display.setTextColor(TFT_LIGHTGRAY);
+ M5Cardputer.Display.setCursor(30, 75);
+ M5Cardputer.Display.setTextSize(0.5); // for the loading dots
+
+ while (tm++ < 110 && WiFi.status() != WL_CONNECTED) {
+ delay(160);
+ M5Cardputer.Display.print(".");
+
+ if (tm == 55) {
+ M5Cardputer.Display.setCursor(30, 80);
+ }
+ }
+
+ if (WiFi.status() == WL_CONNECTED) {
+ return true;
+ }
+
+ WiFi.disconnect();
+ M5Cardputer.Display.setTextColor(TFT_LIGHTGREY);
+ M5Cardputer.Display.setTextSize(1.4);
+ M5Cardputer.Display.drawString("Failed to connect to WiFi", 18, 90);
+ delay(3000);
+ return false;
+}
+
+String askWifiPassword(String ssid) {
+ M5Cardputer.Display.fillScreen(TFT_BLACK);
+ M5Cardputer.Display.setTextColor(0x05A3);
+ M5Cardputer.Display.drawString("SSID: " + ssid, 2, 2);
+ M5Cardputer.Display.setTextColor(TFT_LIGHTGRAY);
+ M5Cardputer.Display.drawString("Enter the password", 37, 90);
+ return inputText("> ", 4, M5Cardputer.Display.height() - 24);
+}
+
+void setupWifi() {
+ bool connected = false;
+ int numNetworks = 0;
+ String savedSSID;
+ String savedPassword;
+ String selectedSSID;
+ String wifiPassword;
+
+ while (!connected) {
+ // Scan Networks
+ numNetworks = scanWifiNetworks();
+
+ // Select Network
+ selectedSSID = selectWifiNetwork(numNetworks);
+
+ // Get saved credentials
+ getWifiCredentials(savedSSID, savedPassword);
+
+ // Saved SSID is empty or selected SSID doesn't match saved SSID
+ if (savedSSID.isEmpty() || savedSSID != selectedSSID) {
+ wifiPassword = askWifiPassword(selectedSSID);
+ } else {
+ wifiPassword = savedPassword;
+ }
+
+ connected = connectToWifi(selectedSSID, wifiPassword);
+
+ if (connected) {
+ setWifiCredentials(selectedSSID, wifiPassword);
+ } else {
+ setWifiCredentials("", ""); // erase creds
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Vendors/CardWifiSetup.h b/src/Vendors/CardWifiSetup.h
new file mode 100644
index 00000000..81dfe97d
--- /dev/null
+++ b/src/Vendors/CardWifiSetup.h
@@ -0,0 +1,35 @@
+/**
+ * @file CardWifiSetup.h
+ * @author Aurélio Avanzi Dutch version Roland Breedveld adapted by Milton Matuda for Mic WebServer
+ * @brief https://github.com/cyberwisk/M5Card_Wifi_KeyBoard_Setup/tree/main/M5Card_Wifi_KeyBoard_Setup
+ * @version Apha 0.4BR
+ * @date 2024-11-14
+ *
+ * @Hardwares: M5Cardputer - https://docs.m5stack.com/en/core/Cardputer
+ * @Dependent Librarys:
+ * M5Cardputer: https://github.com/m5stack/M5Cardputer
+ * WiFi: https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFi
+ **/
+
+#pragma once
+
+#include <WiFi.h>
+#include <M5Cardputer.h>
+#include <Preferences.h>
+
+#define NVS_SSID_KEY "wifi_ssid"
+#define NVS_PASS_KEY "wifi_pass"
+
+inline Preferences& getPreferences() {
+ static Preferences preferences;
+ return preferences;
+}
+
+String inputText(const String& prompt, int x, int y);
+int scanWifiNetworks();
+String selectWifiNetwork(int numNetworks);
+void setWifiCredentials(String ssid, String password);
+void getWifiCredentials(String& ssid, String& password);
+bool connectToWifi(String wifiSSID, String wifiPassword);
+String askWifiPassword(String ssid);
+void setupWifi();
diff --git a/src/Vendors/MakeHex.cpp b/src/Vendors/MakeHex.cpp
new file mode 100644
index 00000000..0d02c1de
--- /dev/null
+++ b/src/Vendors/MakeHex.cpp
@@ -0,0 +1,529 @@
+/*
+
+########################################################################################################################
+# #
+# #
+# This file was adapted from https://github.com/probonopd/MakeHex/. #
+# It takes an IRP string and return the raw IR sequence. By John Fine #
+# #
+# #
+########################################################################################################################
+
+*/
+
+// Copyright 2005 John S. Fine
+
+// You may use, copy, modify and/or distribute this program for private or commercial use provided that:
+// 1) You do not hold me responsible for any damage or negative consequences resulting from those activities.
+// 2) You include this copyright notice and disclaimer in any copy of any part or all of this program.
+// I do not provide any warranty of the correctness, safety, or suitibility of this program for any purpose.
+// If you do not agree to these conditions, you have no permission to use, copy, modify or distribute this program.
+
+#include "MakeHex.h"
+
+std::vector<float> encodeRemoteCommand(const InfraredCommand& cmd, const char* protocolString, int& frequency) {
+
+ // Adapted from
+ // https://github.com/probonopd/MakeHex/tree/master
+ // By John Fine
+
+ char irp[512] = ""; // IRP string, will contains all necessary infos to generate the IR sequence
+
+ // Device
+ if (cmd.getSubdevice() >= 0)
+ snprintf(irp, sizeof(irp), "Device=%d.%d\nFunction=%d\n", cmd.getDevice(), cmd.getSubdevice(), cmd.getFunction());
+ else
+ snprintf(irp, sizeof(irp), "Device=%d\nFunction=%d\n", cmd.getSubdevice(), cmd.getFunction());
+
+ // Protocol
+ int p = -1;
+ for (int i = 0; i < 62; i++) {
+ if (strcmp(protocolString, protocolDefinitions[i].name) == 0) {
+ p = i;
+ break;
+ }
+ }
+ if (p < 0) {
+ // Protocol not found, try for special protocols
+ int M = 0;
+ int L = 0;
+ char tempProt[100];
+ strncpy(tempProt, protocolString, sizeof(tempProt));
+ tempProt[sizeof(tempProt) - 1] = '\0';
+ for (int i = 0; i < strlen(tempProt); i++)
+ tempProt[i] = toupper(tempProt[i]); // Convert to uppercase
+
+ if (sscanf(tempProt, "RC6-%d-%d", &M, &L) == 2) {
+ char temp[512];
+ snprintf(temp, sizeof(temp), "Define M=%d\nDefine L=%d\n", M, L);
+ strncat(irp, temp, sizeof(irp) - strlen(irp) - 1);
+ protocolString = "rc6-M-L";
+ } else if (strcmp("NEC", tempProt) == 0) {
+ protocolString = "nec2";
+ } else if (strcmp("NECX", tempProt) == 0) {
+ protocolString = "NECx2";
+ }
+
+ // Search again for protocol
+ for (int i = 0; i < 62; i++) {
+ if (strcmp(protocolString, protocolDefinitions[i].name) == 0) {
+ p = i;
+ break;
+ }
+ }
+
+ // Default NEC2 if no protocol found
+ // NEC2 for reliabity which continuously sends the full command frame
+ if (p < 0) {
+ protocolString = "nec2";
+ for (int i = 0; i < 62; i++) {
+ if (strcmp(protocolString, protocolDefinitions[i].name) == 0) {
+ p = i;
+ break;
+ }
+ }
+ }
+ }
+
+ strncat(irp, protocolDefinitions[p].def, sizeof(irp) - strlen(irp) - 1);
+
+ // Frequency
+ const char* freqStr = strstr(protocolDefinitions[p].def, "Frequency=");
+ if (freqStr != nullptr) {
+ sscanf(freqStr, "Frequency=%d", &frequency);
+ frequency = frequency / 1000; // Convert to kHz for sendRaw
+ }
+
+ // Validate IRP string
+ IRP Irp;
+ if (!Irp.readIrpString(irp)) {
+ // Bad IRP
+ return {};
+ }
+
+ // Set values
+ Irp.m_value['D' - 'A'] = cmd.getDevice();
+ Irp.m_value['S' - 'A'] = cmd.getSubdevice();
+ Irp.m_value['F' - 'A'] = cmd.getFunction();
+ Irp.m_value['N' - 'A'] = -1;
+
+ // Generate IR sequence
+ int s, r;
+ float seq[256];
+ Irp.generate(&s, &r, seq);
+
+ // Convert to vector for easier handling
+ std::vector<float> result(seq, seq + 2 * (s + r));
+
+ return result;
+}
+
+unsigned int IRP::reverse(unsigned int Number) {
+ Number = ((Number & 0x55555555) << 1) + ((Number >> 1) & 0x55555555);
+ Number = ((Number & 0x33333333) << 2) + ((Number >> 2) & 0x33333333);
+ Number = ((Number & 0xF0F0F0F) << 4) + ((Number >> 4) & 0xF0F0F0F);
+ Number = ((Number & 0xFF00FF) << 8) + ((Number >> 8) & 0xFF00FF);
+ return (Number >> 16) + (Number << 16);
+}
+
+IRP::IRP() :
+ m_frequency(38400),
+ m_timeBase(1),
+ m_messageTime(0),
+ m_prefix(0),
+ m_suffix(0),
+ m_rPrefix(0),
+ m_rSuffix(0),
+ m_msb(false),
+ m_form(0),
+ m_bitGroup(2)
+{
+ memset(m_value, 0, sizeof(m_value));
+ memset(m_def, 0, sizeof(m_def));
+ memset(m_device, -1, sizeof(m_device));
+ memset(m_functions, -1, sizeof(m_functions));
+ memset(m_digits, 0, sizeof(m_digits));
+ m_mask[0] = 0;
+ for (int ndx = 1; ndx < 33; ++ndx)
+ m_mask[ndx] = 2 * m_mask[ndx - 1] + 1;
+}
+
+IRP::~IRP() {
+ for (int i = 0; i < 26; ++i) {
+ if (m_def[i]) {
+ free((void *)m_def[i]);
+ }
+ }
+ for (int i = 0; i < 16; ++i) {
+ if (m_digits[i]) {
+ free((void *)m_digits[i]);
+ }
+ }
+ free((void *)m_prefix);
+ free((void *)m_suffix);
+ free((void *)m_rPrefix);
+ free((void *)m_rSuffix);
+ free((void *)m_form);
+}
+
+bool IRP::match(const char* master) {
+ int len = strlen(master);
+ m_next = m_bufr + len;
+ return 0 == memcmp(m_bufr, master, len);
+}
+void IRP::setDigit(int d) {
+ m_digits[d] = copy();
+ while (d >= m_bitGroup) {
+ m_bitGroup <<= 1;
+ }
+}
+
+bool IRP::readIrpString(char* str) {
+ char* line = strtok(str, "\n");
+ while (line != NULL && line[0] != 0) {
+ strcpy(m_bufr, line);
+ line = m_bufr;
+
+ Value val;
+
+ // Convert to upper case, compress out blanks and discard comments
+ for (char* l2 = line; *l2 && *l2 != '\'' && *l2 != '\n'; l2++) {
+ if (*l2 != ' ' && *l2 != '\t')
+ *(line++) = toupper(*l2);
+ }
+ *line = 0;
+
+ // Recognise some Keywords
+ if (match("FREQUENCY=")) {
+ parseVal(val, const_cast<char*&>(m_next));
+ m_frequency = val.m_val;
+ } else if (match("TIMEBASE=")) {
+ parseVal(val, const_cast<char*&>(m_next));
+ m_timeBase = val.m_val;
+ } else if (match("MESSAGETIME=")) {
+ parseVal(val, const_cast<char*&>(m_next));
+ if (val.m_bits == 0)
+ val.m_val *= m_timeBase;
+ m_messageTime = val.m_val;
+ } else if (m_bufr[0] >= '0' && m_bufr[0] <= '9' && m_bufr[1] == '=') {
+ m_next = m_bufr + 2;
+ setDigit(m_bufr[0] - '0');
+ } else if (m_bufr[0] == '1' && m_bufr[1] >= '0' && m_bufr[1] <= '5' && m_bufr[2] == '=') {
+ m_next = m_bufr + 3;
+ setDigit(m_bufr[1] + (10 - '0'));
+ } else if (match("ZERO=")) {
+ setDigit(0);
+ } else if (match("ONE=")) {
+ setDigit(1);
+ } else if (match("TWO=")) {
+ setDigit(2);
+ } else if (match("THREE=")) {
+ setDigit(3);
+ } else if (match("PREFIX=")) {
+ m_prefix = copy();
+ } else if (match("SUFFIX=")) {
+ m_suffix = copy();
+ } else if (match("R-PREFIX=")) {
+ m_rPrefix = copy();
+ } else if (match("R-SUFFIX=")) {
+ m_rSuffix = copy();
+ } else if (match("FIRSTBIT=MSB")) {
+ m_msb = true;
+ } else if (match("FORM=")) {
+ m_form = copy();
+ } else if (match("DEFINE") || match("DEFAULT")) {
+ if (m_next[1] == '=') {
+ m_next += 2;
+ m_def[m_next[-2] - 'A'] = copy();
+ } else if (m_next[0] == '=' && m_next[2] == 'A' && m_next[3] == 'S') {
+ m_next += 4;
+ m_def[m_next[-3] - 'A'] = copy();
+ } else if (m_next[1] == 'A' && m_next[2] == 'S') {
+ m_next += 3;
+ m_def[m_next[-3] - 'A'] = copy();
+ }
+ } else if (match("DEVICE=")) {
+ getPair(m_device);
+ } else if (match("FUNCTION=")) {
+ getPair(m_functions);
+ if (m_next[0] == '.' && m_next[1] == '.') {
+ m_next += 2;
+ getPair(m_functions + 2);
+ }
+ }
+
+ line = strtok(NULL, "\n");
+ }
+
+ if (m_device[1] >= 0)
+ m_def['S' - 'A'] = 0;
+ if (m_functions[1] >= 0)
+ m_def['N' - 'A'] = 0;
+
+ return true;
+}
+
+void IRP::getPair(int* result) {
+ for (int nIndex = 0; nIndex < 2; nIndex++) {
+ int num = 0;
+ for (; *m_next; m_next++) {
+ if (*m_next >= '0' && *m_next <= '9')
+ num = num * 10 + *m_next - '0';
+ else
+ break;
+ }
+ result[nIndex] = num;
+ if (m_next[0] != '.' || m_next[1] < '0' || m_next[1] > '9')
+ break;
+ m_next++;
+ }
+}
+
+char* IRP::copy() {
+ return strdup(m_next);
+}
+
+void IRP::parseVal(Value& result, char*& in, int prec) {
+ if (*in >= 'A' && *in <= 'Z') {
+ int ndx = *(in++) - 'A';
+ const char* in2 = m_def[ndx];
+ if (in2) {
+ parseVal(result, const_cast<char*&>(in2), 0);
+ if (*in2) {
+ // error
+ }
+ } else {
+ result.m_val = m_value[ndx];
+ result.m_bits = 0;
+ }
+ } else if (*in >= '0' && *in <= '9') {
+ result.m_bits = 0;
+ result.m_val = 0.0;
+ do {
+ result.m_val = result.m_val * 10 + *(in++) - '0';
+ } while (*in >= '0' && *in <= '9');
+ } else switch (*in) {
+ case '-':
+ ++in;
+ parseVal(result, in, 1);
+ result.m_val = -result.m_val;
+ if (result.m_bits > 0)
+ result.m_bits = 0;
+ break;
+ case '~':
+ ++in;
+ parseVal(result, in, 1);
+ result.m_val = -(result.m_val + 1);
+ if (result.m_bits > 0)
+ result.m_val = (double)(((int)result.m_val) & m_mask[result.m_bits]);
+ break;
+ case '(':
+ ++in;
+ parseVal(result, in, 0);
+ if (*in == ')') {
+ ++in;
+ } else {
+ // error
+ }
+ break;
+ default:
+ // error
+ break;
+ }
+
+ if (*in == 'M') {
+ result.m_val *= 1000;
+ result.m_bits = -1;
+ ++in;
+ } else if (*in == 'U') {
+ result.m_bits = -1;
+ ++in;
+ }
+
+ for (;;) {
+ Value v2;
+ if (prec < 2) {
+ if (*in == '*') {
+ ++in;
+ parseVal(v2, in, 2);
+ result.m_val *= v2.m_val;
+ if (result.m_bits > 0)
+ result.m_bits = 0;
+ continue;
+ }
+ }
+ if (prec < 1) {
+ switch (*in) {
+ case '+':
+ ++in;
+ parseVal(v2, in, 1);
+ result.m_val += v2.m_val;
+ if (result.m_bits > 0)
+ result.m_bits = 0;
+ continue;
+ case '-':
+ ++in;
+ parseVal(v2, in, 1);
+ result.m_val -= v2.m_val;
+ if (result.m_bits > 0)
+ result.m_bits = 0;
+ continue;
+ case '^':
+ ++in;
+ parseVal(v2, in, 1);
+ result.m_val = ((int)result.m_val) ^ ((int)v2.m_val);
+ if (result.m_bits > 0 && (v2.m_bits <= 0 || v2.m_bits > result.m_bits))
+ result.m_bits = v2.m_bits;
+ continue;
+ }
+ }
+ if (prec < 3) {
+ if (*in == ':') {
+ ++in;
+ parseVal(v2, in, 3);
+ result.m_bits = v2.m_val;
+ if (*in == ':') {
+ ++in;
+ parseVal(v2, in, 3);
+ result.m_val = (double)(((int)result.m_val) >> ((int)v2.m_val));
+ }
+ if (result.m_bits < 0) {
+ result.m_bits = -result.m_bits;
+ result.m_val = (double)(reverse((int)result.m_val) >> (32 - result.m_bits));
+ }
+ result.m_val = (double)(((int)result.m_val) & m_mask[result.m_bits]);
+ continue;
+ }
+ }
+ break;
+ }
+}
+
+void IRP::generate(int* s, int* r, float* raw) {
+ m_hex.clear();
+ m_cumulative = 0.0;
+ m_pendingBits = (m_msb ? 1 : m_bitGroup);
+ int Single = genHex(m_form);
+ if (m_cumulative < m_messageTime)
+ genHex(m_cumulative - m_messageTime);
+ if (m_hex.size() & 1)
+ genHex(-1.0);
+ if (Single < 0)
+ Single = m_hex.size();
+ Single >>= 1;
+
+ int unit;
+ if (m_frequency) {
+ unit = floor(4145146. / m_frequency + 0.5);
+ } else {
+ float mn = m_hex[0];
+ for (int nIndex = 1; nIndex < m_hex.size(); nIndex++)
+ if (mn > m_hex[nIndex])
+ mn = m_hex[nIndex];
+ unit = 4.145146 * .125 * mn + 0.5;
+ unit &= -2;
+ }
+ if (unit <= 0)
+ unit = 1;
+
+ for (int nIndex = 0; nIndex < m_hex.size(); nIndex += 2) {
+ raw[nIndex] = m_hex[nIndex];
+ raw[nIndex + 1] = m_hex[nIndex + 1];
+ }
+
+ *s = Single;
+ *r = m_hex.size() / 2 - Single;
+ return;
+}
+
+int IRP::genHex(const char* Pattern) {
+ int Result = -1;
+ if (*Pattern == ';') {
+ Result = 0; // Single section is empty
+ Pattern++;
+ }
+ while (*Pattern) {
+ if (*Pattern == '*') {
+ genHex((Result >= 0 && m_rPrefix) ? m_rPrefix : m_prefix);
+ Pattern++;
+ } else if (*Pattern == '_') {
+ genHex((Result >= 0 && m_rSuffix) ? m_rSuffix : m_suffix);
+ Pattern++;
+ if (m_cumulative < m_messageTime) {
+ genHex(m_cumulative - m_messageTime);
+ }
+ } else if (*Pattern == '^') {
+ Pattern++;
+
+ Value val;
+ parseVal(val, const_cast<char*&>(Pattern));
+ if (val.m_bits == 0)
+ val.m_val *= m_timeBase;
+
+ if (m_cumulative < val.m_val) {
+ genHex(m_cumulative - val.m_val);
+ }
+ } else {
+ Value val;
+ parseVal(val, const_cast<char*&>(Pattern));
+
+ if (val.m_bits == 0)
+ val.m_val *= m_timeBase;
+ if (val.m_bits <= 0) {
+ genHex(val.m_val);
+ } else {
+ int Number = (int)(val.m_val);
+ if (m_msb)
+ Number = reverse(Number) >> (32 - val.m_bits);
+ while (--val.m_bits >= 0) {
+ if (m_msb) {
+ m_pendingBits = (m_pendingBits << 1) + (Number & 1);
+ if (m_pendingBits & m_bitGroup) {
+ genHex(m_digits[m_pendingBits - m_bitGroup]);
+ m_pendingBits = 1;
+ }
+ } else {
+ m_pendingBits = (m_pendingBits >> 1) + (Number & 1) * m_bitGroup;
+ if (m_pendingBits & 1) {
+ genHex(m_digits[m_pendingBits >> 1]);
+ m_pendingBits = m_bitGroup;
+ }
+ }
+ Number >>= 1;
+ }
+ }
+ }
+ if (*Pattern == ';') {
+ if (m_cumulative < m_messageTime) {
+ genHex(m_cumulative - m_messageTime);
+ }
+ if (m_hex.size() & 1) {
+ genHex(-1.0);
+ }
+ Result = m_hex.size();
+ m_cumulative = 0.0;
+ } else if (*Pattern != ',')
+ break;
+ Pattern++;
+ }
+ return Result;
+}
+
+void IRP::genHex(float number) {
+ if (number == 0.0)
+ return;
+ int nHex = m_hex.size();
+ if (number > 0) {
+ m_cumulative += number;
+ if (nHex & 1)
+ m_hex[nHex - 1] += number;
+ else
+ m_hex.push_back(number);
+ } else if (nHex) {
+ m_cumulative -= number;
+ if (nHex & 1)
+ m_hex.push_back(-number);
+ else
+ m_hex[nHex - 1] -= number;
+ }
+}
\ No newline at end of file
diff --git a/src/Vendors/MakeHex.h b/src/Vendors/MakeHex.h
new file mode 100644
index 00000000..d9c0e68e
--- /dev/null
+++ b/src/Vendors/MakeHex.h
@@ -0,0 +1,83 @@
+/*
+
+########################################################################################################################
+# #
+# #
+# This file was adapted from https://github.com/probonopd/MakeHex/. #
+# It takes an IRP string and return the raw IR sequence. By John Fine #
+# #
+# #
+########################################################################################################################
+
+*/
+
+// Copyright 2005 John S. Fine
+
+// You may use, copy, modify and/or distribute this program for private or commercial use provided that:
+// 1) You do not hold me responsible for any damage or negative consequences resulting from those activities.
+// 2) You include this copyright notice and disclaimer in any copy of any part or all of this program.
+// I do not provide any warranty of the correctness, safety, or suitibility of this program for any purpose.
+// If you do not agree to these conditions, you have no permission to use, copy, modify or distribute this program.
+
+#pragma once
+
+#include <vector>
+#include <cstring>
+#include <cstdlib>
+#include <cctype>
+#include <cmath>
+#include <cstdio>
+#include <vector>
+#include <Data/InfraredProtocolDefinitions.h>
+#include <Models/InfraredCommand.h>
+
+std::vector<float> encodeRemoteCommand(const InfraredCommand& cmd, const char* protocolString, int& frequency);
+
+class IRP {
+public:
+ IRP();
+ ~IRP();
+
+ bool readIrpString(char* str);
+ void generate(int* s, int* r, float* raw);
+
+private:
+ struct Value {
+ double m_val;
+ int m_bits;
+ };
+
+ unsigned int reverse(unsigned int Number);
+ bool match(const char* master);
+ void setDigit(int d);
+ char* copy();
+ void getPair(int* result);
+ void parseVal(Value& result, char*& in, int prec = 0);
+ void genHex(float number);
+ int genHex(const char* Pattern);
+ char* m_digits[16];
+ int m_frequency;
+ int m_timeBase;
+ int m_messageTime;
+ int m_device[2];
+ int m_functions[4];
+ bool m_msb;
+ const char* m_form;
+ const char* m_prefix;
+ const char* m_suffix;
+ const char* m_rPrefix;
+ const char* m_rSuffix;
+ const char* m_def[26];
+ char m_bufr[1024];
+ const char* m_next;
+ int m_bitGroup;
+ int m_pendingBits;
+ double m_cumulative;
+ unsigned int m_mask[33];
+ std::vector<float> m_hex;
+
+public:
+ int m_value[26];
+};
+
+
diff --git a/src/Views/IDeviceView.h b/src/Views/IDeviceView.h
new file mode 100644
index 00000000..94ff26ee
--- /dev/null
+++ b/src/Views/IDeviceView.h
@@ -0,0 +1,40 @@
+// IDeviceView.h
+#pragma once
+
+#include <string>
+#include "Enums/ModeEnum.h"
+#include "Enums/TerminalTypeEnum.h"
+#include "Models/PinoutConfig.h"
+
+class IDeviceView {
+public:
+ virtual ~IDeviceView() = default;
+
+ // Initiliaze the view
+ virtual void initialize() = 0;
+
+ // Show logo
+ virtual void logo() = 0;
+
+ // Show Welcome screen
+ virtual void welcome(TerminalTypeEnum& terminalType, std::string& terminalInfos) = 0;
+
+ // Show the mode and pinout
+ virtual void show(PinoutConfig& config) = 0;
+
+ // Show loading
+ virtual void loading() = 0;
+
+ // Clear the view
+ virtual void clear() = 0;
+
+ // Display a main title
+ virtual void topBar(const std::string& title, bool submenu, bool searchBar) = 0;
+
+ // Select an item horizontaly
+ virtual void horizontalSelection(
+ const std::vector<std::string>& options,
+ uint16_t selectedIndex,
+ const std::string& description1,
+ const std::string& description2) = 0;
+};
diff --git a/src/Views/ITerminalView.h b/src/Views/ITerminalView.h
new file mode 100644
index 00000000..047d5fd0
--- /dev/null
+++ b/src/Views/ITerminalView.h
@@ -0,0 +1,22 @@
+#pragma once
+#include <string>
+#include <Enums/TerminalTypeEnum.h>
+
+class ITerminalView {
+public:
+ virtual ~ITerminalView() = default;
+
+ // Initialize the terminal
+ virtual void initialize() = 0;
+
+ // Show welcome message with logo and infos
+ virtual void welcome(TerminalTypeEnum& terminalType, std::string& terminalInfos) = 0;
+
+ // Print to the terminal
+ virtual void print(const std::string& text) = 0;
+ virtual void println(const std::string& text) = 0;
+ virtual void printPrompt(const std::string& mode = "HIZ") = 0;
+
+ // Clear the terminal
+ virtual void clear() = 0;
+};
diff --git a/src/Views/M5DeviceView.cpp b/src/Views/M5DeviceView.cpp
new file mode 100644
index 00000000..b42d2bba
--- /dev/null
+++ b/src/Views/M5DeviceView.cpp
@@ -0,0 +1,243 @@
+#include "M5DeviceView.h"
+
+
+void M5DeviceView::initialize() {
+ M5.Lcd.fillScreen(BACKGROUND_COLOR);
+}
+
+void M5DeviceView::welcome(TerminalTypeEnum& terminalType, std::string& terminalInfos) {
+ if (terminalType == TerminalTypeEnum::Serial) {
+ welcomeSerial(terminalInfos);
+ } else {
+ welcomeWeb(terminalInfos);
+ }
+}
+
+void M5DeviceView::logo() {
+ clear();
+
+ M5.Lcd.fillRoundRect(8, 40, 220, 60, DEFAULT_ROUND_RECT, RECT_COLOR_DARK);
+ M5.Lcd.drawRoundRect(8, 40, 220, 60, DEFAULT_ROUND_RECT, PRIMARY_COLOR);
+
+ M5.Lcd.setTextSize(3);
+ M5.Lcd.setTextColor(PRIMARY_COLOR);
+ M5.Lcd.setCursor(31, 49);
+ M5.Lcd.printf("Bus Pirate");
+
+ M5.Lcd.setTextSize(1.6);
+ M5.Lcd.setCursor(43, 80);
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ M5.Lcd.printf("Version 0.1 - Geo");
+
+ delay(3000);
+}
+
+void M5DeviceView::show(PinoutConfig& config) {
+ clear();
+
+ const auto& mappings = config.getMappings();
+ auto mode = config.getMode();
+
+
+ M5.Lcd.setTextSize(2);
+
+ if (mappings.size() > 4) {
+ showDetailedConfig(config, 255); // pas de selec active
+ return;
+ }
+
+ showModeName(mode, 5);
+
+ if (mappings.empty()) {
+ noMapping();
+ }
+
+ int boxHeight = 24;
+ int startY = 25;
+ int spacing = 4;
+
+ for (size_t i = 0; i < mappings.size(); ++i) {
+ const std::string& mapping = mappings[i];
+ int y = startY + i * (boxHeight + spacing);
+
+ M5.Lcd.fillRoundRect(DEFAULT_MARGIN, y, M5.Lcd.width() - 2 * DEFAULT_MARGIN, boxHeight, DEFAULT_ROUND_RECT, RECT_COLOR_DARK);
+ M5.Lcd.drawRoundRect(DEFAULT_MARGIN, y, M5.Lcd.width() - 2 * DEFAULT_MARGIN, boxHeight, DEFAULT_ROUND_RECT, PRIMARY_COLOR);
+
+ int16_t textX = (M5.Lcd.width() - M5.Lcd.textWidth(mapping.c_str())) / 2;
+ int16_t textY = y + (boxHeight - M5.Lcd.fontHeight()) / 2 + 1;
+ M5.Lcd.setCursor(textX, textY);
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ M5.Lcd.print(mapping.c_str());
+ }
+}
+
+void M5DeviceView::topBar(const std::string& title, bool submenu, bool searchBar) {
+ M5.Lcd.fillRect(0, 0, M5.Lcd.width(), TOP_BAR_SIZE, BACKGROUND_COLOR);
+
+ M5.Lcd.setTextSize(2);
+ M5.Lcd.setTextColor(TEXT_COLOR);
+
+ std::string text = title;
+ if (searchBar) {
+ text = title.empty() ? "Type to search" : title;
+ }
+
+ int x = (M5.Lcd.width() -M5.Lcd.textWidth(text.c_str())) / 2;
+ M5.Lcd.setCursor(x, 16);
+ M5.Lcd.printf(text.c_str());
+}
+
+void M5DeviceView::horizontalSelection(
+ const std::vector<std::string>& options,
+ uint16_t selectedIndex,
+ const std::string& description1,
+ const std::string& description2) {
+
+ M5.Lcd.fillRect(0, TOP_BAR_SIZE, M5.Lcd.width(),M5.Lcd.height(), BACKGROUND_COLOR);
+
+ // Description 1
+ M5.Lcd.setTextSize(1.7);
+ M5.Lcd.setTextColor(PRIMARY_COLOR);
+ M5.Lcd.setCursor((M5.Lcd.width() -M5.Lcd.textWidth(description1.c_str())) / 2, 46);
+ M5.Lcd.printf(description1.c_str());
+
+ // Description 2
+ M5.Lcd.setTextSize(1);
+ M5.Lcd.setCursor((M5.Lcd.width() -M5.Lcd.textWidth(description2.c_str())) / 2, 113);
+ M5.Lcd.printf(description2.c_str());
+
+ // Option sélectionnée (nom)
+ const std::string& option = options[selectedIndex];
+ M5.Lcd.fillRoundRect(40, 72, M5.Lcd.width() - 80, 50, DEFAULT_ROUND_RECT, RECT_COLOR_DARK);
+ M5.Lcd.drawRoundRect(40, 72, M5.Lcd.width() - 80, 50, DEFAULT_ROUND_RECT, RECT_COLOR_LIGHT);
+
+ M5.Lcd.setTextSize(2);
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ M5.Lcd.setCursor((M5.Lcd.width() -M5.Lcd.textWidth(option.c_str())) / 2, 90);
+ M5.Lcd.printf(option.c_str());
+
+ // Flèches gauche/droite
+ M5.Lcd.setCursor(15, 91);
+ M5.Lcd.printf("<");
+ M5.Lcd.setCursor(M5.Lcd.width() - 27, 91);
+ M5.Lcd.printf(">");
+}
+
+void M5DeviceView::welcomeSerial(const std::string& baudStr) {
+ M5.Lcd.fillScreen(BACKGROUND_COLOR);
+
+ M5.Lcd.setCursor(14, 32);
+ M5.Lcd.setTextSize(1.8);
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ M5.Lcd.println("Open Serial (USB COM)");
+
+ M5.Lcd.setTextSize(2);
+ M5.Lcd.fillRoundRect(8, 60, 220, 40, DEFAULT_ROUND_RECT, RECT_COLOR_DARK);
+ M5.Lcd.drawRoundRect(8, 60, 220, 40, DEFAULT_ROUND_RECT, PRIMARY_COLOR);
+
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ auto baud = "Baudrate: " + baudStr;
+ int16_t x = (M5.Lcd.width() - M5.Lcd.textWidth(baud.c_str())) / 2;
+ M5.Lcd.setCursor(x, 73);
+ M5.Lcd.printf(baud.c_str());
+}
+
+void M5DeviceView::welcomeWeb(const std::string& ipStr) {
+ M5.Lcd.fillScreen(BACKGROUND_COLOR);
+
+ M5.Lcd.setCursor(16, 34);
+ M5.Lcd.setTextSize(1.6);
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ M5.Lcd.println("Open browser to connect");
+
+ M5.Lcd.setTextSize(1.8);
+ M5.Lcd.fillRoundRect(8, 60, 220, 40, DEFAULT_ROUND_RECT, RECT_COLOR_DARK);
+ M5.Lcd.drawRoundRect(8, 60, 220, 40, DEFAULT_ROUND_RECT, PRIMARY_COLOR);
+
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ auto ip = "http://" + ipStr;
+ int16_t x = (M5.Lcd.width() - M5.Lcd.textWidth(ip.c_str())) / 2;
+ M5.Lcd.setCursor(x, 73);
+ M5.Lcd.printf( ip.c_str());
+}
+
+void M5DeviceView::clear() {
+ M5.Lcd.fillScreen(BACKGROUND_COLOR);
+}
+
+void M5DeviceView::showModeName(std::string& mode, int y) {
+ auto modeName = "Mode: " + mode;
+ int16_t titleX = (M5.Lcd.width() - M5.Lcd.textWidth(modeName.c_str())) / 2;
+ M5.Lcd.setTextColor(TEXT_COLOR, BLACK);
+ M5.Lcd.setCursor(titleX, y);
+ M5.Lcd.print("Mode: ");
+ M5.Lcd.setTextColor(PRIMARY_COLOR, BLACK);
+ M5.Lcd.print(mode.c_str());
+
+}
+
+void M5DeviceView::noMapping() {
+ // Box frame
+ M5.Lcd.drawRoundRect(10, 35, M5.Lcd.width() - 20, 90, DEFAULT_ROUND_RECT, PRIMARY_COLOR);
+
+ // Description
+ std::string map = "No mapping defined";
+ M5.Lcd.setTextSize(1.5);
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ int16_t titleX = (M5.Lcd.width() - M5.Lcd.textWidth(map.c_str())) / 2;
+ M5.Lcd.setCursor(titleX, 75);
+ M5.Lcd.printf(map.c_str());
+}
+
+void M5DeviceView::showDetailedConfig(const PinoutConfig& config, int selectedIndex) {
+ clear();
+
+ const auto& mappings = config.getMappings();
+ auto mode = config.getMode();
+ const size_t count = mappings.size();
+
+ uint8_t halfWidth = (M5.Lcd.width() - 20) / 2;
+ uint8_t sizeY = 22;
+ uint8_t startY = 10;
+ uint8_t stepY = 26;
+ uint8_t margin = DEFAULT_MARGIN;
+ uint8_t textOffsetY = 13;
+ bool selected;
+
+ M5.Lcd.setTextSize(2);
+ showModeName(mode, M5.Lcd.height() - 15);
+
+ M5.Lcd.setTextSize(1);
+
+ for (size_t i = 0; i < count; ++i) {
+ selected = (i == selectedIndex);
+
+ uint8_t col = i / 4; // gauche (0) ou droite (1)
+ uint8_t xPos = margin + col * (halfWidth + margin);
+ uint8_t yPos = startY + (i % 4) * stepY;
+
+ drawRect(selected, xPos, yPos, halfWidth, sizeY);
+ M5.Lcd.setCursor(xPos + margin + 5, yPos + textOffsetY);
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ M5.Lcd.print(mappings[i].c_str());
+ }
+}
+
+void M5DeviceView::drawRect(bool selected, uint8_t margin, uint16_t startY, uint16_t sizeX, uint16_t sizeY) {
+ // Draw rect
+ if (selected) {
+ M5.Lcd.fillRoundRect(margin, startY, sizeX, sizeY, DEFAULT_ROUND_RECT, PRIMARY_COLOR);
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ } else {
+ M5.Lcd.fillRoundRect(margin, startY, sizeX, sizeY, DEFAULT_ROUND_RECT, RECT_COLOR_DARK);
+ M5.Lcd.drawRoundRect(margin, startY, sizeX, sizeY, DEFAULT_ROUND_RECT, PRIMARY_COLOR);
+ M5.Lcd.setTextColor(TEXT_COLOR);
+ }
+}
+
+void M5DeviceView::loading() {
+ clear();
+ M5.Lcd.setTextSize(1.5);
+ M5.Lcd.setTextColor(PRIMARY_COLOR);
+ M5.Lcd.drawString("Loading...", 75, 60);
+}
\ No newline at end of file
diff --git a/src/Views/M5DeviceView.h b/src/Views/M5DeviceView.h
new file mode 100644
index 00000000..66d79f13
--- /dev/null
+++ b/src/Views/M5DeviceView.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include "IDeviceView.h"
+#include <M5Unified.h>
+#include "Enums/ModeEnum.h"
+#include "States/GlobalState.h"
+#include "Models/PinoutConfig.h"
+#include "Enums/ModeEnum.h"
+#include "Enums/TerminalTypeEnum.h"
+
+#define BACKGROUND_COLOR TFT_BLACK
+#define PRIMARY_COLOR 0x05A3
+#define RECT_COLOR_DARK 0x0841
+#define RECT_COLOR_LIGHT 0xd69a
+#define TEXT_COLOR 0xE71C
+#define TEXT_COLOR_ALT TFT_DARKGRAY
+
+#define DEFAULT_MARGIN 5
+#define DEFAULT_ROUND_RECT 5
+
+#define TOP_BAR_SIZE 30
+
+class M5DeviceView : public IDeviceView {
+public:
+ void initialize() override;
+ void logo() override;
+ void welcome(TerminalTypeEnum& terminalType, std::string& terminalInfos) override;
+ void show(PinoutConfig& config) override;
+ void loading() override;
+ void clear() override;
+ void topBar(const std::string& title, bool submenu, bool searchBar) override;
+ void horizontalSelection(
+ const std::vector<std::string>& options,
+ uint16_t selectedIndex,
+ const std::string& description1,
+ const std::string& description2) override;
+
+private:
+ void welcomeSerial(const std::string& baudStr);
+ void welcomeWeb(const std::string& ipStr);
+ void showDetailedConfig(const PinoutConfig& config, int selectedIndex);
+ void drawRect(bool selected, uint8_t margin, uint16_t startY, uint16_t sizeX, uint16_t sizeY);
+ void showModeName(std::string& mode, int y);
+ void noMapping();
+};
diff --git a/src/Views/SerialTerminalView.cpp b/src/Views/SerialTerminalView.cpp
new file mode 100644
index 00000000..46954b0f
--- /dev/null
+++ b/src/Views/SerialTerminalView.cpp
@@ -0,0 +1,52 @@
+#include "SerialTerminalView.h"
+
+void SerialTerminalView::initialize() {
+ Serial.begin(baudrate); // Serial USB CDC, to the PC
+ while (!Serial) {
+ delay(10);
+ }
+}
+
+void SerialTerminalView::welcome(TerminalTypeEnum& terminalType, std::string& terminalInfos) {
+ Serial.println("");
+ Serial.println("");
+ Serial.println(" ____ _ _ ");
+ Serial.println(" | __ ) _ _ ___ _ __ (_)_ __ __ _| |_ ___ ");
+ Serial.println(" | _ \\| | | / __| | '_ \\| | '__/ _` | __/ _ \\");
+ Serial.println(" | |_) | |_| \\__ \\ | |_) | | | | (_| | || __/");
+ Serial.println(" |____/ \\__,_|___/ | .__/|_|_| \\__,_|\\__\\___|");
+ Serial.println(" |_| ");
+ Serial.println(" Version 0.1 Ready to board");
+ Serial.println("");
+ Serial.println(" Type 'mode' to start or 'help' for commands");
+ Serial.println("");
+
+}
+
+void SerialTerminalView::print(const std::string& text) {
+ Serial.print(text.c_str());
+}
+
+void SerialTerminalView::println(const std::string& text) {
+ Serial.println(text.c_str());
+}
+
+void SerialTerminalView::printPrompt(const std::string& mode) {
+ if (!mode.empty()) {
+ Serial.print(mode.c_str());
+ Serial.print("> ");
+ } else {
+ Serial.print("> ");
+ }
+}
+
+void SerialTerminalView::clear() {
+ Serial.write(27); // ESC
+ Serial.print("[2J"); // erase screen
+ Serial.write(27);
+ Serial.print("[H"); // default cursor pos
+}
+
+void SerialTerminalView::setBaudrate(unsigned long baud) {
+ baudrate = baud;
+}
\ No newline at end of file
diff --git a/src/Views/SerialTerminalView.h b/src/Views/SerialTerminalView.h
new file mode 100644
index 00000000..c719c350
--- /dev/null
+++ b/src/Views/SerialTerminalView.h
@@ -0,0 +1,22 @@
+#pragma once
+
+#include <Arduino.h>
+#include <string>
+#include <Views/ITerminalView.h>
+#include <States/GlobalState.h>
+#include <Enums/TerminalTypeEnum.h>
+
+class SerialTerminalView : public ITerminalView {
+public:
+
+ void initialize() override;
+ void welcome(TerminalTypeEnum& terminalType, std::string& terminalInfos) override;
+ void print(const std::string& text) override;
+ void println(const std::string& text) override;
+ void printPrompt(const std::string& mode = "HIZ") override;
+ void clear() override;
+ void setBaudrate(unsigned long baudrate);
+
+private:
+ unsigned long baudrate = 1152200;
+};
diff --git a/src/Views/WebTerminalView.cpp b/src/Views/WebTerminalView.cpp
new file mode 100644
index 00000000..fae51b56
--- /dev/null
+++ b/src/Views/WebTerminalView.cpp
@@ -0,0 +1,28 @@
+#include "WebTerminalView.h"
+
+WebTerminalView::WebTerminalView(WebSocketServer& server)
+ : server(server) {}
+
+void WebTerminalView::initialize() {}
+
+void WebTerminalView::welcome(TerminalTypeEnum& terminalType, std::string& terminalInfos) {
+ const std::string msg = "Welcome to Web CLI\n";
+ server.sendText(msg);
+}
+
+void WebTerminalView::print(const std::string& text) {
+ server.sendText(text);
+}
+
+void WebTerminalView::println(const std::string& text) {
+ server.sendText(text + "\n");
+}
+
+void WebTerminalView::printPrompt(const std::string& mode) {
+ const std::string prompt = mode + "> ";
+ server.sendText(prompt);
+}
+
+void WebTerminalView::clear() {
+ server.sendText("[Screen cleared]\n"); // ph
+}
diff --git a/src/Views/WebTerminalView.h b/src/Views/WebTerminalView.h
new file mode 100644
index 00000000..bf39b819
--- /dev/null
+++ b/src/Views/WebTerminalView.h
@@ -0,0 +1,19 @@
+#pragma once
+#include "ITerminalView.h"
+#include <string>
+#include "Servers/WebSocketServer.h"
+#include "Enums/TerminalTypeEnum.h"
+
+class WebTerminalView : public ITerminalView {
+public:
+ WebTerminalView(WebSocketServer &server);
+
+ void initialize() override;
+ void welcome(TerminalTypeEnum& terminalType, std::string& terminalInfos) override;
+ void print(const std::string& text) override;
+ void println(const std::string& text) override;
+ void printPrompt(const std::string& mode) override;
+ void clear() override;
+private:
+ WebSocketServer server;
+};
diff --git a/src/main.cpp b/src/main.cpp
new file mode 100644
index 00000000..3b8aea75
--- /dev/null
+++ b/src/main.cpp
@@ -0,0 +1,93 @@
+#ifndef UNIT_TEST
+
+#include <M5Cardputer.h>
+#include <Views/SerialTerminalView.h>
+#include <Views/M5DeviceView.h>
+#include <Views/WebTerminalView.h>
+#include <Inputs/SerialTerminalInput.h>
+#include <Inputs/CardputerInput.h>
+#include <Providers/DependencyProvider.h>
+#include <Dispatchers/ActionDispatcher.h>
+#include <Servers/HttpServer.h>
+#include <Servers/WebSocketServer.h>
+#include <Inputs/WebTerminalInput.h>
+#include <Selectors/HorizontalSelector.h>
+#include <Config/TerminalTypeConfigurator.h>
+#include <Config/WifiTypeConfigurator.h>
+#include <Enums/TerminalTypeEnum.h>
+#include <States/GlobalState.h>
+
+void setup() {
+ // Setup the cardputer
+ auto cfg = M5.config();
+ M5Cardputer.begin(cfg, true);
+
+ // Device View/Input
+ M5DeviceView deviceView;
+ CardputerInput deviceInput;
+ deviceView.logo();
+
+ // Select the terminal type
+ HorizontalSelector selector(deviceView, deviceInput);
+ TerminalTypeConfigurator configurator(selector);
+ GlobalState& state = GlobalState::getInstance();
+ TerminalTypeEnum terminalType = configurator.configure();
+
+ switch (terminalType) {
+ case TerminalTypeEnum::Serial: {
+ // Serial View/Input
+ SerialTerminalView serialView;
+ SerialTerminalInput serialInput;
+
+ // Baudrate
+ auto baud = std::to_string(state.getSerialTerminalBaudRate());
+ serialView.setBaudrate(state.getSerialTerminalBaudRate());
+
+ // Build the provider for serial type and run the dispatcher lopp
+ DependencyProvider provider(serialView, deviceView, serialInput, deviceInput);
+ ActionDispatcher dispatcher(provider);
+ dispatcher.setup(terminalType, baud);
+ dispatcher.run();
+ break;
+ }
+ case TerminalTypeEnum::WiFiAp: // Not Yet Implemented
+ case TerminalTypeEnum::WiFiClient: {
+ // Configure Wi-Fi mode
+ WifiTypeConfigurator wifiTypeConfigurator;
+ auto webIp = wifiTypeConfigurator.configure(terminalType);
+ state.setTerminalIp(webIp);
+
+ // Configure Server
+ httpd_handle_t server = nullptr;
+ httpd_config_t config = HTTPD_DEFAULT_CONFIG();
+ if (httpd_start(&server, &config) != ESP_OK) {
+ return;
+ }
+ HttpServer httpServer(server);
+ WebSocketServer wsServer(server);
+
+ // Web View/Input
+ WebTerminalView webView(wsServer);
+ WebTerminalInput webInput(wsServer);
+ deviceView.loading();
+ delay(2000); // let the server begin
+
+ // Setup routes for index and ws
+ httpServer.setupRoutes();
+ wsServer.setupRoutes();
+
+ // Build the provider for webui type and run the dispatcher loop
+ DependencyProvider provider(webView, deviceView, webInput, deviceInput);
+ ActionDispatcher dispatcher(provider);
+ dispatcher.setup(terminalType, webIp);
+ dispatcher.run();
+ break;
+ }
+ }
+}
+
+void loop() {
+ // Empty as all logic is handled in dispatcher
+}
+
+#endif
\ No newline at end of file
diff --git a/test/Selectors/TestHorizontalSelector.cpp b/test/Selectors/TestHorizontalSelector.cpp
new file mode 100644
index 00000000..29392f25
--- /dev/null
+++ b/test/Selectors/TestHorizontalSelector.cpp
@@ -0,0 +1,52 @@
+#ifndef TEST_HORIZONTAL_SELECTORS_H
+#define TEST_HORIZONTAL_SELECTORS_H
+
+#include <unity.h>
+#include "../src/Selectors/HorizontalSelector.h"
+#include "../Views/MockView.h"
+#include "../Inputs/MockInput.h"
+
+void test_horizontal_selector_confirm() {
+ MockView mockView;
+ MockInput mockInput;
+ InactivityManager manager(mockView);
+
+ HorizontalSelector horizontalSelector(mockView, mockInput, manager);
+
+ std::vector<std::string> options = {"OptionA", "OptionB", "OptionC"};
+ std::string title = "Horizontal Selector Test";
+
+ // Mock Input
+ mockInput.enqueueKey(KEY_ARROW_RIGHT);
+ mockInput.enqueueKey(KEY_ARROW_RIGHT);
+ mockInput.enqueueKey(KEY_ARROW_LEFT);
+ mockInput.enqueueKey(KEY_OK);
+
+ int selectedIndex = horizontalSelector.select(title, options);
+
+ TEST_ASSERT_EQUAL(1, selectedIndex); // La deuxième option est sélectionnée
+ TEST_ASSERT_TRUE(mockView.topBarCalled);
+ TEST_ASSERT_TRUE(mockView.horizontalSelectionCalled);
+ TEST_ASSERT_EQUAL_STRING(title.c_str(), mockView.lastTitle.c_str());
+ TEST_ASSERT_EQUAL_STRING("OptionB", mockView.displayedOptions[selectedIndex].c_str());
+}
+
+void test_horizontal_selector_cancel() {
+ MockView mockView;
+ MockInput mockInput;
+ InactivityManager manager(mockView);
+
+ HorizontalSelector horizontalSelector(mockView, mockInput, manager);
+
+ std::vector<std::string> options = {"OptionA", "OptionB", "OptionC"};
+ std::string title = "Horizontal Selector Test";
+
+ // Mock Input
+ mockInput.enqueueKey(KEY_ESC_CUSTOM);
+
+ int selectedIndex = horizontalSelector.select(title, options);
+
+ TEST_ASSERT_EQUAL(-1, selectedIndex); // Retourne -1 si l'utilisateur appuie sur RETURN
+}
+
+#endif // TEST_HORIZONTAL_SELECTORS_H
diff --git a/test/main.cpp b/test/main.cpp
new file mode 100644
index 00000000..354e583d
--- /dev/null
+++ b/test/main.cpp
@@ -0,0 +1,11 @@
+#include <unity.h>
+
+void setup() {
+ UNITY_BEGIN();
+ // Tests
+ UNITY_END();
+}
+
+void loop() {
+ // Required by PlatformIO
+}
diff --git a/webui/index.h b/webui/index.h
new file mode 100644
index 00000000..11a066ba
--- /dev/null
+++ b/webui/index.h
@@ -0,0 +1,25 @@
+#pragma once
+
+inline const char* index_html = R"rawliteral(
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="UTF-8">
+ <title>ESP32 Bus Pirate</title>
+ <link rel="stylesheet" href="/style.css">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, user-scalable=no">
+</head>
+<body>
+ <main>
+ <textarea id="output" readonly></textarea>
+ <div class="input-area">
+ <input type="text" id="command" placeholder="Enter command" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false">
+ <button onclick="sendCommand()">Send</button>
+ </div>
+ <h3 id="history-title" style="display: none;">Command History</h3>
+ <div id="history" class="history-area"></div>
+ </main>
+ <script src="/scripts.js"></script>
+</body>
+</html>
+)rawliteral";
diff --git a/webui/scripts.h b/webui/scripts.h
new file mode 100644
index 00000000..03872e6f
--- /dev/null
+++ b/webui/scripts.h
@@ -0,0 +1,107 @@
+#pragma once
+
+inline const char* scripts_js = R"rawliteral(
+
+let socket = null;
+let pendingEchoLines = 0;
+let reconnectInterval = 1000; // ms
+
+function connectSocket() {
+ socket = new WebSocket("ws://" + window.location.host + "/ws");
+
+ socket.onopen = function () {
+ console.log("[WebSocket] Connected");
+ };
+
+ socket.onmessage = function (event) {
+ const output = document.getElementById("output");
+ const lines = event.data.split("\n");
+
+ if (pendingEchoLines > 0) {
+ pendingEchoLines -= 1;
+ return;
+ }
+
+ output.value += lines.join("\n");
+ output.scrollTop = output.scrollHeight;
+ console.log("[WebSocket] Recv:", event.data);
+ };
+
+ socket.onerror = function (error) {
+ console.error("[WebSocket] Error:", error);
+ };
+
+ socket.onclose = function () {
+ console.warn("[WebSocket] Disconnected. Retrying in 1s...");
+ setTimeout(connectSocket, reconnectInterval);
+ };
+}
+
+function sendCommand() {
+ const input = document.getElementById("command");
+ const output = document.getElementById("output");
+ const cmd = input.value.trim();
+
+ if (socket.readyState !== WebSocket.OPEN) return;
+
+ socket.send(cmd + "\n");
+ pendingEchoLines = cmd.length;
+
+ input.value = "";
+ output.value += cmd;
+ addToHistory(cmd);
+}
+
+// Bind Enter to sendCommand
+window.addEventListener("DOMContentLoaded", function () {
+ const input = document.getElementById("command");
+
+ input.addEventListener("keydown", function (event) {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ sendCommand();
+ }
+ });
+
+ // Initialiser l'affichage du terminal
+ output.value =
+` ____ _ _
+ | __ ) _ _ ___ _ __ (_)_ __ __ _| |_ ___
+ | _ \\| | | / __| | '_ \\| | '__/ _\` | __/ _ \\
+ | |_) | |_| \\__ \\ | |_) | | | | (_| | || __/
+ |____/ \\__,_|___/ | .__/|_|_| \\__,_|\\__\\___|
+ |_|
+ Version 0.1 Ready to board
+
+ Type 'mode' to start or 'help' for commands
+
+HIZ> `;
+
+ connectSocket(); // Initial connection
+});
+
+function addToHistory(cmd) {
+ if (!isValidCommand(cmd)) return;
+ const history = document.getElementById("history");
+
+ const last = history.firstChild;
+ if (last && last.textContent === cmd) return;
+
+ const btn = document.createElement("button");
+ btn.textContent = cmd;
+ btn.onclick = () => {
+ document.getElementById("command").value = cmd;
+ document.getElementById("command").focus();
+ };
+
+ history.insertBefore(btn, history.firstChild);
+}
+
+function isValidCommand(cmd) {
+ if (!cmd) return false;
+ if (cmd.length < 2) return false;
+ if (/^\d+$/.test(cmd)) return false;
+ return true;
+}
+
+)rawliteral";
diff --git a/webui/style.h b/webui/style.h
new file mode 100644
index 00000000..0d6627c9
--- /dev/null
+++ b/webui/style.h
@@ -0,0 +1,205 @@
+#pragma once
+
+inline const char* style_css = R"rawliteral(
+* {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+ overflow-wrap: break-word;
+}
+
+html, body {
+ height: 100%;
+ width: 100%;
+ max-width: 100vw;
+ max-height: 100dvh;
+ font-family: Menlo, 'Courier New', Courier, 'Liberation Mono', monospace;
+ background-color: #121212;
+ color: #e0e0e0;
+ overflow: hidden;
+ touch-action: manipulation;
+}
+
+main {
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ height: 100dvh;
+ padding: max(10px, env(safe-area-inset-top)) max(10px, env(safe-area-inset-right)) max(10px, env(safe-area-inset-bottom)) max(10px, env(safe-area-inset-left));
+ gap: 10px;
+ overflow: hidden;
+ min-width: 0;
+ max-width: 100%;
+}
+
+/* Terminal output */
+#output {
+ font-family: Menlo, 'Courier New', Courier, 'Liberation Mono', monospace;
+ font-size: 0.9rem;
+ letter-spacing: 0;
+ line-height: 1.2;
+ flex-grow: 1;
+ min-height: 0;
+ width: 100%;
+ background: linear-gradient(145deg, #1a1a1a, #0f0f0f);
+ color: #00ff00;
+ border: 1px solid #333;
+ border-radius: 8px;
+ padding: 12px;
+ font-size: 0.9rem;
+ resize: none;
+ box-shadow: inset 0 0 5px #000;
+ box-sizing: border-box;
+ overflow-y: auto;
+ overflow-x: hidden;
+ white-space: pre-wrap;
+ word-break: break-word;
+ white-space: pre;
+ caret-color: transparent;
+}
+
+#output:focus {
+ outline: none;
+ border-color: #00ffcc;
+ box-shadow: 0 0 5px #00ffcc44;
+}
+
+#output::-webkit-scrollbar {
+ display: none;
+}
+
+/* Input + Send Button */
+.input-area {
+ display: flex;
+ gap: 8px;
+ flex-shrink: 0;
+ width: 100%;
+ max-width: 100%;
+ box-sizing: border-box;
+ min-width: 0;
+}
+
+input[type="text"] {
+ flex: 1;
+ padding: 10px;
+ background-color: #1c1c1c;
+ color: #00ff00;
+ border: 1px solid #333;
+ border-radius: 8px;
+ font-size: 1rem;
+ outline: none;
+ box-sizing: border-box;
+ min-width: 0;
+}
+input[type="text"]:focus {
+ border-color: #00ffcc;
+ box-shadow: 0 0 5px #00ffcc44;
+}
+
+button {
+ padding: 10px 16px;
+ background: linear-gradient(145deg, #2a2a2a, #1a1a1a);
+ color: #00ff00;
+ border: 1px solid #444;
+ border-radius: 8px;
+ cursor: pointer;
+ font-size: 1rem;
+ white-space: nowrap;
+ transition: background 0.2s ease, box-shadow 0.2s;
+}
+button:hover {
+ background: #333;
+ box-shadow: 0 0 6px #00ff0044;
+}
+
+/* History */
+#history-title {
+ margin: 4px 0 0 0;
+ font-size: 1rem;
+ display: none;
+ flex-shrink: 0;
+}
+
+.history-area {
+ display: flex;
+ flex-wrap: nowrap;
+ gap: 6px;
+ white-space: nowrap;
+ padding-bottom: 4px;
+ flex-shrink: 0;
+ width: 100%;
+ max-width: 100%;
+ overflow-x: auto;
+ overflow-y: hidden;
+ box-sizing: border-box;
+ min-width: 0;
+ -webkit-overflow-scrolling: touch;
+}
+
+.history-area::-webkit-scrollbar {
+ width: 0;
+ height: 0;
+}
+
+.history-area button {
+ flex: 0 0 auto;
+ background: #1a1a1a;
+ color: #00ff00;
+ border: 1px solid #333;
+ border-radius: 6px;
+ padding: 6px 10px;
+ font-size: 0.85em;
+ transition: background 0.2s ease;
+}
+.history-area button:hover {
+ background: #2a2a2a;
+}
+.history-area::-webkit-scrollbar {
+ height: 6px;
+}
+.history-area::-webkit-scrollbar-thumb {
+ background-color: #444;
+ border-radius: 4px;
+}
+.history-area::-webkit-scrollbar-track {
+ background-color: #222;
+}
+
+/* Responsive */
+@media (max-width: 600px), (max-height: 600px) {
+ main {
+ padding: 8px;
+ gap: 6px;
+ }
+
+ #output {
+ font-size: 0.8rem;
+ padding: 8px;
+ }
+
+ .input-area {
+ flex-direction: column;
+ gap: 6px;
+ }
+
+ input[type="text"] {
+ font-size: 0.95rem;
+ width: 100%;
+ }
+
+ .input-area button {
+ width: 100%;
+ font-size: 0.95rem;
+ }
+
+ .history-area {
+ gap: 4px;
+ }
+
+ .history-area button {
+ font-size: 0.75em;
+ padding: 5px 8px;
+ }
+}
+
+)rawliteral";