ソースを参照

Remove firmware updater

Tuan Nguyen 1 年間 前
コミット
da8aa97e0a

+ 0 - 38
dune_weaver_flask/app.py

@@ -396,44 +396,6 @@ def set_speed():
         logger.error(f"Failed to set speed: {str(e)}")
         return jsonify({"success": False, "error": str(e)}), 500
 
-@app.route('/get_firmware_info', methods=['GET', 'POST'])
-def get_firmware_info():
-    if not serial_manager.is_connected():
-        logger.warning("Attempted to get firmware info without serial connection")
-        return jsonify({"success": False, "error": "Arduino not connected or serial port not open"}), 400
-
-    try:
-        if request.method == "POST":
-            motor_type = request.json.get("motorType", None)
-            success, result = firmware_manager.get_firmware_info(motor_type)
-        else:
-            success, result = firmware_manager.get_firmware_info()
-
-        if not success:
-            logger.error(f"Failed to get firmware info: {result}")
-            return jsonify({"success": False, "error": result}), 500
-        return jsonify({"success": True, **result})
-
-    except Exception as e:
-        logger.error(f"Unexpected error while getting firmware info: {str(e)}")
-        return jsonify({"success": False, "error": str(e)}), 500
-
-@app.route('/flash_firmware', methods=['POST'])
-def flash_firmware():
-    try:
-        motor_type = request.json.get("motorType", None)
-        logger.info(f"Starting firmware flash for motor type: {motor_type}")
-        success, message = firmware_manager.flash_firmware(motor_type)
-        
-        if not success:
-            logger.error(f"Firmware flash failed: {message}")
-            return jsonify({"success": False, "error": message}), 500
-        
-        logger.info("Firmware flash completed successfully")
-        return jsonify({"success": True, "message": message})
-    except Exception as e:
-        logger.critical(f"Unexpected error during firmware flash: {str(e)}")
-        return jsonify({"success": False, "error": str(e)}), 500
 
 @app.route('/check_software_update', methods=['GET'])
 def check_updates():

+ 0 - 152
dune_weaver_flask/modules/firmware/firmware_manager.py

@@ -6,51 +6,6 @@ from ..serial import serial_manager
 # Configure logging
 logger = logging.getLogger(__name__)
 
-# Global state
-MOTOR_TYPE_MAPPING = {
-    "TMC2209": "./firmware/arduino_code_TMC2209/arduino_code_TMC2209.ino",
-    "DRV8825": "./firmware/arduino_code/arduino_code.ino",
-    "esp32": "./firmware/esp32/esp32.ino",
-    "esp32_TMC2209": "./firmware/esp32_TMC2209/esp32_TMC2209.ino"
-}
-
-def get_ino_firmware_details(ino_file_path):
-    """Extract firmware details from the given .ino file."""
-    try:
-        if not ino_file_path:
-            raise ValueError("Invalid path: ino_file_path is None or empty.")
-
-        firmware_details = {"version": None, "motorType": None}
-        logger.debug(f"Reading firmware details from {ino_file_path}")
-
-        with open(ino_file_path, "r") as file:
-            for line in file:
-                if "firmwareVersion" in line:
-                    start = line.find('"') + 1
-                    end = line.rfind('"')
-                    if start != -1 and end != -1 and start < end:
-                        firmware_details["version"] = line[start:end]
-
-                if "motorType" in line:
-                    start = line.find('"') + 1
-                    end = line.rfind('"')
-                    if start != -1 and end != -1 and start < end:
-                        firmware_details["motorType"] = line[start:end]
-
-        if not firmware_details["version"]:
-            logger.warning(f"Firmware version not found in file: {ino_file_path}")
-        if not firmware_details["motorType"]:
-            logger.warning(f"Motor type not found in file: {ino_file_path}")
-
-        return firmware_details if any(firmware_details.values()) else None
-
-    except FileNotFoundError:
-        logger.error(f"File not found: {ino_file_path}")
-        return None
-    except Exception as e:
-        logger.error(f"Error reading .ino file: {str(e)}")
-        return None
-
 def check_git_updates():
     """Check for available Git updates."""
     try:
@@ -136,110 +91,3 @@ def update_software():
     else:
         logger.error("Software update incomplete")
         return False, "Update incomplete", error_log
-
-def get_firmware_info(motor_type=None):
-    """Get firmware information for the current or specified motor type."""
-    if motor_type and motor_type not in MOTOR_TYPE_MAPPING:
-        return False, "Invalid motor type"
-
-    installed_version = serial_manager.firmware_version
-    installed_type = serial_manager.arduino_driver_type
-
-    if motor_type:
-        # POST request with specified motor type
-        ino_path = MOTOR_TYPE_MAPPING[motor_type]
-        firmware_details = get_ino_firmware_details(ino_path)
-
-        if not firmware_details:
-            return False, "Failed to retrieve .ino firmware details"
-
-        return True, {
-            "installedVersion": 'Unknown',
-            "installedType": motor_type,
-            "inoVersion": firmware_details["version"],
-            "inoType": firmware_details["motorType"],
-            "updateAvailable": True
-        }
-    else:
-        # GET request for current firmware info
-        if installed_version != 'Unknown' and installed_type != 'Unknown':
-            ino_path = MOTOR_TYPE_MAPPING.get(installed_type)
-            firmware_details = get_ino_firmware_details(ino_path)
-
-            if not firmware_details or not firmware_details.get("version") or not firmware_details.get("motorType"):
-                return False, "Failed to retrieve .ino firmware details"
-
-            update_available = (
-                installed_version != firmware_details["version"] or
-                installed_type != firmware_details["motorType"]
-            )
-
-            return True, {
-                "installedVersion": installed_version,
-                "installedType": installed_type,
-                "inoVersion": firmware_details["version"],
-                "inoType": firmware_details["motorType"],
-                "updateAvailable": update_available
-            }
-
-        return True, {
-            "installedVersion": installed_version,
-            "installedType": installed_type,
-            "updateAvailable": False
-        }
-
-def flash_firmware(motor_type):
-    """Flash firmware for the specified motor type."""
-    if not motor_type or motor_type not in MOTOR_TYPE_MAPPING:
-        logger.error(f"Invalid or missing motor type: {motor_type}")
-        return False, "Invalid or missing motor type"
-
-    if not serial_manager.is_connected():
-        logger.error("No device connected or connection lost")
-        return False, "No device connected or connection lost"
-
-    try:
-        ino_file_path = MOTOR_TYPE_MAPPING[motor_type]
-        hex_file_path = f"{ino_file_path}.hex"
-        bin_file_path = f"{ino_file_path}.bin"
-        logger.info(f"Flashing firmware for motor type: {motor_type}")
-
-        if motor_type.lower() in ["esp32", "esp32_tmc2209"]:
-            if not os.path.exists(bin_file_path):
-                logger.error(f"Firmware binary not found: {bin_file_path}")
-                return False, f"Firmware binary not found: {bin_file_path}"
-
-            flash_command = [
-                "esptool.py",
-                "--chip", "esp32",
-                "--port", serial_manager.get_port(),
-                "--baud", "115200",
-                "write_flash", "-z", "0x1000", bin_file_path
-            ]
-        else:
-            if not os.path.exists(hex_file_path):
-                logger.error(f"Hex file not found: {hex_file_path}")
-                return False, f"Hex file not found: {hex_file_path}"
-
-            flash_command = [
-                "avrdude",
-                "-v",
-                "-c", "arduino",
-                "-p", "atmega328p",
-                "-P", serial_manager.get_port(),
-                "-b", "115200",
-                "-D",
-                "-U", f"flash:w:{hex_file_path}:i"
-            ]
-
-        logger.debug(f"Running flash command: {' '.join(flash_command)}")
-        flash_process = subprocess.run(flash_command, capture_output=True, text=True)
-        if flash_process.returncode != 0:
-            logger.error(f"Firmware flash failed: {flash_process.stderr}")
-            return False, flash_process.stderr
-
-        logger.info("Firmware flashed successfully")
-        return True, "Firmware flashed successfully"
-    except Exception as e:
-        logger.error(f"Error during firmware flash: {str(e)}")
-        return False, str(e)

+ 0 - 134
dune_weaver_flask/static/js/main.js

@@ -680,139 +680,6 @@ async function restartSerial() {
 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 //  Firmware / Software Updater
 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-async function fetchFirmwareInfo(motorType = null) {
-    const checkButton = document.getElementById("check_updates_button");
-    const motorTypeElement = document.getElementById("motor_type");
-    const currentVersionElement = document.getElementById("current_firmware_version");
-    const newVersionElement = document.getElementById("new_firmware_version");
-    const motorSelectionDiv = document.getElementById("motor_selection");
-    const updateButtonElement = document.getElementById("update_firmware_button");
-
-    try {
-        // Disable the button while fetching
-        checkButton.disabled = true;
-        checkButton.textContent = "Checking...";
-
-        // Prepare fetch options
-        const options = motorType
-            ? {
-                method: "POST",
-                headers: { "Content-Type": "application/json" },
-                body: JSON.stringify({ motorType }),
-            }
-            : { method: "GET" };
-
-        const response = await fetch("/get_firmware_info", options);
-        const data = await response.json();
-        if (data.success) {
-            const { installedVersion, installedType, inoVersion, updateAvailable } = data;
-
-            // Handle unknown motor type
-            if (!installedType || installedType === "Unknown") {
-                motorSelectionDiv.style.display = "flex"; // Show the dropdown
-                updateButtonElement.style.display = "none"; // Hide update button
-                checkButton.style.display = "none";
-            } else {
-                // Display motor type
-                motorTypeElement.textContent = `Type: ${installedType || "Unknown"}`;
-                // Pre-select the correct motor type in the dropdown
-                const motorSelect = document.getElementById("manual_motor_type");
-                if (motorSelect) {
-                    Array.from(motorSelect.options).forEach(option => {
-                        option.selected = option.value === installedType;
-                    });
-                }
-
-                // Display firmware versions
-                currentVersionElement.textContent = `Current version: ${installedVersion || "Unknown"}`;
-
-                if (updateAvailable) {
-                    newVersionElement.textContent = `Latest version: ${inoVersion}`;
-                    updateButtonElement.style.display = "block";
-                    checkButton.style.display = "none";
-                } else {
-                    newVersionElement.textContent = "You are up to date!";
-                    updateButtonElement.style.display = "none";
-                    checkButton.style.display = "none";
-                }
-            }
-        } else {
-            logMessage("Could not fetch firmware info.", LOG_TYPE.WARNING);
-            logMessage(data.error, LOG_TYPE.DEBUG);
-        }
-    } catch (error) {
-        logMessage("Could not fetch firmware info.", LOG_TYPE.WARNING);
-        logMessage(error.message, LOG_TYPE.DEBUG);
-    } finally {
-        // Re-enable the button after fetching
-        checkButton.disabled = false;
-        checkButton.textContent = "Check for Updates";
-    }
-}
-
-function setMotorType() {
-    const selectElement = document.getElementById("manual_motor_type");
-    const selectedMotorType = selectElement.value;
-
-    if (!selectedMotorType) {
-        logMessage("Please select a motor type before proceeding.", LOG_TYPE.WARNING);
-        return;
-    }
-
-    const motorSelectionDiv = document.getElementById("motor_selection");
-    motorSelectionDiv.style.display = "none";
-
-    // Call fetchFirmwareInfo with the selected motor type
-    fetchFirmwareInfo(selectedMotorType);
-}
-
-async function updateFirmware() {
-    const button = document.getElementById("update_firmware_button");
-    const motorTypeDropdown = document.getElementById("manual_motor_type");
-    const motorType = motorTypeDropdown ? motorTypeDropdown.value : null;
-
-    if (!motorType) {
-        logMessage("Motor type is not set. Please select a motor type.", LOG_TYPE.WARNING);
-        return;
-    }
-
-    button.disabled = true;
-    button.textContent = "Updating...";
-
-    try {
-        logMessage("Firmware update started...", LOG_TYPE.INFO);
-
-        const response = await fetch("/flash_firmware", {
-            method: "POST",
-            headers: { "Content-Type": "application/json" },
-            body: JSON.stringify({ motorType }),
-        });
-
-        const data = await response.json();
-        if (data.success) {
-            logMessage("Firmware updated successfully!", LOG_TYPE.SUCCESS);
-            // Refresh the firmware info to update current version
-            logMessage("Refreshing firmware info...");
-            await fetchFirmwareInfo();
-
-            // Display "You're up to date" message if versions match
-            const newVersionElement = document.getElementById("new_firmware_version");
-            const currentVersionElement = document.getElementById("current_firmware_version");
-            currentVersionElement.textContent = newVersionElement.innerHTML
-            newVersionElement.textContent = "You are up to date!";
-            const motorSelectionDiv = document.getElementById("motor_selection");
-            motorSelectionDiv.style.display = "none";
-        } else {
-            logMessage(`Firmware update failed: ${data.error}`, LOG_TYPE.ERROR);
-        }
-    } catch (error) {
-        logMessage(`Error during firmware update: ${error.message}`, LOG_TYPE.ERROR);
-    } finally {
-        button.disabled = false; // Re-enable button
-        button.textContent = "Update Firmware";
-    }
-}
-
 async function checkForUpdates() {
     try {
         const response = await fetch('/check_software_update');
@@ -1835,5 +1702,4 @@ document.addEventListener('DOMContentLoaded', () => {
         updateInterval = setInterval(updateCurrentlyPlaying, 5000);
     }
     checkForUpdates();
-    fetchFirmwareInfo();
 });

+ 0 - 27
dune_weaver_flask/templates/index.html

@@ -345,33 +345,6 @@
                 </div>
             </section>
 
-            <section class="firmware version">
-                <div class="header">
-                    <h2>Firmware Version</h2>
-                </div>
-                <div id="firmware_info">
-                    <div id="motor_type"></div>
-                    <div id="current_firmware_version"></div>
-                    <div id="new_firmware_version"></div>
-                </div>
-                <div class="button-group">
-                    <div id="motor_selection" style="display: none;">
-                        <h3>Select installed motor driver: </h3>
-                        <select id="manual_motor_type">
-                            <option value="TMC2209">Arduino TMC2209</option>
-                            <option value="DRV8825">Arduino DRV8825</option>
-                            <option value="esp32">ESP32</option>
-                            <option value="esp32_TMC2209">ESP32 TMC2209</option>
-                        </select>
-                        <button id="set_motor_type_button" onclick="setMotorType()">Set Motor Type</button>
-                    </div>
-                    <button id="check_updates_button" onclick="fetchFirmwareInfo()">Check for Updates</button>
-                    <button id="update_firmware_button" class="cta" style="display: none;" onclick="updateFirmware()">
-                        <i class="fa-solid fa-file-arrow-up"></i>
-                        <span>Update Firmware</span>
-                    </button>
-                </div>
-            </section>
             <section class="debug main">
                 <div id="github">
                 <span>Help us improve! <a href="https://github.com/tuanchris/dune-weaver/pulls" target="_blank">Submit a Pull Request</a> or <a