Explorar el Código

新增串口日志页面与 MCP serial_log 工具

- 顶部新增「串口日志」标签,支持文本/二进制模式、波特率选择、Probe、智能分析与 RTS 复位
- 支持实时打印、清空/保存、自动滚动与 5000 行滚动缓冲;停止时仅终止 log 子进程,不影响已打开的烧录任务
- MCP 增加 serial_log 工具,可采集指定时长日志返回给 AI 分析
- 同步更新 README 中的功能说明与工具列表
wenhongquan hace 3 semanas
padre
commit
2f9c600ded

+ 1 - 1
README.md

@@ -2,7 +2,7 @@
 
 - [Luatools v3.4.15 逆向分析与多端安装/烧录方案](./Luatools_v3_多端安装与烧录方案.md)
 - [macOS 烧录工具(Electron + luatos-cli)](./luatools-mac/README.md)
-- [macOS 烧录工具 Tauri 版(Rust + luatos-cli;含资源下载、项目管理、MCP)](./luatools-tauri/README.md)
+- [macOS 烧录工具 Tauri 版(Rust + luatos-cli;含资源下载、项目管理、MCP、串口日志)](./luatools-tauri/README.md)
 
 ## macOS 快速开始
 

+ 13 - 0
luatools-tauri/README.md

@@ -65,6 +65,18 @@ Electron 主进程里的命令在 Rust 侧一一对应:
 - 默认下载到应用数据目录的 `resources/`,可以在页面上选择其他目录;下载完成后可在 Finder 中打开。
 - 支持的工具:固件 `.soc`、扩展库、文档包、驱动、量产工具等。
 
+## 串口日志
+
+顶部切到「串口日志」:
+
+- 选择串口和波特率,点「开始监听」即可实时打印设备日志。
+- 文本模式:适合 Air8101 / XT804 / Air724UG 等文本日志,默认 921600。
+- 二进制模式:适合 Air1601/Air1602/CCM4211、Air8000/EC718;默认 2000000,需勾选 Probe。
+- 支持智能分析、RTS 复位、清空/保存日志、自动滚动和 5000 行滚动缓冲。
+- 停止会终止 `luatos-cli log view` 子进程,不会影响已打开的烧录任务。
+
+MCP 也可以用 `serial_log` 采集一段日志(例如 5 秒)返回给 AI 分析。
+
 ## MCP 服务(给 AI 用)
 
 切到「MCP」页面可以看到自动生成的配置。把 JSON 加到 Claude Desktop / Cursor / Codex 等
@@ -95,6 +107,7 @@ MCP 工具:
 | `guide_models` | 列出支持的芯片/型号 |
 | `firmware_info` | 解析 `.soc` |
 | `flash_firmware` | 烧录固件(全量/脚本) |
+| `serial_log` | 采集串口日志(文本/二进制,支持 Probe) |
 | `resource_list` / `resource_download` | 列出/下载 LuatOS CDN 资源 |
 | `project_list` / `project_create` / `project_import` | 项目列表/创建/导入 |
 | `project_info` / `project_config` | 读取/修改项目配置 |

+ 55 - 0
luatools-tauri/src-tauri/mcp/luatos-mcp.mjs

@@ -249,6 +249,24 @@ const TOOLS = [
     },
   },
   {
+    name: 'serial_log',
+    description:
+      '采集一段串口日志(默认 5 秒)并返回文本。Air1601/Air1602/EC718 用 mode=binary,probe 默认开启。',
+    inputSchema: {
+      type: 'object',
+      properties: {
+        port: { type: 'string', description: '串口,例如 /dev/cu.usbmodem1234 或 COM10' },
+        baud: { type: ['string', 'number'], description: '波特率;文本默认 921600,二进制默认 2000000' },
+        mode: { type: 'string', enum: ['text', 'binary'], default: 'text' },
+        duration_secs: { type: 'number', description: '采集秒数,默认 5,最大 60' },
+        probe: { type: 'boolean', description: '二进制模式发送 Probe,默认 true' },
+        smart: { type: 'boolean', description: '启用智能分析' },
+        rts_reset: { type: 'boolean', description: '开始前发送 RTS 复位脉冲' },
+      },
+      required: ['port'],
+    },
+  },
+  {
     name: 'resource_list',
     description: '列出 LuatOS CDN 资源分类;传 module 可列出该分类下的子项、版本和文件。',
     inputSchema: {
@@ -415,6 +433,43 @@ async function callTool(name, args = {}) {
         log_tail: tail(result.lines),
       };
     }
+    case 'serial_log': {
+      if (!args.port) throw new Error('port 不能为空');
+      const mode = args.mode === 'binary' ? 'binary' : 'text';
+      const duration = Math.min(60, Math.max(1, Number(args.duration_secs) || 5));
+      const baud = args.baud || (mode === 'binary' ? 2000000 : 921600);
+      const command = ['log', mode === 'binary' ? 'view-binary' : 'view', '--port', String(args.port), '--baud', String(baud)];
+      if (mode === 'binary' && args.probe !== false) command.push('--probe');
+      if (args.smart) command.push('--smart');
+      if (args.rts_reset) command.push('--rts-reset');
+
+      const result = await runJsonl(command, duration * 1000 + 2000);
+      const logLines = [];
+      for (const event of result.events) {
+        if (event.type === 'log_entry') {
+          const entry = event.entry || {};
+          const prefix = [entry.device_time || entry.timestamp, entry.level, entry.module].filter(Boolean).join(' ');
+          logLines.push(prefix ? `${prefix} ${entry.message || entry.line || ''}` : String(entry.message || entry.line || ''));
+        } else if (event.type === 'message') {
+          logLines.push(String(event.message || ''));
+        } else if (event.type === 'diagnostic') {
+          logLines.push(`[diagnostic] ${JSON.stringify(event.diagnostic || {})}`);
+        } else if (event.type === 'error') {
+          logLines.push(`[error] ${event.message || ''}`);
+        }
+      }
+      if (!logLines.length) logLines.push(...result.lines);
+      const hasEntry = result.events.some((event) => event.type === 'log_entry');
+      const hadError = logLines.some((line) => line.startsWith('[error]'));
+      return {
+        ok: result.error == null && (hasEntry || !hadError),
+        mode,
+        baud,
+        duration_secs: duration,
+        timed_out: result.timedOut,
+        lines: logLines.slice(-600),
+      };
+    }
     case 'resource_list': {
       const command = ['resource', 'list'];
       if (args.module) command.push(args.module);

+ 69 - 0
luatools-tauri/ui/index.html

@@ -38,6 +38,7 @@
 
       <nav class="tabs" id="tabs" aria-label="功能导航">
         <button type="button" class="tab active" data-view="flash">烧录</button>
+        <button type="button" class="tab" data-view="log">串口日志</button>
         <button type="button" class="tab" data-view="projects">项目管理</button>
         <button type="button" class="tab" data-view="resources">资源下载</button>
         <button type="button" class="tab" data-view="mcp">MCP</button>
@@ -168,6 +169,74 @@
         </section>
       </main>
 
+      <main id="view-log" class="page view hidden">
+        <div class="page-head">
+          <div>
+            <h2>串口日志</h2>
+            <p>实时查看设备日志。Air1601/Air1602/EC718 请用二进制模式并勾选 Probe。</p>
+          </div>
+          <div class="page-actions">
+            <button id="btn-log-clear" class="ghost small" type="button">清空</button>
+            <button id="btn-log-save" class="ghost small" type="button">保存</button>
+          </div>
+        </div>
+
+        <section class="card log-control-card">
+          <div class="log-control-grid">
+            <label class="field">
+              <span>串口</span>
+              <div class="input-row">
+                <select id="log-port" class="select" aria-label="日志串口"></select>
+                <button id="btn-log-refresh" class="secondary small" type="button">刷新</button>
+              </div>
+            </label>
+            <label class="field">
+              <span>波特率</span>
+              <select id="log-baud" class="select">
+                <option value="921600" selected>921600</option>
+                <option value="115200">115200</option>
+                <option value="1500000">1500000</option>
+                <option value="2000000">2000000</option>
+                <option value="3000000">3000000</option>
+                <option value="6000000">6000000</option>
+              </select>
+            </label>
+            <label class="field">
+              <span>模式</span>
+              <div id="log-mode" class="segmented" role="tablist" aria-label="日志模式">
+                <button type="button" data-mode="text" class="active" role="tab" aria-selected="true">文本</button>
+                <button type="button" data-mode="binary" role="tab" aria-selected="false">二进制</button>
+              </div>
+            </label>
+            <label class="checkbox field-inline">
+              <input id="log-probe" type="checkbox" checked />
+              <span>Probe</span>
+            </label>
+            <label class="checkbox field-inline">
+              <input id="log-smart" type="checkbox" />
+              <span>智能分析</span>
+            </label>
+            <label class="checkbox field-inline">
+              <input id="log-rts" type="checkbox" />
+              <span>RTS 复位</span>
+            </label>
+          </div>
+          <div class="log-actions-row">
+            <button id="btn-log-start" class="primary" type="button">开始监听</button>
+            <button id="btn-log-stop" class="danger hidden" type="button">停止</button>
+            <span id="log-status" class="muted">未开始</span>
+          </div>
+        </section>
+
+        <section class="card log-view-card">
+          <div class="card-head">
+            <h2>日志输出</h2>
+            <span id="log-count" class="muted">0 行</span>
+          </div>
+          <pre id="serial-log" class="log serial-log" aria-live="polite"></pre>
+        </section>
+      </main>
+
       <main id="view-projects" class="page view hidden">
         <div class="page-head">
           <div>

+ 45 - 0
luatools-tauri/ui/styles.css

@@ -1421,3 +1421,48 @@ button:disabled {
     flex-direction: column;
   }
 }
+
+/* ── Serial log ─────────────────────────────────────────────────── */
+.log-control-card {
+  flex: 0 0 auto;
+}
+
+.log-control-grid {
+  display: grid;
+  grid-template-columns: minmax(220px, 1.4fr) minmax(130px, 0.7fr) minmax(180px, 1fr) auto auto auto;
+  gap: 12px;
+  align-items: end;
+}
+
+.log-actions-row {
+  display: flex;
+  align-items: center;
+  gap: 10px;
+  margin-top: 14px;
+}
+
+.log-view-card {
+  flex: 1;
+  min-height: 0;
+  display: flex;
+  flex-direction: column;
+}
+
+.serial-log {
+  flex: 1;
+  min-height: 260px;
+  height: auto;
+  margin: 0;
+}
+
+@media (max-width: 1100px) {
+  .log-control-grid {
+    grid-template-columns: 1fr 1fr;
+  }
+}
+
+@media (max-width: 640px) {
+  .log-control-grid {
+    grid-template-columns: 1fr;
+  }
+}

+ 227 - 1
luatools-tauri/ui/views.js

@@ -24,6 +24,7 @@
     projectInfo: null,
     activeFile: null,
     resources: { categories: [], activeCategory: null, detail: null, output: '', busy: false },
+    log: { initialized: false, mode: 'text', listening: false, lines: [] },
     mcp: null,
   };
 
@@ -89,7 +90,7 @@
 
   /* ── Navigation ─────────────────────────────────────────────── */
 
-  const VIEWS = ['flash', 'projects', 'resources', 'mcp'];
+  const VIEWS = ['flash', 'log', 'projects', 'resources', 'mcp'];
 
   function showView(name) {
     if (!VIEWS.includes(name)) return;
@@ -106,11 +107,235 @@
     const flashTop = $('#btn-flash-top');
     if (flashTop) flashTop.style.display = name === 'flash' ? '' : 'none';
 
+    if (name === 'log') initSerialLogView().catch((error) => toast(error.message, 'err'));
     if (name === 'projects') loadProjects().catch((error) => toast(error.message, 'err'));
     if (name === 'resources') loadResources().catch((error) => toast(error.message, 'err'));
     if (name === 'mcp') loadMcp().catch((error) => toast(error.message, 'err'));
   }
 
+  /* ── Serial log ─────────────────────────────────────────────── */
+
+  function serialLogLevel(level) {
+    const value = String(level || '').toLowerCase();
+    if (value.includes('error') || value.includes('fatal')) return 'err';
+    if (value.includes('warn')) return 'warn';
+    if (value.includes('debug') || value.includes('verbose')) return 'muted';
+    return 'info';
+  }
+
+  function appendSerialLog(text, level = 'info') {
+    if (!text) return;
+    const log = $('#serial-log');
+    if (!log) return;
+    // eslint-disable-next-line no-control-regex
+    const cleanText = String(text).replace(/\u001b\[[0-9;]*m/g, '');
+    const lines = cleanText.replace(/\r/g, '').split('\n').filter((line) => line.length > 0);
+    for (const raw of lines) {
+      const line = `[${new Date().toTimeString().slice(0, 8)}] ${raw}`;
+      state.log.lines.push(line);
+      if (state.log.lines.length > 5000) state.log.lines.splice(0, state.log.lines.length - 5000);
+
+      const span = document.createElement('span');
+      span.className = 'line';
+      const time = document.createElement('span');
+      time.className = 't';
+      time.textContent = new Date().toTimeString().slice(0, 8);
+      const body = document.createElement('span');
+      body.className = level;
+      body.textContent = raw;
+      span.append(time, body);
+      log.appendChild(span);
+      while (log.children.length > 5000) log.firstElementChild?.remove();
+    }
+    const count = state.log.lines.length;
+    $('#log-count').textContent = `${count} 行`;
+    const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
+    if (nearBottom) log.scrollTop = log.scrollHeight;
+  }
+
+  function appendLogEntry(entry = {}) {
+    const time = entry.device_time || entry.timestamp || '';
+    const module = entry.module || entry.tag || '';
+    const level = String(entry.level || 'info');
+    const message = entry.message || entry.line || JSON.stringify(entry);
+    const prefix = [time, level, module].filter(Boolean).join(' ');
+    appendSerialLog(prefix ? `${prefix} ${message}` : message, serialLogLevel(level));
+  }
+
+  function updateLogButtons() {
+    const listening = state.log.listening;
+    $('#btn-log-start').classList.toggle('hidden', listening);
+    $('#btn-log-stop').classList.toggle('hidden', !listening);
+    $('#log-port').disabled = listening;
+    $('#log-baud').disabled = listening;
+    $('#btn-log-refresh').disabled = listening;
+    $$('#log-mode button').forEach((button) => {
+      button.disabled = listening;
+    });
+  }
+
+  function setLogMode(mode) {
+    state.log.mode = mode;
+    $$('#log-mode button').forEach((button) => {
+      const active = button.dataset.mode === mode;
+      button.classList.toggle('active', active);
+      button.setAttribute('aria-selected', active ? 'true' : 'false');
+    });
+    const probe = $('#log-probe');
+    if (probe) probe.disabled = mode !== 'binary';
+    if (mode === 'binary') {
+      $('#log-baud').value = '2000000';
+    } else {
+      $('#log-baud').value = '921600';
+    }
+  }
+
+  async function refreshLogPorts() {
+    const select = $('#log-port');
+    if (!select) return;
+    select.textContent = '';
+    const result = await api.listPorts();
+    const ports = result?.ok ? result.ports || [] : [];
+    if (!ports.length) {
+      const option = document.createElement('option');
+      option.value = '';
+      option.textContent = result?.ok ? '未发现串口' : `扫描失败:${result?.error || ''}`;
+      select.appendChild(option);
+      return;
+    }
+    for (const port of ports) {
+      const option = document.createElement('option');
+      option.value = port.port_name || '';
+      const bits = [port.port_name];
+      if (port.product) bits.push(port.product);
+      option.textContent = bits.join(' · ');
+      select.appendChild(option);
+    }
+    const preferred = window.__luatos?.state?.port;
+    if (preferred && ports.some((port) => port.port_name === preferred)) {
+      select.value = preferred;
+    }
+  }
+
+  async function startSerialLog() {
+    if (state.log.listening) return;
+    const port = $('#log-port').value;
+    if (!port) {
+      toast('请选择串口', 'err');
+      return;
+    }
+    const mode = state.log.mode;
+    const baud = $('#log-baud').value;
+    const args = ['log', mode === 'binary' ? 'view-binary' : 'view', '--port', port, '--baud', baud];
+    if (mode === 'binary' && $('#log-probe').checked) args.push('--probe');
+    if ($('#log-smart').checked) args.push('--smart');
+    if ($('#log-rts').checked) args.push('--rts-reset');
+
+    state.log.listening = true;
+    state.log.stopping = false;
+    updateLogButtons();
+    $('#log-status').textContent = '正在连接…';
+    appendSerialLog(`开始监听 ${port} @ ${baud} bps(${mode === 'binary' ? '二进制' : '文本'})`, 'cmd');
+    try {
+      const result = await api.startCliStream('log', args);
+      if (result?.error && !state.log.stopping) {
+        appendSerialLog(result.error, 'err');
+      }
+    } catch (error) {
+      appendSerialLog(error.message || String(error), 'err');
+      toast('串口日志启动失败', 'err');
+    } finally {
+      state.log.listening = false;
+      updateLogButtons();
+      if (!state.log.stopping) $('#log-status').textContent = '已停止';
+    }
+  }
+
+  async function stopSerialLog() {
+    if (!state.log.listening) return;
+    state.log.stopping = true;
+    $('#log-status').textContent = '正在停止…';
+    const result = await api.cancelCliStream('log');
+    if (!result?.ok) {
+      appendSerialLog(result?.error || '停止失败', 'err');
+    }
+  }
+
+  async function saveSerialLog() {
+    if (!state.log.lines.length) {
+      toast('日志为空', 'err');
+      return;
+    }
+    const result = await api.saveLog(state.log.lines.join('\n'));
+    if (result?.ok) {
+      toast(`日志已保存:${result.path}`, 'ok');
+    } else if (result?.error) {
+      toast(result.error, 'err');
+    }
+  }
+
+  function clearSerialLog() {
+    state.log.lines = [];
+    const log = $('#serial-log');
+    if (log) log.textContent = '';
+    $('#log-count').textContent = '0 行';
+  }
+
+  function bindSerialLogEvents() {
+    $('#btn-log-start').addEventListener('click', () => startSerialLog().catch((error) => toast(error.message, 'err')));
+    $('#btn-log-stop').addEventListener('click', () => stopSerialLog().catch((error) => toast(error.message, 'err')));
+    $('#btn-log-refresh').addEventListener('click', () => refreshLogPorts().catch((error) => toast(error.message, 'err')));
+    $('#btn-log-clear').addEventListener('click', clearSerialLog);
+    $('#btn-log-save').addEventListener('click', () => saveSerialLog().catch((error) => toast(error.message, 'err')));
+    $('#log-mode').addEventListener('click', (event) => {
+      const button = event.target.closest('button[data-mode]');
+      if (!button || state.log.listening) return;
+      setLogMode(button.dataset.mode);
+    });
+
+    api.onCliEvent('log', (event) => {
+      if (!event || typeof event !== 'object') return;
+      if (event.type === 'log_entry') {
+        appendLogEntry(event.entry || {});
+      } else if (event.type === 'message') {
+        appendSerialLog(event.message || '', serialLogLevel(event.level));
+      } else if (event.type === 'diagnostic') {
+        const diagnostic = event.diagnostic || {};
+        appendSerialLog(`[诊断] ${diagnostic.message || JSON.stringify(diagnostic)}`, 'warn');
+      } else if (event.type === 'error') {
+        appendSerialLog(event.message || '日志错误', 'err');
+      } else if (event.type === 'result') {
+        appendSerialLog(`日志会话结束:${event.status}`, event.status === 'ok' ? 'ok' : 'warn');
+      }
+    });
+    api.onCliLine('log', ({ line, source }) => {
+      if (line) appendSerialLog(line, source === 'stderr' ? 'muted' : 'info');
+    });
+    api.onCliExit('log', ({ code, signal, error }) => {
+      state.log.listening = false;
+      state.log.stopping = false;
+      updateLogButtons();
+      if (error) {
+        appendSerialLog(error, 'err');
+        $('#log-status').textContent = '异常退出';
+      } else {
+        const suffix = signal ? `signal=${signal}` : `code=${code}`;
+        $('#log-status').textContent = `已停止(${suffix})`;
+        appendSerialLog(`监听结束(${suffix})`, code === 0 ? 'ok' : 'warn');
+      }
+    });
+  }
+
+  async function initSerialLogView() {
+    if (!state.log.initialized) {
+      state.log.initialized = true;
+      bindSerialLogEvents();
+      updateLogButtons();
+      setLogMode('text');
+      await refreshLogPorts();
+    }
+  }
+
   /* ── Projects ───────────────────────────────────────────────── */
 
   function projectLog(text, level = 'info') {
@@ -823,6 +1048,7 @@
     'guide_models',
     'firmware_info',
     'flash_firmware',
+    'serial_log',
     'resource_list',
     'resource_download',
     'project_list',