dynamic graph

This commit is contained in:
Siwat Sirichai 2025-06-21 12:55:27 +07:00
parent a606796d9e
commit 5e029ff99c
17 changed files with 1707 additions and 569 deletions

View file

@ -0,0 +1,38 @@
import { NextRequest, NextResponse } from 'next/server';
import { SensorDataStorage } from '@/services/SensorDataStorage';
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const sensorId = searchParams.get('sensorId');
const timespan = parseInt(searchParams.get('timespan') || '86400000'); // Default 24 hours in ms
if (!sensorId) {
return NextResponse.json({
success: false,
error: 'sensorId parameter is required'
}, { status: 400 });
}
const sensorDataStorage = SensorDataStorage.getInstance();
const sensorData = await sensorDataStorage.getDataForSensor(sensorId, timespan);
const timeSeriesData = sensorDataStorage.generateTimeSeriesData(sensorData, timespan);
return NextResponse.json({
success: true,
sensorId,
timespan,
dataPoints: sensorData.length,
data: timeSeriesData,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('Sensor history API error:', error);
return NextResponse.json({
success: false,
error: 'Failed to get sensor history data'
}, { status: 500 });
}
}

View file

@ -1,37 +1,38 @@
import { NextRequest, NextResponse } from 'next/server';
import { BedHardware, PinState, PinChange } from '@/services/BedHardware';
import { SensorDataStorage, SensorDataPoint } from '@/services/SensorDataStorage';
// Complete sensor configuration with positions and pin mappings
// Complete sensor configuration with positions, pin mappings, and thresholds
const SENSOR_CONFIG = [
// Head area
{ id: "head-1", x: 45, y: 15, zone: "head", label: "Head Left", pin: 2, baseNoise: 15 },
{ id: "head-2", x: 55, y: 15, zone: "head", label: "Head Right", pin: 3, baseNoise: 12 },
{ id: "head-1", x: 45, y: 15, zone: "head", label: "Head Left", pin: 2, baseNoise: 200, warningThreshold: 3000, alarmThreshold: 3500, warningDelayMs: 30000 },
{ id: "head-2", x: 55, y: 15, zone: "head", label: "Head Right", pin: 3, baseNoise: 150, warningThreshold: 3000, alarmThreshold: 3500, warningDelayMs: 30000 },
// Shoulder area
{ id: "shoulder-1", x: 35, y: 25, zone: "shoulders", label: "Left Shoulder", pin: 4, baseNoise: 20 },
{ id: "shoulder-2", x: 65, y: 25, zone: "shoulders", label: "Right Shoulder", pin: 5, baseNoise: 18 },
{ id: "shoulder-1", x: 35, y: 25, zone: "shoulders", label: "Left Shoulder", pin: 4, baseNoise: 250, warningThreshold: 2800, alarmThreshold: 3200, warningDelayMs: 45000 },
{ id: "shoulder-2", x: 65, y: 25, zone: "shoulders", label: "Right Shoulder", pin: 5, baseNoise: 220, warningThreshold: 2800, alarmThreshold: 3200, warningDelayMs: 45000 },
// Upper back
{ id: "back-1", x: 40, y: 35, zone: "back", label: "Upper Back Left", pin: 6, baseNoise: 25 },
{ id: "back-2", x: 50, y: 35, zone: "back", label: "Upper Back Center", pin: 7, baseNoise: 30 },
{ id: "back-3", x: 60, y: 35, zone: "back", label: "Upper Back Right", pin: 8, baseNoise: 22 },
{ id: "back-1", x: 40, y: 35, zone: "back", label: "Upper Back Left", pin: 6, baseNoise: 300, warningThreshold: 2500, alarmThreshold: 3000, warningDelayMs: 60000 },
{ id: "back-2", x: 50, y: 35, zone: "back", label: "Upper Back Center", pin: 7, baseNoise: 350, warningThreshold: 2500, alarmThreshold: 3000, warningDelayMs: 60000 },
{ id: "back-3", x: 60, y: 35, zone: "back", label: "Upper Back Right", pin: 8, baseNoise: 280, warningThreshold: 2500, alarmThreshold: 3000, warningDelayMs: 60000 },
// Lower back/Hip area
{ id: "hip-1", x: 35, y: 50, zone: "hips", label: "Left Hip", pin: 9, baseNoise: 35 },
{ id: "hip-2", x: 50, y: 50, zone: "hips", label: "Lower Back", pin: 10, baseNoise: 40 },
{ id: "hip-3", x: 65, y: 50, zone: "hips", label: "Right Hip", pin: 11, baseNoise: 32 },
{ id: "hip-1", x: 35, y: 50, zone: "hips", label: "Left Hip", pin: 9, baseNoise: 400, warningThreshold: 2200, alarmThreshold: 2800, warningDelayMs: 90000 },
{ id: "hip-2", x: 50, y: 50, zone: "hips", label: "Lower Back", pin: 10, baseNoise: 450, warningThreshold: 2200, alarmThreshold: 2800, warningDelayMs: 90000 },
{ id: "hip-3", x: 65, y: 50, zone: "hips", label: "Right Hip", pin: 11, baseNoise: 380, warningThreshold: 2200, alarmThreshold: 2800, warningDelayMs: 90000 },
// Thigh area
{ id: "thigh-1", x: 40, y: 65, zone: "legs", label: "Left Thigh", pin: 12, baseNoise: 28 },
{ id: "thigh-2", x: 60, y: 65, zone: "legs", label: "Right Thigh", pin: 13, baseNoise: 26 },
{ id: "thigh-1", x: 40, y: 65, zone: "legs", label: "Left Thigh", pin: 12, baseNoise: 320, warningThreshold: 2000, alarmThreshold: 2500, warningDelayMs: 120000 },
{ id: "thigh-2", x: 60, y: 65, zone: "legs", label: "Right Thigh", pin: 13, baseNoise: 300, warningThreshold: 2000, alarmThreshold: 2500, warningDelayMs: 120000 },
// Calf area (mock data)
{ id: "calf-1", x: 40, y: 75, zone: "legs", label: "Left Calf", baseNoise: 15 },
{ id: "calf-2", x: 60, y: 75, zone: "legs", label: "Right Calf", baseNoise: 18 },
{ id: "calf-1", x: 40, y: 75, zone: "legs", label: "Left Calf", baseNoise: 200, warningThreshold: 1800, alarmThreshold: 2200, warningDelayMs: 150000 },
{ id: "calf-2", x: 60, y: 75, zone: "legs", label: "Right Calf", baseNoise: 220, warningThreshold: 1800, alarmThreshold: 2200, warningDelayMs: 150000 },
// Feet (mock data)
{ id: "feet-1", x: 45, y: 85, zone: "feet", label: "Left Foot", baseNoise: 10 },
{ id: "feet-2", x: 55, y: 85, zone: "feet", label: "Right Foot", baseNoise: 12 },
{ id: "feet-1", x: 45, y: 85, zone: "feet", label: "Left Foot", baseNoise: 150, warningThreshold: 1500, alarmThreshold: 1800, warningDelayMs: 180000 },
{ id: "feet-2", x: 55, y: 85, zone: "feet", label: "Right Foot", baseNoise: 160, warningThreshold: 1500, alarmThreshold: 1800, warningDelayMs: 180000 },
];
// Create pin mapping from sensor config
@ -43,19 +44,24 @@ SENSOR_CONFIG.forEach(sensor => {
});
let bedHardware: BedHardware | null = null;
const sensorDataStorage = SensorDataStorage.getInstance();
const sensorData: Record<string, {
id: string;
x: number;
y: number;
label: string;
zone: string;
pressure: number;
value: number; // Changed from pressure to value (0-4095)
pin?: number;
digitalState?: number;
timestamp: string;
source: 'hardware' | 'mock';
data: Array<{ time: string; timestamp: number; pressure: number }>;
data: Array<{ time: string; timestamp: number; value: number }>;
status: string;
warningStartTime?: number; // Track when warning state started
warningThreshold: number;
alarmThreshold: number;
warningDelayMs: number;
}> = {};
let isHardwareConnected = false;
@ -69,12 +75,15 @@ function initializeSensorData() {
y: sensor.y,
label: sensor.label,
zone: sensor.zone,
pressure: 30 + Math.random() * 20, // Start with baseline pressure
value: 1000 + Math.random() * 500, // Start with baseline analog value (1000-1500)
pin: sensor.pin,
timestamp: new Date().toISOString(),
source: sensor.pin ? 'hardware' : 'mock',
data: generateTimeSeriesData(),
status: 'normal'
status: 'normal',
warningThreshold: sensor.warningThreshold,
alarmThreshold: sensor.alarmThreshold,
warningDelayMs: sensor.warningDelayMs
};
}
});
@ -90,7 +99,7 @@ function generateTimeSeriesData(hours = 1) {
data.push({
time: time.toLocaleTimeString("en-US", { hour12: false }),
timestamp: time.getTime(),
pressure: Math.random() * 100 + Math.sin(i / 60) * 20 + 40,
value: Math.floor(Math.random() * 4096 + Math.sin(i / 60) * 500 + 2000), // 0-4095 range
});
}
return data;
@ -139,47 +148,81 @@ async function initializeHardware() {
}
}
// Convert digital pin state to analog pressure value with noise
function digitalToPressure(pinState: number, baseNoise: number): number {
// Base pressure from digital state
const basePressure = pinState === 1 ? 60 : 20; // High when pin is HIGH, low when LOW
// Convert digital pin state to analog value with noise
function digitalToAnalogValue(pinState: number, baseNoise: number): number {
// Base value from digital state
const baseValue = pinState === 1 ? 3000 : 1000; // High when pin is HIGH, low when LOW
// Add realistic noise and variation
const timeNoise = Math.sin(Date.now() / 10000) * 10; // Slow oscillation
const timeNoise = Math.sin(Date.now() / 10000) * 200; // Slow oscillation
const randomNoise = (Math.random() - 0.5) * baseNoise;
const sensorDrift = (Math.random() - 0.5) * 5; // Small drift
const sensorDrift = (Math.random() - 0.5) * 50; // Small drift
const pressure = basePressure + timeNoise + randomNoise + sensorDrift;
const value = baseValue + timeNoise + randomNoise + sensorDrift;
// Clamp between 0 and 100
return Math.max(0, Math.min(100, pressure));
// Clamp between 0 and 4095
return Math.max(0, Math.min(4095, Math.floor(value)));
}
// Update sensor data from pin change
function updateSensorFromPin(pin: number, state: number) {
async function updateSensorFromPin(pin: number, state: number) {
const mapping = PIN_SENSOR_MAP[pin];
if (!mapping) return;
const pressure = digitalToPressure(state, mapping.baseNoise);
const value = digitalToAnalogValue(state, mapping.baseNoise);
const timestamp = Date.now();
const time = new Date(timestamp).toLocaleTimeString("en-US", { hour12: false });
// Save to persistent storage
const dataPoint: SensorDataPoint = {
sensorId: mapping.id,
value,
timestamp,
time,
source: 'hardware',
pin,
digitalState: state
};
await sensorDataStorage.addDataPoint(dataPoint);
if (sensorData[mapping.id]) {
// Update existing sensor data
const currentData = sensorData[mapping.id];
// Determine status based on thresholds
let status = 'normal';
let warningStartTime = currentData.warningStartTime;
if (value >= mapping.alarmThreshold) {
status = 'alarm';
warningStartTime = undefined; // Clear warning timer for immediate alarm
} else if (value >= mapping.warningThreshold) {
status = 'warning';
if (!warningStartTime) {
warningStartTime = timestamp; // Start warning timer
} else if (timestamp - warningStartTime >= mapping.warningDelayMs) {
status = 'alarm'; // Escalate to alarm after delay
}
} else {
warningStartTime = undefined; // Clear warning timer
}
sensorData[mapping.id] = {
...currentData,
pressure,
value,
digitalState: state,
timestamp: new Date().toISOString(),
source: 'hardware',
data: [
...currentData.data.slice(-287), // Keep last ~24 hours (288 points at 5min intervals)
{
time: new Date().toLocaleTimeString("en-US", { hour12: false }),
timestamp: Date.now(),
pressure: pressure,
time,
timestamp,
value: value,
}
],
status: pressure > 80 ? 'critical' : pressure > 60 ? 'warning' : 'normal'
status,
warningStartTime
};
}
}
@ -190,22 +233,23 @@ function updateMockSensorData() {
if (!sensor.pin && sensorData[sensor.id]) {
// This is a mock sensor, update with variation
const currentSensor = sensorData[sensor.id];
const variation = (Math.random() - 0.5) * 10;
const newPressure = Math.max(0, Math.min(100, currentSensor.pressure + variation));
const variation = (Math.random() - 0.5) * 200; // Larger variation for analog values
const newValue = Math.max(0, Math.min(4095, currentSensor.value + variation));
sensorData[sensor.id] = {
...currentSensor,
pressure: newPressure,
value: newValue,
timestamp: new Date().toISOString(),
data: [
...currentSensor.data.slice(-287), // Keep last ~24 hours
{
time: new Date().toLocaleTimeString("en-US", { hour12: false }),
timestamp: Date.now(),
pressure: newPressure,
value: newValue,
}
],
status: newPressure > 80 ? 'critical' : newPressure > 60 ? 'warning' : 'normal'
status: newValue >= sensor.alarmThreshold ? 'alarm' :
newValue >= sensor.warningThreshold ? 'warning' : 'normal'
};
}
});
@ -229,9 +273,9 @@ export async function GET() {
// If hardware is connected, get current pin states
if (isHardwareConnected && bedHardware) {
const pinStates = bedHardware.getAllPinStates();
pinStates.forEach(pinState => {
updateSensorFromPin(pinState.pin, pinState.state);
});
for (const pinState of pinStates) {
await updateSensorFromPin(pinState.pin, pinState.state);
}
}
// Return all sensor data