派生自 development/c++

xuxiuxi
2019-02-28 41a1e1ea6173eee746f3b393e164d4815dfc7fa7
QiaoJiaSystem/DataManagerServer/http_configserver.cpp
@@ -21,6 +21,13 @@
//#include "HcRecord.h"
#include <time.h>
#include <dirent.h>
#include "basic/pipe_element/ffmpeg/basic_struct_for_video_image.h"
#include "vss/controller/VssDevTblController.h"
#include "vss/controller/VssChannelTblController.h"
#include "vss/controller/VssDomainUnitTblController.h"
#include "vss/controller/VssLocalSettingTblController.h"
#include "vss/controller/VssUpperSvrTblController.h"
using namespace std;
@@ -65,10 +72,12 @@
void devHttpServer_c::init(void) {
    std::string strDevId = appConfig.getStringProperty("DEV_ID");
//    DSVAD010120181119
    m_batch = strDevId.substr(5, 2);
    m_SerialNumber = strDevId.substr(7, 2);
    DBG("DevID: " << strDevId << " Batch: " << m_batch << " SerNum: " << m_SerialNumber);
    fdfsClient.rwLock.wrlock();
    fdfsClient.fastFds = new FastFds("WebFDSClient.conf");
@@ -240,6 +249,14 @@
                                         std::placeholders::_3, std::placeholders::_4));
    BaseDao::initConnection();
    VssLocalSettingTblSqliteDao::instance()->setLDBTool(&db_c);
    VssDevTblController::instance()->registerHttpServices(_HttpSrvRetRecieve);
    VssChannelTblController::instance()->registerHttpServices(_HttpSrvRetRecieve);
    VssDomainUnitTblController::instance()->registerHttpServices(_HttpSrvRetRecieve);
    VssLocalSettingTblController::instance()->registerHttpServices(_HttpSrvRetRecieve);
    VssUpperSvrTblController::instance()->registerHttpServices(_HttpSrvRetRecieve);
    _HttpSrvRetRecieve.start();
    _HttpSrvRetRecieve.waitForShutDown();
}
@@ -395,6 +412,7 @@
    /*sdk login*/
    ulRet = IMOS_MW_Login(username, passwd, ip, 0, szUserID);
    if (ERR_COMMON_SUCCEED != ulRet) {
        (VOID) IMOS_MW_Cleanup();
        printf("Login error ulRet[%lu]", ulRet);
        return false;
    }
@@ -402,6 +420,8 @@
    pstBasicInfo = (IMOS_MW_BASIC_DEVICE_INFO_S *) malloc(sizeof(IMOS_MW_BASIC_DEVICE_INFO_S));
    ulRet = IMOS_MW_GetDeviceStatus(szUserID, 0, IMOS_MW_STATUS_BASIC_INFO, (void *) pstBasicInfo);
    if (ERR_COMMON_SUCCEED != ulRet) {
        (VOID) IMOS_MW_Logout(szUserID);
        (VOID) IMOS_MW_Cleanup();
        printf("GetDeviceStatus Error[%lu]\n", ulRet);
        return false;
    }
@@ -946,8 +966,10 @@
void devHttpServer_c::killVideoAnalysFromHCApp() const {
    string local_passwd = appConfig.getStringProperty("localPasswd");
    string cmd_kill = "echo \"" + local_passwd + "\" | sudo -S pkill -9 VideoAnalysFrom";
    system(cmd_kill.c_str());
    string cmd_kill_VideoAnalys = "echo \"" + local_passwd + "\" | sudo -S pkill -9 VideoAnalys";
    system(cmd_kill_VideoAnalys.c_str());
    string cmd_kill_VideoToIma = "echo \"" + local_passwd + "\" | sudo -S pkill -9 VideoToIma";
    system(cmd_kill_VideoToIma.c_str());
    DBG("system(\"sudo -S pkill -9 VideoAnalysFromHC\");");
}
@@ -997,8 +1019,10 @@
    std::string out = value.size() > 0 ? value.toStyledString() : "[]";
    return out;
}
#define ADD_CAMERA 0
#define EDIT_CAMERA 1
//编辑摄像机
std::string devHttpServer_c::cam_edit(std::string ip, unsigned int port, std::string content, PResponse &response) {
    DBG("ip:" << ip << "; port:" << port);
@@ -1010,7 +1034,7 @@
    Record_Cam_Dev rec;
    Record_Cam_Sdk rec_sdk_old;
    Record_Cam_Sdk rec_sdk;
    int type=-1;
    int type = -1;
    int dev_type = db_c.searchDevTypeFromConfigTable();
    if (DEV_STORAGE == dev_type) {
        return "{\"ret_status\": \"内容有误,请检查!\"}";
@@ -1036,45 +1060,34 @@
        rec.str_username = QString::fromStdString(value["str_username"].asString());
        rec.str_password = QString::fromStdString(value["str_password"].asString());
        rec.str_brand = QString::fromStdString(value["str_brand"].asString());
        type=value["n_type"].asInt();
        type = value["n_type"].asInt();
//        rec_sdk_old = db_c.searchCamSdkTableByCamId(rec.str_cam_dev_id);
//        rec_sdk.str_cam_dev_id = rec.str_cam_dev_id;
//        rec_sdk.str_sdks = QString::fromStdString(value["str_sdks"].asString());
//        rec_sdk.str_det_thr = QString::fromStdString(value["str_det_thr"].asString());
//        rec_sdk.str_cmp_thr = QString::fromStdString(value["str_cmp_thr"].asString());
        bool is_exist=db_c.searchCamDevByCamId(rec.str_cam_dev_id);
        if(ADD_CAMERA == type )
        {
           if(is_exist)
           {
               return "{\"ret_status\": \"内容有误,请检查!\"}";
           }
           else
           {
               ret =db_c.insertCamDevTable(rec);
               if (!ret) {
                   return "err_db_content";
               }
           }
        }
        else if(EDIT_CAMERA == type )
        {
            if(is_exist)
            {
                ret = db_c.updateCamDevTable(rec);
        bool is_exist = db_c.searchCamDevByCamId(rec.str_cam_dev_id);
        if (ADD_CAMERA == type) {
            if (is_exist) {
                return "{\"ret_status\": \"请勿重复添加!\"}";
            } else {
                ret = db_c.insertCamDevTable(rec);
                if (!ret) {
                    return "err_db_content";
                }
            }
            else
            {
                 return "{\"ret_status\": \"内容有误,请检查!\"}";
        } else if (EDIT_CAMERA == type) {
            if (is_exist) {
                ret = db_c.updateCamDevTable(rec);
                if (!ret) {
                    return "err_db_content";
                }
            } else {
                return "{\"ret_status\": \"内容有误,请检查!\"}";
            }
        }
        else
        {
             return "{\"ret_status\": \"内容有误,请检查!\"}";
        } else {
            return "{\"ret_status\": \"内容有误,请检查!\"}";
        }
@@ -1086,7 +1099,7 @@
        db_c.updateConfigTableByDevType(DEV_CAMERA);
        runAllApp();
    }
    //edit camera's sdks
        //edit camera's sdks
    else/* if ((rec_sdk_old.str_sdks != rec_sdk.str_sdks) ||
             (rec_sdk_old.str_det_thr != rec_sdk.str_det_thr) ||
             (rec_sdk_old.str_cmp_thr != rec_sdk.str_cmp_thr)) */
@@ -2073,6 +2086,12 @@
                    img_str.append(fdfsClient.fastFds->getIp() + "/").append(img_tmp);
                    img_url.swap(img_str);
                }
            } else {
                std::string img_str = "http://";
                if (fdfsClient.fastFds != nullptr) {
                    img_str.append(fdfsClient.fastFds->getIp() + "/").append(img_url);
                    img_url.swap(img_str);
                }
            }
            auto t_results = m_curlDownloadImg.download_jpeg(const_cast<char *>(img_url.c_str()));
@@ -2396,21 +2415,14 @@
    }
}
std::string devHttpServer_c::getAlarmImageFromVideoFile(std::string ip, unsigned int port, std::string content,
                                                        PResponse &response) {
    DBG("ip:" << ip << "; port:" << port);
    DBG("content: " << content);
    Json::Reader reader;
    Json::Value value;
    try {
        if (reader.parse(content, value)) {
            std::string videoPath;
            std::string devId = value["videoNum"].asString();
            std::string picDate = value["picDate"].asString();
            //std::string path_uuid = videoPath;//value["path_uuid"].asString();
std::string devHttpServer_c::getAlarmImageByPicDateAndDevId(const std::string &picDate, const std::string &devId,
                                                            PResponse &response) {
    try {
        if (!devId.empty() && !picDate.empty()) {
            std::string videoPath;
            qint64 sub;
            std::string path = getVideoPathByTime(picDate, devId, sub);
            std::string path = getVideoPathByPicDate(picDate, devId, sub);
            if (path.empty()) {
                ERR("{\"error\":\"not find path\"}");
@@ -2502,12 +2514,10 @@
            }
            fdfsClient.rwLock.unlock();
            std::string result("{\"img_url\":\"" + img_url + "\"}");
//        cout << result << endl;
            return result;
        } else {
            response->write(SimpleWeb::StatusCode::server_error_not_implemented, "{\"error\":\"传输错误,请检查!\"}");
            return "";
//        return "{\"error\":\"传输错误,请检查!\"}";
        }
    }
    catch (std::exception ex) {
@@ -2518,28 +2528,155 @@
    }
}
std::string devHttpServer_c::getAlarmImageFromVideoFile(std::string ip, unsigned int port, std::string content,
                                                        PResponse &response) {
    INFO("ip:" << ip << "; port:" << port << "content: " << content);
    Json::Reader reader;
    Json::Value value;
    try {
        if (reader.parse(content, value)) {
            std::string devId = value["videoNum"].asString();
            std::string picDate = value["picDate"].asString();
            std::string imgKey = value["imgKey"].asString();
            //兼容旧版本
            if (imgKey == "undefined" || imgKey.empty()) {
                DBG("getAlarmImageByPicDateAndDevId " << imgKey);
                return getAlarmImageByPicDateAndDevId(picDate, devId, response);
            } else {
                DBG("getAlarmImageByImageKeyAndDevId " << imgKey);
                return getAlarmImageByImageKeyAndDevId(imgKey, devId, response);
            }
        } else {
            response->write(SimpleWeb::StatusCode::server_error_not_implemented, "{\"error\":\"传输错误,请检查!\"}");
            ERR("ImageURL:传输错误,请检查");
            return "";
        }
    }
    catch (std::exception ex) {
        std::string message = "{\"error\":\"异常错误!";
        message.append(const_cast<char *>(ex.what())).append("\"}");
        response->write(SimpleWeb::StatusCode::server_error_not_implemented, message);
        ERR("ImageURL:异常错误   " << ex.what());
        return "";
    }
}
std::string devHttpServer_c::getAlarmImageByImageKeyAndDevId(const std::string &imgKey, const std::string &devId,
                                                             PResponse &response) {
    try {
        if (!devId.empty() && !imgKey.empty()) {
            std::string videoPath;
            std::string path = getVideoPathByImgKey(imgKey, devId);
            if (path.empty()) {
                ERR("Not Find Path: " << path);
                return "{\"error\":\"未查到视频路径\"}";
            }
            videoPath.clear();
            videoPath = path;
            VideoName_s_t videoSt = VideoName_s_t::fromString(path);
            ImageName_s_t imgSt = ImageName_s_t::fromString(imgKey);
            //#todo 按照时间命名
            std::string str_imgName(AppUtil::getTimeString() + ".jpg");// = "test.jpg";
            auto frameIdDiff = imgSt.m_frameId - videoSt.m_startFrameId;
            char selectExpBuff[32] = {0};
            std::string strSelectTemplate = R"#( -vf "select=eq(n\,%d)")#";
            sprintf(selectExpBuff, strSelectTemplate.c_str(), frameIdDiff - 1);
            if (videoSt.Valid() && imgSt.Valid()) {
                std::string cmd("ffmpeg -i '" + videoPath + "'" + std::string(selectExpBuff) + " -vframes 1" + " -y '" +
                                str_imgName + "'");
                INFO("Video To Image Cmd: " << cmd);
                system(cmd.c_str());
            } else {
                ERR("Parse Video and Image Failed Path: " << path << " ImageId: " << imgKey);
                return "{\"error\":\"未查到视频路径\"}";
            }
            cv::Mat img = cv::imread(str_imgName);
            if (img.empty()) {
                ERR("{\"error\":\"Video File error\"}");
                return "{\"error\":\"视频文件错误\"}";
            }
            std::vector<unsigned char> buffer;
            CvUtil::cvMat2Buffer(img, buffer);
            std::string img_url = "http://";
            fdfsClient.rwLock.rdlock();
            if (fdfsClient.fastFds != nullptr) {
                std::string t_strImg = "";
                if (!fdfsClient.fastFds->uploadFile(buffer, t_strImg, "jpg")) {
                    img_url = "upload image fail";
                    ERR("Upload Image Failed " << str_imgName);
                } else {
                    std::string str_tmp_cmd("rm -f '" + str_imgName + "'");
                    system(str_tmp_cmd.c_str());
                    img_url.append(t_strImg);
                    img_url.clear();
                    img_url = t_strImg;
                }
            }
            fdfsClient.rwLock.unlock();
            std::string result("{\"img_url\":\"" + img_url + "\"}");
            INFO("ImageURL:" << img_url);
            return result;
        } else {
            response->write(SimpleWeb::StatusCode::server_error_not_implemented, "{\"error\":\"传输错误,请检查!\"}");
            ERR("ImageURL:传输错误,请检查");
            return "";
        }
    }
    catch (std::exception ex) {
        std::string message = "{\"error\":\"异常错误!";
        message.append(const_cast<char *>(ex.what())).append("\"}");
        response->write(SimpleWeb::StatusCode::server_error_not_implemented, message);
        ERR("ImageURL:异常错误   " << ex.what());
        return "";
    }
}
std::string
devHttpServer_c::getRecordVideoPath(std::string ip, unsigned int port, std::string content, PResponse &response) {
    Json::Reader reader;
    Json::Value value;
    INFO("REQ From: " << ip << ":" << port << " Content:" << content);
    if (reader.parse(content, value)) {
        std::string devId = value["videoNum"].asString();
        std::string picDate = value["picDate"].asString();
        qint64 sub;
        std::string path = getVideoPathByTime(picDate, devId, sub);
        if (path.empty()) {
        std::string imgKey = value["imgKey"].asString();
        std::string path;
            return "{\"ret_status\":\"内容有误,请检查!\"}";
        //兼容旧版本
        if (imgKey == "undefined" || imgKey.empty()) {
            qint64 sub;
            path = getVideoPathByPicDate(picDate, devId, sub);
        } else {
            path = getVideoPathByImgKey(imgKey, devId);
        }
        //std::string path = getVideoPathByImgKey(imgKey, devId, sub);
        ERR("VideoNum: " << devId << "  PicDate: " << picDate << " imgKey: " << imgKey);
        if (path.empty()) {
            std::string strRsp = "{\"ret_status\":\"内容有误,请检查!\"}";
            ERR("RSP:" << strRsp);
            return strRsp;
        } else {
            std::string result = "{\"file_path\":\"" + path + "\"}";
            INFO("RSP:" << result);
            return result;
        }
    } else {
        return "{\"ret_status\":\"传输错误,请检查!\"}";
        std::string strRsp = "{\"ret_status\":\"传输错误,请检查!\"}";
        ERR("RSP:" << strRsp);
        return strRsp;
    }
}
std::string devHttpServer_c::findDevId(std::string ip, unsigned int port, std::string content, PResponse &response) {
@@ -2617,7 +2754,8 @@
    return true;
}
std::string devHttpServer_c::getVideoPathByTime(const std::string &time, const std::string &camId, qint64 &sub) {
std::string devHttpServer_c::getVideoPathByPicDate(const std::string &time, const std::string &camId, qint64 &sub) {
    std::string t_FilePath = appConfig.getStringProperty("cutPath");
    bool find = false;
@@ -2677,6 +2815,70 @@
}
std::string devHttpServer_c::GetVideoNameByImgKey(const std::string &imgKey, const std::string &strPath) {
    static std::mutex g_mutex;
    std::lock_guard<std::mutex> lock(g_mutex);
    std::vector<std::string> vec = forEachFileByImgKey(strPath);
    ImageName_s_t imgSt = ImageName_s_t::fromString(imgKey);
    if (!imgSt.Valid()) {
        ERR("ParseImageName Failed : " << imgKey);
        return "";
    }
    std::vector<VideoName_s_t> videoStVec;
    for (const auto &item : vec) {
        auto videoParseResult = VideoName_s_t::fromString(item);
        if (videoParseResult.Valid()) {
            if (videoParseResult.m_startFrameId <= imgSt.m_frameId &&
                imgSt.m_frameId <= videoParseResult.m_endFrameId) {
                auto imgTm = AppUtil::ParseFromHypenTimeStr(imgSt.m_timeStamp);
                auto videoTm = AppUtil::ParseFromHypenTimeStr(videoParseResult.m_timeStamp);
                if (AppUtil::IsRightAfterLeft(imgTm, videoTm)) {
                    videoStVec.emplace_back(videoParseResult);
                    INFO("Image " << imgKey << "   Video: " << item << " Match");
                } else {
                    ERR("Image " << imgKey << "   Video: " << item << " Not Match");
                }
            } else {
                ERR("ImageID: " << imgSt.m_frameId << " VideoRange: " << videoParseResult.m_startFrameId << " , "
                                << videoParseResult.m_endFrameId);
            }
        } else {
            ERR("VideoName : " << item << " Parse Failed");
        }
    }
    if (videoStVec.size() >= 1) {
        std::string strVideoName = strPath + videoStVec[0].ToVideoName();
        INFO("ImageName: " << imgKey << "  SingleMatchVideo: " << strVideoName);
        return strVideoName;
    } else {
        ERR("ImageName: " << imgKey << "  MatchVideoCount: " << videoStVec.size());
        for (auto &item:vec) {
            ERR("VideoName: " << item);
        }
        return "";
    }
}
//新的根据图片名称获取路径的方法
std::string devHttpServer_c::getVideoPathByImgKey(const std::string &imgKey, const std::string &camId) {
    INFO("GetVideoFor: " << imgKey << " CamID:" << camId);
    ImageName_s_t imgSt = ImageName_s_t::fromString(imgKey);
    struct tm imgTime = AppUtil::ParseFromHypenTimeStr(imgSt.m_timeStamp);
    char curFolder[128] = {0};
    // 201901/26/2019012614 ---- 201901/26/2019012615 {年月}/{日}/{年月日时}/
    sprintf(curFolder, "%04d%02d/%02d/%04d%02d%02d%02d/", imgTime.tm_year + 1900, imgTime.tm_mon + 1,
            imgTime.tm_mday,
            imgTime.tm_year + 1900, imgTime.tm_mon + 1, imgTime.tm_mday, imgTime.tm_hour);
    std::string t_FilePath = appConfig.getStringProperty("cutPath");
    std::string videoPath = t_FilePath + "/" + camId + "/" + std::string(curFolder);
    return GetVideoNameByImgKey(imgKey, videoPath);
}
qint64 devHttpServer_c::getVideoTime(/*const std::string &videoPath,*/std::string &str_tmpTime) {
//    std::string cmd_getVideoFileTime(
//        " ffmpeg -i '" + videoPath + "' 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");
@@ -2701,6 +2903,7 @@
    return len_ms;
}
//获取某个目录下的所有文件,不带扩展名
std::vector<std::string> devHttpServer_c::forEachFile(const std::string &dir_name) {
    std::vector<std::string> v;
    auto dir = opendir(dir_name.data());
@@ -2714,6 +2917,26 @@
                temp = filename.substr(0, filename.rfind('.'));
                v.push_back(temp);
            }
        }
        closedir(dir);
    }
    return v;
}
//获取某个目录下的所有文件,带扩展名
std::vector<std::string> devHttpServer_c::forEachFileByImgKey(const std::string &dir_name) {
    std::vector<std::string> v;
    auto dir = opendir(dir_name.data());
    struct dirent *ent;
    int len = 0;
    if (dir) {
        while ((ent = readdir(dir)) != NULL) {
            std::string filename = std::string(ent->d_name);
            std::string temp;
            if (filename != "." && filename != "..") {
                v.push_back(filename);
            }
        }
@@ -3046,13 +3269,29 @@
        if (rtsp_url.empty()) {
            return "{\"ret_status\":\"内容有误,请检查!\"}";
        }
//        unsigned char serialnumber[SERIALNO_LEN] = {0};
//        int ret = getDevSerialNumber(ip.c_str(), port,username.c_str(),pass.c_str(),brand.c_str(),serialnumber);
//        if ((!ret) || (serialnumber[0] == 0))
//        {
//            return "{\"ret_status\": \"内容有误,请检查!\"}";
//        }
//        std::string str_cam_dev_id = std::string((char *) serialnumber);//摄像机id cam_mac
        std::string str_imgName = appConfig.getStringProperty("cutPath");
        if (str_imgName.back() != '/') {
            str_imgName.push_back('/');
        }
        str_imgName += ip;
        str_imgName += "-";
        str_imgName += "snapshot.jpg";
        //admin:a1234567@192.168.1.201:554/h264/ch1/main/av_stream -r 1/25 -f image2 -s 1920*1080 /home/basic/work_src/a.jpg
        std::string cmd("ffmpeg -i " + rtsp_url + " -r 1/25  -f image2 -s 1920*1080 -y " + str_imgName);
        std::string cmd(
            "ffmpeg -i " + rtsp_url + " -vf select='eq(pict_type\\,I)',setpts='N/(25*TB)' -f image2 -s 1920*1080 -y " +
            str_imgName);
//        std::string cmd("ffmpeg -i " + rtsp_url + " -r 1/25  -f image2 -s 1920*1080 -y " + str_imgName);
        DBG(cmd);
        system(cmd.c_str());
@@ -3069,13 +3308,14 @@
            CvUtil::cvMat2Buffer(img, buffer);
            std::string strImgUrlTmp = "";
            fdfsClient.fastFds->uploadFile(buffer, strImgUrlTmp, "jpg");
            strImgUrl.append(fdfsClient.fastFds->getIp() + "/" + strImgUrlTmp);
            //  strImgUrl.append(fdfsClient.fastFds->getIp() + "/" + strImgUrlTmp);
            strImgUrl.clear();
            strImgUrl = strImgUrlTmp;
        }
        fdfsClient.rwLock.unlock();
        Json::Value result;
        result["imgUrl"] = strImgUrl;
        db_c.updateCamDevSnapshot(QString::fromStdString(ip), QString::fromStdString(strImgUrl));
        return result.toStyledString();