feature/gateway #21

Merged
master merged 4 commits from feature/gateway into main 2025-10-21 13:50:55 +02:00
8 changed files with 1782 additions and 1398 deletions

198
README.md
View File

@@ -1,14 +1,22 @@
# SPORE UI # SPORE UI Frontend
Zero-configuration web interface for monitoring and managing SPORE embedded systems. Frontend web interface for monitoring and managing SPORE embedded systems. Now works in conjunction with the SPORE Gateway backend service.
## Architecture
This frontend server works together with the **SPORE Gateway** (spore-gateway) backend service:
- **spore-ui**: Serves the static frontend files and provides the user interface
- **spore-gateway**: Handles UDP node discovery, API endpoints, and WebSocket connections
## Features ## Features
- **🌐 Cluster Monitoring**: Real-time view of all cluster members with auto-discovery - **🌐 Cluster Monitoring**: Real-time view of all cluster members via spore-gateway
- **📊 Node Details**: Detailed system information including running tasks and available endpoints - **📊 Node Details**: Detailed system information including running tasks and available endpoints
- **🚀 OTA**: Clusterwide over-the-air firmware updates - **🚀 OTA**: Clusterwide over-the-air firmware updates
- **📱 Responsive**: Works on all devices and screen sizes - **📱 Responsive**: Works on all devices and screen sizes
- **🖥️ Terminal**: Terminal for interacting with a node's WebSocket - **🖥️ Terminal**: Terminal for interacting with a node's WebSocket
- **🔗 Gateway Integration**: Seamlessly connects to spore-gateway for all backend functionality
## Screenshots ## Screenshots
### Cluster ### Cluster
@@ -22,161 +30,85 @@ Zero-configuration web interface for monitoring and managing SPORE embedded syst
## Getting Started ## Getting Started
### Prerequisites
1. **Install dependencies**: `npm install` 1. **Install dependencies**: `npm install`
2. **Start the server**: `npm start` 2. **Start spore-gateway**: `./spore-gateway` (in the spore-gateway directory)
3. **Open in browser**: `http://localhost:3001` 3. **Start frontend server**: `npm start`
## API Endpoints ### Access
- **Frontend UI**: `http://localhost:3000`
- **API Backend**: spore-gateway runs on port 3001
- **WebSocket**: Connects to spore-gateway on port 3001
- **`/`** - Main UI page ## API Integration
- **`/api/cluster/members`** - Get cluster member information
- **`/api/tasks/status`** - Get task status The frontend automatically connects to the spore-gateway for:
- **`/api/node/status`** - Get system status
- **`/api/node/status/:ip`** - Get status from specific node - **Cluster Discovery**: `/api/discovery/*` endpoints
- **Node Management**: `/api/node/*` endpoints
- **Task Monitoring**: `/api/tasks/*` endpoints
- **Real-time Updates**: WebSocket connections via `/ws`
## Technologies Used ## Technologies Used
- **Backend**: Express.js, Node.js - **Backend Integration**: Express.js server connecting to spore-gateway
- **Frontend**: Vanilla JavaScript, CSS3, HTML5 - **Frontend**: Vanilla JavaScript, CSS3, HTML5
- **Framework**: Custom component-based architecture - **Framework**: Custom component-based architecture
- **API**: SPORE Embedded System API - **API**: SPORE Embedded System API via spore-gateway
- **Design**: Glassmorphism, CSS Grid, Flexbox - **Design**: Glassmorphism, CSS Grid, Flexbox
## UDP Heartbeat Discovery ## Development
The backend now includes automatic UDP heartbeat-based discovery for SPORE nodes on the network. This eliminates the need for hardcoded IP addresses and provides a self-healing, scalable solution for managing SPORE clusters. ### File Structure
```
### 🚀 How It Works spore-ui/
├── public/ # Static frontend files
1. **UDP Server**: The backend listens on port 4210 for UDP messages │ ├── index.html # Main HTML page
2. **Heartbeat Message**: Nodes send `CLUSTER_HEARTBEAT` messages to broadcast address `255.255.255.255:4210` │ ├── scripts/ # JavaScript components
3. **Auto Configuration**: When a heartbeat message is received, the source IP is automatically used to configure the SporeApiClient │ └── styles/ # CSS stylesheets
4. **Dynamic Updates**: The system automatically switches to the most recently seen node as the primary connection ├── index.js # Simple static file server
5. **Health Monitoring**: Continuous monitoring of node availability with automatic failover └── package.json # Node.js dependencies
### 📡 Heartbeat Protocol
- **Port**: 4210 (configurable via `UDP_PORT` constant)
- **Message**: `CLUSTER_HEARTBEAT` (configurable via `HEARTBEAT_MESSAGE` constant)
- **Broadcast**: `255.255.255.255:4210`
- **Protocol**: UDP broadcast listening
- **Auto-binding**: Automatically binds to the specified port on startup
### 🔧 Setup Instructions
#### Backend Setup
```bash
# Start the backend server
npm start
# The server will automatically:
# - Start HTTP server on port 3001
# - Start UDP heartbeat server on port 4210
# - Wait for CLUSTER_HEARTBEAT messages
``` ```
#### Node Configuration ### Key Changes
SPORE nodes should send heartbeat messages periodically: - **Simplified Backend**: Now only serves static files
- **Gateway Integration**: All API calls go through spore-gateway
- **WebSocket Proxy**: Real-time updates via spore-gateway
- **UDP Discovery**: Handled by spore-gateway service
## Troubleshooting
### Common Issues
**Frontend not connecting to gateway**
```bash ```bash
# Recommended: Send every 30-60 seconds # Check if spore-gateway is running
# Message format: "CLUSTER_HEARTBEAT:hostname"
# Target: 255.255.255.255:4210
```
### 🌐 Cluster Endpoints
#### Cluster Management
- `GET /api/discovery/nodes` - View all cluster nodes and current status
- `POST /api/discovery/refresh` - Manually trigger cluster refresh
- `POST /api/discovery/primary/:ip` - Manually set a specific node as primary
- `POST /api/discovery/random-primary` - Randomly select a new primary node
#### Health Monitoring
- `GET /api/health` - Comprehensive health check including cluster status
### 🧪 Testing & Development
#### Test Scripts
```bash
# Send discovery messages to test the system
npm run test-discovery broadcast
# Send to specific IP
npm run test-discovery 192.168.1.100
# Send multiple messages
npm run test-discovery broadcast 5
# Test random primary node selection
npm run test-random-selection
# Monitor discovery in real-time
npm run demo-discovery
```
#### Manual Testing
```bash
# Check discovery status
curl http://localhost:3001/api/discovery/nodes
# Check health
curl http://localhost:3001/api/health curl http://localhost:3001/api/health
# Manual refresh # Verify gateway health
curl -X POST http://localhost:3001/api/discovery/refresh # Should return gateway health status
# Random primary selection
curl -X POST http://localhost:3001/api/discovery/random-primary
# Set specific primary
curl -X POST http://localhost:3001/api/discovery/primary/192.168.1.100
``` ```
### 🔍 Troubleshooting **WebSocket connection issues**
#### Common Issues
**No Nodes Discovered**
```bash ```bash
# Check if backend is running # Check WebSocket endpoint
curl http://localhost:3001/api/health curl http://localhost:3001/api/test/websocket
# Verify UDP port is open # Verify gateway WebSocket server is running
netstat -tulpn | grep 4210
# Send test discovery message
npm run test-discovery broadcast
``` ```
**UDP Port Already in Use** **No cluster data**
```bash ```bash
# Check for conflicting processes # Check gateway discovery status
netstat -tulpn | grep 4210
# Kill conflicting processes or change port in code
# Restart backend server
```
**Client Not Initialized**
```bash
# Check discovery status
curl http://localhost:3001/api/discovery/nodes curl http://localhost:3001/api/discovery/nodes
# Verify nodes are sending discovery messages # Verify SPORE nodes are sending heartbeat messages
# Check network connectivity
``` ```
#### Debug Commands ## Architecture Benefits
```bash
# Check discovery status
curl http://localhost:3001/api/discovery/nodes
# Check health 1. **Separation of Concerns**: Frontend handles UI, gateway handles backend logic
curl http://localhost:3001/api/health 2. **Scalability**: Gateway can handle multiple frontend instances
3. **Maintainability**: Clear separation between presentation and business logic
# Manual refresh 4. **Performance**: Gateway can optimize API calls and caching
curl -X POST http://localhost:3001/api/discovery/refresh 5. **Reliability**: Gateway provides failover and health monitoring
# Set primary node
curl -X POST http://localhost:3001/api/discovery/primary/192.168.1.100
```

1164
index-standalone.js Normal file

File diff suppressed because it is too large Load Diff

1141
index.js

File diff suppressed because it is too large Load Diff

View File

@@ -159,9 +159,9 @@ class WebSocketClient {
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
if (currentHost === 'localhost' || currentHost === '127.0.0.1') { if (currentHost === 'localhost' || currentHost === '127.0.0.1') {
this.wsUrl = `${wsProtocol}//localhost:3001`; this.wsUrl = `${wsProtocol}//localhost:3001/ws`;
} else { } else {
this.wsUrl = `${wsProtocol}//${currentHost}:3001`; this.wsUrl = `${wsProtocol}//${currentHost}:3001/ws`;
} }
logger.debug('WebSocket Client initialized with URL:', this.wsUrl); logger.debug('WebSocket Client initialized with URL:', this.wsUrl);
@@ -225,6 +225,9 @@ class WebSocketClient {
case 'node_discovery': case 'node_discovery':
this.emit('nodeDiscovery', data); this.emit('nodeDiscovery', data);
break; break;
case 'firmware_upload_status':
this.emit('firmwareUploadStatus', data);
break;
default: default:
logger.debug('Unknown WebSocket message type:', data.type); logger.debug('Unknown WebSocket message type:', data.type);
} }

View File

@@ -34,6 +34,9 @@ class FirmwareComponent extends Component {
this.addEventListener(radio, 'change', this.handleTargetChange.bind(this)); this.addEventListener(radio, 'change', this.handleTargetChange.bind(this));
}); });
// Setup WebSocket listener for real-time firmware upload status
this.setupWebSocketListeners();
// Setup specific node select change handler // Setup specific node select change handler
const specificNodeSelect = this.findElement('#specific-node-select'); const specificNodeSelect = this.findElement('#specific-node-select');
logger.debug('FirmwareComponent: setupEventListeners - specificNodeSelect found:', !!specificNodeSelect); logger.debug('FirmwareComponent: setupEventListeners - specificNodeSelect found:', !!specificNodeSelect);
@@ -258,8 +261,10 @@ class FirmwareComponent extends Component {
await this.uploadToLabelFilteredNodes(file); await this.uploadToLabelFilteredNodes(file);
} }
// Reset interface after successful upload // NOTE: Don't reset upload state here!
this.viewModel.resetUploadState(); // The upload state should remain active until websocket confirms completion
// Status updates and finalization happen via websocket messages in checkAndFinalizeUploadResults()
logger.debug('Firmware upload HTTP requests completed, waiting for websocket status updates');
} catch (error) { } catch (error) {
logger.error('Firmware deployment failed:', error); logger.error('Firmware deployment failed:', error);
@@ -271,7 +276,7 @@ class FirmwareComponent extends Component {
onConfirm: () => {}, onConfirm: () => {},
onCancel: null onCancel: null
}); });
} finally { // Only complete upload on error
this.viewModel.completeUpload(); this.viewModel.completeUpload();
} }
} }
@@ -300,8 +305,8 @@ class FirmwareComponent extends Component {
// Start batch upload // Start batch upload
const results = await this.performBatchUpload(file, nodes); const results = await this.performBatchUpload(file, nodes);
// Display results // Don't display results here - wait for websocket to confirm all uploads complete
this.displayUploadResults(results); logger.debug('Batch upload HTTP requests completed, waiting for websocket confirmations');
} catch (error) { } catch (error) {
logger.error('Failed to upload firmware to all nodes:', error); logger.error('Failed to upload firmware to all nodes:', error);
@@ -314,23 +319,19 @@ class FirmwareComponent extends Component {
// Show upload progress area // Show upload progress area
this.showUploadProgress(file, [{ ip: nodeIp, hostname: nodeIp }]); this.showUploadProgress(file, [{ ip: nodeIp, hostname: nodeIp }]);
// Update progress to show starting // Note: Status updates will come via websocket messages
this.updateNodeProgress(1, 1, nodeIp, 'Uploading...'); // We don't update progress here as the HTTP response is just an acknowledgment
// Perform single node upload // Perform single node upload (this sends the file and gets acknowledgment)
const result = await this.performSingleUpload(file, nodeIp); const result = await this.performSingleUpload(file, nodeIp);
// Update progress to show completion // Don't immediately mark as completed - wait for websocket status updates
this.updateNodeProgress(1, 1, nodeIp, 'Completed'); logger.debug(`Firmware upload initiated for node ${nodeIp}, waiting for completion status via websocket`);
this.updateOverallProgress(1, 1);
// Display results
this.displayUploadResults([result]);
} catch (error) { } catch (error) {
logger.error(`Failed to upload firmware to node ${nodeIp}:`, error); logger.error(`Failed to upload firmware to node ${nodeIp}:`, error);
// Update progress to show failure // For HTTP errors, we can immediately mark as failed since the upload didn't start
this.updateNodeProgress(1, 1, nodeIp, 'Failed'); this.updateNodeProgress(1, 1, nodeIp, 'Failed');
this.updateOverallProgress(0, 1); this.updateOverallProgress(0, 1);
@@ -369,8 +370,8 @@ class FirmwareComponent extends Component {
// Start batch upload // Start batch upload
const results = await this.performBatchUpload(file, nodes); const results = await this.performBatchUpload(file, nodes);
// Display results // Don't display results here - wait for websocket to confirm all uploads complete
this.displayUploadResults(results); logger.debug('Label-filtered upload HTTP requests completed, waiting for websocket confirmations');
} catch (error) { } catch (error) {
logger.error('Failed to upload firmware to label-filtered nodes:', error); logger.error('Failed to upload firmware to label-filtered nodes:', error);
throw error; throw error;
@@ -382,22 +383,24 @@ class FirmwareComponent extends Component {
const totalNodes = nodes.length; const totalNodes = nodes.length;
let successfulUploads = 0; let successfulUploads = 0;
// Initialize all nodes as uploading first
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
const nodeIp = node.ip;
this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Uploading...');
}
for (let i = 0; i < nodes.length; i++) { for (let i = 0; i < nodes.length; i++) {
const node = nodes[i]; const node = nodes[i];
const nodeIp = node.ip; const nodeIp = node.ip;
try { try {
// Update progress // Upload to this node (HTTP call just initiates the upload)
this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Uploading...');
// Upload to this node
const result = await this.performSingleUpload(file, nodeIp); const result = await this.performSingleUpload(file, nodeIp);
results.push(result);
successfulUploads++;
// Update progress // Don't immediately mark as completed - wait for websocket status
this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Completed'); logger.debug(`Firmware upload initiated for node ${nodeIp}, waiting for completion status via websocket`);
this.updateOverallProgress(successfulUploads, totalNodes); results.push(result);
} catch (error) { } catch (error) {
logger.error(`Failed to upload to node ${nodeIp}:`, error); logger.error(`Failed to upload to node ${nodeIp}:`, error);
@@ -410,9 +413,8 @@ class FirmwareComponent extends Component {
}; };
results.push(errorResult); results.push(errorResult);
// Update progress // For HTTP errors, we can immediately mark as failed since the upload didn't start
this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Failed'); this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Failed');
this.updateOverallProgress(successfulUploads, totalNodes);
} }
// Small delay between uploads // Small delay between uploads
@@ -428,10 +430,16 @@ class FirmwareComponent extends Component {
try { try {
const result = await window.apiClient.uploadFirmware(file, nodeIp); const result = await window.apiClient.uploadFirmware(file, nodeIp);
// IMPORTANT: This HTTP response is just an acknowledgment that the gateway received the file
// The actual firmware processing happens asynchronously on the device
// Status updates will come via WebSocket messages, NOT from this HTTP response
logger.debug(`HTTP acknowledgment received for ${nodeIp}:`, result);
logger.debug(`This does NOT mean upload is complete - waiting for WebSocket status updates`);
return { return {
nodeIp: nodeIp, nodeIp: nodeIp,
hostname: nodeIp, hostname: nodeIp,
success: true, httpAcknowledged: true, // Changed from 'success' to make it clear this is just HTTP ack
result: result, result: result,
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
}; };
@@ -467,7 +475,7 @@ class FirmwareComponent extends Component {
<span class="progress-text">0/${nodes.length} Successful (0%)</span> <span class="progress-text">0/${nodes.length} Successful (0%)</span>
</div> </div>
<div class="progress-summary" id="progress-summary"> <div class="progress-summary" id="progress-summary">
<span>Status: Preparing upload...</span> <span>Status: Upload in progress...</span>
</div> </div>
</div> </div>
<div class="progress-list" id="progress-list"> <div class="progress-list" id="progress-list">
@@ -477,7 +485,7 @@ class FirmwareComponent extends Component {
<span class="node-name">${node.hostname || node.ip}</span> <span class="node-name">${node.hostname || node.ip}</span>
<span class="node-ip">${node.ip}</span> <span class="node-ip">${node.ip}</span>
</div> </div>
<div class="progress-status">Pending...</div> <div class="progress-status uploading">Uploading...</div>
<div class="progress-time" id="time-${node.ip}"></div> <div class="progress-time" id="time-${node.ip}"></div>
</div> </div>
`).join('')} `).join('')}
@@ -490,7 +498,7 @@ class FirmwareComponent extends Component {
// Initialize progress for single-node uploads // Initialize progress for single-node uploads
if (nodes.length === 1) { if (nodes.length === 1) {
const node = nodes[0]; const node = nodes[0];
this.updateNodeProgress(1, 1, node.ip, 'Pending...'); this.updateNodeProgress(1, 1, node.ip, 'Uploading...');
} }
} }
@@ -543,15 +551,9 @@ class FirmwareComponent extends Component {
progressBar.style.backgroundColor = '#fbbf24'; progressBar.style.backgroundColor = '#fbbf24';
} }
// Update progress summary for single-node uploads // NOTE: Don't update progress summary here for single-node uploads
const progressSummary = this.findElement('#progress-summary'); // The summary should only be updated via websocket status updates
if (progressSummary && totalNodes === 1) { // This prevents premature "completed successfully" messages
if (successfulUploads === 1) {
progressSummary.innerHTML = '<span>Status: Upload completed successfully</span>';
} else if (successfulUploads === 0) {
progressSummary.innerHTML = '<span>Status: Upload failed</span>';
}
}
} }
} }
@@ -635,6 +637,217 @@ class FirmwareComponent extends Component {
} }
} }
setupWebSocketListeners() {
// Listen for real-time firmware upload status updates
window.wsClient.on('firmwareUploadStatus', (data) => {
this.handleFirmwareUploadStatus(data);
});
}
handleFirmwareUploadStatus(data) {
const { nodeIp, status, filename, fileSize, timestamp } = data;
logger.debug('Firmware upload status received:', { nodeIp, status, filename, timestamp: new Date(timestamp).toLocaleTimeString() });
// Check if there's currently an upload in progress
const isUploading = this.viewModel.get('isUploading');
if (!isUploading) {
logger.debug('No active upload, ignoring status update');
return;
}
// Find the progress item for this node
const progressItem = this.findElement(`[data-node-ip="${nodeIp}"]`);
if (!progressItem) {
logger.debug('No progress item found for node:', nodeIp);
return;
}
// Update the status display based on the received status
const statusElement = progressItem.querySelector('.progress-status');
const timeElement = progressItem.querySelector('.progress-time');
if (statusElement) {
let displayStatus = status;
let statusClass = '';
logger.debug(`Updating status for node ${nodeIp}: ${status} -> ${displayStatus}`);
switch (status) {
case 'uploading':
displayStatus = 'Uploading...';
statusClass = 'uploading';
break;
case 'completed':
displayStatus = 'Completed';
statusClass = 'success';
logger.debug(`Node ${nodeIp} marked as completed`);
break;
case 'failed':
displayStatus = 'Failed';
statusClass = 'error';
break;
default:
displayStatus = status;
break;
}
statusElement.textContent = displayStatus;
statusElement.className = `progress-status ${statusClass}`;
// Update timestamp for completed/failed uploads
if ((status === 'completed' || status === 'failed') && timeElement) {
timeElement.textContent = new Date(timestamp).toLocaleTimeString();
} else if (status === 'uploading' && timeElement) {
timeElement.textContent = 'Started: ' + new Date(timestamp).toLocaleTimeString();
}
}
// Update overall progress if we have multiple nodes
this.updateOverallProgressFromStatus();
// Check if all uploads are complete and finalize results
this.checkAndFinalizeUploadResults();
}
checkAndFinalizeUploadResults() {
const progressItems = this.findAllElements('.progress-item');
if (progressItems.length === 0) return;
// Check if all uploads are complete (either completed or failed)
let allComplete = true;
let hasAnyCompleted = false;
let hasAnyFailed = false;
let uploadingCount = 0;
const statuses = [];
progressItems.forEach(item => {
const statusElement = item.querySelector('.progress-status');
if (statusElement) {
const status = statusElement.textContent;
statuses.push(status);
if (status !== 'Completed' && status !== 'Failed') {
allComplete = false;
if (status === 'Uploading...') {
uploadingCount++;
}
}
if (status === 'Completed') {
hasAnyCompleted = true;
}
if (status === 'Failed') {
hasAnyFailed = true;
}
}
});
logger.debug('Upload status check:', {
totalItems: progressItems.length,
allComplete,
uploadingCount,
hasAnyCompleted,
hasAnyFailed,
statuses
});
// If all uploads are complete, finalize the results
if (allComplete) {
logger.debug('All firmware uploads complete, finalizing results');
// Generate results based on current status
const results = progressItems.map(item => {
const nodeIp = item.getAttribute('data-node-ip');
const nodeName = item.querySelector('.node-name')?.textContent || nodeIp;
const statusElement = item.querySelector('.progress-status');
const status = statusElement?.textContent || 'Unknown';
return {
nodeIp: nodeIp,
hostname: nodeName,
success: status === 'Completed',
error: status === 'Failed' ? 'Upload failed' : undefined,
timestamp: new Date().toISOString()
};
});
// Update the header and summary to show final results
this.displayUploadResults(results);
// Now that all uploads are truly complete (confirmed via websocket), mark upload as complete
this.viewModel.completeUpload();
// Reset upload state after a short delay to allow user to see results
setTimeout(() => {
this.viewModel.resetUploadState();
}, 5000);
} else if (uploadingCount > 0) {
logger.debug(`${uploadingCount} uploads still in progress, not finalizing yet`);
} else {
logger.debug('Some uploads may have unknown status, but not finalizing yet');
}
}
updateOverallProgressFromStatus() {
const progressItems = this.findAllElements('.progress-item');
if (progressItems.length <= 1) {
return; // Only update for multi-node uploads
}
let completedCount = 0;
let failedCount = 0;
let uploadingCount = 0;
progressItems.forEach(item => {
const statusElement = item.querySelector('.progress-status');
if (statusElement) {
const status = statusElement.textContent;
if (status === 'Completed') {
completedCount++;
} else if (status === 'Failed') {
failedCount++;
} else if (status === 'Uploading...') {
uploadingCount++;
}
}
});
const totalNodes = progressItems.length;
const successfulUploads = completedCount;
const successPercentage = Math.round((successfulUploads / totalNodes) * 100);
// Update overall progress bar
const progressBar = this.findElement('#overall-progress-bar');
const progressText = this.findElement('.progress-text');
if (progressBar && progressText) {
progressBar.style.width = `${successPercentage}%`;
// Update progress bar color based on completion
if (successPercentage === 100) {
progressBar.style.backgroundColor = '#4ade80';
} else if (successPercentage > 50) {
progressBar.style.backgroundColor = '#60a5fa';
} else {
progressBar.style.backgroundColor = '#fbbf24';
}
progressText.textContent = `${successfulUploads}/${totalNodes} Successful (${successPercentage}%)`;
}
// Update progress summary
const progressSummary = this.findElement('#progress-summary');
if (progressSummary) {
if (failedCount > 0) {
progressSummary.innerHTML = `<span>${window.icon('warning', { width: 14, height: 14 })} Upload in progress... (${uploadingCount} uploading, ${failedCount} failed)</span>`;
} else if (uploadingCount > 0) {
progressSummary.innerHTML = `<span>${window.icon('info', { width: 14, height: 14 })} Upload in progress... (${uploadingCount} uploading)</span>`;
} else if (completedCount === totalNodes) {
progressSummary.innerHTML = `<span>${window.icon('success', { width: 14, height: 14 })} All uploads completed successfully at ${new Date().toLocaleTimeString()}</span>`;
}
}
}
populateNodeSelect() { populateNodeSelect() {
const select = this.findElement('#specific-node-select'); const select = this.findElement('#specific-node-select');
if (!select) { if (!select) {

View File

@@ -23,6 +23,9 @@ class FirmwareUploadComponent extends Component {
if (deployBtn) { if (deployBtn) {
this.addEventListener(deployBtn, 'click', this.handleDeploy.bind(this)); this.addEventListener(deployBtn, 'click', this.handleDeploy.bind(this));
} }
// Setup WebSocket listener for real-time firmware upload status
this.setupWebSocketListeners();
} }
setupViewModelListeners() { setupViewModelListeners() {
@@ -35,6 +38,213 @@ class FirmwareUploadComponent extends Component {
this.subscribeToProperty('uploadResults', this.updateUploadResults.bind(this)); this.subscribeToProperty('uploadResults', this.updateUploadResults.bind(this));
} }
setupWebSocketListeners() {
// Listen for real-time firmware upload status updates
window.wsClient.on('firmwareUploadStatus', (data) => {
this.handleFirmwareUploadStatus(data);
});
}
handleFirmwareUploadStatus(data) {
const { nodeIp, status, filename, fileSize, timestamp } = data;
logger.debug('FirmwareUploadComponent: Firmware upload status received:', { nodeIp, status, filename });
// Check if there's currently an upload in progress
const isUploading = this.viewModel.get('isUploading');
if (!isUploading) {
logger.debug('FirmwareUploadComponent: No active upload, ignoring status update');
return;
}
// Find the target node item for this node
const targetNodeItem = this.findElement(`[data-node-ip="${nodeIp}"]`);
if (!targetNodeItem) {
logger.debug('FirmwareUploadComponent: No target node item found for node:', nodeIp);
return;
}
// Update the status display based on the received status
const statusElement = targetNodeItem.querySelector('.status-indicator');
if (statusElement) {
let displayStatus = status;
let statusClass = '';
logger.debug(`FirmwareUploadComponent: Updating status for node ${nodeIp}: ${status} -> ${displayStatus}`);
switch (status) {
case 'uploading':
displayStatus = 'Uploading...';
statusClass = 'uploading';
break;
case 'completed':
displayStatus = 'Completed';
statusClass = 'success';
logger.debug(`FirmwareUploadComponent: Node ${nodeIp} marked as completed`);
break;
case 'failed':
displayStatus = 'Failed';
statusClass = 'error';
break;
default:
displayStatus = status;
break;
}
statusElement.textContent = displayStatus;
statusElement.className = `status-indicator ${statusClass}`;
}
// Update overall progress if we have multiple nodes
this.updateOverallProgressFromStatus();
// Check if all uploads are complete and finalize results
this.checkAndFinalizeUploadResults();
}
updateOverallProgressFromStatus() {
const targetNodeItems = Array.from(this.findAllElements('.target-node-item'));
if (targetNodeItems.length <= 1) {
return; // Only update for multi-node uploads
}
let completedCount = 0;
let failedCount = 0;
let uploadingCount = 0;
targetNodeItems.forEach(item => {
const statusElement = item.querySelector('.status-indicator');
if (statusElement) {
const status = statusElement.textContent;
if (status === 'Completed') {
completedCount++;
} else if (status === 'Failed') {
failedCount++;
} else if (status === 'Uploading...') {
uploadingCount++;
}
}
});
const totalNodes = targetNodeItems.length;
const successfulUploads = completedCount;
const successPercentage = Math.round((successfulUploads / totalNodes) * 100);
// Update overall progress bar
const progressBar = this.findElement('#overall-progress-bar');
const progressText = this.findElement('.progress-text');
if (progressBar && progressText) {
progressBar.style.width = `${successPercentage}%`;
// Update progress bar color based on completion
if (successPercentage === 100) {
progressBar.style.backgroundColor = '#4ade80';
} else if (successPercentage > 50) {
progressBar.style.backgroundColor = '#60a5fa';
} else {
progressBar.style.backgroundColor = '#fbbf24';
}
progressText.textContent = `${successfulUploads}/${totalNodes} Successful (${successPercentage}%)`;
}
// Update progress summary
const progressSummary = this.findElement('#progress-summary');
if (progressSummary) {
if (failedCount > 0) {
progressSummary.innerHTML = `<span>${window.icon('warning', { width: 14, height: 14 })} Upload in progress... (${uploadingCount} uploading, ${failedCount} failed)</span>`;
} else if (uploadingCount > 0) {
progressSummary.innerHTML = `<span>${window.icon('info', { width: 14, height: 14 })} Upload in progress... (${uploadingCount} uploading)</span>`;
} else if (completedCount === totalNodes) {
progressSummary.innerHTML = `<span>${window.icon('success', { width: 14, height: 14 })} All uploads completed successfully at ${new Date().toLocaleTimeString()}</span>`;
}
}
}
checkAndFinalizeUploadResults() {
const targetNodeItems = Array.from(this.findAllElements('.target-node-item'));
if (targetNodeItems.length === 0) return;
// Check if all uploads are complete (either completed or failed)
let allComplete = true;
let hasAnyCompleted = false;
let hasAnyFailed = false;
let uploadingCount = 0;
const statuses = [];
targetNodeItems.forEach(item => {
const statusElement = item.querySelector('.status-indicator');
if (statusElement) {
const status = statusElement.textContent;
statuses.push(status);
if (status !== 'Completed' && status !== 'Failed') {
allComplete = false;
if (status === 'Uploading...') {
uploadingCount++;
}
}
if (status === 'Completed') {
hasAnyCompleted = true;
}
if (status === 'Failed') {
hasAnyFailed = true;
}
}
});
logger.debug('FirmwareUploadComponent: Upload status check:', {
totalItems: targetNodeItems.length,
allComplete,
uploadingCount,
hasAnyCompleted,
hasAnyFailed,
statuses
});
// If all uploads are complete, finalize the results
if (allComplete) {
logger.debug('FirmwareUploadComponent: All firmware uploads complete, finalizing results');
// Generate results based on current status
const results = targetNodeItems.map(item => {
const nodeIp = item.getAttribute('data-node-ip');
const nodeName = item.querySelector('.node-name')?.textContent || nodeIp;
const statusElement = item.querySelector('.status-indicator');
const status = statusElement?.textContent || 'Unknown';
return {
nodeIp: nodeIp,
hostname: nodeName,
success: status === 'Completed',
error: status === 'Failed' ? 'Upload failed' : undefined,
timestamp: new Date().toISOString()
};
});
// Update the header and summary to show final results
this.displayUploadResults(results);
// Hide the progress overlay since upload is complete
this.hideProgressOverlay();
// Now that all uploads are truly complete (confirmed via websocket), mark upload as complete
this.viewModel.completeUpload();
// Reset upload state after a short delay to allow user to see results and re-enable deploy button
setTimeout(() => {
this.viewModel.resetUploadState();
logger.debug('FirmwareUploadComponent: Upload state reset, deploy button should be re-enabled');
}, 5000);
} else if (uploadingCount > 0) {
logger.debug(`FirmwareUploadComponent: ${uploadingCount} uploads still in progress, not finalizing yet`);
} else {
logger.debug('FirmwareUploadComponent: Some uploads may have unknown status, but not finalizing yet');
}
}
mount() { mount() {
super.mount(); super.mount();
@@ -145,14 +355,13 @@ class FirmwareUploadComponent extends Component {
// Start batch upload // Start batch upload
const results = await this.performBatchUpload(file, targetNodes); const results = await this.performBatchUpload(file, targetNodes);
// Display results // NOTE: Don't display results or reset state here!
this.displayUploadResults(results); // The upload state should remain active until websocket confirms completion
// Status updates and finalization happen via websocket messages in checkAndFinalizeUploadResults()
// Reset interface after successful upload logger.debug('FirmwareUploadComponent: Firmware upload HTTP requests completed, waiting for websocket status updates');
this.viewModel.resetUploadState();
} catch (error) { } catch (error) {
logger.error('Firmware deployment failed:', error); logger.error('FirmwareUploadComponent: Firmware deployment failed:', error);
this.showConfirmationDialog({ this.showConfirmationDialog({
title: 'Deployment Failed', title: 'Deployment Failed',
message: `Deployment failed: ${error.message}`, message: `Deployment failed: ${error.message}`,
@@ -161,7 +370,7 @@ class FirmwareUploadComponent extends Component {
onConfirm: () => {}, onConfirm: () => {},
onCancel: null onCancel: null
}); });
} finally { // Only complete upload on error
this.viewModel.completeUpload(); this.viewModel.completeUpload();
this.hideProgressOverlay(); this.hideProgressOverlay();
} }
@@ -172,25 +381,27 @@ class FirmwareUploadComponent extends Component {
const totalNodes = nodes.length; const totalNodes = nodes.length;
let successfulUploads = 0; let successfulUploads = 0;
// Initialize all nodes as uploading first
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
const nodeIp = node.ip;
this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Uploading...');
}
for (let i = 0; i < nodes.length; i++) { for (let i = 0; i < nodes.length; i++) {
const node = nodes[i]; const node = nodes[i];
const nodeIp = node.ip; const nodeIp = node.ip;
try { try {
// Update progress // Upload to this node (HTTP call just initiates the upload)
this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Uploading...');
// Upload to this node
const result = await this.performSingleUpload(file, nodeIp); const result = await this.performSingleUpload(file, nodeIp);
results.push(result);
successfulUploads++;
// Update progress // Don't immediately mark as completed - wait for websocket status
this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Completed'); logger.debug(`FirmwareUploadComponent: Firmware upload initiated for node ${nodeIp}, waiting for completion status via websocket`);
this.updateOverallProgress(successfulUploads, totalNodes); results.push(result);
} catch (error) { } catch (error) {
logger.error(`Failed to upload to node ${nodeIp}:`, error); logger.error(`FirmwareUploadComponent: Failed to upload to node ${nodeIp}:`, error);
const errorResult = { const errorResult = {
nodeIp: nodeIp, nodeIp: nodeIp,
hostname: node.hostname || nodeIp, hostname: node.hostname || nodeIp,
@@ -200,9 +411,8 @@ class FirmwareUploadComponent extends Component {
}; };
results.push(errorResult); results.push(errorResult);
// Update progress // For HTTP errors, we can immediately mark as failed since the upload didn't start
this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Failed'); this.updateNodeProgress(i + 1, totalNodes, nodeIp, 'Failed');
this.updateOverallProgress(successfulUploads, totalNodes);
} }
// Small delay between uploads // Small delay between uploads
@@ -218,10 +428,16 @@ class FirmwareUploadComponent extends Component {
try { try {
const result = await window.apiClient.uploadFirmware(file, nodeIp); const result = await window.apiClient.uploadFirmware(file, nodeIp);
// IMPORTANT: This HTTP response is just an acknowledgment that the gateway received the file
// The actual firmware processing happens asynchronously on the device
// Status updates will come via WebSocket messages, NOT from this HTTP response
logger.debug(`FirmwareUploadComponent: HTTP acknowledgment received for ${nodeIp}:`, result);
logger.debug(`FirmwareUploadComponent: This does NOT mean upload is complete - waiting for WebSocket status updates`);
return { return {
nodeIp: nodeIp, nodeIp: nodeIp,
hostname: nodeIp, hostname: nodeIp,
success: true, httpAcknowledged: true, // Changed from 'success' to make it clear this is just HTTP ack
result: result, result: result,
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
}; };
@@ -260,7 +476,7 @@ class FirmwareUploadComponent extends Component {
<span class="progress-text">0/${nodes.length} Successful (0%)</span> <span class="progress-text">0/${nodes.length} Successful (0%)</span>
</div> </div>
<div class="progress-summary" id="progress-summary"> <div class="progress-summary" id="progress-summary">
<span>Status: Preparing upload...</span> <span>Status: Upload in progress...</span>
</div> </div>
</div> </div>
`; `;
@@ -283,7 +499,7 @@ class FirmwareUploadComponent extends Component {
<span class="node-ip">${node.ip}</span> <span class="node-ip">${node.ip}</span>
</div> </div>
<div class="node-status"> <div class="node-status">
<span class="status-indicator pending">Pending...</span> <span class="status-indicator uploading">Uploading...</span>
</div> </div>
</div> </div>
`).join(''); `).join('');
@@ -330,15 +546,9 @@ class FirmwareUploadComponent extends Component {
progressBar.style.backgroundColor = '#fbbf24'; progressBar.style.backgroundColor = '#fbbf24';
} }
// Update progress summary for single-node uploads // NOTE: Don't update progress summary here for single-node uploads
const progressSummary = this.findElement('#progress-summary'); // The summary should only be updated via websocket status updates
if (progressSummary && totalNodes === 1) { // This prevents premature "completed successfully" messages
if (successfulUploads === 1) {
progressSummary.innerHTML = '<span>Status: Upload completed successfully</span>';
} else if (successfulUploads === 0) {
progressSummary.innerHTML = '<span>Status: Upload failed</span>';
}
}
} }
} }
@@ -426,8 +636,6 @@ class FirmwareUploadComponent extends Component {
`; `;
} }
} }
this.updateDeployButton();
} }
updateUploadProgress() { updateUploadProgress() {

View File

@@ -296,8 +296,10 @@ class WiFiConfigComponent extends Component {
] ]
}); });
if (!response.success) { // Check if the API call was successful based on the response structure
throw new Error(response.error || 'Failed to configure WiFi'); if (!response || response.status !== 200) {
const errorMessage = response?.data?.message || response?.error || 'Failed to configure WiFi';
throw new Error(errorMessage);
} }
return response; return response;

View File

@@ -69,20 +69,11 @@
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.5rem; gap: 0.5rem;
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 12px; border-radius: 12px;
padding: 0.5rem; padding: 0.5rem;
backdrop-filter: var(--backdrop-blur);
transition: all 0.3s ease; transition: all 0.3s ease;
} }
.theme-switcher:hover {
background: var(--bg-hover);
border-color: var(--border-hover);
box-shadow: var(--shadow-secondary);
}
.theme-toggle { .theme-toggle {
background: none; background: none;
border: none; border: none;
@@ -98,9 +89,8 @@
} }
.theme-toggle:hover { .theme-toggle:hover {
background: var(--bg-hover);
color: var(--text-primary); color: var(--text-primary);
transform: scale(1.05); transform: scale(1.1);
} }
.theme-toggle:active { .theme-toggle:active {
@@ -232,16 +222,9 @@
} }
[data-theme="light"] .theme-switcher { [data-theme="light"] .theme-switcher {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(20px);
border: 1px solid rgba(148, 163, 184, 0.25);
box-shadow: 0 4px 16px rgba(148, 163, 184, 0.08);
} }
[data-theme="light"] .theme-switcher:hover { [data-theme="light"] .theme-switcher:hover {
background: rgba(255, 255, 255, 0.15);
border: 1px solid rgba(148, 163, 184, 0.35);
box-shadow: 0 6px 20px rgba(148, 163, 184, 0.12);
} }
[data-theme="light"] .view-content { [data-theme="light"] .view-content {