فهرست منبع

#IQRV #comment [Module] 资源实体一些过长函数的调整

gifur 4 سال پیش
والد
کامیت
65b9048506
3فایلهای تغییر یافته به همراه199 افزوده شده و 289 حذف شده
  1. 26 21
      Module/mod_ResourceWatcher/FileInfo.h
  2. 156 257
      Module/mod_ResourceWatcher/ResourceWatcherFSM.cpp
  3. 17 11
      Module/mod_ResourceWatcher/ResourceWatcherFSM.h

+ 26 - 21
Module/mod_ResourceWatcher/FileInfo.h

@@ -128,6 +128,16 @@ static void ByteSprintf(char * outString, double inNum, char inFormat = 'A')
 #endif //_MSC_VER
 }
 
+static void PrintDiskStatus(LPCTSTR dir, const unsigned long long& uiDiskFreeSize, const unsigned long long& uiDiskOverallSize)
+{
+    char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
+    char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
+    ByteSprintf(szResult, (double)uiDiskFreeSize);
+    ByteSprintf(szResult2, (double)uiDiskOverallSize);
+    double dFreeRate = (uiDiskFreeSize * kConversion[3]) / (uiDiskOverallSize * kConversion[3]);
+    Dbg("[Disk(%s)] total: %s, free: %s, rate: %.1lf%%.", dir, szResult, szResult2, dFreeRate * 100);
+}
+
 struct TmpFileInfo
 {
 #if defined(_MSC_VER)
@@ -203,7 +213,7 @@ struct DiskInfo
     //平均每天录像的数目(当天无录像的不考虑)
     UINT mUAverageFileCreated;
 
-    //平均录像文件的大小(Bytes)
+    //需预留的磁盘空间大小(Bytes)
     ULARGE_INTEGER mUiFreeBytesRequired;
 
     //当前最大的录像文件
@@ -478,9 +488,10 @@ struct DiskInfo
         Dbg("平均每天录像的数目 : %u", mUAverageFileCreated);
 
         //平均录像文件的大小 TODO: 
-        mUliAverageFileSize = mUiAllVideoFilesBytes;
         if (mUVideoFileCount != 0) {
             mUliAverageFileSize = mUiAllVideoFilesBytes / mUVideoFileCount;
+        } else {
+            mUliAverageFileSize = mUiAllVideoFilesBytes;
         }
         ByteSprintf(szResult, (double)mUliAverageFileSize);
         Dbg("平均录像文件的大小 : %s", szResult);
@@ -491,47 +502,47 @@ struct DiskInfo
         //至少需预留的磁盘空间大小 = 平均每天需要的大小*要求留存的天数
         const unsigned long long uiForecastSpaceAvail = uiForecastDailySpace * uRequredDays;
         ByteSprintf(szResult, (double)uiForecastSpaceAvail);
-        Dbg("需预留的磁盘空间大小 : %s", szResult);
+        Dbg("需预留的磁盘空间大小(平均每个文件大小 * 平均每天文件数量 * 要求留存的天数#%u) : %s", uRequredDays, szResult);
         mUiFreeBytesRequired = uiForecastSpaceAvail;
 
-
         uiRequireBytes = uiForecastSpaceAvail;
         return (mBAverageAvailable = TRUE);
     }
 
+    /**
+    uiAdjustmentFactor: 增量调整因子
+    */
     BOOL IsNeedToDoClearJobEx(LPCTSTR lpszDiskPath,
                               const unsigned long long& uiRequiredByts,
-                              const unsigned long long& uiAdjustmentFactor, unsigned long long* pUiRealRequiredByts)
+                              const unsigned long long& uiAdjustmentFactor, 
+                              unsigned long long* pUiRealRequiredByts)
     {
         BOOL bRet = FALSE;
         if (lpszDiskPath == NULL || strlen(lpszDiskPath) == 0)
             return FALSE;
         if (pUiRealRequiredByts != NULL) {
-            pUiRealRequiredByts = 0;
+            *pUiRealRequiredByts = 0;
         }
         unsigned long long uiDiskOverallSize;
         unsigned long long uiDiskFreeSize;
         bRet = GetDiskSpace(lpszDiskPath, uiDiskOverallSize, uiDiskFreeSize);
         if (bRet) {
             assert(uiDiskOverallSize != 0);
-            char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
-            char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
-            ByteSprintf(szResult, (double)uiDiskFreeSize);
-            ByteSprintf(szResult2, (double)uiDiskOverallSize);
-            Dbg("Current operated disk(%s) : %s / %s", lpszDiskPath, szResult, szResult2);
-            unsigned long long uiForecastSpaceAvail;
-            uiForecastSpaceAvail = uiRequiredByts + uiAdjustmentFactor;
+            PrintDiskStatus(lpszDiskPath, uiDiskFreeSize, uiDiskOverallSize);
+            const unsigned long long uiForecastSpaceAvail = uiRequiredByts + uiAdjustmentFactor;
             if (uiForecastSpaceAvail > uiDiskFreeSize) {
                 unsigned long long uiTemp;
                 uiTemp = uiForecastSpaceAvail - uiDiskFreeSize;
+                char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
                 ByteSprintf(szResult, (double)uiTemp);
                 Dbg("More space required : %s", szResult);
                 if (pUiRealRequiredByts != NULL) {
                     *pUiRealRequiredByts = uiTemp;
                 }
+                return TRUE;
             }
         }
-        return bRet;
+        return FALSE;
     }
 
     BOOL IsNeedToDoClearJob(const unsigned long long& uiAdjustmentFactor, unsigned long long* pUiRealRequiredByts)
@@ -575,11 +586,7 @@ struct DiskInfo
         return bResult;
     }
 
-
-	static BOOL GetDiskSpace(
-		LPCTSTR lpszVideoPath,
-		unsigned long long& uiTotalByteNumber,
-		unsigned long long& uiTotalFreeByteNumber)
+	static BOOL GetDiskSpace(LPCTSTR lpszVideoPath,unsigned long long& uiTotalByteNumber, unsigned long long& uiTotalFreeByteNumber)
 	{
         struct statfs buf;
         int result = statfs(lpszVideoPath, &buf);
@@ -587,12 +594,10 @@ struct DiskInfo
             Dbg("statfs failed: %d", errno);
             return FALSE;
         }
-
 		uiTotalByteNumber = (((long long)buf.f_bsize * (long long)buf.f_blocks));
 		uiTotalFreeByteNumber = (((long long)buf.f_bsize * (long long)buf.f_bfree));
 		return TRUE;
 	}
-
 #endif //_MSC_VER
 };
 

+ 156 - 257
Module/mod_ResourceWatcher/ResourceWatcherFSM.cpp

@@ -25,7 +25,6 @@ LPCTSTR UPLOAD_VIDEO_PATH  = "UploadVideo";
 
 const int AD0_DAY_OF_BACKWARD = 7;
 
-const int TIMER_ID_CLEARVIDEO_ENHANCE = 1;
 const int TIMER_INTERVAL_CLEARVIDEO_ENHANCE = 60 * 1000;
 
 const int MAX_VERSION_PATH = 256;
@@ -70,7 +69,7 @@ private:
 ResourceWatcherFSM::ResourceWatcherFSM(void)
 	:m_IsPadDevice(FALSE)
 	, m_bGetStatusRotate(FALSE)
-	,m_csUploadVideoPath(true)
+	,m_uploadedVideoDirPath(true)
 	, m_csDelFileSuffix(true)
     ,m_nDayOfBackward(DEFAULT_DAY_OF_BACKWARD)
 	, m_failDelCnt(0)
@@ -122,7 +121,7 @@ void ResourceWatcherFSM::ClearVideoQueue()
     VideoDailyRecord.clear();
 }
 
-void ResourceWatcherFSM::PrintResult()
+void ResourceWatcherFSM::PrintVideEmurateResult()
 {
     char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
 #if defined(_MSC_VER)
@@ -234,10 +233,9 @@ unsigned int ResourceWatcherFSM::s1_on_event(FSMEvent* e)
 		break;
 	case USER_EVT_CLEAR_UPLOADEDVIDEOFILES_FINISHED:
 		{
-			Dbg("s1_on_event::There are %d file(s), successfully delete %d file(s) in path %s",
-				e->param2, e->param1, (LPCTSTR)m_csUploadVideoPath);
-			if(m_failDelCnt != 0)
-			{
+			Dbg("%s::There are %d file(s), successfully delete %d file(s) in path %s", __FUNCTION__,
+				e->param2, e->param1, (LPCTSTR)m_uploadedVideoDirPath);
+			if(m_failDelCnt != 0) {
 				CSimpleStringA strMsg = CSimpleStringA::Format("There are %d matched files should be deleted", m_failDelCnt);
 				LogWarn(Severity_Middle, Error_Unexpect, 0, (LPCTSTR)strMsg);
 			}
@@ -246,16 +244,6 @@ unsigned int ResourceWatcherFSM::s1_on_event(FSMEvent* e)
 		}
 		e->SetHandled();
 		break;
-	case EVT_TIMER:
-		{
-			if(e->param1 == TIMER_ID_CLEARVIDEO_ENHANCE)
-			{
-				ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
-				GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
-			}
-		}
-		e->SetHandled();
-		break;
 	case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
 		{
 			PostEventFIFO(new FSMEvent(USER_EVT_VERSION_CLEAR));
@@ -323,16 +311,6 @@ unsigned int ResourceWatcherFSM::s2_on_event(FSMEvent* e)
 			e->SetHandled();
 		}
 		break;
-	case EVT_TIMER:
-		{
-			if(e->param1 == TIMER_ID_CLEARVIDEO_ENHANCE)
-			{
-				ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
-				GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
-			}
-		}
-		e->SetHandled();
-		break;
 	case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
 		{
 		}
@@ -387,16 +365,6 @@ unsigned int ResourceWatcherFSM::s3_on_event(FSMEvent* e)
 			e->SetHandled();
 		}
 		break;
-	case EVT_TIMER:
-		{
-			if(e->param1 == TIMER_ID_CLEARVIDEO_ENHANCE)
-			{
-				ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
-				GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
-			}
-		}
-		e->SetHandled();
-		break;
 	case USER_EVT_CLEAR_VIDEOFILE_ENHANCE:
 		{
 			ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
@@ -501,18 +469,18 @@ ErrorCodeEnum ResourceWatcherFSM::OnInit()
 	if(!sysInfo.strMachineType.Compare("RVC.Pad", true)) {
 		m_IsPadDevice = TRUE;
 	}
-	erroCode = GetEntityBase()->GetFunction()->GetPath("LocalVideo", m_csUploadVideoPath);
-    if (erroCode != Error_Succeed || m_csUploadVideoPath.IsNullOrEmpty()) {
+	erroCode = GetEntityBase()->GetFunction()->GetPath("LocalVideo", m_uploadedVideoDirPath);
+    if (erroCode != Error_Succeed || m_uploadedVideoDirPath.IsNullOrEmpty()) {
         return Error_NotInit;
     }
     const BOOL bFirstRun = DetectIsFirstRunAtBoot();
 	Dbg("to initialize critical section...");
 	InitializeCriticalSection(&g_csVideoMoreClear);
     InitialVolumes();
-    //InitBlackList();
+    InitBlackList();
 	readVideoStoreData();
 	m_bReadyFlag = IsNeedToFirstClear();
-	Dbg("Retrieve uploadedVideo path[%s], backwardDays(%d) done(%d)",  (LPCTSTR)m_csUploadVideoPath, m_nDayOfBackward, !m_bReadyFlag);
+	Dbg("Retrieve uploadedVideo path[%s], backwardDays(%d) done(%d)",  (LPCTSTR)m_uploadedVideoDirPath, m_nDayOfBackward, !m_bReadyFlag);
 
 #if defined(_MSC_VER)
     if (!sysInfo.strMachineType.Compare("RVC.Desk2S", true)) {
@@ -526,8 +494,7 @@ ErrorCodeEnum ResourceWatcherFSM::OnInit()
             Dbg("last set audio output time is earlier than system boot time!");
             Dbg("Start to Set Audio output device");
             if (SetDefaultAudioDevice()) {
-                spRunConfig->WriteConfigValue("Device", "SetAudioOutput", CSimpleStringA::Format("0x%08X",
-                                                                                                 (DWORD)CSmallDateTime::GetNow()));
+                spRunConfig->WriteConfigValue("Device", "SetAudioOutput", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
             } else {
                 LogWarn(Severity_High, Error_AudioOut, 0, "Set default video output failed!!");
             }
@@ -654,102 +621,87 @@ BroadCastPoint:
 	return 0;
 }
 
-int ResourceWatcherFSM::ClearVideoFiles(int& newDeletedFilesNum, int initFlag)
+void ResourceWatcherFSM::AppendVideoSizeTogether()
 {
-	LOG_FUNCTION();
-	newDeletedFilesNum = 0;
-	ClearVideoQueue();
-	CSimpleStringA filePath = m_csUploadVideoPath;
+    Dbg("Add UploadFile size together...");
 #if defined(_MSC_VER)
-		filePath += "\\*";
-#endif //_MSC_VER
-	Dbg("(InitFlag:%d) filePath %s", initFlag, (LPCTSTR)filePath);
-	newDeletedFilesNum = 0;
-	m_failDelCnt = 0;
-	int nRet = DeleteBackwardVideoFile((LPCTSTR)filePath, newDeletedFilesNum, m_failDelCnt, initFlag);
-	PrintResult();
-	Dbg("nRet: %d, newDeletedFilesNum:%d, video counts:%d", nRet, newDeletedFilesNum, m_VideoFiles.size());
-	LOG_ASSERT(nRet - newDeletedFilesNum == m_VideoFiles.size());
-	
-	CSmartPointer<IConfigInfo> spConfigRun;
-	GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
-
-	if(!!initFlag)
-	{
-		Dbg("Add UploadFile size together...");
-#if defined(_MSC_VER)
-        ULARGE_INTEGER uiAdditionBytes;
-        CalculateUploadFileSize(uiAdditionBytes);
-        mAllVideoFileSizeCal.QuadPart += uiAdditionBytes.QuadPart;
-        diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
+    ULARGE_INTEGER uiAdditionBytes;
+    CalculateWillUploadDirSize(uiAdditionBytes);
+    mAllVideoFileSizeCal.QuadPart += uiAdditionBytes.QuadPart;
+    diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
 #else
-        unsigned long long uiAdditionBytes;
-        CalculateUploadFileSize(uiAdditionBytes);
-        mAllVideoFileSizeCal += uiAdditionBytes;
-        diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
+    unsigned long long uiAdditionBytes;
+    CalculateWillUploadDirSize(uiAdditionBytes);
+    mAllVideoFileSizeCal += uiAdditionBytes;
+    diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
 #endif //_MSC_VER
+}
 
-		do 
-		{
-            const_map_cu_iter citer = VideoDailyRecord.cbegin();
-            UINT uCount = 0;
-            while (citer != VideoDailyRecord.cend()) {
-                Dbg("date[%d]: %d", (citer->first), citer->second);
-                uCount += citer->second;
-                citer++;
-            }
-            Dbg("uCount#%d, video size#%d", uCount, m_VideoFiles.size());
-			diskInfo.CalAverRequreSpaceEachDay(mAllVideoFileSizeCal, uCount, VideoDailyRecord.size(), BASE_AVAILALBE_DATE_COUNT, mUiRequireBytes);
-		} while (false);
-
-		char displayTime[MAX_PATH] = { 0 };
+void ResourceWatcherFSM::CalculateFreeDiskNeeded()
+{
+    const_map_cu_iter citer = VideoDailyRecord.cbegin();
+    UINT uCount = 0;
+    while (citer != VideoDailyRecord.cend()) {
+        Dbg("date[%d]: %d", (citer->first), citer->second);
+        uCount += citer->second;
+        citer++;
+    }
+    Dbg("count %d and video file size#%d", uCount, m_VideoFiles.size());
+    diskInfo.CalAverRequreSpaceEachDay(mAllVideoFileSizeCal, 
+									   uCount, VideoDailyRecord.size(), 
+									   BASE_AVAILALBE_DATE_COUNT, mUiRequireBytes);
+}
 
+void ResourceWatcherFSM::RecordFreeDiskNeededToRunCfg()
+{
+    CSmartPointer<IConfigInfo> spConfigRun;
+    GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
 #if defined(RVC_OS_WIN)
-        FILETIME ftCurTime;
-        GetSystemTimeAsFileTime(&ftCurTime);
-        SYSTEMTIME stUTC, stLocal;
-        FileTimeToSystemTime(&ftCurTime, &stUTC);
-        SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
-        const int nYear = stLocal.wYear;
-        const int nMonth = stLocal.wMonth;
-        const int nDay = stLocal.wDay;
-		GetTimeFormatStr(displayTime, MAX_PATH, &ftCurTime);
-		spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes.QuadPart);
+    spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes.QuadPart);
 #else
-        time_t ct = time(NULL);
-		const tm* ltm = localtime(&ct);
-        const int nYear = ltm->tm_year + 1900;
-        const int nMonth = ltm->tm_mon + 1;
-        const int nDay = ltm->tm_mday;
-		GetTimeFormatStr(displayTime, MAX_PATH, &ct);
-		//TODO(Gifur): Check the framework
-		spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes);
-		{
-            char tmp[32];
-            sprintf_s(tmp, sizeof(tmp), "0x%" PRIx64 "", mUiRequireBytes);
-			Dbg("WriteConfigValueHexInt: %s", tmp);
-			Dbg("WriteConfigValueHexInt: %d, %d, %d", nYear, nMonth, nDay);
-		}
-
+    spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes);
 #endif //RVC_OS_WIN
-        spConfigRun->WriteConfigValueInt("Video", "FilesNum", nRet);
-        spConfigRun->WriteConfigValueInt("Video", "Deleted", newDeletedFilesNum);
-        spConfigRun->WriteConfigValueInt("Video", "FailedDel", m_failDelCnt);
-        spConfigRun->WriteConfigValue("Video", "LastTime", displayTime);
-        spConfigRun->WriteConfigValueInt("Video", "Year", nYear);
-        spConfigRun->WriteConfigValueInt("Video", "Month", nMonth);
-        spConfigRun->WriteConfigValueInt("Video", "Day", nDay);
-        m_bReadyFlag = false;
-	}
-	else
-	{
+	spConfigRun->WriteConfigValue("LastClearTime", "Video", (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
+    m_bReadyFlag = false;
+}
+
+void ResourceWatcherFSM::GetFreeDiskNeededFromRunCfg()
+{
+    Dbg("Retrieve from runcfg about required bytes.");
+    CSmartPointer<IConfigInfo> spConfigRun;
+    GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
 #if defined(_MSC_VER)
-		spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes.QuadPart);
+    spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes.QuadPart);
 #else
-		UINT64 value(0);
-        spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes", value);
-		mUiRequireBytes = value;
+    UINT64 value(0);
+    spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes", value);
+    mUiRequireBytes = value;
+#endif //_MSC_VER
+}
+
+int ResourceWatcherFSM::CleanVideoFiles(int& newDeletedFilesNum, int initFlag)
+{
+	LOG_FUNCTION();
+	newDeletedFilesNum = 0;
+	ClearVideoQueue();
+	CSimpleStringA filePath = m_uploadedVideoDirPath;
+#if defined(_MSC_VER)
+		filePath += "\\*";
 #endif //_MSC_VER
+	Dbg("(InitFlag:%d) filePath %s", initFlag, (LPCTSTR)filePath);
+	newDeletedFilesNum = 0;
+	m_failDelCnt = 0;
+	const int nRet = RemoveExpireVideoFileAndRecord((LPCTSTR)filePath, newDeletedFilesNum, m_failDelCnt, initFlag);
+	PrintVideEmurateResult();
+	Dbg("nRet: %d, new Deleted Files Num:%d, video counts:%d", nRet, newDeletedFilesNum, m_VideoFiles.size());
+	LOG_ASSERT(nRet - newDeletedFilesNum == m_VideoFiles.size());
+
+	if(!!initFlag) {
+		AppendVideoSizeTogether();
+		CalculateFreeDiskNeeded();
+		RecordFreeDiskNeededToRunCfg();
+	} else {
+		GetFreeDiskNeededFromRunCfg();
 	}
 	return nRet;
 }
@@ -777,7 +729,7 @@ void ResourceWatcherFSM::CalculateBackTime(PFILETIME ftResultTime, int days)
     return;
 }
 
-BOOL ResourceWatcherFSM::CalculateUploadFileSize(ULARGE_INTEGER& uiBytesCal)
+BOOL ResourceWatcherFSM::CalculateWillUploadDirSize(ULARGE_INTEGER& uiBytesCal)
 {
     uiBytesCal.QuadPart = 0;
 #else
@@ -788,18 +740,15 @@ void ResourceWatcherFSM::CalculateBackTime(time_t* ftResultTime, int days)
     *ftResultTime = ftBackTime;
     return;
 }
-BOOL ResourceWatcherFSM::CalculateUploadFileSize(unsigned long long& uiBytesCal)
+BOOL ResourceWatcherFSM::CalculateWillUploadDirSize(unsigned long long& uiBytesCal)
 {
     uiBytesCal = 0;
 #endif //RVC_OS_WIN
 
     BOOL bRet = FALSE;
-    ErrorCodeEnum ec = Error_Unexpect;
-    CSmartPointer<IConfigInfo> spConfig;
-    ec = GetEntityBase()->GetFunction()->OpenConfig(Config_Software, spConfig);
     CSimpleStringA uploadVideoPath;
     CSimpleStringA tmpValue;
-    ec = GetEntityBase()->GetFunction()->GetPath(UPLOAD_VIDEO_PATH, uploadVideoPath);
+	ErrorCodeEnum ec = GetEntityBase()->GetFunction()->GetPath(UPLOAD_VIDEO_PATH, uploadVideoPath);
     if (uploadVideoPath.GetLength() <= 0) ec = Error_Param;
     if (ec == Error_Succeed) {
         Dbg("UploadVideo path: %s", (LPCTSTR)uploadVideoPath);
@@ -822,7 +771,7 @@ BOOL ResourceWatcherFSM::CalculateUploadFileSize(unsigned long long& uiBytesCal)
     return (ec == Error_Succeed);
 }
 
-int ResourceWatcherFSM::DeleteBackwardVideoFile(LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt, const int nFlag)
+int ResourceWatcherFSM::RemoveExpireVideoFileAndRecord(LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt, const int nFlag)
 {
 	int fileCnt = 0;
 	int fileLength = strlen(dirName);
@@ -854,7 +803,7 @@ int ResourceWatcherFSM::DeleteBackwardVideoFile(LPCTSTR dirName, int& deletedFil
                 tempFilePath[fileLength - 1] = '\0';
                 strcat_s(tempFilePath, foundFileData.cFileName);
                 strcat_s(tempFilePath, "\\*");
-                fileCnt += DeleteBackwardVideoFile((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
+                fileCnt += RemoveExpireVideoFileAndRecord((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
             }
         } else {
             strcpy_s(searchFilePath, dirName);
@@ -913,7 +862,7 @@ int ResourceWatcherFSM::DeleteBackwardVideoFile(LPCTSTR dirName, int& deletedFil
 		}
         const bool isdir = !!(S_ISDIR(st.st_mode));
         if (isdir) {
-            fileCnt += DeleteBackwardVideoFile((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
+            fileCnt += RemoveExpireVideoFileAndRecord((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
 		} else {
             if (nFlag == 1 && st.st_mtime < tmp_time) {
 				GetTimeFormatStr(displayTime, MAX_PATH, &st.st_mtime);
@@ -935,10 +884,8 @@ int ResourceWatcherFSM::DeleteBackwardVideoFile(LPCTSTR dirName, int& deletedFil
 }
 
 #if defined(RVC_OS_WIN)
-
 BOOL ResourceWatcherFSM::GetCPUBrand(CSimpleStringA& csCpuBrand)
 {
-
     char CPUBrandString[0x40];
     int CPUInfo[4] = { -1 };
     unsigned nExIds;
@@ -994,7 +941,7 @@ ErrorCodeEnum ResourceWatcherFSM::GetCpuType(
 	SpReqAnsContext<ResourceWatcherService_GetCpuType_Req, ResourceWatcherService_GetCpuType_Ans>::Pointer ctx)
 {
     LOG_FUNCTION();
-
+	ErrorCodeEnum ec = Error_Succeed;
 #if defined(RVC_OS_WIN)
 
     ErrorCodeEnum erroCode = Error_Succeed;
@@ -1038,11 +985,12 @@ ErrorCodeEnum ResourceWatcherFSM::GetCpuType(
     }
     return Error_Succeed;
 #else
-    LogWarn(Severity_Middle, Error_NotSupport, 0, CSimpleStringA::Format("%s is not supported!", __FUNCTION__));
+	ec = Error_NotSupport;
+    LogWarn(Severity_Middle, ec, 0, CSimpleStringA::Format("%s is not supported!", __FUNCTION__));
 	if (ctx != NULL) {
-		ctx->Answer(Error_NotSupport);
+		ctx->Answer(ec);
 	}
-    return Error_NotSupport;
+    return ec;
 #endif //RVC_OS_WIN
 }
 
@@ -1057,12 +1005,8 @@ BOOL ResourceWatcherFSM::RemoveDuplicateCenterSettingFiles()
 		Dbg("OpenConfig of 'Config_Run' failed 0x%x(%d).", erroCode, erroCode);
 		return FALSE;
 	}
-	CSimpleStringA ssCurTarget = "CenterSetting";
 	int nLastTaskTime(0);
-	int nFailedNum(0);
-	spConfigRun->ReadConfigValueInt("ClearTask", "LastTime", nLastTaskTime);
-	spConfigRun->ReadConfigValueInt("ClearTask", "FailedNum", nFailedNum);
-
+	spConfigRun->ReadConfigValueInt("LastClearTime", "CenterSetting", nLastTaskTime);
 	if (IsTodayDone(nLastTaskTime)) {
 		return TRUE;
 	}
@@ -1081,37 +1025,29 @@ BOOL ResourceWatcherFSM::RemoveDuplicateCenterSettingFiles()
 	int nDelFailed = 0;
 	int nfileSum = ClearSpecifieFile(DFT_CenterSetting, ssFilePath, nDelSuc, nDelFailed);
 	Dbg("#CenterSetting#There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
-	spConfigRun->WriteConfigValue("ClearTask", "Target", (LPCTSTR)ssCurTarget);
-	spConfigRun->WriteConfigValue("ClearTask", "LastTime", (const char*) CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
-	spConfigRun->WriteConfigValueInt("ClearTask", "TargetNum", nDelSuc+nDelFailed);
-	spConfigRun->WriteConfigValueInt("ClearTask", "FailedNum", nDelFailed);
+	spConfigRun->WriteConfigValue("LastClearTime", "CenterSetting", (const char*) CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
 	return TRUE;
 }
 
 int ResourceWatcherFSM::ClearSpecifieFile(DealFileType fileType, LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt)
 {
-
 	LOG_FUNCTION();
-
 	int nRes;
 	int nfileCnt = 0;
 	int fileLength = strlen(dirName);
 	char searchFilePath[MAX_PATH] = {0};
 	char tempFilePath[MAX_PATH] = {0};
-
 	char displayTime[MAX_PATH] = {0};
 
 #if defined(RVC_OS_WIN)
 
     WIN32_FIND_DATA fndFileData;
     HANDLE hFind;
-
     hFind = FindFirstFile(dirName, &fndFileData);
     if (hFind == INVALID_HANDLE_VALUE) {
         printf("FindFirstFile failed (%d) \n", GetLastError());
         return -2;
     }
-
 	do 
 	{
         if ((fndFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
@@ -1131,12 +1067,12 @@ int ResourceWatcherFSM::ClearSpecifieFile(DealFileType fileType, LPCTSTR dirName
             strcat_s(searchFilePath, fndFileData.cFileName);
             if (fileType == DFT_Ad0) {
                 if (CompareFileTime(&mftAd0RemoveTime, &fndFileData.ftLastWriteTime) >= 0) {
-                    nRes = DoSomethingWith(fileType, searchFilePath, fndFileData.cFileName);
+                    nRes = RemoveSpecifiedFile(fileType, searchFilePath, fndFileData.cFileName);
                 } else {
                     nRes = 0;
                 }
             } else {
-                nRes = DoSomethingWith(fileType, searchFilePath, fndFileData.cFileName);
+                nRes = RemoveSpecifiedFile(fileType, searchFilePath, fndFileData.cFileName);
             }
             if (nRes == -1) deleteFailedCnt++;
             else if (nRes == 1) deletedFileCnt++;
@@ -1176,7 +1112,7 @@ int ResourceWatcherFSM::ClearSpecifieFile(DealFileType fileType, LPCTSTR dirName
             if (nRes >= 0) nfileCnt += nRes;
 		} else if(!isdir) {
             if (fileType != DFT_Ad0 || (CompareVideoFileTime(&mftAd0RemoveTime, &stFile.st_mtime) >= 0)) {
-				nRes = DoSomethingWith(fileType, tempFilePath, dp->d_name);
+				nRes = RemoveSpecifiedFile(fileType, tempFilePath, dp->d_name);
             } else {
 				nRes = 0;
             }
@@ -1191,11 +1127,10 @@ int ResourceWatcherFSM::ClearSpecifieFile(DealFileType fileType, LPCTSTR dirName
 	return nfileCnt;
 }
 
-int ResourceWatcherFSM::DoSomethingWith(DealFileType fileType, LPCTSTR szFilePath, LPCTSTR szFileName)
+int ResourceWatcherFSM::RemoveSpecifiedFile(DealFileType fileType, LPCTSTR szFilePath, LPCTSTR szFileName)
 {
 	CSimpleStringA ssFileName = szFileName;
 	if(ssFileName.IsNullOrEmpty()) return FALSE;
-
 	if((fileType == DFT_CenterSetting && ssFileName.IsStartWith("centersetting", true) && !ssFileName.IsEndWith(".ini", true))
 		|| fileType == DFT_Ad0
 		) {
@@ -1229,7 +1164,7 @@ void ResourceWatcherFSM::RecordVideoFileInfomation(LPCTSTR lpFilePath, PWIN32_FI
 	SyncUpdateVideoCreateDaily(&(pWfdata->ftLastWriteTime), 1);
 }
 
-void ResourceWatcherFSM::ClearMoreVideoFiles()
+void ResourceWatcherFSM::CleanMoreVideoFiles()
 {
     EnterCriticalSection(&g_csVideoMoreClear);
     ErrorCodeEnum erroCode = Error_Succeed;
@@ -1240,7 +1175,7 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
     if (m_VideoFiles.empty()) {
         int reseved = 0;
         m_bReadyFlag = IsNeedToFirstClear();
-        int nRes = ClearVideoFiles(reseved, m_bReadyFlag ? 1 : 0);
+        int nRes = CleanVideoFiles(reseved, m_bReadyFlag ? 1 : 0);
         if (nRes - reseved == 0) {
             Dbg("There are no any video files in facts.");
             SetSysValAndBroadcast(0, "There are no any video files in facts.");
@@ -1252,7 +1187,7 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
     {//更新记录运行时,并等待下一次的自检执行。
         Dbg("empty?");
         int reseved = 0;
-        ClearVideoFiles(reseved);
+        CleanVideoFiles(reseved);
         Dbg("Wait next time to execute...");
         LeaveCriticalSection(&g_csVideoMoreClear);
         return;
@@ -1270,7 +1205,7 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
     if (BfRank > 0) {
         ULARGE_INTEGER uiTotalBytes;
         ULARGE_INTEGER uiFreeDiskBytes;
-        if (DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes)) {
+        if (DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
             //对比上次,剩余的可用磁盘空间更小了。
             if (mUiCalibration.QuadPart >= uiFreeDiskBytes.QuadPart) {
                 Dbg("Previous Set CurRank from %d to %d.", CurRank, BfRank);
@@ -1302,7 +1237,7 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
         ByteSprintf(szResult, (double)uiSpaceRequired.QuadPart);
         Dbg("Required size(%d): %s", CurRank, szResult);
 
-        if (bOK = diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_csUploadVideoPath,
+        if (bOK = diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_uploadedVideoDirPath,
                                                 uiSpaceRequired, uiFactor, &uiSpaceRealRequired)) {
             if (uiSpaceRealRequired.QuadPart == 0) {
                 break;
@@ -1379,26 +1314,20 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
     if (CurRank < 3) {
         ULARGE_INTEGER uiTotalBytes;
         ULARGE_INTEGER uiFreeDiskBytes;
-        if (DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes)) {
+        if (DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
             char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
             ByteSprintf(szResult, (double)uiTotalBytes.QuadPart);
             ByteSprintf(szResult2, (double)uiFreeDiskBytes.QuadPart);
             double dFreeRate = (uiFreeDiskBytes.QuadPart * kConversion[3]) / (uiTotalBytes.QuadPart * kConversion[3]);
             sprintf_s(szResult3, "[Disk# %c:\\] total: %s, free: %s, rate: %.1lf%%.",
-                      m_csUploadVideoPath[0], szResult, szResult2, dFreeRate * 100);
+                      m_uploadedVideoDirPath[0], szResult, szResult2, dFreeRate * 100);
             mUiCalibration.QuadPart = uiFreeDiskBytes.QuadPart;
         } else {
             strcpy_s(szResult3, "It's not enough disk space for recording video !");
         }
         if (CurRank == 0) {
-            //LogError(Severity_Middle, 
-            //	Error_TooSmallBuffer, 
-            //	LOG_ERR_RES_VIDEO_INSUFFICIENT, szResult3);
             CurRank = 4;
-        } else {
-            //SeverityLevelEnum sle = CurRank == 2 ? Severity_Middle : Severity_High;
-            //LogWarn(sle, Error_TooSmallBuffer, LOG_WARN_RES_VIDEO_INSUFFICIENT, szResult3);
-        }
+        } 
     } else {
         strcpy_s(szResult3, "Disk space is enough for recording.");
     }
@@ -1421,11 +1350,10 @@ void ResourceWatcherFSM::RecordVideoFileInfomation(LPCTSTR lpFilePath, struct st
         strcpy(szMaxSizeFilePath, lpFilePath);
 		mMaxFileSize = pWfdata->st_size;
     }
-
 	SyncUpdateVideoCreateDaily(&pWfdata->st_mtime, 1);
 }
 
-void ResourceWatcherFSM::ClearMoreVideoFiles()
+void ResourceWatcherFSM::CleanMoreVideoFiles()
 {
     EnterCriticalSection(&g_csVideoMoreClear);
     ErrorCodeEnum erroCode = Error_Succeed;
@@ -1433,9 +1361,9 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
     CSmartPointer<IConfigInfo> spConfigRun;
     ErrorCodeEnum ecRunCfg = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
 
-    if (m_VideoFiles.empty()) {
+    if (m_VideoFiles.empty() || mUiRequireBytes == 0) {
         int reseved = 0;
-        int nRes = ClearVideoFiles(reseved, IsNeedToFirstClear() ? 1 : 0);
+        int nRes = CleanVideoFiles(reseved, IsNeedToFirstClear() ? 1 : 0);
         if (nRes - reseved == 0) {
             Dbg("There are no any video files in facts.");
             SetSysValAndBroadcast(0, "There are no any video files in facts.");
@@ -1443,68 +1371,59 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
             return;
         }
     }
-    if (mUiRequireBytes == 0)
-    {//更新记录运行时,并等待下一次的自检执行。
-        Dbg("empty?");
-        int reseved = 0;
-        ClearVideoFiles(reseved);
-        Dbg("Wait next time to execute...");
-        LeaveCriticalSection(&g_csVideoMoreClear);
-        return;
-    }
 
-    unsigned long long uiSpaceRequired;
-	unsigned long long uiSpaceRealRequired;
-    int CurRank = 3;
-    int BfRank = 0;
+    int CurRank = 3; //default
+    
+	int BfRank = 0;
     if (spConfigRun->ReadConfigValueInt("Video", "RequiredRank", BfRank) != Error_Succeed || BfRank < 0) {
         BfRank = 0;
     }
-
     if (BfRank > 0) {
 		unsigned long long uiTotalBytes;
 		unsigned long long uiFreeDiskBytes;
-        if (DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes)) {
-            //对比上次,剩余的可用磁盘空间更小了。
-            if (mUiCalibration >= uiFreeDiskBytes) {
-                Dbg("Previous Set CurRank from %d to %d.", CurRank, BfRank);
-				CurRank = BfRank;
-            }
-            mUiCalibration = uiFreeDiskBytes;
+		if (!DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
+            LeaveCriticalSection(&g_csVideoMoreClear);
+            return;
+		}
+        //对比上次,剩余的可用磁盘空间更小了。
+        if (mUiCalibration >= uiFreeDiskBytes) {
+            Dbg("Previous Set CurRank from %d to %d.", CurRank, BfRank);
+            CurRank = BfRank;
         }
+        mUiCalibration = uiFreeDiskBytes;
     }
 
     char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
     int nEnoughLevel = 0;
     unsigned long long uiFactor;
+
+    char displayTime[MAX_PATH] = { 0 };
+    time_t ftSavedTime;
+    CalculateBackTime(&ftSavedTime, m_nMinSavedDay);
+    GetTimeFormatStr(displayTime, MAX_PATH, &ftSavedTime);
+    Dbg("It's SavedTime backtrace: %s", displayTime);
+
     do {
+        uiFactor = DEFAULT_AVAILALBE_DATE_COUNT; // 7天
+		if (CurRank == 2) uiFactor = LESS_AVAILALBE_DATE_COUNT; // 3天
+		else if (CurRank == 1) uiFactor = LEAST_AVAILALBE_DATE_COUNT; // 1天
 
-        uiFactor = DEFAULT_AVAILALBE_DATE_COUNT;
-		if (CurRank == 2) uiFactor = LESS_AVAILALBE_DATE_COUNT;
-		else if (CurRank == 1) uiFactor = LEAST_AVAILALBE_DATE_COUNT;
-		uiSpaceRequired = mUiRequireBytes * uiFactor;
+        unsigned long long uiSpaceRequired = mUiRequireBytes * uiFactor;
         ByteSprintf(szResult, (double)uiSpaceRequired);
-        Dbg("Required size(%d): %s", CurRank, szResult);
-		uiFactor = 0;
-        if (diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_csUploadVideoPath, uiSpaceRequired, uiFactor, &uiSpaceRealRequired)) {
-            if (uiSpaceRealRequired == 0) {
-                break;
-            }
-            char displayTime[MAX_PATH] = { 0 };
-            time_t ftSavedTime;
-            CalculateBackTime(&ftSavedTime, m_nMinSavedDay);
-            GetTimeFormatStr(displayTime, MAX_PATH, &ftSavedTime);
-            Dbg("It's SavedTime backtrace: %s", displayTime);
-
+        Dbg("Required free disk size: %s, current rank: %d", szResult, CurRank);
+        unsigned long long uiMoreSpaceRealRequired(0);
+		unsigned long long uiAdjustment(0);
+        if (diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_uploadedVideoDirPath, uiSpaceRequired, uiAdjustment, &uiMoreSpaceRealRequired) && uiMoreSpaceRealRequired > 0) {
             unsigned long long uiNewFreeBytes(0);
             UINT uDeletedCnt = 0, uFailedDeleteCnt = 0;
             BOOL bTrackBackStop = FALSE;
-            while (!m_VideoFiles.empty() && uiNewFreeBytes < uiSpaceRealRequired) {
+			Dbg("the more space required: %ull.", uiMoreSpaceRealRequired);
+            while (!m_VideoFiles.empty() && uiNewFreeBytes < uiMoreSpaceRealRequired) {
                 TmpFileInfo* pCurFileInfo = m_VideoFiles.top();
                 if (pCurFileInfo != NULL) {
 					GetTimeFormatStr(displayTime, MAX_PATH, &(pCurFileInfo->mftEditTime));
                     if (CompareVideoFileTime(&ftSavedTime, &(pCurFileInfo->mftEditTime)) < 0) {
-						Dbg("yet %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
+						Dbg("stop at %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
                         bTrackBackStop = TRUE;
                         break;
                     }
@@ -1514,7 +1433,7 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
                         Dbg("Delete suc: %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
 						SyncUpdateVideoCreateDaily(&(pCurFileInfo->mftEditTime), -1);
                     } else {
-                        Dbg("[DelFail] File(%s) %u", pCurFileInfo->msFileName.c_str(), GetLastError());
+                        Dbg("[DelFail] File(%s) %d", pCurFileInfo->msFileName.c_str(), errno);
                         uFailedDeleteCnt++;
                     }
                 }
@@ -1525,20 +1444,23 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
             char szOutput[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
             char szOutput2[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
             ByteSprintf(szOutput, (double)uiNewFreeBytes);
-            ByteSprintf(szOutput2, (double)uiSpaceRealRequired);
+            ByteSprintf(szOutput2, (double)uiMoreSpaceRealRequired);
             Dbg("Result(Rank#%d): Succeed deleted<%d>, Failed deleted<%d>, Deleted Size<%s> Real Required Size<%s>",
                 CurRank, uDeletedCnt, uFailedDeleteCnt, szOutput, szOutput2);
-            if (uiNewFreeBytes >= uiSpaceRealRequired) {
+            if (uiNewFreeBytes >= uiMoreSpaceRealRequired) {
                 break;
             }
             --CurRank;
+
+#ifdef WITH_DEBUG
             UINT uCount = 0;
             for (const_map_cu_iter citer = VideoDailyRecord.cbegin(); citer != VideoDailyRecord.cend(); citer++) {
                 uCount += citer->second;
             }
-            Dbg("FileCount(%d)(%d)", uCount, m_VideoFiles.size());
+			Dbg("FileCount(%d)(%d)", uCount, m_VideoFiles.size());
+#endif
+
         } else {
-            LogError(Severity_Middle, Error_Unexpect, 0, "IsNeedToDoClearJobEx invoked failed !");
             LeaveCriticalSection(&g_csVideoMoreClear);
             return;
         }
@@ -1548,12 +1470,12 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
     if (CurRank < 3) {
         unsigned long long uiTotalBytes; 
 		unsigned long long uiFreeDiskBytes;
-        if (DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes)) {
+        if (DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
             char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
             ByteSprintf(szResult, (double)uiTotalBytes);
             ByteSprintf(szResult2, (double)uiFreeDiskBytes);
             double dFreeRate = (uiFreeDiskBytes * kConversion[3]) / (uiTotalBytes * kConversion[3]);
-            sprintf(szResult3, "[Disk# %s] total: %s, free: %s, rate: %.1lf%%.", m_csUploadVideoPath, szResult, szResult2, dFreeRate * 100);
+            sprintf(szResult3, "[Disk# %s] total: %s, free: %s, rate: %.1lf%%.", m_uploadedVideoDirPath.GetData(), szResult, szResult2, dFreeRate * 100);
             mUiCalibration = uiFreeDiskBytes;
         } else {
             strcpy(szResult3, "It's not enough disk space for recording video !");
@@ -1561,10 +1483,10 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
     } else {
         strcpy(szResult3, "Disk space is enough for recording.");
     }
-
     if (CurRank == 0) {
         CurRank = 4;
     }
+
     if (BfRank != CurRank) {
         erroCode = spConfigRun->WriteConfigValueInt("Video", "RequiredRank", CurRank);
     }
@@ -1577,36 +1499,11 @@ void ResourceWatcherFSM::ClearMoreVideoFiles()
 
 bool ResourceWatcherFSM::IsNeedToFirstClear()
 {
-	bool result = true;
-	CSimpleStringA csLstExecTime;
+	int nLastTaskTime(0);
 	CSmartPointer<IConfigInfo> spRunConfig;
 	GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
-	spRunConfig->ReadConfigValue("Video", "LastTime", csLstExecTime);
-	if(csLstExecTime.GetLength() > 1)
-	{
-		int nYear = 0, nMonth = 0, nDay = 0;
-		spRunConfig->ReadConfigValueInt("Video", "Year", nYear);
-		spRunConfig->ReadConfigValueInt("Video", "Month", nMonth);
-		spRunConfig->ReadConfigValueInt("Video", "Day", nDay);
-		if(nYear != 0 && nMonth != 0 && nDay != 0)
-		{
-#if defined(RVC_OS_WIN)
-            SYSTEMTIME stUTC, stLocal;
-            GetSystemTime(&stUTC);
-            SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
-            if (nYear == stLocal.wYear && nMonth == stLocal.wMonth && nDay == stLocal.wDay)
-#else
-            time_t ct = time(NULL);
-            const tm* t = localtime(&ct);
-			if ((nYear == t->tm_year + 1900) && (nMonth == t->tm_mon +1) && (nDay == t->tm_mday))
-#endif //RVC_OS_WIN
-			{
-				Dbg("Video Clear job has been done today in %s", (LPCTSTR)csLstExecTime);
-				result = false;
-			}
-		}
-	}
-	return result;
+	spRunConfig->ReadConfigValueInt("LastClearTime", "Video", nLastTaskTime);
+	return !IsTodayDone(nLastTaskTime);
 }
 
 int ResourceWatcherFSM::ProcessFileDelete(LPCTSTR lpszPath, int& nDelSucCnt, int& nDelFailedCnt)
@@ -1968,8 +1865,11 @@ int ResourceWatcherFSM::CalculateAllVideoSize(LPCTSTR lpszPath, unsigned long lo
 void ResourceWatcherFSM::SelfTest(EntityTestEnum eTestType, 
 	CSmartPointer<ITransactionContext> pTransactionContext)
 {
+	static uint32_t times = 0;
 	pTransactionContext->SendAnswer(Error_Succeed);
-	if(m_bVideoClearReady) {
+	times++;
+	if(m_bVideoClearReady && times > 60 * 2) { //2 hour per times
+		times = 0;
 		PostEventFIFO(new FSMEvent(USER_EVT_CLEAR_VIDEOFILE_ENHANCE));
 	}
 }
@@ -3572,12 +3472,11 @@ DWORD ResourceWatcherFSM::CalSpecifiedSecondsFrom1970(const WORD wDuration
 BOOL ResourceWatcherFSM::ClearAd0Folder()
 {
 	LOG_FUNCTION();
-	ErrorCodeEnum ec;
 	CSimpleStringA strAd0Path;
 	CSmartPointer<IConfigInfo> spConfigRun;
 	int nLastTaskTime(0);
 	CSimpleStringA ssFilePath(true);
-	ec = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
+	ErrorCodeEnum ec = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
 	spConfigRun->ReadConfigValueInt("LastClearTime", "Ad0Task", nLastTaskTime);
 	if(IsTodayDone(nLastTaskTime)) {
 		return TRUE;

+ 17 - 11
Module/mod_ResourceWatcher/ResourceWatcherFSM.h

@@ -230,7 +230,7 @@ private:
 	BOOL m_bGetStatusRotate;
 	
 	//Video Component
-	CSimpleStringA m_csUploadVideoPath;
+	CSimpleStringA m_uploadedVideoDirPath;
 	CSimpleStringA m_csDelFileSuffix;
 	int m_nDayOfBackward;
 	int m_failDelCnt;
@@ -281,11 +281,11 @@ public:
 	int GetCardSwiperStatus();
 	int m_cardswiperStatus;
 	//Start Video Component  [Josephus in 9:12:26 2016/4/14]
-	int ClearVideoFiles(int& newDeletedFilesNum, int initFlag = 1);
+	int CleanVideoFiles(int& newDeletedFilesNum, int initFlag = 1);
 
 #if defined(_MSC_VER)
 	void CalculateBackTime(PFILETIME ftResultTime, int days);
-	BOOL CalculateUploadFileSize(ULARGE_INTEGER& uiBytesCal);
+	BOOL CalculateWillUploadDirSize(ULARGE_INTEGER& uiBytesCal);
 	/*
 	*-1, First file time is earlier than second file time.
 	* 0, First file time is equal to second file time
@@ -363,7 +363,7 @@ public:
 		return 1;
     }
 	void CalculateBackTime(time_t* ftResultTime, int days);
-	BOOL CalculateUploadFileSize(unsigned long long& uiBytesCal);
+	BOOL CalculateWillUploadDirSize(unsigned long long& uiBytesCal);
 
 	void SyncUpdateVideoCreateDaily(const time_t* ft, int minusOrAdd)
 	{
@@ -374,7 +374,13 @@ public:
     void RecordVideoFileInfomation(LPCTSTR lpFilePath, struct stat* pWfdata);
 	int CalculateAllVideoSize(LPCTSTR lpszPath, unsigned long long* puliSpaceBytes);
 #endif //_MSC_VER
-	int DeleteBackwardVideoFile(LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt, const int nFlag);
+
+	void AppendVideoSizeTogether();
+	void CalculateFreeDiskNeeded();
+	void RecordFreeDiskNeededToRunCfg();
+	void GetFreeDiskNeededFromRunCfg();
+
+	int RemoveExpireVideoFileAndRecord(LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt, const int nFlag);
 	// End Video Component
 
 	ErrorCodeEnum GetCpuType(
@@ -384,15 +390,15 @@ public:
 	// Start CenterSetting Clear Job --Josephus at 15:57:58 20161210
 	BOOL RemoveDuplicateCenterSettingFiles();
 	int ClearSpecifieFile(DealFileType fileType, LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt);
-	int DoSomethingWith(DealFileType fileType, LPCTSTR szFilePath, LPCTSTR szFileName);
+	int RemoveSpecifiedFile(DealFileType fileType, LPCTSTR szFilePath, LPCTSTR szFileName);
 	// End CenterSetting clear Job
 
 	// Start Video Component2 --Josephus at 16:19:56 201755
 	void ClearVideoQueue();
 	// Has been purified --Josephus at 10:42:55 201759
-	void PrintResult();
+	void PrintVideEmurateResult();
 
-	void ClearMoreVideoFiles();
+	void CleanMoreVideoFiles();
 	bool IsNeedToFirstClear();
 	void SetSysValAndBroadcast(DWORD dwVal, LPCTSTR lpszMessage);
 	// End --Josephus at 16:20:02 201755
@@ -494,7 +500,7 @@ struct ClearVideoFilesTask : public ITaskSp
 	{
 		FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CLEAR_UPLOADEDVIDEOFILES_FINISHED);
 		int value(0);
-		fsmEvent->param2 = m_pFSM->ClearVideoFiles(value, m_nInitFlag);
+		fsmEvent->param2 = m_pFSM->CleanVideoFiles(value, m_nInitFlag);
 		fsmEvent->param1 = value;
 		m_pFSM->PostEventFIFO(fsmEvent);
 	}
@@ -508,7 +514,7 @@ struct ClearVideoFilesEnhanceTask : public ITaskSp
 	void Process()
 	{
 		FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED);
-		m_pFSM->ClearMoreVideoFiles();
+		m_pFSM->CleanMoreVideoFiles();
 		m_pFSM->PostEventFIFO(fsmEvent);
 	}
 };
@@ -559,7 +565,7 @@ struct RunTask : public ITaskSp
         m_pFSM->RemoveDuplicateCenterSettingFiles();
         FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CLEAR_UPLOADEDVIDEOFILES_FINISHED);
         int value(0);
-        fsmEvent->param2 = m_pFSM->ClearVideoFiles(value, m_nInitFlag);
+        fsmEvent->param2 = m_pFSM->CleanVideoFiles(value, m_nInitFlag);
         fsmEvent->param1 = value;
         m_pFSM->PostEventFIFO(fsmEvent);
     }