Files
SC-F001/main/landingpage.html
2025-12-30 20:02:44 -06:00

607 lines
22 KiB
HTML

<!DOCTYPE html>
<html>
<!--
tan: #ba965b
light tan: #efede9
white: #ffffff
green: #2a493d
black: #2f2f2f
-->
<head>
<title>Control Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#wrapper { text-align: center; box-sizing: border-box; }
#content { max-width: 500px; margin: auto; padding: 0 10px; }
body { text-align: center; margin: 0; padding: 0; }
* {
font-size: 1.2rem;
background-color: #ffffff;
color: #2f2f2f;
font-family: "Noto Sans", "Verdana", sans-serif;
}
input, button { width: 100%; }
input, button { border: 1px solid #ba965b; border-radius: 5px; background-color: #efede9; text-align: right; box-sizing: border-box; }
input[type="text"], input[type="number"] { font-family: monospace; }
button { text-align: center; }
.changed, #commit_btn { background-color: #2a493d !important; color: #ffffff !important; }
#commit_btn { width: 100%; margin-top: 10px; padding: 10px; cursor: pointer; border: none; font-weight: bold; }
#commit_btn[disabled] { background-color: #444 !important; color: #888; cursor: not-allowed; }
table { width: 100%; border-collapse: collapse; text-align: left; }
td { padding: 8px; border-bottom: 1px solid #efede9; }
summary { border-radius: 5px; font-weight: bold; text-align: left; color: #fff; background-color: #723; padding: 0.3rem;}
.cmd { font-size: 1.5rem; border: none;}
#msg {text-align: center;}
h1 {
font-size: 2.5rem;
}
@media screen and (max-width: 350px) {
#content { max-width: 100%; padding: 0 5px; }
table tr td { display: block; width: 100%; box-sizing: border-box; } /* Stack table cells vertically on mobile for better usability */
table tr { display: block; margin-bottom: 10px; }
}
</style>
</head>
<body>
<div id="wrapper">
<div id="content">
<h1>ClusterCommand</h1>
<table>
<tr>
<td><button class="cmd" onclick="sendCommand('start')">START</button></td>
<td><button class="cmd" onclick="sendCommand('stop')" style="background-color:#723; color: #fff">STOP</button></td>
<td><button class="cmd" onclick="sendCommand('undo')">UNDO</button></td>
</tr>
</table>
<table>
<tr>
<td colspan="3"><input readonly="" id="msg"/></td>
</tr>
<tr>
<td colspan="3"><input type="datetime-local" id="in_time" step="1" onchange="markChanged(this)"/>
<button id="now_btn" onclick="setTimeToNow()">Sync Time</button></td>
</tr>
<tr>
<td>Schedule Start</td>
<td><input type="time" id="move_start" onchange="changeSchedule(this)"/></td>
</tr>
<tr>
<td>Schedule End</td>
<td><input type="time" id="move_end" onchange="changeSchedule(this)"/></td>
</tr>
<tr>
<td># Moves/Day</td>
<td><input type="number" min="0" id="num_moves" onchange="changeSchedule(this)"/></td>
</tr>
<tr>
<td>Remain. Distance (ft)</td>
<td><input type="number" id="remaining_dist" onchange="markChanged(this)"/></td>
</tr>
<tr>
<td>Move Distance (ft)</td>
<td><input type="number" min="0" id="drive_dist" onchange="changeSchedule(this)"/></td>
</tr>
<tr>
<td>Jack Height (in)</td>
<td><input type="number" min="0" id="jack_dist" onchange="changeSchedule(this)"/></td>
</tr>
<tr>
<td>Battery (V)</td>
<td><input readonly="" id="voltage"/></td>
</tr>
<tr>
<td>Program RF Remote</td>
<td>
<button onclick="programRFSequence()">Program All Buttons</button>
</td>
</tr>
</table>
<button id="commit_btn" onclick="commitParams()" disabled>Save Changes</button>
<br/>
<br/>
<details>
<summary>DANGER ZONE</summary>
<table>
<tr>
<td>Calibration</td>
<td><button onclick="calibrate('jack')">Jack Calibration</button>
<button onclick="calibrate('drive')">Drive Calibration</button></td>
</tr>
<tr>
<td>Firmware</td>
<td><input type="file" id="firmware_file" accept=".bin">
<button id="upload_btn" onclick="uploadFirmware()">Upload Firmware</button></td>
</tr>
<tr>
<td>Log File</td>
<td><button id="log_btn" onclick="downloadLogFile()">Download Log</button></td>
</tr>
</table>
<table id="table"></table>
<button class="cmd" onclick="sendCommand('reboot')" style="background-color:#723; color: #fff">REBOOT</button>
</details>
</div>
</div>
<script>
let paramValues = [];
let paramNames = [];
let paramUnits = [];
const ge = (id) => document.getElementById(id);
async function sendCommand(cmdName) {
if (cmdName === 'start') {
if (!confirm("Will begin moving - please confirm."))
return;
}
if (cmdName === 'reboot') {
if (!confirm("Device will reboot - clearing clock and distance. Are you sure?"))
return;
}
await fetch('./cmd', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({cmd: cmdName})
});
}
async function calibrate(axis) {
await fetch('./cmd', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({cmd: `cal_${axis}_start`})
});
const amt = prompt(`Press button on mover. Press button again to stop it. Then, type in actual travelled distance here in inches:`);
if (!isNaN(parseFloat(amt))) {
const response = await fetch('./cmd', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({cmd: 'cal_get'})
});
if (response.ok) {
const data = await response.json();
if (axis === 'drive') {
markChanged(ge('in_6')).value = data.e / amt;
markChanged(ge('in_7')).value = data.t / amt * 1.2; // ok to have more
} else {
markChanged(ge('in_8')).value = data.t / amt;
}
}
}
}
// Highlight changed inputs and enable the save button
function markChanged(el) {
el.classList.add("changed");
ge('commit_btn').disabled = false;
return el;
}
function toFixed(input, n) {
const num = parseFloat(input);
if (isNaN(num)) {
return null;
}
return Number(num.toFixed(n));
}
// --- 1. GET DATA ---
async function fetchStatus() {
try {
const response = await fetch('./status');
if (!response.ok) return;
const data = await response.json();
console.log(data);
// Update time field if available
if (data.time) {
const date = new Date(data.time * 1000).toISOString().slice(0, 19);
ge('in_time').value = date;
}
ge('voltage').value = toFixed(data.battery, 2);
ge('remaining_dist').value = toFixed(data.remaining_dist, 2);
ge('msg').value = data.msg;
// Store values (default to empty array if missing)
paramValues = data.values || [];
paramNames = data.names || [];
paramUnits = data.units || [];
ge('commit_btn').disabled = true;
if (!data.rtc_set) {
ge('in_time').classList.add('error');
if (confirm("Clock not set. Sync with this device's clock?")) {
setTimeToNow();
commitTime();
}
}
} catch(e) {
console.error("Error parsing JSON", e);
}
// Always render table even if request fails or data is empty
renderTable();
}
function secondsToHHMM(seconds) {
const hh = String(Math.floor(seconds / 3600)).padStart(2, '0');
const mm = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0');
return `${hh}:${mm}`;
}
function renderTable() {
const table = ge("table");
// Clear existing parameter rows
while(table.rows.length > 0) { table.deleteRow(0); }
// Loop through the NAMES array to ensure every input is shown
paramNames.forEach((name, i) => {
let row = table.insertRow(table.rows.length);
let pname = (paramNames[i] !== undefined && paramNames[i] !== null)
? paramNames[i]
: "null";
// If the server didn't send a value for this index, show "null"
let pval = (paramValues[i] !== undefined && paramValues[i] !== null)
? paramValues[i]
: "null";
row.innerHTML = `
<td>${i}</td>
<td>${pname}</td>
<td><input type="${typeof pval === 'number' ? 'number':'text'}" id="in_${i}" value="${pval}" oninput="markChanged(this)"></td>
<td>${paramUnits[i] || ""}</td>
`;
});
for (const input of document.getElementsByTagName("input")) {
input.addEventListener("click", (e) => {
e.target.select();
});
}
ge('num_moves').value = paramValues[1];
ge('move_start').value = secondsToHHMM(paramValues[2]);
ge('move_end').value = secondsToHHMM(paramValues[3]);
ge('drive_dist').value = paramValues[4];
ge('jack_dist').value = paramValues[5];
}
function changeSchedule(e) {
markChanged(e);
if (e.id === "num_moves") {
ge('in_1').value = e.value;
markChanged(ge('in_1'));
}
if (e.id === "move_start") {
const [hours, minutes] = e.value.split(':').map(Number);
ge('in_2').value = hours*3600 + minutes*60;
markChanged(ge('in_2'));
}
if (e.id === "move_end") {
const [hours, minutes] = e.value.split(':').map(Number);
ge('in_3').value = hours*3600 + minutes*60;
markChanged(ge('in_3'));
}
if (e.id === "drive_dist") {
ge('in_4').value = e.value;
markChanged(ge('in_4'));
}
if (e.id === "jack_dist") {
ge('in_5').value = e.value;
markChanged(ge('in_5'));
}
}
function setTimeToNow() {
const e = ge('in_time');
markChanged(e);
e.value = new Date().toLocaleString('sv-SE');
}
async function commitTime() {
// Time handling
const datetimeStr = ge("in_time").value; // e.g., "2024-03-15T14:30:00"
// Parse the components
const [datePart, timePart] = datetimeStr.split('T');
const [year, month, day] = datePart.split('-').map(Number);
const [hour, minute, second = 0] = timePart.split(':').map(Number);
// Create UTC timestamp (month is 0-indexed in Date.UTC)
const epoch = Math.floor(Date.UTC(year, month - 1, day, hour, minute, second) / 1000);
const response = await fetch('./st', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: epoch.toString()
});
if (response.ok) {
ge("in_time").classList.remove("changed");
}
if (document.querySelectorAll('input.changed').length === 0) {
ge('commit_btn').disabled = true;
} else {
ge('commit_btn').disabled = false;
}
}
// --- 2. POST DATA ---
async function commitParams() {
ge('commit_btn').disabled = true;
const changedInputs = document.querySelectorAll('input.changed');
const sp = {};
for (const input of changedInputs) {
if (input.id === "in_time") {
await commitTime();
}
else if (input.id === "remaining_dist") {
const x = parseFloat(ge('remaining_dist').value);
const response = await fetch('./cmd', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({cmd: "remaining_dist", amt: x})
});
if (response.ok) {
ge('remaining_dist').classList.remove("changed");
}
}
else if (input.id.startsWith('in_')) {
// Parameter handling
const id = input.id.split('_')[1];
// If the user typed "null", we send null; otherwise parse as float
sp[id] = input.value;
if (input.type === "number") {
sp[id] = (input.value.toLowerCase() === "null") ? null : parseFloat(input.value);
}
}
}
if (Object.keys(sp).length !== 0) {
const response = await fetch('./sp', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(sp)
});
if (response.ok) {
changedInputs.forEach(input => {
if (input.id !== "in_time") {
input.classList.remove("changed");
}
});
} else {
ge('commit_btn').disabled = false;
}
}
await fetchStatus();
}
async function uploadFirmware() {
const fileInput = ge('firmware_file');
if (!fileInput.files.length) {
alert('No file selected');
return;
}
const file = fileInput.files[0];
try {
const response = await fetch('./ota', {
method: 'POST',
headers: {'Content-Type': 'application/octet-stream'},
body: file
});
if (response.ok) {
alert('Upload successful. Device may reboot.');
} else {
alert('Upload failed: ' + response.status);
}
} catch (e) {
alert('Network error during upload');
}
}
function programRF(i) {
fetch('./cmd', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({cmd: 'rfp', channel: i})
});
}
async function programRFSequence() {
const buttonNames = ["Forward", "Reverse", "Up", "Down"];
const learnedCodes = [null, null, null, null];
if (!confirm("This will program all 4 RF remote buttons in sequence.\n\nPress OK to begin, then follow the prompts.")) {
return;
}
// Clear temp storage and disable RF controls during programming
await fetch('./cmd', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({cmd: 'rf_clear_temp'})
});
await fetch('./cmd', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({cmd: 'rf_disable'})
});
for (let i = 0; i < 4; i++) {
// Start learning for this button FIRST
programRF(i);
// Give a moment for the learn flag to be set
await new Promise(resolve => setTimeout(resolve, 100));
// Show dialog and wait for user to press OK
alert(`Button ${i+1}/4: ${buttonNames[i]}\n\nPress the ${buttonNames[i]} button on your remote now.\n\nPress OK when done (or just press OK to leave unprogrammed).`);
// Cancel learning mode
programRF(-1);
// Check what was learned (if anything)
try {
const response = await fetch('./cmd', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({cmd: 'rf_status'})
});
const data = await response.json();
// Get whatever is in temp storage (could be -1 if nothing was pressed)
learnedCodes[i] = data.codes[i];
} catch (e) {
console.error("Error checking RF status:", e);
learnedCodes[i] = -1;
}
// If nothing was learned, make sure it's set to -1
if (learnedCodes[i] === -1) {
await fetch('./cmd', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({cmd: 'rf_set_temp', index: i, code: -1})
});
}
}
// Update input fields for parameters 9-12 (PARAM_KEYCODE_0 through PARAM_KEYCODE_3)
for (let i = 0; i < 4; i++) {
const input = ge(`in_${9 + i}`);
if (input) {
input.value = learnedCodes[i];
markChanged(input);
}
}
// Commit just the RF keycodes (params 9-12)
const sp = {};
for (let i = 0; i < 4; i++) {
sp[9 + i] = learnedCodes[i];
}
const response = await fetch('./sp', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(sp)
});
if (response.ok) {
// Unhighlight the keycode inputs
for (let i = 0; i < 4; i++) {
const input = ge(`in_${9 + i}`);
if (input) {
input.classList.remove("changed");
}
}
// Check if commit button should stay enabled
if (document.querySelectorAll('input.changed').length === 0) {
ge('commit_btn').disabled = true;
}
}
// Re-enable RF controls after programming
await fetch('./cmd', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({cmd: 'rf_enable'})
});
// Show summary
let summary = "RF Remote Programming Complete!\n\n";
for (let i = 0; i < 4; i++) {
if (learnedCodes[i] === -1) {
summary += `${buttonNames[i]}: Not programmed\n`;
} else {
summary += `${buttonNames[i]}: ${learnedCodes[i]}\n`;
}
}
alert(summary);
await fetchStatus();
}
async function downloadLogFile() {
try {
const response = await fetch('./log');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const blob = await response.blob();
// Get current date and time
const now = new Date();
const day = String(now.getDate()).padStart(2, '0');
const monthNames = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
const month = monthNames[now.getMonth()];
const year = now.getFullYear();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const formattedDate = `${day}${month}${year}-${hours}${minutes}`;
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `storage-${formattedDate}.bin`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (error) {
console.error('Download failed:', error);
}
}
// Initial Load
window.onload = fetchStatus;
</script>
</body>
</html>