import { useState, useEffect, useRef } from 'react' import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from '@/components/ui/card' import { Input } from '@/components/ui/input' import { Separator } from '@/components/ui/separator' import { Badge } from '@/components/ui/badge' import { Alert, AlertDescription } from '@/components/ui/alert' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, DialogFooter, } from '@/components/ui/dialog' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from '@/components/ui/tooltip' import { apiClient } from '@/lib/apiClient' import { useStatusStore } from '@/stores/useStatusStore' export function TableControlPage() { const [speedInput, setSpeedInput] = useState('') const [currentSpeed, setCurrentSpeed] = useState(null) const [currentTheta, setCurrentTheta] = useState(0) const [isLoading, setIsLoading] = useState(null) // Subscribe to shared status WebSocket via store const speed = useStatusStore((s) => s.status?.speed ?? null) const isPatternRunning = useStatusStore((s) => (s.status?.is_running || s.status?.is_paused) ?? false ) // Sync speed from store into local state (for the badge display) useEffect(() => { if (speed !== null) setCurrentSpeed(speed) }, [speed]) // Serial terminal state const [consoleCommand, setConsoleCommand] = useState('') const [consoleHistory, setConsoleHistory] = useState>([]) const [consoleLoading, setConsoleLoading] = useState(false) const consoleOutputRef = useRef(null) const consoleInputRef = useRef(null) const handleAction = async ( action: string, endpoint: string, body?: object ) => { setIsLoading(action) try { const data = await apiClient.post<{ success?: boolean; detail?: string }>(endpoint, body) if (data.success !== false) { return { success: true, data } } throw new Error(data.detail || 'Action failed') } catch (error) { console.error(`Error with ${action}:`, error) throw error } finally { setIsLoading(null) } } // Helper to check if pattern is running and show warning const checkPatternRunning = (actionName: string): boolean => { if (isPatternRunning) { toast.error(`Cannot ${actionName} while a pattern is running. Stop the pattern first.`, { action: { label: 'Stop', onClick: () => handleStop(), }, }) return true } return false } const handleHome = async () => { try { await handleAction('home', '/send_home') toast.success('Moving to home position...') } catch { toast.error('Failed to move to home position') } } const handleStop = async () => { try { await handleAction('stop', '/stop_execution') toast.success('Execution stopped') } catch { // Normal stop failed, try force stop try { await handleAction('stop', '/force_stop') toast.success('Force stopped') } catch { toast.error('Failed to stop execution') } } } const handleReset = async () => { try { await handleAction('reset', '/soft_reset') toast.success('Reset sent. Please home the table.') } catch { toast.error('Failed to send reset command') } } const handleMoveToCenter = async () => { if (checkPatternRunning('move to center')) return try { await handleAction('center', '/move_to_center') toast.success('Moving to center...') } catch { toast.error('Failed to move to center') } } const handleMoveToPerimeter = async () => { if (checkPatternRunning('move to perimeter')) return try { await handleAction('perimeter', '/move_to_perimeter') toast.success('Moving to perimeter...') } catch { toast.error('Failed to move to perimeter') } } const handleSetSpeed = async () => { const speed = parseFloat(speedInput) if (isNaN(speed) || speed <= 0) { toast.error('Please enter a valid speed value') return } try { await handleAction('speed', '/set_speed', { speed }) setCurrentSpeed(speed) toast.success(`Speed set to ${speed} mm/s`) setSpeedInput('') } catch { toast.error('Failed to set speed') } } const handleClearPattern = async (patternFile: string, label: string) => { try { await handleAction(patternFile, '/run_theta_rho', { file_name: patternFile, pre_execution: 'none', }) toast.success(`Running ${label}...`) } catch (error) { if (error instanceof Error && error.message.includes('409')) { toast.error('Another pattern is already running') } else { toast.error(`Failed to run ${label}`) } } } const handleRotate = async (degrees: number) => { if (checkPatternRunning('align')) return try { const radians = degrees * (Math.PI / 180) const newTheta = currentTheta + radians await handleAction('rotate', '/send_coordinate', { theta: newTheta, rho: 1 }) setCurrentTheta(newTheta) toast.info(`Rotated ${degrees}°`) } catch { toast.error('Failed to rotate') } } // Board command console: sends $-commands to the FluidNC firmware through // the backend (/api/board/command); output comes from the board's reply and // its rolling session log. const addConsoleHistory = (type: 'cmd' | 'resp' | 'error', text: string) => { const time = new Date().toLocaleTimeString() setConsoleHistory((prev) => [...prev.slice(-200), { type, text, time }]) setTimeout(() => { if (consoleOutputRef.current) { consoleOutputRef.current.scrollTop = consoleOutputRef.current.scrollHeight } }, 10) } const handleConsoleSend = async () => { if (!consoleCommand.trim() || consoleLoading) return const cmd = consoleCommand.trim() setConsoleCommand('') setConsoleLoading(true) addConsoleHistory('cmd', cmd) try { const data = await apiClient.post<{ responses?: string[]; log?: string; detail?: string }>( '/api/board/command', { command: cmd }) const lines = data.responses ?? [] if (lines.length > 0) { lines.forEach((line: string) => addConsoleHistory('resp', line)) } else if (data.log) { data.log.split('\n').slice(-5).forEach((line: string) => addConsoleHistory('resp', line)) } else { addConsoleHistory('resp', '(no response — check the board log)') } } catch (error) { addConsoleHistory('error', `Error: ${error}`) } finally { setConsoleLoading(false) setTimeout(() => consoleInputRef.current?.focus(), 0) } } const handleConsoleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault() if (!consoleLoading) { handleConsoleSend() } } } return (
{/* Page Header */}

Table Control

Manual controls for your sand table

{/* Main Controls Grid - 2x2 */}
{/* Primary Actions */} Primary Actions Calibrate or stop the table
Return to home position Gracefully stop Send soft reset to controller Reset Controller? This will send a soft reset to the controller. warning Homing is required after resetting. The table will lose its position reference.
{/* Speed Control */}
Speed Ball movement speed
{currentSpeed !== null ? `${currentSpeed} mm/s` : '-- mm/s'}
setSpeedInput(e.target.value)} placeholder="mm/s" min="1" step="1" className="flex-1" onKeyDown={(e) => e.key === 'Enter' && handleSetSpeed()} />
{/* Position */} Position Move ball to a specific location
Move ball to center Move ball to edge Align pattern orientation Pattern Orientation Alignment Follow these steps to align your patterns with their previews
    {[ 'Home the table then select move to perimeter. Look at your pattern preview and decide where the "bottom" should be.', 'Manually move the radial arm or use the rotation buttons below to point 90° to the right of where you want the pattern bottom.', 'Click the "Home" button to establish this as the reference position.', 'All patterns will now be oriented according to their previews!', ].map((step, i) => (
  1. {i + 1} {step}
  2. ))}
warning Only perform this when you want to change the orientation reference.

Fine Adjustment

Each click rotates 10 degrees

{/* Clear Patterns */} Clear Sand Erase current pattern from the table
Spiral outward from center Spiral inward from edge Clear with side-to-side motion
{/* Board Command Console */}
terminal Command Console Send $-commands to the table's firmware (e.g. $Sand/HomingMode, $LED/Effect=fire) warning For advanced use. Motion commands sent here can interfere with a running pattern.
{consoleHistory.length > 0 && ( )}
{/* Output area */}
{consoleHistory.length > 0 ? ( consoleHistory.map((entry, i) => (
{entry.time} {entry.type === 'cmd' ? '> ' : ''} {entry.text}
)) ) : (
Ready. Enter a firmware command (e.g. $Sand/HomingMode, $Playlist/List)
)}
{/* Input area */}
setConsoleCommand(e.target.value)} onKeyDown={handleConsoleKeyDown} readOnly={consoleLoading} placeholder="Enter command (e.g. $Sand/HomingMode)" className="font-mono text-base h-11" />
) }