initial commit

This commit is contained in:
2025-11-25 20:14:41 +09:00
commit 5cb1ff372c
559 changed files with 149800 additions and 0 deletions

24
FrontEnd/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

224
FrontEnd/App.tsx Normal file
View File

@@ -0,0 +1,224 @@
import React, { useState, useEffect, useRef } from 'react';
import { HashRouter, Routes, Route } from 'react-router-dom';
import { Layout } from './components/layout/Layout';
import { HomePage } from './pages/HomePage';
import { IOMonitorPage } from './pages/IOMonitorPage';
import { RecipePage } from './pages/RecipePage';
import { SystemState, Recipe, IOPoint, LogEntry, RobotTarget, ConfigItem } from './types';
import { comms } from './communication';
// --- MOCK DATA ---
const INITIAL_IO: IOPoint[] = [
...Array.from({ length: 32 }, (_, i) => {
let name = `DOUT_${i.toString().padStart(2, '0')}`;
if (i === 0) name = "Tower Lamp Red";
if (i === 1) name = "Tower Lamp Yel";
if (i === 2) name = "Tower Lamp Grn";
return { id: i, name, type: 'output' as const, state: false };
}),
...Array.from({ length: 32 }, (_, i) => {
let name = `DIN_${i.toString().padStart(2, '0')}`;
let initialState = false;
if (i === 0) name = "Front Door Sensor";
if (i === 1) name = "Right Door Sensor";
if (i === 2) name = "Left Door Sensor";
if (i === 3) name = "Back Door Sensor";
if (i === 4) { name = "Main Air Pressure"; initialState = true; }
if (i === 5) { name = "Vacuum Generator"; initialState = true; }
if (i === 6) { name = "Emergency Stop Loop"; initialState = true; }
return { id: i, name, type: 'input' as const, state: initialState };
})
];
// --- MAIN APP ---
export default function App() {
const [activeTab, setActiveTab] = useState<'recipe' | 'motion' | 'camera' | 'setting' | 'initialize' | null>(null);
const [systemState, setSystemState] = useState<SystemState>(SystemState.IDLE);
const [currentRecipe, setCurrentRecipe] = useState<Recipe>({ id: '0', name: 'No Recipe', lastModified: '-' });
const [robotTarget, setRobotTarget] = useState<RobotTarget>({ x: 0, y: 0, z: 0 });
const [logs, setLogs] = useState<LogEntry[]>([]);
const [ioPoints, setIoPoints] = useState<IOPoint[]>([]);
const [currentTime, setCurrentTime] = useState(new Date());
const [isLoading, setIsLoading] = useState(true);
const [isHostConnected, setIsHostConnected] = useState(false);
const videoRef = useRef<HTMLVideoElement>(null);
// -- COMMUNICATION LAYER --
useEffect(() => {
const unsubscribe = comms.subscribe((msg: any) => {
if (!msg) return;
if (msg.type === 'CONNECTION_STATE') {
setIsHostConnected(msg.connected);
addLog(msg.connected ? "HOST CONNECTED" : "HOST DISCONNECTED", msg.connected ? "info" : "warning");
}
if (msg.type === 'STATUS_UPDATE') {
if (msg.position) {
setRobotTarget({ x: msg.position.x, y: msg.position.y, z: msg.position.z });
}
if (msg.ioState) {
setIoPoints(prev => {
const newIO = [...prev];
msg.ioState.forEach((update: { id: number, type: string, state: boolean }) => {
const idx = newIO.findIndex(p => p.id === update.id && p.type === update.type);
if (idx >= 0) newIO[idx] = { ...newIO[idx], state: update.state };
});
return newIO;
});
}
if (msg.sysState) {
setSystemState(msg.sysState as SystemState);
}
}
});
addLog("COMMUNICATION CHANNEL OPEN", "info");
setIsHostConnected(comms.getConnectionState());
const timer = setInterval(() => setCurrentTime(new Date()), 1000);
return () => {
clearInterval(timer);
unsubscribe();
};
}, []);
// -- INITIALIZATION --
useEffect(() => {
const initSystem = async () => {
addLog("SYSTEM STARTED", "info");
// Initial IO data will be loaded by HomePage when it mounts
try {
const ioStr = await comms.getIOList();
const ioData = JSON.parse(ioStr);
setIoPoints(ioData);
addLog("IO LIST LOADED", "info");
} catch (e) {
addLog("FAILED TO LOAD IO DATA", "error");
}
setIsLoading(false);
};
initSystem();
}, []);
const addLog = (msg: string, type: 'info' | 'warning' | 'error' = 'info') => {
setLogs(prev => [{ id: Date.now() + Math.random(), timestamp: new Date().toLocaleTimeString(), message: msg, type }, ...prev].slice(0, 50));
};
// Logic Helpers
const doorStates = {
front: ioPoints.find(p => p.id === 0 && p.type === 'input')?.state || false,
right: ioPoints.find(p => p.id === 1 && p.type === 'input')?.state || false,
left: ioPoints.find(p => p.id === 2 && p.type === 'input')?.state || false,
back: ioPoints.find(p => p.id === 3 && p.type === 'input')?.state || false,
};
const isLowPressure = !(ioPoints.find(p => p.id === 4 && p.type === 'input')?.state ?? true);
const isEmergencyStop = !(ioPoints.find(p => p.id === 6 && p.type === 'input')?.state ?? true);
// -- COMMAND HANDLERS --
const handleControl = async (action: 'start' | 'stop' | 'reset') => {
if (isEmergencyStop && action === 'start') return addLog('EMERGENCY STOP ACTIVE', 'error');
try {
await comms.sendControl(action.toUpperCase());
addLog(`CMD SENT: ${action.toUpperCase()}`, 'info');
} catch (e) {
addLog('COMM ERROR', 'error');
}
};
const toggleIO = async (id: number, type: 'input' | 'output', forceState?: boolean) => {
if (type === 'output') {
const current = ioPoints.find(p => p.id === id && p.type === type)?.state;
const nextState = forceState !== undefined ? forceState : !current;
await comms.setIO(id, nextState);
}
};
const moveAxis = async (axis: 'X' | 'Y' | 'Z', value: number) => {
if (isEmergencyStop) return;
await comms.moveAxis(axis, value);
addLog(`CMD MOVE ${axis}: ${value}`, 'info');
};
const handleSaveConfig = async (newConfig: ConfigItem[]) => {
try {
await comms.saveConfig(JSON.stringify(newConfig));
addLog("CONFIGURATION SAVED", "info");
} catch (e) {
console.error(e);
addLog("FAILED TO SAVE CONFIG", "error");
}
};
const handleSelectRecipe = async (r: Recipe) => {
try {
addLog(`LOADING: ${r.name}`, 'info');
const result = await comms.selectRecipe(r.id);
if (result.success) {
setCurrentRecipe(r);
addLog(`RECIPE LOADED: ${r.name}`, 'info');
} else {
addLog(`RECIPE LOAD FAILED: ${result.message}`, 'error');
}
} catch (error: any) {
addLog(`RECIPE LOAD ERROR: ${error.message || 'Unknown error'}`, 'error');
console.error('Recipe selection error:', error);
}
};
return (
<HashRouter>
<Layout
currentTime={currentTime}
isHostConnected={isHostConnected}
robotTarget={robotTarget}
onTabChange={setActiveTab}
activeTab={activeTab}
isLoading={isLoading}
>
<Routes>
<Route
path="/"
element={
<HomePage
systemState={systemState}
currentRecipe={currentRecipe}
robotTarget={robotTarget}
logs={logs}
ioPoints={ioPoints}
doorStates={doorStates}
isLowPressure={isLowPressure}
isEmergencyStop={isEmergencyStop}
activeTab={activeTab}
onSelectRecipe={handleSelectRecipe}
onMove={moveAxis}
onControl={handleControl}
onSaveConfig={handleSaveConfig}
onCloseTab={() => setActiveTab(null)}
videoRef={videoRef}
/>
}
/>
<Route
path="/io-monitor"
element={
<IOMonitorPage
onToggle={toggleIO}
/>
}
/>
<Route
path="/recipe"
element={<RecipePage />}
/>
</Routes>
</Layout>
</HashRouter>
);
}

20
FrontEnd/README.md Normal file
View File

@@ -0,0 +1,20 @@
<div align="center">
<img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
</div>
# Run and deploy your AI Studio app
This contains everything you need to run your app locally.
View your app in AI Studio: https://ai.studio/apps/drive/1WUaQ4phJ_kZujzyiakV5X8RFgCwgaUDq
## Run Locally
**Prerequisites:** Node.js
1. Install dependencies:
`npm install`
2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
3. Run the app:
`npm run dev`

10
FrontEnd/build.bat Normal file
View File

@@ -0,0 +1,10 @@
@echo off
echo Building Frontend...
call npm run build
if %ERRORLEVEL% NEQ 0 (
echo Build Failed!
pause
exit /b %ERRORLEVEL%
)
echo Build Success!
pause

289
FrontEnd/communication.ts Normal file
View File

@@ -0,0 +1,289 @@
// Check if running in WebView2
const isWebView = typeof window !== 'undefined' && !!window.chrome?.webview;
// 비동기 프록시 캐싱 (한 번만 초기화) - 매번 접근 시 오버헤드 제거
const machine = isWebView ? window.chrome!.webview!.hostObjects.machine : null;
type MessageCallback = (data: any) => void;
class CommunicationLayer {
private listeners: MessageCallback[] = [];
private ws: WebSocket | null = null;
private isConnected = false;
constructor() {
if (isWebView) {
console.log("[COMM] Running in WebView2 Mode");
this.isConnected = true; // WebView2 is always connected
window.chrome!.webview!.addEventListener('message', (event: any) => {
this.notifyListeners(event.data);
});
} else {
console.log("[COMM] Running in Browser Mode (WebSocket)");
this.connectWebSocket();
}
}
private connectWebSocket() {
this.ws = new WebSocket('ws://localhost:8081');
this.ws.onopen = () => {
console.log("[COMM] WebSocket Connected");
this.isConnected = true;
this.notifyListeners({ type: 'CONNECTION_STATE', connected: true });
};
this.ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
this.notifyListeners(data);
} catch (e) {
console.error("[COMM] JSON Parse Error", e);
}
};
this.ws.onclose = () => {
console.log("[COMM] WebSocket Closed. Reconnecting...");
this.isConnected = false;
this.notifyListeners({ type: 'CONNECTION_STATE', connected: false });
setTimeout(() => this.connectWebSocket(), 2000);
};
this.ws.onerror = (err) => {
console.error("[COMM] WebSocket Error", err);
};
}
private notifyListeners(data: any) {
this.listeners.forEach(cb => cb(data));
}
public subscribe(callback: MessageCallback) {
this.listeners.push(callback);
return () => {
this.listeners = this.listeners.filter(cb => cb !== callback);
};
}
public getConnectionState(): boolean {
return this.isConnected;
}
// --- API Methods ---
public async getConfig(): Promise<string> {
if (isWebView && machine) {
return await machine.GetConfig();
} else {
// WebSocket Request/Response Pattern
return new Promise((resolve, reject) => {
// 1. Wait for Connection (max 2s)
if (!this.isConnected) {
// Simple wait logic (could be improved)
setTimeout(() => {
if (!this.isConnected) reject("WebSocket connection timeout");
}, 2000);
}
// 2. Send Request with Timeout (max 10s)
const timeoutId = setTimeout(() => {
this.listeners = this.listeners.filter(cb => cb !== handler);
reject("Config fetch timeout");
}, 10000);
const handler = (data: any) => {
if (data.type === 'CONFIG_DATA') {
clearTimeout(timeoutId);
this.listeners = this.listeners.filter(cb => cb !== handler);
resolve(JSON.stringify(data.data));
}
};
this.listeners.push(handler);
this.ws?.send(JSON.stringify({ type: 'GET_CONFIG' }));
});
}
}
public async getIOList(): Promise<string> {
if (isWebView && machine) {
return await machine.GetIOList();
} else {
return new Promise((resolve, reject) => {
if (!this.isConnected) {
setTimeout(() => {
if (!this.isConnected) reject("WebSocket connection timeout");
}, 2000);
}
const timeoutId = setTimeout(() => {
this.listeners = this.listeners.filter(cb => cb !== handler);
reject("IO fetch timeout");
}, 10000);
const handler = (data: any) => {
if (data.type === 'IO_LIST_DATA') {
clearTimeout(timeoutId);
this.listeners = this.listeners.filter(cb => cb !== handler);
resolve(JSON.stringify(data.data));
}
};
this.listeners.push(handler);
this.ws?.send(JSON.stringify({ type: 'GET_IO_LIST' }));
});
}
}
public async getRecipeList(): Promise<string> {
if (isWebView && machine) {
return await machine.GetRecipeList();
} else {
return new Promise((resolve, reject) => {
if (!this.isConnected) {
setTimeout(() => {
if (!this.isConnected) reject("WebSocket connection timeout");
}, 2000);
}
const timeoutId = setTimeout(() => {
this.listeners = this.listeners.filter(cb => cb !== handler);
reject("Recipe fetch timeout");
}, 10000);
const handler = (data: any) => {
if (data.type === 'RECIPE_LIST_DATA') {
clearTimeout(timeoutId);
this.listeners = this.listeners.filter(cb => cb !== handler);
resolve(JSON.stringify(data.data));
}
};
this.listeners.push(handler);
this.ws?.send(JSON.stringify({ type: 'GET_RECIPE_LIST' }));
});
}
}
public async saveConfig(configJson: string): Promise<void> {
if (isWebView && machine) {
await machine.SaveConfig(configJson);
} else {
this.ws?.send(JSON.stringify({ type: 'SAVE_CONFIG', data: JSON.parse(configJson) }));
}
}
public async sendControl(command: string) {
if (isWebView && machine) {
await machine.SystemControl(command);
} else {
this.ws?.send(JSON.stringify({ type: 'CONTROL', command }));
}
}
public async moveAxis(axis: string, value: number) {
if (isWebView && machine) {
await machine.MoveAxis(axis, value);
} else {
this.ws?.send(JSON.stringify({ type: 'MOVE', axis, value }));
}
}
public async setIO(id: number, state: boolean) {
if (isWebView && machine) {
await machine.SetIO(id, false, state);
} else {
this.ws?.send(JSON.stringify({ type: 'SET_IO', id, state }));
}
}
public async selectRecipe(recipeId: string): Promise<{ success: boolean; message: string; recipeId?: string }> {
if (isWebView && machine) {
const resultJson = await machine.SelectRecipe(recipeId);
return JSON.parse(resultJson);
} else {
return new Promise((resolve, reject) => {
if (!this.isConnected) {
setTimeout(() => {
if (!this.isConnected) reject({ success: false, message: "WebSocket connection timeout" });
}, 2000);
}
const timeoutId = setTimeout(() => {
this.listeners = this.listeners.filter(cb => cb !== handler);
reject({ success: false, message: "Recipe selection timeout" });
}, 10000);
const handler = (data: any) => {
if (data.type === 'RECIPE_SELECTED') {
clearTimeout(timeoutId);
this.listeners = this.listeners.filter(cb => cb !== handler);
resolve(data.data);
}
};
this.listeners.push(handler);
this.ws?.send(JSON.stringify({ type: 'SELECT_RECIPE', recipeId }));
});
}
}
public async copyRecipe(recipeId: string, newName: string): Promise<{ success: boolean; message: string; newRecipe?: any }> {
if (isWebView && machine) {
const resultJson = await machine.CopyRecipe(recipeId, newName);
return JSON.parse(resultJson);
} else {
return new Promise((resolve, reject) => {
if (!this.isConnected) {
setTimeout(() => {
if (!this.isConnected) reject({ success: false, message: "WebSocket connection timeout" });
}, 2000);
}
const timeoutId = setTimeout(() => {
this.listeners = this.listeners.filter(cb => cb !== handler);
reject({ success: false, message: "Recipe copy timeout" });
}, 10000);
const handler = (data: any) => {
if (data.type === 'RECIPE_COPIED') {
clearTimeout(timeoutId);
this.listeners = this.listeners.filter(cb => cb !== handler);
resolve(data.data);
}
};
this.listeners.push(handler);
this.ws?.send(JSON.stringify({ type: 'COPY_RECIPE', recipeId, newName }));
});
}
}
public async deleteRecipe(recipeId: string): Promise<{ success: boolean; message: string; recipeId?: string }> {
if (isWebView && machine) {
const resultJson = await machine.DeleteRecipe(recipeId);
return JSON.parse(resultJson);
} else {
return new Promise((resolve, reject) => {
if (!this.isConnected) {
setTimeout(() => {
if (!this.isConnected) reject({ success: false, message: "WebSocket connection timeout" });
}, 2000);
}
const timeoutId = setTimeout(() => {
this.listeners = this.listeners.filter(cb => cb !== handler);
reject({ success: false, message: "Recipe delete timeout" });
}, 10000);
const handler = (data: any) => {
if (data.type === 'RECIPE_DELETED') {
clearTimeout(timeoutId);
this.listeners = this.listeners.filter(cb => cb !== handler);
resolve(data.data);
}
};
this.listeners.push(handler);
this.ws?.send(JSON.stringify({ type: 'DELETE_RECIPE', recipeId }));
});
}
}
}
export const comms = new CommunicationLayer();

View File

@@ -0,0 +1,39 @@
import React from 'react';
import { Camera, Crosshair } from 'lucide-react';
import { PanelHeader } from './common/PanelHeader';
interface CameraPanelProps {
videoRef: React.RefObject<HTMLVideoElement>;
}
export const CameraPanel: React.FC<CameraPanelProps> = ({ videoRef }) => (
<div className="h-full flex flex-col">
<PanelHeader title="Vision Feed" icon={Camera} />
<div className="flex-1 bg-black relative overflow-hidden border border-slate-800 group">
<video ref={videoRef} autoPlay playsInline className="w-full h-full object-cover opacity-80" />
{/* HUD OVERLAY */}
<div className="absolute inset-0 pointer-events-none">
<div className="absolute top-0 left-0 w-full h-full border-[20px] border-neon-blue/10 clip-tech-inv"></div>
<Crosshair className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-12 h-12 text-neon-blue opacity-50" />
<div className="absolute top-4 right-4 flex flex-col items-end gap-1">
<span className="text-[10px] font-mono text-neon-red animate-pulse"> REC</span>
<span className="text-xs font-mono text-neon-blue">1920x1080 @ 60FPS</span>
</div>
<div className="absolute bottom-4 left-4 text-neon-blue/80 font-mono text-xs">
EXPOSURE: AUTO<br />
GAIN: 12dB<br />
FOCUS: 150mm
</div>
</div>
</div>
<div className="grid grid-cols-4 gap-2 mt-3">
<button className="bg-slate-800 text-slate-400 text-[10px] py-2 hover:bg-neon-blue hover:text-black transition-colors">ZOOM +</button>
<button className="bg-slate-800 text-slate-400 text-[10px] py-2 hover:bg-neon-blue hover:text-black transition-colors">ZOOM -</button>
<button className="bg-slate-800 text-slate-400 text-[10px] py-2 hover:bg-neon-blue hover:text-black transition-colors">SNAP</button>
<button className="bg-slate-800 text-slate-400 text-[10px] py-2 hover:bg-neon-blue hover:text-black transition-colors">SETTINGS</button>
</div>
</div>
);

View File

@@ -0,0 +1,50 @@
import React, { useState } from 'react';
import { Activity } from 'lucide-react';
import { IOPoint } from '../types';
import { PanelHeader } from './common/PanelHeader';
import { TechButton } from './common/TechButton';
interface IOPanelProps {
ioPoints: IOPoint[];
onToggle: (id: number, type: 'input' | 'output') => void;
}
export const IOPanel: React.FC<IOPanelProps> = ({ ioPoints, onToggle }) => {
const [tab, setTab] = useState<'in' | 'out'>('in');
const points = ioPoints.filter(p => p.type === (tab === 'in' ? 'input' : 'output'));
return (
<div className="h-full flex flex-col">
<PanelHeader title="I/O Monitor" icon={Activity} />
<div className="flex gap-2 mb-4">
<TechButton active={tab === 'in'} onClick={() => setTab('in')} className="flex-1">Inputs</TechButton>
<TechButton active={tab === 'out'} onClick={() => setTab('out')} className="flex-1" variant="blue">Outputs</TechButton>
</div>
<div className="grid grid-cols-4 gap-2 overflow-y-auto pr-2 custom-scrollbar pb-4">
{points.map(p => (
<div
key={p.id}
onClick={() => onToggle(p.id, p.type)}
className={`
aspect-square flex flex-col items-center justify-center p-1 cursor-pointer transition-all border
clip-tech
${p.state
? (p.type === 'output'
? 'bg-neon-green/10 border-neon-green text-neon-green shadow-[0_0_10px_rgba(10,255,0,0.3)]'
: 'bg-neon-yellow/10 border-neon-yellow text-neon-yellow shadow-[0_0_10px_rgba(255,230,0,0.3)]')
: 'bg-slate-900/50 border-slate-700 text-slate-600 hover:border-slate-500'}
`}
>
<div className={`w-2 h-2 rounded-full mb-2 ${p.state ? (p.type === 'output' ? 'bg-neon-green' : 'bg-neon-yellow') : 'bg-slate-800'}`}></div>
<span className="font-mono text-[10px] font-bold">
{p.type === 'input' ? 'I' : 'Q'}{p.id.toString().padStart(2, '0')}
</span>
<span className="text-[8px] text-center uppercase leading-tight mt-1 opacity-80 truncate w-full px-1">
{p.name.replace(/(Sensor|Door|Lamp)/g, '')}
</span>
</div>
))}
</div>
</div>
);
};

View File

@@ -0,0 +1,181 @@
import React, { useState, useEffect } from 'react';
import { Target, CheckCircle2, Loader2 } from 'lucide-react';
import { TechButton } from './common/TechButton';
interface InitializeModalProps {
isOpen: boolean;
onClose: () => void;
}
type AxisStatus = 'pending' | 'initializing' | 'completed';
interface AxisState {
name: string;
status: AxisStatus;
progress: number;
}
export const InitializeModal: React.FC<InitializeModalProps> = ({ isOpen, onClose }) => {
const [axes, setAxes] = useState<AxisState[]>([
{ name: 'X-Axis', status: 'pending', progress: 0 },
{ name: 'Y-Axis', status: 'pending', progress: 0 },
{ name: 'Z-Axis', status: 'pending', progress: 0 },
]);
const [isInitializing, setIsInitializing] = useState(false);
// Reset state when modal closes
useEffect(() => {
if (!isOpen) {
setAxes([
{ name: 'X-Axis', status: 'pending', progress: 0 },
{ name: 'Y-Axis', status: 'pending', progress: 0 },
{ name: 'Z-Axis', status: 'pending', progress: 0 },
]);
setIsInitializing(false);
}
}, [isOpen]);
const startInitialization = () => {
setIsInitializing(true);
// Initialize each axis with 3 second delay between them
axes.forEach((axis, index) => {
const delay = index * 3000; // 0s, 3s, 6s
// Start initialization after delay
setTimeout(() => {
setAxes(prev => {
const next = [...prev];
next[index] = { ...next[index], status: 'initializing', progress: 0 };
return next;
});
// Progress animation (3 seconds)
const startTime = Date.now();
const duration = 3000;
const interval = setInterval(() => {
const elapsed = Date.now() - startTime;
const progress = Math.min((elapsed / duration) * 100, 100);
setAxes(prev => {
const next = [...prev];
next[index] = { ...next[index], progress };
return next;
});
if (progress >= 100) {
clearInterval(interval);
setAxes(prev => {
const next = [...prev];
next[index] = { ...next[index], status: 'completed', progress: 100 };
return next;
});
// Check if all axes are completed
setAxes(prev => {
if (prev.every(a => a.status === 'completed')) {
// Auto close after 500ms
setTimeout(() => {
onClose();
}, 500);
}
return prev;
});
}
}, 50);
}, delay);
});
};
if (!isOpen) return null;
const allCompleted = axes.every(a => a.status === 'completed');
return (
<div className="absolute inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
<div className="w-[600px] glass-holo p-8 border border-neon-blue shadow-glow-blue relative flex flex-col">
<button
onClick={onClose}
disabled={isInitializing}
className="absolute top-4 right-4 text-slate-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed"
>
</button>
<h2 className="text-2xl font-tech font-bold text-neon-blue mb-8 border-b border-white/10 pb-4 flex items-center gap-3">
<Target className="animate-pulse" /> AXIS INITIALIZATION
</h2>
<div className="space-y-6 mb-8">
{axes.map((axis, index) => (
<div key={axis.name} className="space-y-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{axis.status === 'completed' ? (
<CheckCircle2 className="w-5 h-5 text-neon-green" />
) : axis.status === 'initializing' ? (
<Loader2 className="w-5 h-5 text-neon-blue animate-spin" />
) : (
<div className="w-5 h-5 border-2 border-slate-600 rounded-full" />
)}
<span className="font-tech font-bold text-lg text-white tracking-wider">
{axis.name}
</span>
</div>
<span
className={`font-mono text-sm font-bold ${
axis.status === 'completed'
? 'text-neon-green'
: axis.status === 'initializing'
? 'text-neon-blue'
: 'text-slate-500'
}`}
>
{axis.status === 'completed'
? 'COMPLETED'
: axis.status === 'initializing'
? `${Math.round(axis.progress)}%`
: 'WAITING'}
</span>
</div>
{/* Progress Bar */}
<div className="h-3 bg-black/50 border border-slate-700 overflow-hidden">
<div
className={`h-full transition-all duration-100 ${
axis.status === 'completed'
? 'bg-neon-green shadow-[0_0_10px_rgba(10,255,0,0.5)]'
: 'bg-neon-blue shadow-[0_0_10px_rgba(0,243,255,0.5)]'
}`}
style={{ width: `${axis.progress}%` }}
/>
</div>
</div>
))}
</div>
{allCompleted && (
<div className="mb-6 p-4 bg-neon-green/10 border border-neon-green rounded text-center">
<span className="font-tech font-bold text-neon-green tracking-wider">
ALL AXES INITIALIZED SUCCESSFULLY
</span>
</div>
)}
<div className="flex justify-end gap-4">
<TechButton onClick={onClose} disabled={isInitializing}>
CANCEL
</TechButton>
<TechButton
variant="blue"
active
onClick={startInitialization}
disabled={isInitializing || allCompleted}
>
{isInitializing ? 'INITIALIZING...' : 'START INITIALIZATION'}
</TechButton>
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,633 @@
import React, { useRef, useMemo } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { OrbitControls, Grid, PerspectiveCamera, Text, Box, Environment, RoundedBox } from '@react-three/drei';
import * as THREE from 'three';
import { RobotTarget, IOPoint } from '../types';
interface Machine3DProps {
target: RobotTarget;
ioState: IOPoint[];
doorStates: {
front: boolean;
right: boolean;
left: boolean;
back: boolean;
};
}
// -- Parts Components --
const TowerLamp = ({ ioState }: { ioState: IOPoint[] }) => {
// Outputs 0,1,2 mapped to Red, Yellow, Green
const redOn = ioState.find(io => io.id === 0 && io.type === 'output')?.state;
const yellowOn = ioState.find(io => io.id === 1 && io.type === 'output')?.state;
const greenOn = ioState.find(io => io.id === 2 && io.type === 'output')?.state;
const redMat = useRef<THREE.MeshStandardMaterial>(null);
const yelMat = useRef<THREE.MeshStandardMaterial>(null);
const grnMat = useRef<THREE.MeshStandardMaterial>(null);
useFrame((state) => {
const time = state.clock.elapsedTime;
const pulse = (Math.sin(time * 6) * 0.5 + 0.5);
const intensity = 0.5 + (pulse * 3.0);
if (redMat.current) {
redMat.current.emissiveIntensity = redOn ? intensity : 0;
redMat.current.opacity = redOn ? 1.0 : 0.3;
redMat.current.color.setHex(redOn ? 0xff0000 : 0x550000);
}
if (yelMat.current) {
yelMat.current.emissiveIntensity = yellowOn ? intensity : 0;
yelMat.current.opacity = yellowOn ? 1.0 : 0.3;
yelMat.current.color.setHex(yellowOn ? 0xffff00 : 0x555500);
}
if (grnMat.current) {
grnMat.current.emissiveIntensity = greenOn ? intensity : 0;
grnMat.current.opacity = greenOn ? 1.0 : 0.3;
grnMat.current.color.setHex(greenOn ? 0x00ff00 : 0x005500);
}
});
return (
<group position={[1.8, 2.5, -1.8]}>
{/* Pole */}
<mesh position={[0, 0, 0]}>
<cylinderGeometry args={[0.05, 0.05, 0.5]} />
<meshStandardMaterial color="#333" roughness={0.5} />
</mesh>
{/* Green */}
<mesh position={[0, 0.3, 0]}>
<cylinderGeometry args={[0.08, 0.08, 0.15]} />
<meshStandardMaterial
ref={grnMat}
color="#00ff00"
emissive="#00ff00"
transparent
toneMapped={false}
/>
</mesh>
{/* Yellow */}
<mesh position={[0, 0.46, 0]}>
<cylinderGeometry args={[0.08, 0.08, 0.15]} />
<meshStandardMaterial
ref={yelMat}
color="#ffff00"
emissive="#ffff00"
transparent
toneMapped={false}
/>
</mesh>
{/* Red */}
<mesh position={[0, 0.62, 0]}>
<cylinderGeometry args={[0.08, 0.08, 0.15]} />
<meshStandardMaterial
ref={redMat}
color="#ff0000"
emissive="#ff0000"
transparent
toneMapped={false}
/>
</mesh>
</group>
);
};
// -- DIPPING STATION COMPONENTS --
const LiquidBath = ({
position,
label,
liquidColor,
}: {
position: [number, number, number],
label: string,
liquidColor: string,
}) => {
const width = 1.0;
const depth = 0.8;
const height = 0.3;
const wallThick = 0.03;
const SteelMaterial = (
<meshStandardMaterial color="#e2e8f0" metalness={0.95} roughness={0.2} />
);
return (
<group position={position}>
<group position={[0, height / 2, 0]}>
<mesh position={[0, -height/2 + wallThick/2, 0]}>
<boxGeometry args={[width, wallThick, depth]} />
{SteelMaterial}
</mesh>
<mesh position={[0, 0, depth/2 - wallThick/2]}>
<boxGeometry args={[width, height, wallThick]} />
{SteelMaterial}
</mesh>
<mesh position={[0, 0, -depth/2 + wallThick/2]}>
<boxGeometry args={[width, height, wallThick]} />
{SteelMaterial}
</mesh>
<mesh position={[-width/2 + wallThick/2, 0, 0]}>
<boxGeometry args={[wallThick, height, depth - wallThick*2]} />
{SteelMaterial}
</mesh>
<mesh position={[width/2 - wallThick/2, 0, 0]}>
<boxGeometry args={[wallThick, height, depth - wallThick*2]} />
{SteelMaterial}
</mesh>
<mesh position={[0, height/2 - 0.05, 0]} rotation={[-Math.PI / 2, 0, 0]}>
<planeGeometry args={[width - wallThick*2, depth - wallThick*2]} />
<meshPhysicalMaterial
color={liquidColor}
transparent
opacity={0.85}
roughness={0.05}
metalness={0.2}
transmission={0.4}
thickness={1}
clearcoat={1}
/>
</mesh>
</group>
<Text
position={[0, 0.6, 0.55]}
fontSize={0.12}
color="white"
anchorX="center"
anchorY="middle"
rotation={[-Math.PI/4, 0, 0]}
>
{label}
</Text>
</group>
);
};
const HakkoFX305 = ({ position }: { position: [number, number, number] }) => {
return (
<group position={position}>
{/* Main Blue Chassis */}
<mesh position={[0, 0.25, 0]}>
<boxGeometry args={[1.3, 0.55, 1.0]} />
<meshStandardMaterial color="#2563eb" metalness={0.1} roughness={0.4} />
</mesh>
<mesh position={[-0.66, 0.25, 0]}>
<boxGeometry args={[0.02, 0.3, 0.6]} />
<meshStandardMaterial color="#1e3a8a" />
</mesh>
<mesh position={[0.66, 0.25, 0]}>
<boxGeometry args={[0.02, 0.3, 0.6]} />
<meshStandardMaterial color="#1e3a8a" />
</mesh>
<mesh position={[0, 0.25, 0.51]}>
<planeGeometry args={[1.25, 0.5]} />
<meshStandardMaterial color="#cbd5e1" metalness={0.6} roughness={0.3} />
</mesh>
<Text
position={[0, 0.42, 0.52]}
fontSize={0.08}
color="#2563eb"
anchorX="center"
anchorY="middle"
fontWeight="bold"
>
HAKKO
</Text>
<Text
position={[0.5, 0.42, 0.52]}
fontSize={0.04}
color="#64748b"
anchorX="right"
anchorY="middle"
>
FX-305
</Text>
<mesh position={[0.15, 0.25, 0.52]}>
<planeGeometry args={[0.35, 0.15]} />
<meshStandardMaterial color="#0f172a" roughness={0.2} />
</mesh>
<group position={[-0.45, 0.25, 0.52]} rotation={[Math.PI/2, 0, 0]}>
<mesh>
<cylinderGeometry args={[0.08, 0.08, 0.02, 32]} />
<meshStandardMaterial color="#1e293b" />
</mesh>
<mesh position={[0, 0.02, 0]} rotation={[0, 0, Math.PI/2]}>
<boxGeometry args={[0.02, 0.08, 0.01]} />
<meshStandardMaterial color="#475569" />
</mesh>
</group>
<group position={[0.15, 0.12, 0.52]}>
{[-0.12, 0, 0.12, 0.24].map((x, i) => (
<mesh key={i} position={[x, 0, 0]} rotation={[Math.PI/2, 0, 0]}>
<cylinderGeometry args={[0.035, 0.035, 0.02, 16]} />
<meshStandardMaterial color="#facc15" />
</mesh>
))}
</group>
<mesh position={[0, 0.55, 0]}>
<boxGeometry args={[0.9, 0.05, 0.7]} />
<meshStandardMaterial color="#94a3b8" metalness={0.8} roughness={0.3} />
</mesh>
<group position={[0, 0.58, 0]}>
<mesh position={[0, 0, -0.3]}>
<boxGeometry args={[0.8, 0.05, 0.05]} />
<meshStandardMaterial color="#64748b" metalness={0.7} />
</mesh>
<mesh position={[0, 0, 0.3]}>
<boxGeometry args={[0.8, 0.05, 0.05]} />
<meshStandardMaterial color="#64748b" metalness={0.7} />
</mesh>
<mesh position={[-0.4, 0, 0]}>
<boxGeometry args={[0.05, 0.05, 0.65]} />
<meshStandardMaterial color="#64748b" metalness={0.7} />
</mesh>
<mesh position={[0.4, 0, 0]}>
<boxGeometry args={[0.05, 0.05, 0.65]} />
<meshStandardMaterial color="#64748b" metalness={0.7} />
</mesh>
</group>
<mesh position={[0, 0.57, 0]} rotation={[-Math.PI / 2, 0, 0]}>
<planeGeometry args={[0.75, 0.6]} />
<meshPhysicalMaterial
color="#e2e8f0"
emissive="#cbd5e1"
emissiveIntensity={0.1}
roughness={0.02}
metalness={1.0}
clearcoat={1}
reflectivity={1}
/>
</mesh>
<Text
position={[0, 0.9, 0.6]}
fontSize={0.15}
color="#fbbf24"
anchorX="center"
anchorY="middle"
rotation={[-Math.PI/4, 0, 0]}
>
2. HAKKO SOLDER
</Text>
</group>
);
};
const DippingStations = () => {
return (
<group>
<mesh position={[0, 0.2, 0]}>
<boxGeometry args={[4.5, 0.4, 1.5]} />
<meshStandardMaterial color="#334155" roughness={0.5} metalness={0.5} />
</mesh>
<LiquidBath position={[-1.5, 0.4, 0]} label="1. FLUX" liquidColor="#fef08a" />
<HakkoFX305 position={[0, 0.4, 0]} />
<LiquidBath position={[1.5, 0.4, 0]} label="3. CLEAN" liquidColor="#bae6fd" />
</group>
);
};
const Door = ({
position,
rotation = [0,0,0],
size,
isOpen
}: {
position: [number, number, number],
rotation?: [number, number, number],
size: [number, number],
isOpen: boolean
}) => {
const meshRef = useRef<THREE.Mesh>(null);
useFrame((state, delta) => {
if (!meshRef.current) return;
const targetY = isOpen ? position[1] + 2 : position[1];
meshRef.current.position.y = THREE.MathUtils.lerp(meshRef.current.position.y, targetY, delta * 5);
});
return (
<mesh ref={meshRef} position={position} rotation={rotation as any}>
<planeGeometry args={[size[0], size[1]]} />
<meshPhysicalMaterial
color="#a5f3fc"
transparent
opacity={0.2}
roughness={0}
metalness={0.9}
side={THREE.DoubleSide}
depthWrite={false}
/>
<mesh position={[size[0]/2 - 0.1, 0, 0.02]}>
<boxGeometry args={[0.05, size[1], 0.05]} />
<meshStandardMaterial color="#cbd5e1" />
</mesh>
<mesh position={[-size[0]/2 + 0.1, 0, 0.02]}>
<boxGeometry args={[0.05, size[1], 0.05]} />
<meshStandardMaterial color="#cbd5e1" />
</mesh>
</mesh>
);
};
const MachineFrame = ({ doorStates }: { doorStates: { front: boolean, right: boolean, left: boolean, back: boolean } }) => {
return (
<group>
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -0.05, 0]}>
<planeGeometry args={[6, 6]} />
<meshStandardMaterial color="#0f172a" roughness={0.8} metalness={0.2} />
</mesh>
<Grid infiniteGrid fadeDistance={15} sectionColor="#475569" cellColor="#1e293b" />
{[[-2, -2], [2, -2], [2, 2], [-2, 2]].map(([x, z], i) => (
<mesh key={i} position={[x, 1.5, z]}>
<boxGeometry args={[0.15, 3, 0.15]} />
<meshStandardMaterial color="#64748b" metalness={0.8} roughness={0.2} />
</mesh>
))}
<group position={[0, 3, 0]}>
<mesh position={[0, 0, -2]}>
<boxGeometry args={[4.15, 0.15, 0.15]} />
<meshStandardMaterial color="#64748b" metalness={0.8} roughness={0.2} />
</mesh>
<mesh position={[0, 0, 2]}>
<boxGeometry args={[4.15, 0.15, 0.15]} />
<meshStandardMaterial color="#64748b" metalness={0.8} roughness={0.2} />
</mesh>
<mesh position={[-2, 0, 0]}>
<boxGeometry args={[0.15, 0.15, 4.15]} />
<meshStandardMaterial color="#64748b" metalness={0.8} roughness={0.2} />
</mesh>
<mesh position={[2, 0, 0]}>
<boxGeometry args={[0.15, 0.15, 4.15]} />
<meshStandardMaterial color="#64748b" metalness={0.8} roughness={0.2} />
</mesh>
</group>
<Door position={[0, 1.5, 2]} size={[4, 3]} isOpen={doorStates.front} />
<Door position={[0, 1.5, -2]} size={[4, 3]} isOpen={doorStates.back} />
<Door position={[-2, 1.5, 0]} rotation={[0, Math.PI/2, 0]} size={[4, 3]} isOpen={doorStates.left} />
<Door position={[2, 1.5, 0]} rotation={[0, Math.PI/2, 0]} size={[4, 3]} isOpen={doorStates.right} />
<DippingStations />
</group>
);
};
// --- MISUMI STYLE INDUSTRIAL ACTUATOR COMPONENT ---
const IndustrialActuatorRail = ({ length, label, hasMotor = true }: { length: number, label?: string, hasMotor?: boolean }) => {
const width = 0.14; // Actuator Width
const height = 0.08; // Actuator Height (Profile)
return (
<group>
{/* 1. Main Aluminum Body (White/Light Grey Matte) */}
<RoundedBox args={[width, height, length]} radius={0.01} smoothness={4}>
<meshStandardMaterial color="#f8fafc" roughness={0.8} metalness={0.1} />
</RoundedBox>
{/* 2. Top Stainless Steel Cover Strip */}
<mesh position={[0, height/2 + 0.001, 0]}>
<boxGeometry args={[width * 0.7, 0.002, length]} />
<meshStandardMaterial color="#cbd5e1" metalness={0.9} roughness={0.2} />
</mesh>
{/* 3. Black Gap/Slit for Slider */}
<mesh position={[0, height/2, 0]}>
<boxGeometry args={[width * 0.8, 0.01, length * 0.98]} />
<meshStandardMaterial color="#0f172a" roughness={0.9} />
</mesh>
{/* 4. End Caps (Plastic White) */}
<group position={[0, 0, length/2 + 0.02]}>
<RoundedBox args={[width + 0.01, height + 0.01, 0.04]} radius={0.02} smoothness={4}>
<meshStandardMaterial color="#e2e8f0" />
</RoundedBox>
</group>
<group position={[0, 0, -length/2 - 0.02]}>
<RoundedBox args={[width + 0.01, height + 0.01, 0.04]} radius={0.02} smoothness={4}>
<meshStandardMaterial color="#e2e8f0" />
</RoundedBox>
</group>
{/* 5. Servo Motor Unit (Black & Silver) */}
{hasMotor && (
<group position={[0, 0, -length/2 - 0.15]}>
{/* Flange */}
<mesh position={[0, 0, 0.08]}>
<boxGeometry args={[0.12, 0.12, 0.05]} />
<meshStandardMaterial color="#475569" metalness={0.8} />
</mesh>
{/* Motor Body */}
<mesh position={[0, 0, 0]} rotation={[Math.PI/2, 0, 0]}>
<cylinderGeometry args={[0.05, 0.05, 0.2, 32]} />
<meshStandardMaterial color="#1e293b" metalness={0.6} roughness={0.4} />
</mesh>
{/* Encoder Cap */}
<mesh position={[0, 0, -0.11]} rotation={[Math.PI/2, 0, 0]}>
<cylinderGeometry args={[0.045, 0.045, 0.05, 32]} />
<meshStandardMaterial color="#000000" />
</mesh>
{/* Cable Gland */}
<mesh position={[0, 0.04, -0.05]}>
<boxGeometry args={[0.03, 0.03, 0.03]} />
<meshStandardMaterial color="#333" />
</mesh>
</group>
)}
{/* 6. Label/Branding */}
{label && (
<Text
position={[width/2 + 0.01, 0, length/2 - 0.2]}
rotation={[0, Math.PI/2, 0]}
fontSize={0.06}
color="#334155"
fontWeight="bold"
anchorX="right"
>
{label}
</Text>
)}
</group>
);
}
// The Moving Block on top of the actuator
const IndustrialSlider = ({ width = 0.16, length = 0.18, height = 0.03 }) => {
return (
<group position={[0, 0.06, 0]}>
<RoundedBox args={[width, height, length]} radius={0.005} smoothness={2}>
<meshStandardMaterial color="#f1f5f9" metalness={0.4} roughness={0.5} />
</RoundedBox>
{/* Mounting Holes (Visual) */}
{[-1, 1].map(x => [-1, 1].map(z => (
<mesh key={`${x}-${z}`} position={[x * 0.06, height/2 + 0.001, z * 0.07]} rotation={[Math.PI/2, 0, 0]}>
<circleGeometry args={[0.008, 16]} />
<meshStandardMaterial color="#94a3b8" />
</mesh>
)))}
</group>
)
}
// -- MAIN ROBOT ASSEMBLY --
const Robot = ({ target }: { target: RobotTarget }) => {
const bridgeGroup = useRef<THREE.Group>(null);
const carriageGroup = useRef<THREE.Group>(null);
const zAxisGroup = useRef<THREE.Group>(null);
useFrame((state, delta) => {
if (bridgeGroup.current) {
// Y-Axis Movement
bridgeGroup.current.position.z = THREE.MathUtils.lerp(bridgeGroup.current.position.z, target.y, delta * 3);
}
if (carriageGroup.current) {
// X-Axis Movement
carriageGroup.current.position.x = THREE.MathUtils.lerp(carriageGroup.current.position.x, target.x, delta * 3);
}
if (zAxisGroup.current) {
// Z-Axis Movement
zAxisGroup.current.position.y = THREE.MathUtils.lerp(zAxisGroup.current.position.y, target.z, delta * 3);
}
});
return (
<group position={[0, 2.0, 0]}>
{/* --- Y-AXIS (Left & Right Fixed Actuators) --- */}
<group>
<group position={[-1.8, 0, 0]}>
<IndustrialActuatorRail length={3.8} label="MISUMI-Y1" />
</group>
<group position={[1.8, 0, 0]}>
<IndustrialActuatorRail length={3.8} label="MISUMI-Y2" />
</group>
</group>
{/* --- MOVING BRIDGE (Y-AXIS CARRIAGE + X-AXIS ACTUATOR) --- */}
<group ref={bridgeGroup}>
{/* Y-Sliders (Connecting Bridge to Y-Rails) */}
<group position={[-1.8, 0, 0]}> <IndustrialSlider /> </group>
<group position={[1.8, 0, 0]}> <IndustrialSlider /> </group>
{/* Bridge Beam Structure */}
<mesh position={[0, 0.08, 0]}>
<boxGeometry args={[4.2, 0.05, 0.25]} />
<meshStandardMaterial color="#cbd5e1" metalness={0.6} roughness={0.4} />
</mesh>
{/* X-AXIS ACTUATOR (Mounted on top of Bridge) */}
<group position={[0, 0.14, 0]} rotation={[0, Math.PI/2, 0]}>
<IndustrialActuatorRail length={3.4} label="MISUMI-X" hasMotor />
</group>
{/* --- MOVING CARRIAGE (X-AXIS SLIDER + Z-AXIS) --- */}
<group ref={carriageGroup}>
{/* X-Slider */}
<group position={[0, 0.14, 0]} rotation={[0, Math.PI/2, 0]}>
<IndustrialSlider />
</group>
{/* --- Z-AXIS ACTUATOR (Vertical) --- */}
<group position={[0, 0.2, 0.12]}>
{/* Z-Actuator Body (Fixed to X-Slider) */}
<group position={[0, 0.4, 0]} rotation={[Math.PI/2, 0, 0]}>
<IndustrialActuatorRail length={0.8} label="MISUMI-Z" hasMotor={false} />
{/* Z-Motor on Top */}
<group position={[0, 0, 0.4 + 0.15]} rotation={[0, Math.PI, 0]}>
<mesh position={[0, 0, -0.05]} rotation={[Math.PI/2, 0, 0]}>
<boxGeometry args={[0.1, 0.1, 0.12]} />
<meshStandardMaterial color="#0f172a" />
</mesh>
</group>
</group>
{/* MOVING Z-HEAD (The Slider of Z-Axis) */}
<group ref={zAxisGroup}>
<group position={[0, 0, 0.08]}>
{/* Connection Plate */}
<mesh position={[0, 0, -0.04]}>
<boxGeometry args={[0.12, 0.15, 0.02]} />
<meshStandardMaterial color="#64748b" />
</mesh>
{/* PICKER MECHANISM */}
<group position={[0, -0.2, 0]}>
<mesh position={[0, 0, 0]}>
<boxGeometry args={[0.3, 0.05, 0.1]} />
<meshStandardMaterial color="#334155" />
</mesh>
{/* Fingers */}
<mesh position={[-0.12, -0.15, 0]}>
<boxGeometry args={[0.02, 0.3, 0.05]} />
<meshStandardMaterial color="#94a3b8" metalness={0.8} />
</mesh>
<mesh position={[0.12, -0.15, 0]}>
<boxGeometry args={[0.02, 0.3, 0.05]} />
<meshStandardMaterial color="#94a3b8" metalness={0.8} />
</mesh>
{/* PCB STRIP */}
<group position={[0, -0.35, 0]}>
<mesh>
<boxGeometry args={[0.28, 0.6, 0.02]} />
<meshStandardMaterial color="#166534" roughness={0.3} />
</mesh>
<mesh position={[0, -0.28, 0.011]}>
<planeGeometry args={[0.24, 0.04]} />
<meshStandardMaterial color="#fbbf24" metalness={1.0} roughness={0.1} />
</mesh>
<mesh position={[0, 0, 0.011]}>
<planeGeometry args={[0.15, 0.15]} />
<meshStandardMaterial color="#0f172a" />
</mesh>
</group>
</group>
</group>
</group>
</group>
</group>
</group>
</group>
);
};
export const Machine3D: React.FC<Machine3DProps> = ({ target, ioState, doorStates }) => {
return (
<Canvas shadows className="w-full h-full bg-slate-900">
<PerspectiveCamera makeDefault position={[5, 5, 6]} fov={45} />
<OrbitControls
maxPolarAngle={Math.PI / 2 - 0.05}
minDistance={3}
maxDistance={12}
/>
<Environment preset="city" />
<ambientLight intensity={0.4} />
<pointLight position={[10, 10, 10]} intensity={1} castShadow />
<pointLight position={[-10, 5, -10]} intensity={0.5} />
<pointLight position={[0, 2, 0]} intensity={0.2} color="#bae6fd" distance={5} />
<MachineFrame doorStates={doorStates} />
<TowerLamp ioState={ioState} />
<Robot target={target} />
</Canvas>
);
};

View File

@@ -0,0 +1,58 @@
import React from 'react';
import { Box, Cpu, Activity } from 'lucide-react';
import { Recipe } from '../types';
import { CyberPanel } from './common/CyberPanel';
interface ModelInfoPanelProps {
currentRecipe: Recipe;
}
export const ModelInfoPanel: React.FC<ModelInfoPanelProps> = ({ currentRecipe }) => {
return (
<CyberPanel className="flex-none">
<div className="mb-3 flex items-center justify-between text-xs text-neon-blue font-bold tracking-widest uppercase border-b border-white/10 pb-2">
<span>Model Information</span>
<Box className="w-3 h-3" />
</div>
<div className="space-y-4">
<div>
<div className="text-[10px] text-slate-500 font-mono mb-1">SELECTED MODEL</div>
<div className="text-xl font-bold text-white tracking-wide truncate flex items-center gap-2">
<Cpu className="w-4 h-4 text-neon-blue" />
{currentRecipe.name}
</div>
</div>
<div className="grid grid-cols-2 gap-2">
<div className="bg-white/5 rounded p-2 border border-white/5">
<div className="text-[9px] text-slate-500 font-mono uppercase">Model ID</div>
<div className="text-sm font-mono text-neon-blue">{currentRecipe.id}</div>
</div>
<div className="bg-white/5 rounded p-2 border border-white/5">
<div className="text-[9px] text-slate-500 font-mono uppercase">Last Mod</div>
<div className="text-sm font-mono text-slate-300">{currentRecipe.lastModified}</div>
</div>
</div>
<div className="space-y-1">
<div className="flex justify-between text-[10px] font-mono text-slate-400">
<span>TARGET CYCLE</span>
<span className="text-neon-green">12.5s</span>
</div>
<div className="w-full h-1 bg-slate-800 rounded-full overflow-hidden">
<div className="h-full w-[85%] bg-neon-green/50"></div>
</div>
<div className="flex justify-between text-[10px] font-mono text-slate-400 mt-2">
<span>EST. YIELD</span>
<span className="text-neon-blue">99.8%</span>
</div>
<div className="w-full h-1 bg-slate-800 rounded-full overflow-hidden">
<div className="h-full w-[99%] bg-neon-blue/50"></div>
</div>
</div>
</div>
</CyberPanel>
);
};

View File

@@ -0,0 +1,67 @@
import React, { useState } from 'react';
import { Move } from 'lucide-react';
import { RobotTarget, AxisPosition } from '../types';
import { PanelHeader } from './common/PanelHeader';
import { TechButton } from './common/TechButton';
const MOCK_POSITIONS: AxisPosition[] = [
{ id: 'p1', name: 'Home Position', axis: 'X', value: 0, speed: 100, acc: 100, dec: 100 },
{ id: 'p2', name: 'Pick Pos A', axis: 'X', value: -1.5, speed: 500, acc: 200, dec: 200 },
{ id: 'p3', name: 'Place Pos B', axis: 'X', value: 1.5, speed: 500, acc: 200, dec: 200 },
{ id: 'p4', name: 'Scan Index', axis: 'X', value: 0.5, speed: 300, acc: 100, dec: 100 },
{ id: 'py1', name: 'Rear Limit', axis: 'Y', value: -1.5, speed: 200, acc: 100, dec: 100 },
{ id: 'pz1', name: 'Safe Height', axis: 'Z', value: 0, speed: 50, acc: 50, dec: 50 },
];
interface MotionPanelProps {
robotTarget: RobotTarget;
onMove: (axis: 'X' | 'Y' | 'Z', val: number) => void;
}
export const MotionPanel: React.FC<MotionPanelProps> = ({ robotTarget, onMove }) => {
const [axis, setAxis] = useState<'X' | 'Y' | 'Z'>('X');
return (
<div className="h-full flex flex-col">
<PanelHeader title="Servo Control" icon={Move} />
<div className="flex gap-2 mb-4">
{['X', 'Y', 'Z'].map(a => (
<button
key={a}
onClick={() => setAxis(a as any)}
className={`flex-1 py-2 font-tech font-bold text-lg border-b-2 transition-all ${axis === a ? 'text-neon-blue border-neon-blue bg-neon-blue/10' : 'text-slate-500 border-slate-700 hover:text-slate-300'}`}
>
{a}-AXIS
</button>
))}
</div>
<div className="bg-black/40 p-4 rounded border border-white/10 mb-4 text-center">
<div className="text-[10px] text-slate-400 uppercase tracking-widest mb-1">Current Position</div>
<div className="font-mono text-3xl text-neon-blue text-shadow-glow-blue">
{robotTarget[axis.toLowerCase() as 'x' | 'y' | 'z'].toFixed(3)}
<span className="text-sm text-slate-500 ml-2">mm</span>
</div>
</div>
<div className="space-y-2 overflow-y-auto flex-1 pr-2 custom-scrollbar">
{MOCK_POSITIONS.filter(p => p.axis === axis).map(p => (
<div key={p.id} className="flex items-center justify-between p-3 bg-white/5 border border-white/5 hover:border-neon-blue/50 transition-all group">
<span className="text-xs font-bold text-slate-300 group-hover:text-white">{p.name}</span>
<button
onClick={() => onMove(axis, p.value)}
className="px-3 py-1 bg-slate-800 hover:bg-neon-blue hover:text-black text-xs font-mono transition-colors"
>
GO {p.value}
</button>
</div>
))}
</div>
<div className="flex gap-2 mt-4">
<TechButton className="flex-1 font-mono text-lg" onClick={() => onMove(axis, robotTarget[axis.toLowerCase() as 'x' | 'y' | 'z'] - 0.1)}>-</TechButton>
<TechButton className="flex-1 font-mono text-lg" onClick={() => onMove(axis, robotTarget[axis.toLowerCase() as 'x' | 'y' | 'z'] + 0.1)}>+</TechButton>
</div>
</div>
);
};

View File

@@ -0,0 +1,119 @@
import React, { useState, useEffect } from 'react';
import { Layers, Check, Settings, X, RotateCw } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { Recipe } from '../types';
import { TechButton } from './common/TechButton';
import { comms } from '../communication';
interface RecipePanelProps {
isOpen: boolean;
currentRecipe: Recipe;
onSelectRecipe: (r: Recipe) => void;
onClose: () => void;
}
export const RecipePanel: React.FC<RecipePanelProps> = ({ isOpen, currentRecipe, onSelectRecipe, onClose }) => {
const navigate = useNavigate();
const [recipes, setRecipes] = useState<Recipe[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [selectedId, setSelectedId] = useState<string>(currentRecipe.id);
// Fetch recipes when panel opens
useEffect(() => {
if (isOpen) {
const fetchRecipes = async () => {
setIsLoading(true);
try {
const recipeStr = await comms.getRecipeList();
const recipeData: Recipe[] = JSON.parse(recipeStr);
setRecipes(recipeData);
} catch (e) {
console.error('Failed to fetch recipes:', e);
}
setIsLoading(false);
};
fetchRecipes();
}
}, [isOpen]);
// Update selected ID when currentRecipe changes
useEffect(() => {
setSelectedId(currentRecipe.id);
}, [currentRecipe.id]);
const handleConfirm = () => {
const selected = recipes.find(r => r.id === selectedId);
if (selected) {
onSelectRecipe(selected);
onClose();
}
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm animate-in fade-in duration-200">
<div className="w-[500px] bg-slate-950/90 border border-neon-blue/30 rounded-lg shadow-2xl flex flex-col overflow-hidden">
{/* Header */}
<div className="h-12 bg-white/5 flex items-center justify-between px-4 border-b border-white/10">
<div className="flex items-center gap-2 text-neon-blue font-tech font-bold tracking-wider">
<Layers className="w-4 h-4" /> RECIPE SELECTION
</div>
<button onClick={onClose} className="text-slate-400 hover:text-white transition-colors">
<X className="w-5 h-5" />
</button>
</div>
{/* List (Max height for ~5 items) */}
<div className="p-4 max-h-[320px] overflow-y-auto custom-scrollbar">
{isLoading ? (
<div className="h-64 flex flex-col items-center justify-center gap-4 animate-pulse">
<RotateCw className="w-12 h-12 text-neon-blue animate-spin" />
<div className="text-lg font-tech text-neon-blue tracking-widest">LOADING RECIPES...</div>
</div>
) : (
<div className="space-y-2">
{recipes.map(recipe => (
<div
key={recipe.id}
onClick={() => setSelectedId(recipe.id)}
className={`
p-3 rounded border cursor-pointer transition-all flex items-center justify-between
${selectedId === recipe.id
? 'bg-neon-blue/20 border-neon-blue text-white shadow-[0_0_10px_rgba(0,243,255,0.2)]'
: 'bg-white/5 border-white/10 text-slate-400 hover:bg-white/10 hover:border-white/20'}
`}
>
<div>
<div className="font-bold tracking-wide">{recipe.name}</div>
<div className="text-[10px] font-mono opacity-70">ID: {recipe.id} | MOD: {recipe.lastModified}</div>
</div>
{selectedId === recipe.id && <Check className="w-4 h-4 text-neon-blue" />}
</div>
))}
</div>
)}
</div>
{/* Footer Actions */}
<div className="p-4 border-t border-white/10 flex justify-between gap-4 bg-black/20">
<TechButton
variant="default"
className="flex items-center gap-2 px-4"
onClick={() => navigate('/recipe')}
>
<Settings className="w-4 h-4" /> MANAGEMENT
</TechButton>
<TechButton
variant="blue"
className="flex items-center gap-2 px-8"
onClick={handleConfirm}
>
SELECT
</TechButton>
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,166 @@
import React from 'react';
import { Settings, RotateCw, ChevronDown, ChevronRight } from 'lucide-react';
import { ConfigItem } from '../types';
import { comms } from '../communication';
interface SettingsModalProps {
isOpen: boolean;
onClose: () => void;
onSave: (config: ConfigItem[]) => void;
}
const TechButton = ({ children, onClick, active = false, variant = 'blue', className = '' }: any) => {
const colors: any = {
blue: 'from-blue-600 to-cyan-600 hover:shadow-glow-blue border-cyan-400/30',
red: 'from-red-600 to-pink-600 hover:shadow-glow-red border-red-400/30',
amber: 'from-amber-500 to-orange-600 hover:shadow-orange-500/50 border-orange-400/30',
green: 'from-emerald-500 to-green-600 hover:shadow-green-500/50 border-green-400/30'
};
return (
<button
onClick={onClick}
className={`
relative px-4 py-2 font-tech font-bold tracking-wider uppercase transition-all duration-300
clip-tech border-b-2 border-r-2
${active ? `bg-gradient-to-r ${colors[variant]} text-white` : 'bg-slate-800/50 text-slate-400 hover:text-white hover:bg-slate-700/50 border-slate-600'}
${className}
`}
>
{active && <div className="absolute inset-0 bg-white/20 animate-pulse pointer-events-none"></div>}
{children}
</button>
);
};
export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, onSave }) => {
const [localConfig, setLocalConfig] = React.useState<ConfigItem[]>([]);
const [expandedGroups, setExpandedGroups] = React.useState<Set<string>>(new Set());
const [isRefreshing, setIsRefreshing] = React.useState(false);
// Fetch config data when modal opens
React.useEffect(() => {
if (isOpen) {
const fetchConfig = async () => {
setIsRefreshing(true);
try {
const configStr = await comms.getConfig();
const config: ConfigItem[] = JSON.parse(configStr);
setLocalConfig(config);
// Auto-expand all groups initially
const groups = new Set<string>(config.map(c => c.Group));
setExpandedGroups(groups);
} catch (e) {
console.error('Failed to fetch config:', e);
}
setIsRefreshing(false);
};
fetchConfig();
}
}, [isOpen]);
const handleChange = (idx: number, newValue: string) => {
setLocalConfig(prev => {
const next = [...prev];
next[idx] = { ...next[idx], Value: newValue };
return next;
});
};
const toggleGroup = (group: string) => {
setExpandedGroups(prev => {
const next = new Set(prev);
if (next.has(group)) next.delete(group);
else next.add(group);
return next;
});
};
// Group items by category
const groupedConfig = React.useMemo(() => {
const groups: { [key: string]: { item: ConfigItem, originalIdx: number }[] } = {};
localConfig.forEach((item, idx) => {
if (!groups[item.Group]) groups[item.Group] = [];
groups[item.Group].push({ item, originalIdx: idx });
});
return groups;
}, [localConfig]);
if (!isOpen) return null;
return (
<div className="absolute inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
<div className="w-[900px] glass-holo p-8 border border-neon-blue shadow-glow-blue relative flex flex-col max-h-[90vh]">
<button onClick={onClose} className="absolute top-4 right-4 text-slate-400 hover:text-white"></button>
<h2 className="text-2xl font-tech font-bold text-neon-blue mb-8 border-b border-white/10 pb-4 flex items-center gap-3 flex-none">
<Settings className="animate-spin-slow" /> SYSTEM CONFIGURATION
</h2>
{isRefreshing ? (
<div className="h-64 flex flex-col items-center justify-center gap-4 animate-pulse flex-1">
<RotateCw className="w-12 h-12 text-neon-blue animate-spin" />
<div className="text-xl font-tech text-neon-blue tracking-widest">FETCHING CONFIGURATION...</div>
</div>
) : (
<div className="flex-1 overflow-y-auto custom-scrollbar pr-2 mb-8">
<div className="space-y-6">
{Object.entries(groupedConfig).map(([groupName, items]) => (
<div key={groupName} className="border border-white/10 bg-black/20">
<button
onClick={() => toggleGroup(groupName)}
className="w-full flex items-center gap-2 p-3 bg-white/5 hover:bg-white/10 transition-colors text-left"
>
{expandedGroups.has(groupName) ? <ChevronDown className="w-4 h-4 text-neon-blue" /> : <ChevronRight className="w-4 h-4 text-slate-400" />}
<span className="font-tech font-bold text-lg text-white tracking-wider">{groupName}</span>
<span className="text-xs text-slate-500 ml-auto">{items.length} ITEMS</span>
</button>
{expandedGroups.has(groupName) && (
<div className="p-4 space-y-4">
{items.map(({ item, originalIdx }) => (
<div key={originalIdx} className="grid grid-cols-[250px_1fr] gap-6 items-start group">
<div>
<div className="text-sm font-bold text-neon-blue mb-1">{item.Key}</div>
<div className="text-xs text-slate-400 leading-tight">{item.Description}</div>
</div>
<div>
{item.Type === 'Boolean' ? (
<div className="flex items-center gap-3 h-full">
<button
onClick={() => handleChange(originalIdx, item.Value === 'true' ? 'false' : 'true')}
className={`w-12 h-6 rounded-full p-1 transition-colors ${item.Value === 'true' ? 'bg-neon-green' : 'bg-slate-700'}`}
>
<div className={`w-4 h-4 rounded-full bg-white shadow transition-transform ${item.Value === 'true' ? 'translate-x-6' : 'translate-x-0'}`} />
</button>
<span className={`font-mono text-sm font-bold ${item.Value === 'true' ? 'text-neon-green' : 'text-slate-400'}`}>
{item.Value.toUpperCase()}
</span>
</div>
) : (
<input
type={item.Type === 'Number' ? 'number' : 'text'}
value={item.Value}
onChange={(e) => handleChange(originalIdx, e.target.value)}
className="w-full bg-black/50 border border-slate-700 text-white font-mono text-sm px-3 py-2 focus:border-neon-blue focus:outline-none transition-colors hover:border-slate-500"
/>
)}
</div>
</div>
))}
</div>
)}
</div>
))}
</div>
</div>
)}
<div className="flex justify-end gap-4 flex-none pt-4 border-t border-white/10">
<TechButton onClick={onClose}>CANCEL</TechButton>
<TechButton variant="blue" active onClick={() => { onSave(localConfig); onClose(); }}>SAVE CONFIG</TechButton>
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,29 @@
import React from 'react';
interface CyberPanelProps {
children?: React.ReactNode;
className?: string;
}
export const CyberPanel: React.FC<CyberPanelProps> = ({ children, className = "" }) => (
<div className={`glass-holo p-1 relative group ${className}`}>
{/* Decorative Corners */}
<svg className="absolute top-0 left-0 w-6 h-6 text-neon-blue opacity-70" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M2 22V2H22" />
</svg>
<svg className="absolute top-0 right-0 w-6 h-6 text-neon-blue opacity-70" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M22 22V2H2" />
</svg>
<svg className="absolute bottom-0 left-0 w-6 h-6 text-neon-blue opacity-70" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M2 2V22H22" />
</svg>
<svg className="absolute bottom-0 right-0 w-6 h-6 text-neon-blue opacity-70" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M22 2V22H2" />
</svg>
{/* Inner Content */}
<div className="bg-slate-950/40 backdrop-blur-md h-full w-full p-4 relative z-10 clip-tech border border-white/5">
{children}
</div>
</div>
);

View File

@@ -0,0 +1,19 @@
import React from 'react';
import { LucideIcon } from 'lucide-react';
interface PanelHeaderProps {
title: string;
icon: LucideIcon;
}
export const PanelHeader: React.FC<PanelHeaderProps> = ({ title, icon: Icon }) => (
<div className="flex items-center gap-3 mb-6 border-b border-white/10 pb-2">
<div className="text-neon-blue animate-pulse">
<Icon className="w-5 h-5" />
</div>
<h2 className="text-lg font-tech font-bold text-white tracking-[0.1em] uppercase text-shadow-glow-blue">
{title}
</h2>
<div className="flex-1 h-px bg-gradient-to-r from-neon-blue/50 to-transparent"></div>
</div>
);

View File

@@ -0,0 +1,54 @@
import React from 'react';
interface TechButtonProps {
children?: React.ReactNode;
onClick?: () => void;
active?: boolean;
variant?: 'blue' | 'red' | 'amber' | 'green' | 'default' | 'danger';
className?: string;
disabled?: boolean;
title?: string;
}
export const TechButton: React.FC<TechButtonProps> = ({
children,
onClick,
active = false,
variant = 'blue',
className = '',
disabled = false,
title
}) => {
const colors = {
blue: 'from-blue-600 to-cyan-600 hover:shadow-glow-blue border-cyan-400/30',
red: 'from-red-600 to-pink-600 hover:shadow-glow-red border-red-400/30',
amber: 'from-amber-500 to-orange-600 hover:shadow-orange-500/50 border-orange-400/30',
green: 'from-emerald-500 to-green-600 hover:shadow-green-500/50 border-green-400/30',
default: 'from-slate-600 to-slate-500 hover:shadow-slate-500/50 border-slate-400/30',
danger: 'from-red-600 to-pink-600 hover:shadow-glow-red border-red-400/30'
};
const variantKey = variant === 'danger' ? 'red' : (variant === 'default' ? 'blue' : variant);
return (
<button
onClick={onClick}
disabled={disabled}
title={title}
className={`
relative px-4 py-2 font-tech font-bold tracking-wider uppercase transition-all duration-300
clip-tech border-b-2 border-r-2
${disabled
? 'opacity-50 cursor-not-allowed bg-slate-900 text-slate-600 border-slate-800'
: (active
? `bg-gradient-to-r ${colors[variantKey]} text-white`
: 'bg-slate-800/50 text-slate-400 hover:text-white hover:bg-slate-700/50 border-slate-600')
}
${className}
`}
>
{active && !disabled && <div className="absolute inset-0 bg-white/20 animate-pulse pointer-events-none"></div>}
{children}
</button>
);
};

View File

@@ -0,0 +1,31 @@
import React from 'react';
import { RobotTarget } from '../../types';
interface FooterProps {
isHostConnected: boolean;
robotTarget: RobotTarget;
}
export const Footer: React.FC<FooterProps> = ({ isHostConnected, robotTarget }) => {
return (
<footer className="absolute bottom-0 left-0 right-0 h-10 bg-black/80 border-t border-neon-blue/30 flex items-center px-6 justify-between z-40 backdrop-blur text-xs font-mono text-slate-400">
<div className="flex gap-6">
{['PLC', 'MOTION', 'VISION', 'LIGHT'].map(hw => (
<div key={hw} className="flex items-center gap-2">
<div className="w-2 h-2 bg-neon-green rounded-full shadow-[0_0_5px_#0aff00]"></div>
<span className="font-bold text-slate-300">{hw}</span>
</div>
))}
<div className="flex items-center gap-2">
<div className={`w-2 h-2 rounded-full transition-all ${isHostConnected ? 'bg-neon-green shadow-[0_0_5px_#0aff00]' : 'bg-red-500 shadow-[0_0_5px_#ff0000] animate-pulse'}`}></div>
<span className={`font-bold ${isHostConnected ? 'text-slate-300' : 'text-red-400'}`}>HOST</span>
</div>
</div>
<div className="flex gap-8 text-neon-blue">
<span>POS.X: {robotTarget.x.toFixed(3)}</span>
<span>POS.Y: {robotTarget.y.toFixed(3)}</span>
<span>POS.Z: {robotTarget.z.toFixed(3)}</span>
</div>
</footer>
);
};

View File

@@ -0,0 +1,101 @@
import React from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Activity, Settings, Move, Camera, Layers, Cpu, Target } from 'lucide-react';
interface HeaderProps {
currentTime: Date;
onTabChange: (tab: 'recipe' | 'motion' | 'camera' | 'setting' | 'initialize' | null) => void;
activeTab: 'recipe' | 'motion' | 'camera' | 'setting' | 'initialize' | null;
}
export const Header: React.FC<HeaderProps> = ({ currentTime, onTabChange, activeTab }) => {
const navigate = useNavigate();
const location = useLocation();
const isWebView = typeof window !== 'undefined' && !!window.chrome?.webview;
const isIOPage = location.pathname === '/io-monitor';
return (
<header className="absolute top-0 left-0 right-0 h-20 px-6 flex items-center justify-between z-40 bg-gradient-to-b from-black/80 to-transparent pointer-events-none">
<div
className="flex items-center gap-4 pointer-events-auto cursor-pointer group"
onClick={() => {
navigate('/');
onTabChange(null);
}}
>
<div className="w-12 h-12 border-2 border-neon-blue flex items-center justify-center rounded shadow-glow-blue bg-black/50 backdrop-blur group-hover:bg-neon-blue/10 transition-colors">
<Cpu className="text-neon-blue w-8 h-8 animate-pulse-slow" />
</div>
<div>
<h1 className="text-3xl font-tech font-bold text-white tracking-widest uppercase italic text-shadow-glow-blue group-hover:text-neon-blue transition-colors">
EQUI-HANDLER <span className="text-neon-blue text-sm not-italic">PRO</span>
</h1>
<div className="flex gap-2 text-[10px] text-neon-blue/70 font-mono">
<span>SYS.VER 4.2.0</span>
<span>|</span>
<span className={isWebView ? "text-neon-green" : "text-amber-500"}>
LINK: {isWebView ? "NATIVE" : "SIMULATION"}
</span>
</div>
</div>
</div>
{/* Top Navigation */}
<div className="flex items-center gap-2 pointer-events-auto">
{/* IO Tab Switcher (only on IO page) */}
<div className="bg-black/40 backdrop-blur-md p-1 rounded-full border border-white/10 flex gap-1">
{[
{ id: 'recipe', icon: Layers, label: 'RECIPE', path: '/' },
{ id: 'io', icon: Activity, label: 'I/O MONITOR', path: '/io-monitor' },
{ id: 'motion', icon: Move, label: 'MOTION', path: '/' },
{ id: 'camera', icon: Camera, label: 'VISION', path: '/' },
{ id: 'setting', icon: Settings, label: 'CONFIG', path: '/' },
{ id: 'initialize', icon: Target, label: 'INITIALIZE', path: '/' }
].map(item => {
const isActive = item.id === 'io'
? location.pathname === '/io-monitor'
: activeTab === item.id;
return (
<button
key={item.id}
onClick={() => {
if (item.id === 'io') {
navigate('/io-monitor');
onTabChange(null);
} else {
if (location.pathname !== '/') {
navigate('/');
}
onTabChange(activeTab === item.id ? null : item.id as any);
}
}}
className={`
flex items-center gap-2 px-6 py-2 rounded-full font-tech font-bold text-sm transition-all border border-transparent
${isActive
? 'bg-neon-blue/10 text-neon-blue border-neon-blue shadow-glow-blue'
: 'text-slate-400 hover:text-white hover:bg-white/5'}
`}
>
<item.icon className="w-4 h-4" /> {item.label}
</button>
);
})}
</div>
</div>
<div className="text-right pointer-events-auto">
<div className="text-2xl font-mono font-bold text-white text-shadow-glow-blue">
{currentTime.toLocaleTimeString('en-GB')}
</div>
<div className="text-xs font-tech text-slate-400 tracking-[0.3em]">
{currentTime.toLocaleDateString().toUpperCase()}
</div>
</div>
</header>
);
};

View File

@@ -0,0 +1,61 @@
import React from 'react';
import { Header } from './Header';
import { Footer } from './Footer';
import { RobotTarget } from '../../types';
interface LayoutProps {
children: React.ReactNode;
currentTime: Date;
isHostConnected: boolean;
robotTarget: RobotTarget;
onTabChange: (tab: 'recipe' | 'motion' | 'camera' | 'setting' | 'initialize' | null) => void;
activeTab: 'recipe' | 'motion' | 'camera' | 'setting' | 'initialize' | null;
isLoading: boolean;
}
export const Layout: React.FC<LayoutProps> = ({
children,
currentTime,
isHostConnected,
robotTarget,
onTabChange,
activeTab,
isLoading
}) => {
return (
<div className="relative w-screen h-screen bg-slate-950 text-slate-100 overflow-hidden font-sans">
{/* Animated Nebula Background */}
<div className="absolute inset-0 bg-gradient-to-br from-slate-950 via-[#050a15] to-[#0a0f20] animate-gradient bg-[length:400%_400%] z-0"></div>
<div className="absolute inset-0 grid-bg opacity-30 z-0"></div>
<div className="absolute inset-0 scanlines z-50 pointer-events-none"></div>
{/* LOADING OVERLAY */}
{isLoading && (
<div className="absolute inset-0 z-[100] bg-black flex flex-col items-center justify-center gap-6">
<div className="relative">
<div className="w-24 h-24 border-4 border-neon-blue/30 rounded-full animate-spin"></div>
<div className="absolute inset-0 border-t-4 border-neon-blue rounded-full animate-spin"></div>
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-neon-blue text-2xl font-tech font-bold"></div>
</div>
<div className="text-center">
<h2 className="text-2xl font-tech font-bold text-white tracking-widest mb-2">SYSTEM INITIALIZING</h2>
<p className="font-mono text-neon-blue text-sm animate-pulse">ESTABLISHING CONNECTION...</p>
</div>
</div>
)}
<Header
currentTime={currentTime}
onTabChange={onTabChange}
activeTab={activeTab}
/>
{/* Main Content Area */}
<div className="absolute inset-0 pt-20 pb-10 z-10">
{children}
</div>
<Footer isHostConnected={isHostConnected} robotTarget={robotTarget} />
</div>
);
};

108
FrontEnd/index.css Normal file
View File

@@ -0,0 +1,108 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 4px;
height: 4px;
}
::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.2);
}
::-webkit-scrollbar-thumb {
background: rgba(0, 243, 255, 0.3);
border-radius: 2px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(0, 243, 255, 0.6);
}
/* Holographic Glass */
.glass-holo {
background: linear-gradient(135deg, rgba(10, 15, 30, 0.7) 0%, rgba(20, 30, 50, 0.5) 100%);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(0, 243, 255, 0.1);
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.5);
position: relative;
overflow: hidden;
}
.glass-holo::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 1px;
background: linear-gradient(90deg, transparent, rgba(0, 243, 255, 0.5), transparent);
}
/* Active Element */
.glass-active {
background: rgba(0, 243, 255, 0.1);
border: 1px solid rgba(0, 243, 255, 0.4);
box-shadow: 0 0 15px rgba(0, 243, 255, 0.2);
}
/* Text Glows */
.text-glow-blue {
color: #00f3ff;
text-shadow: 0 0 8px rgba(0, 243, 255, 0.6);
}
.text-glow-purple {
color: #bc13fe;
text-shadow: 0 0 8px rgba(188, 19, 254, 0.6);
}
.text-glow-red {
color: #ff0055;
text-shadow: 0 0 8px rgba(255, 0, 85, 0.6);
}
.text-glow-green {
color: #0aff00;
text-shadow: 0 0 8px rgba(10, 255, 0, 0.6);
}
/* Grid Background */
.grid-bg {
background-size: 50px 50px;
background-image:
linear-gradient(to right, rgba(0, 243, 255, 0.05) 1px, transparent 1px),
linear-gradient(to bottom, rgba(0, 243, 255, 0.05) 1px, transparent 1px);
mask-image: radial-gradient(circle at center, black 40%, transparent 100%);
}
/* CRT Scanline Effect */
.scanlines {
background: linear-gradient(to bottom,
rgba(255, 255, 255, 0),
rgba(255, 255, 255, 0) 50%,
rgba(0, 0, 0, 0.2) 50%,
rgba(0, 0, 0, 0.2));
background-size: 100% 4px;
pointer-events: none;
}
/* Tech Clip Path */
.clip-tech {
clip-path: polygon(0 0,
100% 0,
100% calc(100% - 10px),
calc(100% - 10px) 100%,
0 100%);
}
.clip-tech-inv {
clip-path: polygon(10px 0,
100% 0,
100% 100%,
0 100%,
0 10px);
}

197
FrontEnd/index.html Normal file
View File

@@ -0,0 +1,197 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Industrial HMI - Holographic</title>
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&family=Rajdhani:wght@500;600;700&display=swap" rel="stylesheet">
<script type="importmap">
{
"imports": {
"react-dom/client": "https://esm.sh/react-dom@18.2.0/client",
"react-dom": "https://esm.sh/react-dom@18.2.0",
"react/jsx-runtime": "https://esm.sh/react@18.2.0/jsx-runtime",
"react": "https://esm.sh/react@18.2.0",
"three": "https://esm.sh/three@0.160.0",
"@react-three/fiber": "https://esm.sh/@react-three/fiber@8.15.12?external=react,react-dom,three",
"@react-three/drei": "https://esm.sh/@react-three/drei@9.96.1?external=react,react-dom,three,@react-three/fiber",
"lucide-react": "https://esm.sh/lucide-react@0.303.0?external=react",
"clsx": "https://esm.sh/clsx@2.1.0",
"tailwind-merge": "https://esm.sh/tailwind-merge@2.2.0",
"path": "https://aistudiocdn.com/path@^0.12.7",
"react/": "https://aistudiocdn.com/react@^19.2.0/",
"react-dom/": "https://aistudiocdn.com/react-dom@^19.2.0/",
"vite": "https://aistudiocdn.com/vite@^7.2.4",
"@vitejs/plugin-react": "https://aistudiocdn.com/@vitejs/plugin-react@^5.1.1",
"url": "https://aistudiocdn.com/url@^0.11.4"
}
}
</script>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
mono: ['Rajdhani', 'monospace'],
tech: ['Rajdhani', 'sans-serif'],
},
colors: {
slate: {
850: '#1e293b',
900: '#0f172a',
950: '#020617',
},
neon: {
blue: '#00f3ff',
purple: '#bc13fe',
pink: '#ff0099',
green: '#0aff00',
yellow: '#ffe600',
}
},
boxShadow: {
'glow-blue': '0 0 20px rgba(0, 243, 255, 0.3), inset 0 0 10px rgba(0, 243, 255, 0.1)',
'glow-purple': '0 0 20px rgba(188, 19, 254, 0.4), inset 0 0 10px rgba(188, 19, 254, 0.1)',
'glow-red': '0 0 30px rgba(255, 0, 0, 0.5)',
'hologram': '0 0 15px rgba(6, 182, 212, 0.15), inset 0 0 20px rgba(6, 182, 212, 0.05)',
},
animation: {
'pulse-slow': 'pulse 4s cubic-bezier(0.4, 0, 0.6, 1) infinite',
'glow': 'glow 2s ease-in-out infinite alternate',
'gradient': 'gradient 15s ease infinite',
'scan': 'scan 4s linear infinite',
'spin-slow': 'spin 10s linear infinite',
},
keyframes: {
glow: {
'0%': { boxShadow: '0 0 5px rgba(0, 243, 255, 0.2)' },
'100%': { boxShadow: '0 0 20px rgba(0, 243, 255, 0.6), 0 0 10px rgba(0, 243, 255, 0.4)' },
},
gradient: {
'0%': { backgroundPosition: '0% 50%' },
'50%': { backgroundPosition: '100% 50%' },
'100%': { backgroundPosition: '0% 50%' },
},
scan: {
'0%': { transform: 'translateY(-100%)' },
'100%': { transform: 'translateY(100%)' },
}
}
}
}
}
</script>
<style>
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 4px;
height: 4px;
}
::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.2);
}
::-webkit-scrollbar-thumb {
background: rgba(0, 243, 255, 0.3);
border-radius: 2px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(0, 243, 255, 0.6);
}
/* Holographic Glass */
.glass-holo {
background: linear-gradient(135deg, rgba(10, 15, 30, 0.7) 0%, rgba(20, 30, 50, 0.5) 100%);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(0, 243, 255, 0.1);
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.5);
position: relative;
overflow: hidden;
}
.glass-holo::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0; height: 1px;
background: linear-gradient(90deg, transparent, rgba(0, 243, 255, 0.5), transparent);
}
/* Active Element */
.glass-active {
background: rgba(0, 243, 255, 0.1);
border: 1px solid rgba(0, 243, 255, 0.4);
box-shadow: 0 0 15px rgba(0, 243, 255, 0.2);
}
/* Text Glows */
.text-glow-blue {
color: #00f3ff;
text-shadow: 0 0 8px rgba(0, 243, 255, 0.6);
}
.text-glow-purple {
color: #bc13fe;
text-shadow: 0 0 8px rgba(188, 19, 254, 0.6);
}
.text-glow-red {
color: #ff0055;
text-shadow: 0 0 8px rgba(255, 0, 85, 0.6);
}
.text-glow-green {
color: #0aff00;
text-shadow: 0 0 8px rgba(10, 255, 0, 0.6);
}
/* Grid Background */
.grid-bg {
background-size: 50px 50px;
background-image:
linear-gradient(to right, rgba(0, 243, 255, 0.05) 1px, transparent 1px),
linear-gradient(to bottom, rgba(0, 243, 255, 0.05) 1px, transparent 1px);
mask-image: radial-gradient(circle at center, black 40%, transparent 100%);
}
/* CRT Scanline Effect */
.scanlines {
background: linear-gradient(
to bottom,
rgba(255,255,255,0),
rgba(255,255,255,0) 50%,
rgba(0,0,0,0.2) 50%,
rgba(0,0,0,0.2)
);
background-size: 100% 4px;
pointer-events: none;
}
/* Tech Clip Path */
.clip-tech {
clip-path: polygon(
0 0,
100% 0,
100% calc(100% - 10px),
calc(100% - 10px) 100%,
0 100%
);
}
.clip-tech-inv {
clip-path: polygon(
10px 0,
100% 0,
100% 100%,
0 100%,
0 10px
);
}
</style>
<link rel="stylesheet" href="/index.css">
</head>
<body class="bg-black text-slate-50 overflow-hidden font-sans antialiased selection:bg-neon-blue/30">
<div id="root"></div>
<script type="module" src="/index.tsx"></script>
</body>
</html>

22
FrontEnd/index.tsx Normal file
View File

@@ -0,0 +1,22 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import '@fontsource/inter/300.css';
import '@fontsource/inter/400.css';
import '@fontsource/inter/500.css';
import '@fontsource/rajdhani/500.css';
import '@fontsource/rajdhani/600.css';
import '@fontsource/rajdhani/700.css';
import './index.css';
const rootElement = document.getElementById('root');
if (!rootElement) {
throw new Error("Could not find root element to mount to");
}
const root = ReactDOM.createRoot(rootElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

7
FrontEnd/metadata.json Normal file
View File

@@ -0,0 +1,7 @@
{
"name": "Industrial HMI 3D",
"description": "A Next-Gen Human Machine Interface with 3D simulation, motion control, and I/O monitoring.",
"requestFramePermissions": [
"camera"
]
}

3556
FrontEnd/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

35
FrontEnd/package.json Normal file
View File

@@ -0,0 +1,35 @@
{
"name": "industrial-hmi-3d",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"@fontsource/inter": "^5.2.8",
"@fontsource/rajdhani": "^5.2.7",
"@react-three/drei": "^9.96.1",
"@react-three/fiber": "^8.15.12",
"clsx": "^2.1.0",
"lucide-react": "^0.303.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^7.9.6",
"tailwind-merge": "^2.2.0",
"three": "^0.160.0"
},
"devDependencies": {
"@types/react": "^18.2.43",
"@types/react-dom": "^18.2.17",
"@types/three": "^0.160.0",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.16",
"postcss": "^8.4.32",
"tailwindcss": "^3.4.0",
"typescript": "^5.3.3",
"vite": "^5.0.10"
}
}

163
FrontEnd/pages/HomePage.tsx Normal file
View File

@@ -0,0 +1,163 @@
import React, { useState, useEffect } from 'react';
import { Play, Square, RotateCw, AlertTriangle, Siren, Terminal } from 'lucide-react';
import { Machine3D } from '../components/Machine3D';
import { SettingsModal } from '../components/SettingsModal';
import { InitializeModal } from '../components/InitializeModal';
import { RecipePanel } from '../components/RecipePanel';
import { MotionPanel } from '../components/MotionPanel';
import { CameraPanel } from '../components/CameraPanel';
import { CyberPanel } from '../components/common/CyberPanel';
import { TechButton } from '../components/common/TechButton';
import { ModelInfoPanel } from '../components/ModelInfoPanel';
import { SystemState, Recipe, IOPoint, LogEntry, RobotTarget, ConfigItem } from '../types';
interface HomePageProps {
systemState: SystemState;
currentRecipe: Recipe;
robotTarget: RobotTarget;
logs: LogEntry[];
ioPoints: IOPoint[];
doorStates: { front: boolean; right: boolean; left: boolean; back: boolean };
isLowPressure: boolean;
isEmergencyStop: boolean;
activeTab: 'recipe' | 'motion' | 'camera' | 'setting' | 'initialize' | null;
onSelectRecipe: (r: Recipe) => void;
onMove: (axis: 'X' | 'Y' | 'Z', val: number) => void;
onControl: (action: 'start' | 'stop' | 'reset') => void;
onSaveConfig: (config: ConfigItem[]) => void;
onCloseTab: () => void;
videoRef: React.RefObject<HTMLVideoElement>;
}
export const HomePage: React.FC<HomePageProps> = ({
systemState,
currentRecipe,
robotTarget,
logs,
ioPoints,
doorStates,
isLowPressure,
isEmergencyStop,
activeTab,
onSelectRecipe,
onMove,
onControl,
onSaveConfig,
onCloseTab,
videoRef
}) => {
useEffect(() => {
if (activeTab === 'camera' && navigator.mediaDevices?.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then(s => { if (videoRef.current) videoRef.current.srcObject = s });
}
}, [activeTab, videoRef]);
return (
<main className="relative w-full h-full flex gap-6 px-6">
{/* 3D Canvas (Background Layer) */}
<div className="absolute inset-0 z-0">
<Machine3D target={robotTarget} ioState={ioPoints} doorStates={doorStates} />
</div>
{/* Center Alarms */}
<div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-50 pointer-events-none flex flex-col items-center gap-4">
{isEmergencyStop && (
<div className="bg-red-600/90 text-white p-8 border-4 border-red-500 shadow-glow-red flex items-center gap-6 animate-pulse">
<Siren className="w-16 h-16 animate-spin" />
<div>
<h1 className="text-5xl font-tech font-bold tracking-widest">EMERGENCY STOP</h1>
<p className="text-center font-mono text-lg">SYSTEM HALTED - RELEASE TO RESET</p>
</div>
</div>
)}
{isLowPressure && !isEmergencyStop && (
<div className="bg-amber-500/80 text-black px-8 py-4 rounded font-bold text-2xl tracking-widest flex items-center gap-4 shadow-glow-red animate-bounce">
<AlertTriangle className="w-8 h-8" /> LOW AIR PRESSURE WARNING
</div>
)}
</div>
{/* Floating Panel (Left) */}
{activeTab && activeTab !== 'setting' && activeTab !== 'recipe' && (
<div className="w-[450px] z-20 animate-in slide-in-from-left-20 duration-500 fade-in">
<CyberPanel className="h-full flex flex-col">
{activeTab === 'motion' && <MotionPanel robotTarget={robotTarget} onMove={onMove} />}
{activeTab === 'camera' && <CameraPanel videoRef={videoRef} />}
</CyberPanel>
</div>
)}
{/* Recipe Selection Modal */}
<RecipePanel
isOpen={activeTab === 'recipe'}
currentRecipe={currentRecipe}
onSelectRecipe={onSelectRecipe}
onClose={onCloseTab}
/>
{/* Settings Modal */}
<SettingsModal
isOpen={activeTab === 'setting'}
onClose={onCloseTab}
onSave={onSaveConfig}
/>
{/* Initialize Modal */}
<InitializeModal
isOpen={activeTab === 'initialize'}
onClose={onCloseTab}
/>
{/* Right Sidebar (Dashboard) */}
<div className="w-80 ml-auto z-20 flex flex-col gap-4">
<ModelInfoPanel currentRecipe={currentRecipe} />
<CyberPanel className="flex-none">
<div className="mb-2 text-xs text-neon-blue font-bold tracking-widest uppercase">System Status</div>
<div className={`text-3xl font-tech font-bold mb-4 ${systemState === SystemState.RUNNING ? 'text-neon-green text-shadow-glow-green' : 'text-slate-400'}`}>
{systemState}
</div>
<div className="space-y-3">
<TechButton
variant="green"
className="w-full flex items-center justify-center gap-2"
active={systemState === SystemState.RUNNING}
onClick={() => onControl('start')}
>
<Play className="w-4 h-4" /> START AUTO
</TechButton>
<TechButton
variant="amber"
className="w-full flex items-center justify-center gap-2"
active={systemState === SystemState.PAUSED}
onClick={() => onControl('stop')}
>
<Square className="w-4 h-4 fill-current" /> STOP / PAUSE
</TechButton>
<TechButton
className="w-full flex items-center justify-center gap-2"
onClick={() => onControl('reset')}
>
<RotateCw className="w-4 h-4" /> SYSTEM RESET
</TechButton>
</div>
</CyberPanel>
<CyberPanel className="flex-1 flex flex-col min-h-0">
<div className="mb-2 flex items-center justify-between text-xs text-neon-blue font-bold tracking-widest uppercase border-b border-white/10 pb-2">
<span>Event Log</span>
<Terminal className="w-3 h-3" />
</div>
<div className="flex-1 overflow-y-auto font-mono text-[10px] space-y-1 pr-1 custom-scrollbar">
{logs.map(log => (
<div key={log.id} className={`flex gap-2 ${log.type === 'error' ? 'text-red-500' : log.type === 'warning' ? 'text-amber-400' : 'text-slate-400'}`}>
<span className="opacity-50">[{log.timestamp}]</span>
<span>{log.message}</span>
</div>
))}
</div>
</CyberPanel>
</div>
</main>
);
};

View File

@@ -0,0 +1,125 @@
import React, { useState, useEffect } from 'react';
import { RotateCw } from 'lucide-react';
import { IOPoint } from '../types';
import { comms } from '../communication';
interface IOMonitorPageProps {
onToggle: (id: number, type: 'input' | 'output') => void;
}
export const IOMonitorPage: React.FC<IOMonitorPageProps> = ({ onToggle }) => {
const [ioPoints, setIoPoints] = useState<IOPoint[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [activeIOTab, setActiveIOTab] = useState<'in' | 'out'>('in');
// Fetch initial IO list when page mounts
useEffect(() => {
const fetchIOList = async () => {
setIsLoading(true);
try {
const ioStr = await comms.getIOList();
const ioData: IOPoint[] = JSON.parse(ioStr);
setIoPoints(ioData);
} catch (e) {
console.error('Failed to fetch IO list:', e);
}
setIsLoading(false);
};
fetchIOList();
// Subscribe to real-time IO updates
const unsubscribe = comms.subscribe((msg: any) => {
if (msg?.type === 'STATUS_UPDATE' && msg.ioState) {
setIoPoints(prev => {
const newIO = [...prev];
msg.ioState.forEach((update: { id: number, type: string, state: boolean }) => {
const idx = newIO.findIndex(p => p.id === update.id && p.type === update.type);
if (idx >= 0) newIO[idx] = { ...newIO[idx], state: update.state };
});
return newIO;
});
}
});
return () => {
unsubscribe();
};
}, []);
const points = ioPoints.filter(p => p.type === (activeIOTab === 'in' ? 'input' : 'output'));
return (
<main className="relative w-full h-full px-6 pt-6 pb-20">
<div className="glass-holo p-6 h-full flex flex-col gap-4">
{/* Local Header / Controls */}
<div className="flex items-center justify-between shrink-0">
<div className="flex items-center gap-4">
<h2 className="text-2xl font-tech font-bold text-white tracking-wider">
SYSTEM I/O MONITOR
</h2>
<div className="h-6 w-px bg-white/20"></div>
<div className="text-sm font-mono text-neon-blue">
TOTAL POINTS: {ioPoints.length}
</div>
</div>
<div className="bg-black/40 backdrop-blur-md p-1 rounded-full border border-white/10 flex gap-1">
<button
onClick={() => setActiveIOTab('in')}
className={`px-6 py-2 rounded-full font-tech font-bold text-sm transition-all ${activeIOTab === 'in' ? 'bg-neon-yellow/20 text-neon-yellow border border-neon-yellow shadow-[0_0_15px_rgba(255,230,0,0.3)]' : 'text-slate-400 hover:text-white hover:bg-white/5'}`}
>
INPUTS ({ioPoints.filter(p => p.type === 'input').length})
</button>
<button
onClick={() => setActiveIOTab('out')}
className={`px-6 py-2 rounded-full font-tech font-bold text-sm transition-all ${activeIOTab === 'out' ? 'bg-neon-green/20 text-neon-green border border-neon-green shadow-[0_0_15px_rgba(10,255,0,0.3)]' : 'text-slate-400 hover:text-white hover:bg-white/5'}`}
>
OUTPUTS ({ioPoints.filter(p => p.type === 'output').length})
</button>
</div>
</div>
<div className="bg-slate-950/40 backdrop-blur-md flex-1 overflow-y-auto custom-scrollbar rounded-lg border border-white/5">
{isLoading ? (
<div className="h-full flex flex-col items-center justify-center gap-4 animate-pulse">
<RotateCw className="w-16 h-16 text-neon-blue animate-spin" />
<div className="text-xl font-tech text-neon-blue tracking-widest">LOADING IO POINTS...</div>
</div>
) : (
<div className="grid grid-cols-2 gap-x-8 gap-y-2 p-4">
{points.map(p => (
<div
key={p.id}
onClick={() => onToggle(p.id, p.type)}
className={`
flex items-center gap-4 px-4 py-3 cursor-pointer transition-all border
clip-tech-sm group hover:translate-x-1
${p.state
? (p.type === 'output'
? 'bg-neon-green/10 border-neon-green text-neon-green shadow-[0_0_15px_rgba(10,255,0,0.2)]'
: 'bg-neon-yellow/10 border-neon-yellow text-neon-yellow shadow-[0_0_15px_rgba(255,230,0,0.2)]')
: 'bg-slate-900/40 border-slate-800 text-slate-500 hover:border-slate-600 hover:bg-slate-800/40'}
`}
>
{/* LED Indicator */}
<div className={`w-3 h-3 rounded-full shrink-0 transition-all ${p.state ? (p.type === 'output' ? 'bg-neon-green shadow-[0_0_8px_#0aff00]' : 'bg-neon-yellow shadow-[0_0_8px_#ffe600]') : 'bg-slate-800 border border-slate-700'}`}></div>
{/* ID Badge */}
<div className={`w-12 font-mono font-bold text-lg ${p.state ? 'text-white' : 'text-slate-600'}`}>
{p.type === 'input' ? 'I' : 'Q'}{p.id.toString().padStart(2, '0')}
</div>
{/* Name */}
<div className={`flex-1 font-bold uppercase tracking-wide truncate ${p.state ? 'text-white' : 'text-slate-500'} group-hover:text-white transition-colors`}>
{p.name}
</div>
</div>
))}
</div>
)}
</div>
</div>
</main>
);
};

View File

@@ -0,0 +1,245 @@
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Layers, Plus, Trash2, Copy, Save, ArrowLeft, FileText, Calendar } from 'lucide-react';
import { Recipe } from '../types';
import { comms } from '../communication';
import { TechButton } from '../components/common/TechButton';
export const RecipePage: React.FC = () => {
const navigate = useNavigate();
const [recipes, setRecipes] = useState<Recipe[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [editedRecipe, setEditedRecipe] = useState<Recipe | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const loadRecipes = async () => {
try {
const recipeStr = await comms.getRecipeList();
const recipeData = JSON.parse(recipeStr);
setRecipes(recipeData);
if (recipeData.length > 0) {
setSelectedId(recipeData[0].id);
setEditedRecipe(recipeData[0]);
}
} catch (e) {
console.error("Failed to load recipes", e);
}
setIsLoading(false);
};
loadRecipes();
}, []);
const handleSelect = (r: Recipe) => {
setSelectedId(r.id);
setEditedRecipe({ ...r });
};
const handleSave = async () => {
// Mock Save Logic
console.log("Saving recipe:", editedRecipe);
// In real app: await comms.saveRecipe(editedRecipe);
};
const handleCopy = async () => {
if (!selectedId) return;
const selectedRecipe = recipes.find(r => r.id === selectedId);
if (!selectedRecipe) return;
const newName = prompt(`Copy "${selectedRecipe.name}" as:`, `${selectedRecipe.name}_Copy`);
if (!newName || newName.trim() === '') return;
try {
const result = await comms.copyRecipe(selectedId, newName.trim());
if (result.success && result.newRecipe) {
const newRecipeList = [...recipes, result.newRecipe];
setRecipes(newRecipeList);
setSelectedId(result.newRecipe.id);
setEditedRecipe(result.newRecipe);
console.log("Recipe copied successfully:", result.newRecipe);
} else {
alert(`Failed to copy recipe: ${result.message}`);
}
} catch (error: any) {
alert(`Error copying recipe: ${error.message || 'Unknown error'}`);
console.error('Recipe copy error:', error);
}
};
const handleDelete = async () => {
if (!selectedId) return;
const selectedRecipe = recipes.find(r => r.id === selectedId);
if (!selectedRecipe) return;
const confirmed = window.confirm(`Are you sure you want to delete "${selectedRecipe.name}"?`);
if (!confirmed) return;
try {
const result = await comms.deleteRecipe(selectedId);
if (result.success) {
const newRecipeList = recipes.filter(r => r.id !== selectedId);
setRecipes(newRecipeList);
// Select first recipe or clear selection
if (newRecipeList.length > 0) {
setSelectedId(newRecipeList[0].id);
setEditedRecipe(newRecipeList[0]);
} else {
setSelectedId(null);
setEditedRecipe(null);
}
console.log("Recipe deleted successfully");
} else {
alert(`Failed to delete recipe: ${result.message}`);
}
} catch (error: any) {
alert(`Error deleting recipe: ${error.message || 'Unknown error'}`);
console.error('Recipe delete error:', error);
}
};
return (
<div className="w-full h-full p-6 flex flex-col gap-4">
{/* Header */}
<div className="flex items-center justify-between shrink-0">
<div className="flex items-center gap-4">
<button
onClick={() => navigate('/')}
className="p-2 rounded-full hover:bg-white/10 text-slate-400 hover:text-white transition-colors"
>
<ArrowLeft className="w-6 h-6" />
</button>
<h1 className="text-2xl font-tech font-bold text-white tracking-wider flex items-center gap-3">
<Layers className="text-neon-blue" /> RECIPE MANAGEMENT
</h1>
</div>
<div className="text-sm font-mono text-slate-400">
TOTAL: <span className="text-neon-blue">{recipes.length}</span>
</div>
</div>
<div className="flex-1 flex gap-6 min-h-0">
{/* Left: Recipe List */}
<div className="w-80 flex flex-col gap-4">
<div className="bg-slate-950/40 backdrop-blur-md border border-white/10 rounded-lg flex-1 overflow-hidden flex flex-col">
<div className="p-3 border-b border-white/10 bg-white/5 font-bold text-sm tracking-wider text-slate-300">
RECIPE LIST
</div>
<div className="flex-1 overflow-y-auto p-2 space-y-2 custom-scrollbar">
{recipes.map(r => (
<div
key={r.id}
onClick={() => handleSelect(r)}
className={`
p-3 rounded border cursor-pointer transition-all group
${selectedId === r.id
? 'bg-neon-blue/20 border-neon-blue text-white shadow-glow-blue'
: 'bg-white/5 border-white/5 text-slate-400 hover:bg-white/10 hover:border-white/20'}
`}
>
<div className="font-bold text-sm mb-1">{r.name}</div>
<div className="text-[10px] font-mono opacity-60 flex items-center gap-2">
<Calendar className="w-3 h-3" /> {r.lastModified}
</div>
</div>
))}
</div>
{/* List Actions */}
<div className="p-3 border-t border-white/10 bg-black/20 grid grid-cols-3 gap-2">
<TechButton variant="default" className="flex justify-center" title="Add New">
<Plus className="w-4 h-4" />
</TechButton>
<TechButton
variant="default"
className="flex justify-center"
title="Copy Selected"
onClick={handleCopy}
disabled={!selectedId}
>
<Copy className="w-4 h-4" />
</TechButton>
<TechButton
variant="danger"
className="flex justify-center"
title="Delete Selected"
onClick={handleDelete}
disabled={!selectedId}
>
<Trash2 className="w-4 h-4" />
</TechButton>
</div>
</div>
</div>
{/* Right: Editor */}
<div className="flex-1 bg-slate-950/40 backdrop-blur-md border border-white/10 rounded-lg flex flex-col overflow-hidden">
<div className="p-3 border-b border-white/10 bg-white/5 font-bold text-sm tracking-wider text-slate-300 flex justify-between items-center">
<span>RECIPE EDITOR</span>
{editedRecipe && <span className="text-neon-blue font-mono">{editedRecipe.id}</span>}
</div>
<div className="flex-1 p-6 overflow-y-auto custom-scrollbar">
{editedRecipe ? (
<div className="max-w-2xl space-y-6">
<div className="space-y-2">
<label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Recipe Name</label>
<input
type="text"
value={editedRecipe.name}
onChange={(e) => setEditedRecipe({ ...editedRecipe, name: e.target.value })}
className="w-full bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono"
/>
</div>
<div className="space-y-2">
<label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Description</label>
<textarea
className="w-full h-32 bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono resize-none"
placeholder="Enter recipe description..."
></textarea>
</div>
<div className="grid grid-cols-2 gap-6">
<div className="space-y-2">
<label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Process Time (sec)</label>
<input type="number" className="w-full bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono" defaultValue="120" />
</div>
<div className="space-y-2">
<label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Temperature (°C)</label>
<input type="number" className="w-full bg-black/40 border border-white/10 rounded px-4 py-3 text-white focus:border-neon-blue focus:outline-none transition-colors font-mono" defaultValue="24.5" />
</div>
</div>
{/* Placeholder for more parameters */}
<div className="p-4 border border-dashed border-white/10 rounded bg-white/5 text-center text-slate-500 text-sm">
Additional process parameters would go here...
</div>
</div>
) : (
<div className="h-full flex flex-col items-center justify-center text-slate-500">
<FileText className="w-16 h-16 mb-4 opacity-20" />
<p>Select a recipe to edit</p>
</div>
)}
</div>
{/* Editor Actions */}
<div className="p-4 border-t border-white/10 bg-black/20 flex justify-end">
<TechButton
variant="green"
className="flex items-center gap-2 px-8"
onClick={handleSave}
disabled={!editedRecipe}
>
<Save className="w-4 h-4" /> SAVE CHANGES
</TechButton>
</div>
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

3
FrontEnd/run.bat Normal file
View File

@@ -0,0 +1,3 @@
@echo off
echo Starting Frontend Dev Server...
call npm run dev

View File

@@ -0,0 +1,59 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
mono: ['Rajdhani', 'monospace'],
tech: ['Rajdhani', 'sans-serif'],
},
colors: {
slate: {
850: '#1e293b',
900: '#0f172a',
950: '#020617',
},
neon: {
blue: '#00f3ff',
purple: '#bc13fe',
pink: '#ff0099',
green: '#0aff00',
yellow: '#ffe600',
}
},
boxShadow: {
'glow-blue': '0 0 20px rgba(0, 243, 255, 0.3), inset 0 0 10px rgba(0, 243, 255, 0.1)',
'glow-purple': '0 0 20px rgba(188, 19, 254, 0.4), inset 0 0 10px rgba(188, 19, 254, 0.1)',
'glow-red': '0 0 30px rgba(255, 0, 0, 0.5)',
'hologram': '0 0 15px rgba(6, 182, 212, 0.15), inset 0 0 20px rgba(6, 182, 212, 0.05)',
},
animation: {
'pulse-slow': 'pulse 4s cubic-bezier(0.4, 0, 0.6, 1) infinite',
'glow': 'glow 2s ease-in-out infinite alternate',
'gradient': 'gradient 15s ease infinite',
'scan': 'scan 4s linear infinite',
'spin-slow': 'spin 10s linear infinite',
},
keyframes: {
glow: {
'0%': { boxShadow: '0 0 5px rgba(0, 243, 255, 0.2)' },
'100%': { boxShadow: '0 0 20px rgba(0, 243, 255, 0.6), 0 0 10px rgba(0, 243, 255, 0.4)' },
},
gradient: {
'0%': { backgroundPosition: '0% 50%' },
'50%': { backgroundPosition: '100% 50%' },
'100%': { backgroundPosition: '0% 50%' },
},
scan: {
'0%': { transform: 'translateY(-100%)' },
'100%': { transform: 'translateY(100%)' },
}
}
}
},
plugins: [],
}

22
FrontEnd/tsconfig.json Normal file
View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["vite.config.ts", "node_modules"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}

77
FrontEnd/types.ts Normal file
View File

@@ -0,0 +1,77 @@
export enum SystemState {
IDLE = 'IDLE',
RUNNING = 'RUNNING',
ERROR = 'ERROR',
PAUSED = 'PAUSED',
}
export interface AxisPosition {
id: string;
name: string;
axis: 'X' | 'Y' | 'Z';
value: number;
speed: number;
acc: number;
dec: number;
}
export interface Recipe {
id: string;
name: string;
lastModified: string;
}
export interface IOPoint {
id: number;
name: string;
type: 'input' | 'output';
state: boolean;
}
export interface LogEntry {
id: number;
timestamp: string;
message: string;
type: 'info' | 'warning' | 'error';
}
export interface RobotTarget {
x: number;
y: number;
z: number;
}
// WebView2 Native Bridge Types
export interface ConfigItem {
Key: string;
Value: string;
Group: string;
Type: 'String' | 'Number' | 'Boolean';
Description: string;
}
declare global {
interface Window {
chrome?: {
webview?: {
hostObjects: {
machine: {
MoveAxis(axis: string, value: number): Promise<void>;
SetIO(id: number, isInput: boolean, state: boolean): Promise<void>;
SystemControl(command: string): Promise<void>;
SelectRecipe(recipeId: string): Promise<string>;
CopyRecipe(recipeId: string, newName: string): Promise<string>;
DeleteRecipe(recipeId: string): Promise<string>;
GetConfig(): Promise<string>;
GetIOList(): Promise<string>;
GetRecipeList(): Promise<string>;
SaveConfig(configJson: string): Promise<void>;
}
};
addEventListener(type: string, listener: (event: any) => void): void;
removeEventListener(type: string, listener: (event: any) => void): void;
postMessage(message: any): void;
}
}
}
}

20
FrontEnd/vite.config.ts Normal file
View File

@@ -0,0 +1,20 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
build: {
outDir: 'dist',
emptyOutDir: true,
}
});