All files / client/src/hooks use-serial-io.ts

88.73% Statements 63/71
67.85% Branches 19/28
84.21% Functions 16/19
87.69% Lines 57/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169            155x 155x 155x 155x     155x 155x 155x 155x     155x 132x   100x 104x             155x 31x 99x   31x   31x 31x   31x 11x           155x 155x   155x 3x 3x 2x 1x       155x 2x 2x 2x       2x   2x     2x       2x       155x   20x 20x   1x   19x       20x   20x       20x 9x 9x 9x   9x       155x   19x 19x     155x 1x     155x 2x               155x                 155x                     155x                                                      
import { useState, useCallback, useRef, useEffect, useMemo } from "react";
import type { OutputLine } from "@shared/schema";
import { SerialCharacterRenderer } from "@/utils/serial-character-renderer";
import { emitSerialOutput } from "./use-external-api";
 
export function useSerialIO() {
  const [serialOutput, setSerialOutput] = useState<OutputLine[]>([]);
  const [serialViewMode, setSerialViewMode] = useState<"monitor" | "plotter" | "both">("monitor");
  const [autoScrollEnabled, setAutoScrollEnabled] = useState<boolean>(true);
  const [serialInputValue, setSerialInputValue] = useState("");
  
  // Baudrate-simulated rendering
  const [renderedSerialText, setRenderedSerialText] = useState<string>("");
  const rendererRef = useRef<SerialCharacterRenderer | null>(null);
  const emitDebounceRef = useRef<NodeJS.Timeout | null>(null);
  const pendingOutputRef = useRef<string>("");
 
  // Convert renderedSerialText to OutputLine[] format for SerialMonitor
  const renderedSerialOutput = useMemo<OutputLine[]>(() => {
    if (!renderedSerialText) return [];
    
    const lines = renderedSerialText.split('\n');
    return lines.map((line, index) => ({
      text: line,
      complete: index < lines.length - 1, // All lines except last are complete
    }));
  }, [renderedSerialText]);
 
  // Initialize renderer once and cleanup on unmount
  useEffect(() => {
    const renderer = new SerialCharacterRenderer((char: string) => {
      setRenderedSerialText((prev) => prev + char);
    });
    rendererRef.current = renderer;
 
    return () => {
      renderer.clear();
      // Clean up debounce timer on unmount
      if (emitDebounceRef.current !== null) {
        clearTimeout(emitDebounceRef.current);
      }
    };
  }, []);
 
 
  const showSerialMonitor = serialViewMode !== "plotter";
  const showSerialPlotter = serialViewMode !== "monitor";
 
  const cycleSerialViewMode = useCallback(() => {
    setSerialViewMode((prev) => {
      if (prev === "monitor") return "both";
      if (prev === "both") return "plotter";
      return "monitor";
    });
  }, []);
 
  const clearSerialOutput = useCallback(() => {
    setSerialOutput([]);
    Eif (rendererRef.current) {
      rendererRef.current.clear();
      // Re-enable rendering so the next serial output is displayed.
      // clear() pauses the renderer (to stop current animation), but we must
      // resume() so that data arriving after the clear is not silently dropped.
      rendererRef.current.resume();
    }
    setRenderedSerialText("");
    
    // Clean up any pending debounced emit
    Iif (emitDebounceRef.current !== null) {
      clearTimeout(emitDebounceRef.current);
      emitDebounceRef.current = null;
    }
    pendingOutputRef.current = "";
  }, []);
 
  // Baudrate rendering methods
  const appendSerialOutput = useCallback((text: string) => {
    const isTestMode =
      globalThis.window !== undefined && (globalThis as any).__PLAYWRIGHT_TEST__;
    if (isTestMode) {
      // in tests we bypass baudrate rendering to make output appear instantly
      setRenderedSerialText((prev) => prev + text);
    } else {
      rendererRef.current?.enqueue(text);
    }
    
    // Emit serial output event to parent frame for dashboard monitoring (debounced to 100ms)
    pendingOutputRef.current += text;
    
    Iif (emitDebounceRef.current !== null) {
      clearTimeout(emitDebounceRef.current);
    }
    
    emitDebounceRef.current = setTimeout(() => {
      Eif (pendingOutputRef.current) {
        emitSerialOutput(pendingOutputRef.current);
        pendingOutputRef.current = "";
      }
      emitDebounceRef.current = null;
    }, 100);
  }, []);
 
  const setBaudrate = useCallback((baud: number | undefined) => {
    const isTestMode =
      globalThis.window !== undefined && (globalThis as any).__PLAYWRIGHT_TEST__;
    rendererRef.current?.setBaudrate(isTestMode ? 0 : baud);
  }, []);
 
  const pauseRendering = useCallback(() => {
    rendererRef.current?.pause();
  }, []);
 
  const resumeRendering = useCallback(() => {
    rendererRef.current?.resume();
  }, []);
 
  /**
   * Stop rendering and clear the renderer queue.
   * Used on STOP to prevent old data from leaking into the next simulation.
   * Unlike pauseRendering(), this discards all pending characters.
   */
  const stopRendering = useCallback(() => {
    rendererRef.current?.clear();
  }, []);
 
  /**
   * Inject text directly into rendered output, bypassing the baudrate renderer.
   * Used for system messages ("--- Simulation paused ---" etc.) that must
   * appear instantly regardless of baudrate.
   */
  const appendRenderedText = useCallback((text: string) => {
    setRenderedSerialText((prev) => {
      // Ensure injected text starts on a new line if current output
      // doesn't end with one (e.g., partial serial line was rendering)
      if (prev.length > 0 && !prev.endsWith('\n')) {
        return prev + '\n' + text;
      }
      return prev + text;
    });
  }, []);
 
  return {
    // Existing API (unchanged - for backward compatibility and Plotter)
    serialOutput,
    setSerialOutput,
    serialViewMode,
    setSerialViewMode,
    autoScrollEnabled,
    setAutoScrollEnabled,
    serialInputValue,
    setSerialInputValue,
    showSerialMonitor,
    showSerialPlotter,
    cycleSerialViewMode,
    clearSerialOutput,
    
    // New baudrate rendering API
    renderedSerialText,
    renderedSerialOutput, // OutputLine[] format for SerialMonitor
    appendSerialOutput,
    setBaudrate,
    pauseRendering,
    resumeRendering,
    stopRendering,
    appendRenderedText,
  };
}