initial commit

This commit is contained in:
Siwat Sirichai 2025-06-21 12:09:47 +07:00
commit a606796d9e
26 changed files with 2606 additions and 0 deletions

View file

@ -0,0 +1,52 @@
import { NextResponse } from 'next/server';
// Sensor configuration that matches the API route
const SENSOR_CONFIG = [
// Head area
{ id: "head-1", x: 45, y: 15, zone: "head", label: "Head Left", pin: 2 },
{ id: "head-2", x: 55, y: 15, zone: "head", label: "Head Right", pin: 3 },
// Shoulder area
{ id: "shoulder-1", x: 35, y: 25, zone: "shoulders", label: "Left Shoulder", pin: 4 },
{ id: "shoulder-2", x: 65, y: 25, zone: "shoulders", label: "Right Shoulder", pin: 5 },
// Upper back
{ id: "back-1", x: 40, y: 35, zone: "back", label: "Upper Back Left", pin: 6 },
{ id: "back-2", x: 50, y: 35, zone: "back", label: "Upper Back Center", pin: 7 },
{ id: "back-3", x: 60, y: 35, zone: "back", label: "Upper Back Right", pin: 8 },
// Lower back/Hip area
{ id: "hip-1", x: 35, y: 50, zone: "hips", label: "Left Hip", pin: 9 },
{ id: "hip-2", x: 50, y: 50, zone: "hips", label: "Lower Back", pin: 10 },
{ id: "hip-3", x: 65, y: 50, zone: "hips", label: "Right Hip", pin: 11 },
// Thigh area
{ id: "thigh-1", x: 40, y: 65, zone: "legs", label: "Left Thigh", pin: 12 },
{ id: "thigh-2", x: 60, y: 65, zone: "legs", label: "Right Thigh", pin: 13 },
// Calf area (mock data)
{ id: "calf-1", x: 40, y: 75, zone: "legs", label: "Left Calf" },
{ id: "calf-2", x: 60, y: 75, zone: "legs", label: "Right Calf" },
// Feet (mock data)
{ id: "feet-1", x: 45, y: 85, zone: "feet", label: "Left Foot" },
{ id: "feet-2", x: 55, y: 85, zone: "feet", label: "Right Foot" },
];
export async function GET() {
try {
return NextResponse.json({
success: true,
sensors: SENSOR_CONFIG,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('Sensor config API error:', error);
return NextResponse.json({
success: false,
error: 'Failed to get sensor configuration',
sensors: [],
timestamp: new Date().toISOString()
}, { status: 500 });
}
}

295
app/api/sensors/route.ts Normal file
View file

@ -0,0 +1,295 @@
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<number, typeof SENSOR_CONFIG[0]> = {};
SENSOR_CONFIG.forEach(sensor => {
if (sensor.pin) {
PIN_SENSOR_MAP[sensor.pin] = sensor;
}
});
let bedHardware: BedHardware | null = null;
const sensorData: Record<string, {
id: string;
x: number;
y: number;
label: string;
zone: string;
pressure: number;
pin?: number;
digitalState?: number;
timestamp: string;
source: 'hardware' | 'mock';
data: Array<{ time: string; timestamp: number; pressure: number }>;
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 });
}
}

BIN
app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

122
app/globals.css Normal file
View file

@ -0,0 +1,122 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}

34
app/layout.tsx Normal file
View file

@ -0,0 +1,34 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
);
}

7
app/page.tsx Normal file
View file

@ -0,0 +1,7 @@
"use client"
import Component from "@/components/bed-pressure-monitor"
export default function Page() {
return <Component />
}