diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d20a9fd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,59 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + QT_VERSION: "6.12.0" + AQT_SOURCE: "git+https://github.com/miurahr/aqtinstall.git" + +jobs: + build-and-test: + name: Build and test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, windows-2022, macos-15] + steps: + - name: Check out sources and submodules + uses: actions/checkout@v6 + with: + submodules: recursive + + - name: Install Linux dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y ninja-build libgl1-mesa-dev libxcb-cursor0 libxkbcommon-x11-0 + + - name: Install Qt + uses: jurplel/install-qt-action@v4 + with: + version: ${{ env.QT_VERSION }} + aqtsource: ${{ env.AQT_SOURCE }} + modules: "qt5compat qtserialport" + cache: true + + - name: Configure Windows + if: runner.os == 'Windows' + run: cmake -S . -B build/ci -G "Visual Studio 17 2022" -A x64 -DBUILD_TESTING=ON + + - name: Configure macOS and Linux + if: runner.os != 'Windows' + run: cmake -S . -B build/ci -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON + + - name: Build + run: cmake --build build/ci --config Release --parallel 2 + + - name: Test + run: ctest --test-dir build/ci -C Release --output-on-failure --no-tests=error diff --git a/CHANGELOG.md b/CHANGELOG.md index f0b3f00..212c43e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ 本项目遵循面向用户的变更记录格式。版本号在正式发布前可能继续调整。 +## [0.1.29] - 2026-11-17 + +### 新增 + +- 协议模板可定义载荷字段的类型、字节序、倍率、加值和设备地址;新增实时解析窗口,按模板、地址、字段查看数值,勾选即可比较多个设备的曲线,对应 [#20](https://github.com/txp666/FluentSerialAssistant/issues/20)。 +- 协议编辑器与曲线窗口共用模板字段和解析规则;“创建曲线”带入当前模板与样例,保存同名模板后同步关联曲线并清空旧数据。 + +### 改进 + +- 协议编辑器始终显示字节图和右侧模板设置,字段列表用对应颜色展示字节与解析值,支持拖动数据字段调整顺序;解析窗口可收起左侧配置区。 +- 按字段类型和协议配置自动生成匹配样例并重算长度、校验。手动粘贴或“最新接收”的样例在编辑配置时保留,清空后继续编辑可恢复自动生成。 +- 协议解析与曲线共用断帧逻辑,支持分批接收和连续多帧;已断帧的数据块可跳过长度越界的残缺候选。 + +### 修复 + +- 串口断开、重新连接时丢弃未收齐的半帧,避免不同连接的数据拼接;已采集的曲线保留。 +- 保存其他模板时不再覆盖当前曲线使用的模板草稿。 +- 修复 Qt 6.12.0 下数值输入框在窄布局后恢复宽度仍不显示数值,以及 macOS 辅助功能访问动态表格时可能崩溃的问题。 +- 更新 FluentQtWidgets,补齐表格排序箭头资源。 + ## [0.1.28] - 2026-11-15 ### 新增 diff --git a/CMakeLists.txt b/CMakeLists.txt index ad0ebce..e18ec28 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,11 +2,17 @@ cmake_minimum_required(VERSION 3.21) project( FluentSerialAssistant - VERSION 0.1.28 + VERSION 0.1.29 DESCRIPTION "A Fluent Qt serial assistant prototype" LANGUAGES CXX ) +if(APPLE) + enable_language(OBJCXX) + set(CMAKE_OBJCXX_STANDARD 17) + set(CMAKE_OBJCXX_STANDARD_REQUIRED ON) +endif() + include(GNUInstallDirs) set(CMAKE_CXX_STANDARD 17) @@ -131,6 +137,10 @@ add_executable(FluentSerialAssistant src/app/view/plot_parser_dialog.h src/app/view/protocol_template_window.cpp src/app/view/protocol_template_window.h + src/app/view/protocol_payload_editor.cpp + src/app/view/protocol_payload_editor.h + src/app/view/protocol_analysis_window.cpp + src/app/view/protocol_analysis_window.h src/app/view/quick_plot_window.cpp src/app/view/quick_plot_window.h src/app/view/settings_page.cpp @@ -200,6 +210,12 @@ target_link_libraries(FluentSerialAssistant FluentSerialPlotParser ) +if(APPLE AND Qt6_VERSION VERSION_EQUAL "6.12.0") + target_sources(FluentSerialAssistant PRIVATE src/app/core/macos_accessibility_fix.mm) + set_source_files_properties(src/app/core/macos_accessibility_fix.mm PROPERTIES COMPILE_OPTIONS "-fno-objc-arc") + target_link_libraries(FluentSerialAssistant PRIVATE "-framework AppKit") +endif() + if(WIN32) target_link_libraries(FluentSerialAssistant PRIVATE shell32) endif() @@ -219,7 +235,7 @@ if(BUILD_TESTING) ) get_target_property(workbench_test_libraries FluentSerialAssistant LINK_LIBRARIES) target_link_libraries(FluentSerialTestSupport PUBLIC ${workbench_test_libraries}) - foreach(test_name IN ITEMS data_table_model frame_codecs plot_value_parser control_service workbench_data_table workbench_quick_plot workbench_reliability protocol_windows terminal_view terminal_colors + foreach(test_name IN ITEMS data_table_model frame_codecs plot_value_parser control_service workbench_data_table workbench_quick_plot workbench_reliability protocol_windows protocol_analysis terminal_view terminal_colors auto_reply virtual_serial_pair virtual_serial_workbench update_downloader update_installer update_ui update_manager main_window) add_executable(tst_${test_name} tests/tst_${test_name}.cpp) @@ -227,6 +243,17 @@ if(BUILD_TESTING) add_test(NAME ${test_name} COMMAND tst_${test_name}) set_tests_properties(${test_name} PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen" TIMEOUT 120) endforeach() + if(APPLE AND Qt6_VERSION VERSION_EQUAL "6.12.0") + add_executable(tst_macos_accessibility + tests/tst_macos_accessibility.mm + src/app/core/macos_accessibility_fix.mm + ) + target_include_directories(tst_macos_accessibility PRIVATE src) + target_compile_options(tst_macos_accessibility PRIVATE -fno-objc-arc) + target_link_libraries(tst_macos_accessibility PRIVATE Qt6::Widgets Qt6::Test "-framework AppKit") + add_test(NAME macos_accessibility COMMAND tst_macos_accessibility) + set_tests_properties(macos_accessibility PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=cocoa" TIMEOUT 120) + endif() endif() add_executable(fluentserial-cli diff --git a/README.md b/README.md index fdb359e..0a6e9eb 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,9 @@ Fluent 串口助手提供现代 Fluent 风格的串口终端,覆盖连接、 帧协议编辑器

帧协议编辑器:字节结构、字段和校验一目了然

数据表格

数据表格:按帧查看 HEX、文本和校验结果

+ + 协议解析:按地址查看三个设备的实时字段,并在同一张图上比较曲线

协议解析:按地址查看三个设备的实时字段,并在同一张图上比较曲线

+ ## 下载安装 @@ -70,6 +73,7 @@ macOS 版本未经 Apple 公证,首次打开被系统阻止时,请在“系 ### 协议与工具 - 帧协议模板:在可视化编辑器中定义帧头、长度、命令、载荷、校验和帧尾,校验可从指定偏移开始计算,用样例或最新接收帧检查解析结果;启用后接收记录会标注命令和校验状态。 +- 协议解析窗口:在模板中定义载荷字段和设备地址,直接查看实时数值,勾选字段即可在同一张图上比较不同设备、不同模板的曲线。 - 校验工具:CRC16-Modbus、CRC16-CCITT、CRC32、LRC、XOR、SUM8,可手动计算或在发送时自动追加;可跳过开头和末尾的字节(如帧头、帧尾),校验码插在末尾跳过的字节和换行符之前。 - Modbus RTU:生成常用读写请求、自动追加 CRC,并解析响应摘要。 @@ -100,15 +104,25 @@ macOS 版本未经 Apple 公证,首次打开被系统阻止时,请在“系 1. 选择串口并设置波特率、数据位、校验位、停止位和流控,点击“连接”。 2. 在终端查看收发记录;需要时开启时间戳、自动断帧或切换 HEX 显示。 3. 在发送区输入文本或 HEX,选择行结束符和编码后发送;可勾选校验自动追加或循环发送。 -4. 点击终端工具栏的曲线图标,选择解析协议并确认,即可新建一个曲线窗口。 -5. 在左侧“协议模板”中点击“编辑协议”定义帧格式,保存并启用后,接收记录会显示解析结果。 +4. 点击终端工具栏的曲线图标,确认解析设置即可新建曲线窗口;当前协议模板已定义数据字段时,会直接带入模板和字段。 +5. 在左侧“协议模板”中点击“编辑协议”定义帧格式和载荷字段,保存后勾选“启用”,直接打开数据与曲线解析窗口。 6. 用常用包、宏命令、自动应答或脚本插件把重复操作自动化。 7. 点击终端工具栏最左侧的扫把按钮,同时清空终端和收发计数;用 TXT、CSV、BIN 导出记录。 +### 协议解析窗口 + +1. 点击“编辑协议”,在“字段解析”区域按 1 / 2 / 4 / 8 B 或 Float32 / Float64 添加数据字段;字段按整帧字节顺序排列,同一行显示类型、整帧位置、原始 HEX、解析值和状态。选中一行后,在固定的右侧属性区设置名称、载荷内起点、数值类型、字节序、倍率和加值;右侧“模板设置”常驻显示,集中提供新建、切换、保存和删除操作;下方通过字段选择框配置帧头、长度、设备地址、命令、校验和帧尾。 + 可上下拖动数据字段调整顺序,载荷偏移随之更新。字段值按“原始值 × 倍率 + 加值”换算,保存后生效。字节图始终显示,字段列表的色块和 HEX 底色与字节图对应;点击字节图或列表中的字段可联动查看属性;新建或切换到没有保存样例的模板、修改协议配置时,会自动生成匹配样例,并重算长度和校验;也可直接粘贴 HEX 或使用“最新接收”分析实际数据;这类样例在修改名称、倍率等配置时保留原始字节,清空样例后继续编辑可恢复自动生成。样例缺少数据时明确显示缺失字节数。 +2. 同一总线上有多个设备时,设置地址字节数和地址在整帧中的偏移,解析窗口会按地址的 HEX 字节分组;不区分地址时选择“不区分设备地址”。同一个模板最多定义 32 个载荷字段,未定义时按载荷字节显示 CH1、CH2 等。 +3. 勾选左侧协议模板的“启用”即可打开解析窗口;关闭窗口后可点击“解析数据与曲线”再次打开,沿用当前协议和曲线勾选。需要解析多种帧格式时,在窗口中勾选多个模板。 +4. 列表显示各设备字段的当前值和更新时间,勾选“曲线”即可绘制,共用以秒为单位的时间轴。点击窗口顶部“配置”可收起或展开左侧模板与字段列表,收起后继续采集和绘图,并显示图例以区分设备曲线。窗口最多显示 256 个数据字段,同时绘制 32 条曲线;曲线保留最近 12,000 个点。关闭后再次打开或重启应用会保留曲线勾选。 +5. 暂停、隐藏、最小化或关闭窗口时停止采集;清空后保留字段和勾选,更改参与解析的模板或保存模板修改后清空历史。校验失败的帧不更新数值,缺少的字段显示“—”。原始串口流按模板长度字段或固定载荷长度重组分批接收的数据;没有长度信息时,请在接收设置中先配置断帧。已断帧的数据块会跳过长度越界的残缺候选,继续解析后续帧;原始流仍等待声明长度,避免误切载荷中的帧头。 + ### 曲线窗口 - 每次确认都会新建一个独立窗口,可同时打开多个窗口分别绘制不同字段;窗口左上角的按钮显示当前协议,点击可修改解析设置。 - 用文本或 HEX 样例预览解析结果;二进制字段可配置类型、字节偏移、大小端、比例和偏移,并从完整帧或协议模板载荷中取数。 +- 协议编辑器中的“创建曲线”直接带入当前模板、字段和样例;终端工具栏也会优先使用当前已配置数据字段的模板。模板模式共用字段定义、收帧与校验逻辑,按设备地址分别绘图,可通过“编辑协议”返回编辑器。保存同名模板后,关联曲线同步字段并清空旧数据,开始重新采样。 - 点击工具栏的“通道数据”可展开或隐藏右侧面板,隐藏后曲线占满空间,数据接收和通道设置继续保留。列表显示各通道的颜色和最新值,勾选通道控制曲线显隐;拖动中间分隔条可调整列表宽度。 - “通道设置”默认收起,点击可单独展开或隐藏。选中通道后设置倍率和偏移,按“显示值 = 解析值 × 倍率 + 偏移”同步更新已有曲线、新数据和 CSV 导出;解析值保留,可用“重置当前通道”恢复。二进制字段先应用解析设置中的比例和加值,再应用这里的倍率和偏移。 - 每个窗口的通道设置独立,清空数据后按通道名称保留;更换解析配置或载荷模板后重置,关闭窗口后不保留。 diff --git a/README_EN.md b/README_EN.md index ffb883e..a13ac39 100644 --- a/README_EN.md +++ b/README_EN.md @@ -34,9 +34,12 @@ Fluent Serial Assistant is a modern Fluent-style serial terminal for Windows, ma Frame protocol editor

Frame protocol editor showing byte layout, fields, and checksum

Frame table

Frame table with HEX, text, and checksum results

+ + Protocol analysis: live fields from three device addresses and their curves on one chart

Protocol analysis: live fields from three device addresses and their curves on one chart

+ -The screenshots show the Simplified Chinese interface; English is available in Settings or from the title bar. +The app supports Simplified Chinese and English, switchable in Settings or from the title bar. ## Download @@ -72,6 +75,7 @@ The macOS build is not notarized by Apple. If macOS blocks it on first launch, c ### Protocols and tools - Frame protocol templates: define header, length, command, payload, checksum, and frame tail in a visual editor, with the checksum starting at a chosen offset, and check them against a sample or the latest received frame. Once enabled, received records show the command and checksum status. +- Protocol analysis window: define payload fields and a device address in each template, view live values, and check fields to compare devices and templates on one chart. - Checksums: CRC16-Modbus, CRC16-CCITT, CRC32, LRC, XOR, and SUM8, calculated by hand or added when sending. Bytes at the start and end (such as a header or tail) can be skipped; the checksum goes in front of the skipped end bytes and the line ending. - Modbus RTU: build common read and write requests with CRC and summarize responses. @@ -102,15 +106,25 @@ The macOS build is not notarized by Apple. If macOS blocks it on first launch, c 1. Choose a port, set the baud rate, data bits, parity, stop bits, and flow control, and click **Connect**. 2. Watch traffic in the terminal; turn on timestamps, frame splitting, or HEX display as needed. 3. Type text or HEX in the send area, pick a line ending and encoding, and send; checksums and loop sending are optional. -4. Click the plot icon in the terminal toolbar, choose a protocol, and confirm to open a plot window. -5. Under **Protocol Template** on the left, click **Edit protocol** to define the frame format; once saved and enabled, received records show the parsed result. +4. Click the plot icon in the terminal toolbar and confirm the parser settings to open a plot window. If the current protocol template defines data fields, its template and fields are filled in automatically. +5. Under **Protocol Template** on the left, click **Edit protocol** to define the frame format and payload fields, save, then check **Enable** to open the data and plot analysis window. 6. Automate repeated steps with packets, macros, auto-replies, or scripts. 7. The broom button at the left of the terminal toolbar clears the terminal and the traffic counters; export records as TXT, CSV, or BIN. +### Protocol analysis window + +1. In **Edit protocol**, add data fields with the 1 / 2 / 4 / 8 B or Float32 / Float64 buttons. Fields are ordered by frame position, with type, frame bytes, raw HEX, parsed value, and status on the same row. Select a row to edit its name, payload offset, type, byte order, scale, and add value in the fixed property panel on the right. **Template settings** stays visible on the right, with template selection, creation, save, and delete actions together. Use the field selector below it to configure the header, length, address, command, checksum, or tail. + Drag data rows up or down to reorder fields and update their payload offsets. Values use `raw × scale + add`; save to apply. The byte map stays visible, with matching color swatches and HEX cell backgrounds in the field list. Selecting a byte or row opens its properties. Creating a template, selecting a template without a saved sample, or editing its configuration automatically generates enough payload bytes and recalculates length and checksum. You can also paste HEX or use **Latest received frame** to inspect actual data; these samples retain their original bytes when names, scaling, or other settings change. Clear the sample and continue editing to resume generation. Incomplete samples report the missing byte count. +2. For a bus with multiple devices, set the address size and its byte offset in the whole frame. Data is grouped by the address's HEX bytes. Choose **No device address grouping** to combine frames from a template. Each template supports 32 payload fields; without definitions, payload bytes appear as CH1, CH2, and so on. +3. Check **Enable** in the sidebar to open analysis with the current template. Use **Data and plot analysis** to reopen the window with the same protocol and curve choices. Check additional templates in the window to parse several frame formats. +4. The list shows current values and update times for each device's fields. Check **Plot** to draw them on a shared time axis in seconds. Use **Configure** in the toolbar to hide or show the template and field list; capture and plotting continue while it is hidden, with a legend identifying each device curve. The window displays up to 256 fields and 32 curves at a time, retaining the latest 12,000 points per curve. Curve choices survive closing the window and restarting the app. +5. Pausing, hiding, minimizing, or closing the window stops capture. Clearing keeps fields and curve choices; changing enabled templates or saving template changes clears history. Frames with invalid checksums do not update values; missing fields show “—”. Length fields or a fixed payload length let analysis reassemble raw serial reads; configure receive framing first for templates without length information. Within a completed receive block, incomplete length candidates are skipped so later frames can be decoded. Raw streams continue waiting for the declared length, preserving headers that occur inside payloads. + ### Plot windows - Every confirmation opens a new window, so several fields can be plotted side by side. The button at the top left shows the current protocol and opens the parser settings. - Preview a text or HEX sample before plotting. Binary fields take a type, byte offset, byte order, scale, and offset, read from the whole frame or from the payload of a protocol template. +- **Create plot** in the protocol editor carries over its current template, fields, and sample. The terminal toolbar also uses the current template when it has data fields. Template plots share field definitions, frame assembly, and checksum validation, with separate curves for each device address. **Edit protocol** returns to the same editor. Saving the same named template updates linked plots and clears their old data before sampling resumes. - Click **Channel data** in the toolbar to show or hide the right panel. Hiding it gives the chart the full width while data and channel settings are retained. The list shows each channel's color and latest value; use the checkboxes to show or hide curves, and drag the divider to resize the list. - **Channel settings** is collapsed by default; click it to expand or hide it independently. Select a channel to adjust its scale and offset using `displayed = parsed × scale + offset`. Changes apply to retained curves, incoming data, and CSV exports. Parsed values are kept, so **Reset selected channel** restores them. Binary fields apply their parser scale and add value before these channel adjustments. - Channel settings belong to each window and are kept by channel name when data is cleared. Changing the parser configuration or payload template resets them; closing the window discards them. diff --git a/docs/ai-control.md b/docs/ai-control.md index 0091ded..d6bfe2b 100644 --- a/docs/ai-control.md +++ b/docs/ai-control.md @@ -75,7 +75,7 @@ fluentserial-cli plot --plot-protocol keyValue --plot-field 'free sram' --clear 启用二进制协议模板后,`records` 的 RX 项会增加结构化的 `protocol` 对象,包括命令字、载荷、帧长和校验结果。 -绘图解析由独立的解析层完成,界面只负责展示。文本记录会保留行边界,避免一次串口读取包含多行时把通道错位。快速绘图窗口的“解析设置”使用同一配置模型:文本/JSON 可直接筛选字段,二进制可选择完整帧或协议载荷,并在表格中配置类型、字节序、比例和加值。界面应用的配置会持久化,之后 CLI/MCP 修改时也会同步到窗口。 +绘图解析由独立的解析层完成,界面只负责展示。文本记录会保留行边界,避免一次串口读取包含多行时把通道错位。快速绘图窗口的“解析设置”使用同一配置模型:文本/JSON 可直接筛选字段,二进制可选择完整帧或协议载荷。载荷模板已定义数据字段时直接复用模板中的类型、字节序、倍率和加值,可通过“编辑协议”修改;其他情况在解析设置中手动配置字段。界面应用的配置会持久化,之后 CLI/MCP 修改时也会同步到窗口。 - `numbers`:提取每行的全部数字。 - `delimited`:提取逗号、分号或空白分隔的纯数字。 @@ -83,7 +83,18 @@ fluentserial-cli plot --plot-protocol keyValue --plot-field 'free sram' --clear - `json`:递归提取对象和数组中的数值,嵌套字段使用路径名,例如 `system.free`、`channels[0]`。 - `binary`:从完整帧或启用的协议模板载荷中提取二进制字段。 -`--plot-field` 可重复指定,只保留目标字段。二进制未提供字段定义时,每个字节自动映射为 `CH1`、`CH2` 等无符号曲线。结构化二进制字段通过可重复的 JSON 参数定义: +`--plot-field` 可重复指定,只保留目标字段。使用 `payload` 时,模板中已有的载荷字段优先于 `--binary-field`;模板没有定义字段时,才使用手动字段配置。两者均为空时,每个字节自动映射为 `CH1`、`CH2` 等无符号曲线。 + +模板字段也可直接用于 CLI 绘图: + +```bash +fluentserial-cli protocol-use --name 'Example Template' +fluentserial-cli plot --plot-protocol binary --binary-source payload --clear +``` + +模板中的设备地址会区分同一总线上的曲线。保存同名模板的修改后,关联的曲线窗口同步字段定义并清空旧数据;修改其他模板不会覆盖当前曲线的配置。原始串口数据按模板长度字段或固定载荷长度重组;没有长度信息时,需要先在接收设置中配置断帧。断开或重新连接会丢弃尚未收齐的帧,保留已有曲线历史。 + +没有模板字段时,结构化二进制字段通过可重复的 JSON 参数定义: ```bash fluentserial-cli plot \ diff --git a/docs/images/protocol-analysis-en-dark.png b/docs/images/protocol-analysis-en-dark.png new file mode 100644 index 0000000..c18b8ad Binary files /dev/null and b/docs/images/protocol-analysis-en-dark.png differ diff --git a/docs/images/protocol-analysis-en-light.png b/docs/images/protocol-analysis-en-light.png new file mode 100644 index 0000000..cb5b678 Binary files /dev/null and b/docs/images/protocol-analysis-en-light.png differ diff --git a/docs/images/protocol-analysis-zh-dark.png b/docs/images/protocol-analysis-zh-dark.png new file mode 100644 index 0000000..41867d0 Binary files /dev/null and b/docs/images/protocol-analysis-zh-dark.png differ diff --git a/docs/images/protocol-analysis-zh-light.png b/docs/images/protocol-analysis-zh-light.png new file mode 100644 index 0000000..310719d Binary files /dev/null and b/docs/images/protocol-analysis-zh-light.png differ diff --git a/docs/images/protocol-editor-en-dark.png b/docs/images/protocol-editor-en-dark.png index 46c8725..248eba2 100644 Binary files a/docs/images/protocol-editor-en-dark.png and b/docs/images/protocol-editor-en-dark.png differ diff --git a/docs/images/protocol-editor-en-light.png b/docs/images/protocol-editor-en-light.png index f20ddbc..a1e9946 100644 Binary files a/docs/images/protocol-editor-en-light.png and b/docs/images/protocol-editor-en-light.png differ diff --git a/docs/images/protocol-editor-zh-dark.png b/docs/images/protocol-editor-zh-dark.png index a5619ed..14d202d 100644 Binary files a/docs/images/protocol-editor-zh-dark.png and b/docs/images/protocol-editor-zh-dark.png differ diff --git a/docs/images/protocol-editor-zh-light.png b/docs/images/protocol-editor-zh-light.png index 075d12e..27c38a0 100644 Binary files a/docs/images/protocol-editor-zh-light.png and b/docs/images/protocol-editor-zh-light.png differ diff --git a/docs/release-notes/v0.1.29.md b/docs/release-notes/v0.1.29.md new file mode 100644 index 0000000..1cf2b72 --- /dev/null +++ b/docs/release-notes/v0.1.29.md @@ -0,0 +1,19 @@ +协议模板、实时解析和曲线已打通,同一串口上的多个设备可以按地址分别查看和绘图([#20](https://github.com/txp666/FluentSerialAssistant/issues/20))。 + +- 在“编辑协议”中定义载荷字段、数值类型、字节序、倍率、加值和设备地址,保存后勾选“启用”即可查看实时数值,勾选字段绘制曲线。 +- 字节图始终显示,字段列表使用对应颜色,支持拖动调整数据字段顺序;模板与字段设置集中在右侧,实时解析窗口的左侧配置可收起。 +- 自动生成匹配协议的样例并更新长度、校验。粘贴 HEX 或使用“最新接收”后会保留样例原始字节;清空后继续编辑可恢复自动生成。 +- 编辑器的“创建曲线”和终端的曲线入口共用模板字段。保存同名模板后,关联曲线同步配置并清空旧数据;保存其他模板不影响当前曲线草稿。 +- 分批接收的数据按模板重组,多帧连续到达也可解析;重连时丢弃未收齐的半帧,保留已有曲线历史。没有长度信息的模板仍需配置接收断帧。 +- 修复 Qt 6.12.0 数值输入框显示、macOS 动态表格辅助功能崩溃和表格排序箭头缺失问题。 + +## English + +Protocol templates, live analysis, and plots now share field definitions. Devices on the same serial bus can be inspected and plotted separately by address ([#20](https://github.com/txp666/FluentSerialAssistant/issues/20)). + +- Define payload fields, types, byte order, scale, add values, and the device address in **Edit protocol**. Save and check **Enable** to view live values, then check fields to plot them. +- The byte map stays visible, with matching colors in the field table and drag-to-reorder data rows. Template and field settings stay on the right; the live analysis configuration panel can be hidden. +- Matching samples are generated automatically with updated length and checksum. Pasted HEX and **Latest received frame** samples retain their original bytes while settings change. Clear the sample and continue editing to resume generation. +- **Create plot** in the editor and the terminal's plot button use the same template fields. Saving the same named template updates linked plots and clears old data; saving another template leaves the active plot draft intact. +- Frame assembly handles split reads and multiple frames per read. Reconnecting discards incomplete frames while retaining plot history. Templates without length information still require receive framing. +- Fixed invisible spin box values on Qt 6.12.0, a macOS accessibility crash with dynamic tables, and missing table sort arrows. diff --git a/src/app/core/macos_accessibility_fix.h b/src/app/core/macos_accessibility_fix.h new file mode 100644 index 0000000..a7352c2 --- /dev/null +++ b/src/app/core/macos_accessibility_fix.h @@ -0,0 +1,12 @@ +#pragma once + +#include + +namespace AppPlatform { +// Call on the GUI thread immediately after QApplication, before creating widgets. +#if defined(Q_OS_MACOS) && QT_VERSION == QT_VERSION_CHECK(6, 12, 0) +bool installMacAccessibilityFix(); +#else +inline bool installMacAccessibilityFix() { return false; } +#endif +} // namespace AppPlatform diff --git a/src/app/core/macos_accessibility_fix.mm b/src/app/core/macos_accessibility_fix.mm new file mode 100644 index 0000000..3924f0d --- /dev/null +++ b/src/app/core/macos_accessibility_fix.mm @@ -0,0 +1,112 @@ +#include "app/core/macos_accessibility_fix.h" + +#if defined(Q_OS_MACOS) && QT_VERSION == QT_VERSION_CHECK(6, 12, 0) +#import +#include +#include +#include +#include +#include +#import +#import + +namespace { +// Qt 6.12.0 backport of QTBUG-149612: +// https://github.com/qt/qtbase/commit/8148c48deb8e4345bacb797cb75c011df6f797fa +// Native table placeholders share their table's axid. Their teardown must not +// delete QAccessibleInterfaces owned by Qt's cache and item views. Keep all AX +// querying/selection behavior intact. Remove this shim when upgrading to a Qt +// release containing the upstream fix; never enable it for an unverified ABI. +Class elementClass = Nil; +Ivar axidIvar = nullptr; +Ivar rowsIvar = nullptr; +Ivar columnsIvar = nullptr; +Ivar roleIvar = nullptr; + +void invalidateElement(id element, SEL) +{ + auto *axid = reinterpret_cast(reinterpret_cast(element) + ivar_getOffset(axidIvar)); + *axid = 0; + for (Ivar ivar : {rowsIvar, columnsIvar}) { + id array = object_getIvar(element, ivar); + [array autorelease]; + object_setIvar(element, ivar, nil); + } + object_setIvar(element, roleIvar, nil); + NSAccessibilityPostNotification(element, NSAccessibilityUIElementDestroyedNotification); +} + +void deallocateElement(id element, SEL selector) +{ + [object_getIvar(element, rowsIvar) release]; + [object_getIvar(element, columnsIvar) release]; + objc_super superCall{element, class_getSuperclass(elementClass)}; + reinterpret_cast(objc_msgSendSuper)(&superCall, selector); +} + +bool isVoidInstanceMethod(Method method) +{ + if (!method || method_getNumberOfArguments(method) != 2) + return false; + char *result = method_copyReturnType(method); + char *self = method_copyArgumentType(method, 0); + char *selector = method_copyArgumentType(method, 1); + const bool valid = result && self && selector && std::strcmp(result, "v") == 0 && std::strcmp(self, "@") == 0 && + std::strcmp(selector, ":") == 0; + std::free(result); + std::free(self); + std::free(selector); + return valid; +} + +bool ownsMethod(Class owner, Method method) +{ + unsigned int count = 0; + Method *methods = class_copyMethodList(owner, &count); + bool found = false; + for (unsigned int index = 0; index < count; ++index) + found = found || methods[index] == method; + std::free(methods); + return found; +} + +bool isObjectIvar(Ivar ivar) { return ivar && ivar_getTypeEncoding(ivar) && ivar_getTypeEncoding(ivar)[0] == '@'; } +} // namespace + +bool AppPlatform::installMacAccessibilityFix() +{ + static bool installed = false; + if (installed) + return true; + if (std::strcmp(qVersion(), "6.12.0") != 0) + return false; + if (!QCoreApplication::instance() || QThread::currentThread() != QCoreApplication::instance()->thread()) { + qWarning("Qt macOS accessibility fix must be installed on the QApplication thread"); + return false; + } + elementClass = objc_getClass("QMacAccessibilityElement"); + // Offscreen and other non-Cocoa platforms have no native bridge to repair. + if (!elementClass) + return false; + axidIvar = class_getInstanceVariable(elementClass, "axid"); + rowsIvar = class_getInstanceVariable(elementClass, "rows"); + columnsIvar = class_getInstanceVariable(elementClass, "columns"); + roleIvar = class_getInstanceVariable(elementClass, "synthesizedRole"); + const Method invalidate = class_getInstanceMethod(elementClass, sel_registerName("invalidate")); + const Method deallocate = class_getInstanceMethod(elementClass, sel_registerName("dealloc")); + if (class_getSuperclass(elementClass) != objc_getClass("NSObject") || !axidIvar || + std::strcmp(ivar_getTypeEncoding(axidIvar), @encode(unsigned int)) != 0 || !isObjectIvar(rowsIvar) || + !isObjectIvar(columnsIvar) || !isObjectIvar(roleIvar) || !isVoidInstanceMethod(invalidate) || + !isVoidInstanceMethod(deallocate) || !ownsMethod(elementClass, invalidate) || + !ownsMethod(elementClass, deallocate)) { + qWarning("Qt macOS accessibility fix skipped: unexpected native bridge ABI"); + return false; + } + // Do not call the old implementations: they delete interfaces behind the + // view's back. Both replacements preserve the upstream retain/release rules. + method_setImplementation(invalidate, reinterpret_cast(invalidateElement)); + method_setImplementation(deallocate, reinterpret_cast(deallocateElement)); + installed = true; + return true; +} +#endif diff --git a/src/app/core/plot_value_parser.cpp b/src/app/core/plot_value_parser.cpp index 67c3383..4ff6c96 100644 --- a/src/app/core/plot_value_parser.cpp +++ b/src/app/core/plot_value_parser.cpp @@ -220,7 +220,7 @@ bool extractJsonDocument(const QString &text, AppPlot::PlotSample *values) return true; } -int binaryTypeSize(AppPlot::BinaryType type) +int binaryTypeBytes(AppPlot::BinaryType type) { switch (type) { case AppPlot::BinaryType::UInt8: @@ -266,7 +266,7 @@ qint64 signedValue(quint64 value, int bits) bool decodeBinaryValue(const QByteArray &data, const AppPlot::BinaryField &field, double *value) { - const int size = binaryTypeSize(field.type); + const int size = AppPlot::binaryTypeSize(field.type); if (field.byteOffset < 0 || size <= 0 || field.byteOffset > data.size() - size) { return false; } @@ -357,6 +357,14 @@ bool jsonStringList(const QJsonValue &value, QStringList *result, QString *error namespace AppPlot { +bool operator==(const BinaryField &left, const BinaryField &right) +{ + return left.name == right.name && left.byteOffset == right.byteOffset && left.type == right.type && + left.byteOrder == right.byteOrder && left.scale == right.scale && left.add == right.add; +} + +int binaryTypeSize(BinaryType type) { return binaryTypeBytes(type); } + QStringList supportedProtocolKeys() { return {QStringLiteral("numbers"), QStringLiteral("delimited"), QStringLiteral("keyValue"), QStringLiteral("json"), diff --git a/src/app/core/plot_value_parser.h b/src/app/core/plot_value_parser.h index b713e10..a658998 100644 --- a/src/app/core/plot_value_parser.h +++ b/src/app/core/plot_value_parser.h @@ -57,6 +57,9 @@ struct BinaryField double add = 0.0; }; +bool operator==(const BinaryField &left, const BinaryField &right); +int binaryTypeSize(BinaryType type); + struct ParserConfig { Protocol protocol = Protocol::Numbers; diff --git a/src/app/core/protocol_template.cpp b/src/app/core/protocol_template.cpp index 66e8064..5d5e596 100644 --- a/src/app/core/protocol_template.cpp +++ b/src/app/core/protocol_template.cpp @@ -4,8 +4,12 @@ #include "app/core/hex_utils.h" #include +#include #include +#include +#include + namespace { constexpr int MaxProtocolFrameBytes = 1024 * 1024; @@ -99,7 +103,8 @@ bool operator==(const ProtocolTemplate &left, const ProtocolTemplate &right) left.commandSize == right.commandSize && left.payloadOffset == right.payloadOffset && left.payloadLength == right.payloadLength && left.checksumAlgorithm == right.checksumAlgorithm && left.checksumByteOrder == right.checksumByteOrder && left.checksumStart == right.checksumStart && - left.trailer == right.trailer; + left.trailer == right.trailer && left.payloadFields == right.payloadFields && + left.addressOffset == right.addressOffset && left.addressSize == right.addressSize; } ProtocolTemplate fromJson(const QJsonObject &object) @@ -127,6 +132,18 @@ ProtocolTemplate fromJson(const QJsonObject &object) item.checksumStart = boundedOffset(object.value(QStringLiteral("checksumStart")).toInt(item.checksumStart)); item.trailer = QByteArray::fromHex(object.value(QStringLiteral("trailer")).toString(bytesToHex(item.trailer)).toLatin1()); + item.addressOffset = boundedOffset(object.value(QStringLiteral("addressOffset")).toInt()); + item.addressSize = object.value(QStringLiteral("addressSize")).toInt(); + if (!validLengthSize(item.addressSize)) { + item.addressSize = 0; + } + AppPlot::ParserConfig fields; + QString fieldsError; + if (AppPlot::parserConfigFromJson({{QStringLiteral("protocol"), QStringLiteral("binary")}, + {QStringLiteral("binaryFields"), object.value(QStringLiteral("payloadFields"))}}, + &fields, &fieldsError)) { + item.payloadFields = fields.binaryFields.mid(0, AppPlot::MaximumChannels); + } if (item.name.isEmpty()) { item.name = defaultTemplate().name; } @@ -150,9 +167,58 @@ QJsonObject toJson(const ProtocolTemplate &protocolTemplate) object.insert(QStringLiteral("checksumByteOrder"), AppChecksum::byteOrderKey(protocolTemplate.checksumByteOrder)); object.insert(QStringLiteral("checksumStart"), protocolTemplate.checksumStart); object.insert(QStringLiteral("trailer"), bytesToHex(protocolTemplate.trailer)); + object.insert( + QStringLiteral("payloadFields"), + AppPlot::parserConfigToJson(payloadParserConfig(protocolTemplate)).value(QStringLiteral("binaryFields"))); + object.insert(QStringLiteral("addressOffset"), protocolTemplate.addressOffset); + object.insert(QStringLiteral("addressSize"), protocolTemplate.addressSize); return object; } +AppPlot::ParserConfig payloadParserConfig(const ProtocolTemplate &protocolTemplate) +{ + AppPlot::ParserConfig config; + config.protocol = AppPlot::Protocol::Binary; + config.binarySource = AppPlot::BinarySource::Payload; + config.binaryFields = protocolTemplate.payloadFields; + return config; +} + +qint64 requiredPayloadBytes(const ProtocolTemplate &protocolTemplate) +{ + qint64 required = 0; + for (const auto &field : protocolTemplate.payloadFields) { + required = qMax(required, qint64(field.byteOffset) + AppPlot::binaryTypeSize(field.type)); + } + return required; +} + +QString payloadConfigurationError(const ProtocolTemplate &protocolTemplate) +{ + if (protocolTemplate.payloadFields.size() > AppPlot::MaximumChannels) { + return AppI18n::text("最多定义 %1 个载荷字段").arg(AppPlot::MaximumChannels); + } + if (!validLengthSize(protocolTemplate.addressSize) || protocolTemplate.addressOffset < 0 || + protocolTemplate.addressOffset > MaxProtocolFrameBytes - protocolTemplate.addressSize) { + return AppI18n::text("设备地址字段范围无效"); + } + QSet names; + for (const auto &field : protocolTemplate.payloadFields) { + const QString name = field.name.simplified(); + if (name.isEmpty() || names.contains(name)) { + return AppI18n::text("载荷字段名称不能为空或重复"); + } + names.insert(name); + const int size = AppPlot::binaryTypeSize(field.type); + const int limit = protocolTemplate.payloadLength > 0 ? protocolTemplate.payloadLength : MaxProtocolFrameBytes; + if (size <= 0 || field.byteOffset < 0 || field.byteOffset > limit - size || !std::isfinite(field.scale) || + !std::isfinite(field.add)) { + return AppI18n::text("载荷字段 %1 的范围或换算参数无效").arg(name); + } + } + return {}; +} + QList listFromJson(const QJsonArray &array) { QList items; @@ -196,9 +262,8 @@ FrameLayout frameLayout(const QByteArray &frame, const ProtocolTemplate &protoco } layout.trailerOffset = layout.frameLength - trailerBytes; layout.checksumOffset = layout.trailerOffset - checksumBytes; - layout.payloadLength = protocolTemplate.payloadLength > 0 - ? protocolTemplate.payloadLength - : layout.checksumOffset - protocolTemplate.payloadOffset; + layout.payloadLength = protocolTemplate.payloadLength > 0 ? protocolTemplate.payloadLength + : layout.checksumOffset - protocolTemplate.payloadOffset; return layout; } @@ -223,8 +288,9 @@ ParseResult parseFrame(const QByteArray &frame, const ProtocolTemplate &protocol } const int checksumBytes = checksumSize(protocolTemplate); - if (protocolTemplate.lengthSize > 0 && (protocolTemplate.lengthOffset < 0 || - protocolTemplate.lengthOffset + protocolTemplate.lengthSize > frame.size())) { + if (protocolTemplate.lengthSize > 0 && + (protocolTemplate.lengthOffset < 0 || + protocolTemplate.lengthOffset + protocolTemplate.lengthSize > frame.size())) { result.errorMessage = AppI18n::text("长度字段超出帧范围"); return result; } @@ -299,9 +365,62 @@ ParseResult parseFrame(const QByteArray &frame, const ProtocolTemplate &protocol return result; } +QList takeFrames(QByteArray &buffer, const QByteArray &bytes, const ProtocolTemplate &item, bool stream) +{ + QList frames; + const bool delimited = item.lengthSize > 0 || item.payloadLength > 0; + if (!stream || !delimited) + buffer.clear(); + buffer.append(bytes); + if (buffer.size() > MaxProtocolFrameBytes * 2) + buffer = buffer.right(MaxProtocolFrameBytes); + while (!buffer.isEmpty()) { + if (!item.header.isEmpty()) { + const auto header = buffer.indexOf(item.header); + if (header < 0) { + buffer = buffer.right(qMax(0, int(item.header.size()) - 1)); + break; + } + buffer.remove(0, header); + } + const qint64 prefix = qMax(item.header.size(), qint64(item.lengthOffset) + item.lengthSize); + if (item.lengthSize > 0 && buffer.size() < prefix) + break; + const auto layout = frameLayout(buffer, item); + if (layout.frameLength <= 0 || layout.frameLength > MaxProtocolFrameBytes) { + buffer.remove(0, 1); + continue; + } + if (buffer.size() < layout.frameLength) { + if (stream) + break; + // This record has ended, so this candidate cannot finish within it. + // A raw stream has no such boundary: keep waiting for its payload. + buffer.remove(0, 1); + continue; + } + const auto parsed = parseFrame(buffer, item); + if (!parsed.ok || (parsed.checksumChecked && !parsed.checksumValid)) { + buffer.remove(0, 1); + continue; + } + frames.append({buffer.left(parsed.frameLength), parsed}); + buffer.remove(0, parsed.frameLength); + } + if (!stream || !delimited) + buffer.clear(); + return frames; +} + QByteArray exampleFrame(const ProtocolTemplate &protocolTemplate) { - const int payloadSize = protocolTemplate.payloadLength > 0 ? protocolTemplate.payloadLength : 4; + const qint64 requestedPayloadSize = protocolTemplate.payloadLength > 0 + ? protocolTemplate.payloadLength + : qMax(4, requiredPayloadBytes(protocolTemplate)); + if (requestedPayloadSize > 4096 || !payloadConfigurationError(protocolTemplate).isEmpty()) { + return {}; + } + const int payloadSize = int(requestedPayloadSize); const qint64 checksumOffset = static_cast(protocolTemplate.payloadOffset) + payloadSize; const int checksumBytes = checksumSize(protocolTemplate); if (protocolTemplate.payloadOffset < 0 || checksumOffset > 4096 || checksumOffset <= 0 || @@ -313,6 +432,10 @@ QByteArray exampleFrame(const ProtocolTemplate &protocolTemplate) return {}; } QByteArray frame(static_cast(checksumOffset), '\0'); + if (protocolTemplate.addressSize > 0 && protocolTemplate.addressOffset >= 0 && + protocolTemplate.addressOffset + protocolTemplate.addressSize <= checksumOffset) { + frame[protocolTemplate.addressOffset] = '\x01'; + } frame.replace(0, protocolTemplate.header.size(), protocolTemplate.header); if (protocolTemplate.commandSize > 0) { frame[protocolTemplate.commandOffset] = '\x01'; @@ -321,12 +444,39 @@ QByteArray exampleFrame(const ProtocolTemplate &protocolTemplate) for (int index = 0; index < payloadSize; ++index) { frame[protocolTemplate.payloadOffset + index] = payload.at(index % payload.size()); } + for (int index = 0; index < protocolTemplate.payloadFields.size(); ++index) { + const auto &field = protocolTemplate.payloadFields.at(index); + const int size = AppPlot::binaryTypeSize(field.type); + quint64 raw = field.type == AppPlot::BinaryType::UInt8 ? 1 : 100 + 100 * index; + if (field.type == AppPlot::BinaryType::Int16) { + raw = quint16(1234 + 100 * index); + } else if (field.type == AppPlot::BinaryType::Int8 || field.type == AppPlot::BinaryType::Int32 || + field.type == AppPlot::BinaryType::Int64) { + raw = quint64(qint64(-100)); + } else if (field.type == AppPlot::BinaryType::Float32) { + const float value = 12.5f + index; + quint32 bits = 0; + std::memcpy(&bits, &value, sizeof(value)); + raw = bits; + } else if (field.type == AppPlot::BinaryType::Float64) { + const double value = 12.5 + index; + std::memcpy(&raw, &value, sizeof(value)); + } + for (int byte = 0; byte < size; ++byte) { + const int target = field.byteOrder == AppPlot::ByteOrder::LittleEndian ? byte : size - byte - 1; + frame[protocolTemplate.payloadOffset + field.byteOffset + target] = char((raw >> (byte * 8)) & 0xff); + } + } quint32 length = protocolTemplate.lengthMode == LengthMode::FrameLength ? frame.size() + checksumBytes + protocolTemplate.trailer.size() : payloadSize; + if (protocolTemplate.lengthSize > 0 && protocolTemplate.lengthSize < 4 && + length >= (quint32(1) << (protocolTemplate.lengthSize * 8))) + return {}; for (int index = 0; index < protocolTemplate.lengthSize; ++index) { const int byteIndex = protocolTemplate.lengthByteOrder == AppChecksum::ByteOrder::LittleEndian - ? index : protocolTemplate.lengthSize - index - 1; + ? index + : protocolTemplate.lengthSize - index - 1; frame[protocolTemplate.lengthOffset + byteIndex] = static_cast(length & 0xff); length >>= 8; } diff --git a/src/app/core/protocol_template.h b/src/app/core/protocol_template.h index 10c5274..888bef1 100644 --- a/src/app/core/protocol_template.h +++ b/src/app/core/protocol_template.h @@ -1,6 +1,7 @@ #pragma once #include "app/core/checksum_utils.h" +#include "app/core/plot_value_parser.h" #include #include @@ -34,6 +35,11 @@ struct ProtocolTemplate int checksumStart = 0; // Fixed bytes that end every frame, after the checksum. QByteArray trailer; + // Field offsets are relative to the payload; addressOffset is relative to + // the frame. A zero addressSize keeps all frames in one device group. + QVector payloadFields; + int addressOffset = 0; + int addressSize = 0; }; struct ParseResult @@ -50,6 +56,12 @@ struct ParseResult bool checksumValid = false; }; +struct DecodedFrame +{ + QByteArray bytes; + ParseResult parsed; +}; + // Where a frame's fields lie, using its length field when the template has // one. A length field outside the frame reads as 0. struct FrameLayout @@ -77,8 +89,15 @@ ProtocolTemplate fromJson(const QJsonObject &object); QJsonObject toJson(const ProtocolTemplate &protocolTemplate); QList listFromJson(const QJsonArray &array); QJsonArray listToJson(const QList &protocolTemplates); +AppPlot::ParserConfig payloadParserConfig(const ProtocolTemplate &protocolTemplate); +qint64 requiredPayloadBytes(const ProtocolTemplate &protocolTemplate); +QString payloadConfigurationError(const ProtocolTemplate &protocolTemplate); FrameLayout frameLayout(const QByteArray &frame, const ProtocolTemplate &protocolTemplate); ParseResult parseFrame(const QByteArray &frame, const ProtocolTemplate &protocolTemplate); +// Shared by protocol analysis and plots. Keep incomplete frames only for a +// stream whose template defines a length; returned frames have passed checksum validation. +QList takeFrames(QByteArray &buffer, const QByteArray &bytes, const ProtocolTemplate &protocolTemplate, + bool stream); // A frame that the template parses, or empty when its fields cannot form one. QByteArray exampleFrame(const ProtocolTemplate &protocolTemplate); diff --git a/src/app/resources/i18n/fluentserialassistant.en_US.qm b/src/app/resources/i18n/fluentserialassistant.en_US.qm index a4c454b..4f33314 100644 Binary files a/src/app/resources/i18n/fluentserialassistant.en_US.qm and b/src/app/resources/i18n/fluentserialassistant.en_US.qm differ diff --git a/src/app/resources/i18n/fluentserialassistant.en_US.ts b/src/app/resources/i18n/fluentserialassistant.en_US.ts index 0c36713..04859be 100644 --- a/src/app/resources/i18n/fluentserialassistant.en_US.ts +++ b/src/app/resources/i18n/fluentserialassistant.en_US.ts @@ -3,6 +3,248 @@ AppText + + 自动样例随配置更新;粘贴 HEX 后保留,清空可恢复自动生成 + Generated samples follow configuration changes. Pasted HEX is preserved; clear it to resume generation. + + + 数据字段 + Data fields + + + 已校验 + Verified + + + 字节图 + Byte map + + + 整帧 %1 B · 载荷从字节 %2 开始 · %3 + Frame %1 B · payload starts at byte %2 · %3 + + + 不匹配 + Mismatch + + + %1 位浮点数 + Float %1-bit + + + %1 位有符号整数 + Signed %1-bit + + + %1 位无符号整数 + Unsigned %1-bit + + + 字段属性 + Field properties + + + 整帧起点 + Frame offset + + + 载荷内起点 + Payload offset + + + 数值类型 + Value type + + + 字段属性 · %1 + Field properties · %1 + + + 地址起点按整帧计算,从 0 开始。接收窗口按地址分组显示设备数据。 + The address offset starts at byte 0 of the whole frame. Received data is grouped by device address. + + + 整帧字节 %1–%2 +显示值 = 原始值 × %3 + %4 + Frame bytes %1–%2 +Displayed = raw × %3 + %4 + + + 从左侧选择字段,或点击上方的字节类型添加数据字段。 + Select a field on the left, or add a data field using the byte-type buttons above. + + + 模板设置 + Template settings + + + 生成匹配样例 + Generate sample + + + 帧字段 + Frame fields + + + 添加数据 + Add data + + + 添加 %1 字段 + Add %1 field + + + 整帧字节 + Bytes + + + 状态 + Status + + + 按整帧字节顺序排列;选择一行,在右侧修改属性。 + Fields are ordered by frame byte position. Select a row to edit its properties on the right. + + + 样例校验失败,请检查校验设置或重新生成样例。 + Sample checksum failed. Check the checksum settings or generate a new sample. + + + 样例载荷不足:当前 %1 B,数据字段至少需要 %2 B。 + Sample payload is too short: %1 B available, data fields require at least %2 B. + + + 样例解析通过 · %1 B 载荷 · %2 个数据字段 + Sample parsed · %1 B payload · %2 data fields + + + 样例不足 + Incomplete sample + + + 已识别 + Recognized + + + 固定字节 + Fixed bytes + + + 无法解析 + Cannot parse + + + 帧无效 + Invalid frame + + + 缺少 %1 B + Missing %1 B + + + 数值无效 + Invalid value + + + 已解析 + Parsed + + + 无法校验 + Cannot verify + + + 载荷范围 + Payload range + + + 不区分设备地址 + No device address grouping + + + 设备地址 + Device address + + + 地址在整帧中的偏移 + Address offset in frame + + + 载荷字段偏移从 0 开始;不同地址的数据独立显示,可勾选到同一张曲线图。 + Payload offsets start at 0. Devices are grouped by address and can share one chart. + + + 删除字段 + Remove field + + + 载荷 +%1 · %2 + Payload +%1 · %2 + + + 协议解析 + Protocol analysis + + + 启用协议解析 + Enable protocol analysis + + + 参与解析的模板 + Templates to parse + + + 勾选字段即可显示曲线;载荷字段、倍率和设备地址在编辑协议中设置。 + Check fields to plot them. Configure payload fields, scaling, and device addresses in Edit protocol. + + + 曲线 + Plot + + + 模板 / 地址 + Template / address + + + 更新时间 + Updated + + + %1 · %2 帧 · %3 个数据字段 · 横轴为秒 + %1 · %2 frames · %3 data fields · time axis in seconds + + + 等待接收所选协议的数据 + Waiting for data matching the selected templates + + + 最多显示 %1 个字段,同时绘制 %2 条曲线 + Up to %1 fields and %2 simultaneous curves + + + 最多定义 %1 个载荷字段 + Define up to %1 payload fields + + + 设备地址字段范围无效 + Invalid device address field range + + + 载荷字段名称不能为空或重复 + Payload field names must be non-empty and unique + + + 载荷字段 %1 的范围或换算参数无效 + Invalid range or scaling for payload field %1 + + + 解析数据与曲线 + Data and plot analysis + + + 载荷字段与设备地址 + Payload fields and device address + 展开通道设置 Show channel settings @@ -3013,6 +3255,26 @@ Installation log: %2 当前 %1 B / 需要 %2 B Current %1 B / Required %2 B + + 字段解析 + Field decoding + + + 拖动数据字段调整顺序与偏移 + Drag data fields to reorder and update offsets + + + 帧协议模板 + Frame protocol template + + + 沿用模板的 %1 个数据字段、字节序及换算。保存模板后,关联曲线同步更新并重新开始采样。 + Uses the template’s %1 data fields, byte order, and conversions. Saving the template updates linked plots and restarts sampling. + + + 由帧协议模板定义数据字段,按设备地址区分曲线。 + Use fields defined in the frame protocol template, with separate curves for each device address. + FluentQt::RealtimePlotWidget diff --git a/src/app/resources/i18n/fluentserialassistant.zh_CN.qm b/src/app/resources/i18n/fluentserialassistant.zh_CN.qm index 9291153..5081035 100644 Binary files a/src/app/resources/i18n/fluentserialassistant.zh_CN.qm and b/src/app/resources/i18n/fluentserialassistant.zh_CN.qm differ diff --git a/src/app/resources/i18n/fluentserialassistant.zh_CN.ts b/src/app/resources/i18n/fluentserialassistant.zh_CN.ts index dbda535..5e7572c 100644 --- a/src/app/resources/i18n/fluentserialassistant.zh_CN.ts +++ b/src/app/resources/i18n/fluentserialassistant.zh_CN.ts @@ -3,6 +3,248 @@ AppText + + 自动样例随配置更新;粘贴 HEX 后保留,清空可恢复自动生成 + 自动样例随配置更新;粘贴 HEX 后保留,清空可恢复自动生成 + + + 数据字段 + 数据字段 + + + 已校验 + 已校验 + + + 字节图 + 字节图 + + + 整帧 %1 B · 载荷从字节 %2 开始 · %3 + 整帧 %1 B · 载荷从字节 %2 开始 · %3 + + + 不匹配 + 不匹配 + + + %1 位浮点数 + %1 位浮点数 + + + %1 位有符号整数 + %1 位有符号整数 + + + %1 位无符号整数 + %1 位无符号整数 + + + 字段属性 + 字段属性 + + + 整帧起点 + 整帧起点 + + + 载荷内起点 + 载荷内起点 + + + 数值类型 + 数值类型 + + + 字段属性 · %1 + 字段属性 · %1 + + + 地址起点按整帧计算,从 0 开始。接收窗口按地址分组显示设备数据。 + 地址起点按整帧计算,从 0 开始。接收窗口按地址分组显示设备数据。 + + + 整帧字节 %1–%2 +显示值 = 原始值 × %3 + %4 + 整帧字节 %1–%2 +显示值 = 原始值 × %3 + %4 + + + 从左侧选择字段,或点击上方的字节类型添加数据字段。 + 从左侧选择字段,或点击上方的字节类型添加数据字段。 + + + 模板设置 + 模板设置 + + + 生成匹配样例 + 生成匹配样例 + + + 帧字段 + 帧字段 + + + 添加数据 + 添加数据 + + + 添加 %1 字段 + 添加 %1 字段 + + + 整帧字节 + 整帧字节 + + + 状态 + 状态 + + + 按整帧字节顺序排列;选择一行,在右侧修改属性。 + 按整帧字节顺序排列;选择一行,在右侧修改属性。 + + + 样例校验失败,请检查校验设置或重新生成样例。 + 样例校验失败,请检查校验设置或重新生成样例。 + + + 样例载荷不足:当前 %1 B,数据字段至少需要 %2 B。 + 样例载荷不足:当前 %1 B,数据字段至少需要 %2 B。 + + + 样例解析通过 · %1 B 载荷 · %2 个数据字段 + 样例解析通过 · %1 B 载荷 · %2 个数据字段 + + + 样例不足 + 样例不足 + + + 已识别 + 已识别 + + + 固定字节 + 固定字节 + + + 无法解析 + 无法解析 + + + 帧无效 + 帧无效 + + + 缺少 %1 B + 缺少 %1 B + + + 数值无效 + 数值无效 + + + 已解析 + 已解析 + + + 无法校验 + 无法校验 + + + 载荷范围 + 载荷范围 + + + 不区分设备地址 + 不区分设备地址 + + + 设备地址 + 设备地址 + + + 地址在整帧中的偏移 + 地址在整帧中的偏移 + + + 载荷字段偏移从 0 开始;不同地址的数据独立显示,可勾选到同一张曲线图。 + 载荷字段偏移从 0 开始;不同地址的数据独立显示,可勾选到同一张曲线图。 + + + 删除字段 + 删除字段 + + + 载荷 +%1 · %2 + 载荷 +%1 · %2 + + + 协议解析 + 协议解析 + + + 启用协议解析 + 启用协议解析 + + + 参与解析的模板 + 参与解析的模板 + + + 勾选字段即可显示曲线;载荷字段、倍率和设备地址在编辑协议中设置。 + 勾选字段即可显示曲线;载荷字段、倍率和设备地址在编辑协议中设置。 + + + 曲线 + 曲线 + + + 模板 / 地址 + 模板 / 地址 + + + 更新时间 + 更新时间 + + + %1 · %2 帧 · %3 个数据字段 · 横轴为秒 + %1 · %2 帧 · %3 个数据字段 · 横轴为秒 + + + 等待接收所选协议的数据 + 等待接收所选协议的数据 + + + 最多显示 %1 个字段,同时绘制 %2 条曲线 + 最多显示 %1 个字段,同时绘制 %2 条曲线 + + + 最多定义 %1 个载荷字段 + 最多定义 %1 个载荷字段 + + + 设备地址字段范围无效 + 设备地址字段范围无效 + + + 载荷字段名称不能为空或重复 + 载荷字段名称不能为空或重复 + + + 载荷字段 %1 的范围或换算参数无效 + 载荷字段 %1 的范围或换算参数无效 + + + 解析数据与曲线 + 解析数据与曲线 + + + 载荷字段与设备地址 + 载荷字段与设备地址 + 展开通道设置 展开通道设置 @@ -3013,6 +3255,26 @@ 当前 %1 B / 需要 %2 B 当前 %1 B / 需要 %2 B + + 字段解析 + 字段解析 + + + 拖动数据字段调整顺序与偏移 + 拖动数据字段调整顺序与偏移 + + + 帧协议模板 + 帧协议模板 + + + 沿用模板的 %1 个数据字段、字节序及换算。保存模板后,关联曲线同步更新并重新开始采样。 + 沿用模板的 %1 个数据字段、字节序及换算。保存模板后,关联曲线同步更新并重新开始采样。 + + + 由帧协议模板定义数据字段,按设备地址区分曲线。 + 由帧协议模板定义数据字段,按设备地址区分曲线。 + FluentQt::RealtimePlotWidget diff --git a/src/app/view/plot_parser_dialog.cpp b/src/app/view/plot_parser_dialog.cpp index 91611e2..0108cde 100644 --- a/src/app/view/plot_parser_dialog.cpp +++ b/src/app/view/plot_parser_dialog.cpp @@ -99,11 +99,16 @@ QString protocolHint(AppPlot::Protocol protocol) QString PlotParserDialog::protocolName(AppPlot::Protocol protocol) { switch (protocol) { - case AppPlot::Protocol::Delimited: return AppI18n::text("分隔值"); - case AppPlot::Protocol::KeyValue: return AppI18n::text("键值对"); - case AppPlot::Protocol::Json: return AppI18n::text("JSON 对象"); - case AppPlot::Protocol::Binary: return AppI18n::text("二进制字段"); - default: return AppI18n::text("全部数字"); + case AppPlot::Protocol::Delimited: + return AppI18n::text("分隔值"); + case AppPlot::Protocol::KeyValue: + return AppI18n::text("键值对"); + case AppPlot::Protocol::Json: + return AppI18n::text("JSON 对象"); + case AppPlot::Protocol::Binary: + return AppI18n::text("二进制字段"); + default: + return AppI18n::text("全部数字"); } } @@ -122,9 +127,10 @@ PlotParserDialog::PlotParserDialog(const AppPlot::ParserConfig &config, QWidget root->setContentsMargins(18, 18, 18, 18); root->setSpacing(12); - auto *description = new BodyLabel(requireProtocolChoice - ? AppI18n::text("选择本窗口的数据协议,用样例确认解析结果后创建曲线。") - : AppI18n::text("本窗口独立使用以下协议;修改协议会清空已有曲线。"), this); + auto *description = + new BodyLabel(requireProtocolChoice ? AppI18n::text("选择本窗口的数据协议,用样例确认解析结果后创建曲线。") + : AppI18n::text("本窗口独立使用以下协议;修改协议会清空已有曲线。"), + this); description->setWordWrap(true); root->addWidget(description); @@ -139,7 +145,8 @@ PlotParserDialog::PlotParserDialog(const AppPlot::ParserConfig &config, QWidget AppPlot::protocolFromKey(key, &protocol); m_protocolCombo->addItem(protocolName(protocol), QIcon(), key); } - m_protocolCombo->setCurrentIndex(requireProtocolChoice ? 0 : m_protocolCombo->findData(AppPlot::protocolKey(config.protocol))); + m_protocolCombo->setCurrentIndex( + requireProtocolChoice ? 0 : m_protocolCombo->findData(AppPlot::protocolKey(config.protocol))); form->addRow(AppI18n::text("协议类型"), m_protocolCombo); m_fieldsEdit = new LineEdit(this); m_fieldsEdit->setObjectName(QStringLiteral("plotFieldsEdit")); @@ -162,7 +169,7 @@ PlotParserDialog::PlotParserDialog(const AppPlot::ParserConfig &config, QWidget m_binarySourceCombo = new ComboBox(m_binaryContainer); m_binarySourceCombo->setObjectName(QStringLiteral("plotBinarySourceCombo")); m_binarySourceCombo->addItem(AppI18n::text("完整帧"), QIcon(), QStringLiteral("frame")); - m_binarySourceCombo->addItem(AppI18n::text("协议载荷"), QIcon(), QStringLiteral("payload")); + m_binarySourceCombo->addItem(AppI18n::text("帧协议模板"), QIcon(), QStringLiteral("payload")); m_binarySourceCombo->setCurrentIndex(m_binarySourceCombo->findData(AppPlot::binarySourceKey(config.binarySource))); sourceRow->addWidget(m_binarySourceCombo); sourceRow->addStretch(1); @@ -176,13 +183,17 @@ PlotParserDialog::PlotParserDialog(const AppPlot::ParserConfig &config, QWidget m_templateCombo->setObjectName(QStringLiteral("plotFrameTemplateCombo")); m_templateCombo->addItem(AppI18n::text("请选择帧模板"), QIcon(), -1); templateLayout->addWidget(m_templateCombo, 1); + m_editTemplateButton = new PushButton(AppI18n::text("编辑协议"), m_templateContainer); + m_editTemplateButton->setObjectName(QStringLiteral("plotEditTemplateButton")); + templateLayout->addWidget(m_editTemplateButton); + connect(m_editTemplateButton, &PushButton::clicked, this, [this]() { done(EditTemplate); }); binaryLayout->addWidget(m_templateContainer); - auto *binaryHint = new CaptionLabel( + m_binaryHint = new CaptionLabel( AppI18n::text("字段留空时按字节生成通道。协议载荷使用本窗口选择的帧模板,并验证帧校验。"), m_binaryContainer); - AppUi::setMutedTextColor(binaryHint); - binaryHint->setWordWrap(true); - binaryLayout->addWidget(binaryHint); + AppUi::setMutedTextColor(m_binaryHint); + m_binaryHint->setWordWrap(true); + binaryLayout->addWidget(m_binaryHint); m_binaryFieldsTable = new TableWidget(m_binaryContainer); m_binaryFieldsTable->setObjectName(QStringLiteral("plotBinaryFieldsTable")); @@ -218,7 +229,9 @@ PlotParserDialog::PlotParserDialog(const AppPlot::ParserConfig &config, QWidget addBinaryFieldRow(field); } - auto *fieldButtons = new QHBoxLayout; + m_binaryFieldButtons = new QWidget(m_binaryContainer); + auto *fieldButtons = new QHBoxLayout(m_binaryFieldButtons); + fieldButtons->setContentsMargins(0, 0, 0, 0); auto *addFieldButton = new PushButton(FluentQt::icon(FluentIcon::Add), AppI18n::text("添加字段"), m_binaryContainer); auto *removeFieldButton = @@ -226,7 +239,7 @@ PlotParserDialog::PlotParserDialog(const AppPlot::ParserConfig &config, QWidget fieldButtons->addWidget(addFieldButton); fieldButtons->addWidget(removeFieldButton); fieldButtons->addStretch(1); - binaryLayout->addLayout(fieldButtons); + binaryLayout->addWidget(m_binaryFieldButtons); connect(addFieldButton, &PushButton::clicked, this, &PlotParserDialog::addDefaultBinaryField); connect(removeFieldButton, &PushButton::clicked, this, &PlotParserDialog::removeSelectedBinaryFields); @@ -290,7 +303,8 @@ PlotParserDialog::PlotParserDialog(const AppPlot::ParserConfig &config, QWidget auto *buttons = new QHBoxLayout; buttons->addStretch(1); auto *cancelButton = new PushButton(AppI18n::text("取消"), this); - m_applyButton = new PrimaryPushButton(requireProtocolChoice ? AppI18n::text("创建曲线") : AppI18n::text("应用"), this); + m_applyButton = + new PrimaryPushButton(requireProtocolChoice ? AppI18n::text("创建曲线") : AppI18n::text("应用"), this); m_applyButton->setObjectName(QStringLiteral("plotApplyButton")); buttons->addWidget(cancelButton); buttons->addWidget(m_applyButton); @@ -306,8 +320,17 @@ PlotParserDialog::PlotParserDialog(const AppPlot::ParserConfig &config, QWidget } updateProtocolControls(); }); - connect(m_binarySourceCombo, &ComboBox::currentIndexChanged, this, [this](int) { updateProtocolControls(); }); - connect(m_templateCombo, &ComboBox::currentIndexChanged, this, [this](int) { updatePreview(); }); + connect(m_binarySourceCombo, &ComboBox::currentIndexChanged, this, [this](int) { + updateProtocolControls(); + if (usesProtocolTemplate()) + loadExample(); + }); + connect(m_templateCombo, &ComboBox::currentIndexChanged, this, [this](int) { + m_fieldsEdit->clear(); + updateProtocolControls(); + if (usesProtocolTemplate()) + loadExample(); + }); connect(m_fieldsEdit, &LineEdit::textChanged, this, [this]() { updatePreview(); }); connect(m_sampleModeCombo, &ComboBox::currentIndexChanged, this, [this](int) { updatePreview(); }); connect(m_sampleEdit, &PlainTextEdit::textChanged, this, &PlotParserDialog::updatePreview); @@ -339,7 +362,7 @@ void PlotParserDialog::setProtocolTemplates(const QListsetCurrentIndex(selectedIndex); - updatePreview(); + updateProtocolControls(); } void PlotParserDialog::setProtocolTemplate(const AppProtocol::ProtocolTemplate &protocolTemplate) @@ -356,18 +379,41 @@ void PlotParserDialog::setProtocolTemplate(const AppProtocol::ProtocolTemplate & m_protocolTemplates.append(protocolTemplate); index = m_protocolTemplates.size() - 1; const bool hasSameName = std::any_of(m_protocolTemplates.cbegin(), m_protocolTemplates.cend() - 1, - [&protocolTemplate](const AppProtocol::ProtocolTemplate &item) { - return item.name == protocolTemplate.name; - }); + [&protocolTemplate](const AppProtocol::ProtocolTemplate &item) { + return item.name == protocolTemplate.name; + }); m_templateCombo->addItem(hasSameName ? protocolTemplate.name + AppI18n::text("(当前窗口)") - : protocolTemplate.name, QIcon(), index); + : protocolTemplate.name, + QIcon(), index); } + const QSignalBlocker blocker(m_templateCombo); m_templateCombo->setCurrentIndex(index + 1); + updateProtocolControls(); if (usesProtocolTemplate() && m_sampleEdit->toPlainText().trimmed().isEmpty()) { loadExample(); } } +void PlotParserDialog::setSampleHex(const QString &hex) +{ + const QSignalBlocker blocker(m_sampleModeCombo); + m_sampleModeCombo->setCurrentIndex(m_sampleModeCombo->findData(QStringLiteral("hex"))); + m_sampleEdit->setPlainText(hex); + updatePreview(); +} + +void PlotParserDialog::useProtocolTemplate(const AppProtocol::ProtocolTemplate &protocolTemplate) +{ + m_protocolCombo->setCurrentIndex(m_protocolCombo->findData(QStringLiteral("binary"))); + m_binarySourceCombo->setCurrentIndex(m_binarySourceCombo->findData(QStringLiteral("payload"))); + setProtocolTemplate(protocolTemplate); +} + +bool PlotParserDialog::usesTemplateFields() const +{ + return usesProtocolTemplate() && !protocolTemplate().payloadFields.isEmpty(); +} + bool PlotParserDialog::usesProtocolTemplate() const { return m_protocolCombo->currentData().toString() == QStringLiteral("binary") && @@ -378,7 +424,7 @@ AppProtocol::ProtocolTemplate PlotParserDialog::protocolTemplate() const { const int index = m_templateCombo->currentData().toInt(); return index >= 0 && index < m_protocolTemplates.size() ? m_protocolTemplates.at(index) - : AppProtocol::ProtocolTemplate(); + : AppProtocol::ProtocolTemplate(); } void PlotParserDialog::accept() @@ -403,7 +449,12 @@ bool PlotParserDialog::collectConfig(AppPlot::ParserConfig *config, QString *err config->fields = splitFields(m_fieldsEdit->text()); if (config->protocol == AppPlot::Protocol::Binary) { AppPlot::binarySourceFromKey(m_binarySourceCombo->currentData().toString(), &config->binarySource); - if (!collectBinaryFields(&config->binaryFields, error)) { + if (usesTemplateFields()) { + config->binaryFields = protocolTemplate().payloadFields; + *error = AppProtocol::payloadConfigurationError(protocolTemplate()); + if (!error->isEmpty()) + return false; + } else if (!collectBinaryFields(&config->binaryFields, error)) { return false; } if (usesProtocolTemplate()) { @@ -424,7 +475,18 @@ void PlotParserDialog::updateProtocolControls() const bool binary = selected && protocol == AppPlot::Protocol::Binary; m_binaryContainer->setVisible(binary); m_templateContainer->setVisible(binary && usesProtocolTemplate()); - m_protocolHint->setText(selected ? protocolHint(protocol) : AppI18n::text("每个曲线窗口都需要单独选择协议。")); + const bool templateFields = usesTemplateFields(); + m_binaryFieldsTable->setVisible(!templateFields); + m_binaryFieldButtons->setVisible(!templateFields); + m_editTemplateButton->setEnabled(m_templateCombo->currentData().toInt() >= 0); + m_binaryHint->setText( + templateFields + ? AppI18n::text("沿用模板的 %1 个数据字段、字节序及换算。保存模板后,关联曲线同步更新并重新开始采样。") + .arg(protocolTemplate().payloadFields.size()) + : AppI18n::text("字段留空时按字节生成通道。协议载荷使用本窗口选择的帧模板,并验证帧校验。")); + m_protocolHint->setText(usesProtocolTemplate() ? AppI18n::text("由帧协议模板定义数据字段,按设备地址区分曲线。") + : selected ? protocolHint(protocol) + : AppI18n::text("每个曲线窗口都需要单独选择协议。")); m_fieldsEdit->setEnabled(selected); if (binary != m_binarySample) { // Binary fields read bytes while the other protocols read text. Keep the @@ -529,9 +591,8 @@ void PlotParserDialog::updatePreview() m_previewTable->setItem(row, 2, editableItem(QString::number(value.value, 'g', 14))); } } - QString result = samples.isEmpty() - ? AppI18n::text("未找到匹配的数字字段,请检查样例、字段筛选或字节偏移。") - : AppI18n::text("%1 个采样 · %2 个字段值").arg(samples.size()).arg(totalValues); + QString result = samples.isEmpty() ? AppI18n::text("未找到匹配的数字字段,请检查样例、字段筛选或字节偏移。") + : AppI18n::text("%1 个采样 · %2 个字段值").arg(samples.size()).arg(totalValues); if (totalValues > MaximumPreviewRows) { result += AppI18n::text(" · 预览前 %1 项").arg(MaximumPreviewRows); } @@ -561,7 +622,7 @@ void PlotParserDialog::loadExample() break; case AppPlot::Protocol::Binary: example = bytesToHex(usesProtocolTemplate() ? AppProtocol::exampleFrame(protocolTemplate()) - : QByteArray::fromHex("6400C80000004841")); + : QByteArray::fromHex("6400C80000004841")); break; default: example = QStringLiteral("24.8 60.5 101.3\n25.1 61.2 101.2"); diff --git a/src/app/view/plot_parser_dialog.h b/src/app/view/plot_parser_dialog.h index 19904fc..1625686 100644 --- a/src/app/view/plot_parser_dialog.h +++ b/src/app/view/plot_parser_dialog.h @@ -13,6 +13,7 @@ class LineEdit; class CaptionLabel; class PlainTextEdit; class PrimaryPushButton; +class PushButton; class TableWidget; } // namespace FluentQt @@ -21,6 +22,7 @@ class PlotParserDialog : public QDialog Q_OBJECT public: + static constexpr int EditTemplate = 2; explicit PlotParserDialog(const AppPlot::ParserConfig &config, QWidget *parent = nullptr, bool requireProtocolChoice = false); @@ -30,8 +32,10 @@ class PlotParserDialog : public QDialog AppPlot::ParserConfig parserConfig() const; void setProtocolTemplates(const QList &protocolTemplates); void setProtocolTemplate(const AppProtocol::ProtocolTemplate &protocolTemplate); + void useProtocolTemplate(const AppProtocol::ProtocolTemplate &protocolTemplate); bool usesProtocolTemplate() const; AppProtocol::ProtocolTemplate protocolTemplate() const; + void setSampleHex(const QString &hex); protected: void accept() override; @@ -42,6 +46,7 @@ class PlotParserDialog : public QDialog void removeSelectedBinaryFields(); bool collectBinaryFields(QVector *fields, QString *error) const; bool collectConfig(AppPlot::ParserConfig *config, QString *error) const; + bool usesTemplateFields() const; void updateProtocolControls(); void updatePreview(); void loadExample(); @@ -60,8 +65,11 @@ class PlotParserDialog : public QDialog FluentQt::CaptionLabel *m_protocolHint = nullptr; FluentQt::CaptionLabel *m_previewStatus = nullptr; FluentQt::PrimaryPushButton *m_applyButton = nullptr; + FluentQt::PushButton *m_editTemplateButton = nullptr; + FluentQt::CaptionLabel *m_binaryHint = nullptr; QWidget *m_binaryContainer = nullptr; QWidget *m_templateContainer = nullptr; + QWidget *m_binaryFieldButtons = nullptr; QString m_fieldsProtocol; bool m_binarySample = false; bool m_updatingPreview = false; diff --git a/src/app/view/protocol_analysis_window.cpp b/src/app/view/protocol_analysis_window.cpp new file mode 100644 index 0000000..7fccf17 --- /dev/null +++ b/src/app/view/protocol_analysis_window.cpp @@ -0,0 +1,470 @@ +#include "app/view/protocol_analysis_window.h" + +#include "app/core/app_i18n.h" +#include "app/core/app_settings.h" +#include "app/core/hex_utils.h" +#include "app/view/muted_text.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { +constexpr int MaximumRows = 256; +constexpr auto SelectedTemplatesKey = "protocolAnalysis/templates"; +constexpr auto CurveKeysKey = "protocolAnalysis/curves"; + +QString channelKey(const QString &templateName, const QString &address, const QString &fieldName) +{ + return QString::fromUtf8( + QJsonDocument(QJsonArray{templateName, address, fieldName}).toJson(QJsonDocument::Compact)); +} +} // namespace + +ProtocolAnalysisWindow::ProtocolAnalysisWindow(QWidget *parent) : QWidget(parent, Qt::Window) +{ + using namespace FluentQt; + setObjectName(QStringLiteral("protocolAnalysisWindow")); + setWindowTitle(AppI18n::text("协议解析")); + setMinimumSize(980, 560); + resize(1280, 720); + AppSettings settings; + const auto selected = settings.value(QLatin1String(SelectedTemplatesKey)).toStringList(); + m_selectedTemplates = QSet(selected.cbegin(), selected.cend()); + const auto curves = settings.value(QLatin1String(CurveKeysKey)).toStringList(); + m_curveKeys = QSet(curves.cbegin(), curves.cend()); + + auto *root = new QVBoxLayout(this); + root->setContentsMargins(12, 12, 12, 12); + root->setSpacing(10); + auto *toolbar = new QHBoxLayout; + m_enabledCheck = new CheckBox(AppI18n::text("启用协议解析"), this); + m_enabledCheck->setObjectName(QStringLiteral("protocolAnalysisEnabled")); + auto *edit = new PushButton(icon(FluentIcon::Edit), AppI18n::text("编辑协议"), this); + edit->setObjectName(QStringLiteral("protocolAnalysisEdit")); + m_pauseButton = new PushButton(icon(FluentIcon::Pause), AppI18n::text("暂停"), this); + m_pauseButton->setObjectName(QStringLiteral("protocolAnalysisPause")); + auto *clear = new PushButton(AppI18n::text("清空"), this); + clear->setObjectName(QStringLiteral("protocolAnalysisClear")); + auto *reset = new PushButton(AppI18n::text("复位视图"), this); + auto *configuration = new ToggleButton(icon(FluentIcon::Setting), AppI18n::text("配置"), this); + configuration->setObjectName(QStringLiteral("protocolAnalysisConfigurationToggle")); + configuration->setChecked(true); + toolbar->addWidget(configuration); + toolbar->addWidget(m_enabledCheck); + toolbar->addWidget(edit); + toolbar->addStretch(); + toolbar->addWidget(m_pauseButton); + toolbar->addWidget(clear); + toolbar->addWidget(reset); + root->addLayout(toolbar); + + auto *splitter = new QSplitter(Qt::Horizontal, this); + splitter->setChildrenCollapsible(false); + auto *panel = new QWidget(splitter); + panel->setObjectName(QStringLiteral("protocolAnalysisConfiguration")); + panel->setMinimumWidth(500); + auto *panelLayout = new QVBoxLayout(panel); + panelLayout->setContentsMargins(0, 0, 8, 0); + m_templateTable = new TableWidget(panel); + m_templateTable->setObjectName(QStringLiteral("protocolAnalysisTemplates")); + m_templateTable->setColumnCount(1); + m_templateTable->setHorizontalHeaderLabels({AppI18n::text("参与解析的模板")}); + m_templateTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + m_templateTable->verticalHeader()->hide(); + m_templateTable->verticalHeader()->setDefaultSectionSize(36); + m_templateTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_templateTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_templateTable->setSelectionMode(QAbstractItemView::SingleSelection); + m_templateTable->setMinimumHeight(86); + m_templateTable->setMaximumHeight(140); + panelLayout->addWidget(m_templateTable); + auto *hint = + new CaptionLabel(AppI18n::text("勾选字段即可显示曲线;载荷字段、倍率和设备地址在编辑协议中设置。"), panel); + hint->setWordWrap(true); + AppUi::setMutedTextColor(hint); + panelLayout->addWidget(hint); + m_valueTable = new TableWidget(panel); + m_valueTable->setObjectName(QStringLiteral("protocolAnalysisValues")); + m_valueTable->setColumnCount(5); + m_valueTable->setHorizontalHeaderLabels({AppI18n::text("曲线"), AppI18n::text("模板 / 地址"), AppI18n::text("字段"), + AppI18n::text("当前值"), AppI18n::text("更新时间")}); + auto *header = m_valueTable->horizontalHeader(); + header->setSectionResizeMode(0, QHeaderView::Fixed); + m_valueTable->setColumnWidth(0, 52); + header->setSectionResizeMode(1, QHeaderView::Stretch); + header->setSectionResizeMode(2, QHeaderView::Stretch); + for (int column : {3, 4}) { + header->setSectionResizeMode(column, QHeaderView::Fixed); + m_valueTable->setColumnWidth(column, column == 3 ? 92 : 132); + } + m_valueTable->verticalHeader()->hide(); + m_valueTable->verticalHeader()->setDefaultSectionSize(36); + m_valueTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_valueTable->setWordWrap(false); + m_valueTable->setSelectionBehavior(QAbstractItemView::SelectRows); + panelLayout->addWidget(m_valueTable, 1); + m_plot = new RealtimePlotWidget(splitter); + m_plot->setObjectName(QStringLiteral("protocolAnalysisPlot")); + m_plot->setCapacity(12000); + m_plot->setVisibleSpan(10); + m_plot->setMaximumVisiblePoints(2000); + m_plot->setLegendVisible(false); + m_plot->setCrosshairVisible(true); + m_plot->setAutoScroll(true); + m_plot->setAutoYRange(true); + m_plot->setSeriesVisible(0, false); + m_refreshRate = m_plot->refreshRate(); + m_plot->setRefreshRate(0); + m_plot->setUpdatesEnabled(false); + splitter->addWidget(panel); + splitter->addWidget(m_plot); + splitter->setStretchFactor(0, 1); + splitter->setStretchFactor(1, 1); + splitter->setSizes({570, 680}); + root->addWidget(splitter, 1); + connect(configuration, &PushButton::toggled, this, [this, panel](bool visible) { + panel->setVisible(visible); + m_plot->setLegendVisible(!visible); + }); + m_status = new CaptionLabel(this); + m_status->setObjectName(QStringLiteral("protocolAnalysisStatus")); + m_status->setWordWrap(true); + AppUi::setMutedTextColor(m_status); + root->addWidget(m_status); + m_valueTimer = new QTimer(this); + m_valueTimer->setSingleShot(true); + m_valueTimer->setInterval(50); + connect(m_valueTimer, &QTimer::timeout, this, &ProtocolAnalysisWindow::updateValues); + connect(m_enabledCheck, &CheckBox::toggled, this, [this](bool enabled) { + updateActivity(); + emit parsingEnabledChanged(enabled); + }); + connect(m_pauseButton, &PushButton::clicked, this, [this]() { + m_paused = !m_paused; + m_pauseButton->setText(m_paused ? AppI18n::text("继续") : AppI18n::text("暂停")); + m_pauseButton->setIcon(icon(m_paused ? FluentIcon::Play : FluentIcon::Pause)); + updateActivity(); + }); + connect(clear, &PushButton::clicked, this, &ProtocolAnalysisWindow::clearData); + connect(reset, &PushButton::clicked, m_plot, &RealtimePlotWidget::resetView); + connect(edit, &PushButton::clicked, this, [this]() { + const int row = m_templateTable->currentRow(); + emit editTemplateRequested(row >= 0 && row < m_templates.size() ? m_templates.at(row).name : QString()); + }); + connect(m_templateTable, &TableWidget::itemChanged, this, [this](QTableWidgetItem *item) { + const QString name = m_templates.at(item->row()).name; + if (item->checkState() == Qt::Checked) { + m_selectedTemplates.insert(name); + } else { + m_selectedTemplates.remove(name); + } + AppSettings settings; + settings.setValue(QLatin1String(SelectedTemplatesKey), m_selectedTemplates.values()); + resetChannels(); + }); + connect(m_valueTable, &TableWidget::itemChanged, this, [this](QTableWidgetItem *item) { + if (item->column() == 0) { + setCurveVisible(item->row(), item->checkState() == Qt::Checked); + } + }); + updateStatus(); +} + +void ProtocolAnalysisWindow::setProtocolTemplates(const QList &templates, + const QString &selectedTemplate) +{ + const bool changed = m_templates != templates; + const bool added = !selectedTemplate.isEmpty() && !m_selectedTemplates.contains(selectedTemplate); + if (!changed && !added) { + return; + } + m_templates = templates; + if (!selectedTemplate.isEmpty()) { + m_selectedTemplates.insert(selectedTemplate); + } + const QSignalBlocker blocker(m_templateTable); + m_templateTable->setRowCount(0); + for (int row = 0; row < m_templates.size(); ++row) { + const auto &item = m_templates.at(row); + m_templateTable->insertRow(row); + auto *name = new QTableWidgetItem(item.name); + name->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable); + name->setCheckState(m_selectedTemplates.contains(item.name) ? Qt::Checked : Qt::Unchecked); + m_templateTable->setItem(row, 0, name); + if (item.name == selectedTemplate) { + m_templateTable->selectRow(row); + } + } + m_templateTable->setFixedHeight(qBound(86, 36 * (int(m_templates.size()) + 1) + 4, 140)); + resetChannels(); +} + +void ProtocolAnalysisWindow::setParsingEnabled(bool enabled) +{ + const QSignalBlocker blocker(m_enabledCheck); + m_enabledCheck->setChecked(enabled); + updateActivity(); +} + +bool ProtocolAnalysisWindow::isCapturing() const +{ + return isVisible() && !isMinimized() && !m_paused && m_enabledCheck->isChecked(); +} + +void ProtocolAnalysisWindow::updateActivity() +{ + const bool active = isCapturing(); + m_plot->setRefreshRate(active ? m_refreshRate : 0); + m_plot->setUpdatesEnabled(active); + if (!active) { + m_streamBuffers.clear(); + m_valueTimer->stop(); + } + updateValues(); +} + +void ProtocolAnalysisWindow::showEvent(QShowEvent *event) +{ + QWidget::showEvent(event); + updateActivity(); +} + +void ProtocolAnalysisWindow::hideEvent(QHideEvent *event) +{ + QWidget::hideEvent(event); + updateActivity(); +} + +void ProtocolAnalysisWindow::changeEvent(QEvent *event) +{ + QWidget::changeEvent(event); + if (event->type() == QEvent::WindowStateChange) { + updateActivity(); + } +} + +void ProtocolAnalysisWindow::resetChannels() +{ + m_channels.clear(); + m_channelIndexes.clear(); + m_valueTable->setRowCount(0); + m_plot->clearSeries(); + m_plot->setSeriesVisible(0, false); + m_allocatedSeries = 0; + m_limited = false; + clearData(); + for (const auto &item : m_templates) { + if (m_selectedTemplates.contains(item.name) && item.addressSize == 0) { + for (const auto &field : item.payloadFields) { + channelFor(item.name, {}, field.name); + } + } + } + updateValues(); +} + +void ProtocolAnalysisWindow::resetStream() { m_streamBuffers.clear(); } + +void ProtocolAnalysisWindow::clearData() +{ + m_streamBuffers.clear(); + m_plot->clear(); + m_startTime = {}; + m_lastX = 0; + m_frameCount = 0; + for (auto &channel : m_channels) { + channel.value = std::numeric_limits::quiet_NaN(); + channel.timestamp = {}; + channel.x = 0; + } + updateValues(); +} + +int ProtocolAnalysisWindow::channelFor(const QString &templateName, const QString &address, const QString &fieldName) +{ + const QString key = channelKey(templateName, address, fieldName); + const auto existing = m_channelIndexes.constFind(key); + if (existing != m_channelIndexes.cend()) { + return existing.value(); + } + if (m_channels.size() >= MaximumRows) { + m_limited = true; + return -1; + } + const int row = m_channels.size(); + const QString device = templateName + (address.isEmpty() ? QString() : QStringLiteral(" · ") + address); + Channel channel; + channel.key = key; + channel.label = device + QStringLiteral(" / ") + fieldName; + channel.value = std::numeric_limits::quiet_NaN(); + m_channels.append(channel); + m_channelIndexes.insert(key, row); + { + const QSignalBlocker blocker(m_valueTable); + m_valueTable->insertRow(row); + for (int column = 0; column < m_valueTable->columnCount(); ++column) { + m_valueTable->setItem(row, column, new QTableWidgetItem); + } + auto *check = m_valueTable->item(row, 0); + check->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable); + check->setCheckState(m_curveKeys.contains(key) ? Qt::Checked : Qt::Unchecked); + m_valueTable->item(row, 1)->setText(device); + m_valueTable->item(row, 1)->setToolTip(device); + m_valueTable->item(row, 2)->setText(fieldName); + m_valueTable->item(row, 2)->setToolTip(fieldName); + m_valueTable->item(row, 3)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); + } + if (m_curveKeys.contains(key)) { + setCurveVisible(row, true); + } + return row; +} + +void ProtocolAnalysisWindow::setCurveVisible(int row, bool visible) +{ + auto &channel = m_channels[row]; + const QSignalBlocker blocker(m_valueTable); + int checked = 0; + for (int index = 0; index < m_valueTable->rowCount(); ++index) { + checked += m_valueTable->item(index, 0)->checkState() == Qt::Checked; + } + if (visible && checked > AppPlot::MaximumChannels) { + m_valueTable->item(row, 0)->setCheckState(Qt::Unchecked); + m_limited = true; + updateStatus(); + return; + } + if (visible && channel.series < 0) { + channel.series = m_allocatedSeries++; + if (channel.series >= m_plot->seriesCount()) { + m_plot->addSeries(channel.label); + } else { + m_plot->setSeriesName(channel.series, channel.label); + } + if (channel.timestamp.isValid()) { + m_plot->appendPoint(channel.series, channel.x, channel.value); + } + QPixmap swatch(10, 10); + swatch.fill(m_plot->seriesColor(channel.series)); + m_valueTable->item(row, 2)->setIcon(QIcon(swatch)); + } + if (channel.series >= 0) { + m_plot->setSeriesVisible(channel.series, visible); + } + if (visible) { + m_curveKeys.insert(channel.key); + } else { + m_curveKeys.remove(channel.key); + } + AppSettings settings; + settings.setValue(QLatin1String(CurveKeysKey), m_curveKeys.values()); +} + +void ProtocolAnalysisWindow::appendRecord(const QDateTime ×tamp, const QByteArray &bytes, bool stream) +{ + if (!isCapturing() || bytes.isEmpty()) { + return; + } + for (const auto &item : m_templates) { + if (!m_selectedTemplates.contains(item.name) || !AppProtocol::payloadConfigurationError(item).isEmpty()) { + continue; + } + for (const auto &frame : AppProtocol::takeFrames(m_streamBuffers[item.name], bytes, item, stream)) { + appendFrame(timestamp, frame.bytes, item, frame.parsed); + } + } + if (!m_valueTimer->isActive()) { + m_valueTimer->start(); + } +} + +void ProtocolAnalysisWindow::appendFrame(const QDateTime ×tamp, const QByteArray &frame, + const AppProtocol::ProtocolTemplate &item, + const AppProtocol::ParseResult &parsed) +{ + if (item.addressSize > 0 && item.addressOffset > frame.size() - item.addressSize) { + return; + } + const QString address = + item.addressSize > 0 ? bytesToHex(frame.mid(item.addressOffset, item.addressSize)) : QString(); + const auto samples = AppPlot::extractSamples(AppProtocol::payloadParserConfig(item), {}, frame, parsed.payload); + const AppPlot::PlotSample values = samples.isEmpty() ? AppPlot::PlotSample() : samples.first(); + if (!m_startTime.isValid()) { + m_startTime = timestamp; + } + m_lastX = qMax(m_lastX, m_startTime.msecsTo(timestamp) / 1000.0); + ++m_frameCount; + // Clear absent fields in shorter frames instead of leaving an older value + // looking like a measurement from this frame. + QStringList names; + if (item.payloadFields.isEmpty()) { + for (const auto &value : values) { + names.append(value.name); + } + } else { + for (const auto &field : item.payloadFields) { + names.append(field.name); + } + } + for (const auto &name : names) { + const int row = channelFor(item.name, address, name); + if (row < 0) { + continue; + } + auto &channel = m_channels[row]; + const auto value = + std::find_if(values.cbegin(), values.cend(), [&name](const auto &v) { return v.name == name; }); + channel.value = value == values.cend() ? std::numeric_limits::quiet_NaN() : value->value; + channel.timestamp = timestamp; + channel.x = m_lastX; + if (channel.series >= 0) { + m_plot->appendPoint(channel.series, channel.x, channel.value); + } + } +} + +void ProtocolAnalysisWindow::updateValues() +{ + const QSignalBlocker blocker(m_valueTable); + for (int row = 0; row < m_channels.size(); ++row) { + const auto &channel = m_channels.at(row); + m_valueTable->item(row, 3)->setText(std::isfinite(channel.value) ? QString::number(channel.value, 'g', 12) + : QStringLiteral("—")); + m_valueTable->item(row, 3)->setToolTip(std::isfinite(channel.value) ? QString::number(channel.value, 'g', 16) + : QString()); + m_valueTable->item(row, 4)->setText(channel.timestamp.isValid() + ? channel.timestamp.toString(QStringLiteral("HH:mm:ss.zzz")) + : QStringLiteral("—")); + } + updateStatus(); +} + +void ProtocolAnalysisWindow::updateStatus() +{ + QString state = !m_enabledCheck->isChecked() ? AppI18n::text("协议模板未启用") + : m_paused ? AppI18n::text("已暂停") + : AppI18n::text("实时"); + QString text = + AppI18n::text("%1 · %2 帧 · %3 个数据字段 · 横轴为秒").arg(state).arg(m_frameCount).arg(m_channels.size()); + if (m_channels.isEmpty()) { + text += QStringLiteral(" · ") + AppI18n::text("等待接收所选协议的数据"); + } + if (m_limited) { + text += QStringLiteral(" · ") + + AppI18n::text("最多显示 %1 个字段,同时绘制 %2 条曲线").arg(MaximumRows).arg(AppPlot::MaximumChannels); + } + m_status->setText(text); +} diff --git a/src/app/view/protocol_analysis_window.h b/src/app/view/protocol_analysis_window.h new file mode 100644 index 0000000..e5e81d7 --- /dev/null +++ b/src/app/view/protocol_analysis_window.h @@ -0,0 +1,82 @@ +#pragma once + +#include "app/core/protocol_template.h" + +#include +#include +#include +#include + +class QTimer; +namespace FluentQt { +class CaptionLabel; +class CheckBox; +class PushButton; +class RealtimePlotWidget; +class TableWidget; +} // namespace FluentQt + +class ProtocolAnalysisWindow : public QWidget +{ + Q_OBJECT + + public: + explicit ProtocolAnalysisWindow(QWidget *parent = nullptr); + void setProtocolTemplates(const QList &templates, + const QString &selectedTemplate = {}); + void setParsingEnabled(bool enabled); + void appendRecord(const QDateTime ×tamp, const QByteArray &bytes, bool stream = false); + void clearData(); + void resetStream(); + + signals: + void parsingEnabledChanged(bool enabled); + void editTemplateRequested(const QString &name); + + protected: + void showEvent(QShowEvent *event) override; + void hideEvent(QHideEvent *event) override; + void changeEvent(QEvent *event) override; + + private: + struct Channel + { + QString key; + QString label; + double value = 0.0; + double x = 0.0; + QDateTime timestamp; + int series = -1; + }; + + bool isCapturing() const; + void updateActivity(); + void resetChannels(); + void updateValues(); + void updateStatus(); + int channelFor(const QString &templateName, const QString &address, const QString &fieldName); + void setCurveVisible(int row, bool visible); + void appendFrame(const QDateTime ×tamp, const QByteArray &frame, + const AppProtocol::ProtocolTemplate &protocolTemplate, const AppProtocol::ParseResult &parsed); + + QList m_templates; + QSet m_selectedTemplates; + QSet m_curveKeys; + QHash m_streamBuffers; + QVector m_channels; + QHash m_channelIndexes; + FluentQt::CheckBox *m_enabledCheck = nullptr; + FluentQt::PushButton *m_pauseButton = nullptr; + FluentQt::TableWidget *m_templateTable = nullptr; + FluentQt::TableWidget *m_valueTable = nullptr; + FluentQt::RealtimePlotWidget *m_plot = nullptr; + FluentQt::CaptionLabel *m_status = nullptr; + QTimer *m_valueTimer = nullptr; + QDateTime m_startTime; + double m_lastX = 0.0; + qint64 m_frameCount = 0; + int m_allocatedSeries = 0; + int m_refreshRate = 30; + bool m_paused = false; + bool m_limited = false; +}; diff --git a/src/app/view/protocol_payload_editor.cpp b/src/app/view/protocol_payload_editor.cpp new file mode 100644 index 0000000..b43c5f4 --- /dev/null +++ b/src/app/view/protocol_payload_editor.cpp @@ -0,0 +1,301 @@ +#include "app/view/protocol_payload_editor.h" +#include "app/core/app_i18n.h" +#include "app/view/muted_text.h" +#include +#include +#include +#include +#include + +namespace { +class FieldNumberSpinBox : public FluentQt::DoubleSpinBox +{ + public: + using FluentQt::DoubleSpinBox::DoubleSpinBox; + + protected: + QString textFromValue(double value) const override + { + QString text = FluentQt::DoubleSpinBox::textFromValue(value); + const auto decimal = locale().decimalPoint(); + if (text.contains(decimal)) { + while (text.endsWith(QLatin1Char('0'))) + text.chop(1); + if (text.endsWith(decimal)) + text.chop(decimal.size()); + } + return text; + } +}; +QString typeLabel(AppPlot::BinaryType type) +{ + const int bits = AppPlot::binaryTypeSize(type) * 8; + QString label; + if (type == AppPlot::BinaryType::Float32 || type == AppPlot::BinaryType::Float64) + label = AppI18n::text("%1 位浮点数").arg(bits); + else if (type == AppPlot::BinaryType::Int8 || type == AppPlot::BinaryType::Int16 || + type == AppPlot::BinaryType::Int32 || type == AppPlot::BinaryType::Int64) + label = AppI18n::text("%1 位有符号整数").arg(bits); + else + label = AppI18n::text("%1 位无符号整数").arg(bits); + return label + QStringLiteral(" · ") + AppPlot::binaryTypeKey(type); +} +} // namespace + +ProtocolPayloadEditor::ProtocolPayloadEditor(QWidget *parent) : QWidget(parent) +{ + using namespace FluentQt; + setObjectName(QStringLiteral("protocolPayloadEditor")); + auto *root = new QVBoxLayout(this); + root->setContentsMargins(0, 0, 0, 0); + root->setSpacing(12); + m_title = new StrongBodyLabel(AppI18n::text("字段属性"), this); + root->addWidget(m_title); + m_addressPanel = new QWidget(this); + auto *addressForm = new QFormLayout(m_addressPanel); + addressForm->setContentsMargins(0, 0, 0, 0); + addressForm->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); + addressForm->setVerticalSpacing(8); + m_addressSize = new ComboBox(m_addressPanel); + m_addressSize->setObjectName(QStringLiteral("protocolAddressSize")); + m_addressSize->addItem(AppI18n::text("不区分设备地址"), QIcon(), 0); + for (int size : {1, 2, 4}) + m_addressSize->addItem(QStringLiteral("%1 B").arg(size), QIcon(), size); + m_addressOffset = new SpinBox(m_addressPanel); + m_addressOffset->setObjectName(QStringLiteral("protocolAddressOffset")); + m_addressOffset->setRange(0, 1024 * 1024 - 4); + addressForm->addRow(AppI18n::text("字节数"), m_addressSize); + addressForm->addRow(AppI18n::text("整帧起点"), m_addressOffset); + root->addWidget(m_addressPanel); + m_form = new QWidget(this); + auto *form = new QFormLayout(m_form); + form->setContentsMargins(0, 0, 0, 0); + form->setVerticalSpacing(8); + form->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); + m_name = new LineEdit(m_form); + m_name->setObjectName(QStringLiteral("protocolPayloadFieldName")); + m_offset = new SpinBox(m_form); + m_offset->setObjectName(QStringLiteral("protocolPayloadFieldOffset")); + m_offset->setRange(0, 1024 * 1024 - 1); + m_type = new ComboBox(m_form); + m_type->setObjectName(QStringLiteral("protocolPayloadFieldType")); + for (const auto type : {AppPlot::BinaryType::UInt8, AppPlot::BinaryType::Int8, AppPlot::BinaryType::UInt16, + AppPlot::BinaryType::Int16, AppPlot::BinaryType::UInt32, AppPlot::BinaryType::Int32, + AppPlot::BinaryType::UInt64, AppPlot::BinaryType::Int64, AppPlot::BinaryType::Float32, + AppPlot::BinaryType::Float64}) + m_type->addItem(typeLabel(type), QIcon(), AppPlot::binaryTypeKey(type)); + m_order = new ComboBox(m_form); + m_order->setObjectName(QStringLiteral("protocolPayloadFieldByteOrder")); + m_order->addItem(AppI18n::text("小端"), QIcon(), QStringLiteral("little")); + m_order->addItem(AppI18n::text("大端"), QIcon(), QStringLiteral("big")); + m_scale = new FieldNumberSpinBox(m_form); + m_scale->setObjectName(QStringLiteral("protocolPayloadFieldScale")); + m_add = new FieldNumberSpinBox(m_form); + m_add->setObjectName(QStringLiteral("protocolPayloadFieldAdd")); + for (auto *spin : {m_scale, m_add}) { + spin->setDecimals(9); + spin->setRange(-1e12, 1e12); + spin->setKeyboardTracking(false); + spin->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); + } + m_type->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); + form->addRow(AppI18n::text("名称"), m_name); + form->addRow(AppI18n::text("载荷内起点"), m_offset); + form->addRow(AppI18n::text("数值类型"), m_type); + form->addRow(AppI18n::text("字节序"), m_order); + form->addRow(AppI18n::text("倍率"), m_scale); + form->addRow(AppI18n::text("加值"), m_add); + root->addWidget(m_form); + m_fieldSummary = new CaptionLabel(this); + m_fieldSummary->setObjectName(QStringLiteral("protocolPayloadFieldSummary")); + m_fieldSummary->setWordWrap(true); + m_fieldSummary->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); + AppUi::setMutedTextColor(m_fieldSummary); + root->addWidget(m_fieldSummary); + root->addStretch(1); + connect(m_name, &LineEdit::textChanged, this, &ProtocolPayloadEditor::updateField); + connect(m_offset, &SpinBox::valueChanged, this, &ProtocolPayloadEditor::updateField); + connect(m_type, &ComboBox::currentIndexChanged, this, &ProtocolPayloadEditor::updateField); + connect(m_order, &ComboBox::currentIndexChanged, this, &ProtocolPayloadEditor::updateField); + connect(m_scale, &DoubleSpinBox::valueChanged, this, &ProtocolPayloadEditor::updateField); + connect(m_add, &DoubleSpinBox::valueChanged, this, &ProtocolPayloadEditor::updateField); + connect(m_addressOffset, &SpinBox::valueChanged, this, [this]() { + updateFieldSummary(); + if (!m_loading) + emit changed(); + }); + connect(m_addressSize, &ComboBox::currentIndexChanged, this, [this]() { + m_addressOffset->setEnabled(m_addressSize->currentData().toInt() > 0); + updateFieldSummary(); + if (!m_loading) + emit changed(); + }); + setProtocolTemplate(AppProtocol::ProtocolTemplate()); +} + +void ProtocolPayloadEditor::setProtocolTemplate(const AppProtocol::ProtocolTemplate &protocolTemplate) +{ + m_loading = true; + m_fields = protocolTemplate.payloadFields; + m_payloadOffset = protocolTemplate.payloadOffset; + m_addressOffset->setValue(protocolTemplate.addressOffset); + m_addressSize->setCurrentIndex(m_addressSize->findData(protocolTemplate.addressSize)); + m_addressOffset->setEnabled(protocolTemplate.addressSize > 0); + m_selected = m_fields.isEmpty() ? -1 : qBound(0, m_selected, int(m_fields.size()) - 1); + m_loading = false; + updateControls(); +} +void ProtocolPayloadEditor::applyTo(AppProtocol::ProtocolTemplate &protocolTemplate) const +{ + protocolTemplate.payloadFields = m_fields; + protocolTemplate.addressOffset = m_addressOffset->value(); + protocolTemplate.addressSize = m_addressSize->currentData().toInt(); +} +int ProtocolPayloadEditor::selectedField() const { return m_selected; } +const QVector &ProtocolPayloadEditor::fields() const { return m_fields; } +void ProtocolPayloadEditor::setPayloadOffset(int offset) +{ + m_payloadOffset = offset; + updateFieldSummary(); +} +void ProtocolPayloadEditor::setAddressEditing(bool address) +{ + m_addressEditing = address; + updateControls(); +} +void ProtocolPayloadEditor::selectPayloadField(int index) +{ + m_selected = index >= 0 && index < m_fields.size() ? index : -1; + m_addressEditing = false; + updateControls(); + emit fieldSelected(m_selected); +} +void ProtocolPayloadEditor::addField(AppPlot::BinaryType type) +{ + if (m_fields.size() >= AppPlot::MaximumChannels) + return; + AppPlot::BinaryField field; + field.type = type; + for (int suffix = 1; suffix <= m_fields.size() + 1; ++suffix) { + field.name = QStringLiteral("field_%1").arg(suffix); + bool exists = false; + for (const auto &existing : m_fields) + exists |= existing.name == field.name; + if (!exists) + break; + } + if (!m_fields.isEmpty()) { + qint64 next = 0; + for (const auto &existing : m_fields) + next = qMax(next, qint64(existing.byteOffset) + AppPlot::binaryTypeSize(existing.type)); + field.byteOffset = int(qMin(1024 * 1024 - 1, next)); + } + m_fields.append(field); + m_selected = m_fields.size() - 1; + m_addressEditing = false; + updateControls(); + emit changed(); + emit fieldSelected(m_selected); +} +void ProtocolPayloadEditor::removeField() +{ + if (m_selected < 0 || m_selected >= m_fields.size()) + return; + m_fields.removeAt(m_selected); + m_selected = m_fields.isEmpty() ? -1 : qMin(m_selected, int(m_fields.size()) - 1); + updateControls(); + emit changed(); + emit fieldSelected(m_selected); +} +bool ProtocolPayloadEditor::moveFieldBefore(int field, int before) +{ + if (field < 0 || field >= m_fields.size() || before < -1 || before >= m_fields.size() || field == before) + return false; + QList order(m_fields.size()); + std::iota(order.begin(), order.end(), 0); + std::stable_sort(order.begin(), order.end(), + [this](int a, int b) { return m_fields.at(a).byteOffset < m_fields.at(b).byteOffset; }); + const int from = order.indexOf(field); + int to = before < 0 ? order.size() : order.indexOf(before); + if (to > from) + --to; + if (from == to) + return false; + QList gaps; + int end = 0; + for (int index : order) { + const auto &item = m_fields.at(index); + gaps.append(qMax(0, item.byteOffset - end)); + end = item.byteOffset + AppPlot::binaryTypeSize(item.type); + } + order.move(from, to); + QVector reordered; + int offset = 0; + for (int i = 0; i < order.size(); ++i) { + auto item = m_fields.at(order.at(i)); + offset += gaps.at(i); + item.byteOffset = offset; + offset += AppPlot::binaryTypeSize(item.type); + reordered.append(item); + } + m_fields = reordered; + m_selected = to; + m_addressEditing = false; + updateControls(); + emit changed(); + emit fieldSelected(m_selected); + return true; +} +void ProtocolPayloadEditor::updateControls() +{ + const bool selected = m_selected >= 0 && m_selected < m_fields.size(); + m_addressPanel->setVisible(m_addressEditing); + m_form->setVisible(!m_addressEditing && selected); + m_title->setText(m_addressEditing ? AppI18n::text("设备地址") + : selected ? AppI18n::text("字段属性 · %1").arg(m_fields.at(m_selected).name) + : AppI18n::text("字段属性")); + if (selected) { + m_loading = true; + const auto &field = m_fields.at(m_selected); + m_name->setText(field.name); + m_offset->setValue(field.byteOffset); + m_type->setCurrentIndex(m_type->findData(AppPlot::binaryTypeKey(field.type))); + m_order->setCurrentIndex(m_order->findData(AppPlot::byteOrderKey(field.byteOrder))); + m_order->setEnabled(AppPlot::binaryTypeSize(field.type) > 1); + m_scale->setValue(field.scale); + m_add->setValue(field.add); + m_loading = false; + } + updateFieldSummary(); +} +void ProtocolPayloadEditor::updateField() +{ + if (m_loading || m_selected < 0 || m_selected >= m_fields.size()) + return; + auto &field = m_fields[m_selected]; + field.name = m_name->text().simplified(); + field.byteOffset = m_offset->value(); + AppPlot::binaryTypeFromKey(m_type->currentData().toString(), &field.type); + AppPlot::byteOrderFromKey(m_order->currentData().toString(), &field.byteOrder); + m_order->setEnabled(AppPlot::binaryTypeSize(field.type) > 1); + field.scale = m_scale->value(); + field.add = m_add->value(); + m_title->setText(AppI18n::text("字段属性 · %1").arg(field.name)); + updateFieldSummary(); + emit changed(); +} +void ProtocolPayloadEditor::updateFieldSummary() +{ + if (!m_fieldSummary) + return; + if (m_addressEditing) + m_fieldSummary->setText(AppI18n::text("地址起点按整帧计算,从 0 开始。接收窗口按地址分组显示设备数据。")); + else if (m_selected >= 0 && m_selected < m_fields.size()) { + const auto &field = m_fields.at(m_selected); + m_fieldSummary->setText(AppI18n::text("整帧字节 %1–%2\n显示值 = 原始值 × %3 + %4") + .arg(m_payloadOffset + field.byteOffset) + .arg(m_payloadOffset + field.byteOffset + AppPlot::binaryTypeSize(field.type) - 1) + .arg(QString::number(field.scale, 'g', 12), QString::number(field.add, 'g', 12))); + } else + m_fieldSummary->setText(AppI18n::text("从左侧选择字段,或点击上方的字节类型添加数据字段。")); +} diff --git a/src/app/view/protocol_payload_editor.h b/src/app/view/protocol_payload_editor.h new file mode 100644 index 0000000..e39b500 --- /dev/null +++ b/src/app/view/protocol_payload_editor.h @@ -0,0 +1,52 @@ +#pragma once +#include "app/core/protocol_template.h" +#include +namespace FluentQt { +class CaptionLabel; +class ComboBox; +class DoubleSpinBox; +class LineEdit; +class SpinBox; +class StrongBodyLabel; +} // namespace FluentQt +class ProtocolPayloadEditor : public QWidget +{ + Q_OBJECT + public: + explicit ProtocolPayloadEditor(QWidget *parent = nullptr); + void setProtocolTemplate(const AppProtocol::ProtocolTemplate &protocolTemplate); + void applyTo(AppProtocol::ProtocolTemplate &protocolTemplate) const; + void setPayloadOffset(int offset); + void selectPayloadField(int index); + void setAddressEditing(bool address); + void addField(AppPlot::BinaryType type = AppPlot::BinaryType::UInt8); + void removeField(); + bool moveFieldBefore(int field, int before); + int selectedField() const; + const QVector &fields() const; + signals: + void changed(); + void fieldSelected(int index); + + private: + void updateField(); + void updateControls(); + void updateFieldSummary(); + QVector m_fields; + FluentQt::LineEdit *m_name = nullptr; + FluentQt::SpinBox *m_offset = nullptr; + FluentQt::ComboBox *m_type = nullptr; + FluentQt::ComboBox *m_order = nullptr; + FluentQt::DoubleSpinBox *m_scale = nullptr; + FluentQt::DoubleSpinBox *m_add = nullptr; + FluentQt::SpinBox *m_addressOffset = nullptr; + FluentQt::ComboBox *m_addressSize = nullptr; + FluentQt::CaptionLabel *m_fieldSummary = nullptr; + FluentQt::StrongBodyLabel *m_title = nullptr; + QWidget *m_addressPanel = nullptr; + QWidget *m_form = nullptr; + int m_payloadOffset = 0; + int m_selected = -1; + bool m_addressEditing = false; + bool m_loading = false; +}; diff --git a/src/app/view/protocol_template_window.cpp b/src/app/view/protocol_template_window.cpp index c3b71ea..32025eb 100644 --- a/src/app/view/protocol_template_window.cpp +++ b/src/app/view/protocol_template_window.cpp @@ -1,354 +1,774 @@ #include "app/view/protocol_template_window.h" - #include "app/core/app_i18n.h" #include "app/core/font_preferences.h" #include "app/core/hex_utils.h" #include "app/view/muted_text.h" - +#include "app/view/protocol_payload_editor.h" #include +#include #include +#include +#include +#include +#include +#include #include #include -#include +#include #include +#include #include #include +#include #include +#include +#include +#include namespace { +constexpr auto PayloadFieldMime = "application/x-fluent-serial-payload-field"; -struct FrameArea +class FieldResultModel final : public QStandardItemModel { - const char *name; - QString color; - QString background; + public: + using QStandardItemModel::QStandardItemModel; + std::function moveField; + + QStringList mimeTypes() const override { return {QLatin1String(PayloadFieldMime)}; } + Qt::DropActions supportedDropActions() const override { return Qt::MoveAction; } + QMimeData *mimeData(const QModelIndexList &indexes) const override + { + auto *mime = new QMimeData; + if (!indexes.isEmpty()) { + const auto index = indexes.first().siblingAtColumn(0); + if (index.data(Qt::UserRole).toString() == QLatin1String("field")) + mime->setData(QLatin1String(PayloadFieldMime), index.data(Qt::UserRole + 1).toString().toUtf8()); + } + return mime; + } + bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int, + const QModelIndex &parent) const override + { + if (action != Qt::MoveAction || !data->hasFormat(QLatin1String(PayloadFieldMime)) || parent.isValid()) + return false; + int first = -1, last = -1; + for (int i = 0; i < rowCount(); ++i) { + if (index(i, 0).data(Qt::UserRole).toString() == QLatin1String("field")) { + if (first < 0) + first = i; + last = i; + } + } + const int insertion = row < 0 ? rowCount() : row; + return first >= 0 && insertion >= first && insertion <= last + 1; + } + bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, + const QModelIndex &parent) override + { + if (!canDropMimeData(data, action, row, column, parent)) + return false; + int before = -1; + for (int i = row < 0 ? rowCount() : row; i < rowCount(); ++i) { + const auto target = index(i, 0); + if (target.data(Qt::UserRole).toString() == QLatin1String("field")) { + before = target.data(Qt::UserRole + 1).toInt(); + break; + } + } + return moveField(data->data(QLatin1String(PayloadFieldMime)).toInt(), before); + } }; -const QList &frameAreas() +class FieldResultTable final : public FluentQt::TableView { - static const QList areas = { - {"帧头", QStringLiteral("#176388"), QStringLiteral("#dff2fb")}, - {"长度", QStringLiteral("#775c00"), QStringLiteral("#fff1ba")}, - {"命令", QStringLiteral("#70449a"), QStringLiteral("#eee2fb")}, - {"载荷", QStringLiteral("#21673e"), QStringLiteral("#def3e5")}, - {"校验", QStringLiteral("#a34728"), QStringLiteral("#ffe5d8")}, - {"帧尾", QStringLiteral("#9a2f63"), QStringLiteral("#fbe1ee")}, - {"其他", QStringLiteral("#555555"), QStringLiteral("#eeeeee")}, - }; - return areas; -} + public: + using FluentQt::TableView::TableView; + + protected: + void startDrag(Qt::DropActions) override + { + const auto index = currentIndex().siblingAtColumn(0); + if (index.data(Qt::UserRole).toString() != QLatin1String("field")) + return; + QDrag drag(this); + drag.setMimeData(model()->mimeData({index})); + drag.setPixmap(viewport()->grab(visualRect(index))); + // The protocol editor performs the move and rebuilds the preview; the view must not remove source cells. + drag.exec(Qt::MoveAction); + } +}; QString byteRange(int offset, int size) { - if (size <= 0) { + if (size <= 0) return QStringLiteral("—"); - } return size == 1 ? QString::number(offset) : QStringLiteral("%1–%2").arg(offset).arg(offset + size - 1); } - +struct FieldRow +{ + QString kind, name, type, raw, value, status, details; + int offset = 0, size = 0, field = -1; + bool warning = false; +}; +QString rowColor(const QString &kind, int field) +{ + if (kind == QLatin1String("field")) { + const QStringList colors{QStringLiteral("#def3e5"), QStringLiteral("#dff2fb"), QStringLiteral("#eee2fb"), + QStringLiteral("#fff1ba")}; + return colors.at(qMax(0, field) % colors.size()); + } + if (kind == QLatin1String("header")) + return QStringLiteral("#dff2fb"); + if (kind == QLatin1String("length")) + return QStringLiteral("#fff1ba"); + if (kind == QLatin1String("checksum")) + return QStringLiteral("#ffe5d8"); + if (kind == QLatin1String("trailer")) + return QStringLiteral("#fbe1ee"); + if (kind == QLatin1String("address")) + return QStringLiteral("#e8e6f8"); + if (kind == QLatin1String("command")) + return QStringLiteral("#eee2fb"); + if (kind == QLatin1String("payload")) + return QStringLiteral("#def3e5"); + return QStringLiteral("#eeeeee"); +} } // namespace -ProtocolTemplateWindow::ProtocolTemplateWindow(QWidget *editor, QWidget *parent) : QWidget(parent, Qt::Window) +ProtocolTemplateWindow::ProtocolTemplateWindow(QWidget *editor, QWidget *parent, ProtocolPayloadEditor *payloadEditor) + : QWidget(parent, Qt::Window), m_payloadEditor(payloadEditor), m_internalPayloadEditor(!payloadEditor) { using namespace FluentQt; - setObjectName(QStringLiteral("protocolTemplateWindow")); setWindowTitle(AppI18n::text("帧协议编辑器")); - setMinimumSize(920, 640); - resize(1100, 760); - + setMinimumSize(1000, 720); + resize(1200, 850); auto *root = new QVBoxLayout(this); - root->setContentsMargins(16, 16, 16, 16); - root->setSpacing(12); + root->setContentsMargins(16, 12, 16, 12); + root->setSpacing(10); m_templateTitle = new BodyLabel(AppI18n::text("协议结构与样例解析"), this); QFont titleFont = m_templateTitle->font(); titleFont.setBold(true); titleFont.setPixelSize(18); m_templateTitle->setFont(titleFont); root->addWidget(m_templateTitle); - auto *splitter = new QSplitter(Qt::Horizontal, this); splitter->setChildrenCollapsible(false); - auto *editorScroll = new SingleDirectionScrollArea(Qt::Vertical, splitter); - editorScroll->setObjectName(QStringLiteral("protocolTemplateEditorScroll")); - editorScroll->enableTransparentBackground(); - editorScroll->setWidgetResizable(true); - editorScroll->setMinimumWidth(355); - editorScroll->setWidget(editor); - auto *preview = new QWidget(splitter); - auto *previewLayout = new QVBoxLayout(preview); - previewLayout->setContentsMargins(8, 0, 0, 0); - previewLayout->setSpacing(10); - - m_validationLabel = new CaptionLabel(preview); - m_validationLabel->setObjectName(QStringLiteral("protocolTemplateValidationLabel")); - m_validationLabel->setWordWrap(true); - previewLayout->addWidget(m_validationLabel); - + auto *listPanel = new QWidget(splitter); + auto *listLayout = new QVBoxLayout(listPanel); + listLayout->setContentsMargins(0, 0, 8, 0); + listLayout->setSpacing(12); + auto *sampleCard = new SimpleCardWidget(listPanel); + auto *sampleLayout = new QVBoxLayout(sampleCard); + sampleLayout->setContentsMargins(12, 12, 12, 12); + sampleLayout->setSpacing(6); auto *sampleToolbar = new QHBoxLayout; - sampleToolbar->addWidget(new BodyLabel(AppI18n::text("样例帧 HEX"), preview)); - sampleToolbar->addStretch(1); - auto *exampleButton = new PushButton(AppI18n::text("内置示例帧"), preview); - exampleButton->setObjectName(QStringLiteral("protocolTemplateSampleExampleButton")); - m_lastFrameButton = new PushButton(AppI18n::text("最新接收"), preview); + sampleToolbar->addWidget(new StrongBodyLabel(AppI18n::text("样例帧 HEX"), sampleCard)); + sampleToolbar->addStretch(); + m_lastFrameButton = new PushButton(AppI18n::text("最新接收"), this); m_lastFrameButton->setObjectName(QStringLiteral("protocolTemplateLastFrameButton")); m_lastFrameButton->setEnabled(false); - sampleToolbar->addWidget(exampleButton); sampleToolbar->addWidget(m_lastFrameButton); - previewLayout->addLayout(sampleToolbar); - - m_sampleEdit = new PlainTextEdit(preview); + m_createPlotButton = new PushButton(AppI18n::text("创建曲线"), sampleCard); + m_createPlotButton->setObjectName(QStringLiteral("protocolTemplateCreatePlotButton")); + sampleToolbar->addWidget(m_createPlotButton); + connect(m_createPlotButton, &PushButton::clicked, this, &ProtocolTemplateWindow::createPlotRequested); + sampleLayout->addLayout(sampleToolbar); + m_sampleEdit = new PlainTextEdit(this); m_sampleEdit->setObjectName(QStringLiteral("protocolTemplateSampleEdit")); - m_sampleEdit->setPlaceholderText(QStringLiteral("AA 55 03 10 01 02 03 4D 6E")); + m_sampleEdit->setPlaceholderText(AppI18n::text("自动样例随配置更新;粘贴 HEX 后保留,清空可恢复自动生成")); m_sampleEdit->setFont(AppFontPreferences::inputMonospaceFont()); - m_sampleEdit->setMaximumHeight(88); - m_sampleEdit->setMinimumHeight(70); - previewLayout->addWidget(m_sampleEdit); - - auto *hint = new CaptionLabel(AppI18n::text("编辑字段或样例即可更新解析;字节位置从 0 开始。"), preview); - AppUi::setMutedTextColor(hint); - hint->setWordWrap(true); - previewLayout->addWidget(hint); - - auto *legend = new QHBoxLayout; - for (const FrameArea &area : frameAreas()) { - auto *label = new CaptionLabel(AppI18n::text(area.name), preview); - label->setStyleSheet(QStringLiteral("color:%1;background:%2;border-radius:4px;padding:4px 8px;") - .arg(area.color, area.background)); - legend->addWidget(label); - } - legend->addStretch(); - previewLayout->addLayout(legend); - - m_structureView = new TextBrowser(preview); + m_sampleEdit->setFixedHeight(48); + sampleLayout->addWidget(m_sampleEdit); + m_validationLabel = new CaptionLabel(this); + m_validationLabel->setObjectName(QStringLiteral("protocolTemplateValidationLabel")); + m_validationLabel->setWordWrap(true); + m_validationLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); + sampleLayout->addWidget(m_validationLabel); + m_structureView = new TextBrowser(this); m_structureView->setObjectName(QStringLiteral("protocolTemplateStructureView")); m_structureView->setFont(AppFontPreferences::inputMonospaceFont()); + m_structureView->setOpenLinks(false); m_structureView->setOpenExternalLinks(false); - m_structureView->setMinimumHeight(96); - m_structureView->setMaximumHeight(136); - previewLayout->addWidget(m_structureView); - - m_parseStatusLabel = new CaptionLabel(preview); + m_structureView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_structureView->viewport()->installEventFilter(this); + sampleLayout->addWidget(m_structureView); + m_parseStatusLabel = new CaptionLabel(this); m_parseStatusLabel->setObjectName(QStringLiteral("protocolTemplateParseStatusLabel")); m_parseStatusLabel->setWordWrap(true); - previewLayout->addWidget(m_parseStatusLabel); - - m_resultModel = new QStandardItemModel(this); - m_resultModel->setHorizontalHeaderLabels({AppI18n::text("字段"), AppI18n::text("位置"), AppI18n::text("解析值")}); - m_resultTable = new TableView(preview); + m_parseStatusLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); + AppUi::setMutedTextColor(m_parseStatusLabel); + sampleLayout->addWidget(m_parseStatusLabel); + listLayout->addWidget(sampleCard); + const QList> frameKinds{ + {QStringLiteral("header"), AppI18n::text("帧头")}, {QStringLiteral("length"), AppI18n::text("长度")}, + {QStringLiteral("address"), AppI18n::text("设备地址")}, {QStringLiteral("command"), AppI18n::text("命令")}, + {QStringLiteral("payload"), AppI18n::text("载荷")}, {QStringLiteral("checksum"), AppI18n::text("校验")}, + {QStringLiteral("trailer"), AppI18n::text("帧尾")}}; + auto *resultsCard = new SimpleCardWidget(listPanel); + auto *resultsLayout = new QVBoxLayout(resultsCard); + resultsLayout->setContentsMargins(12, 12, 12, 12); + resultsLayout->setSpacing(8); + auto *resultsHeading = new QHBoxLayout; + resultsHeading->addWidget(new StrongBodyLabel(AppI18n::text("字段解析"), resultsCard)); + resultsHeading->addStretch(); + auto *positionHint = new CaptionLabel(AppI18n::text("拖动数据字段调整顺序与偏移"), resultsCard); + AppUi::setMutedTextColor(positionHint); + resultsHeading->addWidget(positionHint); + resultsLayout->addLayout(resultsHeading); + auto *fieldButtons = new QHBoxLayout; + fieldButtons->setSpacing(6); + fieldButtons->addWidget(new CaptionLabel(AppI18n::text("添加数据"), listPanel)); + const QList> types{{QStringLiteral("1 B"), AppPlot::BinaryType::UInt8}, + {QStringLiteral("2 B"), AppPlot::BinaryType::UInt16}, + {QStringLiteral("4 B"), AppPlot::BinaryType::UInt32}, + {QStringLiteral("8 B"), AppPlot::BinaryType::UInt64}, + {QStringLiteral("Float32"), AppPlot::BinaryType::Float32}, + {QStringLiteral("Float64"), AppPlot::BinaryType::Float64}}; + for (int i = 0; i < types.size(); ++i) { + const auto entry = types.at(i); + auto *button = new PushButton(entry.first, listPanel); + button->setFixedHeight(32); + button->setObjectName(i == 0 ? QStringLiteral("protocolPayloadAddField") + : QStringLiteral("protocolPayloadAdd-") + AppPlot::binaryTypeKey(entry.second)); + button->setAccessibleName(AppI18n::text("添加 %1 字段").arg(entry.first)); + fieldButtons->addWidget(button); + m_addFieldButtons.append(button); + connect(button, &PushButton::clicked, this, [this, type = entry.second]() { m_payloadEditor->addField(type); }); + } + fieldButtons->addSpacing(6); + m_removeFieldButton = new PushButton(AppI18n::text("删除字段"), listPanel); + m_removeFieldButton->setObjectName(QStringLiteral("protocolPayloadRemoveField")); + fieldButtons->addWidget(m_removeFieldButton); + fieldButtons->addStretch(); + resultsLayout->addLayout(fieldButtons); + auto *resultModel = new FieldResultModel(this); + resultModel->moveField = [this](int field, int before) { return m_payloadEditor->moveFieldBefore(field, before); }; + m_resultModel = resultModel; + m_resultModel->setHorizontalHeaderLabels({AppI18n::text("字段"), AppI18n::text("类型"), AppI18n::text("整帧字节"), + QStringLiteral("HEX"), AppI18n::text("解析值"), AppI18n::text("状态")}); + m_resultTable = new FieldResultTable(listPanel); m_resultTable->setObjectName(QStringLiteral("protocolTemplateResultsTable")); m_resultTable->setModel(m_resultModel); m_resultTable->setEditTriggers(QAbstractItemView::NoEditTriggers); m_resultTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_resultTable->setSelectionMode(QAbstractItemView::SingleSelection); + m_resultTable->setDragDropMode(QAbstractItemView::InternalMove); + m_resultTable->setDragDropOverwriteMode(false); + m_resultTable->setDefaultDropAction(Qt::MoveAction); m_resultTable->setAlternatingRowColors(true); m_resultTable->setWordWrap(false); + m_resultTable->setIconSize(QSize(12, 12)); m_resultTable->verticalHeader()->hide(); - m_resultTable->verticalHeader()->setDefaultSectionSize(34); - m_resultTable->horizontalHeader()->setMinimumSectionSize(80); - m_resultTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed); - m_resultTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed); - m_resultTable->setColumnWidth(0, 80); - m_resultTable->setColumnWidth(1, 80); - m_resultTable->horizontalHeader()->setStretchLastSection(true); - m_resultTable->setMinimumHeight(200); - previewLayout->addWidget(m_resultTable, 1); - - splitter->addWidget(editorScroll); - splitter->addWidget(preview); - splitter->setSizes({370, 690}); - splitter->setStretchFactor(0, 0); - splitter->setStretchFactor(1, 1); - root->addWidget(splitter, 1); + m_resultTable->verticalHeader()->setDefaultSectionSize(32); + m_resultTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); + m_resultTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter); + m_resultTable->horizontalHeader()->setStyleSheet( + QStringLiteral("QHeaderView::section { padding-left:16px; padding-right:16px; }")); + m_resultTable->viewport()->installEventFilter(this); + resultsLayout->addWidget(m_resultTable, 1); + listLayout->addWidget(resultsCard, 1); + auto *configurationPanel = new QWidget(splitter); + configurationPanel->setObjectName(QStringLiteral("protocolTemplateConfiguration")); + configurationPanel->setMinimumWidth(330); + configurationPanel->setMaximumWidth(420); + auto *configurationLayout = new QVBoxLayout(configurationPanel); + configurationLayout->setContentsMargins(0, 0, 0, 0); + configurationLayout->setSpacing(10); + auto *metadata = editor->findChild(QStringLiteral("protocolGroup-metadata")); + if (metadata) { + editor->layout()->removeWidget(metadata); + metadata->setParent(configurationPanel); + configurationLayout->addWidget(metadata); + } if (auto *actionBar = editor->findChild(QStringLiteral("protocolTemplateActionBar"))) { - if (editor->layout()) { - editor->layout()->removeWidget(actionBar); - } - root->addWidget(actionBar); + editor->layout()->removeWidget(actionBar); + if (metadata) + metadata->layout()->addWidget(actionBar); + else + configurationLayout->addWidget(actionBar); } - - connect(m_sampleEdit, &QPlainTextEdit::textChanged, this, &ProtocolTemplateWindow::updatePreview); - connect(exampleButton, &PushButton::clicked, this, &ProtocolTemplateWindow::useExampleFrame); + auto *inspectorCard = new SimpleCardWidget(configurationPanel); + auto *inspectorLayout = new QVBoxLayout(inspectorCard); + inspectorLayout->setContentsMargins(12, 12, 12, 12); + inspectorLayout->setSpacing(12); + m_sectionCombo = new ComboBox(inspectorCard); + m_sectionCombo->setObjectName(QStringLiteral("protocolTemplateSectionCombo")); + m_sectionCombo->setAccessibleName(AppI18n::text("字段")); + for (const auto &entry : frameKinds) + m_sectionCombo->addItem(entry.second, QIcon(), entry.first); + m_sectionCombo->addItem(AppI18n::text("数据字段"), QIcon(), QStringLiteral("field")); + inspectorLayout->addWidget(m_sectionCombo); + m_inspector = new QStackedWidget(inspectorCard); + m_editorScroll = new SingleDirectionScrollArea(Qt::Vertical, m_inspector); + m_editorScroll->setObjectName(QStringLiteral("protocolTemplateEditorScroll")); + m_editorScroll->enableTransparentBackground(); + m_editorScroll->setWidgetResizable(true); + m_editorScroll->setWidget(editor); + for (const QString &kind : {QStringLiteral("header"), QStringLiteral("length"), QStringLiteral("command"), + QStringLiteral("payload"), QStringLiteral("checksum"), QStringLiteral("trailer")}) { + if (auto *group = editor->findChild(QStringLiteral("protocolGroup-") + kind)) + m_frameGroups.insert(kind, group); + } + m_inspector->addWidget(m_editorScroll); + auto *payloadScroll = new SingleDirectionScrollArea(Qt::Vertical, m_inspector); + payloadScroll->enableTransparentBackground(); + payloadScroll->setWidgetResizable(true); + if (!m_payloadEditor) + m_payloadEditor = new ProtocolPayloadEditor; + payloadScroll->setWidget(m_payloadEditor); + m_inspector->addWidget(payloadScroll); + inspectorLayout->addWidget(m_inspector); + configurationLayout->addWidget(inspectorCard, 1); + splitter->addWidget(listPanel); + splitter->addWidget(configurationPanel); + splitter->setStretchFactor(0, 1); + splitter->setStretchFactor(1, 0); + splitter->setSizes({790, 350}); + root->addWidget(splitter, 1); + connect(m_sectionCombo, &ComboBox::currentIndexChanged, this, [this](int index) { + const QString kind = m_sectionCombo->itemData(index).toString(); + selectSection(kind, kind == QLatin1String("field") ? m_payloadEditor->selectedField() : -1); + }); + connect(m_removeFieldButton, &PushButton::clicked, m_payloadEditor, &ProtocolPayloadEditor::removeField); + connect(m_sampleEdit, &QPlainTextEdit::textChanged, this, [this]() { + m_generatedSample = m_sampleEdit->toPlainText().trimmed().isEmpty(); + updatePreview(); + }); connect(m_lastFrameButton, &PushButton::clicked, this, [this]() { - if (m_lastFrame.isEmpty()) { - return; - } - setSampleHex(bytesToHex(m_lastFrame)); + if (!m_lastFrame.isEmpty()) + setSampleHex(bytesToHex(m_lastFrame)); + }); + connect(m_payloadEditor, &ProtocolPayloadEditor::fieldSelected, this, [this](int field) { + selectSection(field >= 0 ? QStringLiteral("field") : QStringLiteral("header"), field); + }); + if (m_internalPayloadEditor) + connect(m_payloadEditor, &ProtocolPayloadEditor::changed, this, [this]() { + m_payloadEditor->applyTo(m_protocolTemplate); + refreshGeneratedSample(); + updatePreview(); + }); + connect(m_resultTable->selectionModel(), &QItemSelectionModel::currentRowChanged, this, + [this](const QModelIndex &index) { + if (!m_refreshing && index.isValid()) { + const auto key = m_resultModel->index(index.row(), 0); + selectSection(key.data(Qt::UserRole).toString(), key.data(Qt::UserRole + 1).toInt()); + } + }); + connect(m_structureView, &TextBrowser::anchorClicked, this, [this](const QUrl &url) { + if (url.scheme() == QLatin1String("field")) + selectSection(QStringLiteral("field"), url.path().toInt()); + else if (url.scheme() == QLatin1String("section")) + selectSection(url.path()); + }); + connect(ThemeManager::instance(), &ThemeManager::themeChangedFinished, this, [this]() { + if (isVisible() && !isMinimized()) + updatePreview(); }); m_protocolTemplate = AppProtocol::defaultTemplate(); - useExampleFrame(); + generateMatchingSample(); + updateInspector(); } void ProtocolTemplateWindow::setProtocolTemplate(const AppProtocol::ProtocolTemplate &protocolTemplate) { + const bool changedName = m_protocolTemplate.name != protocolTemplate.name; m_protocolTemplate = protocolTemplate; + if (m_internalPayloadEditor) + m_payloadEditor->setProtocolTemplate(protocolTemplate); + m_payloadEditor->setPayloadOffset(protocolTemplate.payloadOffset); + if (changedName && !isVisible()) { + m_selectedKind = protocolTemplate.payloadFields.isEmpty() ? QStringLiteral("header") : QStringLiteral("field"); + m_selectedField = protocolTemplate.payloadFields.isEmpty() ? -1 : 0; + updateInspector(); + } else if (m_selectedKind == QLatin1String("field") && m_selectedField >= protocolTemplate.payloadFields.size()) { + m_selectedKind = protocolTemplate.payloadFields.isEmpty() ? QStringLiteral("header") : QStringLiteral("field"); + m_selectedField = + protocolTemplate.payloadFields.isEmpty() ? -1 : int(protocolTemplate.payloadFields.size()) - 1; + updateInspector(); + } m_templateTitle->setText(AppI18n::text("协议结构与样例解析") + QStringLiteral(" · ") + protocolTemplate.name); - if (isVisible() && !isMinimized()) { + if (isVisible() && !isMinimized()) updatePreview(); - } } - void ProtocolTemplateWindow::setConfigurationError(const QString &error) { - if (m_configurationError == error) { + if (m_configurationError == error) return; - } m_configurationError = error; - if (isVisible() && !isMinimized()) { + if (isVisible() && !isMinimized()) updatePreview(); - } } - void ProtocolTemplateWindow::setSampleHex(const QString &hex) { + m_generatedSample = hex.trimmed().isEmpty(); const QSignalBlocker blocker(m_sampleEdit); m_sampleEdit->setPlainText(hex); - if (isVisible() && !isMinimized()) { + if (isVisible() && !isMinimized()) updatePreview(); - } } - QString ProtocolTemplateWindow::sampleHex() const { return m_sampleEdit->toPlainText(); } - void ProtocolTemplateWindow::setLastFrame(const QByteArray &frame) { - // The sample changes only on request, so it stays put while a template is edited. m_lastFrame = frame; m_lastFrameButton->setEnabled(!frame.isEmpty()); } - void ProtocolTemplateWindow::showEvent(QShowEvent *event) { QWidget::showEvent(event); updatePreview(); + updateResultColumnWidths(); } - -void ProtocolTemplateWindow::useExampleFrame() +bool ProtocolTemplateWindow::eventFilter(QObject *watched, QEvent *event) { - // The documented frame fits the default layout; other layouts get a frame - // built for them. - QByteArray frame = QByteArray::fromHex("AA5503100102034D6E"); - const AppProtocol::ParseResult parsed = AppProtocol::parseFrame(frame, m_protocolTemplate); - if (!parsed.ok || (parsed.checksumChecked && !parsed.checksumValid)) { - frame = AppProtocol::exampleFrame(m_protocolTemplate); + if (event->type() == QEvent::Resize) { + const auto *resize = static_cast(event); + if (resize->size().width() != resize->oldSize().width()) { + if (m_resultTable && watched == m_resultTable->viewport()) + updateResultColumnWidths(); + else if (watched == m_structureView->viewport() && m_resultTable) + updatePreview(); + } } + return QWidget::eventFilter(watched, event); +} +void ProtocolTemplateWindow::updateResultColumnWidths() +{ + QFont hexFont = AppFontPreferences::inputMonospaceFont(); + hexFont.setPixelSize(13); + const QFontMetrics hexMetrics(hexFont); + const QFontMetrics headerMetrics(m_resultTable->horizontalHeader()->font()); + QList widths{132, 64, 84, hexMetrics.horizontalAdvance(QStringLiteral("00 00 00 00 00 00 00 00")) + 36, + 104, 80}; + for (int row = 0; row < m_resultModel->rowCount(); ++row) + widths[5] = + qMax(widths[5], + m_resultTable->fontMetrics().horizontalAdvance(m_resultModel->index(row, 5).data().toString()) + 48); + int total = 0; + for (int column = 0; column < widths.size(); ++column) { + widths[column] = + qMax(widths[column], + headerMetrics.horizontalAdvance(m_resultModel->headerData(column, Qt::Horizontal).toString()) + 32); + total += widths[column]; + } + // Share extra room between the information columns instead of stretching only the field name. + const int extra = qMax(0, m_resultTable->viewport()->width() - total); + widths[0] += extra * 3 / 10; + widths[3] += extra * 4 / 10; + widths[4] += extra - extra * 3 / 10 - extra * 4 / 10; + for (int column = 0; column < widths.size(); ++column) + m_resultTable->setColumnWidth(column, widths[column]); +} +void ProtocolTemplateWindow::generateMatchingSample() +{ + m_generatedSample = true; + const auto frame = AppProtocol::exampleFrame(m_protocolTemplate); const QSignalBlocker blocker(m_sampleEdit); m_sampleEdit->setPlainText(bytesToHex(frame)); updatePreview(); } +void ProtocolTemplateWindow::refreshGeneratedSample() +{ + if (m_generatedSample) + generateMatchingSample(); +} +void ProtocolTemplateWindow::selectSection(const QString &kind, int field) +{ + if (m_refreshing) + return; + m_selectedKind = kind; + m_selectedField = field; + updateInspector(); + updatePreview(); +} +void ProtocolTemplateWindow::updateInspector() +{ + const QSignalBlocker blocker(m_payloadEditor); + const QSignalBlocker sectionBlocker(m_sectionCombo); + m_sectionCombo->setCurrentIndex(m_sectionCombo->findData(m_selectedKind)); + if (m_selectedKind == QLatin1String("field") || m_selectedKind == QLatin1String("address")) { + m_inspector->setCurrentIndex(1); + if (m_selectedKind == QLatin1String("address")) + m_payloadEditor->setAddressEditing(true); + else + m_payloadEditor->selectPayloadField(m_selectedField); + } else { + for (auto it = m_frameGroups.begin(); it != m_frameGroups.end(); ++it) + it.value()->setVisible(it.key() == m_selectedKind); + m_inspector->setCurrentWidget(m_editorScroll); + } + m_removeFieldButton->setEnabled(m_selectedKind == QLatin1String("field") && m_selectedField >= 0); +} void ProtocolTemplateWindow::updatePreview() { - m_validationLabel->setText(m_configurationError.isEmpty() ? AppI18n::text("配置有效") : m_configurationError); - m_validationLabel->setTextColor(m_configurationError.isEmpty() ? QColor(33, 117, 66) : QColor(180, 62, 35), - m_configurationError.isEmpty() ? QColor(128, 217, 162) : QColor(255, 150, 126)); - m_resultModel->removeRows(0, m_resultModel->rowCount()); - const HexParseResult sample = parseHexPayload(m_sampleEdit->toPlainText()); - if (!sample.ok || !m_configurationError.isEmpty()) { - const QString error = !m_configurationError.isEmpty() - ? m_configurationError - : AppI18n::text("样例 HEX 无效:%1,位置 %2") - .arg(sample.errorMessage) - .arg(sample.errorOffset + 1); + if (m_refreshing) + return; + m_refreshing = true; + for (auto *button : m_addFieldButtons) + button->setEnabled(m_protocolTemplate.payloadFields.size() < AppPlot::MaximumChannels); + const auto sample = parseHexPayload(m_sampleEdit->toPlainText()); + const QString configurationError = m_configurationError.isEmpty() + ? AppProtocol::payloadConfigurationError(m_protocolTemplate) + : m_configurationError; + m_createPlotButton->setEnabled(configurationError.isEmpty() && !m_protocolTemplate.payloadFields.isEmpty()); + if (!sample.ok || !configurationError.isEmpty()) { + m_resultModel->setRowCount(0); + const QString error = + !configurationError.isEmpty() + ? configurationError + : AppI18n::text("样例 HEX 无效:%1,位置 %2").arg(sample.errorMessage).arg(sample.errorOffset + 1); + m_validationLabel->setText(error); + m_validationLabel->setTextColor(QColor(180, 62, 35), QColor(255, 150, 126)); m_parseStatusLabel->setText(error); - m_parseStatusLabel->setTextColor(QColor(180, 62, 35), QColor(255, 150, 126)); m_structureView->clear(); + m_structureView->setFixedHeight(88); + m_refreshing = false; return; } - const QByteArray frame = sample.bytes; - const AppProtocol::ParseResult result = AppProtocol::parseFrame(frame, m_protocolTemplate); + const auto result = AppProtocol::parseFrame(frame, m_protocolTemplate); + const auto layout = AppProtocol::frameLayout(frame, m_protocolTemplate); const int checksumSize = AppProtocol::checksumSize(m_protocolTemplate); - // Highlight the areas even when the frame does not parse. - const AppProtocol::FrameLayout layout = AppProtocol::frameLayout(frame, m_protocolTemplate); - const qint64 expectedFrameLength = layout.frameLength; - const qint64 checksumOffset = qMax(0, layout.checksumOffset); - const qint64 trailerOffset = qMax(0, layout.trailerOffset); - const int trailerSize = int(m_protocolTemplate.trailer.size()); - const qint64 payloadLength = qMax(0, layout.payloadLength); - - QString html = QStringLiteral(""); - const int visibleBytes = int(qMin(frame.size(), 1024)); - for (int i = 0; i < visibleBytes; ++i) { - if (i % 12 == 0) { - html += QStringLiteral(""); - } - int areaIndex = 6; - if (trailerSize > 0 && i >= trailerOffset && i < expectedFrameLength) { - areaIndex = 5; - } else if (checksumSize > 0 && i >= checksumOffset && i < checksumOffset + checksumSize) { - areaIndex = 4; - } else if (i < m_protocolTemplate.header.size()) { - areaIndex = 0; - } else if (m_protocolTemplate.lengthSize > 0 && i >= m_protocolTemplate.lengthOffset && - i < m_protocolTemplate.lengthOffset + m_protocolTemplate.lengthSize) { - areaIndex = 1; - } else if (i >= m_protocolTemplate.commandOffset && - i < m_protocolTemplate.commandOffset + m_protocolTemplate.commandSize) { - areaIndex = 2; - } else if (i >= m_protocolTemplate.payloadOffset && i < m_protocolTemplate.payloadOffset + payloadLength) { - areaIndex = 3; + const bool valid = result.ok && (!result.checksumChecked || result.checksumValid); + const qint64 required = AppProtocol::requiredPayloadBytes(m_protocolTemplate); + const bool fieldsFit = result.ok && result.payload.size() >= required; + QString validation; + if (!valid) + validation = result.ok ? AppI18n::text("样例校验失败,请检查校验设置或重新生成样例。") : result.errorMessage; + else if (!fieldsFit) + validation = + AppI18n::text("样例载荷不足:当前 %1 B,数据字段至少需要 %2 B。").arg(result.payload.size()).arg(required); + else + validation = AppI18n::text("样例解析通过 · %1 B 载荷 · %2 个数据字段") + .arg(result.payload.size()) + .arg(m_protocolTemplate.payloadFields.size()); + m_validationLabel->setText(validation); + m_validationLabel->setTextColor(valid && fieldsFit ? QColor(33, 117, 66) : QColor(180, 62, 35), + valid && fieldsFit ? QColor(128, 217, 162) : QColor(255, 150, 126)); + m_parseStatusLabel->setText(result.ok + ? AppI18n::text("整帧 %1 B · 载荷从字节 %2 开始 · %3") + .arg(result.frameLength) + .arg(m_protocolTemplate.payloadOffset) + .arg(result.checksumChecked ? result.checksumValid ? AppI18n::text("校验正确") + : AppI18n::text("校验错误") + : AppI18n::text("无校验")) + : result.errorMessage); + const auto samples = + valid ? AppPlot::extractSamples(AppProtocol::payloadParserConfig(m_protocolTemplate), {}, frame, result.payload) + : QVector(); + const auto values = samples.isEmpty() ? AppPlot::PlotSample() : samples.first(); + QVector rows; + const auto rawBytes = [&frame](int offset, int count) { + return offset >= 0 && offset < frame.size() ? bytesToHex(frame.mid(offset, qMax(0, count))) : QString(); + }; + const auto addFrameRow = [&](const QString &kind, const QString &name, int offset, int size, const QString &value) { + if (size <= 0) + return; + FieldRow row; + row.kind = kind; + row.name = name; + row.type = QStringLiteral("%1 B").arg(size); + row.offset = offset; + row.size = size; + row.raw = rawBytes(offset, size); + row.value = value; + row.warning = offset < 0 || offset > frame.size() - size; + row.status = row.warning ? AppI18n::text("样例不足") : AppI18n::text("已识别"); + if ((kind == QLatin1String("header") && !frame.startsWith(m_protocolTemplate.header)) || + (kind == QLatin1String("trailer") && !row.warning && + frame.mid(offset, size) != m_protocolTemplate.trailer)) { + row.warning = true; + row.status = AppI18n::text("不匹配"); } - const FrameArea &area = frameAreas().at(areaIndex); - const QString byteText = - QStringLiteral("%1").arg(static_cast(frame.at(i)), 2, 16, QLatin1Char('0')).toUpper(); - html += QStringLiteral("") - .arg(area.background, area.color, - byteText, QString::number(i)); - if (i % 12 == 11 || i + 1 == visibleBytes) { - html += QStringLiteral(""); + rows.append(row); + }; + addFrameRow(QStringLiteral("header"), AppI18n::text("帧头"), 0, m_protocolTemplate.header.size(), + AppI18n::text("固定字节")); + addFrameRow(QStringLiteral("length"), AppI18n::text("长度"), m_protocolTemplate.lengthOffset, + m_protocolTemplate.lengthSize, QString::number(layout.lengthValue)); + addFrameRow(QStringLiteral("address"), AppI18n::text("设备地址"), m_protocolTemplate.addressOffset, + m_protocolTemplate.addressSize, + rawBytes(m_protocolTemplate.addressOffset, m_protocolTemplate.addressSize)); + addFrameRow(QStringLiteral("command"), AppI18n::text("命令"), m_protocolTemplate.commandOffset, + m_protocolTemplate.commandSize, bytesToHex(result.command)); + if (m_protocolTemplate.payloadFields.isEmpty()) + addFrameRow(QStringLiteral("payload"), AppI18n::text("载荷"), m_protocolTemplate.payloadOffset, + int(qMax(0, layout.payloadLength)), bytesToHex(result.payload)); + for (int index = 0; index < m_protocolTemplate.payloadFields.size(); ++index) { + const auto &field = m_protocolTemplate.payloadFields.at(index); + FieldRow row; + row.kind = QStringLiteral("field"); + row.field = index; + row.name = field.name; + row.type = AppPlot::binaryTypeKey(field.type); + row.offset = m_protocolTemplate.payloadOffset + field.byteOffset; + row.size = AppPlot::binaryTypeSize(field.type); + const int available = qMax(0, qMin(row.size, int(result.payload.size()) - field.byteOffset)); + row.raw = bytesToHex(result.payload.mid(field.byteOffset, available)); + const auto value = + std::find_if(values.cbegin(), values.cend(), [&field](const auto &v) { return v.name == field.name; }); + if (!valid) { + row.value = AppI18n::text("无法解析"); + row.status = AppI18n::text("帧无效"); + row.warning = true; + } else if (available < row.size) { + row.value = AppI18n::text("无法解析"); + row.status = AppI18n::text("缺少 %1 B").arg(row.size - available); + row.warning = true; + } else if (value == values.cend() || !std::isfinite(value->value)) { + row.value = AppI18n::text("无法解析"); + row.status = AppI18n::text("数值无效"); + row.warning = true; + } else { + row.value = QString::number(value->value, 'g', 12); + row.status = AppI18n::text("已解析"); } + rows.append(row); } - html += QStringLiteral("
" - "%3
%4
"); - if (frame.size() > visibleBytes) { - html += AppI18n::text("仅显示前 %1 B;解析使用完整样例。 ").arg(visibleBytes).toHtmlEscaped(); + addFrameRow(QStringLiteral("checksum"), AppI18n::text("校验"), int(qMax(0, layout.checksumOffset)), + checksumSize, + result.checksumChecked ? result.checksumValid ? AppI18n::text("正确") : AppI18n::text("错误") + : AppI18n::text("无法解析")); + if (checksumSize > 0 && result.checksumChecked && valid) + rows.last().status = AppI18n::text("已校验"); + if (checksumSize > 0 && !rows.isEmpty() && rows.last().kind == QLatin1String("checksum") && !valid) { + rows.last().warning = true; + rows.last().status = result.checksumChecked ? AppI18n::text("校验错误") : AppI18n::text("无法校验"); } - m_structureView->setHtml(html); - - const bool valid = result.ok && (!result.checksumChecked || result.checksumValid); - m_parseStatusLabel->setText(result.ok ? result.summary : result.errorMessage); - m_parseStatusLabel->setTextColor(valid ? QColor(33, 117, 66) : QColor(180, 62, 35), - valid ? QColor(128, 217, 162) : QColor(255, 150, 126)); - const auto addRow = [this](const QString &field, const QString &position, const QString &value) { - m_resultModel->appendRow({new QStandardItem(field), new QStandardItem(position), new QStandardItem(value)}); - }; - addRow(AppI18n::text("帧头"), byteRange(0, m_protocolTemplate.header.size()), - bytesToHex(frame.left(m_protocolTemplate.header.size()))); - addRow(AppI18n::text("长度"), byteRange(m_protocolTemplate.lengthOffset, m_protocolTemplate.lengthSize), - m_protocolTemplate.lengthSize > 0 - ? QString::number(layout.lengthValue) + QStringLiteral(" · ") + - AppProtocol::lengthModeLabel(m_protocolTemplate.lengthMode) - : AppI18n::text("无长度字段")); - addRow(AppI18n::text("命令"), byteRange(m_protocolTemplate.commandOffset, m_protocolTemplate.commandSize), - bytesToHex(result.command)); - addRow(AppI18n::text("载荷"), - byteRange(m_protocolTemplate.payloadOffset, int(qMin(payloadLength, 1024 * 1024))), - bytesToHex(result.payload)); - if (checksumSize > 0) { - QString checksumValue = bytesToHex(result.checksum); - if (result.checksumChecked) { - const int checksumStart = m_protocolTemplate.checksumStart; - const AppChecksum::ChecksumResult expected = - AppChecksum::calculate(frame.mid(checksumStart, int(checksumOffset) - checksumStart), - m_protocolTemplate.checksumAlgorithm, m_protocolTemplate.checksumByteOrder); - checksumValue += QStringLiteral(" · ") + (result.checksumValid ? AppI18n::text("正确") : AppI18n::text("错误")); - if (expected.ok) { - checksumValue += QStringLiteral(" · ") + AppI18n::text("预期 %1").arg(bytesToHex(expected.bytes)); + if (checksumSize > 0 && result.checksumChecked && !rows.isEmpty()) { + const int start = m_protocolTemplate.checksumStart; + const int end = int(layout.checksumOffset); + const auto checksum = AppChecksum::calculate( + frame.mid(start, end - start), m_protocolTemplate.checksumAlgorithm, m_protocolTemplate.checksumByteOrder); + rows.last().details = AppI18n::text("预期 %1").arg(bytesToHex(checksum.bytes)) + QStringLiteral(" · ") + + AppI18n::text("覆盖 %1").arg(byteRange(start, end - start)); + } + addFrameRow(QStringLiteral("trailer"), AppI18n::text("帧尾"), int(qMax(0, layout.trailerOffset)), + m_protocolTemplate.trailer.size(), AppI18n::text("固定字节")); + std::stable_sort(rows.begin(), rows.end(), [](const auto &a, const auto &b) { return a.offset < b.offset; }); + // Keep indexes and accessibility cells alive while selection callbacks run. + // Rebuilding the model here can invalidate a native selection query in progress. + m_resultModel->setRowCount(rows.size()); + int selectedRow = -1; + for (int index = 0; index < rows.size(); ++index) { + const auto &row = rows.at(index); + QList items; + const QStringList texts{row.name, row.type, byteRange(row.offset, row.size), row.raw, row.value, row.status}; + for (int column = 0; column < texts.size(); ++column) { + auto *item = m_resultModel->item(index, column); + if (!item) { + item = new QStandardItem; + m_resultModel->setItem(index, column, item); } - const QString coverage = byteRange(checksumStart, int(checksumOffset) - checksumStart); - checksumValue += QStringLiteral(" · ") + AppI18n::text("覆盖 %1").arg(coverage); + item->setText(texts.at(column)); + item->setToolTip(texts.at(column)); + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | + (row.kind == QLatin1String("field") ? Qt::ItemIsDragEnabled : Qt::NoItemFlags)); + item->setData(QVariant(), Qt::ForegroundRole); + if (column == 2 || column == 3) { + QFont font = AppFontPreferences::inputMonospaceFont(); + font.setPixelSize(13); + item->setFont(font); + } + items.append(item); } - addRow(AppI18n::text("校验"), byteRange(int(qMin(checksumOffset, 1024 * 1024)), checksumSize), - checksumValue); - } else { - addRow(AppI18n::text("校验"), QStringLiteral("—"), AppI18n::text("无校验")); + items.first()->setData(row.kind, Qt::UserRole); + items.first()->setData(row.field, Qt::UserRole + 1); + const QColor color(rowColor(row.kind, row.field)); + QPixmap swatch(12, 12); + swatch.fill(color); + if (row.kind == QLatin1String("field")) { + QPainter painter(&swatch); + painter.setPen(Qt::NoPen); + painter.setBrush(QColor(QStringLiteral("#617d80"))); + for (int y : {2, 5, 8}) + for (int x : {3, 7}) + painter.drawEllipse(QRect(x, y, 2, 2)); + } + items.first()->setIcon(QIcon(swatch)); + items.at(3)->setBackground(color); + items.at(3)->setForeground(QColor(QStringLiteral("#243740"))); + if (!row.details.isEmpty()) + items.at(4)->setToolTip(row.value + QLatin1Char('\n') + row.details); + if (row.warning) + items.last()->setForeground(FluentQt::ThemeManager::instance()->effectiveTheme() == FluentQt::Theme::Dark + ? QColor(255, 150, 126) + : QColor(180, 62, 35)); + if (row.kind == m_selectedKind && (row.kind != QLatin1String("field") || row.field == m_selectedField)) + selectedRow = index; } - if (trailerSize > 0) { - addRow(AppI18n::text("帧尾"), byteRange(int(qMin(trailerOffset, 1024 * 1024)), trailerSize), - bytesToHex(frame.mid(int(qMin(trailerOffset, frame.size())), trailerSize))); - } else { - addRow(AppI18n::text("帧尾"), QStringLiteral("—"), AppI18n::text("无帧尾")); + if (selectedRow >= 0 && (m_resultTable->currentIndex().row() != selectedRow || + !m_resultTable->selectionModel()->isRowSelected(selectedRow))) + m_resultTable->selectRow(selectedRow); + else if (selectedRow < 0) + m_resultTable->setCurrentIndex(QModelIndex()); + const auto ownerAt = [&rows, &layout](int byte) { + const FieldRow *owner = nullptr; + for (const auto &row : rows) + if (byte >= row.offset && byte < row.offset + row.size) { + if (row.kind == QLatin1String("field") && byte >= layout.checksumOffset) + continue; + if (!owner || row.kind == QLatin1String("field") || row.kind == QLatin1String("address")) + owner = &row; + } + return owner; + }; + const auto targetFor = [](const FieldRow *owner) { + return owner ? owner->kind == QLatin1String("field") ? QStringLiteral("field:%1").arg(owner->field) + : QStringLiteral("section:") + owner->kind + : QStringLiteral("section:payload"); + }; + const int cellWidth = qMax(56, m_structureView->fontMetrics().horizontalAdvance(QStringLiteral("000")) + 16); + const int availableWidth = qMax(cellWidth, m_structureView->viewport()->width() - 16); + const int columns = qBound(8, availableWidth / (cellWidth + 3), 32); + QFont labelFont = font(); + labelFont.setPixelSize(12); + const QFontMetrics labelMetrics(labelFont); + const int visibleBytes = qMin(frame.size(), 1024); + QString html = QStringLiteral("") + .arg(qMin(columns, visibleBytes) * (cellWidth + 3)); + for (int start = 0; start < visibleBytes; start += columns) { + const int end = qMin(start + columns, visibleBytes); + html += QStringLiteral(""); + for (int byte = start; byte < end;) { + const auto *owner = ownerAt(byte); + int next = byte + 1; + while (next < end && ownerAt(next) == owner) + ++next; + const auto label = owner ? owner->name : AppI18n::text("其他"); + const auto shortLabel = labelMetrics.elidedText(label, Qt::ElideRight, (next - byte) * cellWidth - 8); + html += QStringLiteral("") + .arg(next - byte) + .arg(owner ? rowColor(owner->kind, owner->field) : QStringLiteral("#eeeeee"), targetFor(owner), + label.toHtmlEscaped(), shortLabel.toHtmlEscaped(), labelFont.family().toHtmlEscaped()); + byte = next; + } + html += QStringLiteral(""); + for (int byte = start; byte < end; ++byte) { + const auto *owner = ownerAt(byte); + const bool selected = owner && owner->kind == m_selectedKind && + (owner->kind != QLatin1String("field") || owner->field == m_selectedField); + const auto byteText = + QStringLiteral("%1").arg(static_cast(frame.at(byte)), 2, 16, QLatin1Char('0')).toUpper(); + html += QStringLiteral( + "") + .arg(owner ? rowColor(owner->kind, owner->field) : QStringLiteral("#eeeeee")) + .arg(selected ? 2 : 0) + .arg(targetFor(owner), QString::number(byte), byteText) + .arg(cellWidth); + } + if (end - start < columns && start > 0) + html += QStringLiteral("").arg(columns - (end - start)); + html += QStringLiteral(""); } - addRow(AppI18n::text("整帧"), QStringLiteral("0–%1").arg(qMax(0, frame.size() - 1)), - AppI18n::text("当前 %1 B / 需要 %2 B").arg(frame.size()).arg(expectedFrameLength)); + html += QStringLiteral("
%5
%4
%5
"); + m_structureView->setHtml(html); + const int documentHeight = int(std::ceil(m_structureView->document()->size().height())); + const int viewportMargins = m_structureView->height() - m_structureView->viewport()->height(); + m_structureView->setFixedHeight(qBound(88, documentHeight + viewportMargins, 240)); + m_refreshing = false; } diff --git a/src/app/view/protocol_template_window.h b/src/app/view/protocol_template_window.h index 4c4506f..5e77f49 100644 --- a/src/app/view/protocol_template_window.h +++ b/src/app/view/protocol_template_window.h @@ -1,40 +1,46 @@ #pragma once - #include "app/core/protocol_template.h" - +#include #include - class QPlainTextEdit; class QStandardItemModel; - +class QStackedWidget; +class ProtocolPayloadEditor; namespace FluentQt { class BodyLabel; class CaptionLabel; +class ComboBox; class PushButton; class TableView; class TextBrowser; +class SingleDirectionScrollArea; } // namespace FluentQt - class ProtocolTemplateWindow : public QWidget { Q_OBJECT - public: - explicit ProtocolTemplateWindow(QWidget *editor, QWidget *parent = nullptr); - + explicit ProtocolTemplateWindow(QWidget *editor, QWidget *parent = nullptr, + ProtocolPayloadEditor *payloadEditor = nullptr); void setProtocolTemplate(const AppProtocol::ProtocolTemplate &protocolTemplate); void setConfigurationError(const QString &error); void setSampleHex(const QString &hex); QString sampleHex() const; void setLastFrame(const QByteArray &frame); + void generateMatchingSample(); + void refreshGeneratedSample(); + + signals: + void createPlotRequested(); protected: void showEvent(QShowEvent *event) override; + bool eventFilter(QObject *watched, QEvent *event) override; private: void updatePreview(); - void useExampleFrame(); - + void updateResultColumnWidths(); + void selectSection(const QString &kind, int field = -1); + void updateInspector(); AppProtocol::ProtocolTemplate m_protocolTemplate; QString m_configurationError; QByteArray m_lastFrame; @@ -46,4 +52,17 @@ class ProtocolTemplateWindow : public QWidget FluentQt::CaptionLabel *m_validationLabel = nullptr; FluentQt::CaptionLabel *m_parseStatusLabel = nullptr; FluentQt::PushButton *m_lastFrameButton = nullptr; + FluentQt::PushButton *m_removeFieldButton = nullptr; + FluentQt::PushButton *m_createPlotButton = nullptr; + FluentQt::ComboBox *m_sectionCombo = nullptr; + QList m_addFieldButtons; + ProtocolPayloadEditor *m_payloadEditor = nullptr; + FluentQt::SingleDirectionScrollArea *m_editorScroll = nullptr; + QStackedWidget *m_inspector = nullptr; + QHash m_frameGroups; + QString m_selectedKind = QStringLiteral("header"); + int m_selectedField = -1; + bool m_internalPayloadEditor = false; + bool m_refreshing = false; + bool m_generatedSample = true; }; diff --git a/src/app/view/quick_plot_window.cpp b/src/app/view/quick_plot_window.cpp index 3657932..2bafac6 100644 --- a/src/app/view/quick_plot_window.cpp +++ b/src/app/view/quick_plot_window.cpp @@ -6,6 +6,7 @@ #include #include "app/core/app_settings.h" +#include "app/core/hex_utils.h" #include "app/view/muted_text.h" #include #include @@ -25,6 +26,7 @@ #include #include +#include #include #include @@ -392,39 +394,48 @@ void QuickPlotWindow::rebuildPlot(int channel) } void QuickPlotWindow::appendRecord(const QDateTime ×tamp, const QString &text, const QByteArray &frame, - const AppProtocol::ParseResult *parsed) + bool stream) { if (!isPlottingActive() || m_paused) { return; } - QByteArray payload; if (requiresProtocolPayload()) { if (!m_hasProtocolTemplate) { return; } - const AppProtocol::ParseResult result = parsed ? *parsed : AppProtocol::parseFrame(frame, m_protocolTemplate); - if (!result.ok || (result.checksumChecked && !result.checksumValid)) { - return; + for (const auto &decoded : AppProtocol::takeFrames(m_frameBuffer, frame, m_protocolTemplate, stream)) { + appendParsedValues(timestamp, {}, decoded.bytes, decoded.parsed.payload); } - payload = result.payload; + } else { + appendParsedValues(timestamp, text, frame); } +} + +void QuickPlotWindow::appendParsedValues(const QDateTime ×tamp, const QString &text, const QByteArray &frame, + const QByteArray &payload) +{ // Without fields, binary data plots a channel per byte, up to the limit. if (m_parserConfig.protocol == AppPlot::Protocol::Binary && m_parserConfig.binaryFields.isEmpty()) { const QByteArray &data = m_parserConfig.binarySource == AppPlot::BinarySource::Payload ? payload : frame; m_channelsLimited = m_channelsLimited || data.size() > AppPlot::MaximumChannels; } - const QVector samples = AppPlot::extractSamples(m_parserConfig, text, frame, payload); - for (const AppPlot::PlotSample &values : samples) { + QString address; + if (requiresProtocolPayload() && m_protocolTemplate.addressSize > 0) { + if (m_protocolTemplate.addressOffset > frame.size() - m_protocolTemplate.addressSize) + return; + address = bytesToHex(frame.mid(m_protocolTemplate.addressOffset, m_protocolTemplate.addressSize)); + } + auto samples = AppPlot::extractSamples(m_parserConfig, text, frame, payload); + for (auto &values : samples) { + if (!address.isEmpty()) { + for (auto &value : values) + value.name = address + QStringLiteral(" / ") + value.name; + } appendValues(timestamp, values); } } -const AppProtocol::ProtocolTemplate *QuickPlotWindow::payloadTemplate() const -{ - return requiresProtocolPayload() && m_hasProtocolTemplate ? &m_protocolTemplate : nullptr; -} - bool QuickPlotWindow::isPlottingActive() const { return m_plottingActive; } bool QuickPlotWindow::isPaused() const { return m_paused; } @@ -456,6 +467,7 @@ void QuickPlotWindow::setPlottingActive(bool active) } m_plottingActive = active; if (!active) { + m_frameBuffer.clear(); m_channelValueTimer->stop(); updateChannelValues(); m_plot->setUpdatesEnabled(false); @@ -516,6 +528,7 @@ void QuickPlotWindow::appendValues(const QDateTime ×tamp, const AppPlot::Pl void QuickPlotWindow::clearData() { + m_frameBuffer.clear(); m_channelValueTimer->stop(); m_channelTable->setRowCount(0); m_rows.clear(); @@ -536,6 +549,8 @@ void QuickPlotWindow::clearData() updateStatus(); } +void QuickPlotWindow::resetStream() { m_frameBuffer.clear(); } + AppPlot::ParserConfig QuickPlotWindow::savedParserConfig() { AppSettings settings; @@ -560,6 +575,11 @@ bool QuickPlotWindow::configureParser(const AppPlot::ParserConfig &config) return false; } AppPlot::ParserConfig normalized = config; + m_followTemplateFields = config.protocol == AppPlot::Protocol::Binary && + config.binarySource == AppPlot::BinarySource::Payload && m_hasProtocolTemplate && + (m_followTemplateFields || !m_protocolTemplate.payloadFields.isEmpty()); + if (m_followTemplateFields) + normalized.binaryFields = m_protocolTemplate.payloadFields; for (QString &field : normalized.fields) { field = field.simplified(); } @@ -581,6 +601,17 @@ bool QuickPlotWindow::configureParser(const AppPlot::ParserConfig &config) void QuickPlotWindow::setProtocolTemplates(const QList &protocolTemplates) { + if (m_followTemplateFields) { + const auto matches = [this](const auto &item) { return item.name == m_protocolTemplate.name; }; + const auto previous = std::find_if(m_protocolTemplates.cbegin(), m_protocolTemplates.cend(), matches); + const auto updated = std::find_if(protocolTemplates.cbegin(), protocolTemplates.cend(), matches); + // A plot may use an unsaved draft. Only a change to its saved template + // should replace it; publishing another template must leave it alone. + if (updated != protocolTemplates.cend() && + (previous == m_protocolTemplates.cend() || !(*previous == *updated))) { + setProtocolTemplate(*updated); + } + } m_protocolTemplates = protocolTemplates; } @@ -589,10 +620,20 @@ void QuickPlotWindow::setProtocolTemplate(const AppProtocol::ProtocolTemplate &p if (m_hasProtocolTemplate && m_protocolTemplate == protocolTemplate) { return; } + m_followTemplateFields = !protocolTemplate.payloadFields.isEmpty() || + (m_followTemplateFields && m_protocolTemplate.name == protocolTemplate.name); m_protocolTemplate = protocolTemplate; m_hasProtocolTemplate = true; updateProtocolName(); if (requiresProtocolPayload()) { + if (m_followTemplateFields) { + m_parserConfig.binaryFields = m_protocolTemplate.payloadFields; + m_parserConfig.fields.removeIf([this](const QString &name) { + return std::none_of( + m_protocolTemplate.payloadFields.cbegin(), m_protocolTemplate.payloadFields.cend(), + [&name](const auto &field) { return field.name.compare(name, Qt::CaseInsensitive) == 0; }); + }); + } m_channelTransforms.clear(); clearData(); } @@ -696,6 +737,7 @@ void QuickPlotWindow::updateStatus() void QuickPlotWindow::setPaused(bool paused) { m_paused = paused; + m_frameBuffer.clear(); m_channelValueTimer->stop(); updateChannelValues(); if (m_pauseButton) { @@ -712,11 +754,14 @@ void QuickPlotWindow::showParserSettings() if (m_hasProtocolTemplate) { dialog.setProtocolTemplate(m_protocolTemplate); } - if (dialog.exec() == QDialog::Accepted) { - configureParser(dialog.parserConfig()); + const int result = dialog.exec(); + if (result == PlotParserDialog::EditTemplate) { + emit editTemplateRequested(dialog.protocolTemplate().name); + } else if (result == QDialog::Accepted) { if (dialog.usesProtocolTemplate()) { setProtocolTemplate(dialog.protocolTemplate()); } + configureParser(dialog.parserConfig()); } } diff --git a/src/app/view/quick_plot_window.h b/src/app/view/quick_plot_window.h index 25852dd..5ceeb94 100644 --- a/src/app/view/quick_plot_window.h +++ b/src/app/view/quick_plot_window.h @@ -33,14 +33,9 @@ class QuickPlotWindow : public QWidget // The parser configuration a window last applied, used to prefill new windows. static AppPlot::ParserConfig savedParserConfig(); - // parsed: the frame already parsed with payloadTemplate(), so windows that - // share a template parse each frame once. Without it the window parses. - void appendRecord(const QDateTime ×tamp, const QString &text, const QByteArray &frame, - const AppProtocol::ParseResult *parsed = nullptr); - // The template frames are parsed with before plotting, or nullptr when the - // window plots records as they are. - const AppProtocol::ProtocolTemplate *payloadTemplate() const; + void appendRecord(const QDateTime ×tamp, const QString &text, const QByteArray &frame, bool stream = false); void clearData(); + void resetStream(); bool configureParser(const AppPlot::ParserConfig &config); void setProtocolTemplates(const QList &protocolTemplates); void setProtocolTemplate(const AppProtocol::ProtocolTemplate &protocolTemplate); @@ -48,6 +43,9 @@ class QuickPlotWindow : public QWidget bool isPlottingActive() const; bool isPaused() const; + signals: + void editTemplateRequested(const QString &name); + protected: void showEvent(QShowEvent *event) override; void hideEvent(QHideEvent *event) override; @@ -69,6 +67,8 @@ class QuickPlotWindow : public QWidget }; void appendValues(const QDateTime ×tamp, const AppPlot::PlotSample &values); + void appendParsedValues(const QDateTime ×tamp, const QString &text, const QByteArray &frame, + const QByteArray &payload = {}); // The channel for a value, or -1 when it would exceed AppPlot::MaximumChannels. int channelIndexFor(const QString &name, int position); void ensureSeriesCount(int count); @@ -108,6 +108,7 @@ class QuickPlotWindow : public QWidget AppPlot::ParserConfig m_parserConfig; QList m_protocolTemplates; AppProtocol::ProtocolTemplate m_protocolTemplate; + QByteArray m_frameBuffer; int m_channelCount = 0; int m_nextSample = 0; int m_plotRefreshRate = 0; @@ -115,4 +116,5 @@ class QuickPlotWindow : public QWidget bool m_plottingActive = false; bool m_channelsLimited = false; bool m_hasProtocolTemplate = false; + bool m_followTemplateFields = false; }; diff --git a/src/app/view/workbench/workbench_page_plot.cpp b/src/app/view/workbench/workbench_page_plot.cpp index 12e9603..fc5f098 100644 --- a/src/app/view/workbench/workbench_page_plot.cpp +++ b/src/app/view/workbench/workbench_page_plot.cpp @@ -1,18 +1,26 @@ #include "app/view/workbench/workbench_page_internal.h" -#include "app/view/quick_plot_window.h" #include "app/view/plot_parser_dialog.h" - -#include -#include +#include "app/view/protocol_template_window.h" +#include "app/view/quick_plot_window.h" void WorkbenchPage::showQuickPlotWindow() { - // Start from the last applied configuration so field filters and binary - // fields carry over; the protocol itself still has to be chosen. - PlotParserDialog dialog(QuickPlotWindow::savedParserConfig(), window(), true); + const auto current = currentProtocolTemplateFromUi(); + const bool useCurrent = !current.payloadFields.isEmpty() && protocolTemplateInputError().isEmpty(); + PlotParserDialog dialog( + useCurrent ? AppProtocol::payloadParserConfig(current) : QuickPlotWindow::savedParserConfig(), window(), true); dialog.setProtocolTemplates(m_protocolTemplates); - if (dialog.exec() != QDialog::Accepted) { + if (useCurrent) { + dialog.useProtocolTemplate(current); + dialog.setSampleHex(m_protocolTemplateWindow->sampleHex()); + } + const int result = dialog.exec(); + if (result == PlotParserDialog::EditTemplate) { + editProtocolTemplate(dialog.protocolTemplate().name); + return; + } + if (result != QDialog::Accepted) { return; } @@ -45,6 +53,7 @@ QuickPlotWindow *WorkbenchPage::createQuickPlotWindow(const AppPlot::ParserConfi plotWindow->setWindowTitle(AppI18n::text("曲线 %1").arg(m_nextPlotWindowNumber++)); m_quickPlotWindows.append(plotWindow); m_quickPlotWindow = plotWindow; + connect(plotWindow, &QuickPlotWindow::editTemplateRequested, this, &WorkbenchPage::editProtocolTemplate); connect(plotWindow, &QObject::destroyed, this, [this, plotWindow]() { m_quickPlotWindows.removeAll(plotWindow); if (m_quickPlotWindow == plotWindow) { @@ -62,24 +71,10 @@ void WorkbenchPage::appendQuickPlotRecord(const SessionRecord &record) if (record.direction != RecordDirection::Rx) { return; } - // Windows often share a template, so parse the frame once per template. - QList> parsedFrames; for (QuickPlotWindow *plotWindow : m_quickPlotWindows) { if (!plotWindow->isPlottingActive() || plotWindow->isPaused()) { continue; } - const AppProtocol::ProtocolTemplate *protocolTemplate = plotWindow->payloadTemplate(); - if (!protocolTemplate) { - plotWindow->appendRecord(record.timestamp, record.terminalText, record.bytes); - continue; - } - auto parsed = std::find_if(parsedFrames.cbegin(), parsedFrames.cend(), [protocolTemplate](const auto &entry) { - return *entry.first == *protocolTemplate; - }); - if (parsed == parsedFrames.cend()) { - parsedFrames.append({protocolTemplate, AppProtocol::parseFrame(record.bytes, *protocolTemplate)}); - parsed = std::prev(parsedFrames.cend()); - } - plotWindow->appendRecord(record.timestamp, record.terminalText, record.bytes, &parsed->second); + plotWindow->appendRecord(record.timestamp, record.terminalText, record.bytes, record.receivedAsStream); } } diff --git a/src/app/view/workbench/workbench_page_protocol_templates.cpp b/src/app/view/workbench/workbench_page_protocol_templates.cpp index 42c743a..88856ee 100644 --- a/src/app/view/workbench/workbench_page_protocol_templates.cpp +++ b/src/app/view/workbench/workbench_page_protocol_templates.cpp @@ -1,6 +1,8 @@ -#include "app/view/workbench/workbench_page_internal.h" +#include "app/view/protocol_analysis_window.h" +#include "app/view/protocol_payload_editor.h" #include "app/view/protocol_template_window.h" #include "app/view/quick_plot_window.h" +#include "app/view/workbench/workbench_page_internal.h" #include @@ -140,6 +142,9 @@ void WorkbenchPage::loadProtocolTemplates(bool restoreSavedSelection) for (QuickPlotWindow *plotWindow : m_quickPlotWindows) { plotWindow->setProtocolTemplates(m_protocolTemplates); } + if (m_protocolAnalysisWindow) { + m_protocolAnalysisWindow->setProtocolTemplates(m_protocolTemplates); + } return; } @@ -176,6 +181,9 @@ void WorkbenchPage::saveProtocolTemplates() const plotWindow->setProtocolTemplates(m_protocolTemplates); } } + if (m_protocolAnalysisWindow) { + m_protocolAnalysisWindow->setProtocolTemplates(m_protocolTemplates); + } publishSharedList(SharedList::ProtocolTemplates); } @@ -225,7 +233,8 @@ void WorkbenchPage::updateProtocolTemplateActionState() } if (m_protocolDeleteButton) { const int selectedIndex = m_protocolTemplateCombo ? m_protocolTemplateCombo->currentIndex() : -1; - const bool selectedTemplate = selectedIndex >= 0 && selectedIndex < m_protocolTemplates.size() && hasName && + const bool selectedTemplate = + selectedIndex >= 0 && selectedIndex < m_protocolTemplates.size() && hasName && m_protocolTemplates.at(selectedIndex).name == m_protocolNameEdit->text().trimmed(); m_protocolDeleteButton->setEnabled(m_protocolTemplates.size() > 1 && selectedTemplate); } @@ -246,12 +255,12 @@ void WorkbenchPage::updateProtocolTemplateActionState() if (!enabled) { m_protocolStatusLabel->setText(AppI18n::text("协议模板未启用") + QStringLiteral(" · ") + item.name); } else { - m_protocolStatusLabel->setText( - AppI18n::text("%1 · 帧头 %2 B · 命令 %3 B · %4") - .arg(item.name) - .arg(item.header.size()) - .arg(item.commandSize) - .arg(AppProtocol::hasChecksum(item) ? AppChecksum::labelForAlgorithm(item.checksumAlgorithm) + m_protocolStatusLabel->setText(AppI18n::text("%1 · 帧头 %2 B · 命令 %3 B · %4") + .arg(item.name) + .arg(item.header.size()) + .arg(item.commandSize) + .arg(AppProtocol::hasChecksum(item) + ? AppChecksum::labelForAlgorithm(item.checksumAlgorithm) : AppI18n::text("无校验"))); } } @@ -271,6 +280,30 @@ void WorkbenchPage::showProtocolTemplateWindow() m_protocolTemplateWindow->activateWindow(); } +void WorkbenchPage::showProtocolAnalysisWindow() +{ + if (!m_protocolAnalysisWindow) { + m_protocolAnalysisWindow = new ProtocolAnalysisWindow(this); + connect(m_protocolAnalysisWindow, &ProtocolAnalysisWindow::parsingEnabledChanged, m_protocolEnabledCheck, + &CheckBox::setChecked); + connect(m_protocolAnalysisWindow, &ProtocolAnalysisWindow::editTemplateRequested, this, + &WorkbenchPage::editProtocolTemplate); + } + m_protocolAnalysisWindow->setProtocolTemplates(m_protocolTemplates, selectedProtocolTemplate().name); + m_protocolAnalysisWindow->setParsingEnabled(m_protocolEnabledCheck->isChecked()); + m_protocolAnalysisWindow->showNormal(); + m_protocolAnalysisWindow->raise(); + m_protocolAnalysisWindow->activateWindow(); +} + +void WorkbenchPage::editProtocolTemplate(const QString &name) +{ + const int index = m_protocolTemplateCombo->findText(name); + if (index >= 0) + m_protocolTemplateCombo->setCurrentIndex(index); + showProtocolTemplateWindow(); +} + void WorkbenchPage::updateProtocolTemplatePreview() { if (!m_protocolTemplateWindow || m_updatingProtocolTemplateUi) { @@ -299,13 +332,14 @@ void WorkbenchPage::updateProtocolTemplatePreview() QString WorkbenchPage::protocolTemplateInputError() const { - return protocolInputError(m_protocolNameEdit, m_protocolHeaderEdit, m_protocolTrailerEdit, - {{AppI18n::text("长度偏移"), m_protocolLengthOffsetEdit}, - {AppI18n::text("命令偏移"), m_protocolCommandOffsetEdit}, - {AppI18n::text("命令长度"), m_protocolCommandSizeEdit}, - {AppI18n::text("载荷偏移"), m_protocolPayloadOffsetEdit}, - {AppI18n::text("载荷长度"), m_protocolPayloadLengthEdit}, - {AppI18n::text("校验起始偏移"), m_protocolChecksumStartEdit}}); + const QString error = protocolInputError(m_protocolNameEdit, m_protocolHeaderEdit, m_protocolTrailerEdit, + {{AppI18n::text("长度偏移"), m_protocolLengthOffsetEdit}, + {AppI18n::text("命令偏移"), m_protocolCommandOffsetEdit}, + {AppI18n::text("命令长度"), m_protocolCommandSizeEdit}, + {AppI18n::text("载荷偏移"), m_protocolPayloadOffsetEdit}, + {AppI18n::text("载荷长度"), m_protocolPayloadLengthEdit}, + {AppI18n::text("校验起始偏移"), m_protocolChecksumStartEdit}}); + return error.isEmpty() ? AppProtocol::payloadConfigurationError(currentProtocolTemplateFromUi()) : error; } AppProtocol::ProtocolTemplate WorkbenchPage::selectedProtocolTemplate() const @@ -350,6 +384,9 @@ AppProtocol::ProtocolTemplate WorkbenchPage::currentProtocolTemplateFromUi() con m_protocolChecksumByteOrderCombo ? m_protocolChecksumByteOrderCombo->currentData().toString() : AppChecksum::byteOrderKey(AppChecksum::ByteOrder::LittleEndian)); item.checksumStart = intFromEdit(m_protocolChecksumStartEdit); + if (m_protocolPayloadEditor) { + m_protocolPayloadEditor->applyTo(item); + } return item; } @@ -362,6 +399,7 @@ void WorkbenchPage::applyProtocolTemplate(int index) const AppProtocol::ProtocolTemplate item = m_protocolTemplates.at(index); fillProtocolTemplateEditor(item); + updateProtocolTemplateActionState(); if (m_protocolTemplateWindow) { AppSettings settings; const QJsonDocument examples = QJsonDocument::fromJson( @@ -370,18 +408,12 @@ void WorkbenchPage::applyProtocolTemplate(int index) if (example.isString()) { m_protocolTemplateWindow->setSampleHex(example.toString()); } else { - // Without a saved sample, keep the current one only if it is a valid - // frame for this template. Otherwise it would show errors and be - // saved as this template's sample. - const HexParseResult sample = parseHexPayload(m_protocolTemplateWindow->sampleHex()); - const AppProtocol::ParseResult parsed = - sample.ok ? AppProtocol::parseFrame(sample.bytes, item) : AppProtocol::ParseResult(); - if (!parsed.ok || (parsed.checksumChecked && !parsed.checksumValid)) { - m_protocolTemplateWindow->setSampleHex(bytesToHex(AppProtocol::exampleFrame(item))); - } + m_protocolTemplateWindow->generateMatchingSample(); } } - updateProtocolTemplateActionState(); + if (m_protocolAnalysisWindow && m_protocolEnabledCheck->isChecked()) { + m_protocolAnalysisWindow->setProtocolTemplates(m_protocolTemplates, item.name); + } } void WorkbenchPage::fillProtocolTemplateEditor(const AppProtocol::ProtocolTemplate &item) @@ -407,6 +439,9 @@ void WorkbenchPage::fillProtocolTemplateEditor(const AppProtocol::ProtocolTempla setComboCurrentData(m_protocolChecksumAlgorithmCombo, item.checksumAlgorithm); setComboCurrentData(m_protocolChecksumByteOrderCombo, AppChecksum::byteOrderKey(item.checksumByteOrder)); setEditValue(m_protocolChecksumStartEdit, item.checksumStart); + if (m_protocolPayloadEditor) { + m_protocolPayloadEditor->setProtocolTemplate(item); + } m_updatingProtocolTemplateUi = false; } @@ -440,15 +475,20 @@ void WorkbenchPage::saveCurrentProtocolTemplate() const HexParseResult example = parseHexPayload(m_protocolTemplateWindow->sampleHex()); if (example.ok) { AppSettings settings; - QJsonObject examples = QJsonDocument::fromJson( - settings.value(QLatin1String(ProtocolTemplateExamplesSettingsKey)).toString().toUtf8()).object(); + QJsonObject examples = + QJsonDocument::fromJson( + settings.value(QLatin1String(ProtocolTemplateExamplesSettingsKey)).toString().toUtf8()) + .object(); examples.insert(item.name, bytesToHex(example.bytes)); settings.setValue(QLatin1String(ProtocolTemplateExamplesSettingsKey), QString::fromUtf8(QJsonDocument(examples).toJson(QJsonDocument::Compact))); } } - updateProtocolTemplateCombo(index); + updateProtocolTemplateCombo(index, false); saveProtocolTemplates(); + if (m_protocolAnalysisWindow && m_protocolEnabledCheck->isChecked()) { + m_protocolAnalysisWindow->setProtocolTemplates(m_protocolTemplates, item.name); + } showSuccess(AppI18n::text("已保存协议模板"), item.name); } @@ -468,8 +508,9 @@ void WorkbenchPage::deleteCurrentProtocolTemplate() const QString name = m_protocolTemplates.at(index).name; AppSettings settings; - QJsonObject examples = QJsonDocument::fromJson( - settings.value(QLatin1String(ProtocolTemplateExamplesSettingsKey)).toString().toUtf8()).object(); + QJsonObject examples = + QJsonDocument::fromJson(settings.value(QLatin1String(ProtocolTemplateExamplesSettingsKey)).toString().toUtf8()) + .object(); examples.remove(name); settings.setValue(QLatin1String(ProtocolTemplateExamplesSettingsKey), QString::fromUtf8(QJsonDocument(examples).toJson(QJsonDocument::Compact))); diff --git a/src/app/view/workbench/workbench_page_side_sections.cpp b/src/app/view/workbench/workbench_page_side_sections.cpp index dc16e67..0eb109f 100644 --- a/src/app/view/workbench/workbench_page_side_sections.cpp +++ b/src/app/view/workbench/workbench_page_side_sections.cpp @@ -1,5 +1,7 @@ #include "app/core/app_i18n.h" #include "app/view/muted_text.h" +#include "app/view/protocol_analysis_window.h" +#include "app/view/protocol_payload_editor.h" #include "app/view/protocol_template_window.h" #include "app/view/workbench/workbench_page_internal.h" @@ -289,6 +291,17 @@ QWidget *WorkbenchPage::createProtocolTemplateSection() root->addWidget(editProtocolButton); connect(editProtocolButton, &PushButton::clicked, this, &WorkbenchPage::showProtocolTemplateWindow); + auto *analysisButton = new PushButton(icon(FluentIcon::View), AppI18n::text("解析数据与曲线"), section); + analysisButton->setObjectName(QStringLiteral("protocolAnalysisButton")); + root->addWidget(analysisButton); + connect(analysisButton, &PushButton::clicked, this, [this]() { + if (!m_protocolEnabledCheck->isChecked()) { + m_protocolEnabledCheck->setChecked(true); + } else { + showProtocolAnalysisWindow(); + } + }); + m_protocolStatusLabel = new CaptionLabel(AppI18n::text("协议模板未启用"), section); AppUi::setMutedTextColor(m_protocolStatusLabel); m_protocolStatusLabel->setWordWrap(true); @@ -299,8 +312,9 @@ QWidget *WorkbenchPage::createProtocolTemplateSection() auto *editorRoot = new QVBoxLayout(editor); editorRoot->setContentsMargins(0, 0, 12, 0); editorRoot->setSpacing(10); - const auto group = [editor, editorRoot](const QString &title) { + const auto group = [editor, editorRoot](const QString &title, const QString &kind) { auto *box = new SimpleCardWidget(editor); + box->setObjectName(QStringLiteral("protocolGroup-") + kind); box->setBorderRadius(8); box->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); auto *layout = new QVBoxLayout(box); @@ -333,7 +347,7 @@ QWidget *WorkbenchPage::createProtocolTemplateSection() layout->addLayout(fields); }; - auto *basicGroup = group(AppI18n::text("名称、帧头与帧尾")); + auto *basicGroup = group(AppI18n::text("模板设置"), QStringLiteral("metadata")); auto *editorTemplateCombo = new ComboBox(editor); editorTemplateCombo->setObjectName(QStringLiteral("protocolEditorTemplateCombo")); editorTemplateCombo->setPlaceholderText(AppI18n::text("未保存的协议")); @@ -358,19 +372,21 @@ QWidget *WorkbenchPage::createProtocolTemplateSection() makeCompactControl(m_protocolNameEdit); addFormRow(basicGroup, AppI18n::text("名称"), m_protocolNameEdit); + auto *headerGroup = group(AppI18n::text("帧头"), QStringLiteral("header")); m_protocolHeaderEdit = new LineEdit(editor); m_protocolHeaderEdit->setObjectName(QStringLiteral("protocolTemplateHeaderEdit")); m_protocolHeaderEdit->setPlaceholderText(AppI18n::text("帧头 HEX,如 AA 55")); makeCompactControl(m_protocolHeaderEdit); - addFormRow(basicGroup, AppI18n::text("帧头"), m_protocolHeaderEdit); + addFormRow(headerGroup, AppI18n::text("帧头"), m_protocolHeaderEdit); + auto *trailerGroup = group(AppI18n::text("帧尾"), QStringLiteral("trailer")); m_protocolTrailerEdit = new LineEdit(editor); m_protocolTrailerEdit->setObjectName(QStringLiteral("protocolTemplateTrailerEdit")); m_protocolTrailerEdit->setPlaceholderText(AppI18n::text("帧尾 HEX,如 0D 0A,可留空")); makeCompactControl(m_protocolTrailerEdit); - addFormRow(basicGroup, AppI18n::text("帧尾"), m_protocolTrailerEdit); + addFormRow(trailerGroup, AppI18n::text("帧尾"), m_protocolTrailerEdit); - auto *lengthGroup = group(AppI18n::text("长度字段")); + auto *lengthGroup = group(AppI18n::text("长度字段"), QStringLiteral("length")); m_protocolLengthOffsetEdit = createNumberEdit(editor, 2, 0, 65535); m_protocolLengthOffsetEdit->setObjectName(QStringLiteral("protocolTemplateLengthOffsetEdit")); m_protocolLengthSizeCombo = new ComboBox(editor); @@ -400,28 +416,30 @@ QWidget *WorkbenchPage::createProtocolTemplateSection() lengthHint->setWordWrap(true); lengthGroup->addWidget(lengthHint); - auto *commandGroup = group(AppI18n::text("命令字段")); + auto *commandGroup = group(AppI18n::text("命令字段"), QStringLiteral("command")); m_protocolCommandOffsetEdit = createNumberEdit(editor, 3, 0, 65535); m_protocolCommandOffsetEdit->setObjectName(QStringLiteral("protocolTemplateCommandOffsetEdit")); m_protocolCommandSizeEdit = createNumberEdit(editor, 1, 0, 256); m_protocolCommandSizeEdit->setObjectName(QStringLiteral("protocolTemplateCommandSizeEdit")); - pairedFields(commandGroup, AppI18n::text("字节偏移"), m_protocolCommandOffsetEdit, - AppI18n::text("字节数"), m_protocolCommandSizeEdit); + pairedFields(commandGroup, AppI18n::text("字节偏移"), m_protocolCommandOffsetEdit, AppI18n::text("字节数"), + m_protocolCommandSizeEdit); - auto *payloadGroup = group(AppI18n::text("载荷字段")); + auto *payloadGroup = group(AppI18n::text("载荷范围"), QStringLiteral("payload")); m_protocolPayloadOffsetEdit = createNumberEdit(editor, 4, 0, 65535); m_protocolPayloadOffsetEdit->setObjectName(QStringLiteral("protocolTemplatePayloadOffsetEdit")); m_protocolPayloadLengthEdit = createNumberEdit(editor, 0, 0, 65535); m_protocolPayloadLengthEdit->setObjectName(QStringLiteral("protocolTemplatePayloadLengthEdit")); m_protocolPayloadLengthEdit->setAccessibleDescription(AppI18n::text("0 表示按长度字段自动计算")); - pairedFields(payloadGroup, AppI18n::text("字节偏移"), m_protocolPayloadOffsetEdit, - AppI18n::text("固定长度"), m_protocolPayloadLengthEdit); + pairedFields(payloadGroup, AppI18n::text("字节偏移"), m_protocolPayloadOffsetEdit, AppI18n::text("固定长度"), + m_protocolPayloadLengthEdit); auto *payloadHint = new CaptionLabel(AppI18n::text("固定长度填 0,按长度字段或剩余字节自动计算。"), editor); AppUi::setMutedTextColor(payloadHint); payloadHint->setWordWrap(true); payloadGroup->addWidget(payloadHint); - auto *checksumGroup = group(AppI18n::text("校验字段")); + m_protocolPayloadEditor = new ProtocolPayloadEditor; + + auto *checksumGroup = group(AppI18n::text("校验字段"), QStringLiteral("checksum")); m_protocolChecksumAlgorithmCombo = new ComboBox(editor); m_protocolChecksumAlgorithmCombo->setObjectName(QStringLiteral("protocolTemplateChecksumAlgorithmCombo")); m_protocolChecksumAlgorithmCombo->addItem(AppI18n::text("无校验"), QIcon(), AppProtocol::checksumNoneKey()); @@ -464,7 +482,9 @@ QWidget *WorkbenchPage::createProtocolTemplateSection() buttonRow->addWidget(m_protocolSaveButton); editorRoot->addWidget(actionBar); editorRoot->addStretch(); - m_protocolTemplateWindow = new ProtocolTemplateWindow(editor, this); + m_protocolTemplateWindow = new ProtocolTemplateWindow(editor, this, m_protocolPayloadEditor); + connect(m_protocolTemplateWindow, &ProtocolTemplateWindow::createPlotRequested, this, + &WorkbenchPage::showQuickPlotWindow); connect(newTemplateButton, &PushButton::clicked, this, [this]() { QString name = AppI18n::text("新协议"); @@ -488,19 +508,30 @@ QWidget *WorkbenchPage::createProtocolTemplateSection() blank.commandSize = 0; blank.payloadOffset = 0; fillProtocolTemplateEditor(blank); - m_protocolTemplateWindow->setSampleHex(QString()); updateProtocolTemplateActionState(); + m_protocolTemplateWindow->generateMatchingSample(); m_protocolNameEdit->setFocus(); m_protocolNameEdit->selectAll(); }); - const auto markDirty = [this]() { updateProtocolTemplateActionState(); }; + const auto markDirty = [this]() { + updateProtocolTemplateActionState(); + if (!m_updatingProtocolTemplateUi && protocolTemplateInputError().isEmpty()) + m_protocolTemplateWindow->refreshGeneratedSample(); + }; connect(m_protocolTemplateCombo, &ComboBox::currentIndexChanged, this, &WorkbenchPage::applyProtocolTemplate); connect(m_protocolEnabledCheck, &CheckBox::toggled, this, [this](bool) { AppSettings settings; settings.setValue(QStringLiteral("protocolTemplate/enabled"), m_protocolEnabledCheck->isChecked()); updateProtocolTemplateActionState(); + if (m_protocolAnalysisWindow) { + m_protocolAnalysisWindow->setParsingEnabled(m_protocolEnabledCheck->isChecked()); + } + if (m_protocolEnabledCheck->isChecked()) { + showProtocolAnalysisWindow(); + } }); + connect(m_protocolPayloadEditor, &ProtocolPayloadEditor::changed, this, markDirty); connect(m_protocolNameEdit, &LineEdit::textChanged, this, markDirty); connect(m_protocolHeaderEdit, &LineEdit::textChanged, this, markDirty); connect(m_protocolTrailerEdit, &LineEdit::textChanged, this, markDirty); diff --git a/src/app/view/workbench/workbench_page_state.cpp b/src/app/view/workbench/workbench_page_state.cpp index 171b2c1..d445afe 100644 --- a/src/app/view/workbench/workbench_page_state.cpp +++ b/src/app/view/workbench/workbench_page_state.cpp @@ -1,5 +1,6 @@ #include "app/core/app_i18n.h" #include "app/serial/virtual_serial_pair.h" +#include "app/view/protocol_analysis_window.h" #include "app/view/quick_plot_window.h" #include "app/view/workbench/workbench_page_internal.h" @@ -15,6 +16,7 @@ void WorkbenchPage::setupSerialSignals() m_manualDisconnect = false; m_rxFrameBuffer.clear(); m_rxStreamDecoder.reset(); + resetProtocolStreams(); m_connectionStartedAt = QDateTime::currentDateTime(); m_lastStatsRxCount = m_rxCount; m_lastStatsTxCount = m_txCount; @@ -37,6 +39,7 @@ void WorkbenchPage::setupSerialSignals() stopScript(); } flushRxFrameBuffer(); + resetProtocolStreams(); if (m_fileSendFile.isOpen()) { m_fileSendTimer.stop(); m_fileSendFile.close(); @@ -73,6 +76,14 @@ void WorkbenchPage::setupSerialSignals() }); } +void WorkbenchPage::resetProtocolStreams() +{ + for (auto *plot : m_quickPlotWindows) + plot->resetStream(); + if (m_protocolAnalysisWindow) + m_protocolAnalysisWindow->resetStream(); +} + void WorkbenchPage::refreshPorts() { const QString previousPort = m_portCombo->currentData().toString(); diff --git a/src/app/view/workbench/workbench_page_terminal.cpp b/src/app/view/workbench/workbench_page_terminal.cpp index 2ae1e04..7c22695 100644 --- a/src/app/view/workbench/workbench_page_terminal.cpp +++ b/src/app/view/workbench/workbench_page_terminal.cpp @@ -1,4 +1,5 @@ #include "app/core/app_i18n.h" +#include "app/view/protocol_analysis_window.h" #include "app/view/workbench/workbench_page_internal.h" #include @@ -461,9 +462,8 @@ void WorkbenchPage::appendRecord(RecordDirection direction, const QByteArray &da // records and sent data decode on their own. const QString decoded = direction == RecordDirection::Rx && updateStats ? m_rxStreamDecoder.decode(data, receiveEncodingKey()) - : AppTextEncoding::decode(data, direction == RecordDirection::Rx - ? receiveEncodingKey() - : sendEncodingKey()); + : AppTextEncoding::decode(data, direction == RecordDirection::Rx ? receiveEncodingKey() + : sendEncodingKey()); record.terminalText = AppTextEncoding::toTerminalText(decoded); record.displayText = AppTextEncoding::toSingleLineText(decoded); record.sourceLabel = sourceLabel; @@ -481,6 +481,9 @@ void WorkbenchPage::appendRecord(RecordDirection direction, const QByteArray &da writeAutoLogRecord(record); appendQuickPlotRecord(record); if (direction == RecordDirection::Rx) { + if (m_protocolAnalysisWindow) { + m_protocolAnalysisWindow->appendRecord(record.timestamp, record.bytes, record.receivedAsStream); + } updateModbusResponseStatus(data); } diff --git a/src/app/view/workbench_page.h b/src/app/view/workbench_page.h index e3bcf2b..3ea83b6 100644 --- a/src/app/view/workbench_page.h +++ b/src/app/view/workbench_page.h @@ -31,6 +31,8 @@ class ScriptRunner; struct DataTableRecord; class QuickPlotWindow; class ProtocolTemplateWindow; +class ProtocolPayloadEditor; +class ProtocolAnalysisWindow; class WorkbenchPage : public AppPage, public AppControl::SessionControl { @@ -39,6 +41,7 @@ class WorkbenchPage : public AppPage, public AppControl::SessionControl friend class WorkbenchDataTableTest; friend class WorkbenchQuickPlotTest; friend class ProtocolWindowsTest; + friend class ProtocolAnalysisTest; friend class TerminalViewTest; friend class TerminalColorsTest; friend class WorkbenchReliabilityTest; @@ -283,6 +286,7 @@ class WorkbenchPage : public AppPage, public AppControl::SessionControl void recordReceivedBytes(const QByteArray &data); void processBufferedFrameData(const QByteArray &data); void flushRxFrameBuffer(); + void resetProtocolStreams(); void updateFrameControlState(); void loadProtocolTemplates(bool restoreSavedSelection = true); void saveProtocolTemplates() const; @@ -290,6 +294,8 @@ class WorkbenchPage : public AppPage, public AppControl::SessionControl void updateProtocolTemplateUi(); void updateProtocolTemplateActionState(); void showProtocolTemplateWindow(); + void editProtocolTemplate(const QString &name); + void showProtocolAnalysisWindow(); void updateProtocolTemplatePreview(); // Why the template editor's fields cannot form a template, or empty. QString protocolTemplateInputError() const; @@ -401,7 +407,7 @@ class WorkbenchPage : public AppPage, public AppControl::SessionControl void updateAutoLogStatus(); void showQuickPlotWindow(); QuickPlotWindow *createQuickPlotWindow(const AppPlot::ParserConfig &config, - const AppProtocol::ProtocolTemplate *protocolTemplate = nullptr); + const AppProtocol::ProtocolTemplate *protocolTemplate = nullptr); void appendQuickPlotRecord(const SessionRecord &record); void showDataTableWindow(); void refreshDataTableWindow(); @@ -559,6 +565,8 @@ class WorkbenchPage : public AppPage, public AppControl::SessionControl QList m_quickPlotWindows; int m_nextPlotWindowNumber = 1; ProtocolTemplateWindow *m_protocolTemplateWindow = nullptr; + ProtocolPayloadEditor *m_protocolPayloadEditor = nullptr; + ProtocolAnalysisWindow *m_protocolAnalysisWindow = nullptr; FluentQt::PrimaryPushButton *m_connectButton = nullptr; FluentQt::PrimaryPushButton *m_sendButton = nullptr; FluentQt::TransparentToolButton *m_receiveModeButton = nullptr; diff --git a/src/main.cpp b/src/main.cpp index f94f447..c63e23b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3,6 +3,7 @@ #include "app/core/app_i18n.h" #include "app/core/app_settings.h" #include "app/core/font_preferences.h" +#include "app/core/macos_accessibility_fix.h" #include @@ -22,6 +23,7 @@ int main(int argc, char *argv[]) #endif QApplication app(argc, argv); + AppPlatform::installMacAccessibilityFix(); Q_INIT_RESOURCE(app); Q_INIT_RESOURCE(fluentqtwidgets); app.setStyle(QStyleFactory::create(QStringLiteral("Fusion"))); diff --git a/tests/tst_macos_accessibility.mm b/tests/tst_macos_accessibility.mm new file mode 100644 index 0000000..118fc8e --- /dev/null +++ b/tests/tst_macos_accessibility.mm @@ -0,0 +1,93 @@ +#include "app/core/macos_accessibility_fix.h" +#import +#include +#include +#include +#include +#import +#import + +namespace { +id nativeQuery(id object, const char *selector) +{ + return reinterpret_cast(objc_msgSend)(object, sel_registerName(selector)); +} + +id nativeElement(QAccessibleInterface *interface) +{ + return reinterpret_cast(objc_msgSend)( + reinterpret_cast(objc_getClass("QMacAccessibilityElement")), sel_registerName("elementWithId:"), + QAccessible::uniqueId(interface)); +} +} // namespace + +class MacAccessibilityTest : public QObject +{ + Q_OBJECT + private slots: + void selectedCellsSurviveNativeTeardown() + { + if (QString::fromLatin1(qVersion()) != QStringLiteral("6.12.0")) + QSKIP("The runtime Qt version does not need this shim"); + QCOMPARE(QApplication::platformName(), QStringLiteral("cocoa")); + QVERIFY(AppPlatform::installMacAccessibilityFix()); + QAccessible::setActive(true); + QTableWidget table(2, 2); + table.setSelectionBehavior(QAbstractItemView::SelectRows); + table.setSelectionMode(QAbstractItemView::SingleSelection); + const auto populate = [&table]() { + for (int row = 0; row < table.rowCount(); ++row) + for (int column = 0; column < 2; ++column) + if (!table.item(row, column)) + table.setItem(row, column, new QTableWidgetItem(QString::number(row * 2 + column))); + }; + populate(); + table.selectRow(0); + auto *interface = QAccessible::queryAccessibleInterface(&table); + QVERIFY(interface && interface->selectionInterface()); + id element = nativeElement(interface); + QVERIFY(element); + // Before the backport, this first native query deletes the table's + // interfaces while iterating selected cells and deterministically crashes. + NSArray *initial = nativeQuery(element, "accessibilitySelectedChildren"); + QCOMPARE([initial count], NSUInteger(2)); + // Exercise both native model growth and removal, draining each batch. + for (int rowCount : {3, 2}) { + @autoreleasepool { + table.setRowCount(rowCount); + populate(); + const int selectedRow = rowCount - 1; + table.selectRow(selectedRow); + NSArray *children = nativeQuery(element, "accessibilityChildren"); + QVERIFY([children count] > 0); + for (id child in children) { + NSArray *cells = nativeQuery(child, "accessibilityChildren"); + for (id cell in cells) + QVERIFY(nativeQuery(cell, "accessibilityTitle")); + } + NSArray *selected = nativeQuery(element, "accessibilitySelectedChildren"); + QCOMPARE([selected count], NSUInteger(2)); + for (NSUInteger column = 0; column < 2; ++column) { + id cell = selected[column]; + NSString *title = nativeQuery(cell, "accessibilityTitle"); + QCOMPARE(QString::fromNSString(title), QString::number(selectedRow * 2 + int(column))); + QVERIFY(nativeQuery(cell, "accessibilityParent")); + } + } + // Pool draining must not delete the interfaces still owned by Qt. + const auto selectedInterfaces = interface->selectionInterface()->selectedItems(); + QCOMPARE(selectedInterfaces.size(), 2); + for (auto *cell : selectedInterfaces) + QVERIFY(cell && cell->isValid()); + } + } +}; + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + MacAccessibilityTest test; + return QTest::qExec(&test, argc, argv); +} + +#include "tst_macos_accessibility.moc" diff --git a/tests/tst_protocol_analysis.cpp b/tests/tst_protocol_analysis.cpp new file mode 100644 index 0000000..9f52c20 --- /dev/null +++ b/tests/tst_protocol_analysis.cpp @@ -0,0 +1,521 @@ +#include "app/core/app_i18n.h" +#include "app/core/app_settings.h" +#include "app/core/hex_utils.h" +#include "app/view/protocol_analysis_window.h" +#include "app/view/protocol_payload_editor.h" +#include "app/view/protocol_template_window.h" +#include "app/view/workbench_page.h" + +#include +#include +#include +#include +#include +#include + +class ProtocolAnalysisTest : public QObject +{ + Q_OBJECT + + static AppProtocol::ProtocolTemplate motorTemplate() + { + auto item = AppProtocol::defaultTemplate(); + item.name = QStringLiteral("Motors"); + item.commandOffset = 4; + item.payloadOffset = 5; + item.addressOffset = 3; + item.addressSize = 1; + item.payloadFields = { + {QStringLiteral("Angle"), 0, AppPlot::BinaryType::Int16, AppPlot::ByteOrder::LittleEndian, 0.01, 0}, + {QStringLiteral("Speed"), 2, AppPlot::BinaryType::UInt16}, + {QStringLiteral("Status"), 4, AppPlot::BinaryType::UInt8}}; + return item; + } + + static QByteArray motorFrame(int address, qint16 angle = 7033, quint16 speed = 120, + const QByteArray &header = QByteArray::fromHex("AA55")) + { + QByteArray frame = header; + frame.append(char(5)); + frame.append(char(address)); + frame.append(char(0x10)); + frame.append(char(angle & 0xff)); + frame.append(char((quint16(angle) >> 8) & 0xff)); + frame.append(char(speed & 0xff)); + frame.append(char(speed >> 8)); + frame.append(char(1)); + frame += + AppChecksum::calculate(frame, QStringLiteral("crc16-modbus"), AppChecksum::ByteOrder::LittleEndian).bytes; + return frame; + } + + static FluentQt::TableWidget *values(ProtocolAnalysisWindow &window) + { + return window.findChild(QStringLiteral("protocolAnalysisValues")); + } + + static FluentQt::RealtimePlotWidget *plot(ProtocolAnalysisWindow &window) + { + return window.findChild(QStringLiteral("protocolAnalysisPlot")); + } + + static void start(ProtocolAnalysisWindow &window) + { + window.setProtocolTemplates({motorTemplate()}, QStringLiteral("Motors")); + window.setParsingEnabled(true); + window.show(); + } + + private slots: + void initTestCase() + { + Q_INIT_RESOURCE(app); + Q_INIT_RESOURCE(fluentqtwidgets); + FluentQt::FluentConfig::instance()->setFileName( + QDir(AppSettings::directoryPath()).filePath(QStringLiteral("fluent.json"))); + AppI18n::installTranslators(qApp, QStringLiteral("zh_CN")); + FluentQt::ThemeManager::instance()->setTheme(FluentQt::Theme::Light); + } + + void init() + { + AppSettings settings; + settings.clear(); + } + + void templatesKeepFieldsAndRemainBackwardCompatible() + { + const auto item = motorTemplate(); + const auto restored = AppProtocol::fromJson(AppProtocol::toJson(item)); + QVERIFY(restored == item); + auto modified = restored; + modified.payloadFields[0].scale = 0.1; + QVERIFY(!(modified == item)); + auto oldJson = AppProtocol::toJson(AppProtocol::defaultTemplate()); + oldJson.remove(QStringLiteral("payloadFields")); + oldJson.remove(QStringLiteral("addressOffset")); + oldJson.remove(QStringLiteral("addressSize")); + QVERIFY(AppProtocol::fromJson(oldJson) == AppProtocol::defaultTemplate()); + const auto frame = motorFrame(2, -5904); + const auto parsed = AppProtocol::parseFrame(frame, restored); + QVERIFY(parsed.ok && parsed.checksumValid); + const auto decoded = + AppPlot::extractSamples(AppProtocol::payloadParserConfig(restored), {}, frame, parsed.payload); + QCOMPARE(decoded.size(), 1); + QCOMPARE(decoded.first().size(), 3); + QCOMPARE(decoded.first().first().value, -59.04); + } + + void rejectsAmbiguousNamesAndInvalidFieldRanges() + { + auto item = motorTemplate(); + QVERIFY(AppProtocol::payloadConfigurationError(item).isEmpty()); + item.payloadFields[1].name = item.payloadFields.first().name; + QVERIFY(!AppProtocol::payloadConfigurationError(item).isEmpty()); + item.payloadFields[1].name.clear(); + QVERIFY(!AppProtocol::payloadConfigurationError(item).isEmpty()); + item = motorTemplate(); + item.payloadLength = 4; + QVERIFY(!AppProtocol::payloadConfigurationError(item).isEmpty()); + item.payloadFields.removeLast(); + QVERIFY(AppProtocol::payloadConfigurationError(item).isEmpty()); + item.addressOffset = -1; + QVERIFY(!AppProtocol::payloadConfigurationError(item).isEmpty()); + } + + void editorSavesAndRestoresFieldDefinitions() + { + WorkbenchPage page(nullptr, false, false); + page.m_protocolTemplates = {motorTemplate()}; + page.updateProtocolTemplateCombo(0); + auto *editor = page.m_protocolPayloadEditor; + auto *name = editor->findChild(QStringLiteral("protocolPayloadFieldName")); + auto *scale = editor->findChild(QStringLiteral("protocolPayloadFieldScale")); + QVERIFY(name && scale); + name->setText(QStringLiteral("Position")); + scale->setValue(0.02); + page.saveCurrentProtocolTemplate(); + WorkbenchPage restored(nullptr, false, false); + restored.loadProtocolTemplates(); + const auto saved = restored.currentProtocolTemplateFromUi(); + QCOMPARE(saved.name, QStringLiteral("Motors")); + QCOMPARE(saved.payloadFields.size(), 3); + QCOMPARE(saved.payloadFields.first().name, QStringLiteral("Position")); + QCOMPARE(saved.payloadFields.first().scale, 0.02); + QCOMPARE(saved.addressOffset, 3); + QCOMPARE(saved.addressSize, 1); + } + + void draggingFieldsReordersPayloadAndPreservesGaps() + { + WorkbenchPage page(nullptr, false, false); + auto definition = motorTemplate(); + definition.payloadFields[0].byteOffset = 1; + definition.payloadFields[1].byteOffset = 5; + definition.payloadFields[1].type = AppPlot::BinaryType::UInt32; + definition.payloadFields[2].byteOffset = 10; + page.m_protocolTemplates = {definition}; + page.updateProtocolTemplateCombo(0); + page.showProtocolTemplateWindow(); + auto *window = page.m_protocolTemplateWindow; + auto *table = window->findChild(QStringLiteral("protocolTemplateResultsTable")); + auto *model = table->model(); + const auto fieldRow = [model](const QString &name) { + for (int row = 0; row < model->rowCount(); ++row) + if (model->index(row, 0).data().toString() == name) + return row; + return -1; + }; + const int angleRow = fieldRow(QStringLiteral("Angle")); + const int statusRow = fieldRow(QStringLiteral("Status")); + QVERIFY(angleRow >= 0 && statusRow >= 0); + QVERIFY(!(model->flags(model->index(0, 0)) & Qt::ItemIsDragEnabled)); + std::unique_ptr drag(model->mimeData({model->index(statusRow, 0)})); + QVERIFY(!model->canDropMimeData(drag.get(), Qt::MoveAction, 0, 0, {})); + QVERIFY(model->dropMimeData(drag.get(), Qt::MoveAction, angleRow, 0, {})); + const auto reordered = page.currentProtocolTemplateFromUi(); + QCOMPARE(reordered.payloadFields[0].name, QStringLiteral("Status")); + QCOMPARE(reordered.payloadFields[0].byteOffset, 1); + QCOMPARE(reordered.payloadFields[1].name, QStringLiteral("Angle")); + QCOMPARE(reordered.payloadFields[1].byteOffset, 4); + QCOMPARE(reordered.payloadFields[1].scale, 0.01); + QCOMPARE(reordered.payloadFields[2].name, QStringLiteral("Speed")); + QCOMPARE(reordered.payloadFields[2].byteOffset, 7); + QCOMPARE(table->currentIndex().siblingAtColumn(0).data().toString(), QStringLiteral("Status")); + const auto parsed = AppProtocol::parseFrame(parseHexPayload(window->sampleHex()).bytes, reordered); + QVERIFY(parsed.ok && parsed.checksumValid); + QCOMPARE(parsed.payload.size(), 11); + + drag.reset(model->mimeData({model->index(fieldRow(QStringLiteral("Status")), 0)})); + QVERIFY(model->dropMimeData(drag.get(), Qt::MoveAction, fieldRow(QStringLiteral("Speed")) + 1, 0, {})); + QVERIFY(page.currentProtocolTemplateFromUi() == definition); + QCOMPARE(table->currentIndex().siblingAtColumn(0).data().toString(), QStringLiteral("Status")); + } + + void enablingProtocolOpensAnalysisAndUsesSelectedTemplate() + { + WorkbenchPage page(nullptr, false, false); + page.m_protocolTemplates = {motorTemplate()}; + page.updateProtocolTemplateCombo(0); + page.m_protocolEnabledCheck->setChecked(true); + auto *window = page.m_protocolAnalysisWindow; + QVERIFY(window && window->isVisible()); + QVERIFY(!QApplication::activeModalWidget()); + page.appendRecord(WorkbenchPage::RecordDirection::Tx, motorFrame(3), false); + QCOMPARE(values(*window)->rowCount(), 0); + page.appendRecord(WorkbenchPage::RecordDirection::Rx, motorFrame(1), false); + QCOMPARE(values(*window)->rowCount(), 3); + QTRY_COMPARE(values(*window)->item(0, 3)->text(), QStringLiteral("70.33")); + page.showProtocolAnalysisWindow(); + QCOMPARE(page.m_protocolAnalysisWindow, window); + QCOMPARE(values(*window)->rowCount(), 3); + auto *enabled = window->findChild(QStringLiteral("protocolAnalysisEnabled")); + enabled->setChecked(false); + QVERIFY(!page.m_protocolEnabledCheck->isChecked()); + page.appendRecord(WorkbenchPage::RecordDirection::Rx, motorFrame(2), false); + QCOMPARE(values(*window)->rowCount(), 3); + } + + void separatesAddressesAndPlotsOnOneTimeAxis() + { + ProtocolAnalysisWindow window; + start(window); + const auto now = QDateTime::currentDateTime(); + window.appendRecord(now, motorFrame(1, 7033)); + window.appendRecord(now.addMSecs(10), motorFrame(2, -5904)); + auto *table = values(window); + QCOMPARE(table->rowCount(), 6); + QTRY_COMPARE(table->item(0, 3)->text(), QStringLiteral("70.33")); + QTRY_COMPARE(table->item(3, 3)->text(), QStringLiteral("-59.04")); + QVERIFY(table->item(0, 1)->text().endsWith(QStringLiteral("01"))); + QVERIFY(table->item(3, 1)->text().endsWith(QStringLiteral("02"))); + table->item(0, 0)->setCheckState(Qt::Checked); + table->item(3, 0)->setCheckState(Qt::Checked); + QCOMPARE(plot(window)->seriesCount(), 2); + QCOMPARE(plot(window)->points(0).first().y(), 70.33); + QCOMPARE(plot(window)->points(1).first().y(), -59.04); + window.appendRecord(now.addSecs(1), motorFrame(1, 7100)); + window.appendRecord(now.addMSecs(1010), motorFrame(2, -5800)); + QCOMPARE(plot(window)->points(0).size(), 2); + QCOMPARE(plot(window)->points(1).size(), 2); + QCOMPARE(plot(window)->points(0).last(), QPointF(1.0, 71.0)); + QCOMPARE(plot(window)->points(1).last(), QPointF(1.01, -58.0)); + table->item(3, 0)->setCheckState(Qt::Unchecked); + QVERIFY(!plot(window)->isSeriesVisible(1)); + table->item(3, 0)->setCheckState(Qt::Checked); + QCOMPARE(plot(window)->points(1).size(), 2); + } + + void supportsSeveralTemplatesWithoutCrossMatching() + { + ProtocolAnalysisWindow window; + auto second = motorTemplate(); + second.name = QStringLiteral("Sensors"); + second.header = QByteArray::fromHex("BB66"); + window.setProtocolTemplates({motorTemplate(), second}, QStringLiteral("Motors")); + window.setParsingEnabled(true); + window.show(); + auto *templates = window.findChild(QStringLiteral("protocolAnalysisTemplates")); + templates->item(1, 0)->setCheckState(Qt::Checked); + const auto now = QDateTime::currentDateTime(); + window.appendRecord(now, motorFrame(1, 123)); + window.appendRecord(now, motorFrame(1, 456, 120, second.header)); + QCOMPARE(values(window)->rowCount(), 6); + QTRY_COMPARE(values(window)->item(0, 3)->text(), QStringLiteral("1.23")); + QTRY_COMPARE(values(window)->item(3, 3)->text(), QStringLiteral("4.56")); + templates->item(0, 0)->setCheckState(Qt::Unchecked); + window.appendRecord(now, motorFrame(1)); + QCOMPARE(values(window)->rowCount(), 0); + window.appendRecord(now, motorFrame(1, 456, 120, second.header)); + QCOMPARE(values(window)->rowCount(), 3); + } + + void reassemblesRawReadsAndDiscardsBadChecksums() + { + ProtocolAnalysisWindow window; + start(window); + const auto now = QDateTime::currentDateTime(); + const auto first = motorFrame(1); + const auto second = motorFrame(2, -5904); + window.appendRecord(now, QByteArray::fromHex("0000") + first.left(1), true); + window.appendRecord(now, first.mid(1, 6), true); + QCOMPARE(values(window)->rowCount(), 0); + window.appendRecord(now, first.mid(7) + second, true); + QCOMPARE(values(window)->rowCount(), 6); + auto bad = motorFrame(3); + bad[bad.size() - 1] ^= 0x01; + window.appendRecord(now, bad + motorFrame(4), true); + QCOMPARE(values(window)->rowCount(), 9); + QVERIFY(values(window)->item(6, 1)->text().endsWith(QStringLiteral("04"))); + } + + void endedRecordsRecoverAfterAnIncompleteLengthCandidate() + { + auto item = motorTemplate(); + item.lengthSize = 2; + item.commandOffset = 4; + item.addressOffset = 5; + item.payloadOffset = 6; + const auto good = AppProtocol::exampleFrame(item); + auto damaged = good; + damaged[2] = char(0xff); + damaged[3] = char(0xff); + const auto bytes = damaged + good + good; + QByteArray buffer; + // Without a boundary, this could still be the payload of a longer frame. + QVERIFY(AppProtocol::takeFrames(buffer, bytes, item, true).isEmpty()); + QCOMPARE(buffer, bytes); + const auto decoded = AppProtocol::takeFrames(buffer, bytes, item, false); + QCOMPARE(decoded.size(), 2); + QCOMPARE(decoded[0].bytes, good); + QCOMPARE(decoded[1].bytes, good); + QVERIFY(buffer.isEmpty()); + } + + void partialOuterFrameKeepsAValidFrameInsideItsPayload() + { + const auto item = motorTemplate(); + const auto inner = motorFrame(1); + auto outer = QByteArray::fromHex("AA55000110") + inner + QByteArray::fromHex("1234"); + outer[2] = char(inner.size() + 2); + outer += AppChecksum::calculate(outer, item.checksumAlgorithm, item.checksumByteOrder).bytes; + const int split = item.payloadOffset + inner.size(); + QByteArray buffer; + QVERIFY(AppProtocol::takeFrames(buffer, outer.left(split), item, true).isEmpty()); + const auto decoded = AppProtocol::takeFrames(buffer, outer.mid(split), item, true); + QCOMPARE(decoded.size(), 1); + QCOMPARE(decoded.first().bytes, outer); + const auto ended = AppProtocol::takeFrames(buffer, outer, item, false); + QCOMPARE(ended.size(), 1); + QCOMPARE(ended.first().bytes, outer); + } + + void pausesHiddenWindowsAndClearsPartialReads() + { + ProtocolAnalysisWindow window; + start(window); + const auto now = QDateTime::currentDateTime(); + const auto first = motorFrame(1); + window.appendRecord(now, first.left(6), true); + auto *pause = window.findChild(QStringLiteral("protocolAnalysisPause")); + pause->click(); + window.appendRecord(now, first, true); + QCOMPARE(values(window)->rowCount(), 0); + QCOMPARE(plot(window)->refreshRate(), 0); + pause->click(); + window.appendRecord(now, first.mid(6), true); + QCOMPARE(values(window)->rowCount(), 0); + window.hide(); + window.appendRecord(now, first); + QCOMPARE(values(window)->rowCount(), 0); + window.show(); + window.appendRecord(now, first); + QCOMPARE(values(window)->rowCount(), 3); + values(window)->item(0, 0)->setCheckState(Qt::Checked); + window.clearData(); + QCOMPARE(values(window)->item(0, 3)->text(), QStringLiteral("—")); + QCOMPARE(values(window)->item(0, 0)->checkState(), Qt::Checked); + QCOMPARE(plot(window)->points(0).size(), 0); + } + + void reloadsCurveChoicesAndSavedTemplateChanges() + { + ProtocolAnalysisWindow first; + start(first); + const auto now = QDateTime::currentDateTime(); + first.appendRecord(now, motorFrame(1)); + values(first)->item(0, 0)->setCheckState(Qt::Checked); + first.close(); + ProtocolAnalysisWindow second; + start(second); + second.appendRecord(now, motorFrame(1)); + QCOMPARE(values(second)->item(0, 0)->checkState(), Qt::Checked); + QCOMPARE(plot(second)->points(0).size(), 1); + auto changed = motorTemplate(); + changed.payloadFields[0].scale = 0.02; + second.setProtocolTemplates({changed}); + QCOMPARE(values(second)->rowCount(), 0); + second.appendRecord(now, motorFrame(1)); + QTRY_COMPARE(values(second)->item(0, 3)->text(), QStringLiteral("140.66")); + QCOMPARE(plot(second)->points(0).size(), 1); + } + + void missingPayloadFieldsDoNotKeepOldMeasurements() + { + ProtocolAnalysisWindow window; + start(window); + const auto now = QDateTime::currentDateTime(); + window.appendRecord(now, motorFrame(1)); + auto shortFrame = motorFrame(1).left(7); + shortFrame[2] = char(2); + shortFrame += + AppChecksum::calculate(shortFrame, QStringLiteral("crc16-modbus"), AppChecksum::ByteOrder::LittleEndian) + .bytes; + window.appendRecord(now, shortFrame); + QTRY_COMPARE(values(window)->item(1, 3)->text(), QStringLiteral("—")); + QTRY_COMPARE(values(window)->item(2, 3)->text(), QStringLiteral("—")); + QTRY_COMPARE(values(window)->item(0, 3)->text(), QStringLiteral("70.33")); + } + + void boundsDeviceRowsAndSimultaneousCurves() + { + ProtocolAnalysisWindow window; + start(window); + const auto now = QDateTime::currentDateTime(); + for (int address = 0; address < 90; ++address) { + window.appendRecord(now, motorFrame(address)); + } + QCOMPARE(values(window)->rowCount(), 256); + for (int row = 0; row <= AppPlot::MaximumChannels; ++row) { + values(window)->item(row, 0)->setCheckState(Qt::Checked); + } + QCOMPARE(values(window)->item(AppPlot::MaximumChannels, 0)->checkState(), Qt::Unchecked); + QCOMPARE(plot(window)->seriesCount(), AppPlot::MaximumChannels); + } + + void editorReportsMissingBytesAndUpdatesSelectedField() + { + WorkbenchPage page(nullptr, false, false); + auto definition = motorTemplate(); + definition.name = QStringLiteral("虚拟总线"); + definition.commandSize = 0; + definition.payloadOffset = 4; + definition.payloadFields[0].name = QStringLiteral("角度"); + definition.payloadFields[1].name = QStringLiteral("转速"); + definition.payloadFields[2].name = QStringLiteral("状态"); + page.m_protocolTemplates = {definition}; + page.updateProtocolTemplateCombo(0); + auto *window = page.m_protocolTemplateWindow; + window->resize(1100, 760); + page.showProtocolTemplateWindow(); + window->setSampleHex(QStringLiteral("AA 55 03 10 01 02 03 4D 6E")); + auto *validation = + window->findChild(QStringLiteral("protocolTemplateValidationLabel")); + auto *table = window->findChild(QStringLiteral("protocolTemplateResultsTable")); + auto *name = window->findChild(QStringLiteral("protocolPayloadFieldName")); + auto *scale = window->findChild(QStringLiteral("protocolPayloadFieldScale")); + auto *type = window->findChild(QStringLiteral("protocolPayloadFieldType")); + QVERIFY(validation && table && name && scale && type); + QCOMPARE(validation->text(), AppI18n::text("样例载荷不足:当前 %1 B,数据字段至少需要 %2 B。").arg(3).arg(5)); + QCOMPARE(table->model()->rowCount(), 7); + const auto fieldRow = [table](int field) { + for (int row = 0; row < table->model()->rowCount(); ++row) { + const auto index = table->model()->index(row, 0); + if (index.data(Qt::UserRole).toString() == QStringLiteral("field") && + index.data(Qt::UserRole + 1).toInt() == field) + return row; + } + return -1; + }; + const int speedRow = fieldRow(1); + QVERIFY(speedRow >= 0); + QCOMPARE(table->model()->index(speedRow, 4).data().toString(), AppI18n::text("无法解析")); + QCOMPARE(table->model()->index(speedRow, 5).data().toString(), AppI18n::text("缺少 %1 B").arg(1)); + table->selectRow(speedRow); + QCOMPARE(name->text(), QStringLiteral("转速")); + QVERIFY(type->isVisible() && scale->isVisible()); + QVERIFY(window->rect().contains(scale->mapTo(window, scale->rect().bottomRight()))); + table->selectRow(fieldRow(0)); + QCOMPARE(name->text(), QStringLiteral("角度")); + QCOMPARE(scale->value(), 0.01); + const QString capturedSample = window->sampleHex(); + name->setText(QStringLiteral("角度改名")); + QCOMPARE(window->sampleHex(), capturedSample); + name->setText(QStringLiteral("角度")); + scale->setValue(0.02); + QCOMPARE(table->model()->index(fieldRow(0), 4).data().toString(), QStringLiteral("10.26")); + QCOMPARE(window->sampleHex(), capturedSample); + window->findChild(QStringLiteral("protocolTemplateSampleEdit"))->clear(); + scale->setValue(0.01); + const auto frame = parseHexPayload(window->sampleHex()); + const auto parsed = AppProtocol::parseFrame(frame.bytes, definition); + QVERIFY(frame.ok && parsed.ok && parsed.checksumValid); + QCOMPARE(parsed.payload.size(), 5); + QCOMPARE(table->model()->index(fieldRow(0), 4).data().toString(), QStringLiteral("12.34")); + QCOMPARE(table->model()->index(fieldRow(1), 4).data().toString(), QStringLiteral("200")); + QCOMPARE(table->model()->index(fieldRow(2), 4).data().toString(), QStringLiteral("1")); + QCOMPARE(table->model()->index(2, 4).data().toString(), QStringLiteral("01")); + auto *templateName = window->findChild(QStringLiteral("protocolTemplateNameEdit")); + QVERIFY(templateName && templateName->isVisible()); + templateName->setText(QStringLiteral("临时名称")); + QVERIFY(templateName->isVisible()); + templateName->setText(definition.name); + table->selectRow(fieldRow(0)); + auto *add = window->findChild(QStringLiteral("protocolPayloadAdd-u16")); + auto *remove = window->findChild(QStringLiteral("protocolPayloadRemoveField")); + QVERIFY(add && remove); + add->click(); + QCOMPARE(page.currentProtocolTemplateFromUi().payloadFields.last().type, AppPlot::BinaryType::UInt16); + QCOMPARE(page.currentProtocolTemplateFromUi().payloadFields.last().byteOffset, 5); + QCOMPARE( + AppProtocol::parseFrame(parseHexPayload(window->sampleHex()).bytes, page.currentProtocolTemplateFromUi()) + .payload.size(), + 7); + remove->click(); + QCOMPARE(page.currentProtocolTemplateFromUi().payloadFields.size(), 3); + QCOMPARE( + AppProtocol::parseFrame(parseHexPayload(window->sampleHex()).bytes, page.currentProtocolTemplateFromUi()) + .payload.size(), + 5); + } + + void generatedSampleIncludesBigEndianFloatAfterAGap() + { + auto definition = motorTemplate(); + definition.payloadFields = { + {QStringLiteral("value"), 8, AppPlot::BinaryType::Float32, AppPlot::ByteOrder::BigEndian}}; + const auto frame = AppProtocol::exampleFrame(definition); + const auto parsed = AppProtocol::parseFrame(frame, definition); + QVERIFY(parsed.ok && parsed.checksumValid); + QCOMPARE(parsed.payload.size(), 12); + QCOMPARE(parsed.payload.mid(8), QByteArray::fromHex("41480000")); + const auto samples = + AppPlot::extractSamples(AppProtocol::payloadParserConfig(definition), {}, frame, parsed.payload); + QCOMPARE(samples.size(), 1); + QCOMPARE(samples.first().size(), 1); + QCOMPARE(samples.first().first().value, 12.5); + } +}; + +QTEST_MAIN(ProtocolAnalysisTest) +#include "tst_protocol_analysis.moc" diff --git a/tests/tst_protocol_windows.cpp b/tests/tst_protocol_windows.cpp index f9f792c..fd91190 100644 --- a/tests/tst_protocol_windows.cpp +++ b/tests/tst_protocol_windows.cpp @@ -78,10 +78,10 @@ class ProtocolWindowsTest : public QObject QVERIFY(protocolCard && target); QVERIFY(!cards.isEmpty()); QVERIFY(cards.first()->isExpanded()); - auto *connectionAnimation = cards.first()->findChild( - QStringLiteral("expandSettingCardAnimation")); - auto *protocolAnimation = protocolCard->findChild( - QStringLiteral("expandSettingCardAnimation")); + auto *connectionAnimation = + cards.first()->findChild(QStringLiteral("expandSettingCardAnimation")); + auto *protocolAnimation = + protocolCard->findChild(QStringLiteral("expandSettingCardAnimation")); QVERIFY(connectionAnimation && protocolAnimation); QTRY_COMPARE(connectionAnimation->state(), QAbstractAnimation::Stopped); if (target != protocolCard) { @@ -247,8 +247,7 @@ class ProtocolWindowsTest : public QObject QVERIFY(apply->isEnabled()); QCOMPARE(preview->item(0, 2)->text(), QStringLiteral("0")); // Only whole lines from the start are previewed, and the status says so. - const QRegularExpressionMatch match = - QRegularExpression(QStringLiteral("^(\\d+) ")).match(status->text()); + const QRegularExpressionMatch match = QRegularExpression(QStringLiteral("^(\\d+) ")).match(status->text()); QVERIFY(match.hasMatch()); const int previewed = match.captured(1).toInt(); QVERIFY(previewed > 0 && previewed < lines.size()); @@ -299,12 +298,51 @@ class ProtocolWindowsTest : public QObject QCOMPARE(dialog.parserConfig().binarySource, AppPlot::BinarySource::Payload); } + void templateFieldsDrivePlotPreviewAndTemplateSwitching() + { + auto first = AppProtocol::defaultTemplate(); + first.payloadFields = { + {QStringLiteral("angle"), 0, AppPlot::BinaryType::Int16, AppPlot::ByteOrder::LittleEndian, 0.01, -1}}; + auto second = first; + second.name = QStringLiteral("second"); + second.header = QByteArray::fromHex("BB66"); + second.payloadFields = { + {QStringLiteral("speed"), 1, AppPlot::BinaryType::UInt16, AppPlot::ByteOrder::BigEndian, 2, 3}}; + auto config = AppProtocol::payloadParserConfig(first); + config.binaryFields[0].name = QStringLiteral("stale field"); + PlotParserDialog dialog(config); + dialog.setProtocolTemplates({first, second}); + dialog.setProtocolTemplate(first); + dialog.show(); + auto *fields = dialog.findChild(QStringLiteral("plotBinaryFieldsTable")); + auto *preview = dialog.findChild(QStringLiteral("plotPreviewTable")); + auto *templates = dialog.findChild(QStringLiteral("plotFrameTemplateCombo")); + auto *filter = dialog.findChild(QStringLiteral("plotFieldsEdit")); + auto *apply = dialog.findChild(QStringLiteral("plotApplyButton")); + QVERIFY(!fields->isVisible()); + QCOMPARE(preview->item(0, 1)->text(), QStringLiteral("angle")); + QCOMPARE(preview->item(0, 2)->text().toDouble(), 11.34); + filter->setText(QStringLiteral("angle")); + templates->setCurrentIndex(templates->findData(1)); + QVERIFY(filter->text().isEmpty()); + QVERIFY(apply->isEnabled()); + QCOMPARE(preview->item(0, 1)->text(), QStringLiteral("speed")); + QCOMPARE(preview->item(0, 2)->text().toDouble(), 203.0); + apply->click(); + QCOMPARE(dialog.parserConfig().binaryFields, second.payloadFields); + + PlotParserDialog edit(config); + edit.setProtocolTemplate(first); + edit.findChild(QStringLiteral("plotEditTemplateButton"))->click(); + QCOMPARE(edit.result(), PlotParserDialog::EditTemplate); + QCOMPARE(edit.protocolTemplate(), first); + } + void invalidBinaryFieldPreventsConfirmation() { AppPlot::ParserConfig config; config.protocol = AppPlot::Protocol::Binary; - config.binaryFields = {AppPlot::BinaryField{QStringLiteral("temperature"), 0, - AppPlot::BinaryType::UInt16}}; + config.binaryFields = {AppPlot::BinaryField{QStringLiteral("temperature"), 0, AppPlot::BinaryType::UInt16}}; PlotParserDialog dialog(config); auto *fields = dialog.findChild(QStringLiteral("plotBinaryFieldsTable")); auto *apply = dialog.findChild(QStringLiteral("plotApplyButton")); @@ -345,15 +383,17 @@ class ProtocolWindowsTest : public QObject page.showProtocolTemplateWindow(); auto *window = page.m_protocolTemplateWindow; QVERIFY(window && window->isWindow() && window->isVisible()); + window->setSampleHex(QStringLiteral("AA 55 03 10 01 02 03 4D 6E")); auto *structure = window->findChild(QStringLiteral("protocolTemplateStructureView")); auto *table = window->findChild(QStringLiteral("protocolTemplateResultsTable")); - auto *status = window->findChild(QStringLiteral("protocolTemplateParseStatusLabel")); + auto *status = + window->findChild(QStringLiteral("protocolTemplateParseStatusLabel")); auto *sample = window->findChild(QStringLiteral("protocolTemplateSampleEdit")); QVERIFY(structure && table && status && sample); - QCOMPARE(table->model()->rowCount(), 7); - QCOMPARE(table->model()->data(table->model()->index(0, 2)).toString(), QStringLiteral("AA 55")); - QCOMPARE(table->model()->data(table->model()->index(2, 2)).toString(), QStringLiteral("10")); - QCOMPARE(table->model()->data(table->model()->index(3, 2)).toString(), QStringLiteral("01 02 03")); + QCOMPARE(table->model()->rowCount(), 5); + QCOMPARE(table->model()->data(table->model()->index(0, 3)).toString(), QStringLiteral("AA 55")); + QCOMPARE(table->model()->data(table->model()->index(2, 3)).toString(), QStringLiteral("10")); + QCOMPARE(table->model()->data(table->model()->index(3, 3)).toString(), QStringLiteral("01 02 03")); QVERIFY(status->text().contains(AppI18n::text("校验正确"))); QVERIFY(structure->toPlainText().contains(QStringLiteral("AA"))); QVERIFY(structure->toPlainText().contains(QStringLiteral("55"))); @@ -365,8 +405,9 @@ class ProtocolWindowsTest : public QObject QVERIFY(status->text().contains(QStringLiteral("HEX"))); QVERIFY(structure->toPlainText().isEmpty()); sample->setPlainText(QStringLiteral("AA 55 03 10 01")); - QCOMPARE(status->text(), AppProtocol::parseFrame(QByteArray::fromHex("AA55031001"), - AppProtocol::defaultTemplate()).errorMessage); + QCOMPARE( + status->text(), + AppProtocol::parseFrame(QByteArray::fromHex("AA55031001"), AppProtocol::defaultTemplate()).errorMessage); } void frameWindowEditsSavesAndRestoresTemplateAndSample() @@ -402,8 +443,8 @@ class ProtocolWindowsTest : public QObject page.m_protocolTemplateCombo->setCurrentIndex(selected); QCOMPARE(window->sampleHex(), QStringLiteral("AA BB 01 02")); AppSettings settings; - const QJsonDocument templates = QJsonDocument::fromJson( - settings.value(QStringLiteral("protocolTemplate/templates")).toString().toUtf8()); + const QJsonDocument templates = + QJsonDocument::fromJson(settings.value(QStringLiteral("protocolTemplate/templates")).toString().toUtf8()); QCOMPARE(AppProtocol::listFromJson(templates.array()).last().name, QStringLiteral("Saved visual protocol")); const QJsonDocument examples = QJsonDocument::fromJson( settings.value(QStringLiteral("protocolTemplate/exampleFrames")).toString().toUtf8()); @@ -464,9 +505,13 @@ class ProtocolWindowsTest : public QObject return table->model()->data(table->model()->index(row, column)).toString(); }; QCOMPARE(cell(5, 0), AppI18n::text("帧尾")); - QCOMPARE(cell(5, 2), QStringLiteral("0D 0A")); + QCOMPARE(cell(5, 3), QStringLiteral("0D 0A")); const int checksumOffset = int(frame.size()) - 4; - QVERIFY(cell(4, 2).contains(AppI18n::text("覆盖 %1").arg(QStringLiteral("2–%1").arg(checksumOffset - 1)))); + QVERIFY(table->model() + ->index(4, 4) + .data(Qt::ToolTipRole) + .toString() + .contains(AppI18n::text("覆盖 %1").arg(QStringLiteral("2–%1").arg(checksumOffset - 1)))); page.m_protocolChecksumAlgorithmCombo->setCurrentIndex( page.m_protocolChecksumAlgorithmCombo->findData(AppProtocol::checksumNoneKey())); @@ -498,7 +543,8 @@ class ProtocolWindowsTest : public QObject window.setProtocolTemplate(protocol); window.setSampleHex(bytesToHex(frame)); window.show(); - auto *status = window.findChild(QStringLiteral("protocolTemplateParseStatusLabel")); + auto *status = + window.findChild(QStringLiteral("protocolTemplateParseStatusLabel")); QVERIFY(status); QCOMPARE(status->text(), parsed.errorMessage); @@ -583,12 +629,14 @@ class ProtocolWindowsTest : public QObject const auto parsed = AppProtocol::parseFrame(parseHexPayload(window->sampleHex()).bytes, second); QVERIFY2(parsed.ok && parsed.checksumValid, qPrintable(parsed.errorMessage)); page.saveCurrentProtocolTemplate(); - const QJsonObject examples = QJsonDocument::fromJson( - AppSettings().value(QStringLiteral("protocolTemplate/exampleFrames")).toString().toUtf8()).object(); + const QJsonObject examples = + QJsonDocument::fromJson( + AppSettings().value(QStringLiteral("protocolTemplate/exampleFrames")).toString().toUtf8()) + .object(); QCOMPARE(examples.value(second.name).toString(), window->sampleHex()); QVERIFY(examples.value(second.name).toString() != firstSample); - // A sample that is already valid for the next template is kept. + // Templates with the same layout generate the same sample. page.m_protocolTemplateCombo->setCurrentIndex(0); const QString validSample = window->sampleHex(); QVERIFY(AppProtocol::parseFrame(parseHexPayload(validSample).bytes, first).checksumValid); @@ -596,18 +644,19 @@ class ProtocolWindowsTest : public QObject QCOMPARE(window->sampleHex(), validSample); } - void exampleButtonFollowsTheTemplate() + void sampleFollowsProtocolEditsAutomatically() { - ProtocolTemplateWindow window(new QWidget); - auto protocol = AppProtocol::defaultTemplate(); - protocol.header = QByteArray::fromHex("BB66"); - protocol.checksumAlgorithm = QStringLiteral("crc32"); - window.setProtocolTemplate(protocol); - auto *example = - window.findChild(QStringLiteral("protocolTemplateSampleExampleButton")); - QVERIFY(example); - example->click(); - const auto parsed = AppProtocol::parseFrame(parseHexPayload(window.sampleHex()).bytes, protocol); + WorkbenchPage page(nullptr, false, false); + page.showProtocolTemplateWindow(); + page.m_protocolHeaderEdit->setText(QStringLiteral("BB 66")); + page.m_protocolChecksumAlgorithmCombo->setCurrentIndex( + page.m_protocolChecksumAlgorithmCombo->findData(QStringLiteral("crc32"))); + page.saveCurrentProtocolTemplate(); + page.m_protocolHeaderEdit->setText(QStringLiteral("BB 67")); + const auto protocol = page.currentProtocolTemplateFromUi(); + const auto frame = parseHexPayload(page.m_protocolTemplateWindow->sampleHex()).bytes; + QVERIFY(frame.startsWith(QByteArray::fromHex("BB67"))); + const auto parsed = AppProtocol::parseFrame(frame, protocol); QVERIFY2(parsed.ok && parsed.checksumValid, qPrintable(parsed.errorMessage)); } @@ -623,8 +672,8 @@ class ProtocolWindowsTest : public QObject QCOMPARE(page.currentProtocolTemplateFromUi().lengthMode, AppProtocol::LengthMode::FrameLength); page.showProtocolTemplateWindow(); - auto *newButton = - page.m_protocolTemplateWindow->findChild(QStringLiteral("protocolTemplateNewButton")); + auto *newButton = page.m_protocolTemplateWindow->findChild( + QStringLiteral("protocolTemplateNewButton")); QVERIFY(newButton); newButton->click(); const AppProtocol::ProtocolTemplate draft = page.currentProtocolTemplateFromUi(); @@ -641,8 +690,8 @@ class ProtocolWindowsTest : public QObject WorkbenchPage page(nullptr, false, false); page.m_protocolEnabledCheck->setChecked(true); page.showProtocolTemplateWindow(); - auto *newButton = - page.m_protocolTemplateWindow->findChild(QStringLiteral("protocolTemplateNewButton")); + auto *newButton = page.m_protocolTemplateWindow->findChild( + QStringLiteral("protocolTemplateNewButton")); QVERIFY(newButton); newButton->click(); page.m_protocolHeaderEdit->setText(QStringLiteral("CC DD")); @@ -668,6 +717,8 @@ class ProtocolWindowsTest : public QObject QVERIFY(latest->isEnabled()); latest->click(); QCOMPARE(window->sampleHex(), bytesToHex(frame)); + page.m_protocolNameEdit->setText(QStringLiteral("Renamed captured sample")); + QCOMPARE(window->sampleHex(), bytesToHex(frame)); } void restoringTheEditorRefreshesItsPreview() diff --git a/tests/tst_virtual_serial_workbench.cpp b/tests/tst_virtual_serial_workbench.cpp index 9171039..c823051 100644 --- a/tests/tst_virtual_serial_workbench.cpp +++ b/tests/tst_virtual_serial_workbench.cpp @@ -1,6 +1,8 @@ #include "app/core/app_settings.h" #include "app/core/script_runner.h" #include "app/serial/virtual_serial_pair.h" +#include "app/view/protocol_analysis_window.h" +#include "app/view/quick_plot_window.h" #include "app/view/settings_page.h" #include "app/view/workbench_page.h" #include "app/view/workbench_sessions_page.h" @@ -127,6 +129,40 @@ class VirtualSerialWorkbenchTest : public QObject QVERIFY(second->controlStatus().connected); } + void reconnectingDiscardsPartialProtocolFramesAndKeepsHistory() + { + VirtualSerialPair::instance()->setEnabled(true); + WorkbenchPage sender(nullptr, false, false); + WorkbenchPage receiver(nullptr, false, false); + AppProtocol::ProtocolTemplate item; + item.name = QStringLiteral("Raw16"); + item.lengthSize = 0; + item.commandSize = 0; + item.payloadOffset = 0; + item.payloadLength = 2; + item.payloadFields = {{QStringLiteral("value"), 0, AppPlot::BinaryType::UInt16}}; + receiver.m_protocolTemplates = {item}; + receiver.updateProtocolTemplateCombo(0); + receiver.m_protocolEnabledCheck->setChecked(true); + auto *window = receiver.createQuickPlotWindow(AppProtocol::payloadParserConfig(item), &item); + auto *plot = window->findChild(); + auto *values = receiver.m_protocolAnalysisWindow->findChild( + QStringLiteral("protocolAnalysisValues")); + connectUi(sender, VirtualSerialPair::portAName()); + connectUi(receiver, VirtualSerialPair::portBName()); + QString error; + QVERIFY(sender.controlSendBytes(QByteArray::fromHex("341201"), {}, &error)); + QTRY_COMPARE(receiver.controlStatus().receivedBytes, 3); + QCOMPARE(plot->points(), QVector({QPointF(0, 4660)})); + + receiver.controlDisconnect(); + connectUi(receiver, VirtualSerialPair::portBName()); + QVERIFY(sender.controlSendBytes(QByteArray::fromHex("0203"), {}, &error)); + QTRY_COMPARE(receiver.controlStatus().receivedBytes, 5); + QCOMPARE(plot->points(), QVector({QPointF(0, 4660), QPointF(1, 770)})); + QTRY_COMPARE(values->item(0, 3)->text(), QStringLiteral("770")); + } + void autoReplyWorksAcrossThePair() { VirtualSerialPair::instance()->setEnabled(true); diff --git a/tests/tst_workbench_quick_plot.cpp b/tests/tst_workbench_quick_plot.cpp index 5b32b58..dade2e8 100644 --- a/tests/tst_workbench_quick_plot.cpp +++ b/tests/tst_workbench_quick_plot.cpp @@ -1,6 +1,7 @@ #include "app/core/app_i18n.h" #include "app/core/app_settings.h" #include "app/view/plot_parser_dialog.h" +#include "app/view/protocol_template_window.h" #include "app/view/quick_plot_window.h" #include "app/view/workbench_page.h" @@ -554,7 +555,7 @@ class WorkbenchQuickPlotTest : public QObject secondTemplate.payloadLength = 2; auto *first = page.createQuickPlotWindow(parser, &firstTemplate); auto *second = page.createQuickPlotWindow(parser, &secondTemplate); - // Windows with equal templates share one parse of each frame. + // Windows with equal templates decode the same values independently. auto *sameAsFirst = page.createQuickPlotWindow(parser, &firstTemplate); QVERIFY(first && second && sameAsFirst); const QByteArray frame = checkedFrame(); @@ -590,6 +591,121 @@ class WorkbenchQuickPlotTest : public QObject QCOMPARE(second->m_rows.size(), 3); } + void protocolEditorCreatesPlotsFromItsFieldsAndSample() + { + WorkbenchPage page(nullptr, false, false); + auto item = AppProtocol::defaultTemplate(); + item.payloadFields = { + {QStringLiteral("angle"), 0, AppPlot::BinaryType::Int16, AppPlot::ByteOrder::LittleEndian, 0.01, 0}}; + page.m_protocolTemplates = {item}; + page.updateProtocolTemplateCombo(0); + page.showProtocolTemplateWindow(); + const QString sample = page.m_protocolTemplateWindow->sampleHex(); + bool previewMatched = false; + QTimer::singleShot(0, &page, [&]() { + auto *dialog = qobject_cast(QApplication::activeModalWidget()); + if (!dialog) + return; + auto *preview = dialog->findChild(QStringLiteral("plotPreviewTable")); + auto *input = dialog->findChild(QStringLiteral("plotSampleEdit")); + previewMatched = dialog->usesProtocolTemplate() && preview->rowCount() == 1 && + preview->item(0, 1)->text() == QStringLiteral("angle") && input->toPlainText() == sample; + auto *create = dialog->findChild(QStringLiteral("plotApplyButton")); + previewMatched = previewMatched && create->text() == AppI18n::text("创建曲线"); + create->click(); + if (dialog->result() != QDialog::Accepted) + dialog->reject(); + }); + page.m_protocolTemplateWindow + ->findChild(QStringLiteral("protocolTemplateCreatePlotButton")) + ->click(); + QVERIFY(previewMatched); + QVERIFY(page.m_quickPlotWindow); + QCOMPARE(page.m_quickPlotWindow->m_parserConfig.binaryFields, item.payloadFields); + page.handleReceivedData(AppProtocol::exampleFrame(item)); + QCOMPARE(page.m_quickPlotWindow->m_plot->points(), QVector({QPointF(0, 12.34)})); + } + + void templatePlotsSeparateDevicesReassembleFramesAndFollowSavedFields() + { + WorkbenchPage page(nullptr, false, false); + auto item = AppProtocol::defaultTemplate(); + item.commandSize = 0; + item.addressOffset = 3; + item.addressSize = 1; + item.payloadFields = { + {QStringLiteral("angle"), 0, AppPlot::BinaryType::Int16, AppPlot::ByteOrder::LittleEndian, 0.01, 0}}; + page.m_protocolTemplates = {item}; + page.updateProtocolTemplateCombo(0); + auto config = AppProtocol::payloadParserConfig(item); + config.binaryFields.clear(); + config.fields = {QStringLiteral("angle")}; + auto *plot = page.createQuickPlotWindow(config, &item); + QVERIFY(plot); + const auto frameFor = [](int address, int value) { + QByteArray frame = QByteArray::fromHex("AA5502"); + frame += char(address); + frame += char(value & 0xff); + frame += char(value >> 8); + frame += AppChecksum::calculate(frame, QStringLiteral("crc16-modbus"), AppChecksum::ByteOrder::LittleEndian) + .bytes; + return frame; + }; + const auto first = frameFor(1, 1234); + const auto second = frameFor(2, 567); + auto corrupt = first; + corrupt[corrupt.size() - 1] ^= 1; + page.handleReceivedData(first.left(2)); + QVERIFY(plot->m_rows.isEmpty()); + page.handleReceivedData(first.mid(2) + second + corrupt + first); + QCOMPARE(plot->m_rows.size(), 3); + QCOMPARE(plot->m_channelNames, QVector({QStringLiteral("01 / angle"), QStringLiteral("02 / angle")})); + QCOMPARE(plot->m_plot->points(0), QVector({QPointF(0, 12.34), QPointF(2, 12.34)})); + QCOMPARE(plot->m_plot->points(1), QVector({QPointF(1, 5.67)})); + + item.payloadFields = { + {QStringLiteral("level"), 1, AppPlot::BinaryType::UInt8, AppPlot::ByteOrder::LittleEndian, 2, 1}}; + page.fillProtocolTemplateEditor(item); + page.saveCurrentProtocolTemplate(); + QVERIFY(plot->m_rows.isEmpty()); + page.handleReceivedData(first); + QCOMPARE(plot->m_channelNames, QVector({QStringLiteral("01 / level")})); + QCOMPARE(plot->m_plot->points(), QVector({QPointF(0, 9)})); + } + + void unrelatedTemplateSavesKeepDraftPlotConfigurationAndHistory() + { + WorkbenchPage page(nullptr, false, false); + auto saved = AppProtocol::defaultTemplate(); + saved.name = QStringLiteral("A"); + saved.payloadFields = { + {QStringLiteral("angle"), 0, AppPlot::BinaryType::Int16, AppPlot::ByteOrder::LittleEndian, 0.01, 0}}; + auto other = saved; + other.name = QStringLiteral("B"); + page.m_protocolTemplates = {saved, other}; + page.updateProtocolTemplateCombo(0); + auto draft = saved; + draft.payloadFields[0].scale = 0.02; + auto *plot = page.createQuickPlotWindow(AppProtocol::payloadParserConfig(draft), &draft); + const auto frame = AppProtocol::exampleFrame(saved); + page.handleReceivedData(frame); + const auto history = plot->m_plot->points(); + QCOMPARE(history.size(), 1); + page.fillProtocolTemplateEditor(other); + page.saveCurrentProtocolTemplate(); + QCOMPARE(plot->m_parserConfig.binaryFields, draft.payloadFields); + QCOMPARE(plot->m_plot->points(), history); + + // A real save of the associated template still updates the draft plot. + saved.payloadFields[0].scale = 0.03; + page.fillProtocolTemplateEditor(saved); + page.saveCurrentProtocolTemplate(); + QCOMPARE(plot->m_parserConfig.binaryFields, saved.payloadFields); + QVERIFY(plot->m_rows.isEmpty()); + page.handleReceivedData(frame); + QCOMPARE(plot->m_plot->points().first().y(), 37.02); + } + void exportRowsFollowThePlotCapacity() { WorkbenchPage page(nullptr, false, false); diff --git a/third_party/FluentQtWidgets b/third_party/FluentQtWidgets index 4f0ec11..5b7cdb7 160000 --- a/third_party/FluentQtWidgets +++ b/third_party/FluentQtWidgets @@ -1 +1 @@ -Subproject commit 4f0ec11508f1b04f28af268497416657e4557720 +Subproject commit 5b7cdb7fa3af76ca1b84d3e3e8ebb21a1b860e5a