# miles10428/sigroklogger architecture

> Architecture diagram of the GitHub repository miles10428/sigroklogger, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-10). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/miles10428/sigroklogger
- Repository: https://github.com/miles10428/sigroklogger

## Overview

##### 專案類型與目的（從 README + file tree 判斷）
這是一個**單檔 C# 自動化工具/程式庫（automation utility / wrapper）**，核心目的不是提供 Web 服務或 UI，而是：
- 在 Windows 上以 C# **呼叫外部工具 `sigrok-cli`**，
- 針對 fx2lafw 類邏輯分析儀（例如 nanoDLA）做**多通道數位訊號擷取**，
- 提供**重試、延遲、指定擷取時長、背景執行緒、隨時停止、檔案自動命名、日誌目錄管理**等自動化能力，
- 產出 `.sr` 擷取檔，後續可用 PulseView（含額外 decoder）解析。

檔案結構極簡：
- `SigrokLogger.cs`：幾乎涵蓋所有架構與功能（主體類別 `SigrokLogger.SigrokCapture` 及其流程）
- `README.md`：描述安裝、依賴、如何呼叫 API

因此你的系統設計圖應該以「**C# wrapper 對外部 CLI + 硬體裝置 + 檔案系統**」的互動為主，而不是傳統前後端分層。

##### 從檔案結構推導可拆的架構元件（即使在同一檔案也要拆）
雖然只有 `SigrokLogger.cs`，畫圖時請把它**拆成多個邏輯元件**（同一個 assembly/namespace 內部 component）來呈現「真實責任分離」：

建議在圖上把 `SigrokLogger.cs` 拆成至少這些 conceptual components（名稱可依實作調整）：
##### SigrokCapture API（對外入口）
- `StartCaptureWithThread(maxAttempts, durationMs, step)`
- `StopCapture()`
- 對上層呼叫者提供「開始/停止」與參數輸入

##### Capture Orchestrator（擷取流程編排）
- 控制重試次數、每次嘗試間隔、成功/失敗判定
- 維持 capture state（Running/Stopping/Stopped）

##### Thread/Task Runner（背景執行緒控制）
- 將擷取放到 background thread 執行
- Stop 時做 cancellation / process kill / join thread（依程式實作）

##### Sigrok-cli Process Runner（外部程序呼叫器）
- 組裝 `sigrok-cli` command line arguments（duration、channels、output file…）
- `Process.Start` / stdout/stderr 收集
- exit code / timeout / error handling

##### File Naming & Directory Manager（檔名/目錄策略）
- `BaseLogPath` + `YYYYMMDD\YYYYMMDD_HHMMSS_step_X.sr`
- 每日資料夾建立
- 路徑合法性（Windows 路徑）

##### Logging（記錄機制）
- 把「分步驟記錄」和錯誤資訊寫到檔案/console（依實作）
- 日誌目錄也屬於系統的一部分（README 提到會建立每日日誌目錄）

##### Configuration（環境/路徑設定）
- `SoftwarePath`（sigrok-cli 安裝路徑）
- `BaseLogPath`
- 圖上要標明這些是「部署/環境設定」，不是業務邏輯

README 明確提到這些都不是你程式內部的一部分，但對系統成功至關重要：

- **Windows OS**
- **sigrok-cli（外部可執行檔）**
- **PulseView（用於分析 `.sr`）**
- **PulseView protocol decoders（如 I2C ASCII decoder）**
- **硬體：fx2lafw 韌體邏輯分析儀（例如 nanoDLA）**
- （可選）USB driver / libusb（通常隱含在 sigrok stack 內，但你可在圖上以「Sigrok driver stack」作為 sigrok-cli 與硬體之間的抽象層）

##### 建議你畫的「最準確」架構圖：用 C4 + 流程圖補齊
由於這是工具型專案，建議至少畫 **兩張**（越完整可再加第三張）：

##### (A) C4 Container/Context 風格（系統邊界與依賴）
畫「誰依賴誰」與資料流向，適合放在 README 或設計文件首頁。

**元素（建議框/顏色）**
- 你的系統邊界：`SigrokLogger (C# Library/Tool)`
- 外部：
- `sigrok-cli (External CLI)`
- `fx2lafw Logic Analyzer (Hardware)`
- `File System (BaseLogPath, .sr outputs, logs)`
- `PulseView + Decoders (Analysis Tooling)`
- `Caller App/Test Harness`（使用者自己的測試程式或自動化框架，呼叫 `SigrokCapture`）

**箭頭（方向要明確）**
- Caller App → SigrokLogger：呼叫 Start/Stop + 傳參數（attempts/duration/step）
- SigrokLogger → sigrok-cli：spawn process + arguments
- sigrok-cli → Hardware：透過 driver stack 擷取訊號
- sigrok-cli → File System：輸出 `.sr`
- SigrokLogger → File System：建立目錄、寫日誌（若有）
- PulseView → File System：讀取 `.sr`，decoder 解析

> 這張圖要表達的核心：SigrokLogger 本質是 orchestrator/wrapper，真正擷取由 sigrok-cli + hardware 完成。

即使實作都在 `SigrokLogger.cs`，也要在圖上拆出「邏輯元件」，以便未來重構、測試、替換：

SigrokLogger（框內）放：
- `SigrokCapture API`
- `Capture Orchestrator`
- `Thread Runner`
- `Process Runner`
- `File Naming/Directory Manager`
- `Logger`
- `Configuration`

箭頭示例：
- `SigrokCapture API` → `Thread Runner`（StartCaptureWithThread）
- `Thread Runner` → `Capture Orchestrator`
- `Capture Orchestrator` → `File Naming/Directory Manager`（每次 attempt/step 生成 output path）
- `Capture Orchestrator` → `Process Runner`（執行 sigrok-cli）
- `Process Runner` → `sigrok-cli`（外部邊界）
- `StopCapture` → `Thread Runner` / `Process Runner`（取消/終止）

因為此專案的價值在「重試 + 背景執行 + 可停止」，單靠靜態方塊圖不夠精確。用時序圖把關鍵行為畫出來：

生命線：
- Caller
- SigrokCapture
- Thread Runner
- Orchestrator
- File Manager
- Process Runner
- sigrok-cli
- File System

主要流程：
##### loop（attempt 1..N）：
- Orchestrator → File Manager: `EnsureDailyDir()` + `BuildOutputFilename(step, timestamp)`
- Orchestrator → Process Runner: `RunSigrokCli(args, durationMs, outputFile)`
- Process Runner → sigrok-cli: spawn
- sigrok-cli → File System: write `.sr`
- Process Runner → Orchestrator: exit code / stderr
- Orchestrator: success break; else delay then retry
##### Thread Runner: join/cleanup

這張圖可以非常準確地呈現「停止」會影響哪個元件（thread? process? both）。

##### 背景執行：StartCaptureWithThread → background thread/task（這影響停止語意）
4. **StopCapture 行為**：是設旗標、取消 token、kill process、還是等待自然結束（依程式碼實作；若你要最精確，請在看完 `SigrokLogger.cs` 後把實際策略寫在圖的註解框）
##### 外部工具鏈：sigrok-cli 與 PulseView decoders 的關係不要混在一起（擷取 vs 解析）

請在圖中統一使用以下區分（特別適合這種「工具 + 外部依賴」）：

- **顏色/形狀**
- 藍色：你維護的 C# 元件（SigrokLogger 內部 components）
- 灰色：外部依賴（sigrok-cli、PulseView、decoders）
- 橘色：硬體（logic analyzer）
- 綠色：資料儲存（File System：log dir、.sr files）
- **箭頭**
- 實線箭頭：同步呼叫/控制流（Start/Run/Stop）
- 虛線箭頭：資料流（.sr 檔寫入/讀取、stderr/stdout）
- **標籤**
- 每條關係都加上動詞與資料：例如 “spawn process (sigrok-cli …)” / “writes .sr” / “reads .sr for decode”

##### 你可以直接照抄的「最小但完整」圖內容清單（不要過度抽象）

- Caller App / Test Automation
- SigrokLogger
- SigrokCapture API
- Background Thread Runner
- Retry/Orchestrator
- Process Runner (sigrok-cli invoker)
- File Naming & Directory Manager
- Logger
- Config (SoftwarePath, BaseLogPath)
- sigrok-cli (external)
- Sigrok driver/USB stack（可選抽象）
- fx2lafw Logic Analyzer (nanoDLA)
- Windows File System (BaseLogPath)
- Daily Folder YYYYMMDD
- File .sr
- Log Files (if any)
- PulseView + Decoders (I2C ASCII etc.)

把這些全拆出來，你的圖就會「很細」且對未來擴充（例如支援不同硬體、不同輸出格式、或改用 libsigrok API）非常有用。

## Diagram (Mermaid)

```mermaid
flowchart TD
  %% =========================
  %% (A) Context / Container View
  %% =========================
  subgraph "A) System Context (C4-style)"
    direction TB

    Caller["Caller App / Test Automation"]:::external

    subgraph "SigrokLogger (C# Library/Tool)"
      direction TB
      SL_Boundary["SigrokLogger Boundary"]:::boundary
    end

    SigrokCLI["sigrok-cli (External CLI)"]:::external
    DriverStack["Sigrok driver / USB stack (abstract)"]:::external
    Hardware["fx2lafw Logic Analyzer (e.g., nanoDLA)"]:::hardware

    subgraph "Windows File System (BaseLogPath)"
      direction TB
      FSRoot[("BaseLogPath")]:::storage
      DailyDir["Daily Folder (YYYYMMDD)"]:::storage
      SrFile["Capture Output (.sr)\nYYYYMMDD_HHMMSS_step_X.sr"]:::storage
      LogFiles["Log Files (if any)"]:::storage
    end

    PulseView["PulseView (Analysis Tool)"]:::external
    Decoders["PulseView Protocol Decoders\n(e.g., I2C ASCII)"]:::external
    WindowsOS["Windows OS"]:::external
  end

  %% Context connections (control vs data)
  Caller -->|"Start/Stop (attempts,durationMs,step)"| SL_Boundary
  SL_Boundary -->|"spawn process (sigrok-cli args)"| SigrokCLI
  SigrokCLI -->|"uses driver stack"| DriverStack
  DriverStack -->|"captures signals via USB"| Hardware

  SL_Boundary -->|"create dirs / write logs"| FSRoot
  FSRoot -->|"contains"| DailyDir
  DailyDir -->|"contains"| SrFile
  DailyDir -->|"contains"| LogFiles

  SigrokCLI -.->|"writes .sr session"| SrFile
  SigrokCLI -.->|"stdout/stderr"| SL_Boundary

  PulseView -->|"reads .sr"| SrFile
  PulseView -->|"loads"| Decoders

  SL_Boundary -.->|"runs on"| WindowsOS
  SigrokCLI -.->|"runs on"| WindowsOS

  %% =========================
  %% (B) Component View (internal decomposition)
  %% =========================
  subgraph "B) SigrokLogger Internal Components (conceptual, same assembly)"
    direction TB

    subgraph "Public API"
      direction TB
      API["SigrokCapture API\n(StartCaptureWithThread / StopCapture)"]:::cs
    end

    subgraph "Execution & Control"
      direction TB
      ThreadRunner["Thread/Task Runner\n(background thread, stop/join)"]:::cs
      Orchestrator["Capture Orchestrator\n(retry, delay, state)"]:::cs
    end

    subgraph "Integration"
      direction TB
      ProcRunner["Sigrok-cli Process Runner\n(args, Process.Start, stdout/stderr,\nexit code/timeout)"]:::cs
    end

    subgraph "IO & Observability"
      direction TB
      FileMgr["File Naming & Directory Manager\n(BaseLogPath, daily dir,\nYYYYMMDD_HHMMSS_step_X.sr)"]:::cs
      Logger["Logging\n(step logs / errors / console)"]:::cs
    end

    subgraph "Configuration (deployment-coupled)"
      direction TB
      Config["Configuration\n(SoftwarePath, BaseLogPath)"]:::config
    end
  end

  %% Internal component relationships
  API -->|"StartCaptureWithThread()"| ThreadRunner
  API -->|"StopCapture()"| ThreadRunner

  ThreadRunner -->|"run capture loop"| Orchestrator
  ThreadRunner -->|"cancel/stop signal"| Orchestrator

  Orchestrator -->|"ensure dir + build output path"| FileMgr
  Orchestrator -->|"run attempt (durationMs)"| ProcRunner
  Orchestrator -->|"log steps / errors"| Logger
  Orchestrator -->|"read config"| Config

  ProcRunner -->|"locate executable (SoftwarePath)"| Config
  ProcRunner -->|"spawn sigrok-cli"| SigrokCLI
  ProcRunner -.->|"stdout/stderr + exit code"| Orchestrator

  FileMgr -->|"create daily folder"| DailyDir
  FileMgr -->|"target .sr path"| SrFile
  Logger -->|"write logs"| LogFiles

  ThreadRunner -->|"kill process (if running)"| ProcRunner

  %% =========================
  %% (C) Sequence Diagram (key behavior)
  %% =========================
  subgraph "C) Capture Sequence (one session with retry + stop)"
    direction TB

    SeqNote["Notes:\n- Output: .sr (sigrok session)\n- Retry: maxAttempts + retry delay\n- Background execution: StartCaptureWithThread()\n- StopCapture(): cancel + kill/join (implementation-specific)"]:::note

    subgraph "Sequence Overview"
      direction TB
      S1["1) Caller -> API: StartCaptureWithThread(maxAttempts,durationMs,step)"]:::seq
      S2["2) API -> ThreadRunner: start background thread/task"]:::seq
      S3["3) loop attempt 1..N:\n   Orchestrator -> FileMgr: EnsureDailyDir + BuildOutputFilename\n   Orchestrator -> ProcRunner: RunSigrokCli(args,durationMs,outputFile)\n   ProcRunner -> sigrok-cli: spawn\n   sigrok-cli -> FileSystem: write .sr\n   ProcRunner -> Orchestrator: exit code/stderr\n   Orchestrator: success break else delay+retry"]:::seq
      S4["4) Caller -> API: StopCapture()"]:::seq
      S5["5) API/ThreadRunner -> ProcRunner: cancel/kill process (if running)\n   ThreadRunner: join/cleanup"]:::seq
    end
  end

  %% Keep sequence tied to actual components (light linkage, vertical)
  S1 --> API
  S2 --> ThreadRunner
  S3 --> Orchestrator
  S3 --> ProcRunner
  S3 --> FileMgr
  S4 --> API
  S5 --> ThreadRunner

  %% =========================
  %% Click Events (from component_mapping)
  %% =========================
  click SL_Boundary "https://github.com/miles10428/sigroklogger/blob/main/SigrokLogger.cs"
  click API "https://github.com/miles10428/sigroklogger/blob/main/SigrokLogger.cs"
  click Orchestrator "https://github.com/miles10428/sigroklogger/blob/main/SigrokLogger.cs"
  click ThreadRunner "https://github.com/miles10428/sigroklogger/blob/main/SigrokLogger.cs"
  click ProcRunner "https://github.com/miles10428/sigroklogger/blob/main/SigrokLogger.cs"
  click FileMgr "https://github.com/miles10428/sigroklogger/blob/main/SigrokLogger.cs"
  click Logger "https://github.com/miles10428/sigroklogger/blob/main/SigrokLogger.cs"
  click Config "https://github.com/miles10428/sigroklogger/blob/main/SigrokLogger.cs"
  click SeqNote "https://github.com/miles10428/sigroklogger/blob/main/README.md"

  %% =========================
  %% Styles (color-coded)
  %% =========================
  classDef cs fill:#1f77b4,stroke:#0b3d91,color:#ffffff,stroke-width:1.5px
  classDef boundary fill:#2b6cb0,stroke:#0b3d91,color:#ffffff,stroke-width:2px
  classDef external fill:#6b7280,stroke:#374151,color:#ffffff,stroke-width:1.5px
  classDef hardware fill:#f59e0b,stroke:#b45309,color:#111827,stroke-width:1.5px
  classDef storage fill:#10b981,stroke:#065f46,color:#052e1b,stroke-width:1.5px
  classDef config fill:#7c3aed,stroke:#4c1d95,color:#ffffff,stroke-width:1.5px
  classDef note fill:#fde68a,stroke:#b45309,color:#111827,stroke-width:1px
  classDef seq fill:#93c5fd,stroke:#1d4ed8,color:#111827,stroke-width:1px
```
