Exploit database

GH-7d1d061134d2f84a23cf4a0e171249e3

aabdeldayem1/ftc-2023

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2019-11358

1,181 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files45

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

TeamCode/build/intermediates/assets/debug/manage.html

HTML · 44,336 bytes
<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <script type="text/javascript" src="/js/es5-shim.js"></script>
    <script type="text/javascript" src="/js/es6-shim.js"></script>
    <script type="text/javascript" src="/js/websocket-iframe.js"></script>
    <script type="text/javascript" src="/js/jquery-3.4.1.min.js"></script>
    <script type="text/javascript" src="/js/bootstrap.min.js"></script>

    <link rel="stylesheet/less" type="text/css" href="/css/manage.less">
    <script type="text/javascript" src="/js/less.min.js"></script>
</head>
<body>
    <div id="blocker" style="display: none; z-index: 10; width: 100%; height: 200%; background-color: rgba(201,201,201,.7); position: fixed; top: 0; left: 0;">
        <h2 id="blockerText" style="margin:auto; margin-top: 10%; width: 60%; padding:5px; text-align: center; background-color: #ffffff; border: 2px solid black "></h2>
    </div>
    <div id="progressBanner" class="alert alert-info" role="alert" style="position:fixed; width:100%; top:0px; display: none; z-index:10;">
        <div id="progressMessage"></div>
        <div class="progress" style="margin-top:20px; margin-bottom: 10px;">
            <!-- Having a separate indeterminate progress bar prevents animating backwards -->
            <div id="progressBar" class="progress-bar" role="progressbar"></div>
            <div id="indeterminateProgressBar" class="progress-bar progress-bar-striped active" style="width:100%;" role="progressbar"></div>
        </div>
    </div>
    <div class="bordered-text-block">
        <h1 class="header-shared-line">Robot Controller version: </h1><span id="id_rc_version" class="next-to-header"></span>
        <div id="id_control_hub_os_version_item">
            <h1 class="header-shared-line">Control Hub OS version: </h1><span id="id_control_hub_os_version" class="next-to-header"></span>
        </div>
        <div id="id_rev_hubs_item">
            <h1>REV Hubs:</h1>
            <div id="id_rev_hubs" class="indented"></div>
        </div>
    </div>
    <div class="bordered-text-block" id="id_network_settings_block">
        <h1>Wi-Fi Settings</h1>
        <form class="indented">
            <div class="form-group">
                <label for="id_rc_name">Name</label>
                <input id="id_rc_name" class="form-control limited-width" type="text" value="(name)">
            </div>
            <div class="form-group" id="id_password_group">
                <label for="id_ap_new_password">New Password</label>
                <input id="id_ap_new_password" class="form-control limited-width" type="password" value="">
            </div>
            <div class="form-group" id="id_confirmed_password_group">
                <label for="id_ap_confirmed_password">Confirm Password</label>
                <input id="id_ap_confirmed_password" class="form-control limited-width" type="password" value="">
                <div class="checkbox">
                    <label>
                        <input type="checkbox" onclick="onShowPasswordCheckbox()">
                        Show Password
                    </label>
                </div>
            </div>
            <div class="form-group" id="id_wifi_band_group">
                <label>Wi-Fi Band</label>
                <br>
                <label class="radio-inline">
                    <input type="radio" name="wifiBand" id="id_wifi_band_24" value="band_24" onclick="updateChannelList();">2.4 GHz
                </label>
                <label class="radio-inline">
                    <input type="radio" name="wifiBand" id="id_wifi_band_5" value="band_5" onclick="updateChannelList();">5 GHz
                </label>
                <span class="help-block">
                    The 5 GHz Wi-Fi band is highly recommended, unless you need to connect older devices that only support 2.4 GHz Wi-Fi.
                </span>
            </div>
            <div class="form-group">
                <label for="id_ap_channel">Wi-Fi Channel</label>
                <select id="id_ap_channel" class="form-control" style="max-width: 150px; margin-bottom: 10px;" onchange="updateApSettingsButton();"></select>
                <div class="checkbox" id="id_show_overlapping_channels">
                    <label>
                        <input type="checkbox" id="id_show_overlapping_channels_checkbox" onclick="updateChannelList('overlappingChannelsCheckbox')">
                        Show overlapping channels (not recommended)
                    </label>
                </div>
                <div id="id_submit_network_settings_warning" class="sized-input alert alert-danger" role="alert" style="display:inline-block; margin-bottom:0;">
                    Please select a Wi-Fi channel from the dropdown menu
                </div>
            </div>
        </form>
        <button id="id_submit_network_settings_button" class="aligned-select-button btn btn-primary" disabled title="Not connected to robot" onclick="onSubmitNetworkSettings()">
            Apply Wi-Fi Settings
        </button>
        <div id="id_control_hub_wifi_warnings">
            <span class="help-block">
            You will need to reconnect to the new Wi-Fi network after changing the Control Hub's name and/or password.
            </span>
            <span class="help-block" style="margin-bottom:0; max-width:700px">
                If you are unable to connect to the Control Hub's network after switching to the 5 GHz band,
                you can perform a Wi-Fi factory reset by holding down the Control Hub's button while you
                turn it on, until you see a rapid sequence of color changes on the Control Hub's light.
                The Wi-Fi network name and password will be reset to their default values, and the Wi-Fi band will be set to 2.4 GHz.
            </span>
        </div>
    </div>
<div class="bordered-text-block">
    <div id="id_download_logs">
        <h1>Download Robot Controller Logs</h1>
        <p>Examination of activity logs from the robot controller can sometimes help diagnose problems and bugs.</p>
        <p><button onclick="javascript:onDownloadLogsClicked()">Download Logs<span id="id_log_count"></span></button></p>
    </div>
    <div id="id_upload_firmware">
        <h1>Update REV Hub Firmware</h1>
        <p>Update firmware on the REV Expansion Hub and REV Control Hub.<br>You can upload a firmware file yourself, or use the included version.</p>
        <div>
            <p>
                <input id="id_input_file_firmware" type="file" class="hidden hidden-input-file">
                <input id="id_firmware_feedback" readonly class="upload-feedback" type="text" value="(firmware)"><button id="id_firmware_button" class="aligned-select-button" >Select Firmware...</button>
            </p>
            <button id="id_action_firmware" class="aligned-action-button" onclick="firmwareUpdateButtonClicked();">Upload</button>
        </div>
    </div>
    <div id="id_update_robot_controller_application">
        <h1>Update Robot Controller App</h1>
        <p>Upload and install a new Robot Controller App to the REV Control Hub.</p>
        <div>
            <p>
                <input id="id_input_file_apk" type="file" class="hidden hidden-input-file">
                <input id="id_apk_feedback" readonly class="upload-feedback" type="text" value="(apk)"><button id="id_apk_button"
                    class="aligned-select-button">Select App...</button>
                <button id="id_action_apk" class="aligned-action-button" onclick="updateApk();">Update</button>
            </p>
        </div>
    </div>
    <div id="id_upload_webcam_calibration">
        <h1>Upload Webcam Calibration File</h1>
        <p>Upload a webcam calibration file.</p>
        <div>
            <p>
                <input id="id_input_file_webcam_calibration" type="file" class="hidden hidden-input-file">
                <input id="id_webcam_calibration_feedback" readonly class="upload-feedback" type="text" value="(webcam_calibration)">
                    <button id="id_webcam_calibration_button" class="aligned-select-button" >Select Webcam Calibration File...</button>
                <button id="id_action_webcam_calibration" class="aligned-action-button" onclick="uploadWebcamCalibration();">Upload</button>
            </p>
            <p id="id_webcam_calibration_upload_complete" class="text-ok"></p>
        </div>
    </div>
    <div id="id_manage_tflite_models">
        <h1>Manage TensorFlow Lite Models</h1>
        <div>
            <a href="/?page=/FtcTFLiteModels.html" target="_blank">Manage TensorFlow Lite Models</a>
        </div>
    </div>
    <div id="id_manage_sounds">
        <h1>Manage Sounds</h1>
        <div>
            <a href="/?page=/FtcSounds.html" target="_blank">Manage Sounds</a>
        </div>
    </div>
    <div id="id_update_control_hub_operating_system">
        <h1>Update Control Hub Operating System</h1>
        <p>Upload an Operating System update file for the REV Control Hub</p>
        <div>
            <p>
                <input id="id_input_file_ota" type="file" class="hidden hidden-input-file">
                <input id="id_ota_feedback" readonly class="upload-feedback" type="text" value="(zip)">
                <button id="id_ota_button" class="aligned-select-button">Select Update File...</button>
                <button id="id_action_ota" class="aligned-action-button" onclick="uploadOta();">Update &amp; Reboot</button>
            </p>
        </div>
    </div>
</div>

<div class="modal fade" id="id_fw_update_modal" tabindex="-1" role="dialog" aria-labelledby="id_fw_update_title">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h3 class="modal-title" id="id_fw_update_title">REV Hub Firmware Update</h3>
            </div>
            <div class="modal-body">
                <div id="id_fw_update_loading_devices">
                    <h4>Getting devices available for update</h4>
                    <div class="progress">
                        <div class="progress-bar progress-bar-striped active" role="progressbar" style="width:100%;"></div>
                    </div>
                </div>
                <div id="id_fw_update_content">
                    <h4>REV Hubs that will be updated:</h4>
                    <div class="list-group" id="id_fw_update_device_list"></div>
                    <div class="panel panel-info">
                        <div class="panel-heading"><h4 class="panel-title">Note</h4></div>
                        <div class="panel-body">
                            Expansion Hubs are only available for firmware update if they are
                            plugged into the Robot Controller directly via USB (not RS485).
                        </div>
                    </div>
                    <div class="panel panel-danger">
                        <div class="panel-heading"><h4 class="panel-title">Warning</h4></div>
                        <div class="panel-body">
                            While the firmware update is in progress, do not unplug any hubs or restart
                            the robot, or a hub may need to be updated again before it can be used.
                        </div>
                    </div>
                    <div class="text-center">
                        <button type="button" id="id_fw_update_apply_button" class="btn btn-primary" data-dismiss="modal">
                            Update Hub Firmware
                        </button>
                    </div>
                </div>
                <div id="id_fw_update_no_devices_found">
                    <h4>No Expansion Hubs were found via USB.</h4>
                    <div class="text-center">
                        <button type="button" onclick="openFirmwareUpdateModal()" class="btn btn-primary">
                            Re-scan for Expansion Hubs
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript" src="/js/rc_config.js"></script>
<script type="text/javascript" src="/js/util.js"></script>
<script type="text/javascript">
    'use strict';

    var appUpdateRequiresReboot = false;
    var mostRecentUploadIdentifier;
    var allAvailableChannels;
    let currentChannel;
    let currentlyOn2_4Ghz = false;
    let currentlyOn5Ghz = false;
    var isControlHub;
    var originalName;
    var originalPassword;

    var CH_UPDATER_NAMESPACE = "ControlHubUpdater";
    var PROGRESS_NAMESPACE = "progress";

    var remainingModulesForFwUpdate = []; // contains hub serial numbers
    var fwUpdateFilename; // falsy value indicates that the built-in firmware file should be used

    var updateAbandonmentEventHandler = function(event) { event.preventDefault(); event.returnValue = "Update in progress"; }

    var handleShowProgress = function(webSocketMessage) {
        var payload = JSON.parse(webSocketMessage.payload);

        document.getElementById('progressMessage').innerText = payload.message;
        var progressBar = document.getElementById('progressBar');
        var indeterminateProgressBar = document.getElementById('indeterminateProgressBar');

        if (payload.cur === 0) {
            indeterminateProgressBar.style.display = 'block';
            progressBar.style.display = 'none';
        } else {
            var percent = ((payload.cur / payload.max) * 100).toFixed(2) + "%";
            progressBar.style.width = percent;
            progressBar.style.display = 'block';
            indeterminateProgressBar.style.display = 'none';
        }

        document.getElementById('progressBanner').style.display = 'block';
    };

    var dismissProgress = function(webSocketMessage) {
        document.getElementById('progressBanner').style.display = 'none';
    };

    var handleUpdaterNotification = function(webSocketMessage) {
        var payload = JSON.parse(webSocketMessage.payload);
        console.log(payload);
        var message = payload.message;

        if (payload.presentationType === "STATUS") {
            message = message.replace(/\n/g, "<br>");
            showUploadBlocker(message);
        } else {
            hideUploadBlocker();
            removeClass(document.documentElement, "wait");
            window.removeEventListener('beforeunload', updateAbandonmentEventHandler);

            setTimeout(function() {
                // We put this functionality in a 10 ms timeout, because we want the hiding to finish before we display the alert/confirmation
                if (payload.presentationType === "PROMPT") {
                    var confirmationResult = confirm(message);
                    console.log("Confirmation result: " + confirmationResult);
                    if (confirmationResult === true) {
                        var confirmationMessage = new WEBSOCKET_LIB.WebSocketMessage(CH_UPDATER_NAMESPACE, "confirmDangerousAction", mostRecentUploadIdentifier);
                        WEBSOCKET_LIB.webSocketManager.sendMessage(confirmationMessage);
                    } else {
                        // If we aren't going to install the uploaded file, we should delete it.
                        var deleteUploadedFileMessage = new WEBSOCKET_LIB.WebSocketMessage(CH_UPDATER_NAMESPACE, "deleteUploadedFile", mostRecentUploadIdentifier);
                        WEBSOCKET_LIB.webSocketManager.sendMessage(deleteUploadedFileMessage);
                    }
                } else {
                    // For now we treat successes and failures the same way. In the future, we can style the messages differently if desired.
                    alert(message);
                }
            }, 10);
        }
    };

    var bindToControlHubUpdaterTransaction = function (xhr) {
        var responseObject = JSON.parse(xhr.response);
        if (responseObject.uploadIdentifier) {
            addClass(document.documentElement, "wait");
            window.addEventListener('beforeunload', updateAbandonmentEventHandler);
            mostRecentUploadIdentifier = responseObject.uploadIdentifier;
            var bindMessage = new WEBSOCKET_LIB.WebSocketMessage(CH_UPDATER_NAMESPACE, "bind", responseObject.uploadIdentifier);
            WEBSOCKET_LIB.webSocketManager.sendMessage(bindMessage);
        }
    }

    function onWebSocketConnected() {
        updateApSettingsButton();
    }

    function onWebSocketDisconnected() {
        dismissProgress();
        updateApSettingsButton();
    }

    WEBSOCKET_LIB.webSocketManager.subscribeToNamespace(CH_UPDATER_NAMESPACE);
    WEBSOCKET_LIB.webSocketManager.subscribeToNamespace(PROGRESS_NAMESPACE);
    WEBSOCKET_LIB.webSocketManager.registerTypeHandler(CH_UPDATER_NAMESPACE, "notification", handleUpdaterNotification);
    WEBSOCKET_LIB.webSocketManager.registerTypeHandler(PROGRESS_NAMESPACE, "showProgress", handleShowProgress);
    WEBSOCKET_LIB.webSocketManager.registerTypeHandler(PROGRESS_NAMESPACE, "dismissProgress", dismissProgress)
    WEBSOCKET_LIB.webSocketManager.registerConnectionStateListeners(onWebSocketConnected, onWebSocketDisconnected);

    var initUpload = function (idInput, idFeedback, idButton, ext, idAction, options) {
        if (typeof options === 'undefined') options = {};
        if (typeof options.hideActionButton === 'undefined') options.hideActionButton = true;

        var input = document.getElementById(idInput);
        var feedback = document.getElementById(idFeedback);
        var button = document.getElementById(idButton);
        var action = document.getElementById(idAction);

        feedback.value = "";
        feedback.onclick = function () { input.click(); };
        button.onclick = function () { input.click(); };
        input.accept = ext;
        input.onchange = function () { fileInputChange(input, feedback, ext, action, options.fileSelectedCallback); };
        if (options.hideActionButton) {
            hideElement(action, true);
        }
    }

    var fileInputChange = function(input, feedback, ext, action, fileSelectedCallback) {
        if (input.files && input.files.length > 0) {
            var file = input.files[0];
            console.log("fileInputChange() ext=" + ext + " file=" + file);
            if (endsWith(file.name, ext)) {
                feedback.value = file.name;
                feedback.dataFile = file;
                hideElement(action, false);
                if (fileSelectedCallback) {
                    fileSelectedCallback();
                }
            } else {
                alert("Please choose a file with extension: " + ext);
            }
        } else {
            console.log("input files empty");
        }
    }

    initUpload('id_input_file_firmware', 'id_firmware_feedback', 'id_firmware_button', '.bin', 'id_action_firmware', {
        hideActionButton: false,
        fileSelectedCallback: function() {
            document.getElementById('id_action_firmware').innerText = "Update using selected firmware file";
        }
    });
    initUpload('id_input_file_apk',      'id_apk_feedback',      'id_apk_button',      '.apk', 'id_action_apk');
    initUpload('id_input_file_ota',      'id_ota_feedback',      'id_ota_button',      '.zip', 'id_action_ota');

    $('#id_id_webcam_calibration_upload_complete').hide();
    initUpload('id_input_file_webcam_calibration', 'id_webcam_calibration_feedback', 'id_webcam_calibration_button', '.xml', 'id_action_webcam_calibration');

    var showUploadBlocker = function(text) {
        if (!text) {
            text = "Please wait while upload finishes";
        }
        $('#blockerText').html(text);
        $('#blocker').show();
    }

    var hideUploadBlocker = function() {
        $('#blocker').hide();
    }

    var uploadSuccess = function(file, xhr, e) {
        hideUploadBlocker();
    }

    var uploadFailure = function(file, xhr, e) {
        hideUploadBlocker();
    }

    var performNextFirmwareUpdate = function() {
        var module = remainingModulesForFwUpdate.shift();
        if (!module) return;
        console.log("performNextFirmwareUpdate() called, module=" + JSON.stringify(module));
        var fwUpdateRequest = new XMLHttpRequest();
        fwUpdateRequest.onreadystatechange = function() {
            if (fwUpdateRequest.readyState === 4) {
                if (fwUpdateRequest.status === 200) {
                    var result = JSON.parse(fwUpdateRequest.responseText);
                    console.log("Firmware update result: " + fwUpdateRequest.responseText);
                    if (result.success === true) {
                        if (remainingModulesForFwUpdate.length > 0) {
                            performNextFirmwareUpdate();
                        } else {
                            alert("Firmware update completed successfully")
                        }
                        refreshRCInfo();
                    } else {
                        var deviceString;
                        if (module.serialNumber === "(embedded)") {
                            deviceString = "Control Hub";
                        } else {
                            deviceString = "Expansion Hub " + module.serialNumber;
                        }
                        var failureMessage = "Firmware update of " + deviceString + " failed";
                        if (result.errorMessage) {
                            failureMessage += " because " + result.errorMessage;
                        }
                        failureMessage += ". Please try again.";
                        console.log(failureMessage);
                        alert(failureMessage);
                    }
                } else {
                    console.log("Received code " + fwUpdateRequest.status + " when updating firmware");
                }
            }
        };
        fwUpdateRequest.open("POST", URI_PERFORM_REV_FIRMWARE_UPDATE);
        fwUpdateRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        var params = "serialNumber=" + module.serialNumber;
        if (fwUpdateFilename) {
            params += "&filename=" + fwUpdateFilename;
        }
        fwUpdateRequest.send(params);
    }

    var firmwareUpdateButtonClicked = function() {
        var feedback = document.getElementById('id_firmware_feedback');
        var uploadedFile = feedback.dataFile;
        var useUploadedFile = !!uploadedFile;
        console.log("firmwareUpdateButtonClicked() useUploadedFile=" + useUploadedFile);
        if (useUploadedFile) {
            var url = URI_UPLOAD_EXPANSION_HUB_FIRMWARE;
            showUploadBlocker();
            uploadFile(uploadedFile, url, true,
                function(xhr, e) {
                    uploadSuccess(uploadedFile, xhr, e);
                    fwUpdateFilename = xhr.responseText; // response contains uploaded filename
                    openFirmwareUpdateModal();
                },
                function(xhr, e) { uploadFailure(uploadedFile, xhr, e); });
        } else {
            openFirmwareUpdateModal();
        }
    }

    // This method may be called with the modal already open
    // This means that the modal should start over, beginning with a fresh scan
    var openFirmwareUpdateModal = function() {
        var loadingDiv = document.getElementById('id_fw_update_loading_devices');
        var id_fw_update_contentDiv = document.getElementById('id_fw_update_content');
        var noDevicesFoundDiv = document.getElementById('id_fw_update_no_devices_found');

        loadingDiv.style.display = 'block';
        id_fw_update_contentDiv.style.display = 'none';
        noDevicesFoundDiv.style.display = 'none';
        $('#id_fw_update_modal').modal('show');
        var availableDevicesRequest = new XMLHttpRequest();
        availableDevicesRequest.onreadystatechange = function() {
            if (availableDevicesRequest.readyState === 4) {
                if (availableDevicesRequest.status === 200) {
                    loadingDiv.style.display = 'none';
                    var modules = JSON.parse(availableDevicesRequest.responseText).modules;

                    if (modules.length === 0) {
                        noDevicesFoundDiv.style.display = 'block';
                    } else {
                        var deviceList = document.getElementById('id_fw_update_device_list');
                        deviceList.textContent = '';
                        modules.forEach(function(module) {
                            var headerText;
                            var displayModuleAddress;
                            var descriptionText;
                            if (module.serialNumber === '(embedded)') {
                                headerText = "Control Hub";
                                displayModuleAddress = false;
                            } else {
                                headerText = "Expansion Hub";
                                displayModuleAddress = true;
                            }
                            descriptionText = "Serial number: " + module.serialNumber + "<br>";
                            if (displayModuleAddress) {
                                descriptionText += "Module address: " + module.moduleAddress + "<br>";
                            }
                            descriptionText += "Current firmware version: " + module.formattedFirmwareVersionString + "<br>";

                            var listEntry = document.createElement('div');
                            var header = document.createElement('h4');
                            var description = document.createElement('p');
                            listEntry.classList.add("list-group-item");
                            header.appendChild(document.createTextNode(headerText));
                            description.innerHTML = descriptionText;
                            listEntry.appendChild(header);
                            listEntry.appendChild(description);
                            deviceList.appendChild(listEntry);
                        });
                        document.getElementById('id_fw_update_apply_button').onclick = function() {
                            remainingModulesForFwUpdate = modules;
                            performNextFirmwareUpdate();
                        };
                        document.getElementById('id_fw_update_content').style.display = 'block';
                    }
                } else if (availableDevicesRequest.status === 503) {
                    window.setTimeout(openFirmwareUpdateModal, 1000); // Try again after a second, the robot is probably still starting up
                } else {
                    console.log("Received code " + availableDevicesRequest.status + " when getting available devices");
                }
            }
        };
        availableDevicesRequest.open("GET", URI_REV_HUBS_AVAILABLE_FOR_UPDATE);
        availableDevicesRequest.send();
    }

    var updateApk = function() {
        var feedback = document.getElementById('id_apk_feedback');
        var file = feedback.dataFile;
        console.log("updateApk() name=" + file.name);
        var url = URI_UPDATE_CONTROL_HUB_APK;
        showUploadBlocker();
        uploadFile(file, url, true,
            function(xhr, e) {
                if (appUpdateRequiresReboot) {
                    uploadSuccess(file, xhr, e);
                    reboot();
                } else {
                    bindToControlHubUpdaterTransaction(xhr);
                }
            },
            function(xhr, e) {
                uploadFailure(file, xhr, e);
            });
    }

    var reboot = function() {
        console.log("reboot()");
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    // nothing to do
                } else {
                    alert("Robot controller failed to reboot");
                }
            }
        };
        xhr.open("POST", URI_REBOOT);
        xhr.send();
    }

    var uploadWebcamCalibration = function () {
        var feedback = document.getElementById('id_webcam_calibration_feedback');
        var file = feedback.dataFile;
        console.log("uploadWebcamCalibration() name=" + file.name);
        var url = URI_UPLOAD_WEBCAM_CALIBRATION_FILE;
        showUploadBlocker();
        uploadFile(file, url, true,
            function(xhr, e) {
                uploadSuccess(file, xhr, e);
                showToast('id_webcam_calibration_upload_complete', 'Webcam Calibration upload complete');
            },
            function(xhr, e) { uploadFailure(file, xhr, e); });
    }

    var uploadOta = function () {
        var feedback = document.getElementById('id_ota_feedback');
        var file = feedback.dataFile;
        console.log("uploadOta() name=" + file.name);
        var url = URI_UPLOAD_CONTROL_HUB_OTA;
        showUploadBlocker();
        uploadFile(file, url, true,
            function(xhr, e) {
                bindToControlHubUpdaterTransaction(xhr);
            },
            function(xhr, e) {
                uploadFailure(file, xhr, e);
            });
     }

    var onSubmitNetworkSettings = function () {
        console.log("onSubmitNetworkSettings()");
        var newName = document.getElementById("id_rc_name").value.trim();
        var newPw = document.getElementById("id_ap_new_password").value;
        var confirmPw = document.getElementById("id_ap_confirmed_password").value;
        var newChannelName = document.getElementById("id_ap_channel").value;
        const newChannelIs5Ghz = document.getElementById("id_wifi_band_5").checked;
        if (newName.length < 2 || newName.length > 32) {
            alert("RC Name must be between 2 and 32 chars");
        } else if (newName.match(/\s/) != null) {
            alert("RC Name must not include whitespace (space, tab, return, etc..)");
        } else if (newPw && (newPw.length < 8 || newPw.length > 63)) {
            alert("Password must be between 8 and 63 chars");
        } else if (newPw && newPw.localeCompare(confirmPw) !== 0) {
            alert("New password and the confirmation password are different");
        } else {
            console.log("newName=" + newName + " newPw=" + newPw + " newChannelName=" + newChannelName);
            var xhr = new XMLHttpRequest();
            var params = PARAM_NAME + '=' + encodeURIComponent(newName);
            if (newPw) {
                params += "&" + PARAM_AP_PASSWORD + '=' + encodeURIComponent(newPw);
            }
            if (newChannelName) {
                params += "&" + PARAM_CHANNEL_NAME + '=' + encodeURIComponent(newChannelName);
            }
            xhr.open('POST', URI_CHANGE_NETWORK_SETTINGS, true /*async*/);
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200 || xhr.status === 0) {
                        // Either the settings application succeeded, or we were disconnected from the network before we got a response.
                        currentChannel = newChannelName;
                        currentlyOn5Ghz = newChannelIs5Ghz;
                        currentlyOn2_4Ghz = !newChannelIs5Ghz;
                    } else {
                        console.log("Network settings failed to apply. Error code: " + xhr.status + " Error text: " + xhr.responseText);
                        var error = "The network settings failed to apply";
                        if (xhr.responseText) {
                            error += ". " + xhr.responseText;
                        }
                        alert(error);
                    }
                }
            };
            xhr.send(params);

            if (isControlHub) {
                let nameChanged = originalName !== newName;
                let passwordChanged = originalPassword !== newPw;
                if (nameChanged && passwordChanged) {
                    alert("The Control Hub's name and password have been changed. If you are connected to the Control Hub via Wi-Fi, you have been disconnected. You will need to connect to the new network.");
                } else if (nameChanged) {
                    alert("The Control Hub's name has been changed. If you are connected to the Control Hub via Wi-Fi, you have been disconnected. You will need to connect to the new network.");
                } else if (passwordChanged) {
                    // If the password changed but not the name, the user needs to "forget" the old network before reconnecting.
                    alert("The Control Hub's password has been changed. If you are connected to the Control Hub via Wi-Fi, you have been disconnected. You will need to \"forget\" the network, and then connect to it again.");
                }
            }
        }
    }

    var onShowPasswordCheckbox = function () {
        var newPw = document.getElementById("id_ap_new_password");
        var confirmPw = document.getElementById("id_ap_confirmed_password");
        if (newPw.type === "password") {
            newPw.type = "text";
            confirmPw.type = "text";
        } else {
            newPw.type = "password";
            confirmPw.type = "password";
        }
    }

    function updateApSettingsButton() {
        const apSettingsButton = document.getElementById("id_submit_network_settings_button");
        const selectSpecificChannelWarning = document.getElementById("id_submit_network_settings_warning");
        const channelDropdown = document.getElementById("id_ap_channel");

        let disableApSettingsButtonBecauseOfDisconnection = false;
        let showChannelWarningInsteadOfButton = false;

        // Determine our desired state
        if (!WEBSOCKET_LIB.isWebSocketConnected()) {
            disableApSettingsButtonBecauseOfDisconnection = true;
        } else if (!channelDropdown.value) {
            showChannelWarningInsteadOfButton = true;
        }

        // Update the UI accordingly
        if (showChannelWarningInsteadOfButton) {
            apSettingsButton.style.display = 'none';
            selectSpecificChannelWarning.style.display = 'inline-block';
        } else {
            apSettingsButton.style.display = 'inline-block';
            selectSpecificChannelWarning.style.display = 'none';

            if (disableApSettingsButtonBecauseOfDisconnection) {
                apSettingsButton.disabled = true;
                apSettingsButton.title = 'Not connected to robot';
            } else {
                apSettingsButton.disabled = false;
                apSettingsButton.title = '';
            }
        }
    }

    var updateChannelList = function (reason) {
        var show5GhzChannels = document.getElementById("id_wifi_band_5").checked;
        var showOverlappingChannels = document.getElementById("id_show_overlapping_channels_checkbox").checked;
        var channelDropdown = document.getElementById("id_ap_channel");
        const previousChannelSelection = channelDropdown.value;
        hideElement(document.getElementById("id_show_overlapping_channels"), show5GhzChannels);
        channelDropdown.innerText = '';
        allAvailableChannels.forEach(function(channel) {
            var fiveGhzChannel = (channel.band === "BAND_5_GHZ");
            var showChannel = (show5GhzChannels && fiveGhzChannel) || (!show5GhzChannels && !fiveGhzChannel);
            if (!showOverlappingChannels && channel.overlapsWithOtherChannels) {
                showChannel = false;
            }
            if (showChannel) {
                var channelOption = document.createElement("option");
                channelOption.value = channel.name;
                channelOption.textContent = channel.displayName;
                channelDropdown.appendChild(channelOption);
            }
        });

        if (reason === 'overlappingChannelsCheckbox') {
            // When the user checks the overlapping channels checkbox, we want to restore the
            // previous selection (if possible), not the current channel we're broadcasting on.
            channelDropdown.value = previousChannelSelection;
        } else {
            if ((show5GhzChannels && currentlyOn5Ghz) || (!show5GhzChannels && currentlyOn2_4Ghz)) {
                channelDropdown.value = currentChannel;
            } else {
                channelDropdown.value = '';
            }
        }
        updateApSettingsButton();
    }

    var selectBand = function (select5GhzBand) {
        if (select5GhzBand) {
            document.getElementById("id_wifi_band_5").checked = true;
        } else {
            document.getElementById("id_wifi_band_24").checked = true;
        }
    }

    function refreshRCInfo() {
        loadRcInfo(function (rcInfo) {
            if (rcInfo) {
                scaleTextInDocumentBody(rcInfo);

                document.getElementById("id_rc_name").value = rcInfo.deviceName;
                document.getElementById("id_ap_new_password").value = rcInfo.passphrase;
                document.getElementById("id_ap_confirmed_password").value = rcInfo.passphrase;

                var uaIsRobotController = rcInfo.ftcUserAgentCategory === "ROBOT_CONTROLLER";
                hideElement(document.getElementById("id_download_logs"), uaIsRobotController);
                hideElement(document.getElementById("id_upload_firmware"), uaIsRobotController);
                hideElement(document.getElementById("id_update_robot_controller_application"), uaIsRobotController || !rcInfo.isREVControlHub);
                hideElement(document.getElementById("id_control_hub_wifi_warnings"), !rcInfo.isREVControlHub);
                hideElement(document.getElementById("id_password_group"), !rcInfo.isREVControlHub);
                hideElement(document.getElementById("id_confirmed_password_group"), !rcInfo.isREVControlHub);
                hideElement(document.getElementById("id_wifi_band_group"), !rcInfo.supports5GhzAp);
                hideElement(document.getElementById("id_update_control_hub_operating_system"), !rcInfo.supportsOtaUpdate || !rcInfo.isREVControlHub);
                hideElement(document.getElementById("id_control_hub_os_version_item"), !rcInfo.isREVControlHub);
                hideElement(document.getElementById("id_rev_hubs_item"), !rcInfo.revHubNamesAndVersions || rcInfo.revHubNamesAndVersions.length === 0);

                allAvailableChannels = rcInfo.availableChannels;
                isControlHub = rcInfo.isREVControlHub;
                originalName = rcInfo.deviceName;
                originalPassword = rcInfo.passphrase;

                let select5GhzBand = false;
                if (rcInfo.currentChannel.name !== "UNKNOWN") {
                    currentChannel = rcInfo.currentChannel.name;
                    if (rcInfo.currentChannel.band === "BAND_5_GHZ") {
                        currentlyOn5Ghz = true;
                        currentlyOn2_4Ghz = false;
                        select5GhzBand = true;
                    } else {
                        currentlyOn2_4Ghz = true;
                        currentlyOn5Ghz = false;
                    }
                    if (rcInfo.currentChannel.overlapsWithOtherChannels === true) {
                        document.getElementById("id_show_overlapping_channels_checkbox").checked = true;
                    }
                } else {
                    currentlyOn2_4Ghz = false;
                    currentlyOn5Ghz = false;
                    currentChannel = undefined;
                    if (rcInfo.supports5GhzAp) {
                        select5GhzBand = true;
                    }
                }
                selectBand(select5GhzBand);
                updateChannelList();

                document.getElementById("id_rc_version").textContent = rcInfo.rcVersion;
                document.getElementById("id_control_hub_os_version").textContent = rcInfo.chOsVersion;

                const revHubsListing = document.getElementById("id_rev_hubs");
                revHubsListing.textContent = "";

                if (rcInfo.revHubNamesAndVersions) {
                    rcInfo.revHubNamesAndVersions.forEach(function(revHubInfo) {
                        var entry = document.createElement('p');
                        entry.innerHTML = `<b>${revHubInfo.name}</b>
                                           <br><u>Firmware version</u>: ${revHubInfo.firmwareVersion}
                                           <br><u>IMU</u>: ${revHubInfo.imuType}`;
                        revHubsListing.appendChild(entry);
                    });
                }


                // Only update the fw update button if no fw file has been selected
                if (!document.getElementById("id_input_file_firmware").value) {
                    document.getElementById("id_action_firmware").innerText = "Update to firmware version " + rcInfo.includedFirmwareFileVersion;
                }

                if (rcInfo.appUpdateRequiresReboot) {
                    appUpdateRequiresReboot = true;
                    $('#id_action_apk').html('Update &amp; Reboot');
                }
            }
        });
    };
    refreshRCInfo();

    loadJsonObject(URI_LIST_LOG_FILES, function (logFileList) {
        if (logFileList) {
            document.getElementById("id_log_count").innerHTML = " (" + logFileList.length + ")";
        }
    });

    var onDownloadLogsClicked = function() {
        loadJsonObject(URI_LIST_LOG_FILES, function (logFileList) {
            if (logFileList) {
                var i = 0;
                if (isInternetExplorer()) {
                    // the short delay allows IE to download the multiple files
                    var interval = setInterval(function() {
                        if (i < logFileList.length) {
                            var logFileName = logFileList[i++];
                            downloadFile(logFileName);
                        } else {
                            clearInterval(interval);
                        }
                    }, 100);
                } else {
                    for (i = 0; i < logFileList.length; i++) {
                        downloadFile(logFileList[i]);
                    }
                }
            } else {
                alert('unable to list robot controller log files');
            }
        });
    }

    var downloadFile = function(fileName) {
        console.log("downloadFile(" + fileName + ")");
        var url = URI_DOWNLOAD_FILE + "?" + PARAM_NAME + "=" + encodeURIComponent(fileName);
        var anchor = document.createElement("A");
        document.body.appendChild(anchor);  // firefox needs the anchor to be in the body
        anchor.style.display = "none";
        anchor.href = url;
        anchor.download = fileName;
        anchor.click();
        document.body.removeChild(anchor);
    }

</script>
</body>
</html>