feat: releay ui example, simplify logging

This commit is contained in:
2025-09-16 15:32:49 +02:00
parent 2d85f560bb
commit 702eec5a13
27 changed files with 577 additions and 1106 deletions

View File

@@ -1,6 +1,6 @@
#include "RelayService.h"
#include "spore/core/ApiServer.h"
#include "spore/services/LoggingService.h"
#include "spore/util/Logging.h"
RelayService::RelayService(NodeContext& ctx, TaskManager& taskMgr, int pin)
: ctx(ctx), taskManager(taskMgr), relayPin(pin), relayOn(false) {
@@ -65,13 +65,13 @@ void RelayService::turnOn() {
relayOn = true;
// Active LOW relay
digitalWrite(relayPin, LOW);
LOG_INFO(ctx, "RelayService", "Relay ON");
LOG_INFO("RelayService", "Relay ON");
}
void RelayService::turnOff() {
relayOn = false;
digitalWrite(relayPin, HIGH);
LOG_INFO(ctx, "RelayService", "Relay OFF");
LOG_INFO("RelayService", "Relay OFF");
}
void RelayService::toggle() {
@@ -84,6 +84,6 @@ void RelayService::toggle() {
void RelayService::registerTasks() {
taskManager.registerTask("relay_status_print", 5000, [this]() {
LOG_INFO(ctx, "RelayService", "Status - pin: " + String(relayPin) + ", state: " + (relayOn ? "ON" : "OFF"));
LOG_INFO("RelayService", "Status - pin: " + String(relayPin) + ", state: " + (relayOn ? "ON" : "OFF"));
});
}

View File

@@ -0,0 +1,177 @@
// Only initialize if not already done
if (!window.relayControlInitialized) {
class RelayControl {
constructor() {
this.currentState = 'off';
this.relayPin = '';
this.init();
}
init() {
this.createComponent();
this.loadRelayStatus();
this.setupEventListeners();
// Refresh status every 2 seconds
setInterval(() => this.loadRelayStatus(), 2000);
}
createComponent() {
// Create the main container
const container = document.createElement('div');
container.className = 'relay-component';
container.innerHTML = `
<h1>🔌 Relay Control</h1>
<div class="relay-status">
<div class="status-indicator off" id="statusIndicator">
OFF
</div>
<div class="status-text" id="statusText">Relay is OFF</div>
<div class="pin-info" id="pinInfo">Pin: Loading...</div>
</div>
<div class="controls">
<button class="btn btn-success" id="turnOnBtn">
Turn ON
</button>
<button class="btn btn-danger" id="turnOffBtn">
Turn OFF
</button>
<button class="btn btn-primary" id="toggleBtn">
Toggle
</button>
</div>
<div id="message"></div>
<div class="uptime" id="uptime"></div>
`;
// Append to component div
const componentDiv = document.getElementById('component');
if (componentDiv) {
componentDiv.appendChild(container);
} else {
// Fallback to body if component div not found
document.body.appendChild(container);
}
}
setupEventListeners() {
document.getElementById('turnOnBtn').addEventListener('click', () => this.controlRelay('on'));
document.getElementById('turnOffBtn').addEventListener('click', () => this.controlRelay('off'));
document.getElementById('toggleBtn').addEventListener('click', () => this.controlRelay('toggle'));
}
// Load initial relay status
async loadRelayStatus() {
try {
const response = await fetch('/api/relay/status');
if (!response.ok) {
throw new Error('Failed to fetch relay status');
}
const data = await response.json();
this.currentState = data.state;
this.relayPin = data.pin;
this.updateUI();
this.updateUptime(data.uptime);
} catch (error) {
console.error('Error loading relay status:', error);
this.showMessage('Error loading relay status: ' + error.message, 'error');
}
}
// Control relay
async controlRelay(action) {
const buttons = document.querySelectorAll('.btn');
buttons.forEach(btn => btn.classList.add('loading'));
try {
const response = await fetch('/api/relay', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `state=${action}`
});
const data = await response.json();
if (data.success) {
this.currentState = data.state;
this.updateUI();
this.showMessage(`Relay turned ${data.state.toUpperCase()}`, 'success');
} else {
this.showMessage(data.message || 'Failed to control relay', 'error');
}
} catch (error) {
console.error('Error controlling relay:', error);
this.showMessage('Error controlling relay: ' + error.message, 'error');
} finally {
buttons.forEach(btn => btn.classList.remove('loading'));
}
}
// Update UI based on current state
updateUI() {
const statusIndicator = document.getElementById('statusIndicator');
const statusText = document.getElementById('statusText');
const pinInfo = document.getElementById('pinInfo');
if (this.currentState === 'on') {
statusIndicator.className = 'status-indicator on';
statusIndicator.textContent = 'ON';
statusText.textContent = 'Relay is ON';
} else {
statusIndicator.className = 'status-indicator off';
statusIndicator.textContent = 'OFF';
statusText.textContent = 'Relay is OFF';
}
if (this.relayPin) {
pinInfo.textContent = `Pin: ${this.relayPin}`;
}
}
// Update uptime display
updateUptime(uptime) {
const uptimeElement = document.getElementById('uptime');
if (uptime) {
const seconds = Math.floor(uptime / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
let uptimeText = `Uptime: ${seconds}s`;
if (hours > 0) {
uptimeText = `Uptime: ${hours}h ${minutes % 60}m ${seconds % 60}s`;
} else if (minutes > 0) {
uptimeText = `Uptime: ${minutes}m ${seconds % 60}s`;
}
uptimeElement.textContent = uptimeText;
}
}
// Show message to user
showMessage(message, type) {
const messageElement = document.getElementById('message');
messageElement.textContent = message;
messageElement.className = type;
// Clear message after 3 seconds
setTimeout(() => {
messageElement.textContent = '';
messageElement.className = '';
}, 3000);
}
}
// Initialize the relay control when the page loads
document.addEventListener('DOMContentLoaded', () => {
new RelayControl();
});
window.relayControlInitialized = true;
}

View File

@@ -0,0 +1,141 @@
.relay-component {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 20px;
padding: 40px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
text-align: center;
max-width: 400px;
width: 100%;
color: white;
box-sizing: border-box;
}
.relay-component h1 {
margin: 0 0 30px 0;
font-size: 2.2em;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
.relay-component .relay-status {
margin-bottom: 30px;
}
.relay-component .status-indicator {
width: 120px;
height: 120px;
border-radius: 50%;
margin: 0 auto 20px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.2em;
font-weight: bold;
transition: all 0.3s ease;
border: 4px solid rgba(255, 255, 255, 0.3);
}
.relay-component .status-indicator.off {
background: rgba(255, 0, 0, 0.3);
color: #ff6b6b;
}
.relay-component .status-indicator.on {
background: rgba(0, 255, 0, 0.3);
color: #51cf66;
box-shadow: 0 0 20px rgba(81, 207, 102, 0.5);
}
.relay-component .status-text {
font-size: 1.5em;
margin-bottom: 10px;
}
.relay-component .pin-info {
font-size: 0.9em;
opacity: 0.8;
}
.relay-component .controls {
display: flex;
gap: 15px;
justify-content: center;
flex-wrap: wrap;
}
.relay-component .btn {
padding: 12px 24px;
border: none;
border-radius: 25px;
font-size: 1em;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
min-width: 100px;
text-transform: uppercase;
letter-spacing: 1px;
}
.relay-component .btn-primary {
background: rgba(255, 255, 255, 0.2);
color: #333;
border: 2px solid rgba(0, 0, 0, 0.8);
font-weight: bold;
}
.relay-component .btn-primary:hover {
background: rgba(255, 255, 255, 0.4);
color: #222;
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}
.relay-component .btn-primary:active {
transform: translateY(0);
}
.relay-component .btn-success {
background: rgba(81, 207, 102, 0.8);
color: white;
border: 2px solid rgba(81, 207, 102, 1);
}
.relay-component .btn-success:hover {
background: rgba(81, 207, 102, 1);
transform: translateY(-2px);
}
.relay-component .btn-danger {
background: rgba(255, 107, 107, 0.8);
color: white;
border: 2px solid rgba(255, 107, 107, 1);
}
.relay-component .btn-danger:hover {
background: rgba(255, 107, 107, 1);
transform: translateY(-2px);
}
.relay-component .loading {
opacity: 0.6;
pointer-events: none;
}
.relay-component .error {
color: #ff6b6b;
margin-top: 15px;
font-size: 0.9em;
}
.relay-component .success {
color: #51cf66;
margin-top: 15px;
font-size: 0.9em;
}
.relay-component .uptime {
margin-top: 20px;
font-size: 0.8em;
opacity: 0.7;
}

View File

@@ -1,6 +1,5 @@
#include <Arduino.h>
#include "spore/Spore.h"
#include "spore/services/LoggingService.h"
#include "RelayService.h"
// Choose a default relay pin. For ESP-01 this is GPIO0. Adjust as needed for your board.
@@ -29,8 +28,8 @@ void setup() {
// Start the API server and complete initialization
spore.begin();
LOG_INFO(spore.getContext(), "Main", "Relay service registered and ready!");
LOG_INFO(spore.getContext(), "Main", "Web interface available at http://<node-ip>/relay.html");
LOG_INFO("Main", "Relay service registered and ready!");
LOG_INFO("Main", "Web interface available at http://<node-ip>/relay.html");
}
void loop() {