Commit e0b055a2611d05b5da630fdc044f8d704c6b1a49

Authored by Zou XiKun
1 parent a49f4fe7

路数授权

src/left_over/MSRegionSurveilanceCpu.cpp
1 1 #include "MSRegionSurveilanceCpu.h"
2   -#include "head.h"
3 2 #include <opencv2/opencv.hpp>
4 3 #include <opencv2/opencv.hpp>
5 4 #include <opencv2/core/core.hpp>
... ...
src/left_over/MSRegionSurveilanceCpu.h
... ... @@ -2,7 +2,6 @@
2 2 #include "MSRegionSurveilance.h"
3 3 #include "left_over_det.h"
4 4 #include "RegionSurveillanceProcess.h"
5   -#include "head.h"
6 5 class IRegionSurveillanceCpu: public RegionSurveillanceProcess {
7 6 public:
8 7 IRegionSurveillanceCpu()
... ...
src/left_over/RegionSurveillanceProcess.h
1 1 #pragma once
2   -//#include "MSRegionSurveilance.h"
3 2 #include "left_over_det.h"
4   -//#include <boost/thread.hpp>
5   -#include "head.h"
6 3 #include <atomic>
7   -//#include "MSRegionSurveilanceVpt.h"
  4 +#include "header.h"
  5 +#include "checkAuthor.h"
  6 +#define DEVICE_GPU 10
  7 +typedef struct rs_params
  8 +{
  9 + int mode; //运行模式(DEVICE_GPU / DEVICE_CPU)
  10 + int gpuid; //指定显卡id
  11 + //其余算法参数 如长短边等
  12 +
  13 + sy_img image;
  14 + int channel_deal;
  15 + bool filt_flag;
  16 + int min_area;
  17 + int max_area;
  18 +
  19 + rs_params() :mode(DEVICE_GPU), gpuid(0), min_area(0), max_area(1000000) {};
  20 +}rs_params;
  21 +
8 22 class RegionSurveillanceProcess
9 23 {
10 24 public:
... ... @@ -37,8 +51,6 @@ public:
37 51 virtual int rs_detect(const sy_img &img_data, region_info* region_infos, rs_result *result) = 0;
38 52 //virtual int rs_get_arrowdir(const sy_point &p_roi0, const sy_point &p_roi1, const sy_point &dir) = 0;
39 53 //void* handle;
40   - int licence_status = -1;
41   - int thrd_status = -1;
42 54 double scale;
43 55 //int long_side;
44 56 //int short_side;
... ... @@ -48,6 +60,7 @@ public:
48 60 bool init_flag = false;
49 61 sy_rect rect[MAXVERTEXNUM]; //有效区域
50 62 unsigned char rect_num; //有效区域数量
  63 + CheckAuthor * auth = nullptr;
51 64 private:
52 65 //int mode; //运行模式0 cpu
53 66 //MS_RegionSurveillance MS1;
... ...
src/left_over/auth/authorLog.h 0 → 100644
  1 +#pragma once
  2 +#include <string>
  3 +
  4 +class AuthorLog
  5 +{
  6 +public:
  7 +
  8 + static int FileSize(const char* fname)
  9 + {
  10 + struct stat statbuf;
  11 + if (stat(fname, &statbuf) == 0)
  12 + return statbuf.st_size;
  13 + return -1;
  14 + }
  15 +
  16 + static void Write(std::string log) {
  17 + try
  18 + {
  19 + std::string strfile = "./author.log";
  20 + int ss = FileSize(strfile.c_str());
  21 + if (ss > 1024 * 1024 * 10)
  22 + {
  23 + FILE* pf = fopen(strfile.c_str(), "wb");
  24 + if (pf)
  25 + {
  26 + fclose(pf);
  27 + pf = nullptr;
  28 + }
  29 + }
  30 + std::ofstream ofs;
  31 + time_t t = time(0);
  32 + char tmp[64];
  33 + strftime(tmp, sizeof(tmp), "[%Y-%m-%d %X]", localtime(&t));
  34 + ofs.open(strfile.c_str(), std::ofstream::app);
  35 +
  36 + ofs << tmp << " - ";
  37 + ofs.write(log.c_str(), log.size());
  38 + ofs << std::endl;
  39 + ofs.close();
  40 + }
  41 + catch (...)
  42 + {
  43 + }
  44 + }
  45 +};
  46 +
  47 +
... ...
src/left_over/auth/checkAuthor.cpp 0 → 100644
  1 +#include "checkAuthor.h"
  2 +
  3 +#include "httpSend.h"
  4 +#include "authorLog.h"
  5 +
  6 +CheckAuthor::CheckAuthor()
  7 +{
  8 + m_nLog = 0;
  9 + m_nChannel = 0; //授权通道
  10 + m_strCode=""; //授权码
  11 + m_strId=""; //产品序列号
  12 +
  13 + m_nPort = 0;
  14 + m_strIp = "";
  15 +
  16 + m_strHttpUrl = "";
  17 +
  18 + m_lLastTime = 0;
  19 + m_lCheakTime = 1; //多少秒检测一次
  20 +
  21 + m_bFirst = true;
  22 + m_nStatus = 0;
  23 + m_lFailureTime = 0;
  24 +
  25 + //秒
  26 + m_lFailureTotal = 1800;
  27 +
  28 + signal(SIGPIPE, SIG_IGN);
  29 +}
  30 +
  31 +
  32 +CheckAuthor::~CheckAuthor()
  33 +{
  34 +}
  35 +
  36 +int CheckAuthor::Init(std::string strip, int port,
  37 + std::string code, std::string id,
  38 + int channel, int log)
  39 +{
  40 + m_nLog = log;
  41 + m_strId = id;
  42 + m_strCode = code;
  43 + m_nChannel = channel;
  44 +
  45 + m_nPort = port;
  46 + m_strIp = strip;
  47 +
  48 + //http://192.168.10.4:8888/action/auth?authcode=f437a4fdc0674cc98356ccbf8d33db77&productid=2514B7CB4DDE47CCB592E573304C6B92&authchannel=1
  49 + m_strHttpUrl = "http://" + m_strIp + ":" + std::to_string(m_nPort) + "/action/auth?authcode=" + m_strCode + "&productid=" + m_strId + "&authchannel=" + std::to_string(m_nChannel);
  50 +
  51 + start();
  52 +
  53 + return 0;
  54 +}
  55 +int CheckAuthor::Uninit()
  56 +{
  57 + stop();
  58 + return 0;
  59 +}
  60 +
  61 +int CheckAuthor::run()
  62 +{
  63 + while (!m_canExit)
  64 + {
  65 + long dtime = GetTickCount() / 1000;
  66 +
  67 +
  68 + int ntm = dtime - m_lLastTime;
  69 + if (ntm > m_lCheakTime)
  70 + {
  71 + if (m_lCheakTime < 20)
  72 + m_lCheakTime++;
  73 +
  74 + CHttpSend http;
  75 + int ret = http.Init(m_strHttpUrl, 1);
  76 + if (ret < 0) //连接服务失败
  77 + {
  78 + http.Uninit();
  79 +
  80 + if (m_bFirst)
  81 + {
  82 + m_mtxStatus.lock();
  83 + m_nStatus = 0;
  84 + m_mtxStatus.unlock();
  85 + }
  86 + else
  87 + {
  88 + //
  89 + if (m_lFailureTime <= 0)
  90 + m_lFailureTime = dtime;
  91 +
  92 + if (dtime - m_lFailureTime > m_lFailureTotal)
  93 + {
  94 + m_mtxStatus.lock();
  95 + m_nStatus = 0;
  96 + m_mtxStatus.unlock();
  97 + }
  98 + }
  99 + if (m_bFirst)
  100 + m_bFirst = false;
  101 + continue;
  102 + }
  103 +
  104 +
  105 + std::string strJson = "";
  106 + ret = http.SendHttpPost(strJson);
  107 +
  108 + if (m_bFirst && ret < 0)
  109 + {
  110 + m_mtxStatus.lock();
  111 + m_nStatus = 0;
  112 + m_mtxStatus.unlock();
  113 + }
  114 +
  115 + std::string strRes = "";
  116 + if (ret >= 0) //请到应答包
  117 + {
  118 + strRes = http.GetJson();
  119 +
  120 + _check_result_ sResult;
  121 + memset(&sResult, 0, sizeof(_check_result_));
  122 + sprintf(sResult.sucess, "%s", "-1");
  123 +
  124 + if(strRes.size() > 0)
  125 + ProJson(strRes, sResult);
  126 +
  127 + if (atoi(sResult.sucess) == 0)
  128 + {
  129 + m_mtxStatus.lock();
  130 + m_nStatus = 1;
  131 + m_mtxStatus.unlock();
  132 +
  133 + m_lFailureTime = 0;
  134 + }
  135 + else
  136 + {
  137 + if (m_bFirst)
  138 + {
  139 + m_mtxStatus.lock();
  140 + m_nStatus = 0;
  141 + m_mtxStatus.unlock();
  142 + }
  143 + else
  144 + {
  145 + if (m_lFailureTime <= 0)
  146 + m_lFailureTime = dtime;
  147 +
  148 + if (dtime - m_lFailureTime > m_lFailureTotal)
  149 + {
  150 + m_mtxStatus.lock();
  151 + m_nStatus = 0;
  152 + m_mtxStatus.unlock();
  153 + }
  154 + }
  155 + }
  156 + }
  157 + else
  158 + {
  159 + if (m_lFailureTime <= 0)
  160 + m_lFailureTime = dtime;
  161 +
  162 + if (dtime - m_lFailureTime > m_lFailureTotal)
  163 + {
  164 + m_mtxStatus.lock();
  165 + m_nStatus = 0;
  166 + m_mtxStatus.unlock();
  167 + }
  168 + }
  169 +
  170 + http.Uninit();
  171 + m_lLastTime = dtime;
  172 +
  173 + if(m_bFirst)
  174 + m_bFirst = false;
  175 + }
  176 +
  177 + sleep(1);
  178 +
  179 + }
  180 + return 0;
  181 +}
  182 +
  183 +// 0-不可用 1-可用
  184 +int CheckAuthor::GetAuthorStatus()
  185 +{
  186 + if (m_bFirst)
  187 + {
  188 + while (m_bFirst)
  189 + {
  190 + //内部还没有准备好
  191 + sleep(1);
  192 + }
  193 + }
  194 +
  195 + int status = 0;
  196 + m_mtxStatus.lock();
  197 + status = m_nStatus;
  198 + m_mtxStatus.unlock();
  199 +
  200 + return status;
  201 +}
  202 +
  203 +
  204 +long CheckAuthor::GetTickCount()
  205 +{
  206 + struct timeval tv;
  207 + gettimeofday(&tv, NULL);
  208 + return tv.tv_sec * 1000 + tv.tv_usec / 1000; //毫秒
  209 +}
  210 +
  211 +int CheckAuthor::ProJson(std::string strJson, _check_result_& result)
  212 +{
  213 + cJSON *pJsonRoot = cJSON_Parse(strJson.c_str());
  214 + if (!pJsonRoot)
  215 + {
  216 + if (m_nLog == 1)AuthorLog::Write("json is error.");
  217 +
  218 + cJSON_Delete(pJsonRoot);
  219 + return 0;
  220 + }
  221 +
  222 + std::string strResult = "";
  223 + std::string strSucess = "";
  224 + std::string strAuthcount = "";
  225 +
  226 + cJSON* pNode = cJSON_GetObjectItem(pJsonRoot, "result");
  227 + if (pNode)
  228 + {
  229 + strResult = pNode->valuestring;
  230 + sprintf(result.result, "%s", strResult.c_str());
  231 + std::string strInfo = "result: " + strResult;
  232 + if (m_nLog == 1)AuthorLog::Write(strInfo);
  233 + }
  234 +
  235 + pNode = cJSON_GetObjectItem(pJsonRoot, "sucess");
  236 + if (pNode)
  237 + {
  238 + strSucess = pNode->valuestring;
  239 + sprintf(result.sucess, "%s", strSucess.c_str());
  240 +
  241 + std::string strInfo = "sucess: " + strSucess;
  242 + if (m_nLog == 1)AuthorLog::Write(strInfo);
  243 + }
  244 +
  245 + pNode = cJSON_GetObjectItem(pJsonRoot, "authcount");
  246 + if (pNode)
  247 + {
  248 + strAuthcount = pNode->valuestring;
  249 + sprintf(result.authcount, "%s", strAuthcount.c_str());
  250 +
  251 + std::string strInfo = "authcount: " + strAuthcount;
  252 +
  253 + if (m_nLog == 1)AuthorLog::Write(strInfo);
  254 + }
  255 + cJSON_Delete(pJsonRoot);
  256 +
  257 + return 0;
  258 +}
0 259 \ No newline at end of file
... ...
src/left_over/auth/checkAuthor.h 0 → 100644
  1 +#pragma once
  2 +
  3 +#include <mutex>
  4 +#include "syInclude.h"
  5 +
  6 +struct _check_result_
  7 +{
  8 + char result[64];
  9 + char authcount[64];
  10 + char sucess[64];
  11 +};
  12 +
  13 +
  14 +class CheckAuthor : public comn::Thread
  15 +{
  16 +public:
  17 + CheckAuthor();
  18 + ~CheckAuthor();
  19 +
  20 + int Init(std::string strip, int port,
  21 + std::string code, std::string id,
  22 + int channel, int log=0);
  23 +
  24 + int Uninit();
  25 +
  26 + //0-不可用 1-可用
  27 + int GetAuthorStatus();
  28 +
  29 +private:
  30 + virtual int run();
  31 + long GetTickCount();
  32 +
  33 + int ProJson(std::string strJson, _check_result_& result);
  34 +private:
  35 + int m_nLog;
  36 + int m_nPort;
  37 + std::string m_strIp;
  38 +
  39 + int m_nChannel; //授权通道
  40 + std::string m_strCode; //授权码
  41 + std::string m_strId; //产品序列号
  42 +
  43 + std::string m_strHttpUrl;
  44 +
  45 + //-1: 内部还没有准备好,等会重新获取 0-不可用 1-可用
  46 + int m_nStatus;
  47 + std::mutex m_mtxStatus;
  48 +
  49 + long m_lLastTime; //上次检测的时间 (秒)
  50 + long m_lCheakTime;//多长时间检测一次(秒)
  51 +
  52 + long m_lFailureTime; //检测失败的时间
  53 + long m_lFailureTotal;//失败超时时间
  54 +
  55 + bool m_bFirst;
  56 +
  57 +
  58 +};
  59 +
... ...
src/left_over/auth/httpSend.cpp 0 → 100644
  1 +#include "httpSend.h"
  2 +#include "syInclude.h"
  3 +#include "authorLog.h"
  4 +
  5 +CHttpSend::CHttpSend()
  6 +{
  7 + m_nLog = 0;
  8 + m_sockfd = -1;
  9 + m_nThrdStart = 0;
  10 + m_nResStatus = 0;
  11 + pthread_mutex_init(&m_mutex, NULL);
  12 +
  13 + memset(m_buf, 0, sizeof(m_buf));
  14 +}
  15 +
  16 +CHttpSend::~CHttpSend()
  17 +{
  18 + pthread_mutex_destroy(&m_mutex);
  19 +}
  20 +
  21 +
  22 +int CHttpSend::Init(std::string& strUrl, int log)
  23 +{
  24 + m_nLog = log;
  25 + if (AnalysisUrl(strUrl) < 0)
  26 + return -1;
  27 +
  28 + struct sockaddr_in address;
  29 + m_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  30 + address.sin_family = AF_INET;
  31 + address.sin_port = htons(m_nPort); //设置远程计算机的端口号
  32 + address.sin_addr.s_addr = inet_addr(m_strIp.c_str());
  33 +
  34 + if (-1 == connect(m_sockfd, (struct sockaddr *)&address, sizeof(address)))
  35 + {
  36 + if(m_nLog==1)AuthorLog::Write("connection error!");
  37 + return -2;
  38 + }
  39 +
  40 + start();
  41 + m_nThrdStart = 1;
  42 +
  43 + return 0;
  44 +}
  45 +
  46 +int CHttpSend::Uninit()
  47 +{
  48 + if (m_sockfd != -1)
  49 + {
  50 + close(m_sockfd);
  51 + m_sockfd = -1;
  52 + }
  53 +
  54 + if (m_nThrdStart == 1)
  55 + {
  56 + stop();
  57 + }
  58 +
  59 + return 0;
  60 +}
  61 +
  62 +
  63 +int CHttpSend::SendHttpPost( std::string& strJson)
  64 +{
  65 + int s1 = strJson.size();
  66 + int s2 = strJson.length();
  67 +
  68 + //POST请求方式
  69 + std::stringstream stream;
  70 + stream << "POST " << m_strTitle;
  71 + stream << " HTTP/1.0\r\n";
  72 + stream << "Host: " << m_strIp << "\r\n";
  73 + stream << "User-Agent: bj objecteye\r\n";
  74 + stream << "Content-Type:application/json\r\n";
  75 + stream << "Content-Length:" << strJson.length() << "\r\n";
  76 + stream << "Connection:close\r\n\r\n";
  77 + stream << strJson.c_str();
  78 +
  79 + std::string strData = stream.str();
  80 +
  81 + SetStatus(0);
  82 + int ret = SendData((char*)strData.c_str(), strData.length());
  83 + if (ret < 0)
  84 + return -1;
  85 +
  86 + int rr = -1;
  87 +
  88 + int num = 0;
  89 + while (true)
  90 + {
  91 + if (num >= 4)
  92 + break;
  93 +
  94 + int ret = GetStatus();
  95 + if (ret == 1)
  96 + {
  97 + rr = 0;
  98 + break;
  99 + }
  100 + num++;
  101 + sleep(1);
  102 + }
  103 +
  104 + if (num >= 4)
  105 + {
  106 + //接收应答超时
  107 + if (m_nLog == 1)AuthorLog::Write("http: recv response timout.");
  108 + return -2;
  109 + }
  110 +
  111 + if (m_nLog == 1)
  112 + {
  113 + AuthorLog::Write("====== http: recv response ============");
  114 + AuthorLog::Write(m_buf);
  115 + AuthorLog::Write("=======================================");
  116 + }
  117 + return rr;
  118 +}
  119 +
  120 +
  121 +int CHttpSend::run()
  122 +{
  123 + while (!m_canExit)
  124 + {
  125 + int offset = 0;
  126 + int rc;
  127 +
  128 + rc = read(m_sockfd, m_buf + offset, 1024);
  129 + if (rc < 0)
  130 + break;
  131 + else if (rc == 0)
  132 + {
  133 + continue;
  134 + }
  135 +
  136 + offset += rc;
  137 + m_buf[offset] = 0;
  138 +
  139 + SetStatus(1);
  140 + break;
  141 + }
  142 +
  143 + return 0;
  144 +}
  145 +
  146 +std::string CHttpSend::GetResponse()
  147 +{
  148 + return std::string(m_buf);
  149 +}
  150 +
  151 +std::string CHttpSend::GetJson()
  152 +{
  153 + std::string strRes = GetResponse();
  154 +
  155 + char* pTemp = m_buf;
  156 + char* p = strstr(pTemp, "\r\n\r\n");
  157 + if (p && strlen(p) > 4)
  158 + {
  159 + p += 4;
  160 + return std::string(p);
  161 + }
  162 + return"";
  163 +}
  164 +
  165 +
  166 +int CHttpSend::AnalysisUrl(std::string& strUrl)
  167 +{
  168 + m_strUrl = strUrl;
  169 +
  170 + std::string strTemp = strUrl;
  171 +
  172 + int pos = strTemp.find("http://");
  173 + if (pos < 0)
  174 + return -1;
  175 +
  176 + strTemp = strTemp.substr(pos + strlen("http://"));
  177 +
  178 + pos = strTemp.find("/");
  179 + if (pos < 0)
  180 + return -2;
  181 +
  182 + std::string strIpInfo = strTemp.substr(0, pos);
  183 + m_strTitle = strTemp.substr(pos);
  184 +
  185 + pos = strIpInfo.find(":");
  186 + if (pos < 0)
  187 + {
  188 + m_nPort = 80;
  189 + m_strIp = strIpInfo;
  190 + }
  191 + else
  192 + {
  193 + m_strIp = strIpInfo.substr(0, pos);
  194 + strIpInfo = strIpInfo.substr(pos + 1);
  195 +
  196 + m_nPort = atoi(strIpInfo.c_str());
  197 +
  198 + }
  199 + return 0;
  200 +}
  201 +
  202 +int CHttpSend::SendData(char* pbuf, int size)
  203 +{
  204 + char* pTempBuf = pbuf;
  205 + int nTempSize = size;
  206 +
  207 + while (nTempSize > 0)
  208 + {
  209 + int ss = write(m_sockfd, pTempBuf, nTempSize);
  210 + if (ss < 0)
  211 + {
  212 + return -1;
  213 + }
  214 + else if (ss == 0)
  215 + {
  216 + usleep(1000);
  217 + continue;
  218 + }
  219 + nTempSize -= ss;
  220 + }
  221 +
  222 + return 0;
  223 +}
  224 +
  225 +int CHttpSend::SetStatus(int status)
  226 +{
  227 + pthread_mutex_lock(&m_mutex);
  228 + m_nResStatus = status;
  229 + pthread_mutex_unlock(&m_mutex);
  230 +
  231 + return 0;
  232 +}
  233 +
  234 +int CHttpSend::GetStatus()
  235 +{
  236 + int status = 0;
  237 +
  238 + pthread_mutex_lock(&m_mutex);
  239 + status = m_nResStatus;
  240 + pthread_mutex_unlock(&m_mutex);
  241 +
  242 + return status;
  243 +}
0 244 \ No newline at end of file
... ...
src/left_over/auth/httpSend.h 0 → 100644
  1 +#pragma once
  2 +#include <string>
  3 +#include "syThread.h"
  4 +
  5 +class CHttpSend : public comn::Thread
  6 +{
  7 +public:
  8 + CHttpSend();
  9 + ~CHttpSend();
  10 +
  11 + int Init(std::string& strUrl, int log=0);
  12 + int Uninit();
  13 +
  14 + int SendHttpPost(std::string& strJson);
  15 + std::string GetResponse();
  16 + std::string GetJson();
  17 +
  18 +private:
  19 + virtual int run();
  20 + int AnalysisUrl(std::string& strUrl);
  21 +
  22 + int SendData(char* pbuf, int size);
  23 + int SetStatus(int status);
  24 + int GetStatus();
  25 +
  26 + long GetTickCount();
  27 +private:
  28 + int m_nPort;
  29 + std::string m_strUrl;
  30 + std::string m_strIp;
  31 + std::string m_strTitle;
  32 +
  33 + char m_buf[1024*2];
  34 +
  35 + int m_sockfd;
  36 +
  37 + int m_nThrdStart;
  38 +
  39 + pthread_mutex_t m_mutex;
  40 + int m_nResStatus;
  41 +
  42 + int m_nLog;
  43 +
  44 + long m_lLastTime; //上次检测的时间(秒)
  45 + int m_lCheckTime; //多长时间检测一次(秒)
  46 +
  47 +};
  48 +
... ...
src/left_over/auth/syInclude.h 0 → 100644
  1 +#pragma once
  2 +
  3 +/*
  4 +sudo apt-get install libsqlite3-dev
  5 +sudo apt-get install libcurl4-openssl-dev
  6 +
  7 +*/
  8 +
  9 +//////////////////////////////////////////////////////////////////////////
  10 +#include <stdio.h>
  11 +#include <sys/socket.h>
  12 +#include <sys/types.h>
  13 +#include <sys/time.h>
  14 +#include <sys/stat.h>
  15 +#include <sys/sendfile.h>
  16 +#include <sys/wait.h>
  17 +
  18 +#include <netinet/in.h>
  19 +#include <arpa/inet.h>
  20 +#include <unistd.h>
  21 +#include <errno.h>
  22 +#include <string.h>
  23 +#include <stdlib.h>
  24 +
  25 +#include <vector>
  26 +#include <deque>
  27 +#include <iconv.h>
  28 +#include <algorithm>
  29 +#include <fcntl.h>
  30 +
  31 +#include <iostream>
  32 +#include <fstream>
  33 +#include <sstream>
  34 +#include <cstring>
  35 +#include <time.h>
  36 +#include <vector>
  37 +#include <deque>
  38 +#include <map>
  39 +
  40 +
  41 +//////////////////////////////////////////////////////////////////////////
  42 +#include "syThread.h"
  43 +#include "sycJson.h"
  44 +
... ...
src/left_over/auth/syThread.h 0 → 100644
  1 +/*
  2 + * TThread.h
  3 + *
  4 + * Created on: 2010-4-21
  5 + * Author:
  6 + */
  7 +
  8 +#ifndef TTHREAD_H_
  9 +#define TTHREAD_H_
  10 +
  11 +#ifdef WIN32
  12 +#include <windows.h>
  13 +#include <process.h>
  14 +#else //
  15 +#include <stdio.h>
  16 +#include <sched.h>
  17 +#include <pthread.h>
  18 +#include <signal.h>
  19 +#include <time.h>
  20 +#include <sys/time.h>
  21 +#include <errno.h>
  22 +#include <sys/syscall.h>
  23 +#include <unistd.h>
  24 +#endif //WIN32
  25 +#include <assert.h>
  26 +////////////////////////////////////////////////////////////////////////////
  27 +
  28 +namespace comn
  29 +{
  30 +
  31 +#ifdef WIN32
  32 +
  33 +class Thread
  34 +{
  35 +public:
  36 + typedef HANDLE ThreadHandle;
  37 + typedef unsigned int ThreadID;
  38 +
  39 + Thread()
  40 + :m_stackSize(0),m_threadID(0),m_handle(0),m_canExit(false)
  41 + {
  42 + }
  43 +
  44 + explicit Thread(unsigned int stack_size)
  45 + :m_stackSize(stack_size),m_threadID(0),m_handle(0),m_canExit(false)
  46 + {
  47 + }
  48 +
  49 + virtual ~Thread()
  50 + {
  51 + assert(isRunning() == false);
  52 + }
  53 +
  54 + bool start()
  55 + {
  56 + m_canExit = false;
  57 + return createThread();
  58 + }
  59 +
  60 + void stop()
  61 + {
  62 + tryStop();
  63 + join(-1);
  64 + }
  65 +
  66 + void tryStop()
  67 + {
  68 + InterlockedExchange((LPLONG)&m_canExit, true);
  69 + doStop();
  70 + }
  71 +
  72 + bool join(int millisecond = -1)
  73 + {
  74 + bool ok = true;
  75 + if (m_handle != 0)
  76 + {
  77 + DWORD dwMilliseconds = (millisecond >= 0) ? millisecond : INFINITE;
  78 + DWORD res = ::WaitForSingleObject(m_handle, dwMilliseconds);
  79 + ok = (WAIT_OBJECT_0 == res);
  80 + }
  81 + return ok;
  82 + }
  83 +
  84 +
  85 + ThreadHandle getHandle() const
  86 + {
  87 + return m_handle;
  88 + }
  89 +
  90 + ThreadID getThreadID() const
  91 + {
  92 + return m_threadID;
  93 + }
  94 +
  95 + bool isRunning() const
  96 + {
  97 + return (m_handle != 0);
  98 + }
  99 +
  100 + void setStackSize(unsigned int stack_size)
  101 + {
  102 + m_stackSize = stack_size;
  103 + }
  104 +
  105 +protected:
  106 + virtual int run() =0;
  107 + virtual bool startup() { return true; }
  108 + virtual void cleanup() {}
  109 + virtual void doStop() {}
  110 +
  111 +
  112 + unsigned int m_stackSize;
  113 + ThreadID m_threadID;
  114 + ThreadHandle m_handle;
  115 + bool m_canExit;
  116 +
  117 +
  118 +
  119 +private:
  120 + static unsigned __stdcall ThreadFunction(void* param)
  121 + {
  122 + int code = 0;
  123 + Thread* pThread = (Thread*)param;
  124 + if ( !pThread->m_canExit )
  125 + {
  126 + if (pThread->startup())
  127 + {
  128 + code = pThread->run();
  129 + }
  130 + else
  131 + {
  132 + code = 1;
  133 + }
  134 + pThread->cleanup();
  135 + }
  136 + ::CloseHandle(pThread->m_handle);
  137 + pThread->m_handle = 0;
  138 + pThread->m_threadID = 0;
  139 + _endthreadex(code);
  140 + return code;
  141 + }
  142 +
  143 + bool createThread()
  144 + {
  145 + unsigned int flag = 0;
  146 + void* param = (void*)this;
  147 + m_handle = (HANDLE)_beginthreadex(NULL, m_stackSize, ThreadFunction,
  148 + param, flag, &m_threadID);
  149 + return (m_handle != 0);
  150 + }
  151 +
  152 +};
  153 +
  154 +#else //WIN32
  155 +
  156 +class Thread
  157 +{
  158 +public:
  159 + typedef pthread_t ThreadHandle;
  160 + typedef pthread_t ThreadID;
  161 +
  162 + Thread()
  163 + :m_stackSize(0),m_threadID(0),m_handle(-1),m_canExit(false)
  164 + {
  165 + }
  166 +
  167 + explicit Thread(unsigned int stack_size)
  168 + :m_stackSize(stack_size),m_threadID(0),m_handle(-1),m_canExit(false)
  169 + {
  170 + }
  171 +
  172 + virtual ~Thread()
  173 + {
  174 + assert(isRunning() == false);
  175 + }
  176 +
  177 + bool start()
  178 + {
  179 + m_canExit = false;
  180 + return createThread();
  181 + }
  182 +
  183 + bool start(int num)
  184 + {
  185 + m_canExit = false;
  186 + return createThread();
  187 + }
  188 +
  189 + void stop()
  190 + {
  191 + tryStop();
  192 + join(-1);
  193 + }
  194 +
  195 + void tryStop()
  196 + {
  197 + m_canExit = true;
  198 + doStop();
  199 + }
  200 +
  201 + bool join(int millisecond = -1)
  202 + {
  203 + bool ok = true;
  204 + if (m_handle != (pthread_t)-1)
  205 + {
  206 + if (millisecond <= 0)
  207 + {
  208 + ok = (0 == pthread_join(m_handle, NULL));
  209 + m_handle = (pthread_t)-1;
  210 + }
  211 + else
  212 + {
  213 + struct timespec ts;
  214 + getTimeout( &ts, millisecond );
  215 + ok = ( 0 == ::pthread_timedjoin_np(m_handle, NULL, &ts));
  216 + }
  217 + }
  218 +
  219 + return ok;
  220 + }
  221 +
  222 +
  223 + ThreadHandle getHandle() const
  224 + {
  225 + return m_handle;
  226 + }
  227 +
  228 + ThreadID getThreadID() const
  229 + {
  230 + return m_threadID;
  231 + }
  232 +
  233 + bool isRunning() const
  234 + {
  235 + return (m_handle != (pthread_t)-1);
  236 + }
  237 +
  238 + void setStackSize(unsigned int stack_size)
  239 + {
  240 + m_stackSize = stack_size;
  241 + }
  242 +
  243 + int kill(int sig)
  244 + {
  245 + int ret = 0;
  246 + if (isRunning())
  247 + {
  248 + ret = ::pthread_kill(m_handle, sig);
  249 + }
  250 + return ret;
  251 + }
  252 +
  253 +protected:
  254 + virtual int run() =0;
  255 + virtual bool startup() { return true; }
  256 + virtual bool startup(int num) { return true; }
  257 + virtual void cleanup() {}
  258 + virtual void doStop() {}
  259 +
  260 +
  261 + unsigned int m_stackSize;
  262 + ThreadID m_threadID;
  263 + ThreadHandle m_handle;
  264 + bool m_canExit;
  265 +
  266 +
  267 +
  268 +private:
  269 + static void* ThreadFunction(void* param)
  270 + {
  271 + int code = 0;
  272 + Thread* pThread = (Thread*)param;
  273 + pThread->m_threadID = syscall( SYS_gettid );
  274 + if ( !pThread->m_canExit )
  275 + {
  276 + if (pThread->startup())
  277 + {
  278 + code = pThread->run();
  279 + }
  280 + else
  281 + {
  282 + code = 1;
  283 + }
  284 + pThread->cleanup();
  285 + }
  286 + // pThread->m_handle = (pthread_t)-1;
  287 + pThread->m_threadID = 0;
  288 + ::pthread_exit(&code);
  289 + return NULL;
  290 + }
  291 +
  292 + bool createThread()
  293 + {
  294 + pthread_attr_t attr;
  295 + ::pthread_attr_init( &attr );
  296 + pthread_attr_t* pAttr = NULL;
  297 + if ( 0 != m_stackSize )
  298 + {
  299 + ::pthread_attr_setstacksize( &attr, m_stackSize );
  300 + pAttr = &attr;
  301 + }
  302 + int ret = ::pthread_create( &m_handle, pAttr, ThreadFunction, (void*)this );
  303 + ::pthread_attr_destroy( &attr );
  304 + return ( 0 == ret );
  305 + }
  306 +
  307 + //线程绑定CPU的核
  308 + bool createThread(int num)
  309 + {
  310 + pthread_attr_t attr;
  311 + ::pthread_attr_init(&attr);
  312 + pthread_attr_t* pAttr = NULL;
  313 + if (0 != m_stackSize)
  314 + {
  315 + ::pthread_attr_setstacksize(&attr, m_stackSize);
  316 + pAttr = &attr;
  317 + }
  318 + int ret = ::pthread_create(&m_handle, pAttr, ThreadFunction, (void*)this);
  319 +
  320 + cpu_set_t cpu_info;
  321 + CPU_ZERO(&cpu_info);
  322 + CPU_SET(num, &cpu_info);
  323 + if (0 != pthread_setaffinity_np(m_handle, sizeof(cpu_set_t), &cpu_info))
  324 + {
  325 + printf("set affinity failed");
  326 + }
  327 +
  328 + ::pthread_attr_destroy(&attr);
  329 + return (0 == ret);
  330 + }
  331 +
  332 + static void getTimeout(struct timespec *spec, int timer)
  333 + {
  334 + struct timeval current;
  335 + gettimeofday( &current, NULL );
  336 + TIMEVAL_TO_TIMESPEC( &current, spec );
  337 + spec->tv_sec = current.tv_sec + ((timer + current.tv_usec / 1000) / 1000);
  338 + spec->tv_nsec = ((current.tv_usec / 1000 + timer) % 1000) * 1000000;
  339 + }
  340 +
  341 +};
  342 +
  343 +#endif //WIN32
  344 +
  345 +} // end of namespace
  346 +////////////////////////////////////////////////////////////////////////////
  347 +
  348 +#endif /* TTHREAD_H_ */
... ...
src/left_over/auth/sycJson.cpp 0 → 100644
  1 +/*
  2 + Copyright (c) 2009 Dave Gamble
  3 +
  4 + Permission is hereby granted, free of charge, to any person obtaining a copy
  5 + of this software and associated documentation files (the "Software"), to deal
  6 + in the Software without restriction, including without limitation the rights
  7 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8 + copies of the Software, and to permit persons to whom the Software is
  9 + furnished to do so, subject to the following conditions:
  10 +
  11 + The above copyright notice and this permission notice shall be included in
  12 + all copies or substantial portions of the Software.
  13 +
  14 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20 + THE SOFTWARE.
  21 +*/
  22 +
  23 +/* cJSON */
  24 +/* JSON parser in C. */
  25 +
  26 +#include <string.h>
  27 +#include <stdio.h>
  28 +#include <math.h>
  29 +#include <stdlib.h>
  30 +#include <float.h>
  31 +#include <limits.h>
  32 +#include <ctype.h>
  33 +#include "sycJson.h"
  34 +
  35 +static const char *ep;
  36 +
  37 +const char *cJSON_GetErrorPtr(void) {return ep;}
  38 +
  39 +static int cJSON_strcasecmp(const char *s1,const char *s2)
  40 +{
  41 + if (!s1) return (s1==s2)?0:1;if (!s2) return 1;
  42 + for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0;
  43 + return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
  44 +}
  45 +
  46 +static void *(*cJSON_malloc)(size_t sz) = malloc;
  47 +static void (*cJSON_free)(void *ptr) = free;
  48 +
  49 +static char* cJSON_strdup(const char* str)
  50 +{
  51 + size_t len;
  52 + char* copy;
  53 +
  54 + len = strlen(str) + 1;
  55 + if (!(copy = (char*)cJSON_malloc(len))) return 0;
  56 + memcpy(copy,str,len);
  57 + return copy;
  58 +}
  59 +
  60 +void cJSON_InitHooks(cJSON_Hooks* hooks)
  61 +{
  62 + if (!hooks) { /* Reset hooks */
  63 + cJSON_malloc = malloc;
  64 + cJSON_free = free;
  65 + return;
  66 + }
  67 +
  68 + cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
  69 + cJSON_free = (hooks->free_fn)?hooks->free_fn:free;
  70 +}
  71 +
  72 +/* Internal constructor. */
  73 +static cJSON *cJSON_New_Item(void)
  74 +{
  75 + cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
  76 + if (node) memset(node,0,sizeof(cJSON));
  77 + return node;
  78 +}
  79 +
  80 +/* Delete a cJSON structure. */
  81 +void cJSON_Delete(cJSON *c)
  82 +{
  83 + cJSON *next;
  84 + while (c)
  85 + {
  86 + next=c->next;
  87 + if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child);
  88 + if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring);
  89 + if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string);
  90 + cJSON_free(c);
  91 + c=next;
  92 + }
  93 +}
  94 +
  95 +/* Parse the input text to generate a number, and populate the result into item. */
  96 +static const char *parse_number(cJSON *item,const char *num)
  97 +{
  98 + double n=0,sign=1,scale=0;int subscale=0,signsubscale=1;
  99 +
  100 + if (*num=='-') sign=-1,num++; /* Has sign? */
  101 + if (*num=='0') num++; /* is zero */
  102 + if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */
  103 + if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */
  104 + if (*num=='e' || *num=='E') /* Exponent? */
  105 + { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */
  106 + while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */
  107 + }
  108 +
  109 + n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */
  110 +
  111 + item->valuedouble=n;
  112 + item->valueint=(int)n;
  113 + item->type=cJSON_Number;
  114 + return num;
  115 +}
  116 +
  117 +static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; }
  118 +
  119 +typedef struct {char *buffer; int length; int offset; } printbuffer;
  120 +
  121 +static char* ensure(printbuffer *p,int needed)
  122 +{
  123 + char *newbuffer;int newsize;
  124 + if (!p || !p->buffer) return 0;
  125 + needed+=p->offset;
  126 + if (needed<=p->length) return p->buffer+p->offset;
  127 +
  128 + newsize=pow2gt(needed);
  129 + newbuffer=(char*)cJSON_malloc(newsize);
  130 + if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;}
  131 + if (newbuffer) memcpy(newbuffer,p->buffer,p->length);
  132 + cJSON_free(p->buffer);
  133 + p->length=newsize;
  134 + p->buffer=newbuffer;
  135 + return newbuffer+p->offset;
  136 +}
  137 +
  138 +static int update(printbuffer *p)
  139 +{
  140 + char *str;
  141 + if (!p || !p->buffer) return 0;
  142 + str=p->buffer+p->offset;
  143 + return p->offset+strlen(str);
  144 +}
  145 +
  146 +/* Render the number nicely from the given item into a string. */
  147 +static char *print_number(cJSON *item,printbuffer *p)
  148 +{
  149 + char *str=0;
  150 + double d=item->valuedouble;
  151 + if (d==0)
  152 + {
  153 + if (p) str=ensure(p,2);
  154 + else str=(char*)cJSON_malloc(2); /* special case for 0. */
  155 + if (str) strcpy(str,"0");
  156 + }
  157 + else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN)
  158 + {
  159 + if (p) str=ensure(p,21);
  160 + else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */
  161 + if (str) sprintf(str,"%d",item->valueint);
  162 + }
  163 + else
  164 + {
  165 + if (p) str=ensure(p,64);
  166 + else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */
  167 + if (str)
  168 + {
  169 + if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60)sprintf(str,"%.0f",d);
  170 + else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d);
  171 + else sprintf(str,"%f",d);
  172 + }
  173 + }
  174 + return str;
  175 +}
  176 +
  177 +static unsigned parse_hex4(const char *str)
  178 +{
  179 + unsigned h=0;
  180 + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
  181 + h=h<<4;str++;
  182 + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
  183 + h=h<<4;str++;
  184 + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
  185 + h=h<<4;str++;
  186 + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
  187 + return h;
  188 +}
  189 +
  190 +/* Parse the input text into an unescaped cstring, and populate item. */
  191 +static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
  192 +static const char *parse_string(cJSON *item,const char *str)
  193 +{
  194 + const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;
  195 + if (*str!='\"') {ep=str;return 0;} /* not a string! */
  196 +
  197 + while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */
  198 +
  199 + out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */
  200 + if (!out) return 0;
  201 +
  202 + ptr=str+1;ptr2=out;
  203 + while (*ptr!='\"' && *ptr)
  204 + {
  205 + if (*ptr!='\\') *ptr2++=*ptr++;
  206 + else
  207 + {
  208 + ptr++;
  209 + switch (*ptr)
  210 + {
  211 + case 'b': *ptr2++='\b'; break;
  212 + case 'f': *ptr2++='\f'; break;
  213 + case 'n': *ptr2++='\n'; break;
  214 + case 'r': *ptr2++='\r'; break;
  215 + case 't': *ptr2++='\t'; break;
  216 + case 'u': /* transcode utf16 to utf8. */
  217 + uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */
  218 +
  219 + if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; /* check for invalid. */
  220 +
  221 + if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */
  222 + {
  223 + if (ptr[1]!='\\' || ptr[2]!='u') break; /* missing second-half of surrogate. */
  224 + uc2=parse_hex4(ptr+3);ptr+=6;
  225 + if (uc2<0xDC00 || uc2>0xDFFF) break; /* invalid second-half of surrogate. */
  226 + uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));
  227 + }
  228 +
  229 + len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;
  230 +
  231 + switch (len) {
  232 + case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
  233 + case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
  234 + case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
  235 + case 1: *--ptr2 =(uc | firstByteMark[len]);
  236 + }
  237 + ptr2+=len;
  238 + break;
  239 + default: *ptr2++=*ptr; break;
  240 + }
  241 + ptr++;
  242 + }
  243 + }
  244 + *ptr2=0;
  245 + if (*ptr=='\"') ptr++;
  246 + item->valuestring=out;
  247 + item->type=cJSON_String;
  248 + return ptr;
  249 +}
  250 +
  251 +/* Render the cstring provided to an escaped version that can be printed. */
  252 +static char *print_string_ptr(const char *str,printbuffer *p)
  253 +{
  254 + const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token;
  255 +
  256 + for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0;
  257 + if (!flag)
  258 + {
  259 + len=ptr-str;
  260 + if (p) out=ensure(p,len+3);
  261 + else out=(char*)cJSON_malloc(len+3);
  262 + if (!out) return 0;
  263 + ptr2=out;*ptr2++='\"';
  264 + strcpy(ptr2,str);
  265 + ptr2[len]='\"';
  266 + ptr2[len+1]=0;
  267 + return out;
  268 + }
  269 +
  270 + if (!str)
  271 + {
  272 + if (p) out=ensure(p,3);
  273 + else out=(char*)cJSON_malloc(3);
  274 + if (!out) return 0;
  275 + strcpy(out,"\"\"");
  276 + return out;
  277 + }
  278 + ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;}
  279 +
  280 + if (p) out=ensure(p,len+3);
  281 + else out=(char*)cJSON_malloc(len+3);
  282 + if (!out) return 0;
  283 +
  284 + ptr2=out;ptr=str;
  285 + *ptr2++='\"';
  286 + while (*ptr)
  287 + {
  288 + if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++;
  289 + else
  290 + {
  291 + *ptr2++='\\';
  292 + switch (token=*ptr++)
  293 + {
  294 + case '\\': *ptr2++='\\'; break;
  295 + case '\"': *ptr2++='\"'; break;
  296 + case '\b': *ptr2++='b'; break;
  297 + case '\f': *ptr2++='f'; break;
  298 + case '\n': *ptr2++='n'; break;
  299 + case '\r': *ptr2++='r'; break;
  300 + case '\t': *ptr2++='t'; break;
  301 + default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */
  302 + }
  303 + }
  304 + }
  305 + *ptr2++='\"';*ptr2++=0;
  306 + return out;
  307 +}
  308 +/* Invote print_string_ptr (which is useful) on an item. */
  309 +static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);}
  310 +
  311 +/* Predeclare these prototypes. */
  312 +static const char *parse_value(cJSON *item,const char *value);
  313 +static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p);
  314 +static const char *parse_array(cJSON *item,const char *value);
  315 +static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p);
  316 +static const char *parse_object(cJSON *item,const char *value);
  317 +static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p);
  318 +
  319 +/* Utility to jump whitespace and cr/lf */
  320 +static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;}
  321 +
  322 +/* Parse an object - create a new root, and populate. */
  323 +cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated)
  324 +{
  325 + const char *end=0;
  326 + cJSON *c=cJSON_New_Item();
  327 + ep=0;
  328 + if (!c) return 0; /* memory fail */
  329 +
  330 + end=parse_value(c,skip(value));
  331 + if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */
  332 +
  333 + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
  334 + if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);ep=end;return 0;}}
  335 + if (return_parse_end) *return_parse_end=end;
  336 + return c;
  337 +}
  338 +/* Default options for cJSON_Parse */
  339 +cJSON *cJSON_Parse(const char *value) {return cJSON_ParseWithOpts(value,0,0);}
  340 +
  341 +/* Render a cJSON item/entity/structure to text. */
  342 +char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);}
  343 +char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);}
  344 +
  345 +char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt)
  346 +{
  347 + printbuffer p;
  348 + p.buffer=(char*)cJSON_malloc(prebuffer);
  349 + p.length=prebuffer;
  350 + p.offset=0;
  351 + return print_value(item,0,fmt,&p);
  352 + return p.buffer;
  353 +}
  354 +
  355 +
  356 +/* Parser core - when encountering text, process appropriately. */
  357 +static const char *parse_value(cJSON *item,const char *value)
  358 +{
  359 + if (!value) return 0; /* Fail on null. */
  360 + if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; }
  361 + if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; }
  362 + if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; }
  363 + if (*value=='\"') { return parse_string(item,value); }
  364 + if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); }
  365 + if (*value=='[') { return parse_array(item,value); }
  366 + if (*value=='{') { return parse_object(item,value); }
  367 +
  368 + ep=value;return 0; /* failure. */
  369 +}
  370 +
  371 +/* Render a value to text. */
  372 +static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p)
  373 +{
  374 + char *out=0;
  375 + if (!item) return 0;
  376 + if (p)
  377 + {
  378 + switch ((item->type)&255)
  379 + {
  380 + case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;}
  381 + case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;}
  382 + case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;}
  383 + case cJSON_Number: out=print_number(item,p);break;
  384 + case cJSON_String: out=print_string(item,p);break;
  385 + case cJSON_Array: out=print_array(item,depth,fmt,p);break;
  386 + case cJSON_Object: out=print_object(item,depth,fmt,p);break;
  387 + }
  388 + }
  389 + else
  390 + {
  391 + switch ((item->type)&255)
  392 + {
  393 + case cJSON_NULL: out=cJSON_strdup("null"); break;
  394 + case cJSON_False: out=cJSON_strdup("false");break;
  395 + case cJSON_True: out=cJSON_strdup("true"); break;
  396 + case cJSON_Number: out=print_number(item,0);break;
  397 + case cJSON_String: out=print_string(item,0);break;
  398 + case cJSON_Array: out=print_array(item,depth,fmt,0);break;
  399 + case cJSON_Object: out=print_object(item,depth,fmt,0);break;
  400 + }
  401 + }
  402 + return out;
  403 +}
  404 +
  405 +/* Build an array from input text. */
  406 +static const char *parse_array(cJSON *item,const char *value)
  407 +{
  408 + cJSON *child;
  409 + if (*value!='[') {ep=value;return 0;} /* not an array! */
  410 +
  411 + item->type=cJSON_Array;
  412 + value=skip(value+1);
  413 + if (*value==']') return value+1; /* empty array. */
  414 +
  415 + item->child=child=cJSON_New_Item();
  416 + if (!item->child) return 0; /* memory fail */
  417 + value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */
  418 + if (!value) return 0;
  419 +
  420 + while (*value==',')
  421 + {
  422 + cJSON *new_item;
  423 + if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
  424 + child->next=new_item;new_item->prev=child;child=new_item;
  425 + value=skip(parse_value(child,skip(value+1)));
  426 + if (!value) return 0; /* memory fail */
  427 + }
  428 +
  429 + if (*value==']') return value+1; /* end of array */
  430 + ep=value;return 0; /* malformed. */
  431 +}
  432 +
  433 +/* Render an array to text */
  434 +static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p)
  435 +{
  436 + char **entries;
  437 + char *out=0,*ptr,*ret;int len=5;
  438 + cJSON *child=item->child;
  439 + int numentries=0,i=0,fail=0;
  440 + size_t tmplen=0;
  441 +
  442 + /* How many entries in the array? */
  443 + while (child) numentries++,child=child->next;
  444 + /* Explicitly handle numentries==0 */
  445 + if (!numentries)
  446 + {
  447 + if (p) out=ensure(p,3);
  448 + else out=(char*)cJSON_malloc(3);
  449 + if (out) strcpy(out,"[]");
  450 + return out;
  451 + }
  452 +
  453 + if (p)
  454 + {
  455 + /* Compose the output array. */
  456 + i=p->offset;
  457 + ptr=ensure(p,1);if (!ptr) return 0; *ptr='['; p->offset++;
  458 + child=item->child;
  459 + while (child && !fail)
  460 + {
  461 + print_value(child,depth+1,fmt,p);
  462 + p->offset=update(p);
  463 + if (child->next) {len=fmt?2:1;ptr=ensure(p,len+1);if (!ptr) return 0;*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;p->offset+=len;}
  464 + child=child->next;
  465 + }
  466 + ptr=ensure(p,2);if (!ptr) return 0; *ptr++=']';*ptr=0;
  467 + out=(p->buffer)+i;
  468 + }
  469 + else
  470 + {
  471 + /* Allocate an array to hold the values for each */
  472 + entries=(char**)cJSON_malloc(numentries*sizeof(char*));
  473 + if (!entries) return 0;
  474 + memset(entries,0,numentries*sizeof(char*));
  475 + /* Retrieve all the results: */
  476 + child=item->child;
  477 + while (child && !fail)
  478 + {
  479 + ret=print_value(child,depth+1,fmt,0);
  480 + entries[i++]=ret;
  481 + if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1;
  482 + child=child->next;
  483 + }
  484 +
  485 + /* If we didn't fail, try to malloc the output string */
  486 + if (!fail) out=(char*)cJSON_malloc(len);
  487 + /* If that fails, we fail. */
  488 + if (!out) fail=1;
  489 +
  490 + /* Handle failure. */
  491 + if (fail)
  492 + {
  493 + for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]);
  494 + cJSON_free(entries);
  495 + return 0;
  496 + }
  497 +
  498 + /* Compose the output array. */
  499 + *out='[';
  500 + ptr=out+1;*ptr=0;
  501 + for (i=0;i<numentries;i++)
  502 + {
  503 + tmplen=strlen(entries[i]);memcpy(ptr,entries[i],tmplen);ptr+=tmplen;
  504 + if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;}
  505 + cJSON_free(entries[i]);
  506 + }
  507 + cJSON_free(entries);
  508 + *ptr++=']';*ptr++=0;
  509 + }
  510 + return out;
  511 +}
  512 +
  513 +/* Build an object from the text. */
  514 +static const char *parse_object(cJSON *item,const char *value)
  515 +{
  516 + cJSON *child;
  517 + if (*value!='{') {ep=value;return 0;} /* not an object! */
  518 +
  519 + item->type=cJSON_Object;
  520 + value=skip(value+1);
  521 + if (*value=='}') return value+1; /* empty array. */
  522 +
  523 + item->child=child=cJSON_New_Item();
  524 + if (!item->child) return 0;
  525 + value=skip(parse_string(child,skip(value)));
  526 + if (!value) return 0;
  527 + child->string=child->valuestring;child->valuestring=0;
  528 + if (*value!=':') {ep=value;return 0;} /* fail! */
  529 + value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */
  530 + if (!value) return 0;
  531 +
  532 + while (*value==',')
  533 + {
  534 + cJSON *new_item;
  535 + if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
  536 + child->next=new_item;new_item->prev=child;child=new_item;
  537 + value=skip(parse_string(child,skip(value+1)));
  538 + if (!value) return 0;
  539 + child->string=child->valuestring;child->valuestring=0;
  540 + if (*value!=':') {ep=value;return 0;} /* fail! */
  541 + value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */
  542 + if (!value) return 0;
  543 + }
  544 +
  545 + if (*value=='}') return value+1; /* end of array */
  546 + ep=value;return 0; /* malformed. */
  547 +}
  548 +
  549 +/* Render an object to text. */
  550 +static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p)
  551 +{
  552 + char **entries=0,**names=0;
  553 + char *out=0,*ptr,*ret,*str;int len=7,i=0,j;
  554 + cJSON *child=item->child;
  555 + int numentries=0,fail=0;
  556 + size_t tmplen=0;
  557 + /* Count the number of entries. */
  558 + while (child) numentries++,child=child->next;
  559 + /* Explicitly handle empty object case */
  560 + if (!numentries)
  561 + {
  562 + if (p) out=ensure(p,fmt?depth+4:3);
  563 + else out=(char*)cJSON_malloc(fmt?depth+4:3);
  564 + if (!out) return 0;
  565 + ptr=out;*ptr++='{';
  566 + if (fmt) {*ptr++='\n';for (i=0;i<depth-1;i++) *ptr++='\t';}
  567 + *ptr++='}';*ptr++=0;
  568 + return out;
  569 + }
  570 + if (p)
  571 + {
  572 + /* Compose the output: */
  573 + i=p->offset;
  574 + len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0;
  575 + *ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len;
  576 + child=item->child;depth++;
  577 + while (child)
  578 + {
  579 + if (fmt)
  580 + {
  581 + ptr=ensure(p,depth); if (!ptr) return 0;
  582 + for (j=0;j<depth;j++) *ptr++='\t';
  583 + p->offset+=depth;
  584 + }
  585 + print_string_ptr(child->string,p);
  586 + p->offset=update(p);
  587 +
  588 + len=fmt?2:1;
  589 + ptr=ensure(p,len); if (!ptr) return 0;
  590 + *ptr++=':';if (fmt) *ptr++='\t';
  591 + p->offset+=len;
  592 +
  593 + print_value(child,depth,fmt,p);
  594 + p->offset=update(p);
  595 +
  596 + len=(fmt?1:0)+(child->next?1:0);
  597 + ptr=ensure(p,len+1); if (!ptr) return 0;
  598 + if (child->next) *ptr++=',';
  599 + if (fmt) *ptr++='\n';*ptr=0;
  600 + p->offset+=len;
  601 + child=child->next;
  602 + }
  603 + ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0;
  604 + if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
  605 + *ptr++='}';*ptr=0;
  606 + out=(p->buffer)+i;
  607 + }
  608 + else
  609 + {
  610 + /* Allocate space for the names and the objects */
  611 + entries=(char**)cJSON_malloc(numentries*sizeof(char*));
  612 + if (!entries) return 0;
  613 + names=(char**)cJSON_malloc(numentries*sizeof(char*));
  614 + if (!names) {cJSON_free(entries);return 0;}
  615 + memset(entries,0,sizeof(char*)*numentries);
  616 + memset(names,0,sizeof(char*)*numentries);
  617 +
  618 + /* Collect all the results into our arrays: */
  619 + child=item->child;depth++;if (fmt) len+=depth;
  620 + while (child)
  621 + {
  622 + names[i]=str=print_string_ptr(child->string,0);
  623 + entries[i++]=ret=print_value(child,depth,fmt,0);
  624 + if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1;
  625 + child=child->next;
  626 + }
  627 +
  628 + /* Try to allocate the output string */
  629 + if (!fail) out=(char*)cJSON_malloc(len);
  630 + if (!out) fail=1;
  631 +
  632 + /* Handle failure */
  633 + if (fail)
  634 + {
  635 + for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);}
  636 + cJSON_free(names);cJSON_free(entries);
  637 + return 0;
  638 + }
  639 +
  640 + /* Compose the output: */
  641 + *out='{';ptr=out+1;if (fmt)*ptr++='\n';*ptr=0;
  642 + for (i=0;i<numentries;i++)
  643 + {
  644 + if (fmt) for (j=0;j<depth;j++) *ptr++='\t';
  645 + tmplen=strlen(names[i]);memcpy(ptr,names[i],tmplen);ptr+=tmplen;
  646 + *ptr++=':';if (fmt) *ptr++='\t';
  647 + strcpy(ptr,entries[i]);ptr+=strlen(entries[i]);
  648 + if (i!=numentries-1) *ptr++=',';
  649 + if (fmt) *ptr++='\n';*ptr=0;
  650 + cJSON_free(names[i]);cJSON_free(entries[i]);
  651 + }
  652 +
  653 + cJSON_free(names);cJSON_free(entries);
  654 + if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
  655 + *ptr++='}';*ptr++=0;
  656 + }
  657 + return out;
  658 +}
  659 +
  660 +/* Get Array size/item / object item. */
  661 +int cJSON_GetArraySize(cJSON *array) {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;}
  662 +cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;}
  663 +cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;}
  664 +
  665 +/* Utility for array list handling. */
  666 +static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;}
  667 +/* Utility for handling references. */
  668 +static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;}
  669 +
  670 +/* Add item to array/object. */
  671 +void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}}
  672 +void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);}
  673 +void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (!(item->type&cJSON_StringIsConst) && item->string) cJSON_free(item->string);item->string=(char*)string;item->type|=cJSON_StringIsConst;cJSON_AddItemToArray(object,item);}
  674 +void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));}
  675 +void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));}
  676 +
  677 +cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0;
  678 + if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;}
  679 +void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));}
  680 +cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;}
  681 +void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));}
  682 +
  683 +/* Replace array/object items with new ones. */
  684 +void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) {cJSON_AddItemToArray(array,newitem);return;}
  685 + newitem->next=c;newitem->prev=c->prev;c->prev=newitem;if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;}
  686 +void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return;
  687 + newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem;
  688 + if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);}
  689 +void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}}
  690 +
  691 +/* Create basic types: */
  692 +cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;}
  693 +cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;}
  694 +cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;}
  695 +cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;}
  696 +cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;}
  697 +cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;}
  698 +cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;}
  699 +cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;}
  700 +
  701 +/* Create Arrays: */
  702 +cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
  703 +cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
  704 +cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
  705 +cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
  706 +
  707 +/* Duplication */
  708 +cJSON *cJSON_Duplicate(cJSON *item,int recurse)
  709 +{
  710 + cJSON *newitem,*cptr,*nptr=0,*newchild;
  711 + /* Bail on bad ptr */
  712 + if (!item) return 0;
  713 + /* Create new item */
  714 + newitem=cJSON_New_Item();
  715 + if (!newitem) return 0;
  716 + /* Copy over all vars */
  717 + newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble;
  718 + if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}}
  719 + if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}}
  720 + /* If non-recursive, then we're done! */
  721 + if (!recurse) return newitem;
  722 + /* Walk the ->next chain for the child. */
  723 + cptr=item->child;
  724 + while (cptr)
  725 + {
  726 + newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */
  727 + if (!newchild) {cJSON_Delete(newitem);return 0;}
  728 + if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */
  729 + else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */
  730 + cptr=cptr->next;
  731 + }
  732 + return newitem;
  733 +}
  734 +
  735 +void cJSON_Minify(char *json)
  736 +{
  737 + char *into=json;
  738 + while (*json)
  739 + {
  740 + if (*json==' ') json++;
  741 + else if (*json=='\t') json++; /* Whitespace characters. */
  742 + else if (*json=='\r') json++;
  743 + else if (*json=='\n') json++;
  744 + else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */
  745 + else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */
  746 + else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */
  747 + else *into++=*json++; /* All other characters. */
  748 + }
  749 + *into=0; /* and null-terminate. */
  750 +}
... ...
src/left_over/auth/sycJson.h 0 → 100644
  1 +/*
  2 + Copyright (c) 2009 Dave Gamble
  3 +
  4 + Permission is hereby granted, free of charge, to any person obtaining a copy
  5 + of this software and associated documentation files (the "Software"), to deal
  6 + in the Software without restriction, including without limitation the rights
  7 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8 + copies of the Software, and to permit persons to whom the Software is
  9 + furnished to do so, subject to the following conditions:
  10 +
  11 + The above copyright notice and this permission notice shall be included in
  12 + all copies or substantial portions of the Software.
  13 +
  14 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20 + THE SOFTWARE.
  21 +*/
  22 +
  23 +#ifndef cJSON__h
  24 +#define cJSON__h
  25 +
  26 +#ifdef __cplusplus
  27 +extern "C"
  28 +{
  29 +#endif
  30 +
  31 +/* cJSON Types: */
  32 +#define cJSON_False 0
  33 +#define cJSON_True 1
  34 +#define cJSON_NULL 2
  35 +#define cJSON_Number 3
  36 +#define cJSON_String 4
  37 +#define cJSON_Array 5
  38 +#define cJSON_Object 6
  39 +
  40 +#define cJSON_IsReference 256
  41 +#define cJSON_StringIsConst 512
  42 +
  43 +/* The cJSON structure: */
  44 +typedef struct cJSON {
  45 + struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
  46 + struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
  47 +
  48 + int type; /* The type of the item, as above. */
  49 +
  50 + char *valuestring; /* The item's string, if type==cJSON_String */
  51 + int valueint; /* The item's number, if type==cJSON_Number */
  52 + double valuedouble; /* The item's number, if type==cJSON_Number */
  53 +
  54 + char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
  55 +} cJSON;
  56 +
  57 +typedef struct cJSON_Hooks {
  58 + void *(*malloc_fn)(size_t sz);
  59 + void (*free_fn)(void *ptr);
  60 +} cJSON_Hooks;
  61 +
  62 +/* Supply malloc, realloc and free functions to cJSON */
  63 +extern void cJSON_InitHooks(cJSON_Hooks* hooks);
  64 +
  65 +
  66 +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
  67 +extern cJSON *cJSON_Parse(const char *value);
  68 +/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
  69 +extern char *cJSON_Print(cJSON *item);
  70 +/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
  71 +extern char *cJSON_PrintUnformatted(cJSON *item);
  72 +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
  73 +extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt);
  74 +/* Delete a cJSON entity and all subentities. */
  75 +extern void cJSON_Delete(cJSON *c);
  76 +
  77 +/* Returns the number of items in an array (or object). */
  78 +extern int cJSON_GetArraySize(cJSON *array);
  79 +/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
  80 +extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
  81 +/* Get item "string" from object. Case insensitive. */
  82 +extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
  83 +
  84 +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
  85 +extern const char *cJSON_GetErrorPtr(void);
  86 +
  87 +/* These calls create a cJSON item of the appropriate type. */
  88 +extern cJSON *cJSON_CreateNull(void);
  89 +extern cJSON *cJSON_CreateTrue(void);
  90 +extern cJSON *cJSON_CreateFalse(void);
  91 +extern cJSON *cJSON_CreateBool(int b);
  92 +extern cJSON *cJSON_CreateNumber(double num);
  93 +extern cJSON *cJSON_CreateString(const char *string);
  94 +extern cJSON *cJSON_CreateArray(void);
  95 +extern cJSON *cJSON_CreateObject(void);
  96 +
  97 +/* These utilities create an Array of count items. */
  98 +extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
  99 +extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
  100 +extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
  101 +extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
  102 +
  103 +/* Append item to the specified array/object. */
  104 +extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
  105 +extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
  106 +extern void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object */
  107 +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
  108 +extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
  109 +extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
  110 +
  111 +/* Remove/Detatch items from Arrays/Objects. */
  112 +extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
  113 +extern void cJSON_DeleteItemFromArray(cJSON *array,int which);
  114 +extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
  115 +extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string);
  116 +
  117 +/* Update array items. */
  118 +extern void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem); /* Shifts pre-existing items to the right. */
  119 +extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
  120 +extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
  121 +
  122 +/* Duplicate a cJSON item */
  123 +extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
  124 +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
  125 +need to be released. With recurse!=0, it will duplicate any children connected to the item.
  126 +The item->next and ->prev pointers are always zero on return from Duplicate. */
  127 +
  128 +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
  129 +extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
  130 +
  131 +extern void cJSON_Minify(char *json);
  132 +
  133 +/* Macros for creating things quickly. */
  134 +#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
  135 +#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
  136 +#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
  137 +#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))
  138 +#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
  139 +#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
  140 +
  141 +/* When assigning an integer value, it needs to be propagated to valuedouble too. */
  142 +#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val))
  143 +#define cJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val))
  144 +
  145 +#ifdef __cplusplus
  146 +}
  147 +#endif
  148 +
  149 +#endif
... ...
src/left_over/head.h deleted
1   -#pragma once
2   -#include "sy_common.h"
3   -
4   -typedef struct rs_params
5   -{
6   - int mode; //运行模式(DEVICE_GPU / DEVICE_CPU)
7   - int gpuid; //指定显卡id
8   - //其余算法参数 如长短边等
9   -
10   - sy_img image;
11   - int channel_deal;
12   - bool filt_flag;
13   - int min_area;
14   - int max_area;
15   -
16   - rs_params() :mode(DEVICE_GPU), gpuid(0), min_area(0), max_area(1000000) {};
17   -}rs_params;
src/left_over/left_over_det.h
1   -锘/*************************************************************************
2   -* Version: 閬楃暀鐗㏒DK_v0.0.0
3   -* CopyRight: 涓瑙嗚(鍖椾含)绉戞妧鏈夐檺鍏徃
4   -* UpdateDate锛0200319
5   -* Content: 閬楃暀鐗╂娴
  1 +/*************************************************************************
  2 +* Version: 遗留物SDK_v0.0.0
  3 +* CopyRight: 中科视语(北京)科技有限公司
  4 +* UpdateDate:20200319
  5 +* Content: 遗留物检测
6 6 *************************************************************************/
7 7 #pragma once
8 8 #ifdef _MSC_VER
... ... @@ -16,65 +16,107 @@
16 16 #endif
17 17  
18 18  
19   -#include "header.h"
  19 +
20 20  
21 21  
22 22 #define m_BOUNDING_BOX_MIN 50
23 23 #define m_BOUNDING_BOX_MAX 500
24 24 #define m_BOUNDING_BOX_RATEMIN 0.001
25 25 #define m_BOUNDING_BOX_RATEMAX 100
26   -#define MAXROINUM 10 // 鏈澶OI鏁
  26 +#define MAXROINUM 10 // 最大ROI数
27 27 #define MACDETECTOBJNUM 10
28 28  
29 29 #ifdef __cplusplus
30 30 extern "C"
31 31 {
32 32 #endif
  33 +//ImgData
  34 +//Point
  35 +#ifndef __SY_POINT__
  36 +#define __SY_POINT__
  37 +typedef struct sy_point
  38 +{
  39 + int x_;
  40 + int y_;
  41 + sy_point(int m_x, int m_y) :x_(m_x), y_(m_y) {};
  42 + sy_point() {};
  43 +} sy_point;
  44 +#endif
33 45  
34   -#ifndef __RS_PARAM__
35   -#define __RS_PARAM__
  46 +#ifndef __SY_IMG__
  47 +#define __SY_IMG__
  48 +typedef struct sy_img
  49 +{
  50 + unsigned char * data_;
  51 + int w_;
  52 + int h_;
  53 + int c_;
  54 + void set_data(int m_w, int m_h, int m_c, unsigned char * m_data)
  55 + {
  56 + w_ = m_w;
  57 + h_ = m_h;
  58 + c_ = m_c;
  59 + data_ = m_data; //Shallow copy
  60 + }
  61 +} sy_img;
  62 +#endif
  63 +//Rect
36 64 #ifndef __SY_RECT__
37 65 #define __SY_RECT__
38   - typedef struct sy_rect
39   - {
40   - int left_;
41   - int top_;
42   - int width_;
43   - int height_;
44   - sy_rect(int m_left, int m_top, int m_width, int m_height) :left_(m_left), top_(m_top), width_(m_width), height_(m_height) {};
45   - sy_rect() {};
46   - } sy_rect;
  66 +typedef struct sy_rect
  67 +{
  68 + int left_;
  69 + int top_;
  70 + int width_;
  71 + int height_;
  72 + sy_rect(int m_left, int m_top, int m_width, int m_height) :left_(m_left), top_(m_top), width_(m_width), height_(m_height) {};
  73 + sy_rect() {};
  74 +} sy_rect;
47 75 #endif
  76 +#ifndef __RS_PARAM__
  77 +#define __RS_PARAM__
48 78 #define MAXVERTEXNUM 10
  79 +#define MAXVERPATHLEN 128
  80 +typedef struct rs_auth_config {
  81 + char url[MAXVERPATHLEN];
  82 + int port;
  83 +}rs_auth_config;
  84 +
  85 +typedef enum rs_auth_type {
  86 + TIME = 0,
  87 + PRODUCT_ID = 1
  88 +}rs_auth_type;
49 89 typedef struct rs_param
50 90 {
51   - long frame_num; // 閫楃暀鏃堕棿 鍗曚綅甯ф暟
52   - double scale; //缂╁皬姣斾緥
53   - sy_rect rect[MAXVERTEXNUM]; //鏈夋晥鍖哄煙
54   - unsigned char rect_num; //鏈夋晥鍖哄煙鏁伴噺
  91 + long frame_num; //逗留时间 单位帧数
  92 + double scale; //缩小比例
  93 + sy_rect rect[MAXVERTEXNUM]; //有效区域
  94 + unsigned char rect_num; //有效区域数量
  95 + rs_auth_config auth;
  96 + rs_auth_type type;
55 97 }rs_param;
56 98 #endif
57 99  
58 100 #ifndef __MS_TRACE__
59 101 #define __MS_TRACE__
60   -#include "sy_common.h"
61   -// 杩愬姩鐩爣鍧愭爣鍙婅建杩
62   -#define MAXTRACENUM 200 //杞ㄨ抗鏈澶ч暱搴
  102 +
  103 +// 运动目标坐标及轨迹
  104 +#define MAXTRACENUM 200 //轨迹最大长度
63 105 typedef struct ms_trace {
64   - int trace_num; // 杞ㄨ抗闀垮害锛屾弿杩皃ObjTrace鐨勯暱搴
65   - sy_point obj_trace[MAXTRACENUM]; // 杞ㄨ抗锛岀偣鍧愭爣
  106 + int trace_num; // 轨迹长度,描述pObjTrace的长度
  107 + sy_point obj_trace[MAXTRACENUM]; // 轨迹,点坐标
66 108 }ms_trace;
67 109 #endif
68 110  
69 111 #ifndef __RS_INFO__
70 112 #define __RS_INFO__
71 113 typedef struct ms_object_info {
72   - sy_point curPos; // 褰撳墠鍧愭爣
73   - ms_trace trace; // 杞ㄨ抗鍙婃姤璀︾姸鎬
74   - int unique_id; // 褰撳墠鐩爣鐨勭壒鐐笽D
75   - sy_rect tar_box; // 鐩爣澶栨帴鐭╁舰
76   - bool pb_alarm_state[MAXROINUM]; // 瀵瑰簲鍖哄煙鏄惁鎶ヨ
77   - int pb_alarm_type[MAXROINUM]; // 瀵瑰簲鍖哄煙鏄摢绉嶆姤璀
  114 + sy_point curPos; // 当前坐标
  115 + ms_trace trace; // 轨迹及报警状态
  116 + int unique_id; // 当前目标的特点ID
  117 + sy_rect tar_box; // 目标外接矩形
  118 + bool pb_alarm_state[MAXROINUM]; // 对应区域是否报警
  119 + int pb_alarm_type[MAXROINUM]; // 对应区域是哪种报警
78 120 }ms_object_info;
79 121 #endif
80 122  
... ... @@ -90,45 +132,45 @@ typedef struct ms_trace {
90 132 #endif
91 133 /*************************************************************************
92 134 * FUNCTION: rs_init
93   - * PURPOSE: 鍒濆鍖
  135 + * PURPOSE: 初始化
94 136 * PARAM:
95   - [out] handle - 鍙ユ焺
96   - [in] hp_param - 鍒濆鍖栧弬鏁
  137 + [out] handle - 句柄
  138 + [in] hp_param - 初始化参数
97 139 * RETURN:
98   - [out] int - 鍒濆鍖栨槸鍚︽垚鍔燂紙SUCCEEDED琛ㄧず鎴愬姛锛孎AILED琛ㄧず澶辫触锛
  140 + [out] int - 初始化是否成功(SUCCEEDED表示成功,FAILED表示失败)
99 141 * NOTES:
100 142 *************************************************************************/
101 143 MSREGIONSURVEILANCE_API int rs_init(void **handle, rs_param param);
102 144 /*************************************************************************
103 145 * FUNCTION: rs_process
104   - * PURPOSE: 閬楃暀鐗╂娴
  146 + * PURPOSE: 遗留物检测
105 147 * PARAM:
106   - [in] tools - 鍙ユ焺
107   - [in] img_data - 妫娴嬪浘鍍忔暟鎹
108   - [in] result - 妫娴嬬粨鏋
  148 + [in] tools - 句柄
  149 + [in] img_data - 检测图像数据
  150 + [in] result - 检测结果
109 151 * RETURN:
110   - [out] int - 妫娴嬫槸鍚︽垚鍔燂紙SUCCEED琛ㄧず鎴愬姛锛孎AILED琛ㄧず澶辫触锛
  152 + [out] int - 检测是否成功(SUCCEED表示成功,FAILED表示失败)
111 153 * NOTES:
112 154 *************************************************************************/
113 155 MSREGIONSURVEILANCE_API int rs_process(void *handle, sy_img img_data, rs_result *result);
114 156 /*************************************************************************
115 157 * FUNCTION: rs_batch
116   - * PURPOSE: 閬楃暀鐗╂娴 batch
  158 + * PURPOSE: 遗留物检测 batch
117 159 * PARAM:
118   - [in] tools - 鍙ユ焺
119   - [in] img_data - 妫娴嬪浘鍍忔暟鎹
120   - [in] batch_size - 妫娴嬪浘鍍忔暟鐩
121   - [in] result - 妫娴嬬粨鏋
  160 + [in] tools - 句柄
  161 + [in] img_data - 检测图像数据
  162 + [in] batch_size - 检测图像数目
  163 + [in] result - 检测结果
122 164 * RETURN:
123   - [out] int - 妫娴嬫槸鍚︽垚鍔燂紙SUCCEED琛ㄧず鎴愬姛锛孎AILED琛ㄧず澶辫触锛
  165 + [out] int - 检测是否成功(SUCCEED表示成功,FAILED表示失败)
124 166 * NOTES:
125 167 *************************************************************************/
126 168 MSREGIONSURVEILANCE_API int rs_batch(void *handle, sy_img *img_data, int batch_size, rs_result *result);
127 169 /*************************************************************************
128 170 *FUNCTION: rs_release
129   - * PURPOSE : 璧勬簮閲婃斁
  171 + * PURPOSE : 资源释放
130 172 * PARAM :
131   - [in] handle - 澶勭悊鍙ユ焺
  173 + [in] handle - 处理句柄
132 174 * RETURN : NULL
133 175 * NOTES :
134 176 **************************************************************************/
... ... @@ -137,7 +179,7 @@ typedef struct ms_trace {
137 179 * FUNCTION: rs_get_version
138 180 * PURPOSE:
139 181 * PARAM: NULL
140   - * RETURN: 鐗堟湰鍙
  182 + * RETURN: 版本号
141 183 * NOTES:
142 184 *************************************************************************/
143 185 MSREGIONSURVEILANCE_API const char * rs_get_version();
... ...
src/left_over/ms_region_surveilance.cpp
... ... @@ -4,18 +4,10 @@
4 4 #include <thread>
5 5 #include <ctime>
6 6 #include <chrono>
7   -#include "head.h"
8   -//#include "authority.h"
9 7 #include "sy_errorinfo.h"
10 8 #include <opencv2/opencv.hpp>
11   -#ifdef _MSC_VER
12   -#define productSN "50799D35A77C4D15ACB1A4D0018471D8" //windows 视频结构化-图片接口
13   -#else
14   -#define productSN "212B61A819604F588DC421D947F3F344" //linux 视频结构化--图片接口
15   -#endif
16   -//#define AUTHORIZATION
17   -
18   -
  9 +//#define productSN "D92CBC0CFBA54BD3846DEBD4A9D36FC1"
  10 +#define productSN "B5895C36B5304C9A9FE665A372BFFDA2"
19 11  
20 12 //void check_thread(RegionSurveillanceProcess* handle)
21 13 //{
... ... @@ -75,7 +67,7 @@ inline std::chrono::system_clock::time_point makeTimePoint(int year, int mon, in
75 67  
76 68 inline bool timecheck()
77 69 {
78   - std::chrono::system_clock::time_point limitTime = makeTimePoint(2020, 12, 31);
  70 + std::chrono::system_clock::time_point limitTime = makeTimePoint(2021, 7, 1);
79 71 std::chrono::system_clock::time_point nowTime = std::chrono::system_clock::now();
80 72 if (nowTime > limitTime)
81 73 {
... ... @@ -86,16 +78,30 @@ inline bool timecheck()
86 78 return true;
87 79 }
88 80 }
  81 +
  82 +
89 83 int rs_init(void **handle, rs_param param)
90 84 {
91 85 int ret = SUCCESS;
92   -
93   - if (timecheck())
  86 + RegionSurveillanceProcess* regin = new IRegionSurveillanceCpu;
  87 + bool auth_type = false;
  88 + if (param.type == TIME)
  89 + {
  90 + auth_type = timecheck();
  91 + }
  92 + else
  93 + {
  94 + char uuid[36] = {};
  95 + FILE *Uuid = fopen("/proc/sys/kernel/random/uuid", "r");
  96 + fgets(uuid, 36, Uuid);
  97 + //strcpy(uuid,"059bebb1-fca2-42e6-8cbd-6b3195641819");
  98 + fclose(Uuid);
  99 + regin->auth = new CheckAuthor;
  100 + regin->auth->Init(param.auth.url, param.auth.port, uuid, productSN, 1);
  101 + auth_type = regin->auth->GetAuthorStatus();
  102 + }
  103 + if (auth_type)
94 104 {
95   -
96   - RegionSurveillanceProcess* regin = nullptr;
97   - //if (param.mode == 0)
98   - regin = new IRegionSurveillanceCpu;
99 105 regin->frame_num = param.frame_num;
100 106 if (!regin)
101 107 {
... ... @@ -103,12 +109,6 @@ int rs_init(void **handle, rs_param param)
103 109 return -1;
104 110 }
105 111  
106   -
107   - /* regin->long_side = param.long_side;
108   - regin->short_side = param.short_side;*/
109   - regin->licence_status = 0;
110   -
111   - regin->thrd_status = 0;
112 112 regin->scale = param.scale;
113 113 regin->rect_num = param.rect_num; //有效区域数量
114 114 for (int i = 0; i < regin->rect_num; ++i)
... ... @@ -123,6 +123,7 @@ int rs_init(void **handle, rs_param param)
123 123 }
124 124 else
125 125 {
  126 + delete regin;
126 127 return AUTHOR_ERROR;
127 128 }
128 129  
... ... @@ -191,6 +192,12 @@ int rs_process(void *handle, sy_img img_data, rs_result *result)
191 192 printf("handle is NULL \n");
192 193 return -1;
193 194 }
  195 + if (regin->auth && 0 == regin->auth->GetAuthorStatus())
  196 + {
  197 + printf("auth error \n");
  198 + return -1;
  199 + }
  200 +
194 201 region_info pRegionInfo;
195 202 pRegionInfo.alarm_info = 6;
196 203 pRegionInfo.frame_num = regin->frame_num;
... ... @@ -332,14 +339,10 @@ void rs_release(void **handle)
332 339 printf("handle is NULL \n");
333 340 return;
334 341 }
335   - if (regin->thrd_status == 0)
  342 + if (regin->auth)
336 343 {
337   -#ifdef AUTHORIZATION
338   - regin->thrd.interrupt();
339   - //regin->thrd_run = false;
340   - regin->thrd.join();
341   -#endif
342   - regin->thrd_status = -1;
  344 + regin->auth->Uninit();
  345 + delete regin->auth;
343 346 }
344 347 delete regin;
345 348 regin = nullptr;
... ...
src/left_over/svibe.h
... ... @@ -113,8 +113,8 @@ public:
113 113 left_flag = 1; // 逗留标志 0 遗留 1移除
114 114 left_flag_now_s = 1;
115 115 left_flag_now_w = 1;
116   - OBJECT_AREA_MIN = 1000000; //默认最大过滤面积为1,000,000 by zl 20160304
117   - OBJECT_AREA_MAX = 300; //默认最小过滤面积为300 by zl 20160304
  116 + OBJECT_AREA_MAX = 1000000; //默认最大过滤面积为1,000,000 by zl 20160304
  117 + OBJECT_AREA_MIN = 300; //默认最小过滤面积为300 by zl 20160304
118 118  
119 119 stay_dis = 5;
120 120 greyImgData = NULL;
... ...
src/left_over/sy_errorinfo.h 0 → 100644
  1 +#ifndef __SY_ERRORINFO_H__
  2 +#define __SY_ERRORINFO_H__
  3 +
  4 +
  5 +//--------------------------------通用------------------------------------//
  6 +
  7 +#define SUCCESS 0 //成功
  8 +#define FAILED -1 //失败
  9 +
  10 +//1.通用错误 预留编号:(-199) - (-100)
  11 +#define PARAMS_NULL_ERROR -100 //参数为空
  12 +#define FILE_NOTFOUND_ERROR -101 //文件找不到
  13 +#define HANDLE_NULL_ERROR -102 //句柄为空
  14 +#define TYPE_UNKNOWN -103 //未知类型
  15 +#define IMG_DATA_ERROR -104 //图像数据错误
  16 +#define IMG_PARAMS_ERROR -105 //图像参数(宽 高 或者 通道数)有错误
  17 +#define AUTHOR_ERROR -106 //授权失败
  18 +#define VERSION_EXPIRED -107 //时间限制下的版本过期
  19 +#define VIDEOFILEERROR -108 //视频打开失败
  20 +#define BUFFNOTENOUGH -109 //缓冲区太小
  21 +
  22 +#define MEAN_ERROR -110 //均值错误
  23 +#define NEW_DATA_ERROR -111 //内存申请失败
  24 +#define GPUID_PARAM_ERROR -112 //显卡参数设置错误
  25 +#define CODEC_FORMAT_ERROR -113 //不支持的解码格式
  26 +#define PARAMS_INVALID_ERROR -114 //参数值无效
  27 +
  28 +//------------------------------------------------------------------------//
  29 +
  30 +
  31 +//-----------------------------深度学习相关-------------------------------//
  32 +
  33 +//1.通用模块 预留编号:(-299) - (-200)
  34 +
  35 +//a. caffe部分 预留编号:(-239) - (-200)
  36 +#define BATCH_SIZE_NO_EQUAL_INPUT -200 //BATCH_SIZE不匹配
  37 +#define LAYER_NO_REGISTER -201 //层未注册
  38 +
  39 +//b. 网络和模型部分 预留编号:(-279) - (-240)
  40 +#define PROTOFILE_MODEL_MISMATCH -240 //网络和模型不匹配
  41 +#define PROTOFILEORVECTOR_NOTFOUND -241 //网络文件或者数组找不到
  42 +#define PROTOFILE_NOTFOUND -242 //网络文件找不到
  43 +#define PROTOVECTOR_NOTFOUND -243 //网络数组找不到
  44 +#define MODELFILE_NOTFOUND -244 //模型文件找不到
  45 +#define MODELLENGTH_ERROE -245 //模型数组长度错误
  46 +#define MODELVECTOR_ERROE -246 //模型数组错误
  47 +
  48 +//c. 其他深度学习通用错误 预留编号:(-299) - (-280)
  49 +
  50 +//----------------------------------------//
  51 +
  52 +
  53 +//2.人脸模块 预留编号:(-349) - (-300)
  54 +
  55 +//a. 人脸检测错误返回 预留编号:(-319) - (-300)
  56 +#define QUALITY_INIT_ERROR -300 //质量检测初始化失败
  57 +#define ROTATIONCUT_INIT_ERROR -301 //切割旋转初始化失败
  58 +#define FACERECG_INITFAILD_ERROR -302 //人脸识别初始化失败
  59 +#define FACECUT_INITFAILD_ERROR -303 //人脸切割旋转初始化失败
  60 +#define LDMK_INIT_ERROR -304 //关键点检测初始化失败
  61 +#define FACEDETECT_INIT_ERROR -305 //人脸检测初始化失败
  62 +#define POSE_INIT_ERROR -306 //人脸角度初始化失败
  63 +#define SCORE_INIT_ERROR -307 //人脸置信度初始化失败
  64 +#define DB_OPEN_DB_ERROR -308 //数据库打开失败(数据库错误)
  65 +#define DB_OPEN_SYS_ERROR -309 //数据库打开失败(程序内部错误)
  66 +#define DB_ADD_DATA_EXIST_ERROR -310 //数据库插入数据失败(已存在)
  67 +#define DB_ADD_DATA_NOTFOUND -311 //数据库插入数据失败
  68 +#define FACEATTRIBUTES_INITFAILD_ERROR -312 //人脸属性初始化失败
  69 +
  70 +
  71 +//c. 其他人脸模块错误 预留编号:(-349) - (-340)
  72 +
  73 +
  74 +//----------------------------------------//
  75 +
  76 +
  77 +//3.跟踪模块 预留编号:(-399) - (-350)
  78 +#define TRACKER_INIT_ERROR -350 //轨迹跟踪初始化失败
  79 +
  80 +
  81 +//----------------------------------------//
  82 +
  83 +
  84 +//4.快照模块 预留编号:(-449) - (-400)
  85 +#define SHAPSHOT_INIT_ERROR -400 //快照初始化失败
  86 +
  87 +
  88 +//----------------------------------------//
  89 +
  90 +
  91 +//5.流量统计模块 预留编号:(-499) - (-450)
  92 +#define TRAFFICSTATISTICS_INIT_ERROR -450 //流量统计初始化失败
  93 +
  94 +//------------------------------------------------------------------------//
  95 +
  96 +
  97 +//-----------------------------授权部分相关-------------------------------//
  98 +
  99 +//1.授权通用模块 预留编号:(-600) - (-500)
  100 +#define AUTHOR_TIMEEXPIRED_ERROR -500 //超出有效期
  101 +#define AUTHOR_SERVER_ERROR -501 //服务器出错
  102 +#define AUTHOR_NOAUTHORIZATION_ERROR -502 //未注册且没有装机剩余量
  103 +#define AUTHOR_NOCOMMUNICATION_ERROR -503 //无法通信
  104 +#define AUTHOR_NET_ERROR -504 //网络出错
  105 +#define LICENCE_SERVICECHECK_ERROR -505 //服务检查未成功
  106 +#define LICENCE_SERVICENOTRUNNING_ERROR -506 //服务未开启
  107 +#define LICENCE_LICENCEDATA_ERROR -507 //授权文件数据错误
  108 +#define LICENCE_LICENCEINVALID_ERROR -508 //授权文件无效
  109 +#define LICENCE_LICENCENOTEXIST_ERROR -509 //授权文件不存在
  110 +
  111 +//------------------------------------------------------------------------//
  112 +
  113 +
  114 +//--------------------------------sdk相关---------------------------------//
  115 +
  116 +//1.视频结构化模块 预留编号:(-699) - (-600)
  117 +
  118 +
  119 +//a.二次属性错误返回 预留编号:(-649) - (-600)
  120 +
  121 +#define HUMANPARSING_INIT_ERROR -600 //行人结构化初始化失败
  122 +#define HUMANCARPARSING_INIT_ERROR -601 //人骑车结构化初始化失败
  123 +#define VEHICLECOLOR_INIT_ERROR -602 //车颜色识别初始化失败
  124 +#define VEHICLEPLATEDETECT_INIT_ERROR -603 //车牌检测初始化失败
  125 +#define VEHICLEPLATERECOG_INIT_ERROR -604 //车牌识别初始化失败
  126 +#define VEHICLERECOG_INIT_ERROR -605 //车型识别初始化失败
  127 +#define VPT_DET_INIT_ERROR -606 //人车物检测初始化失败
  128 +//c.其他模块错误 预留编号:(-699) - (-650)
  129 +
  130 +//------------------------------------------------------------------------//
  131 +
  132 +
  133 +#endif // __SY_ERRORINFO_H__
0 134 \ No newline at end of file
... ...
src/test/CvxText.cpp deleted
1   -#include <wchar.h>
2   -
3   -#include <locale.h>
4   -#include <ctype.h>
5   -
6   -#include "CvxText.h"
7   -
8   -//====================================================================
9   -//====================================================================
10   -
11   -// 打开字库
12   -
13   -CvxText::CvxText(const char *freeType)
14   -{
15   - assert(freeType != NULL);
16   -
17   - // 打开字库文件, 创建一个字体
18   -
19   - if (FT_Init_FreeType(&m_library)) throw;
20   - if (FT_New_Face(m_library, freeType, 0, &m_face)) throw;
21   -
22   - // 设置字体输出参数
23   -
24   - restoreFont();
25   -
26   - // 设置C语言的字符集环境
27   -
28   - setlocale(LC_ALL, "");
29   -}
30   -
31   -// 释放FreeType资源
32   -
33   -CvxText::~CvxText()
34   -{
35   - FT_Done_Face(m_face);
36   - FT_Done_FreeType(m_library);
37   -}
38   -
39   -// 设置字体参数:
40   -//
41   -// font - 字体类型, 目前不支持
42   -// size - 字体大小/空白比例/间隔比例/旋转角度
43   -// underline - 下画线
44   -// diaphaneity - 透明度
45   -
46   -void CvxText::getFont(int *type, CvScalar *size, bool *underline, float *diaphaneity)
47   -{
48   - if (type) *type = m_fontType;
49   - if (size) *size = m_fontSize;
50   - if (underline) *underline = m_fontUnderline;
51   - if (diaphaneity) *diaphaneity = m_fontDiaphaneity;
52   -}
53   -
54   -void CvxText::setFont(int *type, CvScalar *size, bool *underline, float *diaphaneity)
55   -{
56   - // 参数合法性检查
57   -
58   - if (type)
59   - {
60   - if (type >= 0) m_fontType = *type;
61   - }
62   - if (size)
63   - {
64   - m_fontSize.val[0] = fabs(size->val[0]);
65   - m_fontSize.val[1] = fabs(size->val[1]);
66   - m_fontSize.val[2] = fabs(size->val[2]);
67   - m_fontSize.val[3] = fabs(size->val[3]);
68   - FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0);
69   - }
70   - if (underline)
71   - {
72   - m_fontUnderline = *underline;
73   - }
74   - if (diaphaneity)
75   - {
76   - m_fontDiaphaneity = *diaphaneity;
77   - }
78   - //FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0);
79   -}
80   -
81   -// 恢复原始的字体设置
82   -
83   -void CvxText::restoreFont()
84   -{
85   - m_fontType = 0; // 字体类型(不支持)
86   -
87   - m_fontSize.val[0] = 20; // 字体大小
88   - m_fontSize.val[1] = 0.5; // 空白字符大小比例
89   - m_fontSize.val[2] = 0.1; // 间隔大小比例
90   - m_fontSize.val[3] = 0; // 旋转角度(不支持)
91   -
92   - m_fontUnderline = false; // 下画线(不支持)
93   -
94   - m_fontDiaphaneity = 1.0; // 色彩比例(可产生透明效果)
95   -
96   - // 设置字符大小
97   -
98   - FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0);
99   -}
100   -
101   -// 输出函数(颜色默认为黑色)
102   -
103   -int CvxText::putText(IplImage *img, const char *text, CvPoint pos)
104   -{
105   - return putText(img, text, pos, CV_RGB(255, 255, 255));
106   -}
107   -int CvxText::putText(IplImage *img, const wchar_t *text, CvPoint pos)
108   -{
109   - return putText(img, text, pos, CV_RGB(255, 255, 255));
110   -}
111   -
112   -//
113   -
114   -int CvxText::putText(IplImage *img, const char *text, CvPoint pos, CvScalar color)
115   -{
116   - if (img == NULL) return -1;
117   - if (text == NULL) return -1;
118   -
119   - //
120   -
121   - int i;
122   - for (i = 0; text[i] != '\0'; ++i)
123   - {
124   - wchar_t wc = text[i];
125   -
126   - // 解析双字节符号
127   -
128   - if (!isascii(wc)) mbtowc(&wc, &text[i++], 2);
129   -
130   - // 输出当前的字符
131   -
132   - putWChar(img, wc, pos, color);
133   - }
134   - return i;
135   -}
136   -int CvxText::putText(IplImage *img, const wchar_t *text, CvPoint pos, CvScalar color)
137   -{
138   - if (img == NULL) return -1;
139   - if (text == NULL) return -1;
140   -
141   - //
142   -
143   - int i;
144   - for (i = 0; text[i] != '\0'; ++i)
145   - {
146   - // 输出当前的字符
147   -
148   - putWChar(img, text[i], pos, color);
149   - }
150   - return i;
151   -}
152   -
153   -// 输出当前字符, 更新m_pos位置
154   -
155   -void CvxText::putWChar(IplImage *img, wchar_t wc, CvPoint &pos, CvScalar color)
156   -{
157   - // 根据unicode生成字体的二值位图
158   -
159   - FT_UInt glyph_index = FT_Get_Char_Index(m_face, wc);
160   - FT_Load_Glyph(m_face, glyph_index, FT_LOAD_DEFAULT);
161   - FT_Render_Glyph(m_face->glyph, FT_RENDER_MODE_MONO);
162   -
163   - //
164   -
165   - FT_GlyphSlot slot = m_face->glyph;
166   -
167   - // 行列数
168   -
169   - int rows = slot->bitmap.rows;
170   - int cols = slot->bitmap.width;
171   -
172   - //
173   -
174   - for (int i = 0; i < rows; ++i)
175   - {
176   - for (int j = 0; j < cols; ++j)
177   - {
178   - int off = ((img->origin == 0) ? i : (rows - 1 - i))
179   - * slot->bitmap.pitch + j / 8;
180   -
181   - if (slot->bitmap.buffer[off] & (0xC0 >> (j % 8)))
182   - {
183   - int r = (img->origin == 0) ? pos.y - (rows - 1 - i) : pos.y + i;;
184   - int c = pos.x + j;
185   -
186   - if (r >= 0 && r < img->height
187   - && c >= 0 && c < img->width)
188   - {
189   - CvScalar scalar = cvGet2D(img, r, c);
190   -
191   - // 进行色彩融合
192   -
193   - float p = m_fontDiaphaneity;
194   - for (int k = 0; k < 4; ++k)
195   - {
196   - scalar.val[k] = scalar.val[k] * (1 - p) + color.val[k] * p;
197   - }
198   -
199   - cvSet2D(img, r, c, scalar);
200   - }
201   - }
202   - } // end for
203   - } // end for
204   -
205   - // 修改下一个字的输出位置
206   -
207   - double space = m_fontSize.val[0] * m_fontSize.val[1];
208   - double sep = m_fontSize.val[0] * m_fontSize.val[2];
209   -
210   - pos.x += (int)((cols ? cols : space) + sep);
211   -}
212 0 \ No newline at end of file
src/test/CvxText.h deleted
1   -//====================================================================
2   -//====================================================================
3   -//
4   -// 文件: CvxText.h
5   -//
6   -// 说明: OpenCV汉字输出
7   -//
8   -// 时间:
9   -//
10   -// 作者: chaishushan#gmail.com
11   -//
12   -//====================================================================
13   -//====================================================================
14   -
15   -#ifndef OPENCV_CVX_TEXT_2007_08_31_H
16   -#define OPENCV_CVX_TEXT_2007_08_31_H
17   -
18   -/**
19   -* \file CvxText.h
20   -* \brief OpenCV汉字输出接口
21   -*
22   -* 实现了汉字输出功能。
23   -*/
24   -
25   -#include <ft2build.h>
26   -#include FT_FREETYPE_H
27   -
28   -#include <opencv2/opencv.hpp>
29   -
30   -/**
31   -* \class CvxText
32   -* \brief OpenCV中输出汉字
33   -*
34   -* OpenCV中输出汉字。字库提取采用了开源的FreeFype库。由于FreeFype是
35   -* GPL版权发布的库,和OpenCV版权并不一致,因此目前还没有合并到OpenCV
36   -* 扩展库中。
37   -*
38   -* 显示汉字的时候需要一个汉字字库文件,字库文件系统一般都自带了。
39   -* 这里采用的是一个开源的字库:“文泉驿正黑体”。
40   -*
41   -* 关于"OpenCV扩展库"的细节请访问
42   -* http://code.google.com/p/opencv-extension-library/
43   -*
44   -* 关于FreeType的细节请访问
45   -* http://www.freetype.org/
46   -*/
47   -
48   -
49   -class CvxText
50   -{
51   - // 禁止copy
52   -
53   - CvxText& operator=(const CvxText&);
54   -
55   - //================================================================
56   - //================================================================
57   -
58   -public:
59   -
60   - /**
61   - * 装载字库文件
62   - */
63   -
64   - CvxText(const char *freeType);
65   - virtual ~CvxText();
66   -
67   - //================================================================
68   - //================================================================
69   -
70   - /**
71   - * 获取字体。目前有些参数尚不支持。
72   - *
73   - * \param font 字体类型, 目前不支持
74   - * \param size 字体大小/空白比例/间隔比例/旋转角度
75   - * \param underline 下画线
76   - * \param diaphaneity 透明度
77   - *
78   - * \sa setFont, restoreFont
79   - */
80   -
81   - void getFont(int *type,
82   - CvScalar *size = NULL, bool *underline = NULL, float *diaphaneity = NULL);
83   -
84   - /**
85   - * 设置字体。目前有些参数尚不支持。
86   - *
87   - * \param font 字体类型, 目前不支持
88   - * \param size 字体大小/空白比例/间隔比例/旋转角度
89   - * \param underline 下画线
90   - * \param diaphaneity 透明度
91   - *
92   - * \sa getFont, restoreFont
93   - */
94   -
95   - void setFont(int *type,
96   - CvScalar *size = NULL, bool *underline = NULL, float *diaphaneity = NULL);
97   -
98   - /**
99   - * 恢复原始的字体设置。
100   - *
101   - * \sa getFont, setFont
102   - */
103   -
104   - void restoreFont();
105   -
106   - //================================================================
107   - //================================================================
108   -
109   - /**
110   - * 输出汉字(颜色默认为黑色)。遇到不能输出的字符将停止。
111   - *
112   - * \param img 输出的影象
113   - * \param text 文本内容
114   - * \param pos 文本位置
115   - *
116   - * \return 返回成功输出的字符长度,失败返回-1。
117   - */
118   -
119   - int putText(IplImage *img, const char *text, CvPoint pos);
120   -
121   - /**
122   - * 输出汉字(颜色默认为黑色)。遇到不能输出的字符将停止。
123   - *
124   - * \param img 输出的影象
125   - * \param text 文本内容
126   - * \param pos 文本位置
127   - *
128   - * \return 返回成功输出的字符长度,失败返回-1。
129   - */
130   -
131   - int putText(IplImage *img, const wchar_t *text, CvPoint pos);
132   -
133   - /**
134   - * 输出汉字。遇到不能输出的字符将停止。
135   - *
136   - * \param img 输出的影象
137   - * \param text 文本内容
138   - * \param pos 文本位置
139   - * \param color 文本颜色
140   - *
141   - * \return 返回成功输出的字符长度,失败返回-1。
142   - */
143   -
144   - int putText(IplImage *img, const char *text, CvPoint pos, CvScalar color);
145   -
146   - /**
147   - * 输出汉字。遇到不能输出的字符将停止。
148   - *
149   - * \param img 输出的影象
150   - * \param text 文本内容
151   - * \param pos 文本位置
152   - * \param color 文本颜色
153   - *
154   - * \return 返回成功输出的字符长度,失败返回-1。
155   - */
156   - int putText(IplImage *img, const wchar_t *text, CvPoint pos, CvScalar color);
157   -
158   - //================================================================
159   - //================================================================
160   -
161   -private:
162   -
163   - // 输出当前字符, 更新m_pos位置
164   -
165   - void putWChar(IplImage *img, wchar_t wc, CvPoint &pos, CvScalar color);
166   -
167   - //================================================================
168   - //================================================================
169   -
170   -private:
171   -
172   - FT_Library m_library; // 字库
173   - FT_Face m_face; // 字体
174   -
175   - //================================================================
176   - //================================================================
177   -
178   - // 默认的字体输出参数
179   -
180   - int m_fontType;
181   - CvScalar m_fontSize;
182   - bool m_fontUnderline;
183   - float m_fontDiaphaneity;
184   -
185   - //================================================================
186   - //================================================================
187   -};
188   -
189   -#endif // OPENCV_CVX_TEXT_2007_08_31_H</opencv2></ft2build.h>
190   -
src/test/demo - 副本.cpp deleted
1   -#include <stdio.h>
2   -#include <iostream>
3   -#include <time.h>
4   -#include <stdlib.h>
5   -
6   -#include "MSRegionSurveilance.h"
7   -#include "highgui.h"
8   -#include "cv.h"
9   -#include "RegionAssist.h"
10   -
11   -#include "time_debug.h"
12   -
13   -#include <opencv2/opencv.hpp>
14   -
15   -
16   -using namespace std;
17   -//using namespace cv;
18   -
19   -void imag_ana_1channels();
20   -void imag_ana_3channels();
21   -
22   -int main()
23   -{
24   - imag_ana_1channels();
25   - //imag_ana_3channels();
26   -
27   - system("pause");
28   -}
29   -
30   -
31   -void imag_ana_3channels()
32   -{
33   - //AlarmInfo 1进入禁区 2离开禁区 3单向越界 4双向越界 5徘徊 6丢包
34   - int numROI = 1;
35   -
36   - debug_time_t stime, etime;
37   -
38   - RegionInfo* pRegionInfo = new RegionInfo[numROI];
39   - int LeftPointX = 1050;
40   - int LeftPointY = 450;
41   - int RightPointX = 1400;
42   - int RightPointY = 600;
43   -
44   - // 进入禁区
45   - pRegionInfo[0].AlarmInfo = 1;
46   - pRegionInfo[0].nPointNum = 4;
47   - pRegionInfo[0].pROI[0].x = LeftPointX;
48   - pRegionInfo[0].pROI[0].y = LeftPointY;
49   - pRegionInfo[0].pROI[1].x = RightPointX;
50   - pRegionInfo[0].pROI[1].y = LeftPointY;
51   - pRegionInfo[0].pROI[2].x = RightPointX;
52   - pRegionInfo[0].pROI[2].y = RightPointY;
53   - pRegionInfo[0].pROI[3].x = LeftPointX;
54   - pRegionInfo[0].pROI[3].y = RightPointY;
55   -
56   - //pRegionInfo[0].AlarmInfo = 1;
57   - //pRegionInfo[0].nPointNum = 4;
58   - //pRegionInfo[0].pROI[0].x = LeftPointX/*226*/;
59   - //pRegionInfo[0].pROI[0].y = LeftPointY;
60   - //pRegionInfo[0].pROI[1].x = RightPointX/*223*/;
61   - //pRegionInfo[0].pROI[1].y = LeftPointY;
62   - //pRegionInfo[0].pROI[2].x = LeftPointX/*223*/;
63   - //pRegionInfo[0].pROI[2].y = RightPointY;
64   - //pRegionInfo[0].pROI[3].x = RightPointX/*223*/;
65   - //pRegionInfo[0].pROI[3].y = RightPointY;
66   - //pRegionInfo[0].dirPoint.x = 200;//用于定义方向的点 位于合法方向指向的一侧
67   - //pRegionInfo[0].dirPoint.y = 109;
68   -
69   - // 定义
70   - MS_RegionSurveillance MS1;
71   - IRegionSurveillance* test = MS1.GetMS_RS();
72   - if (!test)
73   - {
74   - printf("model initial failed");
75   - exit(0);
76   - }
77   -
78   - CvCapture* video1 = cvCaptureFromFile("../../data/test1.mp4");
79   - // 用opencv函数读取视频的一帧
80   - IplImage * src = cvQueryFrame(video1);
81   - IplImage * srcscale = cvCreateImage(cvSize(src->width, src->height), 8, 3);
82   - cvResize(src, srcscale);
83   - // 获得图像信息
84   - int width = srcscale->width;
85   - int height = srcscale->height;
86   - int widthstep = srcscale->widthStep;
87   - int nChannel = srcscale->nChannels;
88   -
89   - int frameCount = 0; // 处理的图像序号
90   - MS_ObjectInfo *ObjInfo = NULL; // 结果结构体
91   - int ObjCount;
92   - int error_flag;
93   -
94   - long total_t = 0;
95   - // 循环处理视频的每一帧
96   - while (src)
97   - {
98   - src = cvQueryFrame(video1);
99   -
100   - if (!src)
101   - break;
102   -
103   - cvResize(src, srcscale);
104   -
105   - // 如果当前处理的是第一帧,则要进行初始化
106   - if (frameCount == 0)
107   - {
108   - error_flag = test->RSinit(width, height, widthstep, (unsigned char*)(srcscale->imageData), nChannel, 3, 0, 10, 1000000);
109   - if (error_flag == 0)
110   - {
111   - cout << "设置有问题!!!" << endl;
112   - return;
113   - }
114   -
115   -
116   - error_flag = test->RSRegion(numROI, pRegionInfo, false);
117   - if (error_flag == 0)
118   - {
119   - cout << "区域设置有问题!!!" << endl;
120   - return;
121   - }
122   -
123   -
124   - }
125   - GetTime(&stime);
126   -
127   - // 智能分析
128   - test->RSDetect((unsigned char*)(srcscale->imageData), pRegionInfo);
129   -
130   - GetTime(&etime);
131   - total_t += CalcTimeDiff(&stime, &etime);
132   - //printf("RSDetect %d:%ld fps\n", frameCount, cost_t);
133   -
134   - // 获取智能分析结果
135   - ObjCount = test->getObjectNum();
136   - ObjInfo = new MS_ObjectInfo[ObjCount];
137   - test->getObjectInfo(ObjCount, ObjInfo);
138   - printf("alram:\n");
139   - for (int i = 0; i < ObjCount; i++)
140   - {
141   - if (ObjInfo[i].pbAlarmType[0])
142   - {
143   - switch (ObjInfo[i].pbAlarmType[0])
144   - {
145   - case 1:
146   - printf("obj %d: 进入禁区\n", ObjInfo[i].UniqueID);
147   - break;
148   - case 2:
149   - printf("obj %d: 离开禁区\n", ObjInfo[i].UniqueID);
150   - break;
151   - case 3:
152   - printf("obj %d: 单向越界\n", ObjInfo[i].UniqueID);
153   - break;
154   - case 4:
155   - printf("obj %d: 双向越界\n", ObjInfo[i].UniqueID);
156   - break;
157   - case 5:
158   - printf("obj %d: 徘徊\n", ObjInfo[i].UniqueID);
159   - break;
160   - case 6:
161   - printf("obj %d: 丢包\n", ObjInfo[i].UniqueID);
162   - break;
163   - }
164   - }
165   -
166   - }
167   -
168   - cvRectangle(srcscale, cvPoint(LeftPointX, LeftPointY), cvPoint(RightPointX, RightPointY), cvScalar(0, 0, 0));
169   -
170   - // 轨迹描绘
171   - Trajectory((unsigned char*)(srcscale->imageData), ObjInfo, ObjCount, width, height, widthstep);
172   -
173   - // 目标框描绘
174   - ExternalRectangle((unsigned char*)(srcscale->imageData), ObjInfo, ObjCount, widthstep, numROI);
175   - //画出警报区域
176   - //disp area 1
177   - /*for (int i = 0; i < numROI; i++)
178   - {
179   - cvLine(srcscale, cvPoint(pRegionInfo[i].pROI[0].x, pRegionInfo[i].pROI[0].y),
180   - cvPoint(pRegionInfo[i].pROI[1].x, pRegionInfo[i].pROI[1].y), cvScalar(255, 0, 255), 1);
181   - //获取箭头端点坐标
182   -
183   - if (pRegionInfo[i].AlarmInfo == 3)
184   - {
185   - cv::Point pStart, pEnd;//by zl
186   - pStart.x = pRegionInfo[i].ArrowStartPoint.x;
187   - pStart.y = pRegionInfo[i].ArrowStartPoint.y;
188   - pEnd.x = pRegionInfo[i].ArrowEndPoint.x;
189   - pEnd.y = pRegionInfo[i].ArrowEndPoint.y;
190   - DrawArrow(srcscale, pStart, pEnd, 15, 30);//调用绘制箭头函数
191   - //显示dirPoint
192   - cv::Point pt1;
193   - pt1.x = pRegionInfo[i].dirPoint.x;
194   - pt1.y = pRegionInfo[i].dirPoint.y;
195   - cvLine(srcscale, pt1, pt1, cvScalar(255, 0, 255), 3);
196   - }
197   - //
198   - }*/
199   - ++frameCount;
200   -
201   -
202   - // 图像显示
203   - cvShowImage("3channels", srcscale);
204   -
205   - cvWaitKey(1);
206   -
207   - delete[] ObjInfo;
208   - } //循环处理结束
209   -
210   -
211   - long aver_t = total_t / frameCount;
212   - printf("aver time:%ld us", aver_t);
213   -
214   - delete[] pRegionInfo;
215   - test->RSrelease();
216   - MS1.Destroy();
217   - cvReleaseCapture(&video1);
218   - cvReleaseImage(&srcscale);
219   -}
220   -
221   -
222   -
223   -void imag_ana_1channels()
224   -{
225   - //AlarmInfo 1进入禁区 2离开禁区 3单向越界 4双向越界 5徘徊 6丢包
226   - int numROI = 1;
227   -
228   - debug_time_t stime, etime;
229   -
230   - RegionInfo* pRegionInfo = new RegionInfo[numROI];
231   -
232   - int LeftPointX = 1050;
233   - int LeftPointY = 450;
234   - int RightPointX = 1400;
235   - int RightPointY = 600;
236   -
237   - // 进入禁区
238   - int index = 0;
239   - pRegionInfo[index].AlarmInfo = 1;
240   - pRegionInfo[index].nPointNum = 4;
241   - pRegionInfo[index].pROI[0].x = LeftPointX;
242   - pRegionInfo[index].pROI[0].y = LeftPointY;
243   - pRegionInfo[index].pROI[1].x = RightPointX;
244   - pRegionInfo[index].pROI[1].y = LeftPointY;
245   - pRegionInfo[index].pROI[2].x = RightPointX;
246   - pRegionInfo[index].pROI[2].y = RightPointY;
247   - pRegionInfo[index].pROI[3].x = LeftPointX;
248   - pRegionInfo[index].pROI[3].y = RightPointY;
249   -
250   -
251   - index = 0;
252   - //离开禁区
253   - pRegionInfo[index].AlarmInfo = 2;
254   - pRegionInfo[index].nPointNum = 4;
255   - pRegionInfo[index].pROI[0].x = LeftPointX;
256   - pRegionInfo[index].pROI[0].y = LeftPointY;
257   - pRegionInfo[index].pROI[1].x = RightPointX;
258   - pRegionInfo[index].pROI[1].y = LeftPointY;
259   - pRegionInfo[index].pROI[2].x = RightPointX;
260   - pRegionInfo[index].pROI[2].y = RightPointY;
261   - pRegionInfo[index].pROI[3].x = LeftPointX;
262   - pRegionInfo[index].pROI[3].y = RightPointY;
263   -
264   -
265   -
266   - // 定义
267   - MS_RegionSurveillance MS1;
268   - IRegionSurveillance* test = MS1.GetMS_RS();
269   - if (!test)
270   - {
271   - printf("model initial failed");
272   - exit(0);
273   - }
274   -
275   - CvCapture* video1 = cvCaptureFromFile("../../data/test1.mp4");
276   - // 用opencv函数读取视频的一帧
277   - IplImage * src = cvQueryFrame(video1);
278   - IplImage * srcscale = cvCreateImage(cvSize(src->width, src->height), 8, 3); //用于缩放 当前先不缩放
279   - IplImage * gray = cvCreateImage(cvSize(srcscale->width, srcscale->height), 8, 1);
280   - cvResize(src, srcscale);
281   - cvCvtColor(srcscale, gray, CV_RGB2GRAY);
282   -
283   -
284   - //cv::Mat saveImg = cv::cvarrToMat(src, true);
285   -
286   - //cv::rectangle(saveImg, cv::Rect(1000, 450, 1450-1000, 600-450), cv::Scalar(255, 255, 0), 2);
287   - //cv::imwrite("img.jpg", saveImg);
288   - //cv::imshow("image", saveImg);
289   - //cv::waitKey(0);
290   -
291   -
292   - CvVideoWriter *writer = cvCreateVideoWriter("result_2019_9_23.avi", CV_FOURCC('M', 'J', 'P', 'G'), 30, cvSize(srcscale->width, srcscale->height));
293   -
294   - int frameCount = 0; // 处理的图像序号
295   - MS_ObjectInfo *ObjInfo = NULL; // 结果结构体
296   - int ObjCount;
297   - int error_flag;
298   -
299   - long total_t = 0;
300   -
301   - printf("width = %d height = %d\n", gray->width, gray->height);
302   - // 循环处理视频的每一帧
303   - while (src)
304   - {
305   - src = cvQueryFrame(video1);
306   - if (!src)
307   - break;
308   - cvResize(src, srcscale);
309   - cvCvtColor(srcscale, gray, CV_RGB2GRAY);
310   -
311   - // 如果当前处理的是第一帧,则要进行初始化
312   - if (frameCount == 0)
313   - {
314   - error_flag = test->RSinit(gray->width, gray->height, gray->widthStep,
315   - (unsigned char*)(gray->imageData), gray->nChannels, 1, 0, 10, 1000000);
316   - if (error_flag == 0)
317   - {
318   - cout << "设置有问题!!!" << endl;
319   - return;
320   - }
321   -
322   - error_flag = test->RSRegion(numROI, pRegionInfo, false);
323   - if (error_flag == 0)
324   - {
325   - cout << "区域设置有问题!!!" << endl;
326   - return;
327   - }
328   -
329   - }
330   -
331   - GetTime(&stime);
332   -
333   - // 智能分析
334   - test->RSDetect((unsigned char*)(gray->imageData), pRegionInfo);
335   -
336   - GetTime(&etime);
337   - total_t += CalcTimeDiff(&stime, &etime);
338   - printf("detect time:%ld us\n", CalcTimeDiff(&stime, &etime));
339   -
340   - // 获取智能分析结果
341   - ObjCount = test->getObjectNum();
342   - ObjInfo = new MS_ObjectInfo[ObjCount];
343   - test->getObjectInfo(ObjCount, ObjInfo);
344   -
345   - //报警区域
346   - cvRectangle(srcscale, cvPoint(LeftPointX, LeftPointY), cvPoint(RightPointX, RightPointY), cvScalar(0, 0, 0));
347   -
348   - // 轨迹描绘
349   - Trajectory((unsigned char*)(srcscale->imageData), ObjInfo, ObjCount, srcscale->width, srcscale->height, srcscale->widthStep);
350   -
351   - // 目标框描绘
352   - ExternalRectangle((unsigned char*)(srcscale->imageData), ObjInfo, ObjCount, srcscale->widthStep, numROI);
353   -
354   - for (int i = 0; i < ObjCount; i++)
355   - {
356   - for (int j = 0; j < numROI; j++)
357   - {
358   - if (ObjInfo[i].pbAlarmType[j])
359   - {
360   - switch (ObjInfo[i].pbAlarmType[j])
361   - {
362   - case 1:
363   - printf("obj %d: 进入禁区\n", ObjInfo[i].UniqueID);
364   - break;
365   - case 2:
366   - printf("obj %d: 离开禁区\n", ObjInfo[i].UniqueID);
367   - break;
368   - case 3:
369   - printf("obj %d: 单向越界\n", ObjInfo[i].UniqueID);
370   - break;
371   - case 4:
372   - printf("obj %d: 双向越界\n", ObjInfo[i].UniqueID);
373   - break;
374   - case 5:
375   - printf("obj %d: 徘徊\n", ObjInfo[i].UniqueID);
376   - break;
377   - case 6:
378   - printf("obj %d: 丢包\n", ObjInfo[i].UniqueID);
379   - break;
380   - }
381   - }
382   - }
383   -
384   -
385   - }
386   -
387   - ++frameCount;
388   - cvWriteFrame(writer, srcscale);
389   - // 图像显示
390   - cvShowImage("1channels", srcscale);
391   -
392   - cvWaitKey(1);
393   -
394   - delete[] ObjInfo;
395   - } //循环处理结束
396   -
397   - long aver_t = total_t / frameCount;
398   - printf("aver time:%ld us", aver_t);
399   -
400   - cvReleaseVideoWriter(&writer);
401   - delete[] pRegionInfo;
402   - test->RSrelease();
403   - MS1.Destroy();
404   - cvReleaseCapture(&video1);
405   - cvReleaseImage(&srcscale);
406   - cvReleaseImage(&gray);
407   -
408   -}
409 0 \ No newline at end of file
src/test/demo.cpp
... ... @@ -13,7 +13,6 @@
13 13 #include <opencv2/opencv.hpp>
14 14 #include "left_over_det.h"
15 15 #include <chrono>
16   -#include <boost/thread.hpp>
17 16 #include "RegionAssist.h"
18 17  
19 18 using namespace std;
... ... @@ -23,25 +22,10 @@ void imag_ana_3channels();
23 22 void algorthim_thread1();
24 23 int main()
25 24 {
26   - //int test_count = 10;
27   -
28   - //while (test_count--)
29   - //{
30   - // printf("begin test_count: %d\n", test_count);
31   -
32   - // boost::thread thrd1(boost::bind(algorthim_thread1));
33   - // boost::thread thrd2(boost::bind(algorthim_thread1));
34   - // boost::thread thrd3(boost::bind(algorthim_thread1));
35   - // boost::thread thrd4(boost::bind(algorthim_thread1));
36   -
37   - // thrd1.join();
38   - // thrd2.join();
39   - // thrd3.join();
40   - // thrd4.join();
41   -
42   - // printf("finish\n");
43   - //}
44   - imag_ana_3channels();
  25 + for(int i = 0;i < 10;++i)
  26 + {
  27 + imag_ana_3channels();
  28 + }
45 29  
46 30 system("pause");
47 31 }
... ... @@ -78,63 +62,53 @@ void imag_ana_3channels()
78 62  
79 63 void *tools = nullptr;
80 64 rs_param param;
81   - param.frame_num = 100;
82   - //param.long_side = 1920;
83   - //param.short_side = 1080;
84   - param.scale = 2;
  65 + param.frame_num = 10;
  66 + param.scale = 1;
85 67 param.rect_num = 2;
86 68  
87 69 {
88   - param.rect[0].left_ = 30;
89   - param.rect[0].top_ = 0;
90   - param.rect[0].width_ = 320;
91   - param.rect[0].height_ = 480;
92   -
93   - param.rect[1].left_ = 320;
  70 + param.rect[1].left_ = 30;
94 71 param.rect[1].top_ = 0;
95   - param.rect[1].width_ = 319;
96   - param.rect[1].height_ = 479;
  72 + param.rect[1].width_ = 930;
  73 + param.rect[1].height_ = 1080;
  74 +
  75 + param.rect[0].left_ = 900;
  76 + param.rect[0].top_ = 0;
  77 + param.rect[0].width_ = 960;
  78 + param.rect[0].height_ = 960;
97 79 }
  80 + strcpy(param.auth.url, "192.168.10.4");
  81 + param.auth.port = 8888;
  82 + param.type = PRODUCT_ID;
98 83 if (rs_init(&tools, param) != 0)
99   - cout << "hp_init ailed!" << endl;
  84 + {
  85 + cout << "hp_init ailed!" << endl;
  86 + return;
  87 + }
  88 + else
  89 + {
  90 + printf("hp_init suceed!\n");
  91 + }
  92 +
100 93  
101 94 char imgpath[260];
102   - //CvCapture* video1 = cvCaptureFromFile("D:\\weixin\\ATM遗留物\\20200928\\192.0.0.209_8000_1_4_-1\\20200928_20200928103418_20200928104058_103413.mp4");
103   - //CvCapture* video1 = cvCaptureFromFile("E:\\vpt_pic\\MSRegion.git\\win\\MSRegionDemo\\test1.mp4");
104   - CvCapture* video1 = cvCaptureFromFile("D:\\ruijinVideo\\192.168.1.10_01_2020072911472348.mp4");
  95 + CvCapture* video1 = cvCaptureFromFile("./test.mp4");
105 96 // 用opencv函数读取视频的一帧
106   - IplImage * src = cvQueryFrame(video1);
107   -
108   - //int long_side = (src->width > src->height ? src->width : src->height);
109   - //int short_side = (src->width <= src->height ? src->width : src->height);
110   - //double scale_l = (double)long_side / (double)param.long_side;
111   - //double scale_s = (double)short_side / (double)param.short_side;
112   - //double scale = (scale_l > scale_s ? scale_l : scale_s);
113   - double scale = 1.0;
114   - int width = src->width / scale;
115   - int height = src->height / scale;
116   - //width = 1912;
117   - IplImage * srcscale = cvCreateImage(cvSize(width, height), 8, 3); //用于缩放 当前先不缩放
118   - CvVideoWriter *writer = cvCreateVideoWriter("result_2019_9_23.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25, cvSize(srcscale->width, srcscale->height));
119   - /************************************************/
120   - //int long_side = (srcscale->width > srcscale->height ? srcscale->width : srcscale->height);
121   - //int short_side = (srcscale->width <= srcscale->height ? srcscale->width : srcscale->height);
122   - //double scale_l = (double)long_side / (double)param.long_side;
123   - //double scale_s = (double)short_side / (double)param.short_side;
124   - //double scale = (scale_l > scale_s ? scale_l : scale_s);
125   - //scale = 1.6;
126   -
127   - //int width = srcscale->width / scale;
128   - //int height = srcscale->height / scale;
129   - //CvVideoWriter *writer = cvCreateVideoWriter("result_2019_9_23.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25, cvSize(width, height));
130   - //IplImage * srcscale1 = cvCreateImage(cvSize(width, height), 8, 3); //用于缩放 当前先不缩放
131   - /***********************************************************************/
132   - cvResize(src, srcscale);
  97 + //IplImage * src = cvQueryFrame(video1);
  98 + IplImage *src = cvQueryFrame(video1);
133 99 while (src)
134 100 {
135 101 src = cvQueryFrame(video1);
  102 + //auto frame = cvCloneImage(src);
136 103 if (!src)
137 104 break;
  105 + double scale = 1.0;
  106 + int width = src->width / scale;
  107 + int height = src->height / scale;
  108 + //width = 1912;
  109 + IplImage * srcscale = cvCreateImage(cvSize(width, height), 8, 3); //用于缩放 当前先不缩放
  110 + //CvVideoWriter *writer = cvCreateVideoWriter("result_2019_9_23.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25, cvSize(srcscale->width, srcscale->height));
  111 +
138 112 cvResize(src, srcscale);
139 113 sy_img syimg;
140 114 syimg.set_data(srcscale->width, srcscale->height, srcscale->nChannels, (unsigned char *)srcscale->imageData);
... ... @@ -150,18 +124,9 @@ void imag_ana_3channels()
150 124 }
151 125 }
152 126  
153   -
154   - /********************************************/
155   -
156   -
157   - //cvResize(src, srcscale1);
158   - //ExternalRectangle((unsigned char*)(srcscale1->imageData), srcscale1->width, srcscale1->height, result.obj_infos, result.obj_count, srcscale1->widthStep, 1);
159   -
160   - /*****************************************************/
161 127 ExternalRectangle((unsigned char*)(srcscale->imageData), srcscale->width, srcscale->height, result.obj_infos, result.obj_count, srcscale->widthStep,1);
162 128 CvFont font;
163 129 cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 2, 8);
164   - //cvPutText(srcscale, "1Hello World !", cvPoint(80, 40), &font, cvScalar(255, 0, 0, 1));
165 130 std::string str;
166 131 std::string alarm;
167 132 for (int i = 0; i < result.obj_count; i++)
... ... @@ -211,18 +176,19 @@ void imag_ana_3channels()
211 176  
212 177  
213 178 }
214   - cvWriteFrame(writer, srcscale);
  179 + //cvWriteFrame(writer, srcscale);
215 180  
216 181 // 图像显示
217   - cvShowImage("1channels", srcscale);
218   -
219   - cvWaitKey(1);
  182 + //cvShowImage("1channels", srcscale);
  183 + cvReleaseImage(&srcscale);
  184 + //cvReleaseImage(&frame);
  185 + //cvWaitKey(1);
  186 + //break;
220 187 }
221 188 rs_release(&tools);
222   - //cvReleaseImage(&srcscale1);
223   - //cvReleaseImage(&gray);
  189 + //cvReleaseImage(&src);
224 190 cvReleaseCapture(&video1);
225   - cvReleaseImage(&srcscale);
  191 +
226 192  
227 193 }
228 194  
... ...
src/test/regionassist.h
... ... @@ -5,7 +5,7 @@
5 5 //using namespace cv;
6 6  
7 7 //描绘区域
8   -void DrawRegion(unsigned char* pRGBIn, region_info* pRegionInfo, int numROI, int widthStep);
  8 +//void DrawRegion(unsigned char* pRGBIn, region_info* pRegionInfo, int numROI, int widthStep);
9 9 //画线
10 10 void DrawLine(unsigned char* pRGBIn, int widthStep, const sy_point & p_roi, const sy_point & dir_point);
11 11 //外接矩形描绘
... ...