Initial commit

This commit is contained in:
backuppc
2026-01-16 14:35:56 +09:00
commit 550b8263db
15 changed files with 1183 additions and 0 deletions

24
.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?

354
App.tsx Normal file
View File

@@ -0,0 +1,354 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { SerialManager } from './services/serialService';
import { SerialLogEntry, ViewMode, NavigatorSerial } from './types';
import { generateId, formatTime, uInt8ArrayToHex, uInt8ArrayToAscii } from './utils';
import Terminal from './components/Terminal';
import ControlPanel from './components/ControlPanel';
import InputBar from './components/InputBar';
const BAUD_RATES = [9600, 19200, 38400, 57600, 115200];
const App: React.FC = () => {
// Check for Browser Support
const [isSupported, setIsSupported] = useState(true);
// State for Configuration
const [isDualMode, setIsDualMode] = useState(false);
const [isAttached, setIsAttached] = useState(false);
// Refs for State Access inside Callbacks (Fixes stale closures)
const isAttachedRef = useRef(isAttached);
const isDualModeRef = useRef(isDualMode);
// Independent View Modes
const [viewModeA, setViewModeA] = useState<ViewMode>(ViewMode.ASCII);
const [viewModeB, setViewModeB] = useState<ViewMode>(ViewMode.ASCII);
// Independent Baud Rates
const [baudRateA, setBaudRateA] = useState(115200);
const [baudRateB, setBaudRateB] = useState(115200);
// State for Connections
const [isConnectedA, setIsConnectedA] = useState(false);
const [isConnectedB, setIsConnectedB] = useState(false);
// Logs
const [logsA, setLogsA] = useState<SerialLogEntry[]>([]);
const [logsB, setLogsB] = useState<SerialLogEntry[]>([]);
// Refs to hold SerialManager instances (persisted across renders)
const serialA = useRef(new SerialManager('A'));
const serialB = useRef(new SerialManager('B'));
useEffect(() => {
// Check if Web Serial is supported
const nav = navigator as unknown as { serial: NavigatorSerial };
if (!nav.serial) {
setIsSupported(false);
console.warn("Web Serial API is not supported in this browser.");
}
return () => {
serialA.current.disconnect();
serialB.current.disconnect();
};
}, []);
// Sync Refs with State
useEffect(() => {
isAttachedRef.current = isAttached;
}, [isAttached]);
useEffect(() => {
isDualModeRef.current = isDualMode;
}, [isDualMode]);
// Handle Bridging Logic
useEffect(() => {
if (isAttached && isDualMode) {
// Connect bridges in the Service layer
console.log("Bridging Enabled: A <-> B");
serialA.current.setBridgeTarget(serialB.current);
serialB.current.setBridgeTarget(serialA.current);
} else {
// Disconnect bridges
if (serialA.current['bridgeTarget'] !== null) console.log("Bridging Disabled");
serialA.current.setBridgeTarget(null);
serialB.current.setBridgeTarget(null);
}
}, [isAttached, isDualMode]);
// Safety: If Dual Mode is disabled, automatically detach
useEffect(() => {
if (!isDualMode && isAttached) {
setIsAttached(false);
}
}, [isDualMode]);
// --- Helper to add logs ---
const addLog = useCallback((port: 'A' | 'B', direction: 'TX' | 'RX', data: Uint8Array) => {
const entry: SerialLogEntry = {
id: generateId(),
timestamp: new Date(),
direction,
data
};
if (port === 'A') {
setLogsA(prev => [...prev.slice(-1000), entry]); // Keep last 1000 logs
} else {
setLogsB(prev => [...prev.slice(-1000), entry]);
}
}, []);
// --- Log Saving Logic ---
const handleSaveLogs = (portName: string, logs: SerialLogEntry[]) => {
if (logs.length === 0) {
alert(`No logs to save for ${portName}.`);
return;
}
// Header
let content = `SerialNexus Log - Port ${portName}\n`;
content += `Exported at: ${new Date().toLocaleString()}\n`;
content += `--------------------------------------------------------------------------------\n`;
content += `TIMESTAMP | DIR | HEX DATA | ASCII\n`;
content += `--------------------------------------------------------------------------------\n`;
// Data
content += logs.map(log => {
const time = formatTime(log.timestamp).padEnd(23, ' ');
const dir = log.direction.padEnd(3, ' ');
const hex = uInt8ArrayToHex(log.data).padEnd(40, ' '); // simple padding
const ascii = uInt8ArrayToAscii(log.data);
return `${time} | ${dir} | ${hex} | ${ascii}`;
}).join('\n');
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `serial-log-${portName.toLowerCase()}-${new Date().toISOString().slice(0,19).replace(/[:T]/g,'-')}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
// --- Connection Handlers ---
const handleConnectA = async () => {
try {
console.log("Connect A Clicked");
await serialA.current.connect(baudRateA);
setIsConnectedA(true);
serialA.current.startReading((data) => {
// Log RX on A
addLog('A', 'RX', data);
// Visual Feedback for Bridge: If Attached, we assume it was sent to B
// Note: The actual sending happens in SerialManager, here we just update the UI
if (isAttachedRef.current && isDualModeRef.current && serialB.current.port) {
addLog('B', 'TX', data);
}
});
} catch (err) {
console.error("Connection Error A:", err);
alert("Failed to connect to Port A. Check console for details.");
}
};
const handleDisconnectA = async () => {
await serialA.current.disconnect();
setIsConnectedA(false);
};
const handleConnectB = async () => {
try {
console.log("Connect B Clicked");
await serialB.current.connect(baudRateB);
setIsConnectedB(true);
serialB.current.startReading((data) => {
// Log RX on B
addLog('B', 'RX', data);
// Visual Feedback for Bridge: If Attached, we assume it was sent to A
if (isAttachedRef.current && isDualModeRef.current && serialA.current.port) {
addLog('A', 'TX', data);
}
});
} catch (err) {
console.error("Connection Error B:", err);
alert("Failed to connect to Port B. Check console for details.");
}
};
const handleDisconnectB = async () => {
await serialB.current.disconnect();
setIsConnectedB(false);
};
// --- Send Handlers (Receives Uint8Array from InputBar) ---
const handleSendA = async (data: Uint8Array) => {
if (!isConnectedA) return;
await serialA.current.send(data);
addLog('A', 'TX', data);
};
const handleSendB = async (data: Uint8Array) => {
if (!isConnectedB) return;
await serialB.current.send(data);
addLog('B', 'TX', data);
};
// --- Helper Component for Controls ---
const renderControls = (
baud: number,
setBaud: (r: number) => void,
connected: boolean,
onConnect: () => void,
onDisconnect: () => void,
viewMode: ViewMode,
setViewMode: (v: ViewMode) => void
) => (
<>
<div className="flex items-center gap-2">
<span className="text-[10px] text-gray-500 font-bold uppercase hidden xl:inline">Baud</span>
<select
className="bg-gray-800 text-xs text-white border border-gray-700 rounded px-1 py-0.5 focus:ring-1 focus:ring-indigo-500 outline-none w-20"
value={baud}
onChange={(e) => setBaud(Number(e.target.value))}
disabled={connected}
>
{BAUD_RATES.map(rate => (
<option key={rate} value={rate}>{rate}</option>
))}
</select>
</div>
{connected ? (
<button onClick={onDisconnect} className="bg-red-900/30 text-red-400 border border-red-800/50 hover:bg-red-900/50 px-2 py-0.5 rounded text-xs font-bold transition-all flex items-center gap-1">
DISCONNECT
</button>
) : (
<button
onClick={onConnect}
disabled={!isSupported}
title={!isSupported ? "Web Serial API not supported" : "Connect to Serial Port"}
className="bg-indigo-600 hover:bg-indigo-500 text-white px-3 py-0.5 rounded text-xs font-bold transition-all shadow-lg shadow-indigo-900/20 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isSupported ? "CONNECT" : "NO SERIAL API"}
</button>
)}
{/* View Mode Toggles */}
<div className="flex bg-gray-800 rounded border border-gray-700 ml-2">
<button
onClick={() => setViewMode(ViewMode.ASCII)}
className={`px-2 py-0.5 text-[10px] font-bold rounded-l transition-all ${
viewMode === ViewMode.ASCII ? 'bg-gray-600 text-white' : 'text-gray-400 hover:text-white'
}`}
>
ASCII
</button>
<button
onClick={() => setViewMode(ViewMode.HEX)}
className={`px-2 py-0.5 text-[10px] font-bold rounded-r transition-all ${
viewMode === ViewMode.HEX ? 'bg-gray-600 text-white' : 'text-gray-400 hover:text-white'
}`}
>
HEX
</button>
</div>
</>
);
return (
<div className="flex flex-col h-screen bg-gray-950 text-gray-200">
<ControlPanel
isDualMode={isDualMode}
setDualMode={setIsDualMode}
isAttached={isAttached}
setIsAttached={setIsAttached}
>
<div className="w-full max-w-[728px] h-[90px] bg-gray-800/50 border-2 border-dashed border-gray-700 rounded-lg flex items-center justify-center text-gray-500 text-xs font-mono uppercase tracking-widest relative overflow-hidden group">
<span className="relative z-10">Google AdSense Space (728x90)</span>
<div className="absolute inset-0 bg-gradient-to-r from-transparent via-gray-700/10 to-transparent translate-x-[-100%] group-hover:animate-[shimmer_2s_infinite]"></div>
</div>
</ControlPanel>
{!isSupported && (
<div className="bg-red-900/50 border-b border-red-800 text-red-200 text-xs text-center py-1">
Your browser does not support the Web Serial API. Please use Chrome, Edge, or Opera.
</div>
)}
{/* Main Content Area */}
<div className={`flex-1 flex overflow-hidden p-2 md:p-4 gap-2 md:gap-4 ${isDualMode ? 'flex-col md:flex-row' : 'flex-col'}`}>
{/* Port A Terminal */}
<div className={`flex flex-col transition-all duration-300 ease-in-out ${
isDualMode
? 'w-full h-1/2 md:w-1/2 md:h-full'
: 'w-full h-full'
}`}>
<Terminal
title="Primary Port (A)"
logs={logsA}
viewMode={viewModeA}
isConnected={isConnectedA}
onClear={() => setLogsA([])}
onSave={() => handleSaveLogs("A", logsA)}
className="flex-1"
headerControls={renderControls(
baudRateA, setBaudRateA, isConnectedA, handleConnectA, handleDisconnectA, viewModeA, setViewModeA
)}
/>
<div className="mt-2 shrink-0">
<InputBar
onSend={handleSendA}
disabled={!isConnectedA}
/>
</div>
</div>
{/* Port B Terminal (Only if Dual Mode) */}
{isDualMode && (
<div className="flex flex-col w-full h-1/2 md:w-1/2 md:h-full animate-fade-in-right">
<Terminal
title="Secondary Port (B)"
logs={logsB}
viewMode={viewModeB}
isConnected={isConnectedB}
onClear={() => setLogsB([])}
onSave={() => handleSaveLogs("B", logsB)}
className="flex-1 border-indigo-900/50 shadow-indigo-900/10"
headerControls={renderControls(
baudRateB, setBaudRateB, isConnectedB, handleConnectB, handleDisconnectB, viewModeB, setViewModeB
)}
/>
<div className="mt-2 shrink-0">
<InputBar
onSend={handleSendB}
disabled={!isConnectedB}
/>
</div>
</div>
)}
</div>
{/* Footer / Status */}
<div className="h-6 bg-gray-900 border-t border-gray-800 flex items-center justify-between px-4 text-[10px] text-gray-500 font-mono select-none shrink-0">
<span>&copy; 2026 SIMP</span>
<span className="hidden sm:inline">
{isDualMode
? (isAttached ? "MODE: DUAL MONITOR (ATTACHED: A <-> B)" : "MODE: DUAL MONITOR (INDEPENDENT)")
: "MODE: SINGLE MONITOR (A)"}
</span>
</div>
</div>
);
};
export default App;

20
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/1mwwZRLGTPE76wHsg2Mh5ks9vrdtLnPNE
## 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`

View File

@@ -0,0 +1,87 @@
import React from 'react';
interface ControlPanelProps {
isDualMode: boolean;
setDualMode: (val: boolean) => void;
isAttached: boolean;
setIsAttached: (val: boolean) => void;
children?: React.ReactNode;
}
const ControlPanel: React.FC<ControlPanelProps> = ({
isDualMode,
setDualMode,
isAttached,
setIsAttached,
children
}) => {
return (
<div className="bg-gray-850 p-4 border-b border-gray-800 shadow-md z-20">
<div className="flex flex-col md:flex-row gap-4 items-center md:items-stretch">
{/* Left Column: Brand & Controls */}
<div className="flex flex-col gap-3 shrink-0 md:w-auto">
{/* Brand */}
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-indigo-600 rounded-lg flex items-center justify-center shadow-lg shadow-indigo-900/50 shrink-0">
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
</div>
<div>
<h1 className="text-xl font-bold text-white tracking-tight leading-tight">SerialNexus</h1>
<span className="text-xs text-indigo-400 font-medium block">Bypass & Monitor</span>
</div>
</div>
{/* Controls Row */}
<div className="flex items-center gap-3">
{/* Dual Monitor Toggle */}
<div className={`flex items-center gap-3 p-2 pl-3 rounded-lg border transition-all duration-300 w-48 ${
isDualMode ? 'bg-gray-900 border-indigo-500/50 shadow-[0_0_15px_rgba(79,70,229,0.1)]' : 'bg-gray-900/50 border-gray-800'
}`}>
<label className="flex items-center cursor-pointer select-none w-full">
<div className="relative shrink-0">
<input
type="checkbox"
className="sr-only"
checked={isDualMode}
onChange={(e) => setDualMode(e.target.checked)}
/>
<div className={`block w-9 h-5 rounded-full transition-colors ${isDualMode ? 'bg-indigo-600' : 'bg-gray-700'}`}></div>
<div className={`absolute left-1 top-1 bg-white w-3 h-3 rounded-full transition-transform ${isDualMode ? 'translate-x-4' : 'translate-x-0'}`}></div>
</div>
<div className={`ml-2 text-xs font-bold ${isDualMode ? 'text-indigo-300' : 'text-gray-500'}`}>
DUAL MONITOR
</div>
</label>
</div>
{/* Attach Button */}
<button
onClick={() => setIsAttached(!isAttached)}
disabled={!isDualMode}
className={`flex items-center justify-center gap-2 px-4 py-2 rounded-lg border text-xs font-bold transition-all duration-300 ${
!isDualMode
? 'opacity-50 cursor-not-allowed bg-gray-900 border-gray-800 text-gray-600'
: isAttached
? 'bg-green-900/30 border-green-500/50 text-green-400 shadow-[0_0_10px_rgba(34,197,94,0.2)]'
: 'bg-gray-900 border-gray-700 text-gray-400 hover:border-gray-500 hover:text-gray-300'
}`}
>
<div className={`w-2 h-2 rounded-full ${isAttached && isDualMode ? 'bg-green-500 animate-pulse' : 'bg-gray-600'}`}></div>
{isAttached ? 'ATTACHED' : 'ATTACH'}
</button>
</div>
</div>
{/* Right Column: Sponsor Space */}
<div className="flex-1 w-full flex justify-center md:justify-end items-center">
{children}
</div>
</div>
</div>
);
};
export default ControlPanel;

245
components/InputBar.tsx Normal file
View File

@@ -0,0 +1,245 @@
import React, { useState, KeyboardEvent, useEffect } from 'react';
type InputMode = 'ASCII' | 'HEX';
interface InputBarProps {
onSend: (data: Uint8Array) => void;
disabled: boolean;
}
const InputBar: React.FC<InputBarProps> = ({ onSend, disabled }) => {
const [text, setText] = useState('');
const [stx, setStx] = useState('');
const [etx, setEtx] = useState('');
const [mode, setMode] = useState<InputMode>('ASCII');
// Error states for validation
const [errors, setErrors] = useState({ stx: false, text: false, etx: false });
// Command History State
const [history, setHistory] = useState<string[]>([]);
const [historyIndex, setHistoryIndex] = useState<number>(-1);
// Clear errors when mode changes
useEffect(() => {
setErrors({ stx: false, text: false, etx: false });
}, [mode]);
const isValidHex = (str: string): boolean => {
// Allow empty string, hex digits, and spaces.
// Checks if there is any character that is NOT 0-9, a-f, A-F, or whitespace
return !/[^0-9A-Fa-f\s]/.test(str);
};
const parseString = (str: string, mode: InputMode): Uint8Array => {
if (mode === 'HEX') {
// Remove spaces and non-hex characters (cleaning is still done for safe parsing)
const clean = str.replace(/[^0-9A-Fa-f]/g, '');
if (clean.length === 0) return new Uint8Array(0);
const bytes = new Uint8Array(Math.ceil(clean.length / 2));
for (let i = 0; i < bytes.length; i++) {
const hexPair = clean.slice(i * 2, i * 2 + 2).padEnd(2, '0');
bytes[i] = parseInt(hexPair, 16);
}
return bytes;
} else {
// ASCII Mode with Escape Sequence Parsing
const unescaped = str
.replace(/\\r/g, '\r')
.replace(/\\n/g, '\n')
.replace(/\\t/g, '\t')
.replace(/\\0/g, '\0')
.replace(/\\x([0-9A-Fa-f]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
return new TextEncoder().encode(unescaped);
}
};
const handleSend = () => {
// Validation for HEX mode
if (mode === 'HEX') {
const stxValid = isValidHex(stx);
const textValid = isValidHex(text);
const etxValid = isValidHex(etx);
setErrors({
stx: !stxValid,
text: !textValid,
etx: !etxValid
});
if (!stxValid || !textValid || !etxValid) {
return; // Stop sending if validation fails
}
}
try {
const stxBytes = stx ? parseString(stx, mode) : new Uint8Array(0);
const bodyBytes = text ? parseString(text, mode) : new Uint8Array(0);
const etxBytes = etx ? parseString(etx, mode) : new Uint8Array(0);
if (stxBytes.length === 0 && bodyBytes.length === 0 && etxBytes.length === 0) return;
const totalLength = stxBytes.length + bodyBytes.length + etxBytes.length;
const result = new Uint8Array(totalLength);
result.set(stxBytes, 0);
result.set(bodyBytes, stxBytes.length);
result.set(etxBytes, stxBytes.length + bodyBytes.length);
onSend(result);
// Add to history
if (text.trim() !== '') {
setHistory(prev => {
const newHistory = [...prev];
if (newHistory[newHistory.length - 1] !== text) {
newHistory.push(text);
}
if (newHistory.length > 50) return newHistory.slice(-50);
return newHistory;
});
}
setText('');
setHistoryIndex(-1);
} catch (e) {
console.error("Parse error", e);
alert("Error parsing input data.");
}
};
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
handleSend();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (history.length === 0) return;
setHistoryIndex(prevIndex => {
const newIndex = prevIndex === -1 ? history.length - 1 : Math.max(0, prevIndex - 1);
setText(history[newIndex]);
// Clear text error when recalling history
setErrors(prev => ({ ...prev, text: false }));
return newIndex;
});
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (history.length === 0 || historyIndex === -1) return;
setHistoryIndex(prevIndex => {
if (prevIndex >= history.length - 1) {
setText('');
return -1;
} else {
const newIndex = prevIndex + 1;
setText(history[newIndex]);
// Clear text error when recalling history
setErrors(prev => ({ ...prev, text: false }));
return newIndex;
}
});
}
};
const getBorderClass = (hasError: boolean) => {
return hasError
? "border-red-500 focus:ring-red-500 text-red-300 placeholder-red-300/50"
: "border-gray-700 focus:ring-indigo-500 text-white placeholder-gray-700";
};
return (
<div className="flex flex-col md:flex-row items-center gap-2 p-3 bg-gray-850 border-t border-gray-800">
<div className="flex items-center gap-2 w-full md:w-auto">
{/* Mode Toggle */}
<div className="flex bg-gray-900 rounded border border-gray-700">
<button
onClick={() => setMode('ASCII')}
className={`px-2 py-1 text-[10px] font-bold rounded-l transition-all ${
mode === 'ASCII' ? 'bg-indigo-600 text-white' : 'text-gray-400 hover:text-white'
}`}
>
ASC
</button>
<button
onClick={() => setMode('HEX')}
className={`px-2 py-1 text-[10px] font-bold rounded-r transition-all ${
mode === 'HEX' ? 'bg-indigo-600 text-white' : 'text-gray-400 hover:text-white'
}`}
>
HEX
</button>
</div>
</div>
<div className="flex flex-1 items-center gap-2 w-full">
{/* STX Input */}
<input
type="text"
value={stx}
onChange={(e) => {
setStx(e.target.value);
if (errors.stx) setErrors(prev => ({ ...prev, stx: false }));
}}
disabled={disabled}
placeholder="STX"
className={`w-14 bg-gray-900 text-xs border rounded px-2 py-2 focus:ring-1 outline-none text-center font-mono transition-colors ${
errors.stx
? "border-red-500 focus:ring-red-500 text-red-400 placeholder-red-400/50"
: "border-gray-700 focus:ring-indigo-500 text-amber-200 placeholder-gray-700"
}`}
title="Start Byte (e.g. \x02 or 02)"
/>
{/* Main Input */}
<input
type="text"
value={text}
onChange={(e) => {
setText(e.target.value);
setHistoryIndex(-1);
if (errors.text) setErrors(prev => ({ ...prev, text: false }));
}}
onKeyDown={handleKeyDown}
disabled={disabled}
placeholder={disabled ? "Disconnected..." : (mode === 'HEX' ? (errors.text ? "Invalid HEX!" : "AA BB CC...") : "Type message (supports \\r\\n)...")}
className={`flex-1 bg-gray-900 text-sm border rounded px-3 py-2 focus:ring-2 outline-none disabled:opacity-50 font-mono transition-colors ${getBorderClass(errors.text)}`}
/>
{/* ETX Input */}
<input
type="text"
value={etx}
onChange={(e) => {
setEtx(e.target.value);
if (errors.etx) setErrors(prev => ({ ...prev, etx: false }));
}}
disabled={disabled}
placeholder="ETX"
className={`w-14 bg-gray-900 text-xs border rounded px-2 py-2 focus:ring-1 outline-none text-center font-mono transition-colors ${
errors.etx
? "border-red-500 focus:ring-red-500 text-red-400 placeholder-red-400/50"
: "border-gray-700 focus:ring-indigo-500 text-amber-200 placeholder-gray-700"
}`}
title="End Byte (e.g. \r\n or 0D 0A)"
/>
<button
onClick={handleSend}
disabled={disabled}
className={`text-white text-xs font-bold px-4 py-2 rounded transition-colors uppercase tracking-wider h-full ${
(errors.stx || errors.text || errors.etx)
? "bg-red-600 hover:bg-red-500"
: "bg-indigo-600 hover:bg-indigo-500 disabled:bg-gray-700"
}`}
>
{(errors.stx || errors.text || errors.etx) ? 'Fix' : 'Send'}
</button>
</div>
</div>
);
};
export default InputBar;

112
components/Terminal.tsx Normal file
View File

@@ -0,0 +1,112 @@
import React, { useEffect, useRef } from 'react';
import { SerialLogEntry, ViewMode } from '../types';
import { formatTime, uInt8ArrayToAscii, uInt8ArrayToHex } from '../utils';
interface TerminalProps {
title: string;
logs: SerialLogEntry[];
viewMode: ViewMode;
isConnected: boolean;
onClear: () => void;
onSave: () => void;
className?: string;
headerControls?: React.ReactNode;
}
const Terminal: React.FC<TerminalProps> = ({
title,
logs,
viewMode,
isConnected,
onClear,
onSave,
className,
headerControls
}) => {
const bottomRef = useRef<HTMLDivElement>(null);
useEffect(() => {
// Auto-scroll to bottom on new logs
if (bottomRef.current) {
bottomRef.current.scrollIntoView({ behavior: "smooth" });
}
}, [logs]);
return (
<div className={`flex flex-col h-full bg-gray-900 border border-gray-800 rounded-lg shadow-xl overflow-hidden ${className}`}>
{/* Terminal Header */}
<div className="flex flex-wrap items-center justify-between px-4 py-2 bg-gray-850 border-b border-gray-800 gap-y-2">
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<div className={`w-2 h-2 rounded-full ${isConnected ? 'bg-green-500 animate-pulse' : 'bg-red-500'}`} />
<h2 className="text-sm font-semibold text-gray-300 uppercase tracking-wider whitespace-nowrap">{title}</h2>
</div>
{/* Custom Header Controls (e.g. Baud Rate, Connect Button) */}
{headerControls && (
<div className="flex items-center gap-2 border-l border-gray-700 pl-4">
{headerControls}
</div>
)}
</div>
<div className="flex items-center gap-2 ml-auto">
{/* Save Button (Icon Only) */}
<button
onClick={onSave}
className="p-1.5 text-indigo-400 hover:text-white hover:bg-indigo-900/50 rounded transition-colors border border-transparent hover:border-indigo-500/30"
title="Save Logs to File"
>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
<path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
</svg>
</button>
{/* Clear Button (Icon Only - Trash) */}
<button
onClick={onClear}
className="p-1.5 text-gray-400 hover:text-red-400 hover:bg-red-900/30 rounded transition-colors border border-transparent hover:border-red-500/30"
title="Clear Logs"
>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
<path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
</svg>
</button>
</div>
</div>
{/* Log Area */}
<div className="flex-1 overflow-y-auto font-mono text-sm p-4 space-y-1 relative bg-black/50">
{logs.length === 0 && (
<div className="absolute inset-0 flex items-center justify-center text-gray-600 pointer-events-none">
<p>Waiting for data...</p>
</div>
)}
{logs.map((log) => (
<div key={log.id} className="flex gap-3 hover:bg-white/5 p-0.5 rounded transition-colors group">
<span className="text-gray-600 text-xs select-none w-20 shrink-0">
[{formatTime(log.timestamp)}]
</span>
<span className={`font-bold text-xs w-6 shrink-0 select-none ${
log.direction === 'TX' ? 'text-blue-400' : 'text-orange-400'
}`}>
{log.direction}
</span>
<span className={`break-all ${
log.direction === 'TX' ? 'text-blue-100' : 'text-orange-100'
}`}>
{viewMode === ViewMode.ASCII
? uInt8ArrayToAscii(log.data)
: uInt8ArrayToHex(log.data)
}
</span>
</div>
))}
<div ref={bottomRef} />
</div>
</div>
);
};
export default Terminal;

59
index.html Normal file
View File

@@ -0,0 +1,59 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="https://picsum.photos/32/32" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SerialNexus Bridge</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
gray: {
750: '#2d3748',
850: '#1a202c',
950: '#0d1117',
}
},
fontFamily: {
mono: ['ui-monospace', 'SFMono-Regular', 'Menlo', 'Monaco', 'Consolas', "Liberation Mono", "Courier New", 'monospace'],
}
}
}
}
</script>
<style>
/* Custom Scrollbar for a cleaner look */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #1f2937;
}
::-webkit-scrollbar-thumb {
background: #4b5563;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #6b7280;
}
</style>
<script type="importmap">
{
"imports": {
"react-dom/": "https://esm.sh/react-dom@^19.2.3/",
"react/": "https://esm.sh/react@^19.2.3/",
"react": "https://esm.sh/react@^19.2.3"
}
}
</script>
<link rel="stylesheet" href="/index.css">
</head>
<body class="bg-gray-950 text-gray-200 antialiased overflow-hidden h-screen">
<div id="root"></div>
<script type="module" src="/index.tsx"></script>
</body>
</html>

15
index.tsx Normal file
View File

@@ -0,0 +1,15 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
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
metadata.json Normal file
View File

@@ -0,0 +1,7 @@
{
"name": "Serial Monitor",
"description": "A modern RS232 Serial Port Monitor and Bypass tool. Visualize TX/RX packets in Hex or ASCII, and bridge data between two ports in real-time.",
"requestFramePermissions": [
"serial"
]
}

21
package.json Normal file
View File

@@ -0,0 +1,21 @@
{
"name": "serial-monitor",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react-dom": "^19.2.3",
"react": "^19.2.3"
},
"devDependencies": {
"@types/node": "^22.14.0",
"@vitejs/plugin-react": "^5.0.0",
"typescript": "~5.8.2",
"vite": "^6.2.0"
}
}

135
services/serialService.ts Normal file
View File

@@ -0,0 +1,135 @@
import { SerialPort, NavigatorSerial } from '../types';
export class SerialManager {
port: SerialPort | null = null;
private reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
private writer: WritableStreamDefaultWriter<Uint8Array> | null = null;
private isReading = false;
// Callback for receiving data
private onDataCallback: ((data: Uint8Array) => void) | null = null;
// Optional bridge target to automatically forward read data to
private bridgeTarget: SerialManager | null = null;
constructor(public id: string) {}
async connect(baudRate: number): Promise<void> {
const nav = navigator as unknown as { serial: NavigatorSerial };
if (!nav.serial) {
console.error("Web Serial API is not supported in this environment.");
throw new Error("Web Serial API not supported in this browser.");
}
try {
console.log(`[${this.id}] Requesting port...`);
// Explicitly passing filters: [] allows the user to see all available ports
this.port = await nav.serial.requestPort({ filters: [] });
console.log(`[${this.id}] Port selected. Opening with baudRate ${baudRate}...`);
await this.port.open({ baudRate });
console.log(`[${this.id}] Port opened successfully.`);
} catch (err) {
console.error(`[${this.id}] Failed to connect:`, err);
throw err;
}
}
async disconnect(): Promise<void> {
this.isReading = false;
if (this.reader) {
try {
await this.reader.cancel();
// The loop will catch the cancel and release the lock
} catch (e) {
console.warn("Error cancelling reader", e);
}
}
if (this.writer) {
try {
this.writer.releaseLock();
} catch (e) {
console.warn("Error releasing writer lock", e);
}
this.writer = null;
}
if (this.port) {
// Wait a tick for lock release
setTimeout(async () => {
try {
await this.port?.close();
console.log(`[${this.id}] Port closed.`);
} catch(e) { console.error("Error closing port", e); }
this.port = null;
}, 100);
}
}
setBridgeTarget(target: SerialManager | null) {
this.bridgeTarget = target;
}
startReading(onData: (data: Uint8Array) => void) {
if (!this.port || !this.port.readable) return;
this.onDataCallback = onData;
this.isReading = true;
this.readLoop();
}
private async readLoop() {
while (this.port && this.port.readable && this.isReading) {
try {
this.reader = this.port.readable.getReader();
while (true) {
const { value, done } = await this.reader.read();
if (done) {
break;
}
if (value) {
// 1. Notify UI
if (this.onDataCallback) this.onDataCallback(value);
// 2. Bypass/Bridge: If a target is set, write data immediately to it
if (this.bridgeTarget) {
this.bridgeTarget.send(value).catch(err => console.error("Bridge write error:", err));
}
}
}
} catch (error) {
console.error(`Read error on ${this.id}:`, error);
break;
} finally {
if (this.reader) {
this.reader.releaseLock();
this.reader = null;
}
}
}
}
async send(data: Uint8Array): Promise<void> {
if (!this.port || !this.port.writable) {
console.warn(`[${this.id}] Cannot send: Port not writable or disconnected.`);
return;
}
if (!this.writer) {
this.writer = this.port.writable.getWriter();
}
try {
await this.writer.write(data);
} catch (e) {
console.error("Write error:", e);
// If writer is dead, release and retry next time
this.writer.releaseLock();
this.writer = null;
throw e;
}
// We intentionally keep the writer locked for performance in high-throughput
// scenarios, but for a general app, you might releaseLock here if you expect
// other things to grab it. For this app, SerialManager owns the writer.
}
}

29
tsconfig.json Normal file
View File

@@ -0,0 +1,29 @@
{
"compilerOptions": {
"target": "ES2022",
"experimentalDecorators": true,
"useDefineForClassFields": false,
"module": "ESNext",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"skipLibCheck": true,
"types": [
"node"
],
"moduleResolution": "bundler",
"isolatedModules": true,
"moduleDetection": "force",
"allowJs": true,
"jsx": "react-jsx",
"paths": {
"@/*": [
"./*"
]
},
"allowImportingTsExtensions": true,
"noEmit": true
}
}

23
types.ts Normal file
View File

@@ -0,0 +1,23 @@
export enum ViewMode {
ASCII = 'ASCII',
HEX = 'HEX'
}
export interface SerialLogEntry {
id: string;
timestamp: Date;
direction: 'TX' | 'RX';
data: Uint8Array;
}
// Minimal Web Serial API type definitions since they aren't in all TS configs yet
export interface SerialPort {
open(options: { baudRate: number }): Promise<void>;
close(): Promise<void>;
readable: ReadableStream<Uint8Array> | null;
writable: WritableStream<Uint8Array> | null;
}
export interface NavigatorSerial {
requestPort(options?: { filters: any[] }): Promise<SerialPort>;
}

29
utils.ts Normal file
View File

@@ -0,0 +1,29 @@
export const generateId = (): string => {
return Math.random().toString(36).substring(2, 9);
};
export const formatTime = (date: Date): string => {
const h = date.getHours().toString().padStart(2, '0');
const m = date.getMinutes().toString().padStart(2, '0');
const s = date.getSeconds().toString().padStart(2, '0');
const ms = date.getMilliseconds().toString().padStart(3, '0');
return `${h}:${m}:${s}.${ms}`;
};
export const uInt8ArrayToHex = (arr: Uint8Array): string => {
return Array.from(arr)
.map(b => b.toString(16).padStart(2, '0').toUpperCase())
.join(' ');
};
export const uInt8ArrayToAscii = (arr: Uint8Array): string => {
// Replace non-printable characters with a dot or special symbol to avoid rendering issues
return Array.from(arr)
.map(b => {
if (b >= 32 && b <= 126) {
return String.fromCharCode(b);
}
return '.'; // Placeholder for non-printable chars
})
.join('');
};

23
vite.config.ts Normal file
View File

@@ -0,0 +1,23 @@
import path from 'path';
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, '.', '');
return {
server: {
port: 3000,
host: '0.0.0.0',
},
plugins: [react()],
define: {
'process.env.API_KEY': JSON.stringify(env.GEMINI_API_KEY),
'process.env.GEMINI_API_KEY': JSON.stringify(env.GEMINI_API_KEY)
},
resolve: {
alias: {
'@': path.resolve(__dirname, '.'),
}
}
};
});