Loading files
/* ==========================================================================
OWL Dashboard - System Stats Module
System status polling and UI updates
========================================================================== */
/**
* Start system status update interval
*/
function startUpdateInterval() {
if (updateInterval) clearInterval(updateInterval);
updateSystemStats();
updateInterval = setInterval(updateSystemStats, SYSTEM_UPDATE_INTERVAL);
}
// Last seen storage warning level; notifications fire on transitions only
let lastStorageWarning = null;
function watchStorageWarning(data) {
const warning = data.storage_warning || 'ok';
if (warning === lastStorageWarning) return;
const previous = lastStorageWarning;
lastStorageWarning = warning;
if (previous === null) return; // first poll: no transition to report
const freeGb = (typeof data.storage_free_mb === 'number')
? (data.storage_free_mb / 1024).toFixed(1) : null;
const freeText = freeGb ? ` (${freeGb} GB free)` : '';
if (warning === 'full') {
showNotification('Storage full',
`Recording unavailable${freeText}. Download or delete sessions to continue`,
'error', 10000);
} else if (warning === 'low') {
showNotification('Storage low',
`Space is running out${freeText}. Download or delete sessions soon`,
'warning', 8000);
} else if (previous === 'full' || previous === 'low') {
showNotification('Storage recovered', `Recording available again${freeText}`, 'success');
}
}
// Spray timing labels (farmer wording). Keys are the OWL's actuation_source.
const SPRAY_TIMING_LABELS = {
'device-gps': 'OWL GPS timing',
controller: 'Controller timing',
config: 'Fixed timing'
};
// Last seen speed warning; notifications fire on transitions only
let lastSpeedWarning = null;
function updateSprayTiming(data) {
const line = document.getElementById('sprayTimingLine');
if (line) {
const parts = [];
if (typeof data.speed_kmh === 'number') parts.push(data.speed_kmh.toFixed(1) + ' km/h');
if (SPRAY_TIMING_LABELS[data.actuation_source]) parts.push(SPRAY_TIMING_LABELS[data.actuation_source]);
if (typeof data.latency_ms === 'number') parts.push('Processing ' + Math.round(data.latency_ms) + ' ms');
// Only worth a line once there is a speed or a measured processing time
const show = typeof data.speed_kmh === 'number' || typeof data.latency_ms === 'number';
line.textContent = show ? parts.join(' · ') : '';
line.classList.toggle('hidden', !show);
}
const warning = data.speed_warning || '';
let banner = document.getElementById('speedWarningBanner');
if (warning && !banner && line) {
banner = document.createElement('div');
banner.id = 'speedWarningBanner';
banner.className = 'algorithm-error-banner';
line.parentNode.insertBefore(banner, line.nextSibling);
}
if (banner) {
banner.textContent = warning;
banner.style.display = warning ? '' : 'none';
}
if (warning === lastSpeedWarning) return;
const previous = lastSpeedWarning;
lastSpeedWarning = warning;
if (warning) {
showNotification('Slow down', warning, 'warning', 8000);
} else if (previous) {
showNotification('Speed OK', 'Sprays are on target again', 'success');
}
}
/**
* Update system stats from API
*/
function updateSystemStats() {
apiRequest('/api/system_stats')
.then(r => r.json())
.then(data => {
// Cache resolution + clamp state for recording warning check
lastResWidth = data.resolution_width || 0;
lastResHeight = data.resolution_height || 0;
lastRequestedResWidth = data.requested_resolution_width || data.resolution_width || 0;
lastRequestedResHeight = data.requested_resolution_height || data.resolution_height || 0;
lastResolutionClamped = !!data.resolution_clamped;
lastRpiVersion = data.rpi_version || 'unknown';
lastAllowHighResolution = !!data.allow_high_resolution;
if (typeof setHighResContextBadge === 'function') {
setHighResContextBadge(lastRpiVersion);
}
// Gradient chips
setText('cpuChipVal', `${data.cpu_percent}%`);
setText('memChipVal', `${data.memory_percent}%`);
setText('tempChipVal', `${data.cpu_temp}°C`);
// Active config indicator (subtle line below the feed). Trim the
// .ini and the _YYYYMMDD_HHMMSS timestamp to a readable name.
const cfgLine = document.getElementById('activeConfigLine');
if (cfgLine) {
// The autosave working file displays as its source preset; the
// unsaved marker only shows when content differs from the source
const rawName = data.config_source || data.config_name || '';
let cfgName = rawName.replace(/\.ini$/, '');
cfgName = cfgName.replace(/_\d{8}_\d{6}$/, '').replace(/[-_]+/g, ' ').trim();
if (cfgName && data.config_unsaved) cfgName += ' - unsaved changes';
if (cfgName) {
setText('activeConfigName', cfgName);
cfgLine.classList.remove('hidden');
} else {
cfgLine.classList.add('hidden');
}
}
// Power button reflects owl_running
setPowerButtonState(!!data.owl_running);
// Detection & recording big switches (and status chip)
const detectionOn = !!(data.detection_running ?? data.detection_enable);
const recordingOn = !!(data.recording ?? data.image_sample_enable);
const nozzlesOn = data.detection_mode === 2;
syncSwitch('detectSwitch', nozzlesOn ? false : detectionOn);
syncSwitch('recordSwitch', recordingOn);
syncSwitch('nozzleSwitch', nozzlesOn);
syncSwitch('trackingSwitch', !!data.tracking_enabled);
// Sync session metadata panel visibility with recording state
if (typeof syncSessionMetadataPanel === 'function') {
syncSessionMetadataPanel(recordingOn);
}
// Show/hide track stability panel based on tracking state
var stabilityTile = document.getElementById('track-stability-tile');
if (stabilityTile) {
stabilityTile.style.display = data.tracking_enabled ? '' : 'none';
}
// OWL service status chip
const owlChip = document.getElementById('owlStatusChip');
const owlText = document.getElementById('owlStatusText');
if (owlChip && owlText) {
if (data.owl_running) {
owlChip.classList.add('on');
owlChip.classList.remove('off');
owlText.textContent = 'Running';
} else {
owlChip.classList.remove('on');
owlChip.classList.add('off');
owlText.textContent = 'Stopped';
}
}
// Sensitivity buttons (mode-aware: reads the axis matching the
// active detection mode, highlights nothing on a custom value)
if (typeof syncSensitivityFromStats === 'function') {
syncSensitivityFromStats(data);
}
// Fan Auto/100 + RPM
const fanMode = normalizeFanMode(data.fan_status);
document.querySelectorAll('.seg-btn[data-fan]').forEach(b => {
b.classList.toggle('active', b.dataset.fan === fanMode);
});
const rpmEl = document.getElementById('fanRpmReadout');
if (rpmEl) {
const rpm = data?.fan_status?.rpm;
rpmEl.textContent = (typeof rpm === 'number') ? `${rpm} rpm` : '--';
}
// Storage warning transitions (internal/eMMC mode): notify once
// per state change, never per poll
watchStorageWarning(data);
// Spray timing line + forward-speed warning
updateSprayTiming(data);
// Header online/offline
const statusDot = document.getElementById('statusDot');
const statusText = document.getElementById('statusText');
if (statusDot && statusText) {
statusDot.classList.toggle('connected', !!data.owl_running);
statusText.textContent = data.owl_running ? 'Online' : 'Offline';
}
// Header cloud (Noktura) link status
renderCloudStatus(
document.getElementById('cloudStatusDot'),
document.getElementById('cloudStatusText'),
data
);
if (typeof updateCloudManageBlock === 'function') {
updateCloudManageBlock(data);
}
// Sync AI tab if function exists
if (typeof syncAITabFromStats === 'function') {
syncAITabFromStats(data);
}
// Sync config sliders from MQTT state
if (typeof syncSlidersFromStats === 'function') {
syncSlidersFromStats(data);
}
// Sync painted LUT panel (config tab)
if (typeof syncLutPanelFromStats === 'function') {
syncLutPanelFromStats(data);
}
// Update hardware lock UI based on controller status
updateHardwareLockUI();
// Pipeline mode selector
if (typeof updatePipelineModeUI === 'function' && data.algorithm) {
updatePipelineModeUI(data.algorithm);
}
if (typeof updateModeAvailability === 'function') {
updateModeAvailability(!!data.model_available);
}
if (typeof updatePaintedChipHint === 'function') {
updatePaintedChipHint((data.available_lut_profiles || []).length > 0);
}
// Algorithm error banner
if (typeof updateAlgorithmError === 'function') {
updateAlgorithmError(data.algorithm_error);
}
// Live white balance readout + calibration progress (Config tab)
if (typeof updateAwbReadout === 'function') {
updateAwbReadout(data.camera, data.awb_calibration,
typeof onAwbCalibrationComplete === 'function' ? onAwbCalibrationComplete : null);
}
})
.catch(err => {
// Silent fail for stats polling
})
.finally(() => {
checkForErrors();
});
// Helper functions
function setText(id, text) {
const el = document.getElementById(id);
if (el) el.textContent = text;
}
function syncSwitch(id, on) {
const btn = document.getElementById(id);
if (!btn) return;
btn.setAttribute('aria-pressed', on ? 'true' : 'false');
const state = btn.querySelector('.switch-state');
if (state) state.textContent = on ? 'ON' : 'OFF';
}
function setPowerButtonState(on) {
const btn = document.getElementById('owlPowerBtn');
if (!btn) return;
btn.classList.remove('booting', 'stopping');
btn.setAttribute('aria-pressed', on ? 'true' : 'false');
btn.classList.toggle('on', on);
}
}
/**
* Normalize sensitivity data from API
*/
function normalizeSensitivity(data) {
if (data && typeof data.sensitivity_level === 'string') {
return data.sensitivity_level.toLowerCase();
}
return 'medium';
}
/**
* Normalize fan mode from status object
*/
function normalizeFanMode(status) {
if (!status || !status.mode) return 'auto';
const m = String(status.mode).toLowerCase();
if (m.includes('100')) return '100';
if (m.includes('auto')) return 'auto';
return (m === '1' || m === '100' || m === '1.0') ? '100' : 'auto';
}
/**
* Polls the backend for errors from owl.py and displays them as notifications
*/
function checkForErrors() {
apiRequest('/api/get_errors')
.then(response => response.json())
.then(errors => {
if (errors && errors.length > 0) {
errors.forEach(error => {
const title = `OWL Error: ${error.level || 'ERROR'}`;
const message = error.message || 'An unknown error occurred.';
showNotification(title, message, 'error', 0);
});
}
})
.catch(error => {
// Silent fail for error polling
});
}
d12e5a18fThis file is pinned to the selected release. Download the original to open it in your design tool.