zhunk 2 месяцев назад
Родитель
Сommit
b1a969c903

+ 131 - 98
Application_cbd_apm32f1/applications/control.c

@@ -857,8 +857,6 @@ void ResetInit(void)
     ctr_Heat(ON);
     //关闭制冷
     ctr_Cold(OFF);
-    //关闭补光灯
-    ctr_led(OFF);
     //关闭Y轴驱动电源
     ctr_Collect_Fan(OFF);
     //关闭X轴驱动电源
@@ -872,45 +870,73 @@ void ResetInit(void)
 u_int8_t alarmCheck(u_int8_t starthour,u_int8_t endhour,u_int8_t startmin,u_int8_t endmin)
 {
     u_int8_t workflag = 0;
-    if(starthour == endhour) return workflag;
     time_t now;
     time(&now);
     struct tm now_tm = *localtime(&now);
     rt_uint32_t curr_sec = now_tm.tm_hour*3600 + now_tm.tm_min*60 + now_tm.tm_sec;
-    rt_uint32_t start_sec = starthour * 3600 + startmin * 60;
-    rt_uint32_t end_sec = endhour * 3600 + endmin * 60;
-
-    // 处理开始和结束时间相同的情况
-     if (start_sec == end_sec) {
-         workflag =  0;
-     }
-    // 修复跨天判断逻辑
-    if (start_sec < end_sec)
+    rt_uint32_t start_sec = (rt_uint32_t)starthour * 3600 + startmin * 60;
+    rt_uint32_t end_sec   = (rt_uint32_t)endhour * 3600 + endmin * 60;
+
+    if (start_sec == end_sec)
+    {
+        /* 起止时刻相同,视为无效时间段,保持待机 */
+        workflag = 0;
+    }
+    else if (start_sec < end_sec)
     {
-        // 不跨天模式
+        /* 不跨天模式,如 08:00~10:00 */
         workflag = (curr_sec >= start_sec && curr_sec < end_sec) ? 1 : 0;
     }
     else
     {
-        // 跨天模式
+        /* 跨天模式,如 22:00~06:00 */
         workflag = (curr_sec >= start_sec || curr_sec < end_sec) ? 1 : 0;
     }
-    LOG_I("时控模式:状态[%s] 当前时间:%02d:%02d:%02d 设置:%02d:%02d-%02d:%02d",
-          workflag ? "工作" : "待机",
-          now_tm.tm_hour, now_tm.tm_min, now_tm.tm_sec,
-          starthour,startmin, endhour,endmin);
-    rt_thread_delay(10000);
     return workflag;
 }
 
+/* 采集段结束处理:卷带电机转一圈 + 发送自动对焦指令
+ * 进入时先清零自锁,避免执行期间(turnlimit可能阻塞较久)新的采集段结束事件被覆盖丢失
+ * work_done 由工作流程线程独占清零,消除与状态检测线程的双写竞态
+ */
+static void exec_work_done(void)
+{
+    device_status.work_done = 0;
+    LOG_I("采集段结束, 执行转带+自动对焦");
+    turnlimit();                           //卷带电机转一圈
+    rt_thread_delay(2000);
+    uint8_t retry_send = 0;
+    while(1){
+        char *take_start = makeJson_Warn("start", "autofocus");
+        if(take_start != RT_NULL) {
+            DTU_Write("%s",take_start);
+            rt_free(take_start);
+        } else {
+            LOG_E("makeJson_Warn failed! retry:%d", retry_send);
+        }
+        rt_thread_delay(5000);
+        retry_send++;
+        if(retry_send==30||device_status.autotakepic>0){
+            LOG_I("send start msg done, retry=%d, autotakepic=%d", retry_send, device_status.autotakepic);
+            break;
+        }
+    }
+}
+
 void WorkTask_BZYV2(void)
 {
     if(device_status.ds==1&&device_status.temp_status==0){
 
+        /* 等待设备进入工作窗口 */
         while(device_status.work_status ==0){
-            rt_thread_delay(10000);
-            LOG_W("等待设备进入工作");
+            /* 待机期间若有未处理的采集段结束动作,立即补做 */
+            if(device_status.work_done==1){
+                exec_work_done();
+            }
+            rt_thread_delay(1000);
         }
+
+        /* 处于工作窗口:按对焦状态控制路由器供电 */
         while(device_status.work_status ==1){
             if(device_status.autotakepic==0){
                 ctr_router(ON);
@@ -922,30 +948,17 @@ void WorkTask_BZYV2(void)
                 ctr_router(OFF);
                 break;
             }
-            rt_thread_delay(10000);
+            /* 任一采集段窗口结束(下降沿置位 work_done)立即执行转带+对焦 */
+            if(device_status.work_done==1){
+                exec_work_done();
+            }
+            rt_thread_delay(1000);
         }
         ctr_router(OFF);
 
+        /* 退出工作循环后若有未处理的结束动作(如温控异常跳出), 补做 */
         if(device_status.work_done==1){
-            turnlimit();                           //卷带电机转一圈
-            rt_thread_delay(2000);
-            uint8_t retry_send = 0;
-            while(1){
-                char *take_start = makeJson_Warn("start", "autofocus");
-                if(take_start != RT_NULL) {
-                    DTU_Write("%s",take_start);
-                    rt_free(take_start);
-                } else {
-                    LOG_E("makeJson_Warn failed! retry:%d", retry_send);
-                }
-                rt_thread_delay(5000);
-                retry_send++;
-                if(retry_send==30||device_status.autotakepic>0){
-                    LOG_I("send start msg done, retry=%d, autotakepic=%d", retry_send, device_status.autotakepic);
-                    break;
-                }
-            }
-            device_status.work_done = 0;
+            exec_work_done();
         }
     }else{
         LOG_W("==================!!!设备已待机!!!===================");
@@ -957,61 +970,57 @@ void WorkTask_BZYV2(void)
 static void Work_status_thread_entry(void *parameter)
 {
     static uint32_t takephoto_cnt = 0;
-     while(1)
-     {
-         if(device_status.ds==0||
-            device_status.temp_status==1){
-             device_status.work_status = 0;
-             rt_thread_delay(5000);
-             continue;
-         }
-
-         while(alarmCheck(device_status.collecting_sh1,device_status.collecting_eh1,device_status.collt_min_sh1,device_status.collt_min_eh1) == ON)
-         {
-             device_status.work_status = 1;
-             LOG_I("the alarm1 workflag was ON");
-             device_status.work_done=1;
-             rt_thread_delay(1000);
-         }
-         //如果当前时间大于collecting_eh1,开始拍照
+    /* 记录上一轮各采集段的窗口状态,用于检测窗口结束(ON->OFF下降沿) */
+    u_int8_t last_seg_on[3] = {OFF, OFF, OFF};
 
-         while(alarmCheck(device_status.collecting_sh2,device_status.collecting_eh2,device_status.collt_min_sh2,device_status.collt_min_eh2) == ON)
-         {
-           device_status.work_status = 1;
-           device_status.work_done=1;
-           LOG_I("the alarm2 workflag was ON");
-           rt_thread_delay(1000);
-         }
-         //如果当前时间大于collecting_eh2,开始拍照
+    while(1)
+    {
+        if(device_status.ds==0 || device_status.temp_status==1)
+        {
+            device_status.work_status = 0;
+            /* 设备待机时复位上一轮窗口状态,避免恢复工作后误判下降沿 */
+            last_seg_on[0] = OFF;
+            last_seg_on[1] = OFF;
+            last_seg_on[2] = OFF;
+            rt_thread_delay(5000);
+            continue;
+        }
 
-         while(alarmCheck(device_status.collecting_sh3,device_status.collecting_eh3,device_status.collt_min_sh3,device_status.collt_min_eh3) == ON)
-         {
-             device_status.work_status = 1;
-             device_status.work_done=1;
-             LOG_I("the alarm3 workflag was ON");
+        /* 依次判断3段采集窗口,任何一段处于窗口内即为工作状态 */
+        u_int8_t seg_on[3];
+        seg_on[0] = alarmCheck(device_status.collecting_sh1, device_status.collecting_eh1,
+                               device_status.collt_min_sh1, device_status.collt_min_eh1);
+        seg_on[1] = alarmCheck(device_status.collecting_sh2, device_status.collecting_eh2,
+                               device_status.collt_min_sh2, device_status.collt_min_eh2);
+        seg_on[2] = alarmCheck(device_status.collecting_sh3, device_status.collecting_eh3,
+                               device_status.collt_min_sh3, device_status.collt_min_eh3);
 
-             rt_thread_delay(1000);
-         }
-         device_status.work_status = 0;
+        device_status.work_status = (seg_on[0] || seg_on[1] || seg_on[2]) ? 1 : 0;
 
-         if(device_status.autotakepic==2){
-             takephoto_cnt++;
-         }else{
-             takephoto_cnt=0;
-         }
-         if(takephoto_cnt==3600){
-             device_status.autotakepic = 0;
-             takephoto_cnt = 0;
-         }
-         //如果当前时间大于
-         if(device_status.work_done!=0)
-         {
-             rt_thread_delay(1000*30);
-             device_status.work_done = 0;
-         }
+        /* 每段窗口结束(ON->OFF)置位一次 work_done,保证每个采集段结束后只触发一次转带+对焦 */
+        u_int8_t i;
+        for(i = 0; i < 3; i++)
+        {
+            if(last_seg_on[i] == ON && seg_on[i] == OFF)
+            {
+                device_status.work_done = 1;
+                LOG_I("alarm%d 采集段结束, 触发转带+对焦", i+1);
+            }
+            last_seg_on[i] = seg_on[i];
+        }
 
-         rt_thread_delay(1000);
-     }
+        /* 自动对焦保护:对焦中超过1小时强制退出,避免对焦卡死 */
+        if(device_status.autotakepic==2){
+            takephoto_cnt++;
+        }else{
+            takephoto_cnt=0;
+        }
+        if(takephoto_cnt==3600){
+            device_status.autotakepic = 0;
+            takephoto_cnt = 0;
+        }
+        rt_thread_delay(1000);
+    }
 }
 /*入口函数-工作流程*/
 static void Work_Loop_thread_entry(void *parameter)
@@ -1100,14 +1109,38 @@ void slide_thread_entry(void *parameter)
     case 6:{    //Y轴
                 ctr_move(Y_,slide_para.ydir,slide_para.ydis,slide_para.pulse_period);
                 rt_kprintf("The slide's y movement was done ok\n");
-                rt_thread_delay(1000);
+                rt_thread_delay(2000);  //20260905 -- 1000>2000   消抖
                 if(1){
-                    char utos[5];
-                    rt_sprintf(utos,"%d",slide_para.ystep);
-                    char *photo = makeJson_Warn("movy",utos);
-                    LOG_I("%s",photo);
-                    DTU_Write("%s",photo);
-                    rt_free(photo);
+                    /* 发送movy后等待相机回传focus, 5S超时未收到则重发, 最多重传3次, 避免对焦卡死 */
+                    int focus_ok = 0;
+                    int retry = 0;
+                    do {
+                        char utos[5];
+                        rt_sprintf(utos,"%d",slide_para.ystep);
+                        char *photo = makeJson_Warn("movy",utos);
+                        LOG_I("%s",photo);
+                        focus_valid_flag = 0;   /* 清零后再发送, 避免误用上次残留的focus */
+                        DTU_Write("%s",photo);
+                        rt_free(photo);
+                        /* 等待相机回传有效focus, 超时5S */
+                        rt_uint32_t deadline = rt_tick_get() + 5 * RT_TICK_PER_SECOND;
+                        while ((rt_int32_t)(rt_tick_get() - deadline) < 0) {
+                            if (focus_valid_flag) {
+                                focus_valid_flag = 0;
+                                focus_ok = 1;
+                                break;
+                            }
+                            rt_thread_delay(RT_TICK_PER_SECOND / 10);   /* 100ms轮询一次 */
+                        }
+                        if (focus_ok) {
+                            break;
+                        }
+                        retry++;
+                        LOG_W("movy 未收到focus回传, 重传第%d次", retry);
+                    } while (retry < 3);
+                    if (!focus_ok) {
+                        LOG_W("movy 连续4次未收到focus回传, 放弃重传");
+                    }
                 }
                 slide_para.ydis = 0;
                 slide_para.stop_flag = 0;

+ 4 - 1
Application_cbd_apm32f1/applications/control.h

@@ -16,7 +16,10 @@
 //定制相关//////////////////////////////////////////////////////
 #define SENSOR_EN        0              //温湿度:0关闭,1打开
 ////////////////////////////////////////////////////////////////
-#define VERSION_BZY         "2.9.21"                   //孢子仪
+#define VERSION_BZY         "2.9.32"                   //孢子仪
+
+/* 对焦串口通信异常标志: 串口收到合法 JSON 且含 "focus" 字段时置1(定义于dtu_uart2.c) */
+extern volatile uint8_t focus_valid_flag;
 
 /*********************************************************************/
 typedef struct  _packed

+ 6 - 0
Application_cbd_apm32f1/applications/dtu_uart2.c

@@ -40,6 +40,9 @@ Device_Status_typedef device_status;
 Device_slide_typedef slide_para;
 DataTemp data_arry;
 
+/* 对焦串口通信异常标志: 串口收到合法 JSON 且含 "focus" 字段时置1, movy发送后的超时重传逻辑检测后清零 */
+volatile uint8_t focus_valid_flag = 0;
+
 void list_mem(void);
 /* 串口接收消息结构*/
 struct rx_msg
@@ -1036,6 +1039,7 @@ int parseDtu(char *json_string)
           item_focus = cJSON_GetObjectItem(root,"focus");
           if(item_focus!=RT_NULL){
               device_status.focus_value = item_focus->valuedouble;
+              focus_valid_flag = 1;   /* 标记收到有效focus, 供movy发送后的超时重传检测 */
               if(device_status.calibrate_slide==0){
                   send_signal(SIGUSR1);
               }else{
@@ -1196,8 +1200,10 @@ int parseDtu(char *json_string)
                   //{"ext": {"type": "led_off"}, "cmd": "ctrl"}
                   else if (strstr(type->valuestring,"led_off")!=RT_NULL)
                   {
+                      device_status.autotakepic = 0;
                       ctr_led(OFF);
                       stop_move();
+                      report_takephoto_duration();   /* 收到关闭LED指令, 上报对焦拍照持续时间 */
                   }
                   else if(strstr(type->valuestring,"selfcheck")!=RT_NULL)
                   {

+ 340 - 200
Application_cbd_apm32f1/applications/hmi.c

@@ -39,7 +39,7 @@
 #define HMI_THREAD_TIMESLICE        10           //时间片
 
 #define CONTROL_MOTOR_PRIORITY      7
-#define CONTROL_MOTOR_STACK_SIZE    2048
+#define CONTROL_MOTOR_STACK_SIZE    8192
 #define CONTROL_MOTOR_TIMESLICE     5
 
 
@@ -163,9 +163,8 @@ static void Hmi_thread_entry(void *parameter)
         result = rt_mq_recv(&rx_mq, &msg, sizeof(msg), 50);
         if (result == RT_EOK)
         {
-
-                rx_length = rt_device_read(msg.dev, 0, rx_buffer, msg.size);
-                rx_buffer[rx_length] = '\0';
+            rx_length = rt_device_read(msg.dev, 0, rx_buffer, msg.size);
+            rx_buffer[rx_length] = '\0';
         }
         /*********************************************************************************************************************/
         //rt_kprintf("%04d-%02d-%02d %02d:%02d:%02d\n",tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);
@@ -214,210 +213,317 @@ void send_signal(int sig)
     rt_thread_kill(ctr_motor, sig);
 }
 
-// 全局状态变量(需在合适位置初始化)
-static float g_best_sharpness = -FLT_MAX;    // 全局最佳清晰度
-static int g_best_pos = 0;                   // 全局最佳位置
-static float g_last_sharpness = 0.0;    // 上一次移动后的清晰度
-static bool g_initial_move = true;           // 初始方向判断标志
-static bool focus_done = false;
-int maxIterations = 100;
-uint8_t dir = 1;
-uint8_t stepSize = 20;     // 初始步长(单位:步进电机脉冲数)
-int current_pos = 0;  // 根据实际类型修改(int/float等)
-static int g_peak_counter = 0;      // 连续上升后下降的计数器
-static bool g_last_rising = false;   // 记录上次是否上升
-static int counter_sharpness_reduce = 0;    //清晰度降低累计
-static int counter_sharpness_diff = 0;      //清晰度累计插值 次数变化
-#define MAX(a, b) ((a) > (b) ? (a) : (b))  // 手动定义宏
-
+/* ========== 自动对焦(Auto Focus)控制块 ========== */
+#define AF_FOCUS_TIMEOUT_MS   5000    /* 等待 focus 回复超时时间(ms) */
+#define AF_FOCUS_RETRY_MAX    3       /* 等待 focus 超时补发指令次数上限 */
+
+typedef struct {
+    float best_sharpness;        /* 全局最佳清晰度 */
+    int   best_pos;              /* 全局最佳位置 */
+    float last_sharpness;        /* 上一次移动后的清晰度 */
+    int   dir;                   /* 行进方向: 1=正向, 0=反向 */
+    int   step_size;             /* 步进电机脉冲数 */
+    int   current_pos;           /* 当前位置 */
+    int   peak_counter;          /* 连续上升后下降的峰值计数 */
+    int   reduce_counter;        /* 清晰度连续降低计数 */
+    int   diff_counter;          /* 清晰度变化微小累计次数 */
+    bool  last_rising;           /* 上次是否上升 */
+    int   max_iterations;        /* 最大迭代次数 */
+    bool  initial_move;          /* 初始方向判断标志 */
+    volatile bool sharpness_updated;  /* 信号处理程序置位: 有新清晰度值 */
+    float new_sharpness;         /* 信号处理程序写入的新清晰度值 */
+    bool  active;                /* 对焦进行中标志(用于超时重试判定) */
+    rt_tick_t wait_start_tick;   /* 开始等待 focus 回复的时间 */
+    int   retry_cnt;             /* 已连续超时补发指令次数 */
+} auto_focus_t;
+
+static auto_focus_t g_af;
+/* 轻量级信号处理程序:仅存储清晰度值,不阻塞 */
 void thread1_signal_handler(int sig)
 {
-    rt_timer_stop(timer_takephoto);
-    LOG_I("[对焦] 清晰度值更新:%.2f", device_status.focus_value);
-    slide_para.pulse_period = mapSpeed(1);  // 更新电机速度参数
-    maxIterations--;
-
-    if (device_status.autotakepic == 2 && maxIterations >= 0) {
-        float current_sharpness = device_status.focus_value;
-
-        /* 更新全局最佳状态 */
-        if (current_sharpness > g_best_sharpness) {
-            g_best_sharpness = current_sharpness;
-            g_best_pos = current_pos;
-            LOG_I("[对焦] 发现更佳位置:%d (清晰度:%.2f)", g_best_pos, g_best_sharpness);
-        }
-
-        /* 初始方向判断(首步移动后) */
-        if (g_initial_move) {
-            if (current_sharpness > g_last_sharpness) {
-                LOG_I("[对焦] 初始方向正确,保持方向:%d", dir);
-            } else {
-                dir = !dir;             // 反转方向
-                LOG_I("[对焦] 初始方向错误,反转方向:%d", dir);
-            }
-            g_initial_move = false;
-        } else {
+    g_af.sharpness_updated = true;
+    g_af.new_sharpness = device_status.focus_value;
+}
 
-            double diff_sharpness =  fabs(current_sharpness-g_last_sharpness);
-            if(diff_sharpness<1.0)
-            {
-                counter_sharpness_diff++;
-                if(counter_sharpness_diff>=10){ //持续10次
-                    stepSize = 20;
-                }
-            }
 
-            if(diff_sharpness > 3.5)  //动态调整,发生明显变化,降低步进幅度
-            {
-                counter_sharpness_diff = 0;
-                stepSize = 4;
-            }
-            LOG_I("[对焦] 清晰度变化累计%d次小于1.0",counter_sharpness_diff);
-
-            if(current_sharpness< (g_last_sharpness-0.3f)){    //持续3次清晰度降低,调整行进方向
-                counter_sharpness_reduce++;
-                LOG_I("[对焦] 清晰度下降,次数:%d", counter_sharpness_reduce);
-                if(counter_sharpness_reduce>=3){
-                    counter_sharpness_reduce = 0;
-                    dir = !dir;             // 清晰度下降,反转方向
-                    LOG_I("[对焦] 连续清晰度下降,调转行进方向!");
-                }
-            }else {
-                counter_sharpness_reduce = 0;
-            }
+/* 初始化自动对焦状态 */
+static void auto_focus_init(void)
+{
+    memset(&g_af, 0, sizeof(g_af));
+    g_af.best_sharpness = -FLT_MAX;
+    g_af.last_sharpness = 0.0f;
+    g_af.initial_move = true;
+    g_af.last_rising = false;
+    g_af.dir = 1;
+    g_af.step_size = 20;
+    g_af.current_pos = 0;
+    g_af.max_iterations = 100;
+    g_af.peak_counter = 0;
+    g_af.best_pos = 0;
+    g_af.reduce_counter = 0;
+    /* 超时重试状态 */
+    g_af.active = true;
+    g_af.wait_start_tick = rt_tick_get();
+    g_af.retry_cnt = 0;
+}
 
-            /* 方向策略调整,检测到清晰度变大 */
-            if (current_sharpness > (g_last_sharpness - 3.5f)) { // 噪声容忍阈值3.0
-                // 保持方向,当接近峰值时自动减小步长
-                LOG_I("保持方向,当接近峰值时自动减小步长...");
-                g_last_rising = true;
-                stepSize += 2;          //动态调整步幅
-            } else {
-                if(g_last_rising){
-                    g_peak_counter++;
-                    LOG_I("[对焦] 检测到清晰度波动[%d/3]", g_peak_counter);
-                    stepSize = 2;
-                }else {
-                    g_peak_counter = 0;  // 连续下降则重置
-                }
-                g_last_rising = false;
-                dir = !dir;             // 清晰度下降,反转方向
-                LOG_I("[对焦] 清晰度下降,反转方向:%d 步长:%d", dir, stepSize);
-            }
-        }
+/* 移动电机一步 */
+static void auto_focus_move(void)
+{
+    g_af.current_pos += g_af.dir ? g_af.step_size : -g_af.step_size;
+    LOG_I("[对焦] 移动:方向=%d 步长=%d 位置=%d", g_af.dir, g_af.step_size, g_af.current_pos);
 
-        /* 记录本次清晰度值 */
-        g_last_sharpness = current_sharpness;
+    slide_para.pulse_period = mapSpeed(1);
+    slide_para.ystep = g_af.step_size;
+    slide_para.ydir = g_af.dir;
+    slide_para.ydis = g_af.step_size;
+    slide_para.en_slide = 6;
 
-        /* 计算并执行下一步移动 */
-        current_pos += dir ? stepSize : -stepSize;
-        LOG_I("[对焦] 方向:%d 移动步长:%d 新位置:%d", dir, stepSize, current_pos);
+    while (slide_para.en_slide != 0) {
+        rt_thread_delay(100);
+    }
 
-        if(counter_sharpness_diff>=30){
-            dir = !dir;
-            stepSize += 10; //增大步幅
-            counter_sharpness_diff = 0;
-        }
+    LOG_I("[对焦] 电机到位");
+    g_af.wait_start_tick = rt_tick_get();   /* 移动完成,开始等待 focus 回复 */
+}
 
-        LOG_I("[对焦] 最佳位置:%d (清晰度:%.2f)", g_best_pos, g_best_sharpness);
+/* 完成对焦 */
+static void auto_focus_done(void)
+{
+    LOG_I("[对焦] 完成! 最佳位置:%d 清晰度:%.2f", g_af.best_pos, g_af.best_sharpness);
+    g_af.active = false;   /* 对焦完成,停止超时重试检测 */
+    char *c0 = makeJson_Warn("auto_focus","auto_focus");
+    DTU_Write("%s",c0);
+    rt_free(c0);
+}
 
+/* 处理一次清晰度值,执行对焦算法 */
+static void auto_focus_process(void)
+{
+    float current_sharpness = g_af.new_sharpness;
+    g_af.sharpness_updated = false;
+    g_af.max_iterations--;
+    g_af.retry_cnt = 0;                       /* 收到 focus 回复,清零超时重试计数 */
+    g_af.wait_start_tick = rt_tick_get();     /* 重置等待计时 */
+
+    LOG_I("[对焦] 清晰度:%.2f 位置:%d 剩余:%d",
+           current_sharpness, g_af.current_pos, g_af.max_iterations);
+
+    /* 更新最佳位置 */
+    if (current_sharpness > g_af.best_sharpness) {
+        g_af.best_sharpness = current_sharpness;
+        g_af.best_pos = g_af.current_pos;
+        LOG_I("[对焦] 新最佳:位置%d 清晰度%.2f", g_af.best_pos, g_af.best_sharpness);
+    }
 
-        if(g_peak_counter>=3&&current_sharpness>g_best_sharpness*0.95){
-            focus_done = true;
-        }else{
-            focus_done = false;
-            g_best_sharpness -= 2.0f;   //降低阈值,防止找不到
+    /* 初始方向判断:比较首次移动前后的清晰度 */
+    if (g_af.initial_move) {
+        g_af.initial_move = false;
+        if (current_sharpness > g_af.last_sharpness) {
+            LOG_I("[对焦] 初始方向正确");
+        } else {
+            g_af.dir = !g_af.dir;
+            LOG_I("[对焦] 初始方向错误,反转");
         }
+        g_af.last_sharpness = current_sharpness;
+        auto_focus_move();
+        return;
+    }
 
-        /* 终止条件检测 */
-        if (counter_sharpness_diff>=100||maxIterations <= 0 || focus_done==true) {
-            counter_sharpness_reduce = 0;
-            maxIterations = 100;
-            LOG_I("[对焦] 完成搜索,最佳位置:%d (清晰度:%.2f)", g_best_pos, g_best_sharpness);
-            if (g_peak_counter >= 3) {
-                LOG_I("[对焦] 连续三次波动确认峰值");
-            }
-            focus_done = false;
-            LOG_I("[对焦] 已到达最佳对焦位置");
-            if(maxIterations==0)
-            {
-                stepSize = 20;
-                dir = !dir;
-                current_pos = 0;
-            }else{
-                counter_sharpness_diff = 0;
-                char *c0 = makeJson_Warn("auto_focus","auto_focus");
-                DTU_Write("%s",c0);
-                rt_free(c0);
-                device_status.autotakepic = 0; // 退出自动对焦模式
-                return;
-            }
+    /* 计算清晰度变化 */
+    float diff = current_sharpness - g_af.last_sharpness;
+
+    /* 动态调整步长 */
+    if (fabs(diff) > 3.0f) {
+        /* 清晰度大幅变化 -> 缩小步长精细搜索 */
+        g_af.step_size = 10;
+        g_af.diff_counter = 0;
+        LOG_I("[对焦] 大幅变化,步长=%d", g_af.step_size);
+    } else if (fabs(diff) < 1.0f) {
+        /* 清晰度变化微小 -> 累计平坦区域 */
+        g_af.diff_counter++;
+        if (g_af.diff_counter >= 10) {
+            g_af.step_size = 20;
         }
-        slide_para.ystep = stepSize;
-        slide_para.ydir = dir;
-        slide_para.ydis = stepSize;
-        slide_para.en_slide = 6;  // 触发移动
-        while (slide_para.en_slide != 0) {
-            rt_thread_delay(500); // 等待移动完成
+        LOG_I("[对焦] 平坦[%d/10] 步长=%d", g_af.diff_counter, g_af.step_size);
+    } else {
+        g_af.diff_counter = 0;
+    }
+
+    if (current_sharpness > (g_af.last_sharpness - 3.5f)) { // 噪声容忍阈值3.0
+        // 保持方向,当接近峰值时自动减小步长
+        LOG_I("保持方向,当接近峰值时自动减小步长...");
+        g_af.last_rising = true;
+        g_af.step_size += 2;          //动态调整步幅
+    } else {
+        if(g_af.last_rising){
+            g_af.peak_counter++;
+            LOG_I("[对焦] 检测到清晰度波动[%d/2]", g_af.peak_counter);
+            g_af.step_size = 2;
+        }else {
+            g_af.peak_counter = 0;  // 连续下降则重置
         }
+        g_af.last_rising = false;
+        g_af.dir = !g_af.dir;    // 清晰度下降,反转方向
+        LOG_I("[对焦] 清晰度下降,反转方向:%d 步长:%d", g_af.dir, g_af.step_size);
+    }
+
+    g_af.last_sharpness = current_sharpness;
+
+
+    /* 平坦区域超时:强制反转并增大步长 */
+    if (g_af.diff_counter >= 30) {
+        g_af.dir = !g_af.dir;
+        g_af.step_size += 10;
+        g_af.diff_counter = 0;
+        LOG_I("[对焦] 平坦超时,增大步长=%d", g_af.step_size);
+    }
+
+    LOG_I("[对焦] 最佳:位置%d 清晰度%.2f", g_af.best_pos, g_af.best_sharpness);
+
+    /* 终止条件 */
+    bool done = false;
+    if (g_af.peak_counter >= 2 && current_sharpness > g_af.best_sharpness * 0.90f) {
+        done = true;
+        LOG_I("[对焦] 峰值确认完成");
+        g_af.max_iterations = 100;
+        g_af.reduce_counter = 0;
+        g_af.diff_counter = 0;
     }
+    if (g_af.max_iterations <= 0) {
+        done = true;
+        g_af.step_size = 20;
+        g_af.dir = !g_af.dir;
+        g_af.current_pos = 0;
+        LOG_I("[对焦] 迭代次数耗尽");
+    }
+
+    if (done) {
+        auto_focus_done();
+        return;
+    }
+
+    /* 移动电机 */
+    auto_focus_move();
 }
 
+/* ========== Y轴校准(Calibration)控制块 ========== */
+typedef struct {
+    float best_sharpness;
+    float last_sharpness;
+    int   diff_counter;
+    bool  initial_move;
+    int   dir;
+    int   ystep;
+    volatile bool sharpness_updated;
+    float new_sharpness;
+} calibrate_t;
+
+static calibrate_t g_cal;
+
+/* 轻量级信号处理程序:仅存储清晰度值,不阻塞 */
 void thread2_signal_handler(int sig)
 {
-    rt_timer_stop(timer_takephoto);
-    maxIterations--;
-    LOG_I("[Y] 清晰度值更新:%.2f", device_status.focus_value);
-    slide_para.pulse_period = mapSpeed(50);  // 更新电机速度参数
-    if(device_status.calibrate_slide==20&& maxIterations >= 0){
-        float current_sharpness = device_status.focus_value;
-        /* 更新全局最佳状态 */
-        if (current_sharpness > g_best_sharpness) {
-            g_best_sharpness = current_sharpness;
-            LOG_I("[Y] 发现更佳位置(清晰度:%.2f)",g_best_sharpness);
-        }
-        /* 初始方向判断(首步移动后) */
-        if (g_initial_move) {
-            if (current_sharpness > g_last_sharpness) {
-                LOG_I("[对焦] 初始方向正确,保持方向:%d", dir);
-            }
-            g_initial_move = false;
-        }else{
-            double diff_sharpness =  fabs(current_sharpness-g_last_sharpness);
-            if(diff_sharpness<1.0)
-            {
-                counter_sharpness_diff++;
-            }
+    g_cal.sharpness_updated = true;
+    g_cal.new_sharpness = device_status.focus_value;
+}
 
-            LOG_I("[Y] 清晰度变化累计%d次小于1.0",counter_sharpness_diff);
-            if(counter_sharpness_diff>1&&diff_sharpness>100.0){
-                //停止,保存当前位置
-                device_status.calibrate_slide = 0;
-                device_status.y_init_dis = slide_para.ystep;
-                LOG_I("设置Y轴初始位置:%d",slide_para.ystep);
-                ef_set_env_blob("y_init_dis", &device_status.y_init_dis, sizeof(device_status.y_init_dis));
-                return;
-            }
-            /* 记录本次清晰度值 */
-            g_last_sharpness = current_sharpness;
-        }
+/* 初始化校准状态 */
+static void calibrate_init(void)
+{
+    memset(&g_cal, 0, sizeof(g_cal));
+    g_cal.best_sharpness = -FLT_MAX;
+    g_cal.last_sharpness = 0.0f;
+    g_cal.initial_move = true;
+    g_cal.dir = 1;
+    g_cal.ystep = 0;
+}
 
-        /* 终止条件检测 */
-        if (maxIterations <= 0) {
-            device_status.calibrate_slide = 0;
-            return;
-        }
-        slide_para.ydir = dir;
-        slide_para.ydis = 80;
-        slide_para.ystep += 80;
-        slide_para.en_slide = 6;  // 触发移动
-        while (slide_para.en_slide != 0) {
-            rt_thread_delay(500); // 等待移动完成
+/* 移动电机一步 */
+static void calibrate_move(void)
+{
+    g_cal.ystep += 80;
+    slide_para.pulse_period = mapSpeed(50);
+    slide_para.ydir = g_cal.dir;
+    slide_para.ydis = 80;
+    slide_para.ystep = g_cal.ystep;
+    slide_para.en_slide = 6;
+
+    while (slide_para.en_slide != 0) {
+        rt_thread_delay(500);
+    }
+
+    LOG_I("[Y] 电机到位 位置:%d", g_cal.ystep);
+}
+
+/* 处理一次校准清晰度值 */
+static void calibrate_process(void)
+{
+    float current_sharpness = g_cal.new_sharpness;
+    g_cal.sharpness_updated = false;
+
+    LOG_I("[Y] 清晰度值:%.2f 位置:%d", current_sharpness, g_cal.ystep);
+
+    /* 更新最佳位置 */
+    if (current_sharpness > g_cal.best_sharpness) {
+        g_cal.best_sharpness = current_sharpness;
+        LOG_I("[Y] 更佳位置(清晰度:%.2f) 位置:%d", g_cal.best_sharpness, g_cal.ystep);
+    }
+
+    /* 初始方向判断 */
+    if (g_cal.initial_move) {
+        g_cal.initial_move = false;
+        if (current_sharpness > g_cal.last_sharpness) {
+            LOG_I("[Y] 初始方向正确");
         }
+        g_cal.last_sharpness = current_sharpness;
+        calibrate_move();
+        return;
+    }
+
+    /* 计算变化 */
+    double diff_sharpness = fabs(current_sharpness - g_cal.last_sharpness);
+    if (diff_sharpness < 1.0) {
+        g_cal.diff_counter++;
+    }
+
+    LOG_I("[Y] 平坦累计:%d 变化量:%.2f", g_cal.diff_counter, diff_sharpness);
+
+    /* 从平坦区域到突变 -> 特征点,保存当前位置 */
+    if (g_cal.diff_counter > 1 && diff_sharpness > 100.0) {
+        device_status.calibrate_slide = 0;
+        device_status.y_init_dis = g_cal.ystep;
+        LOG_I("设置Y轴初始位置:%d", g_cal.ystep);
+        ef_set_env_blob("y_init_dis", &device_status.y_init_dis, sizeof(device_status.y_init_dis));
+        return;
     }
 
+    g_cal.last_sharpness = current_sharpness;
+
+    /* 继续移动 */
+    calibrate_move();
 }
 
+/* 对焦拍照开始计时时刻(文件级): 供收到关闭LED/触发超时时上报持续时间 */
+static rt_tick_t takephoto_start_tick = 0;
+
+/* 上报对焦拍照持续时间: 在收到关闭LED指令(led_off)或触发超时(拍照超时/focus超时)时调用 */
+void report_takephoto_duration(void)
+{
+    if (takephoto_start_tick == 0) {
+        return;   /* 未开始拍照计时或已上报, 不重复上报 */
+    }
+    rt_uint32_t duration_s = (rt_tick_get() - takephoto_start_tick) / RT_TICK_PER_SECOND;
+    LOG_I("[拍照] 结束, 持续时间 %u 秒", duration_s);
+    char duration_str[16];
+    rt_sprintf(duration_str, "%dS", duration_s);
+    char *dur_warn = makeJson_Warn("takephoto_duration", duration_str);
+    if(dur_warn != RT_NULL) {
+        DTU_Write("%s", dur_warn);
+        rt_free(dur_warn);
+    }
+    takephoto_start_tick = 0;   /* 复位计时, 防止重复上报 */
+}
 
 //入口函数-电机控制及
 static void Ctr_Mortor_entry(void* parameter)
@@ -430,6 +536,13 @@ static void Ctr_Mortor_entry(void* parameter)
    static uint32_t t_takephoto = 0;
     while(1)
     {
+        /* ========== 对焦拍照持续时间计时 ==========
+         * autotakepic 非0且未在计时: 开始计时;
+         * 上报时机: 收到关闭LED指令(led_off)或触发超时(拍照超时/focus超时)时调用 report_takephoto_duration() 上报 */
+        if((device_status.autotakepic != 0) && (takephoto_start_tick == 0)) {
+            takephoto_start_tick = rt_tick_get();
+            LOG_I("[拍照] 开始计时");
+        }
         if(device_status.calibrate_slide==2)
         {
             device_status.autotakepic=1;
@@ -438,11 +551,45 @@ static void Ctr_Mortor_entry(void* parameter)
         if(device_status.autotakepic==2)
         {
             t_takephoto++;
-            if(t_takephoto==36000)
+            if(t_takephoto==360000)
             {
+                ctr_led(OFF);
                 t_takephoto = 0;
                 device_status.autotakepic = 0;
+                report_takephoto_duration();   /* 拍照超时, 上报对焦拍照持续时间 */
+            }
+            /* 自动对焦:等待 focus 回复超时则补发指令(最多重试3次),
+             * 防止串口乱码导致 focus 帧丢失而对焦中断 */
+            if (g_af.active &&
+                (rt_tick_get() - g_af.wait_start_tick) >
+                    rt_tick_from_millisecond(AF_FOCUS_TIMEOUT_MS))
+            {
+                if (g_af.retry_cnt < AF_FOCUS_RETRY_MAX) {
+                    g_af.retry_cnt++;
+                    g_af.wait_start_tick = rt_tick_get();   /* 重新计时,等待下一个5s */
+                    LOG_W("[对焦] 等待focus超时,补发指令(%d/%d)",
+                          g_af.retry_cnt, AF_FOCUS_RETRY_MAX);
+                    char *p1 = makeJson_Warn("movy", "4");
+                    DTU_Write("%s", p1);
+                    rt_free(p1);
+                    DTU_Write("{\"cmd\": \"takephoto\" }");
+                } else {
+                    LOG_E("[对焦] focus超时,重试%d次无回复,中止对焦", AF_FOCUS_RETRY_MAX);
+                    g_af.active = false;
+                    device_status.autotakepic = 0;
+                    ctr_led(OFF);
+                    slidelock();
+                    report_takephoto_duration();   /* focus超时中止, 上报对焦拍照持续时间 */
+                }
             }
+            /* 自动对焦:有新清晰度值时处理 */
+           if (g_af.sharpness_updated) {
+               auto_focus_process();
+           }
+           /* Y轴校准:有新清晰度值时处理 */
+           if (g_cal.sharpness_updated) {
+               calibrate_process();
+           }
         }else {
             t_takephoto = 0;
         }
@@ -501,7 +648,6 @@ static void Ctr_Mortor_entry(void* parameter)
                 DTU_Write("%s",photo);
                 rt_free(photo);
                 device_status.autotakepic = 4;
-                rt_timer_start(timer_takephoto);
             }
         }
         if(device_status.autotakepic==3)
@@ -528,25 +674,18 @@ static void Ctr_Mortor_entry(void* parameter)
             DTU_Write("%s",photo);
             rt_free(photo);
             device_status.autotakepic = 4;
-            rt_timer_start(timer_takephoto);
         }
         if(device_status.autotakepic == 4)
         {
-            device_status.autotakepic = 2;
-            g_best_sharpness = 0.0;    // 全局最佳清晰度
-            g_best_pos = 0;                   // 全局最佳位置
-            g_last_sharpness = 0.0;    // 上一次移动后的清晰度
-            g_initial_move = true;           // 初始方向判断标志
-            maxIterations = 100;
-            counter_sharpness_diff = 0;
-            dir = 1;
-            stepSize = 20;     // 初始步长(单位:步进电机脉冲数)
-            current_pos = 0;  // 根据实际类型修改(int/float等)
+            /* 根据当前模式只初始化对应的状态机:
+             * 校准模式(custom calibrate_slide!=0)下不应激活自动对焦的重试检测 */
+            if (device_status.calibrate_slide == 0) {
+                auto_focus_init();
+            } else {
+                calibrate_init();
+            }
             slide_para.ystep = 0;
-            g_peak_counter = 0;
-            g_last_rising = false;
-            focus_done = false;
-            //启动超时检测定时器
+            device_status.autotakepic = 2;
         }
         if(device_status.fsl_sw==1)
         {
@@ -556,10 +695,10 @@ static void Ctr_Mortor_entry(void* parameter)
         if(device_status.auto_test_sw==1)
         {
             //开始采集风机持续5S
-            ctr_router(ON);
+            ctr_Heat(ON);
             rt_thread_delay(1000*60);
             //关闭采集风机
-            ctr_router(OFF);
+            ctr_Heat(OFF);
             //胶带传送
             turnlimit();
             rt_thread_delay(1000);
@@ -571,6 +710,7 @@ static void Ctr_Mortor_entry(void* parameter)
             DTU_Write(take_start);
             rt_free(take_start);
         }
+
         rt_thread_delay(100);
     }
 }

+ 1 - 0
Application_cbd_apm32f1/applications/hmi.h

@@ -35,5 +35,6 @@ void bubblesort(int a[], int n);
 
 
 void send_signal(int sig);
+void report_takephoto_duration(void);
 
 #endif /* APPLICATIONS_INC_HMI_H_ */

+ 1 - 2
Application_cbd_apm32f1/applications/selfcheck.c

@@ -44,7 +44,6 @@ static void t_takephoto_callback(void *parameter)
     ctr_led(OFF);
     //关闭滑台驱动
     slidelock();
-    Beep_Tip(5000);
 }
 
 int selfcheck(uint8_t type)
@@ -302,5 +301,5 @@ int rt_software_timer_init(void)
     }
 }
 
-INIT_APP_EXPORT(rt_software_timer_init);
+//INIT_APP_EXPORT(rt_software_timer_init);
 

+ 1 - 1
Application_cbd_apm32f1/packages/EasyFlash-v4.1.0/inc/ef_cfg.h

@@ -92,7 +92,7 @@
 #define EF_START_ADDR             PKG_EASYFLASH_START_ADDR
 
 /* ENV area size. It's at least one empty sector for GC. So it's definition must more then or equal 2 flash sector size. */
-#define ENV_AREA_SIZE             (EF_ERASE_MIN_SIZE * 256) /* default is the double erase min size */
+#define ENV_AREA_SIZE             (EF_ERASE_MIN_SIZE * 16) /* default is the double erase min size */
 
 /* print debug information of flash */
 #ifdef PKG_EASYFLASH_DEBUG

+ 33 - 0
Application_cbd_apm32f1/readme.md

@@ -1,3 +1,36 @@
+# 2026-09-05 更新说明
+	#define VERSION_BZY         "2.9.32"                   //孢子仪
+	1、修复拍照持续时间不上传问题:上报时机改为收到关闭LED指令(led_off)或触发超时(拍照超时/focus超时中止)时执行,修复原判断条件中未定义变量导致的不触发上报;
+# 2026-09-05 更新说明
+	#define VERSION_BZY         "2.9.31"                   //孢子仪
+	1、对焦峰值确认后电机回退到峰值位置(best_pos):检测到清晰度上升后连续3次下降即确认峰值完成,回退返回并停在最佳聚焦位置;
+# 2026-09-05 更新说明
+	#define VERSION_BZY         "2.9.30"                   //孢子仪
+	1、对焦算法优化:检测到清晰度上升后,连续3次清晰度下降才反转方向,避免波动误反转;
+# 2026-09-05 更新说明
+	#define VERSION_BZY         "2.9.29"                   //孢子仪
+	1、movy发送后增加focus回传超时重传:5S未收到{"focus":xx}则重发movy,最多重传3次,避免对焦卡死;
+# 2026-09-05 更新说明
+	#define VERSION_BZY         "2.9.28"                   //孢子仪
+	1、增加对焦拍照持续时间检测与上报:autotakepic 0->非0时开始计时,任务结束(非0->0)后上报持续时间预警消息 takephoto_duration(秒);
+# 2026-09-05 更新说明
+	#define VERSION_BZY         "2.9.27"                   //孢子仪
+	1、对焦拍照代码结构优化和2.1一致;
+	2、增加对焦超时处理;
+# 2026-09-03 更新说明
+	#define VERSION_BZY         "2.9.26"                   //孢子仪
+	1、增加对焦拍照持续时间检测:autotakepic 0->非0时开始计时,任务结束(非0->0)后上报持续时间预警消息 takephoto_duration(秒);
+# 2026-09-03 更新说明
+	#define VERSION_BZY         "2.9.25"                   //孢子仪
+	1、优化对焦峰值检测逻辑:连续上升(≥3次)进入上升趋势,再连续下降(≥2次)才确认峰值,抑制噪声误判;峰值确认后转为小步进(2)精细对焦并反转回扫,二次确认且接近最佳即完成对焦;
+# 2026-09-03 更新说明
+	#define VERSION_BZY         "2.9.24"                   //孢子仪
+	1、优化工作状态检测与工作流程:work_done 改为采集段结束(下降沿)触发一次,修复多段采集时结束事件相互干扰/遗漏问题;
+	2、alarmCheck 移除 10s 阻塞与刷屏日志,检测轮询加快至 1s,修复同小时窗口误判无效的 bug;
+	3、工作流程线程由 10s 轮询加快至 1s,提取 exec_work_done 并由工作流程线程独占清零 work_done,消除双写竞态;
+# 2026-08-31 更新说明
+	#define VERSION_BZY         "2.9.22"                   //孢子仪
+	1、修复ctr_motor线程栈溢出;
 # 2026-08-04 更新说明
 	#define VERSION_BZY         "2.9.21"                   //孢子仪
 	1、修复lwjson解析出现帧错乱的问题;