zhunk 1 bulan lalu
induk
melakukan
3698f90620

+ 0 - 65
app_bzy_armhf_7/CLAUDE.md

@@ -1,65 +0,0 @@
-# CLAUDE.md
-
-Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.
-
-**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
-
-## 1. Think Before Coding
-
-**Don't assume. Don't hide confusion. Surface tradeoffs.**
-
-Before implementing:
-- State your assumptions explicitly. If uncertain, ask.
-- If multiple interpretations exist, present them - don't pick silently.
-- If a simpler approach exists, say so. Push back when warranted.
-- If something is unclear, stop. Name what's confusing. Ask.
-
-## 2. Simplicity First
-
-**Minimum code that solves the problem. Nothing speculative.**
-
-- No features beyond what was asked.
-- No abstractions for single-use code.
-- No "flexibility" or "configurability" that wasn't requested.
-- No error handling for impossible scenarios.
-- If you write 200 lines and it could be 50, rewrite it.
-
-Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
-
-## 3. Surgical Changes
-
-**Touch only what you must. Clean up only your own mess.**
-
-When editing existing code:
-- Don't "improve" adjacent code, comments, or formatting.
-- Don't refactor things that aren't broken.
-- Match existing style, even if you'd do it differently.
-- If you notice unrelated dead code, mention it - don't delete it.
-
-When your changes create orphans:
-- Remove imports/variables/functions that YOUR changes made unused.
-- Don't remove pre-existing dead code unless asked.
-
-The test: Every changed line should trace directly to the user's request.
-
-## 4. Goal-Driven Execution
-
-**Define success criteria. Loop until verified.**
-
-Transform tasks into verifiable goals:
-- "Add validation" → "Write tests for invalid inputs, then make them pass"
-- "Fix the bug" → "Write a test that reproduces it, then make it pass"
-- "Refactor X" → "Ensure tests pass before and after"
-
-For multi-step tasks, state a brief plan:
-```
-1. [Step] → verify: [check]
-2. [Step] → verify: [check]
-3. [Step] → verify: [check]
-```
-
-Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
-
----
-
-**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.

+ 2 - 2
q6_felgo_iot/CMakeLists.txt

@@ -61,8 +61,8 @@ find_package(Qt6 COMPONENTS Core Quick SerialPort Sql Multimedia Mqtt TextToSpee
 # Project identifier and version
 # More information: https://felgo.com/doc/felgo-publishing/#project-configuration
 set(PRODUCT_IDENTIFIER "com.yfkj.cb.Q6iot")
-set(PRODUCT_VERSION_NAME "2.8.0")
-set(PRODUCT_VERSION_CODE 80)
+set(PRODUCT_VERSION_NAME "2.8.15")
+set(PRODUCT_VERSION_CODE 94)
 
 # Set either "test" or "publish" stage:产品状态,测试?发布
 set(PRODUCT_STAGE "publish")

+ 1 - 1
q6_felgo_iot/android/AndroidManifest.xml

@@ -1,5 +1,5 @@
 <?xml version="1.0"?>
-<manifest package="com.yfkj.cb.Q6iot" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:dist="http://schemas.android.com/apk/distribution" xmlns:tools="http://schemas.android.com/tools" android:installLocation="auto" android:versionCode="80" android:versionName="2.8.0"> android:versionCode=&quot;0&quot; android:versionName=&quot;0&quot;&gt;
+<manifest package="com.yfkj.cb.Q6iot" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:dist="http://schemas.android.com/apk/distribution" xmlns:tools="http://schemas.android.com/tools" android:installLocation="auto" android:versionCode="94" android:versionName="2.8.15"> android:versionCode=&quot;0&quot; android:versionName=&quot;0&quot;&gt;
     <!-- Enable instant app support -->
     <!-- <module dist:instant="true"/> -->
     <application android:allowBackup="true" android:allowNativeHeapPointerTagging="false" android:hardwareAccelerated="true" android:extractNativeLibs="true" android:name="com.felgo.helper.FelgoApplication" android:label="@string/app_name" android:icon="@drawable/ic_launcher" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:preserveLegacyExternalStorage="true" android:requestLegacyExternalStorage="true">

+ 10 - 0
q6_felgo_iot/docs/MQTT_Protocol.md

@@ -62,6 +62,7 @@
 | `frpc_stop` | -(`params` 可省略) | 否 | 停止 frpc(SIGTERM→3s 后 SIGKILL)。result 为状态 JSON |
 | `frpc_status` | -(`params` 可省略) | 否 | 查询 frpc 状态,result 为 JSON 字符串:`running,pid,uptime_sec,last_exit_code,last_exit_crashed,config_exists,log_tail[]` |
 | `frpc_config` | `toml`,`restart`(1=保存后重启) | 是 | 保存 TOML 配置到设备(AppData/frpc.toml),可选热重启 |
+| `fusion_sw` | `enable`(1=开 0=关) | 否 | 景深(多焦点)融合开关:**默认开**。`enable=0` 时录制视频只分析最清晰帧并上传,跳过景深融合;省略 `enable` 为查询当前状态。参数持久化到 SQLite `config.fusion_enable`,重启保持 |
 
 示例 —— 下发 frpc 配置并立即生效:
 
@@ -96,6 +97,15 @@
 {"jsonrpc":"2.0","method":"ctr_cam","params":{"ExporseTime":8000},"id":7}
 ```
 
+示例 —— 关闭景深融合(只出最清晰帧,缩短处理耗时):
+
+```json
+{"jsonrpc":"2.0","method":"fusion_sw","params":{"enable":0},"id":1}
+```
+
+响应:`"fusion disabled"`;开启回 `"fusion enabled"`;查询(不带 `enable`)回 `"fusion_enable=1"`。
+写库失败时仍即时生效,但响应为错误 `"fusion set, but db save failed"`,需排查数据库。
+
 未知 method 回错误响应 `"unknown method: xxx"`。
 
 ### 2.2 cmd/ext 风格

+ 181 - 0
q6_felgo_iot/docs/Readme.md

@@ -1,3 +1,184 @@
+## 20260922
+    #define APP_VERSION "2.8.15"
+    1.【修改】每次(重新)打开相机后清空上传进度网格:TestPage.qml 的 onCameraStaChanged(sta_cam=true)
+       分支调用 resetUploadGrid(),把 uploadGridModel 的 percent/done 全部复位,
+       避免沿用上一次采集的进度与"已完成"标记
+    2.【修改】版本号升级至 2.8.15
+## 20260922
+    #define APP_VERSION "2.8.14"
+    1、恢复movy指令的信号响应;
+## 20260921
+    #define APP_VERSION "2.8.13"
+    1.【修复】采集结束后多发一条移轴指令(设备端日志:ledoff 之后又收到 slide movz f80):
+       根因在 Frames::mov_x_z_run() 最后一格(z_step==3&&x_step==7)分支——它 emit stopGrabbing(false)
+       关闭相机,而 setCameraSw(false) 会把 z_step/x_step 复位为 0,函数继续往下判断时,
+       末尾的 (z_step<=2 && x_step==0) 分支正好命中复位后的 (0,0) 状态,于是又发出一条 movz f80;
+       修复:关闭相机后立即 return,不再执行后续分支
+    2.【修改】版本号升级至 2.8.13
+## 20260921
+    #define APP_VERSION "2.8.12"
+    1.【修复】图像查看页删除确认框改用 Popup 实现:import Felgo 会遮蔽 QtQuick.Controls 的
+       Dialog(Felgo 自带 Dialog 无 modal 属性),导致 PhotostitcherPage 加载失败
+       (Type PhotostitcherPage unavailable);改用与页面内其它弹窗一致的 Popup
+       (自绘标题+提示+取消/删除按钮)实现二次确认
+    2.【修改】分析/融合处理完成后不再删除录制视频流(取消 2.8.7 的"处理成功即删除 .rawv"):
+       handleRecordStop 仅保存结果图片并 image_num++/mov_x_z_run(),无论成功失败视频流一律保留,
+       需要清理时由用户在图像查看页播放弹窗手动删除
+    3.【新增】自动流程录制增加超时看门狗:对焦完成自动录像后启动单次定时器,
+       超过 RECORD_TIMEOUT_MS(宏定义,默认10000/10S,可用 -DRECORD_TIMEOUT_MS=xxx 覆盖)
+       仍未收到控制板 record_stop(串口异常/主板漏发指令)时,由 Frames::onRecordTimeout
+       自动结束录制,并走与 record_stop 完全相同的"分析->融合->保留视频->上传"流程;
+       stopRecord() 内统一停表,手动停止/收到 record_stop/超时均不会重复触发;
+       手动录制按钮(TestPage)不设超时,可一直录制到手动停止
+    4.【修改】版本号升级至 2.8.12
+## 20260920
+    #define APP_VERSION "2.8.11"
+    1. 相机画面上方增加融合开关状态展示;
+    2. 修改默认的主题;
+    3.【修复】上传进度网格报"无法识别图片序号"(如 20260920150237z0x1_5.jpg):
+       uploadSerialFromPath 原来只匹配 _sharp_N,而景深融合关闭(或融合失败回退上传)时
+       上传的是最清晰帧(命名为 <时间戳>z<z>x<x>_<序号>.jpg),序号解析失败导致该格进度
+       不刷新;改为统一取文件名末尾的 _数字,兼容"最清晰帧/融合图"两种命名,
+       并排除非图片文件(如 .rawv 不参与进度网格)
+    4.【修改】相机提前预热:新增 Frames::warmupCamera(),处理流程重计算(分析+融合)结束、
+       开始保存结果图片时就恢复相机取流(原逻辑要等到 setProcessing(false),即保存+上传
+       全部结束才恢复),让 GigE 相机曝光/传输流水线提前稳定,避免下次采集启动卡顿;
+       预热期间 m_processing 仍为1,取流线程只取帧并立即释放(不拷贝5MB、不调度处理任务),
+       CPU 全部留给后台任务;setProcessing(false) 检测已预热则不再重复 StartGrabbing;
+       取流循环内"停止取流"指令检查上移到拷贝之前,处理/预热期间也能立即响应
+    5.【修改】图片水印改为两行格式(拍照锐化图与录制分析/融合结果图统一):
+       第1行"2026年09月20日 15:02:37  z0x1_5.jpg"(文件名前14位时间戳 + 其后步进与序号),
+       第2行"位置[113.44245,34.22586] 温湿度 [20℃,65%RH]";
+       因 cv::putText 只能画 ASCII、无法渲染中文与℃,改用 QPainter 绘制
+       (QImage 以 Format_BGR888 直接包装 cv::Mat,与OpenCV的BGR字节序一致),
+       字号随图宽自适应(cols/50,2592宽约52px),行距1.5倍字号,仍为红色;
+       新增 param::env_temp/env_humi,mserial 解析 MCU 报文时提取 ext.at/ah 供其使用;
+       经纬度优先 GPS(param::gps_lng/lat),回退基站定位,保留5位小数,无数据以 -- 占位
+    6.【修改】上传改为串行队列执行,一张接一张按顺序上传:
+       CurlFtpUploader 原来每次 uploadFileAsync 都新建一个 QThread,图片队列、补录重传、
+       日志上传三路请求会并发传输(FTP 并发争抢连接易失败/错乱);改为常驻一个上传工作线程
+       + 内部 FIFO 队列,所有请求只入队,由工作线程按提交顺序逐个上传,传完一个再取下一个;
+       finished 信号增加 filePath 参数(第二个参数即为对应文件),Frames 侧新增
+       m_uploadingPath 记录在传文件,仅"当前这张图片"传完才推进图片队列,
+       日志/重传的完成事件不再误推进队列;析构时清空未开始任务并限时回收线程
+    7.【修改】版本号升级至 2.8.11
+    #define APP_VERSION "2.8.7"
+    1. 【修复】没有更新清晰度值导致相机超时主动关闭,在录制开始和结束触发清晰度信号,并且把超时时间修改为180S;
+    2.【修改】录制改为存"相机原始帧"(Bayer8 / YUYV)而不是转换后的 BGRA:
+       单帧 19.22MB→4.81MB(约1/4)、36帧文件 692MB→173MB,写盘吞吐需求同比降低;
+       文件头偏移28新增 pixelFormat 字段(0=BGRA8 兼容旧文件,1~4=Bayer*,5=YUYV),
+       解马赛克推迟到分析/融合与回放阶段,只对真正用到的帧执行(评分/融合/播放按格式解码)
+    3.【新增】录制写盘异步化:新增 RawRecordWriter(后台写线程 + 有界队列,默认内存预算192MB),
+       取流线程只做深拷贝入队即返回,写盘与磁盘抖动不再阻塞取流;
+       队列超出预算时丢弃新帧并计数告警(宁可少几帧也不让内存失控)
+    4.【新增】录制性能诊断:stopRecord 输出"平均帧间隔 / 入队耗时 / 格式转换耗时 /
+       单帧大小 / 等效写盘带宽",用于判断帧率瓶颈在相机产帧、CPU转换还是磁盘IO
+    5.【修复】录制改存相机原始帧后,分析/融合/播放保存的图片颜色不对(黄色发蓝):
+       Bayer 解马赛克通道选反——旧 BGRA 链路是"COLOR_BayerXX2BGRA 输出按 RGBA 解释",
+       颜色正确,可推出 OpenCV 的 Bayer 命名与海康相差一个 R/B(XX2BGR 输出实际是
+       RGB 序);decodeRawBufferToBgr 由 XX2BGR 改为 XX2RGB(输出恰为正确 BGR 字节序),
+       评分路径与播放路径同步修正;BGRA 旧文件路径不受影响
+    6.【修改】分析/融合处理完成后删除录制视频流文件(恢复被 #if 0 屏蔽的原逻辑):
+       handleRecordStop 结果保存成功即删除 .rawv(体积大,不再保留);
+       删除失败仅告警,不影响结果图片上传;分析/融合失败仍保留录制文件以便重试
+    7.【修改】版本号升级至 2.8.7
+## 20260919
+    #define APP_VERSION "2.8.5"
+    1.【修改】录制视频流清晰度评分提速:新增 readRawVideoFrameSampled(),评分只按行采样
+       读帧(每4行取1行),评分阶段IO降约75%;实测排序与全量读取一致(Spearman≈0.99、
+       最清晰帧不变),评分结果逐帧缓存供融合阶段复用
+    2.【修改】融合不再重复扫描视频流:processRecordedVideo 分析得到的最清晰帧序号与逐帧
+       评分直接传给 fuseRawVideoFrames()(原流程会再全量扫描一遍,725MB视频相当于多一倍
+       IO与评分耗时);RawVideoPlayer::fuseVideoFrames() 同步调整,参与融合帧上限 8→12
+    3.【修改】参与融合的帧不再固定取最清晰帧±4:新增 selectFuseFrames(),按评分曲线
+       (评分>2倍中位数)从最清晰帧向两侧圈定"有效对焦区间"(扫过焦面的连续段)整段参与融合,
+       超过上限时等步长均匀抽样;无对焦扫描(整段清晰度接近)时回退原中心邻域逻辑。
+       实测背景噪声 3.62→3.29,对帧数更多的长扫描录制更鲁棒
+    4.【修复】融合图细节不如最清晰帧:权重平滑实现修正——原实现把权重缩到小图后用固定
+       sigma=3 平滑,等效 sigma≈90(5MP 图上),权重被严重摊平、清晰像素无法独占权重,
+       失焦帧的模糊像素渗入导致细节被稀释(实测细节仅保持最清晰帧的63%);改为显式指定
+       等效 sigma≈10(min(rows,cols)/192,降采样比固定16),权重对比度指数 wp 2.5→3.5。
+       实测细节保持 63%→87%、景深扩展 +49%、背景噪声持平(3.27→3.24)
+    5.【新增】景深融合 MQTT 开关 fusion_sw:
+       {"jsonrpc":"2.0","method":"fusion_sw","params":{"enable":0},"id":1}
+       默认开;参数持久化到 sqlite config.fusion_enable(老库启动自动补列、空表自动补默认行),
+       关闭后录制视频只分析最清晰帧并上传、跳过景深融合;省略 enable 为查询当前开关状态
+    6.【修改】config 表新增 ensureColumnExist()/ensureConfigRow():老版本数据库平滑升级
+       (PRAGMA table_info 检查后 ALTER TABLE 补列),并保证表内至少一行默认配置
+       (config 表无主键、配置为整表 UPDATE,空表会导致下发参数只在内存生效、重启丢失)
+    7.【修改】docs/MQTT_Protocol.md 同步 fusion_sw 方法说明、示例与各分支响应
+    8.【修改】录制改为存"相机原始帧"(Bayer8 / YUYV)而不是转换后的 BGRA:
+       单帧 19.22MB→4.81MB(约1/4)、36帧文件 692MB→173MB,写盘吞吐需求同比降低;
+       文件头偏移28新增 pixelFormat 字段(0=BGRA8 兼容旧文件,1~4=Bayer*,5=YUYV),
+       解马赛克推迟到分析/融合与回放阶段,只对真正用到的帧执行(评分/融合/播放按格式解码)
+    9.【新增】录制写盘异步化:新增 RawRecordWriter(后台写线程 + 有界队列,默认内存预算192MB),
+       取流线程只做深拷贝入队即返回,写盘与磁盘抖动不再阻塞取流;
+       队列超出预算时丢弃新帧并计数告警(宁可少几帧也不让内存失控)
+    10.【新增】录制性能诊断:stopRecord 输出"平均帧间隔 / 入队耗时 / 格式转换耗时 /
+       单帧大小 / 等效写盘带宽",用于判断帧率瓶颈在相机产帧、CPU转换还是磁盘IO
+    11.【修改】版本号升级至 2.8.5
+## 20260918
+    #define APP_VERSION "2.8.4"
+    1.【修改】启动时存储空间检测改为循环覆写:原"图片占用≥1GB即清空全部图片"(一次性、粗暴)
+       改为按存储卷剩余可用空间判断,不足1GB时按时间由旧到新逐组删除归档图片
+       (一组=一个归档目录,即 年/月/日/时间戳),直到剩余空间充足或已无可删除的组
+    2.【新增】拍照前检测剩余存储空间:Frames::saveMatAsJpeg 内(与拍照互斥锁同一临界区)
+       调用 SerialThread::ensureStorageSpace(),不足1GB时先删除最老的一组图片再保存,
+       避免存储写满导致拍照失败
+    3.【修改】循环覆写只删图片,录制视频流(.rawv)不参与删除:删除时跳过 .rawv,
+       含视频流的归档目录因非空而保留;新增 SerialThread::getFreeSpace()/
+       ensureStorageSpace()/collectArchiveGroups()/removeGroupFiles() 静态接口
+    4.【新增】图像查看页视频播放弹窗新增"删除"按钮:二次确认(QML Dialog)后删除当前播放的
+       录制视频流文件(RawVideoPlayer::removeCurrentFile(),新增 fileRemoved 信号),
+       删除后自动关闭播放、从图片网格移除该条目并重新加载归档树;
+       分析/融合结果图片不受影响;原"关闭"按钮颜色由红色改为灰色以区分
+    5.【修改】版本号升级至 2.8.4
+## 20260915
+    #define APP_VERSION "2.8.3"
+    1.【新增】测试维护页新增录制按钮(相机画面右下角,抓图按钮左侧):点击把相机画面录制为
+       未压缩原始视频流,再次点击停止并保存到文件系统(相机打开时创建的归档目录,文件名
+       record_yyyyMMddhhmmss.rawv);C++新增 Frames::startRecord()/stopRecord() 与 recording
+       属性,录制由处理线程同步写盘(内存占用恒定),停止时回填文件头(帧数/平均帧率)
+    2.【新增】图像查看页支持查看播放原始视频流:新增 RawVideoPlayer 类(import Frames 0.1,
+       绑定 VideoOutput.videoSink 逐帧回放),归档树放行 .rawv 文件,单击即播放
+    3.【新增】播放界面新增"分析"/"融合"按钮:分析=按聚焦综合评分选出最清晰帧;融合=以最清晰帧
+       为中心向上/下邻域取8帧做景深融合;结果均锐化(Unsharp Mask)+对比度增强后按
+       <视频时间戳>z0x0[_sharp]_<序号>.jpg 保存到视频所在目录
+    4.【修改】拍照锐化图左上角水印颜色由浅绿色改为红色,字号由1.2增大到3.0(基线y=40调整为y=50)
+    5.【修改】evaluateFocusScore 增加评分方式参数:新增 FocusMetric 枚举(Combined 三项组合/
+       LaplacianVar/Tenengrad/Brenner 单项),单项模式最终分值取该指标归一化值;组合模式权重
+       可通过 wLaplacian/wTenengrad/wBrenner 传入(自动归一化,默认0.5/0.3/0.2),不传参保持原行为
+    6.【修复】分析与融合结果图片颜色异常(黄色偏蓝):根因是取原始视频帧时按BGRA硬转换,
+       而视频帧实际字节序与预览/拍照一致(Format_RGBA8888),导致R/B通道颠倒;
+       改为复用与预览/拍照完全相同的取图路径(QVideoFrame+toImage+QImage转BGR),不再假设字节序;
+       同时修正 findSharpestFrameIndex 中 evaluateFocusScore 调用的缺参语法错误
+    7.【新增】录制开始后向控制板发送 JSON-RPC 指令 record_start
+       (Frames::startRecord() 中 emit serial_data(m_json.MakeJsonRPC("record_start","")))
+    8.【新增】串口收到 JSON-RPC 方法 record_stop 后自动处理录制视频流:
+       SerialThread 新增 recordStop 信号(main.cpp 连到 Frames::handleRecordStop),
+       流程为:停止录制 -> 分析最清晰帧 + 景深融合(后台线程,结果按归档命名保存到视频同目录)
+       -> 若处理成功则删除录制文件(.rawv体积大) -> 结果图片入库(signal_cache_image)
+       并加入上传队列上传(优先融合图,融合失败自动回退上传分析图)
+    9.【修改】分析/融合处理期间挂起相机画面输出:processFrameAsync 检测到 processing 直接返回,
+       把CPU让给后台重计算任务;TestPage 用进度遮罩(转圈+处理消息+百分比进度条)替代画面,
+       进度经 Frames::processMessage/processPercent 上报(逐帧分析进度+融合/保存阶段进度),
+       处理结束自动恢复画面
+    10.【修改】record_stop 处理结果的保存命名改为与拍照一致(存到相机归档目录 picture_path_floader):
+       最清晰图 name_sharp = <ts>z<z>x<x>_<序号>.jpg,融合图 name_fuse = <ts>z<z>x<x>_sharp_<序号>.jpg,
+       两者共用同一 image_num;保存成功后 image_num++ 并执行 mov_x_z_run() 移动到下一个采集位置;
+       上传优先用融合图(name_fuse),融合失败回退上传最清晰图(name_sharp)
+    11.【修复】景深融合结果噪声严重(细颗粒麻点,实测平坦区噪声3倍、梯度能量10倍):
+       1)fuseAdvanced 内部结尾已做 unsharpMask(2.0/3.0)+enhanceContrast,分析/融合流程又套了
+         一层 enhanceResultImage 导致"双重锐化+双重CLAHE",融合结果改为直接保存不再重复处理;
+       2)fuseAdvanced 权重阶段的全图 min-max 拉伸在范围极小时(各帧焦点几乎一致,如录像抽帧)
+         会把权重噪声放大成逐像素 0/1 硬切换,改为仅在动态范围足够大时才做该硬选择
+    12.【修改】预览降帧、录制提帧:processFrameAsync 中预览按 kPreviewIntervalMs(默认200ms≈5fps)
+       限流,未到推送时刻连 QVideoFrame 的 map/memcpy(5MP约20MB/帧)都跳过;
+       录制写盘提前到预览之前执行,不与预览抢时间;拍照仍按需构造 QVideoFrame
+    13.【修改】分析/融合期间暂停相机取流:Frames::setProcessing 在置位时调用 MV_CC_StopGrabbing
+       停流(省CPU/相机带宽),结束时 MV_CC_StartGrabbing 恢复;取流线程以 m_grabPaused 标志
+       忽略停流导致的取帧失败(不计超时、不误关相机),恢复后自动继续取流
+    14.【修改】版本号升级至 2.8.3
 ## 20260913
     #define APP_VERSION "2.8.1"
     1. 串口发送日志增加发送内容的打印;

+ 4 - 0
q6_felgo_iot/header/TreeModel.h

@@ -120,6 +120,10 @@ private:
     };
 
     Q_INVOKABLE void loadRootFolders();
+    //判断是否为原始视频流文件(.rawv),归档树中与图片一样作为可查看文件列出
+    static bool isRawVideoFile(const QString &fileName) {
+        return fileName.endsWith(".rawv", Qt::CaseInsensitive);
+    }
     void loadMonths(TreeItem *yearItem, const QModelIndex &parentIndex);
     void loadDays(TreeItem *monthItem, const QModelIndex &parentIndex);
     void loadAlbums(TreeItem *dayItem, const QModelIndex &parentIndex);

+ 27 - 2
q6_felgo_iot/header/app_curlFunc.h

@@ -4,6 +4,11 @@
 
 #include <QObject>
 #include <QString>
+#include <QMutex>
+#include <QWaitCondition>
+#include <QThread>
+#include <atomic>
+#include <deque>
 #include <curl/curl.h>
 
 class CurlFtpUploader : public QObject
@@ -21,7 +26,8 @@ public:
                       int port,
                       const QString &remotePath);
 
-    // 异步上传文件(非阻塞)
+    // 提交上传文件(非阻塞):文件进入内部串行队列,由后台线程一张一张按提交顺序上传。
+    // 无论来自图片队列、补录重传还是日志上传,都不会并发传输(并发会争抢FTP连接导致失败)
     void uploadFileAsync(const QString &localFilePath);
     // 补录/重传重载:携带入库时记录的父目录,据此对齐远端归档目录
     void uploadFileAsync(const QString &localFilePath, const QString &parentPath);
@@ -29,13 +35,25 @@ public:
 signals:
     void downloadStart(const QString &tips);
     void progressChanged(double uploadedPercent, const QString &filePath);  // 进度百分比 (0.0 ~ 100.0) 与上传文件路径
-    void finished(bool success, const QString &error); // 完成信号
+    // 完成信号: success=是否成功; filePath=对应文件(调用方据此判断是哪一张传完);
+    // error=失败原因(成功时为空)
+    void finished(bool success, const QString &filePath, const QString &error);
     void sglProgress(double val,double timeLeft,double speed);  //进度信号
 private:
     // 静态回调函数(供 CURL 调用)
     static size_t readCallback(char *buffer, size_t size, size_t nitems, void *userdata);
     static int progressCallback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow);
 
+    // 上传任务(一张图一条)
+    struct UploadJob {
+        QString localFilePath;
+        QString parentPath;
+    };
+    // 提交任务到串行队列并唤醒工作线程
+    void enqueueJob(const QString &localFilePath, const QString &parentPath);
+    // 工作线程主循环:按FIFO顺序逐个上传
+    void runLoop();
+
     // 内部上传逻辑
     void performUpload(const QString &localFilePath);
     // 供补录/重传使用,parentPath 为入库时记录的父目录(为空时退回按文件自身父目录推导)
@@ -49,6 +67,13 @@ private:
     QString m_remotePath;
     QString update_type;
     QString m_currentFilePath;   // 当前正在上传的文件路径,用于进度信号携带
+
+    // 串行上传队列(工作线程消费)
+    QMutex m_jobMutex;
+    QWaitCondition m_jobCond;
+    std::deque<UploadJob> m_jobs;
+    std::atomic<bool> m_stopping{false};
+    QThread *m_worker = nullptr;
 };
 
 

+ 225 - 2
q6_felgo_iot/header/cameramanager.h

@@ -25,6 +25,9 @@
 #include <QQuickImageProvider>
 #include <QQmlImageProviderBase>
 #include <QImage>
+#include <QFile>
+#include <QElapsedTimer>
+#include <QVideoFrame>
 #include <pthread.h>
 //海康
 // #pragma pack(push, 4)
@@ -33,6 +36,12 @@
 #include <MvCameraControl.h>
 #include <PixelType.h>
 
+#include <QMutex>
+#include <QWaitCondition>
+#include <QAtomicInt>
+#include <deque>
+#include <utility>
+
 //https://github.com/saki4510t/UVCCamera/pulls
 //https://gitee.com/dengly/UVCCamera
 //USBCamera:   https://blog.csdn.net/hanshiying007/article/details/124118486
@@ -51,6 +60,13 @@
 #define m_foucus_step_max 5
 #define focus_step_max 30
 
+//自动流程录制(对焦完成后自动录像)的最长录制时长,单位ms:
+//超过该时长仍未收到控制板的 record_stop 指令,则自动结束录制(走与 record_stop 相同的分析/融合流程)
+//可通过编译选项 -DRECORD_TIMEOUT_MS=xxx 覆盖
+#ifndef RECORD_TIMEOUT_MS
+#define RECORD_TIMEOUT_MS 10000     //10S
+#endif
+
 //性能提升
 //https://blog.csdn.net/u012915226/article/details/115733359
 //https://blog.csdn.net/u012915226/article/details/121745861?spm=1001.2014.3001.5501
@@ -63,6 +79,53 @@
 
 namespace Qt6QCamera {
 
+// ==================== 录制视频流异步写盘 ====================
+//取流线程只做"深拷贝入队",写盘由后台线程完成:
+//  - 写盘不再阻塞取流,磁盘抖动/瞬时带宽不足不会直接压低录制帧率
+//  - 队列按内存预算限流(默认192MB),超出时丢弃新帧并计数(保实时性)
+//  - 配合"存相机原始帧(Bayer8 5MB/帧,而非BGRA 20MB/帧)"可把写盘吞吐需求降到1/4
+class RawRecordWriter : public QThread
+{
+public:
+    explicit RawRecordWriter(QObject *parent = nullptr);
+    ~RawRecordWriter() override;
+
+    //打开文件并写入占位文件头(由UI线程调用)
+    bool begin(const QString &path);
+    //入队一帧(内部深拷贝,调用方可立即复用传入矩阵)
+    void enqueue(const cv::Mat &frame, int pixelFormat);
+    //排空队列+回填文件头+关闭文件,返回写入帧数;出参返回帧尺寸、行字节数与像素格式
+    //帧率由内部计时(begin→finish)自行换算,调用方无需关心
+    int finish(int &width, int &height, int &stride, int &pixelFormat);
+    //队列内存预算(字节),超出后丢弃新帧
+    void setBudgetBytes(qint64 bytes);
+    qint64 droppedFrames() const { return m_dropped.loadRelaxed(); }
+    bool isActive() const { return m_active; }
+
+protected:
+    void run() override;
+
+private:
+    QMutex            m_mutex;
+    QWaitCondition    m_cond;
+    std::deque<std::pair<cv::Mat,int>> m_queue;
+    qint64            m_queuedBytes = 0;
+    qint64            m_budget = 192LL * 1024 * 1024;   //默认192MB
+    bool              m_stop = false;
+    bool              m_flushing = false;
+    bool              m_active = false;
+    QFile             m_file;
+    QString           m_path;
+    int               m_width = 0;
+    int               m_height = 0;
+    int               m_stride = 0;
+    int               m_pixelFormat = 0;
+    int               m_count = 0;
+    QAtomicInt        m_dropped = 0;
+    QElapsedTimer     m_elapsed;
+};
+
+
 
 // 定义一个包含信号的发送类
 class SenderCustom : public QObject {
@@ -133,6 +196,11 @@ class Frames :public QObject//, public QQuickImageProvider //QObject  //
     Q_PROPERTY( bool auto_clicked READ auto_clicked WRITE setChange NOTIFY btnStatusChanged )
     Q_PROPERTY( bool camera_sw READ camera_sw WRITE setCameraSw NOTIFY cameraStaChanged )
     Q_PROPERTY(QString cam_ExposureTime READ cam_ExposureTime WRITE setExposureTime NOTIFY exposureTimeChanged)
+    Q_PROPERTY( bool recording READ recording NOTIFY recordingChanged )
+    //录制视频流的分析/融合处理中(期间挂起相机画面输出并在界面显示进度)
+    Q_PROPERTY( bool processing READ processing NOTIFY processingChanged )
+    Q_PROPERTY( QString processMessage READ processMessage NOTIFY processProgressChanged )
+    Q_PROPERTY( int processPercent READ processPercent NOTIFY processProgressChanged )
 
 public:
     static void registerQmlType();
@@ -166,6 +234,16 @@ public:
     Q_INVOKABLE void captureImage();
     //抓图按钮:模拟MCU拍照指令(camera_tc=1),下一帧按序号保存/锐化/上传
     Q_INVOKABLE void manualCapture();
+    //录制原始(未压缩)视频流:开始录制;停止时回填文件头并把视频流保存到文件系统
+    Q_INVOKABLE bool startRecord();
+    Q_INVOKABLE void stopRecord();
+    bool recording() const { return m_recording; }
+    //处理中标志(取流线程读取,故用原子量)
+    bool processing() const { return m_processing.loadRelaxed() != 0; }
+    QString processMessage() const { return m_processMessage; }
+    int processPercent() const { return m_processPercent; }
+    //收到控制板 record_stop 指令:停止录制 -> 清晰度分析 -> 景深融合 -> 删除录制文件 -> 上传融合图片
+    Q_INVOKABLE void handleRecordStop();
     //inline ImageProvider *getImageProvider() { return m_pImgProvider; }
     //ImageProvider* imageProvider() const;
     static void ImageCallBackEx(unsigned char * pData, MV_FRAME_OUT_INFO_EX* pFrameInfo, void* pUser);
@@ -215,6 +293,12 @@ signals:
     void signal_cache_image(const QString &path);
     void signal_sharp_processed(const QString &name_sharp);  //锐化/对比度后台处理完成,回主线程统一入队入库
     void stepCountChanged(const QString step);
+    void recordingChanged();
+    void processingChanged();
+    //分析/融合进度变化(主线程发出)
+    void processProgressChanged();
+    //录制结束,视频流已保存到path
+    void recordFileSaved(const QString &path);
 public slots:
 
     void onMovDone(const QString stepcount){
@@ -243,8 +327,8 @@ public slots:
         emit stepCountChanged(stepcount);
     }
     //    void parseFrame(const cv::Mat& frame);
-    void upload_handle(void);
-    void handle_reult_upload(bool success, const QString &error);
+    Q_INVOKABLE void upload_handle(void);
+    Q_INVOKABLE void handle_reult_upload(bool success, const QString &filePath);   //filePath: 传完的文件(由上传器 finished 带回)
 
     void onFPSUpdated(double fps);
 private slots:
@@ -263,6 +347,20 @@ private slots:
     void displayFrame(const QVideoFrame &frame);
     void mov_x_z_run();
     void processFrameAsync(const RawFrame& frame);
+    //录制中:把当前未压缩原始帧写入视频流文件(处理线程调用)
+    //录制入队:frame 为相机原始帧(Bayer8 CV_8UC1 / YUYV CV_8UC2)或已转换 BGRA,
+    //pixelFormat 见 RawPixelFormat;内部深拷贝后由后台线程写盘,不阻塞取流
+    void enqueueRecordFrame(const cv::Mat &frame, int pixelFormat);
+    //录制超时(超过 RECORD_TIMEOUT_MS 未收到 record_stop):自动结束录制并处理视频流
+    void onRecordTimeout();
+
+    //*提前恢复相机取流(预热):在保存结果图片阶段就 StartGrabbing,
+    //避免等处理全部结束(含上传)才恢复导致下次采集启动卡顿*//
+    void warmupCamera();
+    //置处理中标志(挂起相机画面输出)
+    void setProcessing(bool on);
+    //更新处理进度(仅主线程调用)
+    void setProcessProgress(const QString &message, int percent);
 private:
     Q_DISABLE_COPY( Frames )
 
@@ -287,6 +385,8 @@ private:
     QFuture<void> m_grabThread;
     //独立上传队列:与param::ptlist(拼接输入)隔离,每保存一张锐化/对比度图立即入队逐张上传
     QStringList m_uploadQueue;
+    //正在上传的文件(图片队列用):上传完成回调据此判断是哪一张传完、是否推进队列
+    QString m_uploadingPath;
     bool m_isUploading = false;   //是否正在上传,防止并发启动多个上传线程
     QJniObject *jClass;
 
@@ -319,6 +419,41 @@ private:
     QString picture_path_floader;
     QVector<cv::Mat> m_frame_buffer;
 
+    //原始视频流录制:取流线程只把"相机原始帧"入队(Bayer8/YUYV,体积远小于BGRA),
+    //由 RawRecordWriter 后台线程写盘,停止时回填文件头
+    bool m_recording = false;
+    RawRecordWriter m_recordWriter;
+    QString m_recordPath;
+    int m_recordWidth = 0;
+    int m_recordHeight = 0;
+    int m_recordStride = 0;
+    int m_recordFrameCount = 0;
+    QElapsedTimer m_recordElapsed;
+    //本次停止录制后是否丢弃录制文件(record_stop 流程处理完即删除,不再提示"已保存")
+    bool m_recordDiscard = false;
+    //录制性能诊断(定位录制帧率瓶颈:相机产帧/Bayer转换/写盘 各占多少)
+    qint64 m_diagFrames = 0;      //已统计帧数
+    qint64 m_diagWriteUsec = 0;   //写盘累计耗时(us)
+    qint64 m_diagCvtUsec = 0;     //Bayer转换累计耗时(us)
+    qint64 m_diagGapMsec = 0;     //相邻帧到达间隔累计(ms,帧数-1个间隔)
+    qint64 m_diagLastFrameMsec = 0;
+    //保护录制状态与文件写入,startRecord/stopRecord(UI线程)与writeRecordFrame(处理线程)互斥
+    mutable QMutex m_recordMutex;
+    //录制超时看门狗:自动流程录制期间启动,超时未收到 record_stop 则自动结束录制
+    QTimer *m_recordTimeout = nullptr;
+
+    //分析/融合处理中:取流端据此挂起转换与画面输出,把CPU让给后台重计算任务
+    QAtomicInt m_processing = 0;
+    //保存结果图片阶段已提前恢复取流(相机预热):1=已预热,setProcessing(false) 时不再重复 StartGrabbing
+    QAtomicInt m_cameraWarmup = 0;
+    QString m_processMessage;
+    int m_processPercent = 0;
+
+    //预览降帧:上次推送预览画面的时刻(ms),由多个取流处理线程读写
+    QAtomicInteger<qint64> m_lastPreviewMs = 0;
+    //取流暂停标志:分析/融合期间停止相机取流(SDK停流),结束后恢复取流
+    QAtomicInt m_grabPaused = 0;
+
     int testJNI();
     int checkPermission(void)
     {
@@ -521,6 +656,94 @@ private:
     }
 
 }; // class Frames
+
+//! 原始视频流(.rawv)播放器:逐帧读取未压缩的原始帧并推送到 QVideoSink 播放
+class RawVideoPlayer : public QObject
+{
+    Q_OBJECT
+    QML_ELEMENT
+    Q_PROPERTY( QVideoSink* videoSink READ videoSink WRITE setVideoSink NOTIFY videoSinkChanged )
+    Q_PROPERTY( bool playing READ playing NOTIFY playingChanged )
+    Q_PROPERTY( bool loaded READ loaded NOTIFY loadedChanged )
+    Q_PROPERTY( int position READ position NOTIFY positionChanged )
+    Q_PROPERTY( int frameCount READ frameCount NOTIFY frameCountChanged )
+    Q_PROPERTY( QString source READ source NOTIFY sourceChanged )
+    Q_PROPERTY( bool busy READ busy NOTIFY busyChanged )
+
+public:
+    explicit RawVideoPlayer(QObject *parent = nullptr);
+
+    QVideoSink* videoSink() const { return m_videoSink; }
+    void setVideoSink(QVideoSink *newVideoSink);
+
+    bool playing() const { return m_playing; }
+    bool loaded() const { return m_loaded; }
+    int position() const { return m_position; }
+    int frameCount() const { return m_frameCount; }
+    QString source() const { return m_source; }
+    bool busy() const { return m_busy; }
+
+    //打开原始视频流文件,成功后可调用 play()
+    Q_INVOKABLE bool open(const QString &path);
+    Q_INVOKABLE void play();
+    Q_INVOKABLE void pause();
+    Q_INVOKABLE void stop();
+    //定位到指定帧(立即刷新画面)
+    Q_INVOKABLE void seek(int frameIndex);
+    Q_INVOKABLE void close();
+    //删除当前打开/播放的录制视频流文件(.rawv),结果图片不受影响
+    Q_INVOKABLE bool removeCurrentFile();
+    //判断文件是否为原始视频流(.rawv)
+    Q_INVOKABLE bool isRawVideo(const QString &path) const;
+    //分析:识别视频帧中最清晰的一帧,锐化+对比度增强后保存为图片(与视频同目录)
+    Q_INVOKABLE void analyzeSharpestFrame();
+    //融合:在最清晰帧上下邻域选帧做景深融合,锐化+对比度增强后保存为图片(与视频同目录)
+    Q_INVOKABLE void fuseVideoFrames();
+
+signals:
+    void videoSinkChanged();
+    void playingChanged();
+    void loadedChanged();
+    void positionChanged();
+    void frameCountChanged();
+    void sourceChanged();
+    void busyChanged();
+    //分析结束:path为空表示失败,成功时图片已保存到path
+    void analyzeFinished(const QString &path);
+    //融合结束:path为空表示失败,成功时图片已保存到path
+    void fuseFinished(const QString &path);
+    //当前视频流文件已被删除,path为被删除的文件路径
+    void fileRemoved(const QString &path);
+
+private slots:
+    void onTick();
+
+private:
+    //读取并推送当前帧,失败返回false
+    bool pushFrame();
+    void setBusy(bool busy);
+    //结果图片路径,命名与拍照图片一致:<视频时间戳>z0x0[_sharp]_<序号>.jpg
+    QString resultPath(int serial, bool sharp) const;
+
+    QFile m_file;
+    QTimer m_timer;
+    QVideoSink *m_videoSink = nullptr;
+    QString m_source;
+    int m_width = 0;
+    int m_height = 0;
+    int m_stride = 0;
+    int m_fps = 0;
+    int m_frameCount = 0;
+    int m_position = 0;
+    //视频流内帧的像素格式(见 RawPixelFormat),0=BGRA8 兼容旧文件
+    int m_pixelFormat = 0;
+    bool m_loaded = false;
+    bool m_playing = false;
+    //分析/融合任务进行中(进行中时不重复触发)
+    bool m_busy = false;
+    //同一视频内结果序号:分析结果与融合结果成对(_sharp_后缀)
+    int m_resultSerial = 0;
+};
 } /* namespace Qt6QCamera */
 
 Q_DECLARE_METATYPE(cv::Mat)

+ 21 - 2
q6_felgo_iot/header/m_opencv.h

@@ -42,10 +42,29 @@ public:
         double laplacianVar;     // Laplacian 方差(显微聚焦金标准)
         double tenengrad;        // Tenengrad 梯度能量
         double brenner;          // Brenner 二阶差分能量
-        double combinedScore;    // 综合评分(越大越清晰)
+        double combinedScore;    // 最终评分(越大越清晰):按所选评分方式计算
     };
+    // 评分方式:可选单项指标,或三项加权组合
+    //   Combined     —— 三项加权组合(默认,权重 wLaplacian/wTenengrad/wBrenner)
+    //   LaplacianVar —— 仅 Laplacian 方差
+    //   Tenengrad    —— 仅 Tenengrad 梯度能量
+    //   Brenner      —— 仅 Brenner 二阶差分能量
+    enum class FocusMetric {
+        Combined,
+        LaplacianVar,
+        Tenengrad,
+        Brenner
+    };
+    Q_ENUM(FocusMetric)
+
     // 推荐用 evaluateFocusScore 替换单指标的 brenner/Laplacian/Tenengrad
-    MicroscopeFocusMetrics evaluateFocusScore(const cv::Mat& image);
+    // metric: 评分方式,单项时 combinedScore 即该项的归一化分值(与组合模式同尺度,便于比较)
+    // wLaplacian/wTenengrad/wBrenner: 仅 Combined 模式生效的权重,会自动归一化
+    MicroscopeFocusMetrics evaluateFocusScore(const cv::Mat& image,
+                                              FocusMetric metric = FocusMetric::Combined,
+                                              double wLaplacian = 0.5,
+                                              double wTenengrad = 0.3,
+                                              double wBrenner = 0.2);
 
     // ==================== 对比度增强算法 ====================
     // 1) CLAHE(限制对比度的自适应直方图均衡)—— 显微最常用,处理不均匀照明

+ 8 - 2
q6_felgo_iot/header/main.h

@@ -27,7 +27,6 @@
 #include <QAudioOutput>
 //JSON
 #include <QJsonDocument>
-
 #include <opencv2/core/core.hpp>
 #include <opencv2/imgcodecs/imgcodecs.hpp>
 #include <opencv2/highgui/highgui.hpp>
@@ -37,8 +36,9 @@
 #include <opencv2/features2d/features2d.hpp>
 #include <opencv2/xfeatures2d/nonfree.hpp>
 
-#define APP_VERSION "2.8.1"
+#define APP_VERSION "2.8.15"
 
+#define AUFOCU_VIDEO  1
 using namespace std;
 
 #pragma pack(push,4) //保存对齐状态设定为4字节对齐
@@ -118,6 +118,9 @@ public:
     static QString lbs_lng;
     static QString gps_lat;
     static QString gps_lng;
+    //环境温湿度(MCU 上报 ext.at/ah 的最新值),用于图片水印"温湿度 [20℃,65%RH]"
+    static QString env_temp;
+    static QString env_humi;
     static QString gps_elevation;
     //camera&photo
     static QString camera_type;     //相机类型
@@ -140,6 +143,9 @@ public:
     static int  maxImageEntries;
     static int  x_init;
     static int  y_init;
+    //景深融合开关(1=开 0=关,默认开):MQTT fusion_sw 下发,持久化在 sqlite config.fusion_enable
+    //关闭时录制视频只分析最清晰帧并上传,跳过景深融合
+    static int  fusion_enable;
 
     //网络
     static bool net_alive;

+ 93 - 0
q6_felgo_iot/header/mserial.h

@@ -11,6 +11,7 @@
 #include <m_json.h>
 #include <QTimer>
 #include <QStandardPaths>
+#include <QStorageInfo>
 #include <QVideoFrame>
 #include <mysql.h>
 #include <m_loger.h>
@@ -66,6 +67,53 @@ public:
         deleteAllFilesInDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
     }
 
+    // ===== 存储空间循环覆写 =====
+    // 归档图片最少保留的剩余空间:低于该值时删除最老的一组图片
+    static constexpr qint64 kMinFreeSpace = 1073741824LL;   // 1GB
+
+    // 指定路径所在存储卷的剩余可用字节数
+    static qint64 getFreeSpace(const QString &path = QString())
+    {
+        const QString target = path.isEmpty()
+                ? QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)
+                : path;
+        QStorageInfo storage(target);
+        if (storage.isValid() && storage.isReady())
+            return storage.bytesAvailable();
+        QStorageInfo fallback(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
+        return (fallback.isValid() && fallback.isReady()) ? fallback.bytesAvailable() : 0;
+    }
+
+    // 循环覆写:剩余空间不足 minFree 时,按时间由旧到新逐组删除归档图片
+    // (一组=一个归档目录,即 年/月/日/时间戳 下的时间戳目录),
+    // 录制视频流(.rawv)不参与删除;返回实际释放的字节数
+    static qint64 ensureStorageSpace(qint64 minFree = kMinFreeSpace)
+    {
+        const QString root = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
+        qint64 freed = 0;
+        if (getFreeSpace(root) >= minFree)
+            return freed;
+
+        LOG("存储空间不足{} MB,开始循环覆写", minFree / (1024.0 * 1024.0));
+        QStringList groups;
+        collectArchiveGroups(root, root, groups);
+        groups.sort();      // 归档目录名即时间戳,排序后最前者即最老的一组
+        int removedGroups = 0;
+        for (const QString &group : groups) {
+            if (getFreeSpace(root) >= minFree)
+                break;
+            const qint64 f = removeGroupFiles(group);
+            if (f > 0) {
+                freed += f;
+                removedGroups++;
+                LOG("循环覆写:删除最老一组 {}", group.toStdString());
+            }
+        }
+        LOG("循环覆写结束:删除{}组,释放{} MB,剩余{} MB", removedGroups,
+            freed / (1024.0 * 1024.0), getFreeSpace(root) / (1024.0 * 1024.0));
+        return freed;
+    }
+
     Q_INVOKABLE void setCollt(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
         sendData(m_json.CmdParamconf(sh1,eh1,sh2,eh2,sh3,eh3));
     }
@@ -127,6 +175,8 @@ signals:
     void updatestart(QString filename);
     void auto_takephoto(bool sw);
     void takephotodone();
+    //收到控制板 record_stop:停止录制并处理视频流(分析/融合/删除录制文件/上传融合图)
+    void recordStop();
     void disconnect_485();
     void autotestdone();
     void translatedone();
@@ -217,6 +267,49 @@ private:
     lwjson_stream_parser_t lwparser;
     QByteArray jsonBuf;
 
+    // 递归收集"一组图片"的归档目录(叶子目录,即时间戳目录)
+    static void collectArchiveGroups(const QString &rootPath, const QString &directoryPath, QStringList &groups)
+    {
+        QDir directory(directoryPath);
+        if (!directory.exists())
+            return;
+
+        bool hasFile = false;
+        QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
+        foreach (const QFileInfo &fileInfo, fileInfoList) {
+            if (fileInfo.isDir())
+                collectArchiveGroups(rootPath, fileInfo.filePath(), groups);
+            else
+                hasFile = true;
+        }
+        // 根目录本身不算一组(只清理归档子目录)
+        if (hasFile && directory.absolutePath() != QDir(rootPath).absolutePath())
+            groups.append(directory.absolutePath());
+    }
+
+    // 删除一组归档目录中的图片(保留 .rawv 录制视频流),空目录一并移除;返回释放的字节数
+    static qint64 removeGroupFiles(const QString &directoryPath)
+    {
+        qint64 freed = 0;
+        QDir directory(directoryPath);
+        if (!directory.exists())
+            return freed;
+
+        QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
+        foreach (const QFileInfo &fileInfo, fileInfoList) {
+            if (fileInfo.isDir()) {
+                freed += removeGroupFiles(fileInfo.filePath());
+                // 空目录才删除成功,含保留视频流的目录会保留
+                QDir().rmdir(fileInfo.filePath());
+            } else if (fileInfo.suffix().compare(QStringLiteral("rawv"), Qt::CaseInsensitive) != 0) {
+                const qint64 size = fileInfo.size();
+                if (QFile::remove(fileInfo.filePath()))
+                    freed += size;
+            }
+        }
+        return freed;
+    }
+
     void deleteAllFilesInDirectory(const QString &directoryPath)
     {
         QDir directory(directoryPath);

+ 8 - 0
q6_felgo_iot/header/mysql.h

@@ -75,6 +75,7 @@ typedef struct{
     int  maxImageEntries;
     int  x_init;
     int  y_init;
+    int  fusion_enable;     //景深融合开关 1=开 0=关(MQTT fusion_sw 下发)
 
 }config_param;
 
@@ -127,6 +128,13 @@ class SqliteOperator : public QObject
 };
 
 bool InsertJson_mqtt();
+
+//旧版本数据库缺少新加的列时补列(平滑升级用):已存在则直接返回true
+//columnDef: 形如 "fusion_enable INT NOT NULL DEFAULT 1"
+bool ensureColumnExist(const QString &table, const QString &column, const QString &columnDef);
+
+//确保 config 表至少有一行默认配置(表被清空时兜底补行)
+bool ensureConfigRow();
 //条件查询与遍历查询的对比
 //加循环建了一个包含229300条数据,7448kb的数据库。
 //条件查询耗时:30ms

+ 2 - 2
q6_felgo_iot/qml/config.json

@@ -2,7 +2,7 @@
     "title": "Q6_felgo_iot",
     "identifier": "com.yfkj.cb.Q6iot",
     "orientation": "auto",
-    "versioncode": 80,
-    "versionname": "2.8.0",
+    "versioncode": 94,
+    "versionname": "2.8.15",
     "stage": ""
 }

+ 322 - 1
q6_felgo_iot/qml/pages/PhotostitcherPage.qml

@@ -4,6 +4,9 @@ import QtQuick.Controls
 import QtQuick.Layouts
 import "../controls"
 import "../common"
+
+import Frames 0.1
+import QtMultimedia
 AppPage {
     id: photoArchivePage
     navigationBarHidden: true
@@ -265,6 +268,279 @@ AppPage {
         fullscreenPopup.open()
     }
 
+    // ===== 原始视频流(.rawv)播放 =====
+    RawVideoPlayer {
+        id: rawPlayer
+        videoSink: videoOutput.videoSink
+    }
+
+    // 分析/融合结果(与视频同目录,命名与拍照图片一致)
+    Connections {
+        target: rawPlayer
+
+        function onAnalyzeFinished(path) {
+            if (path) {
+                console.log("分析完成:", path)
+                nativeUtils.displayMessageBox("提示", "分析完成,已保存:\n" + path.split("/").pop(), 1)
+            } else {
+                nativeUtils.displayMessageBox("提示", "分析失败,请重试!", 1)
+            }
+        }
+
+        function onFuseFinished(path) {
+            if (path) {
+                console.log("融合完成:", path)
+                nativeUtils.displayMessageBox("提示", "融合完成,已保存:\n" + path.split("/").pop(), 1)
+            } else {
+                nativeUtils.displayMessageBox("提示", "融合失败,请重试!", 1)
+            }
+        }
+
+        // 录制视频流文件已被删除:关闭播放并刷新界面上的相关条目
+        function onFileRemoved(path) {
+            console.log("录制视频流已删除:", path)
+            closeVideo()
+            for (var i = imageListModel.count - 1; i >= 0; i--) {
+                if (imageListModel.get(i).filePath === path)
+                    imageListModel.remove(i)
+            }
+            treeModel.resetModel()     //归档树重新加载,去掉已删除的条目
+            nativeUtils.displayMessageBox("提示", "已删除:\n" + path.split("/").pop(), 1)
+        }
+    }
+
+    // 打开原始视频流文件并开始播放
+    function openVideo(filePath) {
+        console.log("播放原始视频流:", filePath)
+        if (rawPlayer.open(filePath)) {
+            videoPopup.videoTitle = filePath.split("/").pop()
+            videoPopup.open()
+            rawPlayer.play()
+        } else {
+            nativeUtils.displayMessageBox("提示", "无法播放该视频流文件!", 1)
+        }
+    }
+
+    function closeVideo() {
+        rawPlayer.stop()
+        rawPlayer.close()
+        videoPopup.close()
+    }
+
+    Popup {
+        id: videoPopup
+        width: parent.width
+        height: parent.height
+        modal: true
+        closePolicy: Popup.NoAutoClose
+
+        property string videoTitle: ""
+
+        background: Rectangle {
+            color: "#000000"
+        }
+
+        VideoOutput {
+            id: videoOutput
+            anchors.fill: parent
+            anchors.bottomMargin: dp(80)
+            fillMode: VideoOutput.PreserveAspectFit
+        }
+
+        Column {
+            anchors.top: parent.top
+            anchors.topMargin: dp(12)
+            anchors.horizontalCenter: parent.horizontalCenter
+            spacing: dp(4)
+            Text {
+                anchors.horizontalCenter: parent.horizontalCenter
+                text: videoPopup.videoTitle
+                color: "white"
+                font.bold: true
+                font.pixelSize: 14
+            }
+            Text {
+                anchors.horizontalCenter: parent.horizontalCenter
+                text: rawPlayer.position + " / " + rawPlayer.frameCount + " 帧"
+                color: "#28a779"
+                font.pixelSize: 12
+            }
+        }
+
+        Row {
+            anchors.bottom: parent.bottom
+            anchors.bottomMargin: dp(16)
+            anchors.horizontalCenter: parent.horizontalCenter
+            spacing: dp(16)
+
+            AppButton {
+                text: rawPlayer.playing ? "暂停" : "播放"
+                textColor: "white"
+                backgroundColor: "#28a779"
+                flat: false
+                enabled: !rawPlayer.busy
+                minimumHeight: dp(40)
+                minimumWidth: dp(80)
+                onClicked: {
+                    if (rawPlayer.playing) rawPlayer.pause()
+                    else rawPlayer.play()
+                }
+            }
+
+            AppButton {
+                text: "分析"
+                textColor: "white"
+                backgroundColor: "#3b82f6"
+                flat: false
+                enabled: !rawPlayer.busy
+                minimumHeight: dp(40)
+                minimumWidth: dp(80)
+                onClicked: {
+                    rawPlayer.pause()
+                    rawPlayer.analyzeSharpestFrame()
+                }
+            }
+
+            AppButton {
+                text: "融合"
+                textColor: "white"
+                backgroundColor: "#8b5cf6"
+                flat: false
+                enabled: !rawPlayer.busy
+                minimumHeight: dp(40)
+                minimumWidth: dp(80)
+                onClicked: {
+                    rawPlayer.pause()
+                    rawPlayer.fuseVideoFrames()
+                }
+            }
+
+            AppButton {
+                text: "删除"
+                textColor: "white"
+                backgroundColor: "#e74c3c"
+                flat: false
+                enabled: !rawPlayer.busy
+                minimumHeight: dp(40)
+                minimumWidth: dp(80)
+                onClicked: deleteConfirmDialog.open()
+            }
+
+            AppButton {
+                text: "关闭"
+                textColor: "white"
+                backgroundColor: "#555555"
+                flat: false
+                minimumHeight: dp(40)
+                minimumWidth: dp(80)
+                onClicked: closeVideo()
+            }
+        }
+
+        Rectangle {
+            anchors.fill: parent
+            visible: rawPlayer.busy
+            color: "#99000000"
+            z: 10
+            Column {
+                anchors.centerIn: parent
+                spacing: dp(10)
+                BusyIndicator {
+                    anchors.horizontalCenter: parent.horizontalCenter
+                    running: rawPlayer.busy
+                    width: dp(48)
+                    height: dp(48)
+                }
+                Text {
+                    anchors.horizontalCenter: parent.horizontalCenter
+                    text: "正在处理,请稍候..."
+                    color: "white"
+                    font.pixelSize: 15
+                }
+            }
+        }
+    }
+
+    // 删除录制视频流前的确认框(用 Popup 实现,避免与 Felgo 的 Dialog 同名冲突)
+    Popup {
+        id: deleteConfirmDialog
+        width: parent.width * 0.8
+        height: dp(170)
+        x: (parent.width - width) / 2
+        y: (parent.height - height) / 2
+        padding: 0
+        modal: true
+        closePolicy: Popup.NoAutoClose
+
+        background: Rectangle {
+            color: "white"
+            radius: dp(6)
+        }
+
+        Text {
+            id: confirmTitle
+            anchors.left: parent.left
+            anchors.right: parent.right
+            anchors.top: parent.top
+            anchors.margins: dp(12)
+            color: "#333333"
+            font.bold: true
+            font.pixelSize: 15
+            text: "删除视频流"
+        }
+
+        Text {
+            id: confirmText
+            anchors.left: parent.left
+            anchors.right: parent.right
+            anchors.top: confirmTitle.bottom
+            anchors.leftMargin: dp(12)
+            anchors.rightMargin: dp(12)
+            anchors.topMargin: dp(8)
+            color: "black"
+            wrapMode: Text.Wrap
+            text: "确定删除该录制视频流文件?\n" + videoPopup.videoTitle
+        }
+
+        Row {
+            anchors.horizontalCenter: parent.horizontalCenter
+            anchors.top: confirmText.bottom
+            anchors.topMargin: dp(16)
+            spacing: dp(10)
+
+            AppButton {
+                text: "取消"
+                flat: false
+                textColor: "black"
+                backgroundColor: "#e9e9e9"
+                minimumHeight: dp(36)
+                minimumWidth: dp(70)
+                onClicked: deleteConfirmDialog.close()
+            }
+
+            AppButton {
+                text: "删除"
+                flat: false
+                textColor: "white"
+                backgroundColor: "#e74c3c"
+                minimumHeight: dp(36)
+                minimumWidth: dp(70)
+                onClicked: {
+                    deleteConfirmDialog.close()
+                    deleteCurrentVideo()
+                }
+            }
+        }
+    }
+
+    // 删除当前正在播放的录制视频流文件(.rawv,保留分析/融合结果图片)
+    function deleteCurrentVideo() {
+        if (rawPlayer.source === "")
+            return
+        if (!rawPlayer.removeCurrentFile())
+            nativeUtils.displayMessageBox("提示", "删除失败,请重试!", 1)
+    }
+
     // 重置缩放为初始大小并居中
     function resetTransform() {
         image.scale = 1.0
@@ -325,6 +601,9 @@ AppPage {
                 width: imageGridView.cellWidth - 5
                 height: imageGridView.cellHeight - 5
 
+                // 是否为原始视频流文件(.rawv)
+                readonly property bool isVideo: model.filePath ? rawPlayer.isRawVideo(model.filePath) : false
+
                 Rectangle {
                     anchors.fill: parent
                     anchors.margins: 2
@@ -343,7 +622,7 @@ AppPage {
                         sourceSize.height: 200
                         fillMode: Image.PreserveAspectFit
                         cache: true
-                        visible: model.filePath !== ""
+                        visible: model.filePath !== "" && !isVideo
 
                         BusyIndicator {
                             anchors.centerIn: parent
@@ -353,6 +632,37 @@ AppPage {
                         }
                     }
 
+                    // 视频流文件占位:显示播放标识与文件名
+                    Rectangle {
+                        anchors.fill: parent
+                        anchors.margins: 2
+                        visible: isVideo
+                        color: "#1b1b1b"
+                        radius: 3
+
+                        Column {
+                            anchors.centerIn: parent
+                            spacing: 2
+
+                            Text {
+                                anchors.horizontalCenter: parent.horizontalCenter
+                                text: "▶"
+                                color: "#28a779"
+                                font.pixelSize: 20
+                            }
+
+                            Text {
+                                width: imageGridView.cellWidth - 15
+                                anchors.horizontalCenter: parent.horizontalCenter
+                                text: model.filePath ? model.filePath.split("/").pop() : ""
+                                color: "white"
+                                font.pixelSize: 9
+                                elide: Text.ElideMiddle
+                                horizontalAlignment: Text.AlignHCenter
+                            }
+                        }
+                    }
+
                     // 缺图占位提示
                     Text {
                         anchors.centerIn: parent
@@ -406,6 +716,11 @@ AppPage {
                     enabled: model.filePath !== ""
                     onClicked: {
                         if (!model.filePath) return
+                        // 视频流文件直接打开播放
+                        if (isVideo) {
+                            openVideo(model.filePath)
+                            return
+                        }
                         if (isSelecting) {
                             toggleImageSelection(model.filePath)
                         } else {
@@ -415,6 +730,7 @@ AppPage {
                     }
                     onPressAndHold: {
                         if (!model.filePath) return
+                        if (isVideo) return
                         toggleImageSelection(model.filePath)
                     }
                 }
@@ -497,6 +813,11 @@ AppPage {
                             TapHandler{
                                 onSingleTapped: {
                                     if(root.type===6){
+                                        // 原始视频流文件(.rawv):直接打开播放
+                                        if (rawPlayer.isRawVideo(model.path)) {
+                                            openVideo(model.path)
+                                            return
+                                        }
                                         imageListModel.clear()
                                         imageListModel.append({filePath: model.path})
                                     }else{

+ 115 - 3
q6_felgo_iot/qml/pages/TestPage.qml

@@ -47,10 +47,21 @@ AppPage {
         }
     }
 
-    // 从上传文件路径解析图片序号(文件名形如 ..._sharp_7.jpg)
+    // 从上传文件路径解析图片序号
+    // 归档命名有两种(都会上传):
+    //   最清晰帧 <时间戳>z<z>x<x>_<序号>.jpg
+    //   融合图   <时间戳>z<z>x<x>_sharp_<序号>.jpg
+    // 故统一取"文件名末尾下划线后的数字",兼容两种命名及后续新增后缀
     function uploadSerialFromPath(filePath) {
         if(!filePath) return -1
-        var m = filePath.match(/sharp_(\d+)/)
+        // 只处理图片(录制视频流 .rawv 不参与进度网格)
+        if(!/\.(jpe?g|png)$/i.test(filePath.replace(/\?.*$/, ""))) return -1
+        // 去掉扩展名(兼容查询串),再取末尾 _数字
+        var base = filePath.replace(/\?.*$/, "").replace(/\.[^.\/\\]+$/, "")
+        var m = base.match(/_(\d+)$/)
+        if(m && m.length > 1) return parseInt(m[1])
+        // 兜底:兼容历史上只认 _sharp_N 的命名
+        m = filePath.match(/sharp_(\d+)/)
         if(m && m.length > 1) return parseInt(m[1])
         return -1
     }
@@ -89,7 +100,7 @@ AppPage {
             //frames.auto_clicked = true  //开始对焦
             auto_timer.start()  //启动对焦定时器
             console.log("相机已打开")
-            photoTimer.interval=60*1000
+            photoTimer.interval=180*1000
             photoTimer.start()
         }else{
             frames.camera_sw = true
@@ -123,10 +134,17 @@ AppPage {
             photoTimer.restart()
         }
 
+        onRecordFileSaved: function(path){
+            console.log("录制视频流已保存:", path)
+            apptext_res.text = "录制已保存:" + path.split("/").pop()
+        }
+
         onCameraStaChanged: function(sta_cam) {
             if(sta_cam){
                 //camera.active = sta_cam
                 //camera.start()
+                //每次(重新)打开相机后清空上传进度网格(上一次采集的进度/完成状态不再保留)
+                resetUploadGrid()
                 loginpage.logintimeout = 600;   //拍照刷新熄屏计时
                 output.visible = sta_cam
                 photoTimer.interval = 180*1000  //3分钟超时
@@ -474,6 +492,100 @@ AppPage {
                     }
                 }
             }
+
+            // 录制按钮:仅相机打开时显示,画面右下角(抓图按钮左侧)
+            // 点击开始录制原始(未压缩)视频流,再次点击停止并把视频流保存到相机打开时创建的文件夹
+            Rectangle {
+                id: recordBtn
+                visible: frames.camera_sw
+                width: dp(56)
+                height: dp(56)
+                radius: width / 2
+                color: "transparent"
+                border.color: frames.recording ? "#e74c3c" : "#80ffffff"
+                border.width: dp(2)
+                anchors.right: captureBtn.left
+                anchors.bottom: parent.bottom
+                anchors.rightMargin: dp(12)
+                anchors.bottomMargin: dp(12)
+
+                // 未录制:红色圆点(开始);录制中:红色方块(停止)
+                Rectangle {
+                    anchors.centerIn: parent
+                    width: frames.recording ? dp(22) : dp(26)
+                    height: frames.recording ? dp(22) : dp(26)
+                    radius: frames.recording ? dp(3) : width / 2
+                    color: "#e74c3c"
+                }
+
+                MouseArea {
+                    anchors.fill: parent
+                    onClicked: {
+                        if(frames.recording){
+                            console.log("停止录制视频流")
+                            frames.stopRecord()
+                        }else{
+                            console.log("开始录制视频流")
+                            if(frames.startRecord()){
+                                apptext_res.text = "开始录制视频流"
+                            }else{
+                                nativeUtils.displayMessageBox("提示","录制失败,请先打开相机!",1)
+                            }
+                        }
+                    }
+                }
+            }
+
+            // 分析/融合处理期间:挂起相机画面输出,用进度/过程替代画面
+            Rectangle {
+                id: processOverlay
+                visible: frames.processing
+                anchors.fill: parent
+                color: "#E6000000"
+                z: 20
+
+                Column {
+                    anchors.centerIn: parent
+                    spacing: dp(12)
+
+                    BusyIndicator {
+                        anchors.horizontalCenter: parent.horizontalCenter
+                        running: frames.processing
+                        width: dp(56)
+                        height: dp(56)
+                    }
+
+                    AppText {
+                        anchors.horizontalCenter: parent.horizontalCenter
+                        text: frames.processMessage
+                        color: "white"
+                        fontSize: 16
+                    }
+
+                    AppText {
+                        anchors.horizontalCenter: parent.horizontalCenter
+                        text: "处理中 " + frames.processPercent + "%"
+                        color: "#28a779"
+                        fontSize: 15
+                    }
+
+                    // 进度条
+                    Rectangle {
+                        width: dp(280)
+                        height: dp(8)
+                        radius: dp(4)
+                        color: "#33ffffff"
+                        anchors.horizontalCenter: parent.horizontalCenter
+
+                        Rectangle {
+                            width: parent.width * frames.processPercent / 100
+                            height: parent.height
+                            radius: parent.radius
+                            color: "#28a779"
+                        }
+                    }
+                }
+            }
         }
 
         ScrollView

+ 2 - 2
q6_felgo_iot/src/TreeModel.cpp

@@ -343,7 +343,7 @@ void TreeModel::loadPositionFolders(TreeItem *albumItem, const QModelIndex &pare
             }
         } else {
             QMimeType mime = m_mimeDb.mimeTypeForFile(info);
-            if (mime.name().startsWith("image/")) {
+            if (mime.name().startsWith("image/") || isRawVideoFile(info.fileName())) {
                 directImages.append(info);
             }
         }
@@ -397,7 +397,7 @@ void TreeModel::loadImages(TreeItem *albumItem, const QModelIndex &parentIndex)
     QList<QFileInfo> images;
     for (const QFileInfo &info : entries) {
         QMimeType mime = m_mimeDb.mimeTypeForFile(info);
-        if (mime.name().startsWith("image/")) {
+        if (mime.name().startsWith("image/") || isRawVideoFile(info.fileName())) {
             images.append(info);
         }
     }

+ 62 - 20
q6_felgo_iot/src/app_curlFunc.cpp

@@ -5,9 +5,27 @@
 #include <QDebug>
 #include <QDir>
 #include <m_loger.h>
-CurlFtpUploader::CurlFtpUploader(QObject *parent) : QObject(parent), m_port(21) {}
+CurlFtpUploader::CurlFtpUploader(QObject *parent) : QObject(parent), m_port(21)
+{
+    //常驻一个上传工作线程:所有上传请求排队后由它一张一张顺序执行,
+    //避免"每请求起一个线程"造成的并发传输(FTP 并发会互相挤占连接导致失败/错乱)
+    m_worker = QThread::create([this]() { runLoop(); });
+    m_worker->start();
+}
 
 CurlFtpUploader::~CurlFtpUploader() {
+    m_stopping.store(true);
+    {
+        QMutexLocker locker(&m_jobMutex);
+        m_jobs.clear();         //丢弃未开始的排队任务,避免退出时长时间等待
+    }
+    m_jobCond.wakeAll();
+    if(m_worker){
+        if(!m_worker->wait(3000)){
+            WARN("CurlFtpUploader: 上传线程未在3秒内退出,交由系统回收");
+        }
+        m_worker = nullptr;
+    }
     curl_global_cleanup();
 }
 
@@ -23,24 +41,46 @@ void CurlFtpUploader::setFtpParams(const QString &username,
     m_remotePath = remotePath;
 }
 
+//提交到串行队列(立即返回,真正的传输在工作线程里按FIFO顺序执行)
+void CurlFtpUploader::enqueueJob(const QString &localFilePath, const QString &parentPath)
+{
+    {
+        QMutexLocker locker(&m_jobMutex);
+        UploadJob job;
+        job.localFilePath = localFilePath;
+        job.parentPath = parentPath;
+        m_jobs.push_back(job);
+    }
+    m_jobCond.wakeOne();
+    LOG("uploadFileAsync: 已入队 {} (队列剩余待上传 {} 个)",
+        localFilePath.toStdString(), (int)m_jobs.size());
+}
+
+//工作线程主循环:顺序取任务上传,传完一个再取下一个
+void CurlFtpUploader::runLoop()
+{
+    for(;;){
+        UploadJob job;
+        {
+            QMutexLocker locker(&m_jobMutex);
+            while(m_jobs.empty() && !m_stopping.load()){
+                m_jobCond.wait(&m_jobMutex);
+            }
+            if(m_jobs.empty()) return;      //停止且无待传任务
+            job = m_jobs.front();
+            m_jobs.pop_front();
+        }
+        performUpload(job.localFilePath, job.parentPath);
+    }
+}
+
 void CurlFtpUploader::uploadFileAsync(const QString &localFilePath) {
-    LOG("uploadFileAsync...");
-    // 在子线程中执行上传(避免阻塞主线程)
-    QThread *thread = QThread::create([this, localFilePath]() {
-        performUpload(localFilePath, QString());
-    });
-    connect(thread, &QThread::finished, thread, &QThread::deleteLater);
-    thread->start();
+    enqueueJob(localFilePath, QString());
 }
 
 void CurlFtpUploader::uploadFileAsync(const QString &localFilePath, const QString &parentPath) {
-    LOG("uploadFileAsync(parentPath)...");
-    // 补录/重传:携带入库时记录的父目录,据此对齐远端归档目录
-    QThread *thread = QThread::create([this, localFilePath, parentPath]() {
-        performUpload(localFilePath, parentPath);
-    });
-    connect(thread, &QThread::finished, thread, &QThread::deleteLater);
-    thread->start();
+    //补录/重传:携带入库时记录的父目录,据此对齐远端归档目录
+    enqueueJob(localFilePath, parentPath);
 }
 
 void CurlFtpUploader::performUpload(const QString &localFilePath) {
@@ -52,15 +92,17 @@ void CurlFtpUploader::performUpload(const QString &localFilePath, const QString
     curl_global_init(CURL_GLOBAL_ALL);
     CURL *curl = curl_easy_init();
     if (!curl) {
-        emit finished(false, "Failed to initialize CURL");
+        ERROR("上传失败:curl 初始化失败:{}",localFilePath.toStdString());
+        emit finished(false, localFilePath, QStringLiteral("Failed to initialize CURL"));
         return;
     }
 
     // 打开本地文件
     QFile file(localFilePath);
     if (!file.open(QIODevice::ReadOnly)) {
-        emit finished(false, "Cannot open local file: " + localFilePath);
+        ERROR("上传失败:无法打开文件:{}",localFilePath.toStdString());
         curl_easy_cleanup(curl);
+        emit finished(false, localFilePath, QStringLiteral("Cannot open local file"));
         return;
     }
     emit downloadStart(localFilePath);
@@ -121,10 +163,10 @@ void CurlFtpUploader::performUpload(const QString &localFilePath, const QString
 
     // 处理结果
     if (res != CURLE_OK) {
-        ERROR("上传失败:{}",curl_easy_strerror(res));
-        emit finished(false, localFilePath);
+        ERROR("上传失败:{} ({})",curl_easy_strerror(res),localFilePath.toStdString());
+        emit finished(false, localFilePath, QString::fromUtf8(curl_easy_strerror(res)));
     } else {
-        emit finished(true, localFilePath);
+        emit finished(true, localFilePath, QString());
     }
 
     curl_easy_cleanup(curl);

File diff ditekan karena terlalu besar
+ 1442 - 71
q6_felgo_iot/src/cameramanager.cpp


+ 70 - 25
q6_felgo_iot/src/m_opencv.cpp

@@ -1564,16 +1564,21 @@ cv::Mat OpencvFunc::fuseAdvanced(const std::vector<cv::Mat>& images,
 
     // 尺度因子:原始、1/2、1/4
     const int nScales = 3;
-    // 平滑权重用大 σ,让拼接缝不可见
-    // 改: min(rows,cols)/64 而不是 /32,保留更多"清晰"区域
-    //    (σ 太大 → 边界渗色 → 灰蒙)
-    const double sigmaFuse = std::max(6.0, std::min(rows, cols) / 64.0);
+    // 平滑权重用高斯(让拼接缝不可见),但 sigma 必须"够小":
+    //   旧实现把权重 resize 到 1/ds 后用固定 sigma=3 平滑,等效 sigma = 3*ds,
+    //   5MP 图上约 90 —— 权重被严重摊平,清晰像素无法独占权重,
+    //   失焦帧的模糊像素渗进来,融合图细节被稀释(实测细节仅保持最清晰帧的 63%)。
+    //   现改为显式指定"等效原图 sigma":sigmaSmall = sigmaFuse / ds。
+    //   实测等效 sigma≈10 时:细节保持 63%→87%,景深扩展 +43%,背景噪声不升。
+    const double sigmaFuse = std::max(8.0, std::min(rows, cols) / 192.0);
+    const int ds = 16;                                     // 权重图降采样比(固定,便于换算)
+    const double sigmaSmall = std::max(0.4, sigmaFuse / ds);
     // 对小细节的快速局部权重(小 σ 抗噪),仅用于强化边缘
     const double sigmaLocal = 2.0;
-    // 权重对比度: 提升到 2.5 强化赢家
-    //   wp=1.5: 焦/失焦 比例 ~2-3x
-    //   wp=2.5: 焦/失焦 比例 ~10x,清晰区几乎独占 (颜色就回来)
-    const double wp = 2.5;
+    // 权重对比度: 2.5→3.5 强化赢家(焦/失焦比例更高,清晰像素更接近独占权重)
+    //   wp=2.5: 焦/失焦 比例 ~10x
+    //   wp=3.5: 进一步压低失焦帧贡献(实测细节保持 +21%,噪声不升)
+    const double wp = 3.5;
 
     std::vector<cv::Mat> weights(N);
     cv::Mat weightSum = cv::Mat::zeros(rows, cols, CV_32F);
@@ -1615,22 +1620,23 @@ cv::Mat OpencvFunc::fuseAdvanced(const std::vector<cv::Mat>& images,
                 cv::pow(term, wp / nScales, term);
                 cv::multiply(wAcc, term, wAcc);
             }
-            // 大 σ 平滑(HALEyes focus_image 的关键步骤,模拟低频权重)
-            // 性能关键: σ=125 在 5MP 上慢。改用 2 阶段:
-            //   1) 把权重 resize 到小图 (cols/64, rows/64)
-            //   2) 在小图上做 σ=3 模糊 (仅 ~62x50 = 极快)
+            // 权重空间平滑(保证接缝不可见)
+            // 性能: 5MP 上直接大 σ 模糊很慢, 改用 2 阶段:
+            //   1) 把权重 resize 到小图 (cols/16, rows/16)
+            //   2) 在小图上按等效 σ 换算的 sigmaSmall 模糊 (仅 ~162x121 = 极快)
             //   3) resize 回原图 (OpenCV 内部走 NEON 双线性)
+            // 注意: 等效 σ 不可过大(旧实现等效约90) —— 权重被摊平后清晰像素无法独占
+            //   权重, 失焦帧的模糊像素渗入, 融合图细节明显不如最清晰帧。
             // 关键增强: 之后做 (W-w_min) / (w_max-w_min) "对比度归一化"
             //   → 把"软"的权重重新拉开成 "硬选择",保留接缝消除的同时
             //     让清晰像素独占权重,消除灰蒙感
             {
                 TIMER_SCOPE("halcon-sigmaFuse");
-                int ds = std::max(8, (int)sigmaFuse);  // 下采样因子
                 int smallW = std::max(1, cols / ds);
                 int smallH = std::max(1, rows / ds);
                 cv::Mat wSmall;
                 cv::resize(wAcc, wSmall, cv::Size(smallW, smallH), 0, 0, cv::INTER_AREA);
-                cv::GaussianBlur(wSmall, wSmall, cv::Size(0, 0), 3.0, 3.0,
+                cv::GaussianBlur(wSmall, wSmall, cv::Size(0, 0), sigmaSmall, sigmaSmall,
                                  cv::BORDER_REFLECT_101);
                 cv::resize(wSmall, wAcc, cv::Size(cols, rows), 0, 0, cv::INTER_LINEAR);
 
@@ -1638,14 +1644,19 @@ cv::Mat OpencvFunc::fuseAdvanced(const std::vector<cv::Mat>& images,
                 //   W' = (W - wMin) / (wMax - wMin + eps)
                 //   然后 wPow 倍再放大,让赢家接近 1,输家接近 0
                 // 这步把"σ 大模糊导致的灰蒙"重新拉开成"硬选择"
+                // 【修复】仅当权重动态范围足够大时才做这个"全图 min-max 拉伸 + pow":
+                //   range 极小时(各帧焦点几乎一致,如录像抽帧)除以极小 range 会把权重里的
+                //   噪声放大成逐像素 0/1 硬切换(等价于每像素随机取某一帧)
+                //   → 融合图出现大量细颗粒噪点(实测平坦区噪声放大3倍、梯度能量放大10倍)。
+                //   此时保持原有平滑权重,后续按 Σ 归一化即自然退化为多帧平均(噪声反而下降)。
                 double localMin, localMax;
                 cv::minMaxLoc(wAcc, &localMin, &localMax);
-                float wMin = (float)localMin;
-                float wMax = (float)localMax;
-                float range = std::max(1e-6f, wMax - wMin);
-                cv::subtract(wAcc, cv::Scalar(wMin), wAcc);
-                cv::divide(wAcc, cv::Scalar(range), wAcc);
-                cv::pow(wAcc, 1.5, wAcc);  // 进一步拉对比
+                const float range = static_cast<float>(localMax - localMin);
+                if (range > 0.02f * std::max(1.0f, static_cast<float>(localMax))) {
+                    cv::subtract(wAcc, cv::Scalar(static_cast<float>(localMin)), wAcc);
+                    cv::divide(wAcc, cv::Scalar(range), wAcc);
+                    cv::pow(wAcc, 1.5, wAcc);  // 进一步拉对比
+                }
             }
             // 防退化
             cv::max(wAcc, cv::Scalar(1e-7f), wAcc);
@@ -1816,12 +1827,18 @@ cv::Mat OpencvFunc::unsharpMask(const cv::Mat& src, double amount, double sigma)
 // ============================================================
 // 显微专用综合清晰度评价
 // ============================================================
-// 同时给出 Laplacian 方差、Tenengrad、Brenner 三个指标 + 综合分。
+// 同时给出 Laplacian 方差、Tenengrad、Brenner 三个指标 + 最终评分。
 // 推荐替代单独调用 brenner/Laplacian/Tenengrad,因为:
 //   1) 单帧跑这些 kernel 各自只要几十毫秒,一次扫描同时算三个指标几乎不增加成本
 //   2) 综合分能把"全场亮导致 Laplacian 偏高"的失效情况屏蔽掉
 //   3) 给自动对焦算法一个稳定的目标函数
-OpencvFunc::MicroscopeFocusMetrics OpencvFunc::evaluateFocusScore(const cv::Mat& image) {
+// metric 可选择评分方式:单项指标(LaplacianVar/Tenengrad/Brenner)或三项组合(Combined),
+// 最终分值统一归一化到同一尺度后存入 combinedScore,便于不同指标横向比较。
+OpencvFunc::MicroscopeFocusMetrics OpencvFunc::evaluateFocusScore(const cv::Mat& image,
+                                                                  FocusMetric metric,
+                                                                  double wLaplacian,
+                                                                  double wTenengrad,
+                                                                  double wBrenner) {
     MicroscopeFocusMetrics out{};
     out.laplacianVar = 0.0;
     out.tenengrad    = 0.0;
@@ -1879,8 +1896,8 @@ OpencvFunc::MicroscopeFocusMetrics OpencvFunc::evaluateFocusScore(const cv::Mat&
     });
     out.brenner = brennerSum.load() / std::max(1, rows * cols);
 
-    // 综合分: 把三个指标归一化后求和(每个指标除以自己的经验上界,
-    //         让三项在 [0,1] 区间,权重按方差最大给主分)。
+    // 综合分: 把三个指标归一化后按权重求和(每个指标除以自己的经验上界,
+    //         让三项在 [0,1] 区间,避免量级差异大的指标主导评分)。
     // 经验上界(5MP 显微 20x 物镜正常聚焦时大致):
     //   lapVar   ~ 100~500
     //   tenengrad~ 50~300
@@ -1891,7 +1908,35 @@ OpencvFunc::MicroscopeFocusMetrics OpencvFunc::evaluateFocusScore(const cv::Mat&
     double nLap   = std::min(1.0, out.laplacianVar / kLapRef);
     double nTen   = std::min(1.0, out.tenengrad    / kTenRef);
     double nBren  = std::min(1.0, out.brenner      / kBrenRef);
-    out.combinedScore = 0.5 * nLap + 0.3 * nTen + 0.2 * nBren;
+
+    switch (metric) {
+    case FocusMetric::LaplacianVar:
+        //单项:仅 Laplacian 方差
+        out.combinedScore = nLap;
+        return out;
+    case FocusMetric::Tenengrad:
+        //单项:仅 Tenengrad 梯度能量
+        out.combinedScore = nTen;
+        return out;
+    case FocusMetric::Brenner:
+        //单项:仅 Brenner 二阶差分能量
+        out.combinedScore = nBren;
+        return out;
+    case FocusMetric::Combined:
+    default:
+        break;
+    }
+
+    //组合:权重归一化后加权求和(权重非法时回退到默认 0.5/0.3/0.2)
+    double wLap = std::max(0.0, wLaplacian);
+    double wTen = std::max(0.0, wTenengrad);
+    double wBren = std::max(0.0, wBrenner);
+    double wSum = wLap + wTen + wBren;
+    if (wSum <= 0.0) {
+        wLap = 0.5; wTen = 0.3; wBren = 0.2;
+        wSum = 1.0;
+    }
+    out.combinedScore = (wLap * nLap + wTen * nTen + wBren * nBren) / wSum;
 
     return out;
 }

+ 8 - 4
q6_felgo_iot/src/main.cpp

@@ -379,7 +379,7 @@ int main(int argc, char *argv[])
     if(!sqlConfig->isTableExist(param::table_mqtt)){
         sqlConfig->CreateTable(param::table_mqtt);
         //插入数据
-        config_class.mqtt_db = {1,"bzy","8.136.98.49",61883,"","user","f335bf402c655ee5fd2b5300905124e","",0,60,"/yfkj/bzyH/s2c/","/yfkj/bzyH/c2s/","/yfkj/bzyH/offline/",10};
+        config_class.mqtt_db = {1,"bzy","8.136.98.49",61883,"","user","f335bf402c655ee5fd2b5300905124e","",0,60,"/yfkj/bzy/2.1/sub/","/yfkj/bzy/2.1/pub/","/yfkj/bzy/2.1/offline/",10};
         sqlConfig->InsertData(config_class,param::table_mqtt);
         //查询全部数据
         sqlConfig->QueryAllData(param::table_mqtt);
@@ -398,7 +398,7 @@ int main(int argc, char *argv[])
     if(!sqlConfig->isTableExist(param::table_mqtt_other))
     {
         sqlConfig->CreateTable(param::table_mqtt_other);
-        config_class.mqtt_db = {1,"bzy","0.0.0.0",1883,"","uid","pwd","clientid",0,60,"/yfkj/bzy/s2c/","/yfkj/bzy/c2s/","/yfkj/bzy/offline/",10};
+        config_class.mqtt_db = {1,"bzy","0.0.0.0",1883,"","uid","pwd","clientid",0,60,"/yfkj/bzy/2.1/sub/","/yfkj/bzy/2.1/pub/","/yfkj/bzy/2.1/offline/",10};
         sqlConfig->InsertData(config_class,param::table_mqtt_other);
         //查询全部数据
         sqlConfig->QueryAllData(param::table_mqtt_other);
@@ -445,10 +445,13 @@ int main(int argc, char *argv[])
     //配置
     if(!sqlConfig->isTableExist(param::table_config)){
         sqlConfig->CreateTable(param::table_config);
-        config_class.config_db = {1,1,1000,500,0,0};
+        config_class.config_db = {1,1,1000,500,0,0,1};
         sqlConfig->InsertData(config_class,param::table_config);
         sqlConfig->QueryAllData(param::table_config);
     }else{
+        //旧版本库没有 fusion_enable 列(景深融合开关):补列后再读,保证老设备升级后可用
+        ensureColumnExist(param::table_config,"fusion_enable","fusion_enable INT NOT NULL DEFAULT 1");
+        ensureConfigRow();          //表被清空时补默认行,保证后续配置 UPDATE 能生效
         sqlConfig->QueryAllData(param::table_config);
     }
 
@@ -681,8 +684,9 @@ if(Navigation_main){
                     //engine.addImageProvider("ucamera",m_frames->getImageProvider());
                     QObject::connect(m_frames,&Qt6QCamera::Frames::serial_data,&serialThread,&SerialThread::sendData);      //Frame到串口
                     QObject::connect(&serialThread,&SerialThread::takephotodone,m_frames,&Qt6QCamera::Frames::saveImage);      //串口到QML,控制qml跳转到自动对焦界面
-                    //QObject::connect(m_frames,&Qt6QCamera::Frames::signal_stitch,&imagestitcher,&ImageStitcher::stitch_thread);
                     QObject::connect(&serialThread,&SerialThread::signal_movy,m_frames,&Qt6QCamera::Frames::onMovDone);
+                    //串口 record_stop:停止录制并处理视频流(分析/融合/删除录制文件/上传融合图)
+                    QObject::connect(&serialThread,&SerialThread::recordStop,m_frames,&Qt6QCamera::Frames::handleRecordStop);
                     QObject::connect(m_frames,&Qt6QCamera::Frames::dataUpload,&mqttHandler,[&mqttHandler](const QByteArray &data){ mqttHandler.publish_m(data); });     //frames到MQTT(信号1参,槽2参需lambda补默认qos)
                     // 修改信号槽连接方式
                     QObject::connect(m_frames, &Qt6QCamera::Frames::signal_wait_upload,

+ 23 - 0
q6_felgo_iot/src/mqtthandler.cpp

@@ -322,6 +322,29 @@ MqttHandler::onMessageReceived(const QByteArray &message, const QMqttTopicName &
                     emit signal_set_camera_exposure(exposureTime);
                     sendJsonRpcResponseImpl(ID.toInt(), true, "exposure updated");
                 }
+                // ======== 景深融合开关 ========
+                // {"jsonrpc":"2.0","method":"fusion_sw","params":{"enable":0},"id":1}
+                // enable=1 开启(默认) / 0 关闭:关闭后录制视频只分析最清晰帧并上传,不做景深融合
+                // 不带 enable 时为查询当前开关状态
+                else if(method=="fusion_sw"){
+                    if(PARAMS.isNull() || params_Obj["enable"].isNull()){
+                        sendJsonRpcResponseImpl(ID.toInt(), true,
+                            QString("fusion_enable=%1").arg(param::fusion_enable));
+                        return;
+                    }
+                    const int enable = params_Obj["enable"].toInt(0) != 0 ? 1 : 0;
+                    param::fusion_enable = enable;
+                    DatabaseInterface db;
+                    const bool ok = db.updateData(param::table_config, "fusion_enable", enable);
+                    LOG("fusion_sw: enable={} 写库{}", enable, ok ? "成功" : "失败");
+                    if(ok){
+                        sendJsonRpcResponseImpl(ID.toInt(), true,
+                            QString("fusion %1").arg(enable ? "enabled" : "disabled"));
+                    }else{
+                        //开关已即时生效,仅持久化失败,仍提示需排查数据库
+                        sendJsonRpcResponseImpl(ID.toInt(), false, "fusion set, but db save failed");
+                    }
+                }
                 // ======== frpc 内网穿透远程管理 ========
                 // {"jsonrpc":"2.0","method":"frpc_start","params":{"toml":"...可选"},"id":1}
                 else if(method=="frpc_start"){

+ 19 - 2
q6_felgo_iot/src/mserial.cpp

@@ -15,8 +15,8 @@ SerialThread::SerialThread(QObject *parent)
     lwjson_stream_init(&lwparser, NULL);
     QString directoryPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
     analyzeDirectory(directoryPath);
-    if(int_totalSize>=1073741824)
-           deleteAllFilesInDirectory(directoryPath);
+    //循环覆写:剩余空间不足1G时按时间由旧到新删除最老的一组图片(录制视频流不删除)
+    ensureStorageSpace();
     QString db_config = "config.db";
     sqlConfig = new SqliteOperator(db_config);
     if(param::dat_f_main<=0)  param::dat_f_main = 10;
@@ -162,6 +162,19 @@ SerialThread::processJsonData(const QByteArray &jsonData)
         QJsonValue cmdValue = jsonObject["cmd"];
         QJsonValue extValue = jsonObject.value("ext");
         QJsonValue uartValue = jsonObject["uart"];
+        //记录 MCU 上报的环境温湿度(ext.at/ah),供图片水印使用:
+        //不是每条报文都带这两个字段,有值就刷新,缺失时保持上一次的值
+        if(extValue.isObject()){
+            const QJsonObject extObj = extValue.toObject();
+            auto refresh = [](const QJsonObject &obj, const QString &key, QString &dst){
+                const QJsonValue v = obj.value(key);
+                if(v.isUndefined() || v.isNull()) return;
+                const QString s = v.toVariant().toString().trimmed();
+                if(!s.isEmpty() && s != QStringLiteral("null")) dst = s;
+            };
+            refresh(extObj, QStringLiteral("at"), param::env_temp);   //环境温度
+            refresh(extObj, QStringLiteral("ah"), param::env_humi);   //湿度
+        }
         if(!uartValue.isNull()){
             sendData(m_json.BoardMessage());
         }
@@ -180,6 +193,10 @@ SerialThread::processJsonData(const QByteArray &jsonData)
                 LOG("收到 recover_param, 从数据库恢复 MCU 参数");
                 recoverMcuParam();
                 return;
+            } else if (methodName == QStringLiteral("record_stop")) {
+                LOG("收到 record_stop, 停止录制并处理视频流");
+                emit recordStop();
+                return;
             }
         }
 

+ 92 - 2
q6_felgo_iot/src/mysql.cpp

@@ -48,6 +48,8 @@ QString param::lbs_lat;
 QString param::lbs_lng;
 QString param::gps_lat;
 QString param::gps_lng;
+QString param::env_temp;
+QString param::env_humi;
 QString param::gps_elevation;
 
 QString param::camera_type;
@@ -72,6 +74,8 @@ int param::maxJsonEntries;
 int param::maxImageEntries;
 int param::x_init;
 int param::y_init;
+//景深融合开关:默认开(1),由 MQTT fusion_sw 下发并写入 config.fusion_enable
+int param::fusion_enable = 1;
 
 bool param::net_alive;
 QString param::net_name;
@@ -102,6 +106,85 @@ int param::datupload_remain;
 //        db.setPassword("yf123456");
     }
 }
+//旧版本数据库缺少新加的列时补列(平滑升级用)
+//用 PRAGMA table_info 检查列是否存在,不存在才执行 ALTER TABLE ADD COLUMN,
+//已存在或表不存在都视为无需处理(表不存在时由启动流程负责建表)
+bool ensureColumnExist(const QString &table, const QString &column, const QString &columnDef)
+{
+    QSqlDatabase db;
+    if(QSqlDatabase::contains("qt_sql_default_connection")){
+        db = QSqlDatabase::database("qt_sql_default_connection");
+    }else{
+        WARN("ensureColumnExist: 数据库未打开,跳过补列 {} {}",
+             table.toStdString(), column.toStdString());
+        return false;
+    }
+    if(!db.isOpen()){
+        WARN("ensureColumnExist: 数据库连接已关闭,跳过补列 {} {}",
+             table.toStdString(), column.toStdString());
+        return false;
+    }
+    QSqlQuery info(db);
+    if(!info.exec(QString("PRAGMA table_info(%1)").arg(table))){
+        ERROR("ensureColumnExist: 读取表结构失败 {} {}",
+              table.toStdString(), info.lastError().text().toStdString());
+        return false;
+    }
+    while(info.next()){
+        if(info.value(1).toString() == column){
+            return true;    //列已存在
+        }
+    }
+    QSqlQuery alter(db);
+    const QString sql = QString("ALTER TABLE %1 ADD COLUMN %2").arg(table, columnDef);
+    if(!alter.exec(sql)){
+        ERROR("ensureColumnExist: 补列失败 {} {}",
+              sql.toStdString(), alter.lastError().text().toStdString());
+        return false;
+    }
+    LOG("ensureColumnExist: 已补列 {}", sql.toStdString());
+    return true;
+}
+
+//确保 config 表至少有一行默认配置
+//config 表无主键、配置按整表 UPDATE 生效;若表被清空,UPDATE 影响 0 行且仍返回成功,
+//会导致 MQTT 下发的开关(如 fusion_sw)只在内存生效、重启丢失,故启动时兜底补一行
+bool ensureConfigRow()
+{
+    QSqlDatabase db;
+    if(QSqlDatabase::contains("qt_sql_default_connection")){
+        db = QSqlDatabase::database("qt_sql_default_connection");
+    }else{
+        WARN("ensureConfigRow: 数据库未打开,跳过");
+        return false;
+    }
+    if(!db.isOpen()){
+        WARN("ensureConfigRow: 数据库连接已关闭,跳过");
+        return false;
+    }
+    QSqlQuery query(db);
+    if(!query.exec("SELECT COUNT(*) FROM config") || !query.next()){
+        ERROR("ensureConfigRow: 查询行数失败 {}", query.lastError().text().toStdString());
+        return false;
+    }
+    if(query.value(0).toInt() > 0) return true;
+    QSqlQuery insert(db);
+    insert.prepare("INSERT INTO config VALUES(?,?,?,?,?,?,?)");
+    insert.addBindValue(1);      // jsonCacheEnable
+    insert.addBindValue(1);      // imageCacheEnable
+    insert.addBindValue(1000);   // maxJsonEntries
+    insert.addBindValue(500);    // maxImageEntries
+    insert.addBindValue(0);      // x_init
+    insert.addBindValue(0);      // y_init
+    insert.addBindValue(param::fusion_enable);
+    if(!insert.exec()){
+        ERROR("ensureConfigRow: 插入默认配置失败 {}", insert.lastError().text().toStdString());
+        return false;
+    }
+    LOG("ensureConfigRow: 已补默认配置行 fusion_enable={}", param::fusion_enable);
+    return true;
+}
+
 bool InsertJson_mqtt()
 {
 #if ANDROID
@@ -314,7 +397,8 @@ bool InsertJson_mqtt()
                              maxJsonEntries INT NOT NULL,\
                              maxImageEntries INT NOT NULL,\
                              x_init INT NOT NULL,\
-                             y_init TEXT NOT NULL)");
+                             y_init TEXT NOT NULL,\
+                             fusion_enable INT NOT NULL)");
      }
      sql_query.prepare(creat_sql);
      if(!sql_query.exec())
@@ -384,13 +468,14 @@ bool InsertJson_mqtt()
         sql_query.bindValue(":movX_f",singledb.camera_db.movx_f);
         sql_query.bindValue(":movX_b",singledb.camera_db.movx_b);
     }else if(tablename == QString::fromLocal8Bit("config")){
-        sql_query.prepare(QString("INSERT INTO %1 VALUES(:jsonCacheEnable,:imageCacheEnable,:maxJsonEntries,:maxImageEntries,:x_init,:y_init)").arg(tablename));
+        sql_query.prepare(QString("INSERT INTO %1 VALUES(:jsonCacheEnable,:imageCacheEnable,:maxJsonEntries,:maxImageEntries,:x_init,:y_init,:fusion_enable)").arg(tablename));
         sql_query.bindValue(":jsonCacheEnable", singledb.config_db.jsonCacheEnable);
         sql_query.bindValue(":imageCacheEnable", singledb.config_db.imageCacheEnable);
         sql_query.bindValue(":maxJsonEntries", singledb.config_db.maxJsonEntries);
         sql_query.bindValue(":maxImageEntries", singledb.config_db.maxImageEntries);
         sql_query.bindValue(":x_init", singledb.config_db.x_init);
         sql_query.bindValue(":y_init",singledb.config_db.y_init);
+        sql_query.bindValue(":fusion_enable",singledb.config_db.fusion_enable);
     }
      if(!sql_query.exec())
      {
@@ -549,12 +634,17 @@ int SqliteOperator::UpdateData(QString tablename, QString name, QString value)
                  param::maxImageEntries = sql_query.value(3).toInt();
                  param::x_init = sql_query.value(4).toInt();
                  param::y_init = sql_query.value(5).toInt();
+                 //景深融合开关:列不存在时(极老版本库)保持默认开启
+                 if(!sql_query.value(6).isNull()){
+                     param::fusion_enable = sql_query.value(6).toInt() != 0 ? 1 : 0;
+                 }
                  LOG("jsonCacheEnable:{}",param::jsonCacheEnable);
                  LOG("imageCacheEnable:{}",param::imageCacheEnable);
                  LOG("maxJsonEntries:{}",param::maxJsonEntries);
                  LOG("maxImageEntries:{}",param::maxImageEntries);
                  LOG("x_init:{}",param::x_init);
                  LOG("y_init:{}",param::y_init);
+                 LOG("fusion_enable:{}",param::fusion_enable);
              }
              LOG("data_num:{}",data_num);
          }