hunting/middleware/StorageManager/src/StorageBase.cpp
2024-06-27 11:35:37 +08:00

111 lines
3.1 KiB
C++

/*
* Copyright (c) 2023 Fancy Code.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "StorageBase.h"
#include "ILog.h"
#include "IStorageManager.h"
#include <cctype>
#include <chrono>
#include <cstring>
#include <ctime>
#include <errno.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sys/stat.h>
bool StorageBase::CheckDirectory(const char *filepath)
{
LogInfo("CheckDirectory:%s\n", filepath);
char *path = nullptr;
char *sep = nullptr;
struct stat st = {0};
path = strdup(filepath);
if (!path) {
LogError("strdup\n");
return false;
}
for (sep = strchr(path, '/'); sep != NULL; sep = strchr(sep + 1, '/')) {
*sep = '\0';
if (strlen(path) == 0) {
*sep = '/';
continue;
}
if (stat(path, &st) == -1) {
if (errno == ENOENT) {
// LogInfo("mkdir:%s\n", path);
if (mkdir(path, 0755) == -1) {
LogError("mkdir path failed:%s\n", path);
free(path);
return false;
}
}
else {
LogError("stat\n");
free(path);
return false;
}
}
*sep = '/';
}
// TODO: check if files exist finally here.
free(path);
return true;
}
const char *StorageBase::PrintStringStorageEvent(const StorageEvent &event)
{
switch (event) {
case StorageEvent::SD_CARD_INSERT: {
return "SD_CARD_INSERT";
}
case StorageEvent::SD_CARD_REMOVE: {
return "SD_CARD_REMOVE";
}
case StorageEvent::SD_ABNORMAL: {
return "SD_ABNORMAL";
}
case StorageEvent::EMMC_NORMAL: {
return "EMMC_NORMAL";
}
case StorageEvent::END: {
return "END";
}
default: {
return "UNDEFINE";
}
}
}
std::string StorageBase::CreateFilesSavingPath(void)
{
auto now = std::chrono::system_clock::now();
time_t t_now = std::chrono::system_clock::to_time_t(now);
struct tm tm_now = *std::localtime(&t_now);
int year = tm_now.tm_year + 1900;
int month = tm_now.tm_mon + 1;
int day = tm_now.tm_mday;
std::ostringstream pathStream;
pathStream << SD_CARD_MOUNT_PATH << "/DCIM/" << std::setw(4) << std::setfill('0') << year << "/" << std::setw(2)
<< std::setfill('0') << month << "/" << std::setw(2) << std::setfill('0') << day << "/";
CheckDirectory((pathStream.str() + "anyfile").c_str());
return pathStream.str();
}