import { NextRequest, NextResponse } from 'next/server'; import { BedHardware, PinState, PinChange } from '@/services/BedHardware'; // Complete sensor configuration with positions and pin mappings 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 }, // 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 }, // 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 }, // 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 }, // 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 }, // 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 }, // 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 }, ]; // Create pin mapping from sensor config const PIN_SENSOR_MAP: Record = {}; SENSOR_CONFIG.forEach(sensor => { if (sensor.pin) { PIN_SENSOR_MAP[sensor.pin] = sensor; } }); let bedHardware: BedHardware | null = null; const sensorData: Record; status: string; }> = {}; let isHardwareConnected = false; // Initialize all sensor data function initializeSensorData() { SENSOR_CONFIG.forEach(sensor => { if (!sensorData[sensor.id]) { sensorData[sensor.id] = { id: sensor.id, x: sensor.x, y: sensor.y, label: sensor.label, zone: sensor.zone, pressure: 30 + Math.random() * 20, // Start with baseline pressure pin: sensor.pin, timestamp: new Date().toISOString(), source: sensor.pin ? 'hardware' : 'mock', data: generateTimeSeriesData(), status: 'normal' }; } }); } // Generate time series data for a sensor function generateTimeSeriesData(hours = 1) { const data = []; const now = new Date(); for (let i = hours * 60; i >= 0; i -= 5) { const time = new Date(now.getTime() - i * 60 * 1000); data.push({ time: time.toLocaleTimeString("en-US", { hour12: false }), timestamp: time.getTime(), pressure: Math.random() * 100 + Math.sin(i / 60) * 20 + 40, }); } return data; } // Initialize hardware connection async function initializeHardware() { if (bedHardware && isHardwareConnected) return; try { // Try to find available serial ports const availablePorts = await BedHardware.listPorts(); const portPath = availablePorts.find(port => port.includes('ttyUSB') || port.includes('ttyACM') || port.includes('cu.usbmodem') ) || '/dev/ttyUSB0'; // Default fallback bedHardware = new BedHardware(portPath, 9600); bedHardware.on('connected', () => { console.log('BedHardware connected'); isHardwareConnected = true; }); bedHardware.on('disconnected', () => { console.log('BedHardware disconnected'); isHardwareConnected = false; }); bedHardware.on('pinChanged', (change: PinChange) => { updateSensorFromPin(change.pin, change.currentState); }); bedHardware.on('pinInitialized', (pinState: PinState) => { updateSensorFromPin(pinState.pin, pinState.state); }); bedHardware.on('error', (error) => { console.error('BedHardware error:', error); isHardwareConnected = false; }); await bedHardware.connect(); } catch (error) { console.warn('Failed to connect to hardware, using mock data:', error); isHardwareConnected = false; } } // 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 // Add realistic noise and variation const timeNoise = Math.sin(Date.now() / 10000) * 10; // Slow oscillation const randomNoise = (Math.random() - 0.5) * baseNoise; const sensorDrift = (Math.random() - 0.5) * 5; // Small drift const pressure = basePressure + timeNoise + randomNoise + sensorDrift; // Clamp between 0 and 100 return Math.max(0, Math.min(100, pressure)); } // Update sensor data from pin change function updateSensorFromPin(pin: number, state: number) { const mapping = PIN_SENSOR_MAP[pin]; if (!mapping) return; const pressure = digitalToPressure(state, mapping.baseNoise); if (sensorData[mapping.id]) { // Update existing sensor data const currentData = sensorData[mapping.id]; sensorData[mapping.id] = { ...currentData, pressure, 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, } ], status: pressure > 80 ? 'critical' : pressure > 60 ? 'warning' : 'normal' }; } } // Update mock sensor data with variation function updateMockSensorData() { SENSOR_CONFIG.forEach(sensor => { 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)); sensorData[sensor.id] = { ...currentSensor, pressure: newPressure, 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, } ], status: newPressure > 80 ? 'critical' : newPressure > 60 ? 'warning' : 'normal' }; } }); } export async function GET() { try { // Initialize sensor data if not already done if (Object.keys(sensorData).length === 0) { initializeSensorData(); } // Initialize hardware if not already done if (!bedHardware) { await initializeHardware(); } // Update mock sensor data updateMockSensorData(); // If hardware is connected, get current pin states if (isHardwareConnected && bedHardware) { const pinStates = bedHardware.getAllPinStates(); pinStates.forEach(pinState => { updateSensorFromPin(pinState.pin, pinState.state); }); } // Return all sensor data return NextResponse.json({ success: true, connected: isHardwareConnected, sensors: Object.values(sensorData), timestamp: new Date().toISOString() }); } catch (error) { console.error('Sensor API error:', error); return NextResponse.json({ success: false, error: 'Failed to get sensor data', connected: false, sensors: [], timestamp: new Date().toISOString() }, { status: 500 }); } } export async function POST(request: NextRequest) { try { const body = await request.json(); if (body.action === 'connect') { await initializeHardware(); return NextResponse.json({ success: true, connected: isHardwareConnected, message: isHardwareConnected ? 'Hardware connected' : 'Using mock data' }); } if (body.action === 'disconnect') { if (bedHardware) { await bedHardware.disconnect(); bedHardware = null; isHardwareConnected = false; } return NextResponse.json({ success: true, connected: false, message: 'Hardware disconnected' }); } return NextResponse.json({ success: false, error: 'Invalid action' }, { status: 400 }); } catch (error) { console.error('Sensor API POST error:', error); return NextResponse.json({ success: false, error: 'Failed to process request' }, { status: 500 }); } }