diff --git a/build/windows/HGWebService/HGWebService.vcxproj b/build/windows/HGWebService/HGWebService.vcxproj index 98b00a9d..05ea1961 100644 --- a/build/windows/HGWebService/HGWebService.vcxproj +++ b/build/windows/HGWebService/HGWebService.vcxproj @@ -24,6 +24,8 @@ + + @@ -41,6 +43,8 @@ + + diff --git a/doc/webservice/新版websdk接口说明.doc b/doc/webservice/新版websdk接口说明.doc index d27aa1f5..421ebc4d 100644 Binary files a/doc/webservice/新版websdk接口说明.doc and b/doc/webservice/新版websdk接口说明.doc differ diff --git a/sdk/webservice/HttpHead.cpp b/sdk/webservice/HttpHead.cpp index 47af99e9..8788f529 100644 --- a/sdk/webservice/HttpHead.cpp +++ b/sdk/webservice/HttpHead.cpp @@ -1,441 +1,438 @@ #include "HttpHead.h" -namespace ver_1 +const unsigned int asciiTableData[256] = { - const unsigned int asciiTableData[256] = - { - 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, - 0x004, 0x104, 0x104, 0x004, 0x104, 0x104, 0x004, 0x004, - 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, - 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, - 0x140, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, - 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, - 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, - 0x459, 0x459, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, - 0x0d0, 0x653, 0x653, 0x653, 0x653, 0x653, 0x653, 0x253, - 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, - 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, - 0x253, 0x253, 0x253, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, - 0x0d0, 0x473, 0x473, 0x473, 0x473, 0x473, 0x473, 0x073, - 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, - 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, - 0x073, 0x073, 0x073, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x004 - /* the upper 128 are all zeroes */ - }; + 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, + 0x004, 0x104, 0x104, 0x004, 0x104, 0x104, 0x004, 0x004, + 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, + 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, + 0x140, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, + 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, + 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, + 0x459, 0x459, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, + 0x0d0, 0x653, 0x653, 0x653, 0x653, 0x653, 0x653, 0x253, + 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, + 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, + 0x253, 0x253, 0x253, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, + 0x0d0, 0x473, 0x473, 0x473, 0x473, 0x473, 0x473, 0x073, + 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, + 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, + 0x073, 0x073, 0x073, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x004 + /* the upper 128 are all zeroes */ +}; - static void TrimString(std::string& str) +static void TrimString(std::string& str) +{ + std::string str1; + bool add1 = false; + std::string::const_iterator iter1; + for (iter1 = str.begin(); iter1 != str.end(); ++iter1) { - std::string str1; - bool add1 = false; - std::string::const_iterator iter1; - for (iter1 = str.begin(); iter1 != str.end(); ++iter1) + int c = (HGByte)(*iter1); + if (!add1) { - int c = (HGByte)(*iter1); - if (!add1) - { - if (!isspace(c)) - { - str1.push_back(c); - add1 = true; - } - } - else + if (!isspace(c)) { str1.push_back(c); + add1 = true; } } - - if (str1.empty()) + else { - str.clear(); - return; + str1.push_back(c); } + } - std::string str2; - bool add2 = false; - std::string::const_reverse_iterator iter2; - for (iter2 = str1.rbegin(); iter2 != str1.rend(); ++iter2) + if (str1.empty()) + { + str.clear(); + return; + } + + std::string str2; + bool add2 = false; + std::string::const_reverse_iterator iter2; + for (iter2 = str1.rbegin(); iter2 != str1.rend(); ++iter2) + { + int c = (HGByte)(*iter2); + if (!add2) { - int c = (HGByte)(*iter2); - if (!add2) - { - if (!isspace(c)) - { - str2.push_back(c); - add2 = true; - } - } - else + if (!isspace(c)) { str2.push_back(c); + add2 = true; } } - - if (str2.empty()) + else { - str.clear(); - return; + str2.push_back(c); } - - str = std::string(str2.rbegin(), str2.rend()); } - HttpHead::HttpHead() + if (str2.empty()) { - + str.clear(); + return; } - HttpHead::~HttpHead() - { + str = std::string(str2.rbegin(), str2.rend()); +} - } +HttpHead::HttpHead() +{ - bool HttpHead::Parse(const std::string& head) - { - AnalysisHead(head, m_requestMethod, m_requestURIPath, m_requestURIQueryInfos, - m_requestURIFragment, m_requestHttpVersion, m_headInfos); - return true; - } +} - void HttpHead::Clear() - { - m_requestMethod.clear(); - m_requestURIPath.clear(); - m_requestURIQueryInfos.clear(); - m_requestURIFragment.clear(); - m_requestHttpVersion.clear(); - m_headInfos.clear(); - } +HttpHead::~HttpHead() +{ - std::string HttpHead::GetRequestMethod() const - { - return m_requestMethod; - } +} - std::string HttpHead::GetRequestURIPath() const - { - return m_requestURIPath; - } +bool HttpHead::Parse(const std::string& head) +{ + AnalysisHead(head, m_requestMethod, m_requestURIPath, m_requestURIQueryInfos, + m_requestURIFragment, m_requestHttpVersion, m_headInfos); + return true; +} - HttpPairs HttpHead::GetRequestURIQueryInfos() const - { - return m_requestURIQueryInfos; - } +void HttpHead::Clear() +{ + m_requestMethod.clear(); + m_requestURIPath.clear(); + m_requestURIQueryInfos.clear(); + m_requestURIFragment.clear(); + m_requestHttpVersion.clear(); + m_headInfos.clear(); +} - std::string HttpHead::GetRequestURIFragment() const - { - return m_requestURIFragment; - } +std::string HttpHead::GetRequestMethod() const +{ + return m_requestMethod; +} - std::string HttpHead::GetRequestHttpVersion() const - { - return m_requestHttpVersion; - } +std::string HttpHead::GetRequestURIPath() const +{ + return m_requestURIPath; +} - HttpPairs HttpHead::GetHeadInfos() const - { - return m_headInfos; - } +HttpPairs HttpHead::GetRequestURIQueryInfos() const +{ + return m_requestURIQueryInfos; +} - int HttpHead::GetContentLength() const +std::string HttpHead::GetRequestURIFragment() const +{ + return m_requestURIFragment; +} + +std::string HttpHead::GetRequestHttpVersion() const +{ + return m_requestHttpVersion; +} + +HttpPairs HttpHead::GetHeadInfos() const +{ + return m_headInfos; +} + +int HttpHead::GetContentLength() const +{ + int len = 0; + for (int i = 0; i < (int)m_headInfos.size(); ++i) { - int len = 0; - for (int i = 0; i < (int)m_headInfos.size(); ++i) - { #if defined(HG_CMP_MSC) - if (0 == _stricmp("Content-Length", m_headInfos[i].first.c_str())) + if (0 == _stricmp("Content-Length", m_headInfos[i].first.c_str())) #else - if (0 == strcasecmp("Content-Length", m_headInfos[i].first.c_str())) + if (0 == strcasecmp("Content-Length", m_headInfos[i].first.c_str())) #endif - { - len = atoi(m_headInfos[i].second.c_str()); - break; - } + { + len = atoi(m_headInfos[i].second.c_str()); + break; } - - return len; } - std::string HttpHead::GetContentType() const + return len; +} + +std::string HttpHead::GetContentType() const +{ + std::string type; + for (int i = 0; i < (int)m_headInfos.size(); ++i) { - std::string type; - for (int i = 0; i < (int)m_headInfos.size(); ++i) - { #if defined(HG_CMP_MSC) - if (0 == _stricmp("Content-Type", m_headInfos[i].first.c_str())) + if (0 == _stricmp("Content-Type", m_headInfos[i].first.c_str())) #else - if (0 == strcasecmp("Content-Type", m_headInfos[i].first.c_str())) + if (0 == strcasecmp("Content-Type", m_headInfos[i].first.c_str())) #endif - { - type = m_headInfos[i].second.c_str(); - break; - } - } - - return type; - } - - std::string HttpHead::GetValue(const HttpPairs& infos, const std::string& key) - { - std::string value; - for (int i = 0; i < (int)infos.size(); ++i) { - if (key == infos[i].first) - { - value = infos[i].second; - break; - } + type = m_headInfos[i].second.c_str(); + break; } - - return value; } - void HttpHead::AnalysisURIQuery(const std::string& query, HttpPairs& queryInfos) - { - std::vector queryList; + return type; +} - char* p = new char[query.size() + 1]; - strcpy(p, query.c_str()); - char* pStr = strtok(p, "&"); +std::string HttpHead::GetValue(const HttpPairs& infos, const std::string& key) +{ + std::string value; + for (int i = 0; i < (int)infos.size(); ++i) + { + if (key == infos[i].first) + { + value = infos[i].second; + break; + } + } + + return value; +} + +void HttpHead::AnalysisURIQuery(const std::string& query, HttpPairs& queryInfos) +{ + std::vector queryList; + + char* p = new char[query.size() + 1]; + strcpy(p, query.c_str()); + char* pStr = strtok(p, "&"); + if (NULL != pStr) + queryList.push_back(pStr); + while (1) + { + pStr = strtok(NULL, "&"); + if (NULL == pStr) + break; + queryList.push_back(pStr); + } + delete[] p; + + queryInfos.clear(); + for (int i = 0; i < (int)queryList.size(); ++i) + { + p = new char[queryList[i].size() + 1]; + strcpy(p, queryList[i].c_str()); + + std::pair pr; + pStr = strtok(p, "="); if (NULL != pStr) - queryList.push_back(pStr); - while (1) - { - pStr = strtok(NULL, "&"); - if (NULL == pStr) - break; - queryList.push_back(pStr); - } + pr.first = AnalyURIString(pStr); + pStr = strtok(NULL, "="); + if (NULL != pStr) + pr.second = AnalyURIString(pStr); + + queryInfos.push_back(pr); delete[] p; + } +} - queryInfos.clear(); - for (int i = 0; i < (int)queryList.size(); ++i) +void HttpHead::AnalysisURI(const std::string& uri, std::string& path, HttpPairs& queryInfos, std::string& fragment) +{ + size_t pathPos = uri.find('/'); + size_t queryPos = uri.find('?'); + size_t fragmentPos = uri.find('#'); + + path.clear(); + if (std::string::npos != pathPos) + { + size_t count = std::string::npos; + if (queryPos != std::string::npos) { - p = new char[queryList[i].size() + 1]; - strcpy(p, queryList[i].c_str()); - - std::pair pr; - pStr = strtok(p, "="); - if (NULL != pStr) - pr.first = AnalyURIString(pStr); - pStr = strtok(NULL, "="); - if (NULL != pStr) - pr.second = AnalyURIString(pStr); - - queryInfos.push_back(pr); - delete[] p; + assert(queryPos > pathPos); + count = queryPos - pathPos; } + else if (fragmentPos != std::string::npos) + { + assert(fragmentPos > pathPos); + count = fragmentPos - pathPos; + } + + path = AnalyURIString(uri.substr(pathPos, count)); } - void HttpHead::AnalysisURI(const std::string& uri, std::string& path, HttpPairs& queryInfos, std::string& fragment) + queryInfos.clear(); + if (std::string::npos != queryPos) { - size_t pathPos = uri.find('/'); - size_t queryPos = uri.find('?'); - size_t fragmentPos = uri.find('#'); - - path.clear(); - if (std::string::npos != pathPos) + size_t count = std::string::npos; + if (fragmentPos != std::string::npos) { - size_t count = std::string::npos; - if (queryPos != std::string::npos) - { - assert(queryPos > pathPos); - count = queryPos - pathPos; - } - else if (fragmentPos != std::string::npos) - { - assert(fragmentPos > pathPos); - count = fragmentPos - pathPos; - } - - path = AnalyURIString(uri.substr(pathPos, count)); + assert(fragmentPos > queryPos); + count = fragmentPos - queryPos; } - queryInfos.clear(); - if (std::string::npos != queryPos) - { - size_t count = std::string::npos; - if (fragmentPos != std::string::npos) - { - assert(fragmentPos > queryPos); - count = fragmentPos - queryPos; - } - - std::string query = uri.substr(queryPos + 1, count - 1); - AnalysisURIQuery(query, queryInfos); - } - - fragment.clear(); - if (std::string::npos != fragmentPos) - { - fragment = AnalyURIString(uri.substr(fragmentPos + 1)); - } + std::string query = uri.substr(queryPos + 1, count - 1); + AnalysisURIQuery(query, queryInfos); } - void HttpHead::AnalysisHead(const std::string& head, std::string& requestMethod, std::string& requestURIPath, - HttpPairs& requestURIQueryInfos, std::string& requestURIFragment, std::string& httpVersion, HttpPairs& headInfos) + fragment.clear(); + if (std::string::npos != fragmentPos) { - requestMethod.clear(); - requestURIPath.clear(); - requestURIQueryInfos.clear(); - requestURIFragment.clear(); - httpVersion.clear(); - headInfos.clear(); + fragment = AnalyURIString(uri.substr(fragmentPos + 1)); + } +} - std::vector headList; +void HttpHead::AnalysisHead(const std::string& head, std::string& requestMethod, std::string& requestURIPath, + HttpPairs& requestURIQueryInfos, std::string& requestURIFragment, std::string& httpVersion, HttpPairs& headInfos) +{ + requestMethod.clear(); + requestURIPath.clear(); + requestURIQueryInfos.clear(); + requestURIFragment.clear(); + httpVersion.clear(); + headInfos.clear(); - char* p = new char[head.size() + 1]; - strcpy(p, head.c_str()); - char* pStr = strtok(p, "\r\n"); + std::vector headList; + + char* p = new char[head.size() + 1]; + strcpy(p, head.c_str()); + char* pStr = strtok(p, "\r\n"); + if (NULL != pStr) + headList.push_back(pStr); + while (1) + { + pStr = strtok(NULL, "\r\n"); + if (NULL == pStr) + break; + headList.push_back(pStr); + } + delete[] p; + + if (headList.size() < 1) + { + return; + } + + std::string requestURI; + + // 解析请求行 + p = new char[headList[0].size() + 1]; + strcpy(p, headList[0].c_str()); + pStr = strtok(p, " "); + if (NULL != pStr) + requestMethod = pStr; + pStr = strtok(NULL, " "); + if (NULL != pStr) + requestURI = pStr; + pStr = strtok(NULL, " "); + if (NULL != pStr) + httpVersion = pStr; + delete[] p; + + // 解析URI + AnalysisURI(requestURI, requestURIPath, requestURIQueryInfos, requestURIFragment); + + // 解析请求头 + for (int i = 1; i < (int)headList.size(); ++i) + { + p = new char[headList[i].size() + 1]; + strcpy(p, headList[i].c_str()); + + std::pair pr; + pStr = strtok(p, ":"); if (NULL != pStr) - headList.push_back(pStr); - while (1) - { - pStr = strtok(NULL, "\r\n"); - if (NULL == pStr) - break; - headList.push_back(pStr); - } + pr.first = pStr; + pStr = strtok(NULL, ":"); + if (NULL != pStr) + pr.second = pStr; + + TrimString(pr.first); + TrimString(pr.second); + headInfos.push_back(pr); + delete[] p; - - if (headList.size() < 1) - { - return; - } - - std::string requestURI; - - // 解析请求行 - p = new char[headList[0].size() + 1]; - strcpy(p, headList[0].c_str()); - pStr = strtok(p, " "); - if (NULL != pStr) - requestMethod = pStr; - pStr = strtok(NULL, " "); - if (NULL != pStr) - requestURI = pStr; - pStr = strtok(NULL, " "); - if (NULL != pStr) - httpVersion = pStr; - delete[] p; - - // 解析URI - AnalysisURI(requestURI, requestURIPath, requestURIQueryInfos, requestURIFragment); - - // 解析请求头 - for (int i = 1; i < (int)headList.size(); ++i) - { - p = new char[headList[i].size() + 1]; - strcpy(p, headList[i].c_str()); - - std::pair pr; - pStr = strtok(p, ":"); - if (NULL != pStr) - pr.first = pStr; - pStr = strtok(NULL, ":"); - if (NULL != pStr) - pr.second = pStr; - - TrimString(pr.first); - TrimString(pr.second); - headInfos.push_back(pr); - - delete[] p; - } } +} - /*判断ascii码是否是数字0-9*/ - static bool asciiIsDigit(char c) - { - /*字符的ascii码&8 结果为0-127,则是数字*/ - return asciiTableData[(unsigned char)c & (1 << 3)]; - } +/*判断ascii码是否是数字0-9*/ +static bool asciiIsDigit(char c) +{ + /*字符的ascii码&8 结果为0-127,则是数字*/ + return asciiTableData[(unsigned char)c & (1 << 3)]; +} - static int asciiDigitValue(char c) - { - if (asciiIsDigit(c)) - return c - '0'; +static int asciiDigitValue(char c) +{ + if (asciiIsDigit(c)) + return c - '0'; + return -1; +} + +static int asciiXdigitValue(char c) +{ + //printf("-->%c\n",c); + if (c >= 'A' && c <= 'F') + return c - 'A' + 10;//(A B C D E F)->(10 11 12 13 14 15) + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + + return asciiDigitValue(c);//('0'...'9')->(0...9) +} + +static int unescapeCharacter(const char* scanner) +{ + int first = asciiXdigitValue(scanner[0]); + if (first < 0) return -1; - } - static int asciiXdigitValue(char c) + int second = asciiXdigitValue(scanner[1]); + if (second < 0) + return -1; + + return (first << 4) | second; //== (first*16 | second) == (first*16 + second) +} + +static char* unescapeUriString(const char* uriString, bool asciiEscape) +{ + if (NULL == uriString) + return NULL; + + int strLen = (int)strlen(uriString); + char* result = (char*)malloc(strLen + 1);//可推测解码后的长度<=原长度 + char* out = result; + + const char* in, * end; + for (in = uriString, end = in + strLen; in < end; ++in) { - //printf("-->%c\n",c); - if (c >= 'A' && c <= 'F') - return c - 'A' + 10;//(A B C D E F)->(10 11 12 13 14 15) - if (c >= 'a' && c <= 'f') - return c - 'a' + 10; + int c = *in; - return asciiDigitValue(c);//('0'...'9')->(0...9) - } - - static int unescapeCharacter(const char* scanner) - { - int first = asciiXdigitValue(scanner[0]); - if (first < 0) - return -1; - - int second = asciiXdigitValue(scanner[1]); - if (second < 0) - return -1; - - return (first << 4) | second; //== (first*16 | second) == (first*16 + second) - } - - static char* unescapeUriString(const char* uriString, bool asciiEscape) - { - if (NULL == uriString) - return NULL; - - int strLen = (int)strlen(uriString); - char* result = (char*)malloc(strLen + 1);//可推测解码后的长度<=原长度 - char* out = result; - - const char* in, * end; - for (in = uriString, end = in + strLen; in < end; ++in) + //遇到了'%'才去解析 + if ('%' == c) { - int c = *in; + if (in + 3 > end) + break; + //获取%后2个字符的解码值 + c = unescapeCharacter(in + 1); + if (c <= 0) + break; - //遇到了'%'才去解析 - if ('%' == c) - { - if (in + 3 > end) - break; - //获取%后2个字符的解码值 - c = unescapeCharacter(in + 1); - if (c <= 0) - break; + if (asciiEscape && c <= 0x7F) + break; - if (asciiEscape && c <= 0x7F) - break; - - in += 2;//一般的格式为%后加两个ascii码字符 - } - - *out++ = c;//存储转义结果 + in += 2;//一般的格式为%后加两个ascii码字符 } - *out = '\0'; - - if (in != end) - { - free(result); - return NULL; - } - - return result; + *out++ = c;//存储转义结果 } - std::string HttpHead::AnalyURIString(const std::string& str) + *out = '\0'; + + if (in != end) { - std::string ret; - char* decodeStr = unescapeUriString(str.c_str(), false); - if (NULL != decodeStr) - { - ret = decodeStr; - free(decodeStr); - } - - return ret; + free(result); + return NULL; } + + return result; +} + +std::string HttpHead::AnalyURIString(const std::string& str) +{ + std::string ret; + char* decodeStr = unescapeUriString(str.c_str(), false); + if (NULL != decodeStr) + { + ret = decodeStr; + free(decodeStr); + } + + return ret; } \ No newline at end of file diff --git a/sdk/webservice/HttpHead.h b/sdk/webservice/HttpHead.h index a756a10b..4f6d4062 100644 --- a/sdk/webservice/HttpHead.h +++ b/sdk/webservice/HttpHead.h @@ -5,44 +5,41 @@ #include #include -namespace ver_1 +typedef std::pair HttpPair; +typedef std::vector HttpPairs; + +class HttpHead { - typedef std::pair HttpPair; - typedef std::vector HttpPairs; +public: + HttpHead(); + ~HttpHead(); - class HttpHead - { - public: - HttpHead(); - ~HttpHead(); + bool Parse(const std::string& head); + void Clear(); - bool Parse(const std::string& head); - void Clear(); + std::string GetRequestMethod() const; + std::string GetRequestURIPath() const; + HttpPairs GetRequestURIQueryInfos() const; + std::string GetRequestURIFragment() const; + std::string GetRequestHttpVersion() const; + HttpPairs GetHeadInfos() const; + int GetContentLength() const; + std::string GetContentType() const; - std::string GetRequestMethod() const; - std::string GetRequestURIPath() const; - HttpPairs GetRequestURIQueryInfos() const; - std::string GetRequestURIFragment() const; - std::string GetRequestHttpVersion() const; - HttpPairs GetHeadInfos() const; - int GetContentLength() const; - std::string GetContentType() const; + static std::string GetValue(const HttpPairs& infos, const std::string& key); + static void AnalysisURIQuery(const std::string& query, HttpPairs& queryInfos); + static void AnalysisURI(const std::string& uri, std::string& path, HttpPairs& queryInfos, std::string& fragment); + static void AnalysisHead(const std::string& head, std::string& requestMethod, std::string& requestURIPath, + HttpPairs& requestURIQueryInfos, std::string& requestURIFragment, std::string& httpVersion, HttpPairs& headInfos); - static std::string GetValue(const HttpPairs& infos, const std::string& key); - static void AnalysisURIQuery(const std::string& query, HttpPairs& queryInfos); - static void AnalysisURI(const std::string& uri, std::string& path, HttpPairs& queryInfos, std::string& fragment); - static void AnalysisHead(const std::string& head, std::string& requestMethod, std::string& requestURIPath, - HttpPairs& requestURIQueryInfos, std::string& requestURIFragment, std::string& httpVersion, HttpPairs& headInfos); +private: + static std::string AnalyURIString(const std::string& str); - private: - static std::string AnalyURIString(const std::string& str); - - private: - std::string m_requestMethod; - std::string m_requestURIPath; - HttpPairs m_requestURIQueryInfos; - std::string m_requestURIFragment; - std::string m_requestHttpVersion; - HttpPairs m_headInfos; - }; -} \ No newline at end of file +private: + std::string m_requestMethod; + std::string m_requestURIPath; + HttpPairs m_requestURIQueryInfos; + std::string m_requestURIFragment; + std::string m_requestHttpVersion; + HttpPairs m_headInfos; +}; \ No newline at end of file diff --git a/sdk/webservice/HttpServer.cpp b/sdk/webservice/HttpServer.cpp index 3856fd55..7ae0b806 100644 --- a/sdk/webservice/HttpServer.cpp +++ b/sdk/webservice/HttpServer.cpp @@ -4,10 +4,10 @@ namespace ver_1 { - HttpServer::HttpServer(HGMsgPump msgPump, Manager* manager) - : WebServer(msgPump, manager) + HttpServer::HttpServer(HGMsgPump msgPump, ManagerV1* manager) + : WebServer(msgPump) { - + m_manager = manager; } HttpServer::~HttpServer() @@ -15,6 +15,11 @@ namespace ver_1 } + ManagerV1* HttpServer::GetManger() + { + return m_manager; + } + void HttpServer::Connect(const ConnectParam* param) { assert(NULL != param && this == param->svr); diff --git a/sdk/webservice/HttpServer.h b/sdk/webservice/HttpServer.h index aede1bf1..8bce3a6c 100644 --- a/sdk/webservice/HttpServer.h +++ b/sdk/webservice/HttpServer.h @@ -5,15 +5,17 @@ namespace ver_1 { - class Manager; - class HttpServer : public WebServer { public: - HttpServer(HGMsgPump msgPump, Manager* manager); + HttpServer(HGMsgPump msgPump, ManagerV1* manager); virtual ~HttpServer(); + ManagerV1* GetManger(); void Connect(const ConnectParam* param); void Command(const HttpCmdParam* param); + + private: + ManagerV1* m_manager; }; } \ No newline at end of file diff --git a/sdk/webservice/HttpUser.cpp b/sdk/webservice/HttpUser.cpp index 67a27abe..9561b224 100644 --- a/sdk/webservice/HttpUser.cpp +++ b/sdk/webservice/HttpUser.cpp @@ -1,6 +1,6 @@ #include "HttpUser.h" -#include "WebServer.h" -#include "Manager.h" +#include "HttpServer.h" +#include "ManagerV1.h" #include "base/HGInfo.h" #include "cJSON.h" @@ -103,9 +103,9 @@ namespace ver_1 } #if defined(HG_CMP_MSC) - HttpUser::HttpUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, SOCKET sockConn) + HttpUser::HttpUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, SOCKET sockConn) #else - HttpUser::HttpUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, int sockConn) + HttpUser::HttpUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, int sockConn) #endif : WebUser(server, id, ip, port, sockConn) { @@ -117,6 +117,11 @@ namespace ver_1 } + ManagerV1* HttpUser::GetManager() + { + return ((HttpServer*)m_server)->GetManger(); + } + void HttpUser::HandleCmd(const HttpCmdParam* param) { assert(NULL != param && m_id == param->usrId); diff --git a/sdk/webservice/HttpUser.h b/sdk/webservice/HttpUser.h index 87527ac8..5a559bb7 100644 --- a/sdk/webservice/HttpUser.h +++ b/sdk/webservice/HttpUser.h @@ -5,18 +5,17 @@ namespace ver_1 { - class WebServer; - class HttpUser : public WebUser { public: #if defined(HG_CMP_MSC) - HttpUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, SOCKET sockConn); + HttpUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, SOCKET sockConn); #else - HttpUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, int sockConn); + HttpUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, int sockConn); #endif virtual ~HttpUser(); + ManagerV1* GetManager(); void HandleCmd(const HttpCmdParam* param); protected: diff --git a/sdk/webservice/Manager.cpp b/sdk/webservice/Manager.cpp index d547ec43..25b40b36 100644 --- a/sdk/webservice/Manager.cpp +++ b/sdk/webservice/Manager.cpp @@ -1,2082 +1,11 @@ #include "Manager.h" -#include "base/HGBuffer.h" -#include "base/HGBase64.h" -#include "base/HGUtility.h" -#include "base/HGInfo.h" -#include "imgfmt/HGJpeg.h" -#include "imgfmt/HGOfd.h" -#include "imgfmt/HGPdf.h" -#include "imgfmt/HGTiff.h" -#include "imgfmt/HGImgFmt.h" -#include "HGString.h" -extern "C" + +Manager::Manager(HGMsgPump msgPump) { -#include "zip.h" -}; -#include -#include -#include - -namespace ver_1 -{ - DevParam::DevParam() - { - Reset(); - } - - DevParam::~DevParam() - { - - } - - void DevParam::Reset() - { - autofeeder = true; - pixel = 1; - white = false; - discardBlankThre = 5; - single = false; - format = "jpg"; - resolution = 200; - orentation = 0; - paperType = "Auto"; - splitImage = 0; - noiseDetachEnable = true; - noiseDetach = 15; - - uploadMode = 2; - ftpPath = "/images"; - ftpPort = 21; - ftpMode = 2; - } - - void DevParam::Load(const std::string& cfgPath) - { - HGInt intValue; - HGChar strValue[256]; - - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "device", "", strValue, 256); - device = strValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "autofeeder", 1, &intValue); - autofeeder = (bool)intValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "pixel", 1, &intValue); - pixel = intValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "white", 0, &intValue); - white = (bool)intValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "discardBlankThre", 5, &intValue); - discardBlankThre = intValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "single", 0, &intValue); - single = (bool)intValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "format", "jpg", strValue, 256); - format = strValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "resolution", 200, &intValue); - resolution = intValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "orentation", 0, &intValue); - orentation = intValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "paperType", "Auto", strValue, 256); - paperType = strValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "splitImage", 0, &intValue); - splitImage = intValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "noiseDetachEnable”", 1, &intValue); - noiseDetachEnable = (bool)intValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "noiseDetach", 15, &intValue); - noiseDetach = intValue; - - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "uploadMode", 2, &intValue); - uploadMode = intValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "httpUrl", "", strValue, 256); - httpUrl = strValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "fileName", "", strValue, 256); - fileName = strValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "httpMethod", "", strValue, 256); - httpMethod = strValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "header", "", strValue, 256); - header = strValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "param", "", strValue, 256); - param = strValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "ftpUrl", "", strValue, 256); - ftpUrl = strValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "ftpPath", "", strValue, 256); - ftpPath = strValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "ftpUser", "", strValue, 256); - ftpUser = strValue; - HGBase_GetProfileString(cfgPath.c_str(), "devParam", "ftpPassword", "", strValue, 256); - ftpPassword = strValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "ftpPort", 21, &intValue); - ftpPort = intValue; - HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "ftpMode", 2, &intValue); - ftpMode = intValue; - } - - void DevParam::Save(const std::string& cfgPath) - { - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "device", device.c_str()); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "autofeeder", autofeeder); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "pixel", pixel); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "white", white); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "discardBlankThre", discardBlankThre); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "single", single); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "format", format.c_str()); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "resolution", resolution); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "orentation", orentation); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "paperType", paperType.c_str()); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "splitImage", splitImage); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "noiseDetachEnable", noiseDetachEnable); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "noiseDetach", noiseDetach); - - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "uploadMode", uploadMode); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "httpUrl", httpUrl.c_str()); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "fileName", fileName.c_str()); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "httpMethod", httpMethod.c_str()); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "header", header.c_str()); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "param", param.c_str()); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "ftpUrl", ftpUrl.c_str()); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "ftpPath", ftpPath.c_str()); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "ftpUser", ftpUser.c_str()); - HGBase_SetProfileString(cfgPath.c_str(), "devParam", "ftpPassword", ftpPassword.c_str()); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "ftpPort", ftpPort); - HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "ftpMode", ftpMode); - } - - Manager::Manager(HGMsgPump msgPump) - { - m_msgPump = msgPump; - HGBase_CreateLock(&m_lock); - m_devName.clear(); - m_devHandle = NULL; - m_scanEvent = NULL; - m_scanParam = NULL; - - m_scanInsertImgName.clear(); - m_scanIsInsert = false; - m_scanning = false; - - SANE_Int version_code = 0; - SANE_Status status = sane_init_ex(&version_code, sane_ex_callback, this); - assert(SANE_STATUS_GOOD == status); - } - - Manager::~Manager() - { - if (NULL != m_devHandle) - { - StopScan(); - - m_devParam.Reset(); - sane_close(m_devHandle); - m_devHandle = NULL; - m_devName.clear(); - } - - sane_exit(); - - HGBase_DestroyLock(m_lock); - m_lock = NULL; - } - - void Manager::OpenDev(const OpenDevParam* param) - { - assert(NULL != param && this == param->mgr); - - if (!m_devName.empty() || NULL != m_devHandle) - { - return; - } - - SANE_Handle devHandle = NULL; - SANE_Status status = sane_open(param->devName.c_str(), &devHandle); - if (SANE_STATUS_GOOD == status) - { - assert(NULL != devHandle); - - m_devName = param->devName; - m_devHandle = devHandle; - - std::string filePath = GetFilePath(m_devName); - std::string cfgPath = filePath + "config.ini"; - m_devParam.Load(cfgPath); - SetDevParam(m_devName, m_devParam); - } - } - - void Manager::CloseDev(const CloseDevParam* param) - { - assert(NULL != param && this == param->mgr); - - if (m_devName.empty() || NULL == m_devHandle || m_devName != param->devName) - { - return; - } - - assert(NULL != m_devHandle); - - StopScan(); - - m_devParam.Reset(); - sane_close(m_devHandle); - m_devHandle = NULL; - m_devName.clear(); - } - - void Manager::ScanFinish(const ScanFinishParam* param) - { - assert(NULL != param && this == param->mgr); - - m_scanInsertImgName.clear(); - m_scanIsInsert = false; - m_scanning = false; - } - - void Manager::SetScanEvent(ScanEvent event, void* param) - { - assert(NULL != event && NULL != param); - - HGBase_EnterLock(m_lock); - m_scanEvent = event; - m_scanParam = param; - HGBase_LeaveLock(m_lock); - } - - void Manager::ResetScanEvent() - { - HGBase_EnterLock(m_lock); - m_scanEvent = NULL; - m_scanParam = NULL; - HGBase_LeaveLock(m_lock); - } - - bool Manager::Scan(const std::string& insertImgName, bool isInsert) - { - if (m_scanning) - { - return false; - } - - bool ret = false; - if (NULL != m_devHandle) - { - m_scanInsertImgName = insertImgName; - m_scanIsInsert = isInsert; - if (SANE_STATUS_GOOD == sane_start(m_devHandle)) - { - m_scanning = true; - ret = true; - } - else - { - m_scanInsertImgName.clear(); - m_scanIsInsert = false; - } - } - - return ret; - } - - bool Manager::StopScan() - { - if (m_scanning) - { - assert(NULL != m_devHandle); - sane_cancel(m_devHandle); - } - - return true; - } - - bool Manager::GetCurDevId(std::string& devId) - { - devId.clear(); - if (m_scanning) - { - return false; - } - - devId = m_devName; - return true; - } - - bool Manager::GetDevNames(std::vector& devNameList) - { - devNameList.clear(); - if (m_scanning) - { - return false; - } - - const SANE_Device** device_list; - if (SANE_STATUS_GOOD == sane_get_devices(&device_list, SANE_TRUE)) - { - const SANE_Device** p; - for (p = device_list; *p != NULL; ++p) - { - devNameList.push_back((*p)->name); - } - } - - return true; - } - - bool Manager::GetImageByDevId(const std::string& devId, std::vector& imgNameList, - std::vector& imgBase64List) - { - imgNameList.clear(); - imgBase64List.clear(); - if (m_scanning) - { - return false; - } - - std::string filePath = GetFilePath(devId); - std::vector fileNameList = GetFileNameList(devId); - HGBase_WriteInfo(HGBASE_INFOTYPE_DEBUG, "filePath=%s", filePath.c_str()); - - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - std::string fileName = filePath + fileNameList[i]; - - HGImage img = NULL; - HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); - if (NULL != img) - { - std::string imgBase64 = "data:image/jpeg;base64,"; - imgBase64 += GetBase64(img); - - imgNameList.push_back(fileNameList[i]); - imgBase64List.push_back(imgBase64); - HGBase_DestroyImage(img); - } - } - - SaveFileNameList(devId, imgNameList); - return true; - } - - bool Manager::GetDevParam(const std::string& devId, DevParam& devParam) - { - devParam.Reset(); - if (m_scanning) - { - return false; - } - - bool ret = false; - if (NULL != m_devHandle) - { - m_devParam.device = m_devName; - - // 从设备获取到m_devParam - - SANE_Int num_dev_options = 0; - sane_control_option(m_devHandle, 0, SANE_ACTION_GET_VALUE, &num_dev_options, NULL); - for (int i = 1; i < num_dev_options; ++i) - { - const SANE_Option_Descriptor* desp = sane_get_option_descriptor(m_devHandle, i); - if (NULL == desp) - continue; - - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "title=%s", Utf8ToStdString(desp->title).c_str()); - - if (SANE_TYPE_BOOL == desp->type) - { - SANE_Bool value = 0; - sane_control_option(m_devHandle, i, SANE_ACTION_GET_VALUE, &value, NULL); - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=BOOL, value=%s", value ? "TRUE" : "FALSE"); - - if (0 == strcmp(desp->title, OPTION_TITLE_TXCF)) - m_devParam.splitImage = value ? 1 : 0; - else if (0 == strcmp(desp->title, OPTION_TITLE_HBTXZDYH)) - m_devParam.noiseDetachEnable = (bool)value; - } - else if (SANE_TYPE_INT == desp->type) - { - SANE_Int value = 0; - sane_control_option(m_devHandle, i, SANE_ACTION_GET_VALUE, &value, NULL); - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=INT, value=%d", value); - - if (0 == strcmp(desp->title, OPTION_TITLE_TGKBYLMD)) - m_devParam.discardBlankThre = value; - else if (0 == strcmp(desp->title, OPTION_TITLE_FBL)) - m_devParam.resolution = value; - } - else if (SANE_TYPE_FIXED == desp->type) - { - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=FIXED"); - } - else if (SANE_TYPE_STRING == desp->type) - { - char value[256] = {0}; - sane_control_option(m_devHandle, i, SANE_ACTION_GET_VALUE, value, NULL); - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=STRING, value=%s", Utf8ToStdString(value).c_str()); - - if (0 == strcmp(OPTION_TITLE_SMZS, desp->title) && 0 == strcmp(OPTION_VALUE_SMZS_LXSM, value)) - m_devParam.autofeeder = true; - else if (0 == strcmp(OPTION_TITLE_SMZS, desp->title) && 0 == strcmp(OPTION_VALUE_SMZS_SMZDZS, value)) - m_devParam.autofeeder = false; - else if (0 == strcmp(OPTION_TITLE_YSMS, desp->title) && (0 == strcmp(OPTION_VALUE_YSMS_24WCS, value) - || 0 == strcmp(OPTION_VALUE_YSMS_YSZDSB, value))) - m_devParam.pixel = 2; - else if (0 == strcmp(OPTION_TITLE_YSMS, desp->title) && 0 == strcmp(OPTION_VALUE_YSMS_256JHD, value)) - m_devParam.pixel = 1; - else if (0 == strcmp(OPTION_TITLE_YSMS, desp->title) && 0 == strcmp(OPTION_VALUE_YSMS_HB, value)) - m_devParam.pixel = 0; - else if (0 == strcmp(OPTION_TITLE_SMYM, desp->title) && 0 == strcmp(OPTION_VALUE_SMYM_SM, value)) - { - m_devParam.white = false; - m_devParam.single = false; - } - else if (0 == strcmp(OPTION_TITLE_SMYM, desp->title) && 0 == strcmp(OPTION_VALUE_SMYM_DM, value)) - { - m_devParam.white = false; - m_devParam.single = true; - } - else if (0 == strcmp(OPTION_TITLE_SMYM, desp->title) && (0 == strcmp(OPTION_VALUE_SMYM_TGKBYTY, value) - || 0 == strcmp(OPTION_VALUE_SMYM_TGKBYFPZ, value))) - { - m_devParam.white = true; - m_devParam.single = false; - } - else if (0 == strcmp(OPTION_TITLE_WGFX, desp->title) && 0 == strcmp(OPTION_VALUE_WGFX_0, value)) - m_devParam.orentation = 0; - else if (0 == strcmp(OPTION_TITLE_WGFX, desp->title) && 0 == strcmp(OPTION_VALUE_WGFX_90, value)) - m_devParam.orentation = 90; - else if (0 == strcmp(OPTION_TITLE_WGFX, desp->title) && 0 == strcmp(OPTION_VALUE_WGFX_180, value)) - m_devParam.orentation = 180; - else if (0 == strcmp(OPTION_TITLE_WGFX, desp->title) && 0 == strcmp(OPTION_VALUE_WGFX__90, value)) - m_devParam.orentation = 270; - else if (0 == strcmp(OPTION_TITLE_ZZCC, desp->title) && 0 == strcmp(OPTION_VALUE_ZZCC_PPYSCC, value)) - m_devParam.paperType = "Auto"; - else if (0 == strcmp(OPTION_TITLE_ZZCC, desp->title) && 0 == strcmp(OPTION_VALUE_ZZCC_A3, value)) - m_devParam.paperType = "A3"; - else if (0 == strcmp(OPTION_TITLE_ZZCC, desp->title) && 0 == strcmp(OPTION_VALUE_ZZCC_A4, value)) - m_devParam.paperType = "A4"; - } - else if (SANE_TYPE_BUTTON == desp->type) - { - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=BUTTON"); - } - else if (SANE_TYPE_GROUP == desp->type) - { - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=GROUP"); - } - } - - std::string filePath = GetFilePath(m_devName); - std::string cfgPath = filePath + "config.ini"; - m_devParam.Save(cfgPath); - ret = true; - } - - devParam = m_devParam; - return ret; - } - - bool Manager::SetDevParam(const std::string& devId, const DevParam& devParam) - { - if (m_scanning) - { - return false; - } - - m_devParam = devParam; - - std::string filePath = GetFilePath(m_devName); - std::string cfgPath = filePath + "config.ini"; - m_devParam.Save(cfgPath); - - bool ret = false; - if (NULL != m_devHandle) - { - // 设置m_devParam到设备 - - SANE_Int num_dev_options = 0; - sane_control_option(m_devHandle, 0, SANE_ACTION_GET_VALUE, &num_dev_options, NULL); - for (int i = 1; i < num_dev_options; ++i) - { - const SANE_Option_Descriptor* desp = sane_get_option_descriptor(m_devHandle, i); - if (NULL == desp) - continue; - - if (SANE_TYPE_BOOL == desp->type) - { - if (0 == strcmp(desp->title, OPTION_TITLE_TXCF)) - { - SANE_Bool value = SANE_FALSE; - if (0 != m_devParam.splitImage) - value = SANE_TRUE; - sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, &value, NULL); - } - else if (0 == strcmp(desp->title, OPTION_TITLE_HBTXZDYH)) - { - SANE_Bool value = SANE_FALSE; - if (m_devParam.noiseDetachEnable) - value = SANE_TRUE; - sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, &value, NULL); - } - } - else if (SANE_TYPE_INT == desp->type) - { - if (0 == strcmp(desp->title, OPTION_TITLE_TGKBYLMD)) - { - SANE_Int value = m_devParam.discardBlankThre; - sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, &value, NULL); - } - else if (0 == strcmp(desp->title, OPTION_TITLE_FBL)) - { - SANE_Int value = m_devParam.resolution; - sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, &value, NULL); - } - else if (0 == strcmp(desp->title, OPTION_TITLE_SMSL)) - { - SANE_Int value = 1; - sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, &value, NULL); - } - } - else if (SANE_TYPE_FIXED == desp->type) - { - - } - else if (SANE_TYPE_STRING == desp->type) - { - if (0 == strcmp(OPTION_TITLE_SMZS, desp->title)) - { - char value[256] = { 0 }; - strcpy(value, OPTION_VALUE_SMZS_LXSM); - if (!m_devParam.autofeeder) - strcpy(value, OPTION_VALUE_SMZS_SMZDZS); - sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, (void*)value, NULL); - } - else if (0 == strcmp(OPTION_TITLE_YSMS, desp->title)) - { - char value[256] = { 0 }; - strcpy(value, OPTION_VALUE_YSMS_24WCS); - if (1 == m_devParam.pixel) - strcpy(value, OPTION_VALUE_YSMS_256JHD); - else if (0 == m_devParam.pixel) - strcpy(value, OPTION_VALUE_YSMS_HB); - sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, (void *)value, NULL); - } - else if (0 == strcmp(OPTION_TITLE_SMYM, desp->title)) - { - char value[256] = { 0 }; - strcpy(value, OPTION_VALUE_SMYM_SM); - if (m_devParam.single) - strcpy(value, OPTION_VALUE_SMYM_DM); - else if (m_devParam.white) - strcpy(value, OPTION_VALUE_SMYM_TGKBYTY); - sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, (void*)value, NULL); - } - else if (0 == strcmp(OPTION_TITLE_WGFX, desp->title)) - { - char value[256] = { 0 }; - strcpy(value, OPTION_VALUE_WGFX_0); - if (90 == m_devParam.orentation) - strcpy(value, OPTION_VALUE_WGFX_90); - else if (180 == m_devParam.orentation) - strcpy(value, OPTION_VALUE_WGFX_180); - else if (270 == m_devParam.orentation) - strcpy(value, OPTION_VALUE_WGFX__90); - sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, (void*)value, NULL); - } - else if (0 == strcmp(OPTION_TITLE_ZZCC, desp->title)) - { - char value[256] = { 0 }; - strcpy(value, OPTION_VALUE_ZZCC_PPYSCC); - if ("A3" == m_devParam.paperType) - strcpy(value, OPTION_VALUE_ZZCC_A3); - else if ("A4" == m_devParam.paperType) - strcpy(value, OPTION_VALUE_ZZCC_A4); - sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, (void*)value, NULL); - } - } - else if (SANE_TYPE_BUTTON == desp->type) - { - - } - else if (SANE_TYPE_GROUP == desp->type) - { - - } - } - - ret = true; - } - - return ret; - } - - bool Manager::ExportOfd(const std::string& devId, bool isAuto, std::string& imgBase64) - { - imgBase64.clear(); - if (m_scanning) - { - return false; - } - - HGByte* data = NULL; - HGUInt size = 0; - ExportOfdFile(devId, isAuto, &data, &size); - if (NULL != data) - { - imgBase64 = GetBase64(data, size); - delete[] data; - } - - return !imgBase64.empty(); - } - - bool Manager::ExportOfdFile(const std::string& devId, bool isAuto, const std::string& fileName) - { - std::string filePath = GetFilePath(devId); - std::vector fileNameList = GetFileNameList(devId); - if (fileNameList.empty()) - { - return false; - } - - HGOfdImageWriter writer = NULL; - HGImgFmt_OpenOfdImageWriter(fileName.c_str(), &writer); - if (NULL == writer) - { - return false; - } - - bool ret = false; - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - HGImage img = NULL; - std::string fileName = filePath + fileNameList[i]; - HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); - if (NULL != img) - { - if (HGBASE_ERR_OK == HGImgFmt_SaveJpegImageToOfdImageWriter(writer, img, NULL)) - ret = true; - HGBase_DestroyImage(img); - } - } - - HGImgFmt_CloseOfdImageWriter(writer); - - if (!ret) - { - HGBase_DeleteFile(fileName.c_str()); - return false; - } - - return true; - } - - bool Manager::ExportOfdFile(const std::string& devId, bool isAuto, HGByte** data, HGUInt* size) - { - *data = NULL; - *size = 0; - if (m_scanning) - { - return false; - } - - HGChar tmpFileName[512]; - HGBase_GetTmpFileName(tmpFileName, 512); - ExportOfdFile(devId, isAuto, tmpFileName); - - *data = GetBuffer(tmpFileName, size); - HGBase_DeleteFile(tmpFileName); - return (NULL != *data); - } - - bool Manager::ExportPdf(const std::string& devId, std::string& imgBase64) - { - imgBase64.clear(); - if (m_scanning) - { - return false; - } - - HGByte* data = NULL; - HGUInt size = 0; - ExportPdfFile(devId, &data, &size); - if (NULL != data) - { - imgBase64 = GetBase64(data, size); - delete[] data; - } - - return !imgBase64.empty(); - } - - bool Manager::ExportPdfFile(const std::string& devId, const std::string& fileName) - { - std::string filePath = GetFilePath(devId); - std::vector fileNameList = GetFileNameList(devId); - if (fileNameList.empty()) - { - return false; - } - - HGPdfImageWriter writer = NULL; - HGImgFmt_OpenPdfImageWriter(fileName.c_str(), &writer); - if (NULL == writer) - { - return false; - } - - bool ret = false; - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - HGImage img = NULL; - std::string fileName = filePath + fileNameList[i]; - HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); - if (NULL != img) - { - if (HGBASE_ERR_OK == HGImgFmt_SaveJpegImageToPdfImageWriter(writer, img, NULL)) - ret = true; - HGBase_DestroyImage(img); - } - } - - HGImgFmt_ClosePdfImageWriter(writer); - - if (!ret) - { - HGBase_DeleteFile(fileName.c_str()); - return false; - } - - return true; - } - - bool Manager::ExportPdfFile(const std::string& devId, HGByte** data, HGUInt* size) - { - *data = NULL; - *size = 0; - if (m_scanning) - { - return false; - } - - HGChar tmpFileName[512]; - HGBase_GetTmpFileName(tmpFileName, 512); - ExportPdfFile(devId, tmpFileName); - - *data = GetBuffer(tmpFileName, size); - HGBase_DeleteFile(tmpFileName); - return (NULL != *data); - } - - bool Manager::ExportTiff(const std::string& devId, std::string& imgBase64) - { - imgBase64.clear(); - if (m_scanning) - { - return false; - } - - HGByte* data = NULL; - HGUInt size = 0; - ExportTiffFile(devId, &data, &size); - if (NULL != data) - { - imgBase64 = GetBase64(data, size); - delete[] data; - } - - return !imgBase64.empty(); - } - - bool Manager::ExportTiff(const std::string& devId, const std::string& fileName) - { - std::string filePath = GetFilePath(devId); - std::vector fileNameList = GetFileNameList(devId); - if (fileNameList.empty()) - { - return false; - } - - HGTiffWriter writer = NULL; - HGImgFmt_OpenTiffWriter(fileName.c_str(), &writer); - if (NULL == writer) - { - return false; - } - - bool ret = false; - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - HGImage img = NULL; - std::string fileName = filePath + fileNameList[i]; - HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); - if (NULL != img) - { - if (HGBASE_ERR_OK == HGImgFmt_SaveImageToTiffWriter(writer, img, NULL)) - ret = true; - HGBase_DestroyImage(img); - } - } - - HGImgFmt_CloseTiffWriter(writer); - - if (!ret) - { - HGBase_DeleteFile(fileName.c_str()); - return false; - } - - return true; - } - - bool Manager::ExportTiffFile(const std::string& devId, HGByte** data, HGUInt* size) - { - *data = NULL; - *size = 0; - if (m_scanning) - { - return false; - } - - HGChar tmpFileName[512]; - HGBase_GetTmpFileName(tmpFileName, 512); - ExportTiff(devId, tmpFileName); - - *data = GetBuffer(tmpFileName, size); - HGBase_DeleteFile(tmpFileName); - return (NULL != *data); - } - - bool Manager::ExportZip(const std::string& devId, std::string& imgBase64) - { - imgBase64.clear(); - if (m_scanning) - { - return false; - } - - HGByte* data = NULL; - HGUInt size = 0; - ExportZipFile(devId, &data, &size); - if (NULL != data) - { - imgBase64 = GetBase64(data, size); - delete[] data; - } - - return !imgBase64.empty(); - } - - bool Manager::ExportZipFile(const std::string& devId, const std::string& fileName) - { - std::string filePath = GetFilePath(devId); - std::vector fileNameList = GetFileNameList(devId); - if (fileNameList.empty()) - { - return false; - } - - int error = 0; - zip* z = zip_open(StdStringToUtf8(fileName.c_str()).c_str(), ZIP_CREATE | ZIP_TRUNCATE, &error); - if (NULL == z) - { - return false; - } - - bool ret = false; - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - std::string fileName = filePath + fileNameList[i]; - zip_source_t* s = zip_source_file(z, StdStringToUtf8(fileName.c_str()).c_str(), 0, 0); - if (NULL != s) - { - if (zip_file_add(z, StdStringToUtf8(fileNameList[i].c_str()).c_str(), s, ZIP_FL_OVERWRITE) >= 0) - { - ret = true; - } - else - { - zip_source_free(s); - } - } - } - - zip_close(z); - z = NULL; - - if (!ret) - { - HGBase_DeleteFile(fileName.c_str()); - return false; - } - - return true; - } - - bool Manager::ExportZipFile(const std::string& devId, HGByte** data, HGUInt* size) - { - *data = NULL; - *size = 0; - if (m_scanning) - { - return false; - } - - HGChar tmpFileName[512]; - HGBase_GetTmpFileName(tmpFileName, 512); - ExportZipFile(devId, tmpFileName); - - *data = GetBuffer(tmpFileName, size); - HGBase_DeleteFile(tmpFileName); - return (NULL != *data); - } - - bool Manager::UploadImage(const UploadParam& uploadParam) - { - if (m_scanning) - { - return false; - } - - std::string devId; - GetCurDevId(devId); - - HGChar tmpFileName[512]; - HGBase_GetTmpFileName(tmpFileName, 512); - if (0 == uploadParam.format) - { - strcat(tmpFileName, ".ofd"); - ExportOfdFile(devId, true, tmpFileName); - } - else if (1 == uploadParam.format) - { - strcat(tmpFileName, ".pdf"); - ExportPdfFile(devId, tmpFileName); - } - else - { - strcat(tmpFileName, ".zip"); - ExportZipFile(devId, tmpFileName); - } - - bool ret = false; - if (0 == uploadParam.uploadMode) // HTTP - { - ret = HTTPUpload(tmpFileName, uploadParam.httpUrl, uploadParam.fileName, uploadParam.httpMethod, - uploadParam.header, uploadParam.param); - } - else if (1 == uploadParam.uploadMode) // FTP - { - ret = FTPUpload(tmpFileName, uploadParam.ftpUrl, uploadParam.ftpPort, uploadParam.ftpPath, - uploadParam.ftpUser, uploadParam.ftpPassword, uploadParam.ftpMode); - } - - HGBase_DeleteFile(tmpFileName); - return ret; - } - - bool Manager::SaveImage(const std::string& devId, const std::string& imgName, const std::string& imgBase64) - { - if (m_scanning) - { - return false; - } - - std::string filePath = GetFilePath(devId); - std::string fileName = filePath + imgName; - - size_t pos = imgBase64.find(","); - if (std::string::npos != pos) - return SaveBase64(fileName, imgBase64.c_str() + pos + 1); - else - return SaveBase64(fileName, imgBase64.c_str()); - } - - bool Manager::DeleteImage(const std::string& devId, const std::string& imgName) - { - if (m_scanning) - { - return false; - } - - std::string filePath = GetFilePath(devId); - std::string fileName = filePath + imgName; - - bool ret = false; - if (HGBASE_ERR_OK == HGBase_DeleteFile(fileName.c_str())) - { - std::vector fileNameList = GetFileNameList(devId); - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - if (imgName == fileNameList[i]) - { - fileNameList.erase(fileNameList.begin() + i); - break; - } - } - - SaveFileNameList(devId, fileNameList); - ret = true; - } - - return ret; - } - - bool Manager::DeleteAllImage(const std::string& devId) - { - if (m_scanning) - { - return false; - } - - std::string filePath = GetFilePath(devId); - std::vector fileNameList = GetFileNameList(devId); - - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - std::string fileName = filePath + fileNameList[i]; - HGBase_DeleteFile(fileName.c_str()); - } - fileNameList.clear(); - - SaveFileNameList(devId, fileNameList); - return true; - } - - bool Manager::MergeImage(const std::string& devId, bool isHorizontal, const std::vector& imgIndexList, - std::string& imgName, std::string& imgBase64) - { - imgName.clear(); - imgBase64.clear(); - if (m_scanning) - { - return false; - } - - std::string filePath = GetFilePath(devId); - std::vector fileNameList = GetFileNameList(devId); - - std::vector imgList; - for (int i = 0; i < (int)imgIndexList.size(); ++i) - { - int index = imgIndexList[i]; - if (index >= 0 && index < (int)fileNameList.size()) - { - std::string fileName = filePath + fileNameList[index]; - HGImage img = NULL; - HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); - if (NULL != img) - imgList.push_back(img); - } - } - - HGUInt width = 0, height = 0; - for (int i = 0; i < (int)imgList.size(); ++i) - { - HGImageInfo imgInfo; - HGBase_GetImageInfo(imgList[i], &imgInfo); - if (isHorizontal) - { - width += imgInfo.width; - if (imgInfo.height > height) - height = imgInfo.height; - } - else - { - height += imgInfo.height; - if (imgInfo.width > width) - width = imgInfo.width; - } - } - - if (width > 0 && height > 0) - { - HGImage img = NULL; - HGBase_CreateImage(width, height, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); - if (NULL != img) - { - HGUInt x = 0, y = 0; - for (int i = 0; i < (int)imgList.size(); ++i) - { - HGImageInfo imgInfo; - HGBase_GetImageInfo(imgList[i], &imgInfo); - - HGImageRoi roi = {x, y, x + imgInfo.width, y + imgInfo.height}; - HGBase_SetImageROI(img, &roi); - HGBase_CopyImage(imgList[i], img); - HGBase_ResetImageROI(img); - - if (isHorizontal) - x += imgInfo.width; - else - y += imgInfo.height; - } - - int maxIndex = 0; - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - int index = atoi(fileNameList[i].c_str()); - if (index > maxIndex) - maxIndex = index; - } - - HGChar name[256]; - sprintf(name, "%d.%s", maxIndex + 1, m_devParam.format.c_str()); - imgName = name; - - HGBase_CreateDir(filePath.c_str()); - std::string fileName = filePath + imgName; - HGImgFmt_SaveImage(img, 0, NULL, fileName.c_str()); - - fileNameList.push_back(imgName); - SaveFileNameList(devId, fileNameList); - - imgBase64 = "data:image/jpeg;base64,"; - imgBase64 += GetBase64(img); - - HGBase_DestroyImage(img); - } - } - - for (int i = 0; i < (int)imgList.size(); ++i) - { - HGBase_DestroyImage(imgList[i]); - } - - return true; - } - - static bool LowerSort(const std::string &str1, const std::string& str2) - { - return atoi(str1.c_str()) < atoi(str2.c_str()); - } - - bool Manager::BookSort(const std::string& devId, std::vector& imgNameList, - std::vector& imgBase64List) - { - imgNameList.clear(); - imgBase64List.clear(); - if (m_scanning) - { - return false; - } - - std::vector fileNameList = GetFileNameList(devId); - std::sort(fileNameList.begin(), fileNameList.end(), LowerSort); - SaveFileNameList(devId, fileNameList); - - return GetImageByDevId(devId, imgNameList, imgBase64List); - } - - bool Manager::ExchangeImage(const std::string& devId, int index1, int index2) - { - if (m_scanning) - { - return false; - } - - std::string filePath = GetFilePath(devId); - std::vector fileNameList = GetFileNameList(devId); - if (index1 < 0 || index1 >= (int)fileNameList.size() || index2 < 0 || index2 >= (int)fileNameList.size()) - return false; - - std::string imgName1 = fileNameList[index1]; - std::string imgName2 = fileNameList[index2]; - fileNameList[index1] = imgName2; - fileNameList[index2] = imgName1; - - SaveFileNameList(devId, fileNameList); - return true; - } - - bool Manager::GetLastBetch(std::string& devId) - { - devId.clear(); - if (m_scanning) - { - return false; - } - - devId = m_devName; - return true; - } - - bool Manager::ResetPatchIndex() - { - if (m_scanning) - { - return false; - } - - return true; - } - - bool Manager::SplitImage(const std::string& devId, const std::string& imgName, bool isHorizontal, int x1, int y1, int x2, int y2, - std::string& imgName1, std::string& imgBase64_1, std::string& imgName2, std::string& imgBase64_2) - { - imgName1.clear(); - imgBase64_1.clear(); - imgName2.clear(); - imgBase64_2.clear(); - if (m_scanning) - { - return false; - } - - std::string filePath = GetFilePath(devId); - std::string fileName = filePath + imgName; - - HGImage img = NULL; - HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); - if (NULL != img) - { - HGImageInfo imgInfo; - HGBase_GetImageInfo(img, &imgInfo); - - for (int i = 0; i < 2; ++i) - { - HGUInt newWidth = isHorizontal ? x1 : imgInfo.width; - if (1 == i) - newWidth = isHorizontal ? (imgInfo.width - x1) : imgInfo.width; - - HGUInt newHeight = isHorizontal ? imgInfo.height : y1; - if (1 == i) - newHeight = isHorizontal ? imgInfo.height : (imgInfo.height - y1); - - HGImage newImg = NULL; - HGBase_CreateImage(newWidth, newHeight, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &newImg); - if (NULL != newImg) - { - HGImageRoi roi; - - if (isHorizontal) - { - roi.left = 0; - roi.top = 0; - roi.right = x1; - roi.bottom = imgInfo.height; - - if (1 == i) - { - roi.left = x1; - roi.right = imgInfo.width; - } - } - else - { - roi.left = 0; - roi.top = 0; - roi.right = imgInfo.width; - roi.bottom = y1; - - if (1 == i) - { - roi.top = y1; - roi.bottom = imgInfo.height; - } - } - - if (1 == i) - { - roi.left = x1; - roi.right = imgInfo.width; - } - - HGBase_SetImageROI(img, &roi); - HGBase_CopyImage(img, newImg); - HGBase_ResetImageROI(img); - - std::vector fileNameList = GetFileNameList(devId); - - int maxIndex = 0; - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - int index = atoi(fileNameList[i].c_str()); - if (index > maxIndex) - maxIndex = index; - } - - HGChar name[256]; - sprintf(name, "%d.%s", maxIndex + 1, m_devParam.format.c_str()); - std::string imgName = name; - - HGBase_CreateDir(filePath.c_str()); - std::string fileName = filePath + imgName; - HGImgFmt_SaveImage(newImg, 0, NULL, fileName.c_str()); - - fileNameList.push_back(imgName); - SaveFileNameList(devId, fileNameList); - - std::string imgBase64 = "data:image/jpeg;base64,"; - imgBase64 += GetBase64(newImg); - - if (0 == i) - { - imgName1 = imgName; - imgBase64_1 = imgBase64; - } - else - { - imgName2 = imgName; - imgBase64_2 = imgBase64; - } - - HGBase_DestroyImage(newImg); - } - } - - HGBase_DestroyImage(img); - } - - return true; - } - - bool Manager::GetDevSerialNo(const std::string& devId, std::string& serialNo) - { - serialNo.clear(); - if (m_scanning) - { - return false; - } - - serialNo = devId; - return true; - } - - bool Manager::GetImageBase64(const std::string& devId, const std::string& imgName, std::string& imgBase64) - { - imgBase64.clear(); - if (m_scanning) - { - return false; - } - - std::string filePath = GetFilePath(devId); - std::string fileName = filePath + imgName; - - HGImage img = NULL; - HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); - if (NULL != img) - { - imgBase64 = "data:image/jpeg;base64,"; - imgBase64 += GetBase64(img); - HGBase_DestroyImage(img); - } - - return true; - } - - std::string Manager::GetFilePath(const std::string& devId) - { - HGChar docsPath[256]; - HGBase_GetDocumentsPath(docsPath, 256); - HGChar imgPath[512]; - sprintf(imgPath, "%s%s/", docsPath, Utf8ToStdString(devId.c_str()).c_str()); - HGChar stdImgPath[512]; - HGBase_StandardiseFileName(imgPath, stdImgPath, 512); - - return stdImgPath; - } - - std::vector Manager::GetFileNameList(const std::string& devId) - { - std::vector fileNameList; - - std::string filePath = GetFilePath(devId); - std::string cfgName = filePath + "images.txt"; - FILE* file = fopen(cfgName.c_str(), "r"); - if (NULL != file) - { - while (feof(file) == 0) - { - char lineContent[256] = { 0 }; - if (NULL == fgets(lineContent, 256, file) || '\n' == *lineContent) - { - continue; - } - - if (lineContent[strlen(lineContent) - 1] == '\n') - lineContent[strlen(lineContent) - 1] = 0; - - fileNameList.push_back(lineContent); - } - - fclose(file); - } - - return fileNameList; - } - - bool Manager::SaveFileNameList(const std::string& devId, const std::vector& fileNameList) - { - bool ret = false; - - std::string filePath = GetFilePath(devId); - std::string cfgName = filePath + "images.txt"; - FILE* file = fopen(cfgName.c_str(), "w"); - if (NULL != file) - { - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - fwrite(fileNameList[i].c_str(), 1, fileNameList[i].size(), file); - fwrite("\n", 1, strlen("\n"), file); - } - - fclose(file); - ret = true; - } - - return ret; - } - - std::string Manager::GetBase64(HGImage image) - { - std::string strBase64; - - if (NULL != image) - { - HGBuffer buffer = NULL; - HGImgFmt_SaveJpegImageToBuffer(image, NULL, &buffer); - if (NULL != buffer) - { - HGByte* data; - HGBase_GetBufferData(buffer, &data); - HGUSize size; - HGBase_GetBufferSize(buffer, &size); - - HGSize base64Size = 0; - HGBase_Base64Encode(data, size, NULL, &base64Size); - uint8_t* base64 = new uint8_t[base64Size + 1]; - HGBase_Base64Encode(data, size, base64, &base64Size); - base64[base64Size] = 0; - strBase64 = (const char*)base64; - delete[] base64; - - HGBase_DestroyBuffer(buffer); - } - } - - return strBase64; - } - - std::string Manager::GetBase64(const HGByte* data, HGUInt size) - { - std::string strBase64; - - if (NULL != data && 0 != size) - { - HGSize base64Size = 0; - HGBase_Base64Encode(data, size, NULL, &base64Size); - uint8_t* base64 = new uint8_t[base64Size + 1]; - HGBase_Base64Encode(data, size, base64, &base64Size); - base64[base64Size] = 0; - strBase64 = (const char*)base64; - delete[] base64; - } - - return strBase64; - } - - std::string Manager::GetBase64(const std::string& fileName) - { - std::string strBase64; - - FILE* file = fopen(fileName.c_str(), "rb"); - if (NULL != file) - { - fseek(file, 0, SEEK_END); - long size = ftell(file); - fseek(file, 0, SEEK_SET); - - if (size > 0) - { - HGByte* data = new HGByte[size]; - long readLen = (long)fread(data, 1, size, file); - if (readLen == size) - { - HGSize base64Size = 0; - HGBase_Base64Encode(data, size, NULL, &base64Size); - uint8_t* base64 = new uint8_t[base64Size + 1]; - HGBase_Base64Encode(data, size, base64, &base64Size); - base64[base64Size] = 0; - strBase64 = (const char*)base64; - delete[] base64; - } - - delete[] data; - } - - fclose(file); - } - - return strBase64; - } - - HGByte* Manager::GetBuffer(const std::string& fileName, HGUInt* size) - { - HGByte* data = NULL; - *size = 0; - - FILE* file = fopen(fileName.c_str(), "rb"); - if (NULL != file) - { - fseek(file, 0, SEEK_END); - *size = ftell(file); - fseek(file, 0, SEEK_SET); - - if (*size > 0) - { - data = new HGByte[*size]; - - HGUInt readLen = (HGUInt)fread(data, 1, *size, file); - if (readLen != *size) - { - delete[] data; - data = NULL; - *size = 0; - } - } - - fclose(file); - } - - return data; - } - - bool Manager::SaveBase64(const std::string& fileName, const char* base64) - { - if (NULL == base64 || 0 == *base64) - return false; - - HGUInt base64Size = (HGUInt)strlen(base64); - - bool ret = false; - FILE* file = fopen(fileName.c_str(), "wb"); - if (NULL != file) - { - HGSize size = 0; - HGBase_Base64Decode((const HGByte*)base64, (HGSize)base64Size, NULL, &size); - uint8_t* data = new HGByte[size]; - HGBase_Base64Decode((const HGByte*)base64, (HGSize)base64Size, data, &size); - - size_t writeLen = fwrite(data, 1, size, file); - if (writeLen == (size_t)size) - ret = true; - - delete[] data; - fclose(file); - } - - return ret; - } - - static std::string MakePreFileData(const char* pszBoundary, const char* pszRemoteFileName) - { - char data[512]; - sprintf(data, "--%s\r\nContent-Disposition: form-data; name=\"filedata\"; filename=\"%s\"\r\n", - pszBoundary, pszRemoteFileName); - std::string ret = data; - ret += "Content-Type: application/octet-stream; charset=utf-8\r\n"; - ret += "Content-Transfer-Encoding: binary\r\n"; - ret += "\r\n"; - return ret; - } - - static std::string MakePostFileData(const char* pszBoundary) - { - char data[512]; - sprintf(data, "\r\n--%s\r\nContent-Disposition: form-data; name=\"submitted\"\r\n\r\nsubmit\r\n--%s--\r\n", pszBoundary, pszBoundary); - return data; - } - - static void ParseHttpURL(const std::string &url, std::string &addr, int &port, std::string &path) - { - addr.clear(); - port = 0; - path.clear(); - - std::string url2; - std::string::size_type pos = url.find("//"); - if (std::string::npos != pos) - { - std::string protocal = url.substr(0, pos); - if (protocal != "http:") - { - return; - } - - url2 = url.substr(pos + 2); - } - else - { - url2 = url; - } - - std::string addr_port; - pos = url2.find("/"); - if (std::string::npos != pos) - { - addr_port = url2.substr(0, pos); - path = url2.substr(pos); - } - else - { - addr_port = url2; - } - - pos = addr_port.find(":"); - if (std::string::npos != pos) - { - addr = addr_port.substr(0, pos); - port = atoi(addr_port.substr(pos + 1).c_str()); - } - else - { - addr = addr_port; - port = 80; - } - } - - bool Manager::HTTPUpload(const std::string& localFileName, const std::string& httpUrl, const std::string& remoteFileName, - const std::string& httpMethod, const std::string& header, const std::string& param) - { - unsigned char* fileData = NULL; - long fileSize = 0; - FILE* file = fopen(localFileName.c_str(), "rb"); - if (NULL != file) - { - fseek(file, 0, SEEK_END); - fileSize = ftell(file); - fseek(file, 0, SEEK_SET); - - if (0 != fileSize) - { - fileData = new unsigned char[fileSize]; - fread(fileData, 1, fileSize, file); - } - - fclose(file); - } - - if (NULL == fileData) - { - return false; - } - - std::string addr; - int port; - std::string path; - ParseHttpURL(httpUrl, addr, port, path); - - #if defined(HG_CMP_MSC) - SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0); - assert(INVALID_SOCKET != sockClient); - #else - int sockClient = socket(AF_INET, SOCK_STREAM, 0); - assert(-1 != sockClient); - #endif - - #if defined(HG_CMP_MSC) - u_long ul = 1; // 设为非阻塞 - ioctlsocket(sockClient, FIONBIO, &ul); - #else - ioctl(sockClient, FIONBIO, 1); - #endif - - #if defined(HG_CMP_MSC) - SOCKADDR_IN addrServer = { 0 }; - addrServer.sin_addr.S_un.S_addr = inet_addr(addr.c_str()); - addrServer.sin_family = AF_INET; - addrServer.sin_port = htons(port); - if (0 != connect(sockClient, (SOCKADDR*)&addrServer, sizeof(SOCKADDR_IN))) - #else - struct sockaddr_in addrServer = { 0 }; - addrServer.sin_addr.s_addr = inet_addr(addr.c_str()); - addrServer.sin_family = AF_INET; - addrServer.sin_port = htons(port); - if (0 != connect(sockClient, (struct sockaddr*)&addrServer, sizeof(addrServer))) - #endif - { - fd_set fds; - FD_ZERO(&fds); - FD_SET(sockClient, &fds); - timeval tm; - tm.tv_sec = 1; - tm.tv_usec = 0; - - if (select((int)(sockClient + 1), NULL, &fds, NULL, &tm) <= 0) - { - #if defined(HG_CMP_MSC) - closesocket(sockClient); - #else - close(sockClient); - #endif - delete[] fileData; - return false; - } - - if (!FD_ISSET(sockClient, &fds)) - { - #if defined(HG_CMP_MSC) - closesocket(sockClient); - #else - close(sockClient); - #endif - delete[] fileData; - return false; - } - } - - #if defined(HG_CMP_MSC) - ul = 0; // 设为阻塞 - ioctlsocket(sockClient, FIONBIO, &ul); - #else - ioctl(sockClient, FIONBIO, 0); - #endif - - char remoteName[256]; - HGBase_GetFileName(localFileName.c_str(), remoteName, 256); - - bool ret = false; - - const char* pszBoundary = "---------------------------7d33a816d302b6"; - - std::string strPreFileData = MakePreFileData(pszBoundary, remoteName); - std::string strPostFileData = MakePostFileData(pszBoundary); - - char hostname[128]; - gethostname(hostname, 128); - - std::string head; - char data[512]; - sprintf(data, "POST %s HTTP/1.1\r\nHost: %s\r\n", path.c_str(), hostname); - head += data; - sprintf(data, "Content-Type: multipart/form-data; boundary=%s\r\n", pszBoundary); - head += data; - sprintf(data, "Content-Length: %d\r\n\r\n", (int)strPreFileData.size() + (int)fileSize + (int)strPostFileData.size()); - head += data; - - send(sockClient, head.c_str(), (int)head.size(), 0); - send(sockClient, strPreFileData.c_str(), (int)strPreFileData.size(), 0); - send(sockClient, (const char *)fileData, (int)fileSize, 0); - send(sockClient, strPostFileData.c_str(), (int)strPostFileData.size(), 0); - - char recvBuf[2048] = {0}; - recv(sockClient, recvBuf, 2048, 0); - - std::string strRecv(recvBuf); - std::string::size_type pos = strRecv.find("\r\n"); - if (pos != std::string::npos) - { - std::string head = strRecv.substr(0, pos); - if (head.find("200") != std::string::npos) - { - ret = true; - } - } - - #if defined(HG_CMP_MSC) - closesocket(sockClient); - #else - close(sockClient); - #endif - delete[] fileData; - return ret; - } - - static size_t read_callback(char* ptr, size_t size, size_t nmemb, void* stream) - { - unsigned long nread; - /* in real-world cases, this would probably get this data differently - as this fread() stuff is exactly what the library already would do - by default internally */ - size_t retcode = fread(ptr, size, nmemb, (FILE*)stream); - - if (retcode > 0) - { - nread = (unsigned long)retcode; - //fprintf(stderr, "*** We read %lu bytes from file\n", nread); - } - - return retcode; - } - - bool Manager::FTPUpload(const std::string& localFileName, const std::string& ftpUrl, int ftpPort, const std::string& ftpPath, - const std::string& ftpUser, const std::string& ftpPassword, int ftpMode) - { - FILE* file = fopen(localFileName.c_str(), "rb"); - if (NULL == file) - { - return false; - } - - bool ret = false; - fseek(file, 0, SEEK_END); - long fsize = ftell(file); - fseek(file, 0, SEEK_SET); - - curl_global_init(CURL_GLOBAL_ALL); - - /* get a curl handle */ - CURL *curl = curl_easy_init(); - if (NULL != curl) - { - char tmpName[256]; - HGBase_GetUuid(tmpName, 256); - char remoteName[256]; - HGBase_GetFileName(localFileName.c_str(), remoteName, 256); - - char ftp_rnfr[512]; - sprintf(ftp_rnfr, "RNFR %s", tmpName); - char ftp_rnto[512]; - sprintf(ftp_rnto, "RNTO %s", remoteName); - - struct curl_slist* headerlist = NULL; - headerlist = curl_slist_append(headerlist, ftp_rnfr); - headerlist = curl_slist_append(headerlist, ftp_rnto); - - /* we want to use our own read function */ - curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); - - curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); - - char url[512]; - if (!ftpUser.empty() && !ftpPassword.empty()) - { - sprintf(url, "ftp://%s:%s@%s:%d%s/%s", ftpUser.c_str(), ftpPassword.c_str(), - ftpUrl.c_str(), ftpPort, ftpPath.c_str(), tmpName); - } - else - { - sprintf(url, "ftp://%s:%d%s/%s", ftpUrl.c_str(), ftpPort, ftpPath.c_str(), tmpName); - } - curl_easy_setopt(curl, CURLOPT_URL, url); - - curl_easy_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS, 1); - - /* pass in that last of FTP commands to run after the transfer */ - curl_easy_setopt(curl, CURLOPT_POSTQUOTE, headerlist); - - /* now specify which file to upload */ - curl_easy_setopt(curl, CURLOPT_READDATA, file); - - /* Set the size of the file to upload (optional). If you give a *_LARGE - option you MUST make sure that the type of the passed-in argument is a - curl_off_t. If you use CURLOPT_INFILESIZE (without _LARGE) you must - make sure that to pass in a type 'long' argument. */ - curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fsize); - - /* Now run off and do what you have been told! */ - CURLcode res = curl_easy_perform(curl); - /* Check for errors */ - if (res != CURLE_OK) - fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); - else - ret = true; - - /* clean up the FTP commands list */ - curl_slist_free_all(headerlist); - - /* always cleanup */ - curl_easy_cleanup(curl); - } - fclose(file); /* close the local file */ - - curl_global_cleanup(); - return ret; - } - - int Manager::sane_ex_callback(SANE_Handle hdev, int code, void* data, unsigned int* len, void* param) - { - (void)hdev; - (void)len; - - Manager* p = (Manager*)param; - switch (code) - { - case SANE_EVENT_DEVICE_ARRIVED: - { - SANE_Device* sane_dev = (SANE_Device*)data; - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "device arrive, name=%s", Utf8ToStdString(sane_dev->name).c_str()); - - HGBase_EnterLock(p->m_lock); - if (NULL != p->m_scanEvent) - p->m_scanEvent(SCANEVENT_ARRIVE, (void*)sane_dev->name, (void*)0, p->m_scanParam); - HGBase_LeaveLock(p->m_lock); - - OpenDevParam* openDevParam = new OpenDevParam; - openDevParam->mgr = p; - openDevParam->devName = sane_dev->name; - - HGMsg msg; - msg.id = MSGID_OPEN_DEVICE; - msg.data = openDevParam; - if (HGBASE_ERR_OK != HGBase_PostPumpMessage(p->m_msgPump, &msg)) - { - delete openDevParam; - } - } - break; - case SANE_EVENT_DEVICE_LEFT: - { - SANE_Device* sane_dev = (SANE_Device*)data; - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "device remove, name=%s", Utf8ToStdString(sane_dev->name).c_str()); - - HGBase_EnterLock(p->m_lock); - if (NULL != p->m_scanEvent) - p->m_scanEvent(SCANEVENT_REMOVE, (void*)sane_dev->name, (void*)0, p->m_scanParam); - HGBase_LeaveLock(p->m_lock); - - CloseDevParam* closeDevParam = new CloseDevParam; - closeDevParam->mgr = p; - closeDevParam->devName = sane_dev->name; - - HGMsg msg; - msg.id = MSGID_CLOSE_DEVICE; - msg.data = closeDevParam; - if (HGBASE_ERR_OK != HGBase_PostPumpMessage(p->m_msgPump, &msg)) - { - delete closeDevParam; - } - } - break; - case SANE_EVENT_STATUS: - { - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "SANE_EVENT_STATUS, msg=%s", Utf8ToStdString((char *)data).c_str()); - - HGBase_EnterLock(p->m_lock); - if (NULL != p->m_scanEvent) - p->m_scanEvent(SCANEVENT_STATUS, (void*)data, (void*)0, p->m_scanParam); - HGBase_LeaveLock(p->m_lock); - } - break; - case SANE_EVENT_ERROR: - { - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "SANE_EVENT_ERROR, msg=%s", Utf8ToStdString((char*)data).c_str()); - - HGBase_EnterLock(p->m_lock); - if (NULL != p->m_scanEvent) - p->m_scanEvent(SCANEVENT_ERROR, (void *)data, (void*)0, p->m_scanParam); - HGBase_LeaveLock(p->m_lock); - } - break; - case SANE_EVENT_WORKING: - { - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "SANE_EVENT_WORKING, msg=%s", Utf8ToStdString((char*)data).c_str()); - - HGBase_EnterLock(p->m_lock); - if (NULL != p->m_scanEvent) - p->m_scanEvent(SCANEVENT_WORKING, (void*)data, (void*)0, p->m_scanParam); - HGBase_LeaveLock(p->m_lock); - } - break; - case SANE_EVENT_IMAGE_OK: - { - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "SANE_EVENT_IMAGE_OK"); - - SANE_Image* sane_img = (SANE_Image*)data; - - HGUInt imgType = 0; - if (sane_img->header.format == SANE_FRAME_GRAY) - imgType = HGBASE_IMGTYPE_GRAY; - else if (sane_img->header.format == SANE_FRAME_RGB) - imgType = HGBASE_IMGTYPE_RGB; - - HGByte* data = sane_img->data; - HGImageInfo imgInfo = { (HGUInt)sane_img->header.pixels_per_line, (HGUInt)sane_img->header.lines, - imgType, (HGUInt)sane_img->header.bytes_per_line, HGBASE_IMGORIGIN_TOP }; - - HGImage img = NULL; - HGBase_CreateImageFromData(data, &imgInfo, nullptr, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); - if (NULL != img) - { - std::string filePath = GetFilePath(p->m_devName); - std::vector fileNameList = GetFileNameList(p->m_devName); - - int maxIndex = 0; - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - int index = atoi(fileNameList[i].c_str()); - if (index > maxIndex) - maxIndex = index; - } - - HGChar name[256]; - sprintf(name, "%d.%s", maxIndex + 1, p->m_devParam.format.c_str()); - std::string imgName = name; - - HGBase_CreateDir(filePath.c_str()); - std::string fileName = filePath + imgName; - HGImgFmt_SaveImage(img, 0, NULL, fileName.c_str()); - - if (0 == p->m_devParam.uploadMode) // HTTP - { - HTTPUpload(fileName, p->m_devParam.httpUrl, p->m_devParam.fileName, p->m_devParam.httpMethod, - p->m_devParam.header, p->m_devParam.param); - } - else if (1 == p->m_devParam.uploadMode) // FTP - { - FTPUpload(fileName, p->m_devParam.ftpUrl, p->m_devParam.ftpPort, p->m_devParam.ftpPath, - p->m_devParam.ftpUser, p->m_devParam.ftpPassword, p->m_devParam.ftpMode); - } - - if (p->m_scanIsInsert) - { - int index = -1; - for (int i = 0; i < (int)fileNameList.size(); ++i) - { - if (fileNameList[i] == p->m_scanInsertImgName) - { - index = i; - break; - } - } - - if (-1 != index) - { - fileNameList.insert(fileNameList.begin() + index, imgName); - } - else - { - fileNameList.push_back(imgName); - } - } - else - { - fileNameList.push_back(imgName); - } - - SaveFileNameList(p->m_devName, fileNameList); - - std::string imgBase64 = "data:image/jpeg;base64,"; - imgBase64 += GetBase64(img); - - HGBase_EnterLock(p->m_lock); - if (NULL != p->m_scanEvent) - p->m_scanEvent(SCANEVENT_IMAGE, (void*)imgName.c_str(), (void *)imgBase64.c_str(), p->m_scanParam); - HGBase_LeaveLock(p->m_lock); - - HGBase_DestroyImage(img); - } - } - break; - case SANE_EVENT_SCAN_FINISHED: - { - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "SANE_EVENT_SCAN_FINISHED, msg=%s", Utf8ToStdString((char*)data).c_str()); - - HGBase_EnterLock(p->m_lock); - if (NULL != p->m_scanEvent) - p->m_scanEvent(SCANEVENT_FINISH, (void*)data, (void*)0, p->m_scanParam); - HGBase_LeaveLock(p->m_lock); - - ScanFinishParam* scanFinishParam = new ScanFinishParam; - scanFinishParam->mgr = p; - - HGMsg msg; - msg.id = MSGID_SCAN_FINISH; - msg.data = scanFinishParam; - if (HGBASE_ERR_OK != HGBase_PostPumpMessage(p->m_msgPump, &msg)) - { - delete scanFinishParam; - } - } - break; - } - - return 0; - } + m_msgPump = msgPump; +} + +Manager::~Manager() +{ + } diff --git a/sdk/webservice/Manager.h b/sdk/webservice/Manager.h index bff26026..04564c5d 100644 --- a/sdk/webservice/Manager.h +++ b/sdk/webservice/Manager.h @@ -2,193 +2,14 @@ #include "base/HGDef.h" #include "base/HGInc.h" -#include "base/HGLock.h" -#include "base/HGImage.h" #include "base/HGMsgPump.h" -#include "sane/sane_ex.h" -#include "sane/sane_option_definitions.h" -#include "Msg.h" -#include -namespace ver_1 +class Manager { - enum - { - SCANEVENT_ARRIVE = 1L, - SCANEVENT_REMOVE, - SCANEVENT_STATUS, - SCANEVENT_WORKING, - SCANEVENT_IMAGE, - SCANEVENT_FINISH, - SCANEVENT_ERROR - }; +public: + Manager(HGMsgPump msgPump); + virtual ~Manager(); - struct DevParam - { - DevParam(); - ~DevParam(); - - void Reset(); - void Load(const std::string& cfgPath); - void Save(const std::string& cfgPath); - - std::string device; // 设备名称,默认null - bool autofeeder; // 自动进纸,默认true - int pixel; // 扫描模式 0:黑白 1:灰度 2:彩色,默认1 - bool white; // 丢弃空白页,默认false - int discardBlankThre; // 跳过空白页阈值 1­-100 默认值5 - bool single; // 单页扫描,默认false - std::string format; // 输出格式 jpg png bmp tiff pdf ofd,默认jpg - int resolution; // 扫描分辨率 范围 100­-600 默认值200 - int orentation; // 图片旋转 0:原图 90:度 180:旋转180度 270:旋转270度,默认0 - std::string paperType; // 扫描幅面 A3:A3幅面 Auto:自适应幅面 A4:A4幅面,默认Auto - int splitImage; // 图像分割 0:disable 1:垂直分割 2: 水平分割,默认0 - bool noiseDetachEnable; // 去除噪点,默认true - int noiseDetach; // 噪点阈值 范围:10­-50 默认值15 - - int uploadMode; // 是否边扫边上传 0:http 1:ftp 2: 不上传,默认2 - std::string httpUrl; // 上传地址,默认null - std::string fileName; // 接收文件参数名,默认null - std::string httpMethod; // 上传方式 GET POST PUT,默认null - std::string header; // 请求头,默认null - std::string param; // 参数 json格式,默认null - std::string ftpUrl; // ftp 地址,默认null - std::string ftpPath; // 路径,默认/images - std::string ftpUser; // ftp 用户名,默认null - std::string ftpPassword; // ftp 密码,默认null - int ftpPort; // 端口号,默认21 - int ftpMode; // 连接模式 1:主动 2:被动,默认2 - }; - - struct UploadParam - { - UploadParam() - { - uploadMode = 2; - ftpPort = 21; - ftpMode = 2; - format = 2; - } - - int uploadMode; // 上传模式 0:http 1:ftp 默认0 - std::string httpUrl; // 上传地址,默认null - std::string fileName; // 接收文件参数名,默认null - std::string httpMethod; // 上传方式 GET POST PUT,默认null - std::string header; // 请求头,默认null - std::string param; // 参数 json格式,默认null - std::string ftpUrl; // ftp 地址,默认null - std::string ftpPath; // 路径,默认/images - std::string ftpUser; // ftp 用户名,默认null - std::string ftpPassword; // ftp 密码,默认null - int ftpPort; // 端口号,默认21 - int ftpMode; // 连接模式 1:主动 2:被动,默认2 - int format; // 上传格式 0: ofd 1: pdf 2: zip, 默认2 - }; - - typedef void (*ScanEvent)(HGUInt event, void* value1, void* value2, void* param); - - class Manager - { - public: - Manager(HGMsgPump msgPump); - ~Manager(); - - // 打开设备 - void OpenDev(const OpenDevParam* param); - // 关闭设备 - void CloseDev(const CloseDevParam* param); - // 扫描完成 - void ScanFinish(const ScanFinishParam* param); - - // 设置回调 - void SetScanEvent(ScanEvent event, void* param); - // 清理回调 - void ResetScanEvent(); - // 扫描 - bool Scan(const std::string& insertImgName, bool isInsert); - // 停止扫描 - bool StopScan(); - // 获取当前连接的设备ID - bool GetCurDevId(std::string& devId); - // 获取连接的设备名列表 - bool GetDevNames(std::vector& devNameList); - // 获取上次的扫描结果 - bool GetImageByDevId(const std::string& devId, std::vector& imgNameList, - std::vector& imgBase64List); - // 获取配置参数 - bool GetDevParam(const std::string& devId, DevParam& devParam); - // 设置配置参数 - bool SetDevParam(const std::string& devId, const DevParam& devParam); - // 生成OFD - bool ExportOfd(const std::string& devId, bool isAuto, std::string& imgBase64); - bool ExportOfdFile(const std::string& devId, bool isAuto, const std::string& fileName); - bool ExportOfdFile(const std::string& devId, bool isAuto, HGByte** data, HGUInt* size); - // 生成PDF - bool ExportPdf(const std::string& devId, std::string& imgBase64); - bool ExportPdfFile(const std::string& devId, const std::string& fileName); - bool ExportPdfFile(const std::string& devId, HGByte** data, HGUInt* size); - // 生成TIFF - bool ExportTiff(const std::string& devId, std::string& imgBase64); - bool ExportTiff(const std::string& devId, const std::string& fileName); - bool ExportTiffFile(const std::string& devId, HGByte** data, HGUInt* size); - // 生成ZIP - bool ExportZip(const std::string& devId, std::string& imgBase64); - bool ExportZipFile(const std::string& devId, const std::string& fileName); - bool ExportZipFile(const std::string& devId, HGByte** data, HGUInt* size); - // 上传图像 - bool UploadImage(const UploadParam& uploadParam); - // 保存图片 - bool SaveImage(const std::string& devId, const std::string& imgName, const std::string& imgBase64); - // 删除图片 - bool DeleteImage(const std::string& devId, const std::string& imgName); - // 删除所有图片 - bool DeleteAllImage(const std::string& devId); - // 图像合并 - bool MergeImage(const std::string& devId, bool isHorizontal, const std::vector& imgIndexList, - std::string& imgName, std::string& imgBase64); - // 自动排序 - bool BookSort(const std::string& devId, std::vector& imgNameList, - std::vector& imgBase64List); - // 交换文件 - bool ExchangeImage(const std::string& devId, int index1, int index2); - // 获取最后批次 - bool GetLastBetch(std::string& devId); - // 重置索引 - bool ResetPatchIndex(); - // 拆分图像 - bool SplitImage(const std::string& devId, const std::string& imgName, bool isHorizontal, int x1, int y1, int x2, int y2, - std::string& imgName1, std::string& imgBase64_1, std::string& imgName2, std::string& imgBase64_2); - // 获取设备序列号 - bool GetDevSerialNo(const std::string& devId, std::string& serialNo); - // 获取图像Base64 - bool GetImageBase64(const std::string& devId, const std::string& imgName, std::string& imgBase64); - - private: - static std::string GetFilePath(const std::string& devId); - static std::vector GetFileNameList(const std::string& devId); - static bool SaveFileNameList(const std::string& devId, const std::vector& fileNameList); - static std::string GetBase64(HGImage image); - static std::string GetBase64(const HGByte* data, HGUInt size); - static std::string GetBase64(const std::string& fileName); - static HGByte* GetBuffer(const std::string& fileName, HGUInt* size); - static bool SaveBase64(const std::string& fileName, const char* base64); - static bool HTTPUpload(const std::string& localFileName, const std::string& httpUrl, const std::string& remoteFileName, - const std::string& httpMethod, const std::string& header, const std::string& param); - static bool FTPUpload(const std::string& localFileName, const std::string& ftpUrl, int ftpPort, const std::string& ftpPath, - const std::string& ftpUser, const std::string& ftpPassword, int ftpMode); - static int sane_ex_callback(SANE_Handle hdev, int code, void* data, unsigned int* len, void* param); - - private: - HGMsgPump m_msgPump; - HGLock m_lock; - std::string m_devName; - SANE_Handle m_devHandle; - DevParam m_devParam; - ScanEvent m_scanEvent; - void* m_scanParam; - - std::string m_scanInsertImgName; - bool m_scanIsInsert; - bool m_scanning; - }; -} +protected: + HGMsgPump m_msgPump; +}; diff --git a/sdk/webservice/ManagerV1.cpp b/sdk/webservice/ManagerV1.cpp new file mode 100644 index 00000000..df992241 --- /dev/null +++ b/sdk/webservice/ManagerV1.cpp @@ -0,0 +1,2082 @@ +#include "ManagerV1.h" +#include "base/HGBuffer.h" +#include "base/HGBase64.h" +#include "base/HGUtility.h" +#include "base/HGInfo.h" +#include "imgfmt/HGJpeg.h" +#include "imgfmt/HGOfd.h" +#include "imgfmt/HGPdf.h" +#include "imgfmt/HGTiff.h" +#include "imgfmt/HGImgFmt.h" +#include "HGString.h" +extern "C" +{ +#include "zip.h" +}; +#include +#include +#include + +namespace ver_1 +{ + DevParam::DevParam() + { + Reset(); + } + + DevParam::~DevParam() + { + + } + + void DevParam::Reset() + { + autofeeder = true; + pixel = 1; + white = false; + discardBlankThre = 5; + single = false; + format = "jpg"; + resolution = 200; + orentation = 0; + paperType = "Auto"; + splitImage = 0; + noiseDetachEnable = true; + noiseDetach = 15; + + uploadMode = 2; + ftpPath = "/images"; + ftpPort = 21; + ftpMode = 2; + } + + void DevParam::Load(const std::string& cfgPath) + { + HGInt intValue; + HGChar strValue[256]; + + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "device", "", strValue, 256); + device = strValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "autofeeder", 1, &intValue); + autofeeder = (bool)intValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "pixel", 1, &intValue); + pixel = intValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "white", 0, &intValue); + white = (bool)intValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "discardBlankThre", 5, &intValue); + discardBlankThre = intValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "single", 0, &intValue); + single = (bool)intValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "format", "jpg", strValue, 256); + format = strValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "resolution", 200, &intValue); + resolution = intValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "orentation", 0, &intValue); + orentation = intValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "paperType", "Auto", strValue, 256); + paperType = strValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "splitImage", 0, &intValue); + splitImage = intValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "noiseDetachEnable", 1, &intValue); + noiseDetachEnable = (bool)intValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "noiseDetach", 15, &intValue); + noiseDetach = intValue; + + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "uploadMode", 2, &intValue); + uploadMode = intValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "httpUrl", "", strValue, 256); + httpUrl = strValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "fileName", "", strValue, 256); + fileName = strValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "httpMethod", "", strValue, 256); + httpMethod = strValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "header", "", strValue, 256); + header = strValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "param", "", strValue, 256); + param = strValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "ftpUrl", "", strValue, 256); + ftpUrl = strValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "ftpPath", "", strValue, 256); + ftpPath = strValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "ftpUser", "", strValue, 256); + ftpUser = strValue; + HGBase_GetProfileString(cfgPath.c_str(), "devParam", "ftpPassword", "", strValue, 256); + ftpPassword = strValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "ftpPort", 21, &intValue); + ftpPort = intValue; + HGBase_GetProfileInt(cfgPath.c_str(), "devParam", "ftpMode", 2, &intValue); + ftpMode = intValue; + } + + void DevParam::Save(const std::string& cfgPath) + { + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "device", device.c_str()); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "autofeeder", autofeeder); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "pixel", pixel); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "white", white); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "discardBlankThre", discardBlankThre); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "single", single); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "format", format.c_str()); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "resolution", resolution); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "orentation", orentation); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "paperType", paperType.c_str()); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "splitImage", splitImage); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "noiseDetachEnable", noiseDetachEnable); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "noiseDetach", noiseDetach); + + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "uploadMode", uploadMode); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "httpUrl", httpUrl.c_str()); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "fileName", fileName.c_str()); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "httpMethod", httpMethod.c_str()); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "header", header.c_str()); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "param", param.c_str()); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "ftpUrl", ftpUrl.c_str()); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "ftpPath", ftpPath.c_str()); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "ftpUser", ftpUser.c_str()); + HGBase_SetProfileString(cfgPath.c_str(), "devParam", "ftpPassword", ftpPassword.c_str()); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "ftpPort", ftpPort); + HGBase_SetProfileInt(cfgPath.c_str(), "devParam", "ftpMode", ftpMode); + } + + ManagerV1::ManagerV1(HGMsgPump msgPump) + : Manager(msgPump) + { + HGBase_CreateLock(&m_lock); + m_devName.clear(); + m_devHandle = NULL; + m_scanEvent = NULL; + m_scanParam = NULL; + + m_scanInsertImgName.clear(); + m_scanIsInsert = false; + m_scanning = false; + + SANE_Int version_code = 0; + SANE_Status status = sane_init_ex(&version_code, sane_ex_callback, this); + assert(SANE_STATUS_GOOD == status); + } + + ManagerV1::~ManagerV1() + { + if (NULL != m_devHandle) + { + StopScan(); + + m_devParam.Reset(); + sane_close(m_devHandle); + m_devHandle = NULL; + m_devName.clear(); + } + + sane_exit(); + + HGBase_DestroyLock(m_lock); + m_lock = NULL; + } + + void ManagerV1::OpenDev(const OpenDevParam* param) + { + assert(NULL != param && this == param->mgr); + + if (!m_devName.empty() || NULL != m_devHandle) + { + return; + } + + SANE_Handle devHandle = NULL; + SANE_Status status = sane_open(param->devName.c_str(), &devHandle); + if (SANE_STATUS_GOOD == status) + { + assert(NULL != devHandle); + + m_devName = param->devName; + m_devHandle = devHandle; + + std::string filePath = GetFilePath(m_devName); + std::string cfgPath = filePath + "config.ini"; + m_devParam.Load(cfgPath); + SetDevParam(m_devName, m_devParam); + } + } + + void ManagerV1::CloseDev(const CloseDevParam* param) + { + assert(NULL != param && this == param->mgr); + + if (m_devName.empty() || NULL == m_devHandle || m_devName != param->devName) + { + return; + } + + assert(NULL != m_devHandle); + + StopScan(); + + m_devParam.Reset(); + sane_close(m_devHandle); + m_devHandle = NULL; + m_devName.clear(); + } + + void ManagerV1::ScanFinish(const ScanFinishParam* param) + { + assert(NULL != param && this == param->mgr); + + m_scanInsertImgName.clear(); + m_scanIsInsert = false; + m_scanning = false; + } + + void ManagerV1::SetScanEvent(ScanEvent event, void* param) + { + assert(NULL != event && NULL != param); + + HGBase_EnterLock(m_lock); + m_scanEvent = event; + m_scanParam = param; + HGBase_LeaveLock(m_lock); + } + + void ManagerV1::ResetScanEvent() + { + HGBase_EnterLock(m_lock); + m_scanEvent = NULL; + m_scanParam = NULL; + HGBase_LeaveLock(m_lock); + } + + bool ManagerV1::Scan(const std::string& insertImgName, bool isInsert) + { + if (m_scanning) + { + return false; + } + + bool ret = false; + if (NULL != m_devHandle) + { + m_scanInsertImgName = insertImgName; + m_scanIsInsert = isInsert; + if (SANE_STATUS_GOOD == sane_start(m_devHandle)) + { + m_scanning = true; + ret = true; + } + else + { + m_scanInsertImgName.clear(); + m_scanIsInsert = false; + } + } + + return ret; + } + + bool ManagerV1::StopScan() + { + if (m_scanning) + { + assert(NULL != m_devHandle); + sane_cancel(m_devHandle); + } + + return true; + } + + bool ManagerV1::GetCurDevId(std::string& devId) + { + devId.clear(); + if (m_scanning) + { + return false; + } + + devId = m_devName; + return true; + } + + bool ManagerV1::GetDevNames(std::vector& devNameList) + { + devNameList.clear(); + if (m_scanning) + { + return false; + } + + const SANE_Device** device_list; + if (SANE_STATUS_GOOD == sane_get_devices(&device_list, SANE_TRUE)) + { + const SANE_Device** p; + for (p = device_list; *p != NULL; ++p) + { + devNameList.push_back((*p)->name); + } + } + + return true; + } + + bool ManagerV1::GetImageByDevId(const std::string& devId, std::vector& imgNameList, + std::vector& imgBase64List) + { + imgNameList.clear(); + imgBase64List.clear(); + if (m_scanning) + { + return false; + } + + std::string filePath = GetFilePath(devId); + std::vector fileNameList = GetFileNameList(devId); + HGBase_WriteInfo(HGBASE_INFOTYPE_DEBUG, "filePath=%s", filePath.c_str()); + + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + std::string fileName = filePath + fileNameList[i]; + + HGImage img = NULL; + HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); + if (NULL != img) + { + std::string imgBase64 = "data:image/jpeg;base64,"; + imgBase64 += GetBase64(img); + + imgNameList.push_back(fileNameList[i]); + imgBase64List.push_back(imgBase64); + HGBase_DestroyImage(img); + } + } + + SaveFileNameList(devId, imgNameList); + return true; + } + + bool ManagerV1::GetDevParam(const std::string& devId, DevParam& devParam) + { + devParam.Reset(); + if (m_scanning) + { + return false; + } + + bool ret = false; + if (NULL != m_devHandle) + { + m_devParam.device = m_devName; + + // 豸ȡm_devParam + + SANE_Int num_dev_options = 0; + sane_control_option(m_devHandle, 0, SANE_ACTION_GET_VALUE, &num_dev_options, NULL); + for (int i = 1; i < num_dev_options; ++i) + { + const SANE_Option_Descriptor* desp = sane_get_option_descriptor(m_devHandle, i); + if (NULL == desp) + continue; + + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "title=%s", Utf8ToStdString(desp->title).c_str()); + + if (SANE_TYPE_BOOL == desp->type) + { + SANE_Bool value = 0; + sane_control_option(m_devHandle, i, SANE_ACTION_GET_VALUE, &value, NULL); + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=BOOL, value=%s", value ? "TRUE" : "FALSE"); + + if (0 == strcmp(desp->title, OPTION_TITLE_TXCF)) + m_devParam.splitImage = value ? 1 : 0; + else if (0 == strcmp(desp->title, OPTION_TITLE_HBTXZDYH)) + m_devParam.noiseDetachEnable = (bool)value; + } + else if (SANE_TYPE_INT == desp->type) + { + SANE_Int value = 0; + sane_control_option(m_devHandle, i, SANE_ACTION_GET_VALUE, &value, NULL); + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=INT, value=%d", value); + + if (0 == strcmp(desp->title, OPTION_TITLE_TGKBYLMD)) + m_devParam.discardBlankThre = value; + else if (0 == strcmp(desp->title, OPTION_TITLE_FBL)) + m_devParam.resolution = value; + } + else if (SANE_TYPE_FIXED == desp->type) + { + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=FIXED"); + } + else if (SANE_TYPE_STRING == desp->type) + { + char value[256] = { 0 }; + sane_control_option(m_devHandle, i, SANE_ACTION_GET_VALUE, value, NULL); + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=STRING, value=%s", Utf8ToStdString(value).c_str()); + + if (0 == strcmp(OPTION_TITLE_SMZS, desp->title) && 0 == strcmp(OPTION_VALUE_SMZS_LXSM, value)) + m_devParam.autofeeder = true; + else if (0 == strcmp(OPTION_TITLE_SMZS, desp->title) && 0 == strcmp(OPTION_VALUE_SMZS_SMZDZS, value)) + m_devParam.autofeeder = false; + else if (0 == strcmp(OPTION_TITLE_YSMS, desp->title) && (0 == strcmp(OPTION_VALUE_YSMS_24WCS, value) + || 0 == strcmp(OPTION_VALUE_YSMS_YSZDSB, value))) + m_devParam.pixel = 2; + else if (0 == strcmp(OPTION_TITLE_YSMS, desp->title) && 0 == strcmp(OPTION_VALUE_YSMS_256JHD, value)) + m_devParam.pixel = 1; + else if (0 == strcmp(OPTION_TITLE_YSMS, desp->title) && 0 == strcmp(OPTION_VALUE_YSMS_HB, value)) + m_devParam.pixel = 0; + else if (0 == strcmp(OPTION_TITLE_SMYM, desp->title) && 0 == strcmp(OPTION_VALUE_SMYM_SM, value)) + { + m_devParam.white = false; + m_devParam.single = false; + } + else if (0 == strcmp(OPTION_TITLE_SMYM, desp->title) && 0 == strcmp(OPTION_VALUE_SMYM_DM, value)) + { + m_devParam.white = false; + m_devParam.single = true; + } + else if (0 == strcmp(OPTION_TITLE_SMYM, desp->title) && (0 == strcmp(OPTION_VALUE_SMYM_TGKBYTY, value) + || 0 == strcmp(OPTION_VALUE_SMYM_TGKBYFPZ, value))) + { + m_devParam.white = true; + m_devParam.single = false; + } + else if (0 == strcmp(OPTION_TITLE_WGFX, desp->title) && 0 == strcmp(OPTION_VALUE_WGFX_0, value)) + m_devParam.orentation = 0; + else if (0 == strcmp(OPTION_TITLE_WGFX, desp->title) && 0 == strcmp(OPTION_VALUE_WGFX_90, value)) + m_devParam.orentation = 90; + else if (0 == strcmp(OPTION_TITLE_WGFX, desp->title) && 0 == strcmp(OPTION_VALUE_WGFX_180, value)) + m_devParam.orentation = 180; + else if (0 == strcmp(OPTION_TITLE_WGFX, desp->title) && 0 == strcmp(OPTION_VALUE_WGFX__90, value)) + m_devParam.orentation = 270; + else if (0 == strcmp(OPTION_TITLE_ZZCC, desp->title) && 0 == strcmp(OPTION_VALUE_ZZCC_PPYSCC, value)) + m_devParam.paperType = "Auto"; + else if (0 == strcmp(OPTION_TITLE_ZZCC, desp->title) && 0 == strcmp(OPTION_VALUE_ZZCC_A3, value)) + m_devParam.paperType = "A3"; + else if (0 == strcmp(OPTION_TITLE_ZZCC, desp->title) && 0 == strcmp(OPTION_VALUE_ZZCC_A4, value)) + m_devParam.paperType = "A4"; + } + else if (SANE_TYPE_BUTTON == desp->type) + { + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=BUTTON"); + } + else if (SANE_TYPE_GROUP == desp->type) + { + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, " valueType=GROUP"); + } + } + + std::string filePath = GetFilePath(m_devName); + std::string cfgPath = filePath + "config.ini"; + m_devParam.Save(cfgPath); + ret = true; + } + + devParam = m_devParam; + return ret; + } + + bool ManagerV1::SetDevParam(const std::string& devId, const DevParam& devParam) + { + if (m_scanning) + { + return false; + } + + m_devParam = devParam; + + std::string filePath = GetFilePath(m_devName); + std::string cfgPath = filePath + "config.ini"; + m_devParam.Save(cfgPath); + + bool ret = false; + if (NULL != m_devHandle) + { + // m_devParam豸 + + SANE_Int num_dev_options = 0; + sane_control_option(m_devHandle, 0, SANE_ACTION_GET_VALUE, &num_dev_options, NULL); + for (int i = 1; i < num_dev_options; ++i) + { + const SANE_Option_Descriptor* desp = sane_get_option_descriptor(m_devHandle, i); + if (NULL == desp) + continue; + + if (SANE_TYPE_BOOL == desp->type) + { + if (0 == strcmp(desp->title, OPTION_TITLE_TXCF)) + { + SANE_Bool value = SANE_FALSE; + if (0 != m_devParam.splitImage) + value = SANE_TRUE; + sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, &value, NULL); + } + else if (0 == strcmp(desp->title, OPTION_TITLE_HBTXZDYH)) + { + SANE_Bool value = SANE_FALSE; + if (m_devParam.noiseDetachEnable) + value = SANE_TRUE; + sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, &value, NULL); + } + } + else if (SANE_TYPE_INT == desp->type) + { + if (0 == strcmp(desp->title, OPTION_TITLE_TGKBYLMD)) + { + SANE_Int value = m_devParam.discardBlankThre; + sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, &value, NULL); + } + else if (0 == strcmp(desp->title, OPTION_TITLE_FBL)) + { + SANE_Int value = m_devParam.resolution; + sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, &value, NULL); + } + else if (0 == strcmp(desp->title, OPTION_TITLE_SMSL)) + { + SANE_Int value = 1; + sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, &value, NULL); + } + } + else if (SANE_TYPE_FIXED == desp->type) + { + + } + else if (SANE_TYPE_STRING == desp->type) + { + if (0 == strcmp(OPTION_TITLE_SMZS, desp->title)) + { + char value[256] = { 0 }; + strcpy(value, OPTION_VALUE_SMZS_LXSM); + if (!m_devParam.autofeeder) + strcpy(value, OPTION_VALUE_SMZS_SMZDZS); + sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, (void*)value, NULL); + } + else if (0 == strcmp(OPTION_TITLE_YSMS, desp->title)) + { + char value[256] = { 0 }; + strcpy(value, OPTION_VALUE_YSMS_24WCS); + if (1 == m_devParam.pixel) + strcpy(value, OPTION_VALUE_YSMS_256JHD); + else if (0 == m_devParam.pixel) + strcpy(value, OPTION_VALUE_YSMS_HB); + sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, (void*)value, NULL); + } + else if (0 == strcmp(OPTION_TITLE_SMYM, desp->title)) + { + char value[256] = { 0 }; + strcpy(value, OPTION_VALUE_SMYM_SM); + if (m_devParam.single) + strcpy(value, OPTION_VALUE_SMYM_DM); + else if (m_devParam.white) + strcpy(value, OPTION_VALUE_SMYM_TGKBYTY); + sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, (void*)value, NULL); + } + else if (0 == strcmp(OPTION_TITLE_WGFX, desp->title)) + { + char value[256] = { 0 }; + strcpy(value, OPTION_VALUE_WGFX_0); + if (90 == m_devParam.orentation) + strcpy(value, OPTION_VALUE_WGFX_90); + else if (180 == m_devParam.orentation) + strcpy(value, OPTION_VALUE_WGFX_180); + else if (270 == m_devParam.orentation) + strcpy(value, OPTION_VALUE_WGFX__90); + sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, (void*)value, NULL); + } + else if (0 == strcmp(OPTION_TITLE_ZZCC, desp->title)) + { + char value[256] = { 0 }; + strcpy(value, OPTION_VALUE_ZZCC_PPYSCC); + if ("A3" == m_devParam.paperType) + strcpy(value, OPTION_VALUE_ZZCC_A3); + else if ("A4" == m_devParam.paperType) + strcpy(value, OPTION_VALUE_ZZCC_A4); + sane_control_option(m_devHandle, i, SANE_ACTION_SET_VALUE, (void*)value, NULL); + } + } + else if (SANE_TYPE_BUTTON == desp->type) + { + + } + else if (SANE_TYPE_GROUP == desp->type) + { + + } + } + + ret = true; + } + + return ret; + } + + bool ManagerV1::ExportOfd(const std::string& devId, bool isAuto, std::string& imgBase64) + { + imgBase64.clear(); + if (m_scanning) + { + return false; + } + + HGByte* data = NULL; + HGUInt size = 0; + ExportOfdFile(devId, isAuto, &data, &size); + if (NULL != data) + { + imgBase64 = GetBase64(data, size); + delete[] data; + } + + return !imgBase64.empty(); + } + + bool ManagerV1::ExportOfdFile(const std::string& devId, bool isAuto, const std::string& fileName) + { + std::string filePath = GetFilePath(devId); + std::vector fileNameList = GetFileNameList(devId); + if (fileNameList.empty()) + { + return false; + } + + HGOfdImageWriter writer = NULL; + HGImgFmt_OpenOfdImageWriter(fileName.c_str(), &writer); + if (NULL == writer) + { + return false; + } + + bool ret = false; + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + HGImage img = NULL; + std::string fileName = filePath + fileNameList[i]; + HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); + if (NULL != img) + { + if (HGBASE_ERR_OK == HGImgFmt_SaveJpegImageToOfdImageWriter(writer, img, NULL)) + ret = true; + HGBase_DestroyImage(img); + } + } + + HGImgFmt_CloseOfdImageWriter(writer); + + if (!ret) + { + HGBase_DeleteFile(fileName.c_str()); + return false; + } + + return true; + } + + bool ManagerV1::ExportOfdFile(const std::string& devId, bool isAuto, HGByte** data, HGUInt* size) + { + *data = NULL; + *size = 0; + if (m_scanning) + { + return false; + } + + HGChar tmpFileName[512]; + HGBase_GetTmpFileName(tmpFileName, 512); + ExportOfdFile(devId, isAuto, tmpFileName); + + *data = GetBuffer(tmpFileName, size); + HGBase_DeleteFile(tmpFileName); + return (NULL != *data); + } + + bool ManagerV1::ExportPdf(const std::string& devId, std::string& imgBase64) + { + imgBase64.clear(); + if (m_scanning) + { + return false; + } + + HGByte* data = NULL; + HGUInt size = 0; + ExportPdfFile(devId, &data, &size); + if (NULL != data) + { + imgBase64 = GetBase64(data, size); + delete[] data; + } + + return !imgBase64.empty(); + } + + bool ManagerV1::ExportPdfFile(const std::string& devId, const std::string& fileName) + { + std::string filePath = GetFilePath(devId); + std::vector fileNameList = GetFileNameList(devId); + if (fileNameList.empty()) + { + return false; + } + + HGPdfImageWriter writer = NULL; + HGImgFmt_OpenPdfImageWriter(fileName.c_str(), &writer); + if (NULL == writer) + { + return false; + } + + bool ret = false; + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + HGImage img = NULL; + std::string fileName = filePath + fileNameList[i]; + HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); + if (NULL != img) + { + if (HGBASE_ERR_OK == HGImgFmt_SaveJpegImageToPdfImageWriter(writer, img, NULL)) + ret = true; + HGBase_DestroyImage(img); + } + } + + HGImgFmt_ClosePdfImageWriter(writer); + + if (!ret) + { + HGBase_DeleteFile(fileName.c_str()); + return false; + } + + return true; + } + + bool ManagerV1::ExportPdfFile(const std::string& devId, HGByte** data, HGUInt* size) + { + *data = NULL; + *size = 0; + if (m_scanning) + { + return false; + } + + HGChar tmpFileName[512]; + HGBase_GetTmpFileName(tmpFileName, 512); + ExportPdfFile(devId, tmpFileName); + + *data = GetBuffer(tmpFileName, size); + HGBase_DeleteFile(tmpFileName); + return (NULL != *data); + } + + bool ManagerV1::ExportTiff(const std::string& devId, std::string& imgBase64) + { + imgBase64.clear(); + if (m_scanning) + { + return false; + } + + HGByte* data = NULL; + HGUInt size = 0; + ExportTiffFile(devId, &data, &size); + if (NULL != data) + { + imgBase64 = GetBase64(data, size); + delete[] data; + } + + return !imgBase64.empty(); + } + + bool ManagerV1::ExportTiff(const std::string& devId, const std::string& fileName) + { + std::string filePath = GetFilePath(devId); + std::vector fileNameList = GetFileNameList(devId); + if (fileNameList.empty()) + { + return false; + } + + HGTiffWriter writer = NULL; + HGImgFmt_OpenTiffWriter(fileName.c_str(), &writer); + if (NULL == writer) + { + return false; + } + + bool ret = false; + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + HGImage img = NULL; + std::string fileName = filePath + fileNameList[i]; + HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); + if (NULL != img) + { + if (HGBASE_ERR_OK == HGImgFmt_SaveImageToTiffWriter(writer, img, NULL)) + ret = true; + HGBase_DestroyImage(img); + } + } + + HGImgFmt_CloseTiffWriter(writer); + + if (!ret) + { + HGBase_DeleteFile(fileName.c_str()); + return false; + } + + return true; + } + + bool ManagerV1::ExportTiffFile(const std::string& devId, HGByte** data, HGUInt* size) + { + *data = NULL; + *size = 0; + if (m_scanning) + { + return false; + } + + HGChar tmpFileName[512]; + HGBase_GetTmpFileName(tmpFileName, 512); + ExportTiff(devId, tmpFileName); + + *data = GetBuffer(tmpFileName, size); + HGBase_DeleteFile(tmpFileName); + return (NULL != *data); + } + + bool ManagerV1::ExportZip(const std::string& devId, std::string& imgBase64) + { + imgBase64.clear(); + if (m_scanning) + { + return false; + } + + HGByte* data = NULL; + HGUInt size = 0; + ExportZipFile(devId, &data, &size); + if (NULL != data) + { + imgBase64 = GetBase64(data, size); + delete[] data; + } + + return !imgBase64.empty(); + } + + bool ManagerV1::ExportZipFile(const std::string& devId, const std::string& fileName) + { + std::string filePath = GetFilePath(devId); + std::vector fileNameList = GetFileNameList(devId); + if (fileNameList.empty()) + { + return false; + } + + int error = 0; + zip* z = zip_open(StdStringToUtf8(fileName).c_str(), ZIP_CREATE | ZIP_TRUNCATE, &error); + if (NULL == z) + { + return false; + } + + bool ret = false; + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + std::string fileName = filePath + fileNameList[i]; + zip_source_t* s = zip_source_file(z, StdStringToUtf8(fileName).c_str(), 0, 0); + if (NULL != s) + { + if (zip_file_add(z, StdStringToUtf8(fileNameList[i]).c_str(), s, ZIP_FL_OVERWRITE) >= 0) + { + ret = true; + } + else + { + zip_source_free(s); + } + } + } + + zip_close(z); + z = NULL; + + if (!ret) + { + HGBase_DeleteFile(fileName.c_str()); + return false; + } + + return true; + } + + bool ManagerV1::ExportZipFile(const std::string& devId, HGByte** data, HGUInt* size) + { + *data = NULL; + *size = 0; + if (m_scanning) + { + return false; + } + + HGChar tmpFileName[512]; + HGBase_GetTmpFileName(tmpFileName, 512); + ExportZipFile(devId, tmpFileName); + + *data = GetBuffer(tmpFileName, size); + HGBase_DeleteFile(tmpFileName); + return (NULL != *data); + } + + bool ManagerV1::UploadImage(const UploadParam& uploadParam) + { + if (m_scanning) + { + return false; + } + + std::string devId; + GetCurDevId(devId); + + HGChar tmpFileName[512]; + HGBase_GetTmpFileName(tmpFileName, 512); + if (0 == uploadParam.format) + { + strcat(tmpFileName, ".ofd"); + ExportOfdFile(devId, true, tmpFileName); + } + else if (1 == uploadParam.format) + { + strcat(tmpFileName, ".pdf"); + ExportPdfFile(devId, tmpFileName); + } + else + { + strcat(tmpFileName, ".zip"); + ExportZipFile(devId, tmpFileName); + } + + bool ret = false; + if (0 == uploadParam.uploadMode) // HTTP + { + ret = HTTPUpload(tmpFileName, uploadParam.httpUrl, uploadParam.fileName, uploadParam.httpMethod, + uploadParam.header, uploadParam.param); + } + else if (1 == uploadParam.uploadMode) // FTP + { + ret = FTPUpload(tmpFileName, uploadParam.ftpUrl, uploadParam.ftpPort, uploadParam.ftpPath, + uploadParam.ftpUser, uploadParam.ftpPassword, uploadParam.ftpMode); + } + + HGBase_DeleteFile(tmpFileName); + return ret; + } + + bool ManagerV1::SaveImage(const std::string& devId, const std::string& imgName, const std::string& imgBase64) + { + if (m_scanning) + { + return false; + } + + std::string filePath = GetFilePath(devId); + std::string fileName = filePath + imgName; + + size_t pos = imgBase64.find(","); + if (std::string::npos != pos) + return SaveBase64(fileName, imgBase64.c_str() + pos + 1); + else + return SaveBase64(fileName, imgBase64.c_str()); + } + + bool ManagerV1::DeleteImage(const std::string& devId, const std::string& imgName) + { + if (m_scanning) + { + return false; + } + + std::string filePath = GetFilePath(devId); + std::string fileName = filePath + imgName; + + bool ret = false; + if (HGBASE_ERR_OK == HGBase_DeleteFile(fileName.c_str())) + { + std::vector fileNameList = GetFileNameList(devId); + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + if (imgName == fileNameList[i]) + { + fileNameList.erase(fileNameList.begin() + i); + break; + } + } + + SaveFileNameList(devId, fileNameList); + ret = true; + } + + return ret; + } + + bool ManagerV1::DeleteAllImage(const std::string& devId) + { + if (m_scanning) + { + return false; + } + + std::string filePath = GetFilePath(devId); + std::vector fileNameList = GetFileNameList(devId); + + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + std::string fileName = filePath + fileNameList[i]; + HGBase_DeleteFile(fileName.c_str()); + } + fileNameList.clear(); + + SaveFileNameList(devId, fileNameList); + return true; + } + + bool ManagerV1::MergeImage(const std::string& devId, bool isHorizontal, const std::vector& imgIndexList, + std::string& imgName, std::string& imgBase64) + { + imgName.clear(); + imgBase64.clear(); + if (m_scanning) + { + return false; + } + + std::string filePath = GetFilePath(devId); + std::vector fileNameList = GetFileNameList(devId); + + std::vector imgList; + for (int i = 0; i < (int)imgIndexList.size(); ++i) + { + int index = imgIndexList[i]; + if (index >= 0 && index < (int)fileNameList.size()) + { + std::string fileName = filePath + fileNameList[index]; + HGImage img = NULL; + HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); + if (NULL != img) + imgList.push_back(img); + } + } + + HGUInt width = 0, height = 0; + for (int i = 0; i < (int)imgList.size(); ++i) + { + HGImageInfo imgInfo; + HGBase_GetImageInfo(imgList[i], &imgInfo); + if (isHorizontal) + { + width += imgInfo.width; + if (imgInfo.height > height) + height = imgInfo.height; + } + else + { + height += imgInfo.height; + if (imgInfo.width > width) + width = imgInfo.width; + } + } + + if (width > 0 && height > 0) + { + HGImage img = NULL; + HGBase_CreateImage(width, height, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); + if (NULL != img) + { + HGUInt x = 0, y = 0; + for (int i = 0; i < (int)imgList.size(); ++i) + { + HGImageInfo imgInfo; + HGBase_GetImageInfo(imgList[i], &imgInfo); + + HGImageRoi roi = { x, y, x + imgInfo.width, y + imgInfo.height }; + HGBase_SetImageROI(img, &roi); + HGBase_CopyImage(imgList[i], img); + HGBase_ResetImageROI(img); + + if (isHorizontal) + x += imgInfo.width; + else + y += imgInfo.height; + } + + int maxIndex = 0; + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + int index = atoi(fileNameList[i].c_str()); + if (index > maxIndex) + maxIndex = index; + } + + HGChar name[256]; + sprintf(name, "%d.%s", maxIndex + 1, m_devParam.format.c_str()); + imgName = name; + + HGBase_CreateDir(filePath.c_str()); + std::string fileName = filePath + imgName; + HGImgFmt_SaveImage(img, 0, NULL, fileName.c_str()); + + fileNameList.push_back(imgName); + SaveFileNameList(devId, fileNameList); + + imgBase64 = "data:image/jpeg;base64,"; + imgBase64 += GetBase64(img); + + HGBase_DestroyImage(img); + } + } + + for (int i = 0; i < (int)imgList.size(); ++i) + { + HGBase_DestroyImage(imgList[i]); + } + + return true; + } + + static bool LowerSort(const std::string& str1, const std::string& str2) + { + return atoi(str1.c_str()) < atoi(str2.c_str()); + } + + bool ManagerV1::BookSort(const std::string& devId, std::vector& imgNameList, + std::vector& imgBase64List) + { + imgNameList.clear(); + imgBase64List.clear(); + if (m_scanning) + { + return false; + } + + std::vector fileNameList = GetFileNameList(devId); + std::sort(fileNameList.begin(), fileNameList.end(), LowerSort); + SaveFileNameList(devId, fileNameList); + + return GetImageByDevId(devId, imgNameList, imgBase64List); + } + + bool ManagerV1::ExchangeImage(const std::string& devId, int index1, int index2) + { + if (m_scanning) + { + return false; + } + + std::string filePath = GetFilePath(devId); + std::vector fileNameList = GetFileNameList(devId); + if (index1 < 0 || index1 >= (int)fileNameList.size() || index2 < 0 || index2 >= (int)fileNameList.size()) + return false; + + std::string imgName1 = fileNameList[index1]; + std::string imgName2 = fileNameList[index2]; + fileNameList[index1] = imgName2; + fileNameList[index2] = imgName1; + + SaveFileNameList(devId, fileNameList); + return true; + } + + bool ManagerV1::GetLastBetch(std::string& devId) + { + devId.clear(); + if (m_scanning) + { + return false; + } + + devId = m_devName; + return true; + } + + bool ManagerV1::ResetPatchIndex() + { + if (m_scanning) + { + return false; + } + + return true; + } + + bool ManagerV1::SplitImage(const std::string& devId, const std::string& imgName, bool isHorizontal, int x1, int y1, int x2, int y2, + std::string& imgName1, std::string& imgBase64_1, std::string& imgName2, std::string& imgBase64_2) + { + imgName1.clear(); + imgBase64_1.clear(); + imgName2.clear(); + imgBase64_2.clear(); + if (m_scanning) + { + return false; + } + + std::string filePath = GetFilePath(devId); + std::string fileName = filePath + imgName; + + HGImage img = NULL; + HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); + if (NULL != img) + { + HGImageInfo imgInfo; + HGBase_GetImageInfo(img, &imgInfo); + + for (int i = 0; i < 2; ++i) + { + HGUInt newWidth = isHorizontal ? x1 : imgInfo.width; + if (1 == i) + newWidth = isHorizontal ? (imgInfo.width - x1) : imgInfo.width; + + HGUInt newHeight = isHorizontal ? imgInfo.height : y1; + if (1 == i) + newHeight = isHorizontal ? imgInfo.height : (imgInfo.height - y1); + + HGImage newImg = NULL; + HGBase_CreateImage(newWidth, newHeight, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &newImg); + if (NULL != newImg) + { + HGImageRoi roi; + + if (isHorizontal) + { + roi.left = 0; + roi.top = 0; + roi.right = x1; + roi.bottom = imgInfo.height; + + if (1 == i) + { + roi.left = x1; + roi.right = imgInfo.width; + } + } + else + { + roi.left = 0; + roi.top = 0; + roi.right = imgInfo.width; + roi.bottom = y1; + + if (1 == i) + { + roi.top = y1; + roi.bottom = imgInfo.height; + } + } + + if (1 == i) + { + roi.left = x1; + roi.right = imgInfo.width; + } + + HGBase_SetImageROI(img, &roi); + HGBase_CopyImage(img, newImg); + HGBase_ResetImageROI(img); + + std::vector fileNameList = GetFileNameList(devId); + + int maxIndex = 0; + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + int index = atoi(fileNameList[i].c_str()); + if (index > maxIndex) + maxIndex = index; + } + + HGChar name[256]; + sprintf(name, "%d.%s", maxIndex + 1, m_devParam.format.c_str()); + std::string imgName = name; + + HGBase_CreateDir(filePath.c_str()); + std::string fileName = filePath + imgName; + HGImgFmt_SaveImage(newImg, 0, NULL, fileName.c_str()); + + fileNameList.push_back(imgName); + SaveFileNameList(devId, fileNameList); + + std::string imgBase64 = "data:image/jpeg;base64,"; + imgBase64 += GetBase64(newImg); + + if (0 == i) + { + imgName1 = imgName; + imgBase64_1 = imgBase64; + } + else + { + imgName2 = imgName; + imgBase64_2 = imgBase64; + } + + HGBase_DestroyImage(newImg); + } + } + + HGBase_DestroyImage(img); + } + + return true; + } + + bool ManagerV1::GetDevSerialNo(const std::string& devId, std::string& serialNo) + { + serialNo.clear(); + if (m_scanning) + { + return false; + } + + serialNo = devId; + return true; + } + + bool ManagerV1::GetImageBase64(const std::string& devId, const std::string& imgName, std::string& imgBase64) + { + imgBase64.clear(); + if (m_scanning) + { + return false; + } + + std::string filePath = GetFilePath(devId); + std::string fileName = filePath + imgName; + + HGImage img = NULL; + HGImgFmt_LoadImage(fileName.c_str(), 0, NULL, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); + if (NULL != img) + { + imgBase64 = "data:image/jpeg;base64,"; + imgBase64 += GetBase64(img); + HGBase_DestroyImage(img); + } + + return true; + } + + std::string ManagerV1::GetFilePath(const std::string& devId) + { + HGChar docsPath[256]; + HGBase_GetDocumentsPath(docsPath, 256); + HGChar imgPath[512]; + sprintf(imgPath, "%s%s/", docsPath, Utf8ToStdString(devId).c_str()); + HGChar stdImgPath[512]; + HGBase_StandardiseFileName(imgPath, stdImgPath, 512); + + return stdImgPath; + } + + std::vector ManagerV1::GetFileNameList(const std::string& devId) + { + std::vector fileNameList; + + std::string filePath = GetFilePath(devId); + std::string cfgName = filePath + "images.txt"; + FILE* file = fopen(cfgName.c_str(), "r"); + if (NULL != file) + { + while (feof(file) == 0) + { + char lineContent[256] = { 0 }; + if (NULL == fgets(lineContent, 256, file) || '\n' == *lineContent) + { + continue; + } + + if (lineContent[strlen(lineContent) - 1] == '\n') + lineContent[strlen(lineContent) - 1] = 0; + + fileNameList.push_back(lineContent); + } + + fclose(file); + } + + return fileNameList; + } + + bool ManagerV1::SaveFileNameList(const std::string& devId, const std::vector& fileNameList) + { + bool ret = false; + + std::string filePath = GetFilePath(devId); + std::string cfgName = filePath + "images.txt"; + FILE* file = fopen(cfgName.c_str(), "w"); + if (NULL != file) + { + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + fwrite(fileNameList[i].c_str(), 1, fileNameList[i].size(), file); + fwrite("\n", 1, strlen("\n"), file); + } + + fclose(file); + ret = true; + } + + return ret; + } + + std::string ManagerV1::GetBase64(HGImage image) + { + std::string strBase64; + + if (NULL != image) + { + HGBuffer buffer = NULL; + HGImgFmt_SaveJpegImageToBuffer(image, NULL, &buffer); + if (NULL != buffer) + { + HGByte* data; + HGBase_GetBufferData(buffer, &data); + HGUSize size; + HGBase_GetBufferSize(buffer, &size); + + HGSize base64Size = 0; + HGBase_Base64Encode(data, size, NULL, &base64Size); + uint8_t* base64 = new uint8_t[base64Size + 1]; + HGBase_Base64Encode(data, size, base64, &base64Size); + base64[base64Size] = 0; + strBase64 = (const char*)base64; + delete[] base64; + + HGBase_DestroyBuffer(buffer); + } + } + + return strBase64; + } + + std::string ManagerV1::GetBase64(const HGByte* data, HGUInt size) + { + std::string strBase64; + + if (NULL != data && 0 != size) + { + HGSize base64Size = 0; + HGBase_Base64Encode(data, size, NULL, &base64Size); + uint8_t* base64 = new uint8_t[base64Size + 1]; + HGBase_Base64Encode(data, size, base64, &base64Size); + base64[base64Size] = 0; + strBase64 = (const char*)base64; + delete[] base64; + } + + return strBase64; + } + + std::string ManagerV1::GetBase64(const std::string& fileName) + { + std::string strBase64; + + FILE* file = fopen(fileName.c_str(), "rb"); + if (NULL != file) + { + fseek(file, 0, SEEK_END); + long size = ftell(file); + fseek(file, 0, SEEK_SET); + + if (size > 0) + { + HGByte* data = new HGByte[size]; + long readLen = (long)fread(data, 1, size, file); + if (readLen == size) + { + HGSize base64Size = 0; + HGBase_Base64Encode(data, size, NULL, &base64Size); + uint8_t* base64 = new uint8_t[base64Size + 1]; + HGBase_Base64Encode(data, size, base64, &base64Size); + base64[base64Size] = 0; + strBase64 = (const char*)base64; + delete[] base64; + } + + delete[] data; + } + + fclose(file); + } + + return strBase64; + } + + HGByte* ManagerV1::GetBuffer(const std::string& fileName, HGUInt* size) + { + HGByte* data = NULL; + *size = 0; + + FILE* file = fopen(fileName.c_str(), "rb"); + if (NULL != file) + { + fseek(file, 0, SEEK_END); + *size = ftell(file); + fseek(file, 0, SEEK_SET); + + if (*size > 0) + { + data = new HGByte[*size]; + + HGUInt readLen = (HGUInt)fread(data, 1, *size, file); + if (readLen != *size) + { + delete[] data; + data = NULL; + *size = 0; + } + } + + fclose(file); + } + + return data; + } + + bool ManagerV1::SaveBase64(const std::string& fileName, const char* base64) + { + if (NULL == base64 || 0 == *base64) + return false; + + HGUInt base64Size = (HGUInt)strlen(base64); + + bool ret = false; + FILE* file = fopen(fileName.c_str(), "wb"); + if (NULL != file) + { + HGSize size = 0; + HGBase_Base64Decode((const HGByte*)base64, (HGSize)base64Size, NULL, &size); + uint8_t* data = new HGByte[size]; + HGBase_Base64Decode((const HGByte*)base64, (HGSize)base64Size, data, &size); + + size_t writeLen = fwrite(data, 1, size, file); + if (writeLen == (size_t)size) + ret = true; + + delete[] data; + fclose(file); + } + + return ret; + } + + static std::string MakePreFileData(const char* pszBoundary, const char* pszRemoteFileName) + { + char data[512]; + sprintf(data, "--%s\r\nContent-Disposition: form-data; name=\"filedata\"; filename=\"%s\"\r\n", + pszBoundary, pszRemoteFileName); + std::string ret = data; + ret += "Content-Type: application/octet-stream; charset=utf-8\r\n"; + ret += "Content-Transfer-Encoding: binary\r\n"; + ret += "\r\n"; + return ret; + } + + static std::string MakePostFileData(const char* pszBoundary) + { + char data[512]; + sprintf(data, "\r\n--%s\r\nContent-Disposition: form-data; name=\"submitted\"\r\n\r\nsubmit\r\n--%s--\r\n", pszBoundary, pszBoundary); + return data; + } + + static void ParseHttpURL(const std::string& url, std::string& addr, int& port, std::string& path) + { + addr.clear(); + port = 0; + path.clear(); + + std::string url2; + std::string::size_type pos = url.find("//"); + if (std::string::npos != pos) + { + std::string protocal = url.substr(0, pos); + if (protocal != "http:") + { + return; + } + + url2 = url.substr(pos + 2); + } + else + { + url2 = url; + } + + std::string addr_port; + pos = url2.find("/"); + if (std::string::npos != pos) + { + addr_port = url2.substr(0, pos); + path = url2.substr(pos); + } + else + { + addr_port = url2; + } + + pos = addr_port.find(":"); + if (std::string::npos != pos) + { + addr = addr_port.substr(0, pos); + port = atoi(addr_port.substr(pos + 1).c_str()); + } + else + { + addr = addr_port; + port = 80; + } + } + + bool ManagerV1::HTTPUpload(const std::string& localFileName, const std::string& httpUrl, const std::string& remoteFileName, + const std::string& httpMethod, const std::string& header, const std::string& param) + { + unsigned char* fileData = NULL; + long fileSize = 0; + FILE* file = fopen(localFileName.c_str(), "rb"); + if (NULL != file) + { + fseek(file, 0, SEEK_END); + fileSize = ftell(file); + fseek(file, 0, SEEK_SET); + + if (0 != fileSize) + { + fileData = new unsigned char[fileSize]; + fread(fileData, 1, fileSize, file); + } + + fclose(file); + } + + if (NULL == fileData) + { + return false; + } + + std::string addr; + int port; + std::string path; + ParseHttpURL(httpUrl, addr, port, path); + +#if defined(HG_CMP_MSC) + SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0); + assert(INVALID_SOCKET != sockClient); +#else + int sockClient = socket(AF_INET, SOCK_STREAM, 0); + assert(-1 != sockClient); +#endif + +#if defined(HG_CMP_MSC) + u_long ul = 1; // Ϊ + ioctlsocket(sockClient, FIONBIO, &ul); +#else + ioctl(sockClient, FIONBIO, 1); +#endif + +#if defined(HG_CMP_MSC) + SOCKADDR_IN addrServer = { 0 }; + addrServer.sin_addr.S_un.S_addr = inet_addr(addr.c_str()); + addrServer.sin_family = AF_INET; + addrServer.sin_port = htons(port); + if (0 != connect(sockClient, (SOCKADDR*)&addrServer, sizeof(SOCKADDR_IN))) +#else + struct sockaddr_in addrServer = { 0 }; + addrServer.sin_addr.s_addr = inet_addr(addr.c_str()); + addrServer.sin_family = AF_INET; + addrServer.sin_port = htons(port); + if (0 != connect(sockClient, (struct sockaddr*)&addrServer, sizeof(addrServer))) +#endif + { + fd_set fds; + FD_ZERO(&fds); + FD_SET(sockClient, &fds); + timeval tm; + tm.tv_sec = 1; + tm.tv_usec = 0; + + if (select((int)(sockClient + 1), NULL, &fds, NULL, &tm) <= 0) + { +#if defined(HG_CMP_MSC) + closesocket(sockClient); +#else + close(sockClient); +#endif + delete[] fileData; + return false; + } + + if (!FD_ISSET(sockClient, &fds)) + { +#if defined(HG_CMP_MSC) + closesocket(sockClient); +#else + close(sockClient); +#endif + delete[] fileData; + return false; + } + } + +#if defined(HG_CMP_MSC) + ul = 0; // Ϊ + ioctlsocket(sockClient, FIONBIO, &ul); +#else + ioctl(sockClient, FIONBIO, 0); +#endif + + char remoteName[256]; + HGBase_GetFileName(localFileName.c_str(), remoteName, 256); + + bool ret = false; + + const char* pszBoundary = "---------------------------7d33a816d302b6"; + + std::string strPreFileData = MakePreFileData(pszBoundary, remoteName); + std::string strPostFileData = MakePostFileData(pszBoundary); + + char hostname[128]; + gethostname(hostname, 128); + + std::string head; + char data[512]; + sprintf(data, "POST %s HTTP/1.1\r\nHost: %s\r\n", path.c_str(), hostname); + head += data; + sprintf(data, "Content-Type: multipart/form-data; boundary=%s\r\n", pszBoundary); + head += data; + sprintf(data, "Content-Length: %d\r\n\r\n", (int)strPreFileData.size() + (int)fileSize + (int)strPostFileData.size()); + head += data; + + send(sockClient, head.c_str(), (int)head.size(), 0); + send(sockClient, strPreFileData.c_str(), (int)strPreFileData.size(), 0); + send(sockClient, (const char*)fileData, (int)fileSize, 0); + send(sockClient, strPostFileData.c_str(), (int)strPostFileData.size(), 0); + + char recvBuf[2048] = { 0 }; + recv(sockClient, recvBuf, 2048, 0); + + std::string strRecv(recvBuf); + std::string::size_type pos = strRecv.find("\r\n"); + if (pos != std::string::npos) + { + std::string head = strRecv.substr(0, pos); + if (head.find("200") != std::string::npos) + { + ret = true; + } + } + +#if defined(HG_CMP_MSC) + closesocket(sockClient); +#else + close(sockClient); +#endif + delete[] fileData; + return ret; + } + + static size_t read_callback(char* ptr, size_t size, size_t nmemb, void* stream) + { + unsigned long nread; + /* in real-world cases, this would probably get this data differently + as this fread() stuff is exactly what the library already would do + by default internally */ + size_t retcode = fread(ptr, size, nmemb, (FILE*)stream); + + if (retcode > 0) + { + nread = (unsigned long)retcode; + //fprintf(stderr, "*** We read %lu bytes from file\n", nread); + } + + return retcode; + } + + bool ManagerV1::FTPUpload(const std::string& localFileName, const std::string& ftpUrl, int ftpPort, const std::string& ftpPath, + const std::string& ftpUser, const std::string& ftpPassword, int ftpMode) + { + FILE* file = fopen(localFileName.c_str(), "rb"); + if (NULL == file) + { + return false; + } + + bool ret = false; + fseek(file, 0, SEEK_END); + long fsize = ftell(file); + fseek(file, 0, SEEK_SET); + + curl_global_init(CURL_GLOBAL_ALL); + + /* get a curl handle */ + CURL* curl = curl_easy_init(); + if (NULL != curl) + { + char tmpName[256]; + HGBase_GetUuid(tmpName, 256); + char remoteName[256]; + HGBase_GetFileName(localFileName.c_str(), remoteName, 256); + + char ftp_rnfr[512]; + sprintf(ftp_rnfr, "RNFR %s", tmpName); + char ftp_rnto[512]; + sprintf(ftp_rnto, "RNTO %s", remoteName); + + struct curl_slist* headerlist = NULL; + headerlist = curl_slist_append(headerlist, ftp_rnfr); + headerlist = curl_slist_append(headerlist, ftp_rnto); + + /* we want to use our own read function */ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + char url[512]; + if (!ftpUser.empty() && !ftpPassword.empty()) + { + sprintf(url, "ftp://%s:%s@%s:%d%s/%s", ftpUser.c_str(), ftpPassword.c_str(), + ftpUrl.c_str(), ftpPort, ftpPath.c_str(), tmpName); + } + else + { + sprintf(url, "ftp://%s:%d%s/%s", ftpUrl.c_str(), ftpPort, ftpPath.c_str(), tmpName); + } + curl_easy_setopt(curl, CURLOPT_URL, url); + + curl_easy_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS, 1); + + /* pass in that last of FTP commands to run after the transfer */ + curl_easy_setopt(curl, CURLOPT_POSTQUOTE, headerlist); + + /* now specify which file to upload */ + curl_easy_setopt(curl, CURLOPT_READDATA, file); + + /* Set the size of the file to upload (optional). If you give a *_LARGE + option you MUST make sure that the type of the passed-in argument is a + curl_off_t. If you use CURLOPT_INFILESIZE (without _LARGE) you must + make sure that to pass in a type 'long' argument. */ + curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fsize); + + /* Now run off and do what you have been told! */ + CURLcode res = curl_easy_perform(curl); + /* Check for errors */ + if (res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); + else + ret = true; + + /* clean up the FTP commands list */ + curl_slist_free_all(headerlist); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + fclose(file); /* close the local file */ + + curl_global_cleanup(); + return ret; + } + + int ManagerV1::sane_ex_callback(SANE_Handle hdev, int code, void* data, unsigned int* len, void* param) + { + (void)hdev; + (void)len; + + ManagerV1* p = (ManagerV1*)param; + switch (code) + { + case SANE_EVENT_DEVICE_ARRIVED: + { + SANE_Device* sane_dev = (SANE_Device*)data; + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "device arrive, name=%s", Utf8ToStdString(sane_dev->name).c_str()); + + HGBase_EnterLock(p->m_lock); + if (NULL != p->m_scanEvent) + p->m_scanEvent(SCANEVENT_ARRIVE, (void*)sane_dev->name, (void*)0, p->m_scanParam); + HGBase_LeaveLock(p->m_lock); + + OpenDevParam* openDevParam = new OpenDevParam; + openDevParam->mgr = p; + openDevParam->devName = sane_dev->name; + + HGMsg msg; + msg.id = MSGID_OPEN_DEVICE; + msg.data = openDevParam; + if (HGBASE_ERR_OK != HGBase_PostPumpMessage(p->m_msgPump, &msg)) + { + delete openDevParam; + } + } + break; + case SANE_EVENT_DEVICE_LEFT: + { + SANE_Device* sane_dev = (SANE_Device*)data; + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "device remove, name=%s", Utf8ToStdString(sane_dev->name).c_str()); + + HGBase_EnterLock(p->m_lock); + if (NULL != p->m_scanEvent) + p->m_scanEvent(SCANEVENT_REMOVE, (void*)sane_dev->name, (void*)0, p->m_scanParam); + HGBase_LeaveLock(p->m_lock); + + CloseDevParam* closeDevParam = new CloseDevParam; + closeDevParam->mgr = p; + closeDevParam->devName = sane_dev->name; + + HGMsg msg; + msg.id = MSGID_CLOSE_DEVICE; + msg.data = closeDevParam; + if (HGBASE_ERR_OK != HGBase_PostPumpMessage(p->m_msgPump, &msg)) + { + delete closeDevParam; + } + } + break; + case SANE_EVENT_STATUS: + { + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "SANE_EVENT_STATUS, msg=%s", Utf8ToStdString((char*)data).c_str()); + + HGBase_EnterLock(p->m_lock); + if (NULL != p->m_scanEvent) + p->m_scanEvent(SCANEVENT_STATUS, (void*)data, (void*)0, p->m_scanParam); + HGBase_LeaveLock(p->m_lock); + } + break; + case SANE_EVENT_ERROR: + { + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "SANE_EVENT_ERROR, msg=%s", Utf8ToStdString((char*)data).c_str()); + + HGBase_EnterLock(p->m_lock); + if (NULL != p->m_scanEvent) + p->m_scanEvent(SCANEVENT_ERROR, (void*)data, (void*)0, p->m_scanParam); + HGBase_LeaveLock(p->m_lock); + } + break; + case SANE_EVENT_WORKING: + { + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "SANE_EVENT_WORKING, msg=%s", Utf8ToStdString((char*)data).c_str()); + + HGBase_EnterLock(p->m_lock); + if (NULL != p->m_scanEvent) + p->m_scanEvent(SCANEVENT_WORKING, (void*)data, (void*)0, p->m_scanParam); + HGBase_LeaveLock(p->m_lock); + } + break; + case SANE_EVENT_IMAGE_OK: + { + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "SANE_EVENT_IMAGE_OK"); + + SANE_Image* sane_img = (SANE_Image*)data; + + HGUInt imgType = 0; + if (sane_img->header.format == SANE_FRAME_GRAY) + imgType = HGBASE_IMGTYPE_GRAY; + else if (sane_img->header.format == SANE_FRAME_RGB) + imgType = HGBASE_IMGTYPE_RGB; + + HGByte* data = sane_img->data; + HGImageInfo imgInfo = { (HGUInt)sane_img->header.pixels_per_line, (HGUInt)sane_img->header.lines, + imgType, (HGUInt)sane_img->header.bytes_per_line, HGBASE_IMGORIGIN_TOP }; + + HGImage img = NULL; + HGBase_CreateImageFromData(data, &imgInfo, nullptr, HGBASE_IMGTYPE_RGB, HGBASE_IMGORIGIN_TOP, &img); + if (NULL != img) + { + std::string filePath = GetFilePath(p->m_devName); + std::vector fileNameList = GetFileNameList(p->m_devName); + + int maxIndex = 0; + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + int index = atoi(fileNameList[i].c_str()); + if (index > maxIndex) + maxIndex = index; + } + + HGChar name[256]; + sprintf(name, "%d.%s", maxIndex + 1, p->m_devParam.format.c_str()); + std::string imgName = name; + + HGBase_CreateDir(filePath.c_str()); + std::string fileName = filePath + imgName; + HGImgFmt_SaveImage(img, 0, NULL, fileName.c_str()); + + if (0 == p->m_devParam.uploadMode) // HTTP + { + HTTPUpload(fileName, p->m_devParam.httpUrl, p->m_devParam.fileName, p->m_devParam.httpMethod, + p->m_devParam.header, p->m_devParam.param); + } + else if (1 == p->m_devParam.uploadMode) // FTP + { + FTPUpload(fileName, p->m_devParam.ftpUrl, p->m_devParam.ftpPort, p->m_devParam.ftpPath, + p->m_devParam.ftpUser, p->m_devParam.ftpPassword, p->m_devParam.ftpMode); + } + + if (p->m_scanIsInsert) + { + int index = -1; + for (int i = 0; i < (int)fileNameList.size(); ++i) + { + if (fileNameList[i] == p->m_scanInsertImgName) + { + index = i; + break; + } + } + + if (-1 != index) + { + fileNameList.insert(fileNameList.begin() + index, imgName); + } + else + { + fileNameList.push_back(imgName); + } + } + else + { + fileNameList.push_back(imgName); + } + + SaveFileNameList(p->m_devName, fileNameList); + + std::string imgBase64 = "data:image/jpeg;base64,"; + imgBase64 += GetBase64(img); + + HGBase_EnterLock(p->m_lock); + if (NULL != p->m_scanEvent) + p->m_scanEvent(SCANEVENT_IMAGE, (void*)imgName.c_str(), (void*)imgBase64.c_str(), p->m_scanParam); + HGBase_LeaveLock(p->m_lock); + + HGBase_DestroyImage(img); + } + } + break; + case SANE_EVENT_SCAN_FINISHED: + { + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "SANE_EVENT_SCAN_FINISHED, msg=%s", Utf8ToStdString((char*)data).c_str()); + + HGBase_EnterLock(p->m_lock); + if (NULL != p->m_scanEvent) + p->m_scanEvent(SCANEVENT_FINISH, (void*)data, (void*)0, p->m_scanParam); + HGBase_LeaveLock(p->m_lock); + + ScanFinishParam* scanFinishParam = new ScanFinishParam; + scanFinishParam->mgr = p; + + HGMsg msg; + msg.id = MSGID_SCAN_FINISH; + msg.data = scanFinishParam; + if (HGBASE_ERR_OK != HGBase_PostPumpMessage(p->m_msgPump, &msg)) + { + delete scanFinishParam; + } + } + break; + } + + return 0; + } +} \ No newline at end of file diff --git a/sdk/webservice/ManagerV1.h b/sdk/webservice/ManagerV1.h new file mode 100644 index 00000000..9289a6d0 --- /dev/null +++ b/sdk/webservice/ManagerV1.h @@ -0,0 +1,194 @@ +#pragma once + +#include "base/HGDef.h" +#include "base/HGInc.h" +#include "base/HGLock.h" +#include "base/HGImage.h" +#include "base/HGMsgPump.h" +#include "sane/sane_ex.h" +#include "sane/sane_option_definitions.h" +#include "Manager.h" +#include "Msg.h" +#include + +namespace ver_1 +{ + enum + { + SCANEVENT_ARRIVE = 1L, + SCANEVENT_REMOVE, + SCANEVENT_STATUS, + SCANEVENT_WORKING, + SCANEVENT_IMAGE, + SCANEVENT_FINISH, + SCANEVENT_ERROR + }; + + struct DevParam + { + DevParam(); + ~DevParam(); + + void Reset(); + void Load(const std::string& cfgPath); + void Save(const std::string& cfgPath); + + std::string device; // 设备名称,默认null + bool autofeeder; // 自动进纸,默认true + int pixel; // 扫描模式 0:黑白 1:灰度 2:彩色,默认1 + bool white; // 丢弃空白页,默认false + int discardBlankThre; // 跳过空白页阈值 1­-100 默认值5 + bool single; // 单页扫描,默认false + std::string format; // 输出格式 jpg png bmp tiff pdf ofd,默认jpg + int resolution; // 扫描分辨率 范围 100­-600 默认值200 + int orentation; // 图片旋转 0:原图 90:度 180:旋转180度 270:旋转270度,默认0 + std::string paperType; // 扫描幅面 A3:A3幅面 Auto:自适应幅面 A4:A4幅面,默认Auto + int splitImage; // 图像分割 0:disable 1:垂直分割 2: 水平分割,默认0 + bool noiseDetachEnable; // 去除噪点,默认true + int noiseDetach; // 噪点阈值 范围:10­-50 默认值15 + + int uploadMode; // 是否边扫边上传 0:http 1:ftp 2: 不上传,默认2 + std::string httpUrl; // 上传地址,默认null + std::string fileName; // 接收文件参数名,默认null + std::string httpMethod; // 上传方式 GET POST PUT,默认null + std::string header; // 请求头,默认null + std::string param; // 参数 json格式,默认null + std::string ftpUrl; // ftp 地址,默认null + std::string ftpPath; // 路径,默认/images + std::string ftpUser; // ftp 用户名,默认null + std::string ftpPassword; // ftp 密码,默认null + int ftpPort; // 端口号,默认21 + int ftpMode; // 连接模式 1:主动 2:被动,默认2 + }; + + struct UploadParam + { + UploadParam() + { + uploadMode = 2; + ftpPort = 21; + ftpMode = 2; + format = 2; + } + + int uploadMode; // 上传模式 0:http 1:ftp 默认0 + std::string httpUrl; // 上传地址,默认null + std::string fileName; // 接收文件参数名,默认null + std::string httpMethod; // 上传方式 GET POST PUT,默认null + std::string header; // 请求头,默认null + std::string param; // 参数 json格式,默认null + std::string ftpUrl; // ftp 地址,默认null + std::string ftpPath; // 路径,默认/images + std::string ftpUser; // ftp 用户名,默认null + std::string ftpPassword; // ftp 密码,默认null + int ftpPort; // 端口号,默认21 + int ftpMode; // 连接模式 1:主动 2:被动,默认2 + int format; // 上传格式 0: ofd 1: pdf 2: zip, 默认2 + }; + + typedef void (*ScanEvent)(HGUInt event, void* value1, void* value2, void* param); + + class ManagerV1 : public Manager + { + public: + ManagerV1(HGMsgPump msgPump); + virtual ~ManagerV1(); + + // 打开设备 + void OpenDev(const OpenDevParam* param); + // 关闭设备 + void CloseDev(const CloseDevParam* param); + // 扫描完成 + void ScanFinish(const ScanFinishParam* param); + + // 设置回调 + void SetScanEvent(ScanEvent event, void* param); + // 清理回调 + void ResetScanEvent(); + // 扫描 + bool Scan(const std::string& insertImgName, bool isInsert); + // 停止扫描 + bool StopScan(); + // 获取当前连接的设备ID + bool GetCurDevId(std::string& devId); + // 获取连接的设备名列表 + bool GetDevNames(std::vector& devNameList); + // 获取上次的扫描结果 + bool GetImageByDevId(const std::string& devId, std::vector& imgNameList, + std::vector& imgBase64List); + // 获取配置参数 + bool GetDevParam(const std::string& devId, DevParam& devParam); + // 设置配置参数 + bool SetDevParam(const std::string& devId, const DevParam& devParam); + // 生成OFD + bool ExportOfd(const std::string& devId, bool isAuto, std::string& imgBase64); + bool ExportOfdFile(const std::string& devId, bool isAuto, const std::string& fileName); + bool ExportOfdFile(const std::string& devId, bool isAuto, HGByte** data, HGUInt* size); + // 生成PDF + bool ExportPdf(const std::string& devId, std::string& imgBase64); + bool ExportPdfFile(const std::string& devId, const std::string& fileName); + bool ExportPdfFile(const std::string& devId, HGByte** data, HGUInt* size); + // 生成TIFF + bool ExportTiff(const std::string& devId, std::string& imgBase64); + bool ExportTiff(const std::string& devId, const std::string& fileName); + bool ExportTiffFile(const std::string& devId, HGByte** data, HGUInt* size); + // 生成ZIP + bool ExportZip(const std::string& devId, std::string& imgBase64); + bool ExportZipFile(const std::string& devId, const std::string& fileName); + bool ExportZipFile(const std::string& devId, HGByte** data, HGUInt* size); + // 上传图像 + bool UploadImage(const UploadParam& uploadParam); + // 保存图片 + bool SaveImage(const std::string& devId, const std::string& imgName, const std::string& imgBase64); + // 删除图片 + bool DeleteImage(const std::string& devId, const std::string& imgName); + // 删除所有图片 + bool DeleteAllImage(const std::string& devId); + // 图像合并 + bool MergeImage(const std::string& devId, bool isHorizontal, const std::vector& imgIndexList, + std::string& imgName, std::string& imgBase64); + // 自动排序 + bool BookSort(const std::string& devId, std::vector& imgNameList, + std::vector& imgBase64List); + // 交换文件 + bool ExchangeImage(const std::string& devId, int index1, int index2); + // 获取最后批次 + bool GetLastBetch(std::string& devId); + // 重置索引 + bool ResetPatchIndex(); + // 拆分图像 + bool SplitImage(const std::string& devId, const std::string& imgName, bool isHorizontal, int x1, int y1, int x2, int y2, + std::string& imgName1, std::string& imgBase64_1, std::string& imgName2, std::string& imgBase64_2); + // 获取设备序列号 + bool GetDevSerialNo(const std::string& devId, std::string& serialNo); + // 获取图像Base64 + bool GetImageBase64(const std::string& devId, const std::string& imgName, std::string& imgBase64); + + private: + static std::string GetFilePath(const std::string& devId); + static std::vector GetFileNameList(const std::string& devId); + static bool SaveFileNameList(const std::string& devId, const std::vector& fileNameList); + static std::string GetBase64(HGImage image); + static std::string GetBase64(const HGByte* data, HGUInt size); + static std::string GetBase64(const std::string& fileName); + static HGByte* GetBuffer(const std::string& fileName, HGUInt* size); + static bool SaveBase64(const std::string& fileName, const char* base64); + static bool HTTPUpload(const std::string& localFileName, const std::string& httpUrl, const std::string& remoteFileName, + const std::string& httpMethod, const std::string& header, const std::string& param); + static bool FTPUpload(const std::string& localFileName, const std::string& ftpUrl, int ftpPort, const std::string& ftpPath, + const std::string& ftpUser, const std::string& ftpPassword, int ftpMode); + static int sane_ex_callback(SANE_Handle hdev, int code, void* data, unsigned int* len, void* param); + + private: + HGLock m_lock; + std::string m_devName; + SANE_Handle m_devHandle; + DevParam m_devParam; + ScanEvent m_scanEvent; + void* m_scanParam; + + std::string m_scanInsertImgName; + bool m_scanIsInsert; + bool m_scanning; + }; +} \ No newline at end of file diff --git a/sdk/webservice/ManagerV2.cpp b/sdk/webservice/ManagerV2.cpp new file mode 100644 index 00000000..9955177f --- /dev/null +++ b/sdk/webservice/ManagerV2.cpp @@ -0,0 +1,306 @@ +#include "ManagerV2.h" +#include "base/HGBuffer.h" +#include "base/HGBase64.h" +#include "base/HGUtility.h" +#include "base/HGInfo.h" +#include "imgfmt/HGJpeg.h" +#include "imgfmt/HGOfd.h" +#include "imgfmt/HGPdf.h" +#include "imgfmt/HGTiff.h" +#include "imgfmt/HGImgFmt.h" +#include "HGString.h" + +namespace ver_2 +{ + ManagerV2::ManagerV2(HGMsgPump msgPump) + : Manager(msgPump) + { + + } + + ManagerV2::~ManagerV2() + { + + } + + void ManagerV2::ScanFinish(const ScanFinishParam* param) + { + assert(NULL != param && this == param->mgr); + } + + int ManagerV2::SetGlobalConfig(const GlobalConfig& cfg) + { + if ("date_time" != cfg.fileNameMode && "random" != cfg.fileNameMode) + return -1; + if ("jpg" != cfg.imageFormat && "bmp" != cfg.imageFormat && "png" != cfg.imageFormat && "tif" != cfg.imageFormat + && "pdf" != cfg.imageFormat && "ofd" != cfg.imageFormat && "ocr-pdf" != cfg.imageFormat && "ocr-ofd" != cfg.imageFormat) + return -1; + if (cfg.imageJpegQuality < 0 || cfg.imageJpegQuality > 100) + return -1; + if ("none" != cfg.imageTiffCompression && "lzw" != cfg.imageTiffCompression && "jpeg" != cfg.imageTiffCompression) + return -1; + if (cfg.imageTiffJpegQuality < 0 || cfg.imageTiffJpegQuality > 100) + return -1; + + SetCfgStringValue("global", "fileSavePath", Utf8ToStdString(cfg.fileSavePath)); + SetCfgStringValue("global", "fileNamePrefix", Utf8ToStdString(cfg.fileNamePrefix)); + SetCfgStringValue("global", "fileNameMode", cfg.fileNameMode); + SetCfgStringValue("global", "imageFormat", cfg.imageFormat); + SetCfgIntValue("global", "imageJpegQuality", cfg.imageJpegQuality); + SetCfgStringValue("global", "imageTiffCompression", cfg.imageTiffCompression); + SetCfgIntValue("global", "imageTiffJpegQuality", cfg.imageTiffJpegQuality); + SetCfgStringValue("global", "uploadHttpHost", cfg.uploadHttpHost); + SetCfgIntValue("global", "uploadHttpPort", cfg.uploadHttpPort); + SetCfgStringValue("global", "uploadHttpPath", cfg.uploadHttpPath); + SetCfgStringValue("global", "uploadFtpUser", cfg.uploadFtpUser); + SetCfgStringValue("global", "uploadFtpPassword", cfg.uploadFtpPassword); + SetCfgStringValue("global", "uploadFtpHost", cfg.uploadFtpHost); + SetCfgIntValue("global", "uploadFtpPort", cfg.uploadFtpPort); + return 0; + } + + int ManagerV2::GetGlobalConfig(GlobalConfig& cfg) + { + HGChar docPath[256]; + HGBase_GetDocumentsPath(docPath, 256); + cfg.fileSavePath = StdStringToUtf8(GetCfgStringValue("global", "fileSavePath", docPath)); + cfg.fileNamePrefix = StdStringToUtf8(GetCfgStringValue("global", "fileNamePrefix", "Huago")); + cfg.fileNameMode = GetCfgStringValue("global", "fileNameMode", "date_time"); + cfg.imageFormat = GetCfgStringValue("global", "imageFormat", "jpg"); + cfg.imageJpegQuality = GetCfgIntValue("global", "imageJpegQuality", 80); + cfg.imageTiffCompression = GetCfgStringValue("global", "imageTiffCompression", "lzw"); + cfg.imageTiffJpegQuality = GetCfgIntValue("global", "imageTiffJpegQuality", 80); + cfg.uploadHttpHost = GetCfgStringValue("global", "uploadHttpHost", ""); + cfg.uploadHttpPort = GetCfgIntValue("global", "uploadHttpPort", 80); + cfg.uploadHttpPath = GetCfgStringValue("global", "uploadHttpPath", "/upload.cgi"); + cfg.uploadFtpUser = GetCfgStringValue("global", "uploadFtpUser", ""); + cfg.uploadFtpPassword = GetCfgStringValue("global", "uploadFtpPassword", ""); + cfg.uploadFtpHost = GetCfgStringValue("global", "uploadFtpHost", ""); + cfg.uploadFtpPort = GetCfgIntValue("global", "uploadFtpPort", 21); + return 0; + } + + int ManagerV2::LoadLocalImage(const std::string& imagePath, std::string& imgBase64) + { + imgBase64.clear(); + + HGUInt imgType = 0; + HGImgFmt_GetImgFmtType(Utf8ToStdString(imagePath).c_str(), &imgType); + if (0 == imgType) + return -1; + + std::string prefix = "data:image/jpeg;base64,"; + if (HGIMGFMT_TYPE_BMP == imgType) + prefix = "data:image/bmp;base64,"; + else if (HGIMGFMT_TYPE_PNG == imgType) + prefix = "data:image/png;base64,"; + else if (HGIMGFMT_TYPE_TIFF == imgType) + prefix = "data:image/tiff;base64,"; + else if (HGIMGFMT_TYPE_PDF == imgType) + prefix = "data:image/pdf;base64,"; + else if (HGIMGFMT_TYPE_OFD == imgType) + prefix = "data:image/ofd;base64,"; + + int ret = GetBase64(Utf8ToStdString(imagePath), imgBase64); + if (0 != ret) + return ret; + + imgBase64.insert(0, prefix); + return 0; + } + + int ManagerV2::SaveLocalImage(const std::string& imgBase64, std::string& imagePath) + { + imagePath.clear(); + + size_t pos = imgBase64.find(','); + if (std::string::npos == pos) + return -1; + + std::string prefix = imgBase64.substr(0, pos + 1); + + std::string suffix = "jpg"; + if ("data:image/bmp;base64," == prefix) + suffix = "bmp"; + else if ("data:image/png;base64," == prefix) + suffix = "png"; + else if ("data:image/tiff;base64," == prefix) + suffix = "tif"; + else if ("data:image/pdf;base64," == prefix) + suffix = "pdf"; + else if ("data:image/ofd;base64," == prefix) + suffix = "ofd"; + + std::string imagePath2 = GetFilePath(suffix); + int ret = SaveBase64(imagePath2, imagePath.c_str() + pos + 1); + if (0 == ret) + imagePath = StdStringToUtf8(imagePath2); + return ret; + } + + int ManagerV2::DeleteLocalFile(const std::string& filePath) + { + return 0; + } + + std::string ManagerV2::GetCfgStringValue(const std::string& app, const std::string& key, const std::string& def) + { + HGChar cfgPath[256]; + HGBase_GetConfigPath(cfgPath, 256); + strcat(cfgPath, "config2.ini"); + + HGChar val[256] = { 0 }; + HGBase_GetProfileString(cfgPath, app.c_str(), key.c_str(), def.c_str(), val, 256); + return val; + } + + int ManagerV2::GetCfgIntValue(const std::string& app, const std::string& key, int def) + { + HGChar cfgPath[256]; + HGBase_GetConfigPath(cfgPath, 256); + strcat(cfgPath, "config2.ini"); + + HGInt val = 0; + HGBase_GetProfileInt(cfgPath, app.c_str(), key.c_str(), def, &val); + return val; + } + + bool ManagerV2::GetCfgBoolValue(const std::string& app, const std::string& key, bool def) + { + HGChar cfgPath[256]; + HGBase_GetConfigPath(cfgPath, 256); + strcat(cfgPath, "config2.ini"); + + HGInt val = 0; + HGBase_GetProfileInt(cfgPath, app.c_str(), key.c_str(), (HGInt)def, &val); + return (bool)val; + } + + bool ManagerV2::SetCfgStringValue(const std::string& app, const std::string& key, const std::string& val) + { + HGChar cfgPath[256]; + HGBase_GetConfigPath(cfgPath, 256); + HGBase_CreateDir(cfgPath); + strcat(cfgPath, "config2.ini"); + + return (HGBASE_ERR_OK == HGBase_SetProfileString(cfgPath, app.c_str(), key.c_str(), val.c_str())); + } + + bool ManagerV2::SetCfgIntValue(const std::string& app, const std::string& key, int val) + { + HGChar cfgPath[256]; + HGBase_GetConfigPath(cfgPath, 256); + HGBase_CreateDir(cfgPath); + strcat(cfgPath, "config2.ini"); + + return (HGBASE_ERR_OK == HGBase_SetProfileInt(cfgPath, app.c_str(), key.c_str(), val)); + } + + bool ManagerV2::SetCfgBoolValue(const std::string& app, const std::string& key, bool val) + { + HGChar cfgPath[256]; + HGBase_GetConfigPath(cfgPath, 256); + HGBase_CreateDir(cfgPath); + strcat(cfgPath, "config2.ini"); + + return (HGBASE_ERR_OK == HGBase_SetProfileInt(cfgPath, app.c_str(), key.c_str(), (HGInt)val)); + } + + int ManagerV2::GetBase64(const std::string& fileName, std::string& base64) + { + base64.clear(); + + int ret = -1; + FILE* file = fopen(fileName.c_str(), "rb"); + if (NULL != file) + { + fseek(file, 0, SEEK_END); + long size = ftell(file); + fseek(file, 0, SEEK_SET); + + if (size > 0) + { + HGByte* data = new HGByte[size]; + long readLen = (long)fread(data, 1, size, file); + if (readLen == size) + { + HGSize base64Size = 0; + HGBase_Base64Encode(data, size, NULL, &base64Size); + uint8_t* base64Data = new uint8_t[base64Size + 1]; + HGBase_Base64Encode(data, size, base64Data, &base64Size); + base64Data[base64Size] = 0; + base64 = (const char*)base64Data; + delete[] base64Data; + ret = 0; + } + + delete[] data; + } + + fclose(file); + } + + return ret; + } + + int ManagerV2::SaveBase64(const std::string& fileName, const std::string& base64) + { + if (base64.empty()) + return -1; + + const char* base64Data = base64.c_str(); + size_t base64Size = base64.size(); + + int ret = -1; + FILE* file = fopen(fileName.c_str(), "wb"); + if (NULL != file) + { + HGSize size = 0; + HGBase_Base64Decode((const HGByte*)base64Data, (HGSize)base64Size, NULL, &size); + uint8_t* data = new HGByte[size]; + HGBase_Base64Decode((const HGByte*)base64Data, (HGSize)base64Size, data, &size); + + size_t writeLen = fwrite(data, 1, size, file); + if (writeLen == (size_t)size) + ret = 0; + + delete[] data; + fclose(file); + } + + return ret; + } + + std::string ManagerV2::GetFilePath(const std::string& suffix) + { + HGChar docPath[256]; + HGBase_GetDocumentsPath(docPath, 256); + std::string fileSavePath = GetCfgStringValue("global", "fileSavePath", docPath); + std::string fileNamePrefix = GetCfgStringValue("global", "fileNamePrefix", "Huago"); + std::string fileNameMode = GetCfgStringValue("global", "fileNameMode", "date_time"); + + char filePath[256] = { 0 }; + if ("random" == fileNameMode) + { + HGChar uuid[256]; + HGBase_GetUuid(uuid, 256); + sprintf(filePath, "%s%s%s.%s", fileSavePath.c_str(), fileNamePrefix.c_str(), uuid, suffix.c_str()); + } + else + { + timeb tb; + ftime(&tb); + struct tm* p = localtime(&tb.time); + sprintf(filePath, "%s%s%04d%02d%02d%02d%02d%02d.%s", fileSavePath.c_str(), fileNamePrefix.c_str(), (1900 + p->tm_year), + (1 + p->tm_mon), p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, suffix.c_str()); + } + + return filePath; + } + + std::string ManagerV2::GetImagePath() + { + std::string imageFormat = GetCfgStringValue("global", "imageFormat", "jpg"); + return GetFilePath(imageFormat); + } +} diff --git a/sdk/webservice/ManagerV2.h b/sdk/webservice/ManagerV2.h new file mode 100644 index 00000000..e7804a46 --- /dev/null +++ b/sdk/webservice/ManagerV2.h @@ -0,0 +1,72 @@ +#pragma once + +#include "base/HGDef.h" +#include "base/HGInc.h" +#include "base/HGLock.h" +#include "base/HGImage.h" +#include "base/HGMsgPump.h" +#include "sane/sane_ex.h" +#include "sane/sane_option_definitions.h" +#include "Manager.h" +#include "Msg.h" +#include + +namespace ver_2 +{ + struct GlobalConfig + { + // ļ + std::string fileSavePath; + std::string fileNamePrefix; + std::string fileNameMode; + // ͼ񱣴 + std::string imageFormat; + int imageJpegQuality; + std::string imageTiffCompression; + int imageTiffJpegQuality; + // ϴ + std::string uploadHttpHost; + unsigned short uploadHttpPort; + std::string uploadHttpPath; + std::string uploadFtpUser; + std::string uploadFtpPassword; + std::string uploadFtpHost; + unsigned short uploadFtpPort; + }; + + class ManagerV2 : public Manager + { + public: + ManagerV2(HGMsgPump msgPump); + virtual ~ManagerV2(); + + // ɨ + void ScanFinish(const ScanFinishParam* param); + + // ȫ + int SetGlobalConfig(const GlobalConfig& cfg); + // ȡȫ + int GetGlobalConfig(GlobalConfig& cfg); + // رͼ + int LoadLocalImage(const std::string& imagePath, std::string& imgBase64); + // 汾ͼ + int SaveLocalImage(const std::string& imgBase64, std::string& imagePath); + // ɾļ + int DeleteLocalFile(const std::string& filePath); + + private: + std::string GetCfgStringValue(const std::string& app, const std::string& key, const std::string& def); + int GetCfgIntValue(const std::string& app, const std::string& key, int def); + bool GetCfgBoolValue(const std::string& app, const std::string& key, bool def); + bool SetCfgStringValue(const std::string& app, const std::string& key, const std::string& val); + bool SetCfgIntValue(const std::string& app, const std::string& key, int val); + bool SetCfgBoolValue(const std::string& app, const std::string& key, bool val); + static int GetBase64(const std::string& fileName, std::string& base64); + static int SaveBase64(const std::string& fileName, const std::string& base64); + std::string GetFilePath(const std::string& suffix); + std::string GetImagePath(); + + private: + + }; +} \ No newline at end of file diff --git a/sdk/webservice/Msg.h b/sdk/webservice/Msg.h index fdfdbc58..7c360c2b 100644 --- a/sdk/webservice/Msg.h +++ b/sdk/webservice/Msg.h @@ -2,61 +2,66 @@ #include "base/HGDef.h" #include "base/HGInc.h" -#include "HttpHead.h" #include +#include "HttpHead.h" + +enum +{ + MSGID_CONNECT = 1L, + MSGID_DISCONNECT +}; + +class WebServer; + +struct ConnectParam +{ + WebServer* svr; + std::string ip; + HGUShort port; +#if defined(HG_CMP_MSC) + SOCKET socket; +#else + int socket; +#endif +}; + +struct DisConnectParam +{ + WebServer* svr; + HGUInt usrId; +}; namespace ver_1 { enum { - MSGID_OPEN_DEVICE = 1L, + MSGID_OPEN_DEVICE = 3L, MSGID_CLOSE_DEVICE, MSGID_SCAN_FINISH, - MSGID_CONNECT, - MSGID_DISCONNECT, MSGID_HTTP_COMMAND, MSGID_SOCKIO_COMMAND, MSGID_SOCKIO_EVENT }; - class Manager; - class WebServer; + class ManagerV1; class HttpServer; class SockIoServer; struct OpenDevParam { - Manager* mgr; + ManagerV1* mgr; std::string devName; }; struct CloseDevParam { - Manager* mgr; + ManagerV1* mgr; std::string devName; }; struct ScanFinishParam { - Manager* mgr; - }; - - struct ConnectParam - { - WebServer* svr; - HGChar ip[16]; - HGUShort port; -#if defined(HG_CMP_MSC) - SOCKET socket; -#else - int socket; -#endif - }; - - struct DisConnectParam - { - WebServer* svr; - HGUInt usrId; + ManagerV1* mgr; }; struct HttpCmdParam @@ -83,4 +88,38 @@ namespace ver_1 HGByte* data; HGUInt size; }; +} + +namespace ver_2 +{ + enum + { + MSGID_SCAN_FINISH = 3L, + MSGID_WS_COMMAND, + MSGID_WS_EVENT + }; + + class ManagerV2; + class WSServer; + + struct ScanFinishParam + { + ManagerV2* mgr; + }; + + struct WSCmdParam + { + WSServer* svr; + HGUInt usrId; + HGByte* data; + HGUInt size; + }; + + struct WSEvtParam + { + WSServer* svr; + HGUInt usrId; + HGByte* data; + HGUInt size; + }; } \ No newline at end of file diff --git a/sdk/webservice/MsgPumpCallback.cpp b/sdk/webservice/MsgPumpCallback.cpp index ac981277..2e44c798 100644 --- a/sdk/webservice/MsgPumpCallback.cpp +++ b/sdk/webservice/MsgPumpCallback.cpp @@ -1,9 +1,11 @@ -#include "MsgPumpCallback.h" +#include "MsgPumpCallback.h" #include "base/HGDef.h" #include "base/HGInc.h" -#include "Manager.h" +#include "ManagerV1.h" +#include "ManagerV2.h" #include "HttpServer.h" #include "SockIoServer.h" +#include "WSServer.h" namespace ver_1 { @@ -15,6 +17,20 @@ namespace ver_1 switch (msg->id) { + case MSGID_CONNECT: + { + ConnectParam* param = (ConnectParam*)msg->data; + param->svr->Connect(param); + delete param; + } + break; + case MSGID_DISCONNECT: + { + DisConnectParam* param = (DisConnectParam*)msg->data; + param->svr->DisConnect(param); + delete param; + } + break; case MSGID_OPEN_DEVICE: { OpenDevParam* param = (OpenDevParam*)msg->data; @@ -36,20 +52,6 @@ namespace ver_1 delete param; } break; - case MSGID_CONNECT: - { - ConnectParam* param = (ConnectParam*)msg->data; - param->svr->Connect(param); - delete param; - } - break; - case MSGID_DISCONNECT: - { - DisConnectParam* param = (DisConnectParam*)msg->data; - param->svr->DisConnect(param); - delete param; - } - break; case MSGID_HTTP_COMMAND: { HttpCmdParam* param = (HttpCmdParam*)msg->data; @@ -73,4 +75,54 @@ namespace ver_1 break; } } -} \ No newline at end of file +} + + +namespace ver_2 +{ + void HGMsgPumpCallback(HGMsgPump msgPump, const HGMsg* msg, HGPointer param) + { + (void)msgPump; + (void)param; + assert(NULL != msg); + + switch (msg->id) + { + case MSGID_CONNECT: + { + ConnectParam* param = (ConnectParam*)msg->data; + param->svr->Connect(param); + delete param; + } + break; + case MSGID_DISCONNECT: + { + DisConnectParam* param = (DisConnectParam*)msg->data; + param->svr->DisConnect(param); + delete param; + } + break; + case MSGID_SCAN_FINISH: + { + ScanFinishParam* param = (ScanFinishParam*)msg->data; + param->mgr->ScanFinish(param); + delete param; + } + break; + case MSGID_WS_COMMAND: + { + WSCmdParam* param = (WSCmdParam*)msg->data; + param->svr->Command(param); + delete param; + } + break; + case MSGID_WS_EVENT: + { + WSEvtParam* param = (WSEvtParam*)msg->data; + param->svr->Event(param); + delete param; + } + break; + } + } +} diff --git a/sdk/webservice/MsgPumpCallback.h b/sdk/webservice/MsgPumpCallback.h index 1426f7e3..fc9a0efc 100644 --- a/sdk/webservice/MsgPumpCallback.h +++ b/sdk/webservice/MsgPumpCallback.h @@ -1,8 +1,13 @@ -#pragma once +#pragma once #include "base/HGMsgPump.h" namespace ver_1 +{ + void HGMsgPumpCallback(HGMsgPump msgPump, const HGMsg* msg, HGPointer param); +} + +namespace ver_2 { void HGMsgPumpCallback(HGMsgPump msgPump, const HGMsg* msg, HGPointer param); } \ No newline at end of file diff --git a/sdk/webservice/SockIoServer.cpp b/sdk/webservice/SockIoServer.cpp index f2daa9e1..2024325d 100644 --- a/sdk/webservice/SockIoServer.cpp +++ b/sdk/webservice/SockIoServer.cpp @@ -4,10 +4,10 @@ namespace ver_1 { - SockIoServer::SockIoServer(HGMsgPump msgPump, Manager* manager) - : WebServer(msgPump, manager) + SockIoServer::SockIoServer(HGMsgPump msgPump, ManagerV1* manager) + : WebServer(msgPump) { - + m_manager = manager; } SockIoServer::~SockIoServer() @@ -15,6 +15,11 @@ namespace ver_1 } + ManagerV1* SockIoServer::GetManger() + { + return m_manager; + } + void SockIoServer::Connect(const ConnectParam* param) { assert(NULL != param && this == param->svr); diff --git a/sdk/webservice/SockIoServer.h b/sdk/webservice/SockIoServer.h index 1e73ff08..6696bfce 100644 --- a/sdk/webservice/SockIoServer.h +++ b/sdk/webservice/SockIoServer.h @@ -5,16 +5,18 @@ namespace ver_1 { - class Manager; - class SockIoServer : public WebServer { public: - SockIoServer(HGMsgPump msgPump, Manager* manager); + SockIoServer(HGMsgPump msgPump, ManagerV1* manager); virtual ~SockIoServer(); + ManagerV1* GetManger(); void Connect(const ConnectParam* param); void Command(const SockIoCmdParam* param); void Event(const SockIoEvtParam* param); + + private: + ManagerV1* m_manager; }; } \ No newline at end of file diff --git a/sdk/webservice/SockIoUser.cpp b/sdk/webservice/SockIoUser.cpp index 4c76b245..6a00c7e1 100644 --- a/sdk/webservice/SockIoUser.cpp +++ b/sdk/webservice/SockIoUser.cpp @@ -1,18 +1,18 @@ #include "SockIoUser.h" -#include "WebServer.h" -#include "Manager.h" +#include "SockIoServer.h" +#include "ManagerV1.h" #include "base/HGInfo.h" #include "base/HGUtility.h" +#include "cJSON.h" #include "sha1.h" #include "base64.h" -#include "cJSON.h" namespace ver_1 { #if defined(HG_CMP_MSC) - SockIoUser::SockIoUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, SOCKET sockConn) + SockIoUser::SockIoUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, SOCKET sockConn) #else - SockIoUser::SockIoUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, int sockConn) + SockIoUser::SockIoUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, int sockConn) #endif : WebUser(server, id, ip, port, sockConn) { @@ -24,6 +24,11 @@ namespace ver_1 GetManager()->ResetScanEvent(); } + ManagerV1* SockIoUser::GetManager() + { + return ((SockIoServer*)m_server)->GetManger(); + } + void SockIoUser::HandleCmd(const SockIoCmdParam* param) { assert(NULL != param && m_id == param->usrId); diff --git a/sdk/webservice/SockIoUser.h b/sdk/webservice/SockIoUser.h index add71447..1f447126 100644 --- a/sdk/webservice/SockIoUser.h +++ b/sdk/webservice/SockIoUser.h @@ -5,18 +5,17 @@ namespace ver_1 { - class WebServer; - class SockIoUser : public WebUser { public: #if defined(HG_CMP_MSC) - SockIoUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, SOCKET sockConn); + SockIoUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, SOCKET sockConn); #else - SockIoUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, int sockConn); + SockIoUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, int sockConn); #endif virtual ~SockIoUser(); + ManagerV1* GetManager(); void HandleCmd(const SockIoCmdParam* param); void HandleEvent(const SockIoEvtParam* param); diff --git a/sdk/webservice/WSServer.cpp b/sdk/webservice/WSServer.cpp index e69de29b..66220b80 100644 --- a/sdk/webservice/WSServer.cpp +++ b/sdk/webservice/WSServer.cpp @@ -0,0 +1,54 @@ +#include "WSServer.h" +#include "WSUser.h" +#include "base/HGInfo.h" + +namespace ver_2 +{ + WSServer::WSServer(HGMsgPump msgPump, ManagerV2* manager) + : WebServer(msgPump) + { + m_manager = manager; + } + + WSServer::~WSServer() + { + + } + + ManagerV2* WSServer::GetManger() + { + return m_manager; + } + + void WSServer::Connect(const ConnectParam* param) + { + assert(NULL != param && this == param->svr); + + WebUser* user = new WSUser(this, m_currUserId, param->ip, param->port, param->socket); + user->Open(); + ++m_currUserId; + m_vectorUser.push_back(user); + } + + void WSServer::Command(const WSCmdParam* param) + { + assert(NULL != param && this == param->svr); + + int nIndex = GetUserIndex(param->usrId); + if (-1 != nIndex) + { + ((WSUser*)m_vectorUser[nIndex])->HandleCmd(param); + } + } + + void WSServer::Event(const WSEvtParam* param) + { + assert(NULL != param && this == param->svr); + + int nIndex = GetUserIndex(param->usrId); + if (-1 != nIndex) + { + ((WSUser*)m_vectorUser[nIndex])->HandleEvent(param); + } + } +} diff --git a/sdk/webservice/WSServer.h b/sdk/webservice/WSServer.h index e69de29b..488ed594 100644 --- a/sdk/webservice/WSServer.h +++ b/sdk/webservice/WSServer.h @@ -0,0 +1,22 @@ +#pragma once + +#include "WebServer.h" +#include "Msg.h" + +namespace ver_2 +{ + class WSServer : public WebServer + { + public: + WSServer(HGMsgPump msgPump, ManagerV2* manager); + virtual ~WSServer(); + + ManagerV2* GetManger(); + void Connect(const ConnectParam* param); + void Command(const WSCmdParam* param); + void Event(const WSEvtParam* param); + + private: + ManagerV2* m_manager; + }; +} \ No newline at end of file diff --git a/sdk/webservice/WSUser.cpp b/sdk/webservice/WSUser.cpp index e69de29b..59445ad6 100644 --- a/sdk/webservice/WSUser.cpp +++ b/sdk/webservice/WSUser.cpp @@ -0,0 +1,549 @@ +#include "WSUser.h" +#include "WSServer.h" +#include "ManagerV2.h" +#include "base/HGInfo.h" +#include "cJSON.h" +#include "sha1.h" +#include "base64.h" + +namespace ver_2 +{ + static int GetJsonIntValue(cJSON* json, const std::string& key) + { + int ret = 0; + + cJSON* p = json->child; + while (NULL != p) + { + if (0 == strcmp(p->string, key.c_str())) + { + if (p->type == cJSON_Number) + ret = p->valueint; + break; + } + + p = p->next; + } + + return ret; + } + + static bool GetJsonBoolValue(cJSON* json, const std::string& key) + { + bool ret = false; + + cJSON* p = json->child; + while (NULL != p) + { + if (0 == strcmp(p->string, key.c_str())) + { + if (p->type == cJSON_True) + ret = true; + break; + } + + p = p->next; + } + + return ret; + } + + static std::string GetJsonStringValue(cJSON* json, const std::string& key) + { + std::string ret; + + cJSON* p = json->child; + while (NULL != p) + { + if (0 == strcmp(p->string, key.c_str())) + { + if (p->type == cJSON_String) + ret = p->valuestring; + break; + } + + p = p->next; + } + + return ret; + } + +#if defined(HG_CMP_MSC) + WSUser::WSUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, SOCKET sockConn) +#else + WSUser::WSUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, int sockConn) +#endif + : WebUser(server, id, ip, port, sockConn) + { + + } + + WSUser::~WSUser() + { + + } + + ManagerV2* WSUser::GetManager() + { + return ((WSServer*)m_server)->GetManger(); + } + + void WSUser::HandleCmd(const WSCmdParam* param) + { + assert(NULL != param && m_id == param->usrId); + + std::string cmdData((const char*)param->data, param->size); + cJSON* json = cJSON_Parse(cmdData.c_str()); + if (NULL != json) + { + std::string func = GetJsonStringValue(json, "func"); + if ("set_global_config" == func) + { + + } + else if ("get_global_config" == func) + { + + } + else if ("load_local_image" == func) + { + + } + + cJSON_Delete(json); + } + } + + void WSUser::HandleEvent(const WSEvtParam* param) + { + assert(NULL != param && m_id == param->usrId); + + SendResponse(param->data, param->size, HGTRUE); + } + + void WSUser::PostCmdMsg(const HGByte* data, HGUInt dataSize) + { + WSCmdParam* param = new WSCmdParam; + param->svr = (WSServer*)m_server; + param->usrId = m_id; + param->data = new HGByte[dataSize]; + param->size = dataSize; + memcpy(param->data, data, dataSize); + + HGMsg msg; + msg.id = MSGID_WS_COMMAND; + msg.data = param; + if (HGBASE_ERR_OK != HGBase_PostPumpMessage(m_server->GetMsgPump(), &msg)) + { + delete[] param->data; + param->size = 0; + delete param; + } + } + + void WSUser::PostEventMsg(const HGByte* data, HGUInt dataSize) + { + WSEvtParam* param = new WSEvtParam; + param->svr = (WSServer*)m_server; + param->usrId = m_id; + param->data = new HGByte[dataSize]; + param->size = dataSize; + memcpy(param->data, data, dataSize); + + HGMsg msg; + msg.id = MSGID_WS_EVENT; + msg.data = param; + if (HGBASE_ERR_OK != HGBase_PostPumpMessage(m_server->GetMsgPump(), &msg)) + { + delete[] param->data; + param->size = 0; + delete param; + } + } + + void WSUser::ThreadFunc() + { + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "WSUser::ThreadFunc"); + + char chBuffer[2048]; + const char* pBuffer = chBuffer; + int nBufferSize = 0; + bool bConnect = false; + + unsigned char connectDataTail[4] = { '\r', '\n', '\r', '\n' }; + unsigned int connectDataTailLen = 0; + std::string connectData; + + uint8_t* pData = NULL; + int nDataSize = 0; + uint8_t* pDataEx = NULL; + int nRemainSize = 0; + uint8_t headData[20]; + uint32_t nHeadDataLen = 0; + uint8_t vMask[4]; + uint32_t nMaskCount = 0; + bool bHandle = false; + std::vector vAllData; + + while (1) + { + if (0 == nBufferSize) + { + int len = recv(m_sockConn, chBuffer, 2048, 0); + if (len <= 0) + { + // ǷرsocketConn߿ͻ˹رsocketϿ + PostDisConnectMsg(); + break; + } + else + { + pBuffer = chBuffer; + nBufferSize = len; + } + } + + assert(nBufferSize > 0); + + if (!bConnect) + { + unsigned char b = *pBuffer; + ++pBuffer; + --nBufferSize; + + connectData.push_back(b); + if (b == connectDataTail[connectDataTailLen]) + { + ++connectDataTailLen; + } + else + { + connectDataTailLen = 0; + if (b == connectDataTail[connectDataTailLen]) + { + ++connectDataTailLen; + } + } + + if (4 == connectDataTailLen) + { + connectDataTailLen = 0; + bool shakeRet = ShakeHand(connectData); + connectData.clear(); + + if (!shakeRet) + { + PostDisConnectMsg(); + break; + } + + bConnect = true; + } + } + else + { + if (NULL == pData) + { + assert(0 == nDataSize); + + uint8_t b = *pBuffer; + ++pBuffer; + --nBufferSize; + headData[nHeadDataLen] = b; + ++nHeadDataLen; + + if (1 == nHeadDataLen) + { + if ((0x80 | 0x08) == headData[0]) // Ͽ + { + PostDisConnectMsg(); + break; + } + else if ((0x80 | 0x09) == headData[0]) // PING֡ + { + // + } + else if ((0x80 | 0x0A) == headData[0]) // PONG֡ + { + // + } + else if ((0x00 | 0x01) == headData[0] || (0x00 | 0x02) == headData[0] || (0x00 | 0x00) == headData[0] || (0x80 | 0x00) == headData[0] + || (0x80 | 0x01) == headData[0] || (0x80 | 0x02) == headData[0]) // ֡ + { + if ((0x80 | 0x00) == headData[0] || (0x80 | 0x01) == headData[0] || (0x80 | 0x02) == headData[0]) + { + // Ƭ + bHandle = true; + } + else + { + // Ƭ֡ + bHandle = false; + } + } + else // ֡󣬶Ͽ + { + PostDisConnectMsg(); + break; + } + } + else if (2 == nHeadDataLen) + { + if (0 == (headData[1] & 0x80)) // 뾭봦 + { + PostDisConnectMsg(); + break; + } + + if ((0x80 | 0x09) == headData[0]) // PING֡ + { + if (0x80 != headData[1]) + { + PostDisConnectMsg(); + break; + } + } + else if ((0x80 | 0x0A) == headData[0]) // PONG֡ + { + if (0x80 != headData[1]) + { + PostDisConnectMsg(); + break; + } + } + else + { + if ((headData[1] & 0x7F) <= 125) + { + uint32_t nCmdSize = (headData[1] & 0x7F); + nHeadDataLen = 0; + + if (0 == nCmdSize) + { + PostDisConnectMsg(); + break; + } + + nDataSize = nCmdSize; + nRemainSize = nCmdSize; + pData = new uint8_t[nDataSize]; + pDataEx = pData; + } + } + } + else if (4 == nHeadDataLen) + { + if ((0x80 | 0x09) == headData[0]) // PING֡ + { + // + } + else if ((0x80 | 0x0A) == headData[0]) // PONG֡ + { + // + } + else + { + if ((headData[1] & 0x7F) == 126) + { + uint32_t nCmdSize = ntohs(*(uint16_t*)&headData[2]); + nHeadDataLen = 0; + + if (0 == nCmdSize) + { + PostDisConnectMsg(); + break; + } + + nDataSize = nCmdSize; + nRemainSize = nCmdSize; + pData = new uint8_t[nDataSize]; + pDataEx = pData; + } + } + } + else if (6 == nHeadDataLen) + { + if ((0x80 | 0x09) == headData[0]) // PING֡ + { + nHeadDataLen = 0; + + Pong(); + } + else if ((0x80 | 0x0A) == headData[0]) // PONG֡ + { + nHeadDataLen = 0; + } + } + else if (10 == nHeadDataLen) + { + if ((headData[1] & 0x7F) == 127) // һ127 + { + uint32_t nCmdSizeHigh = ntohl(*(uint32_t*)&headData[2]); + uint32_t nCmdSize = ntohl(*(uint32_t*)&headData[6]); + nHeadDataLen = 0; + + if ((0 != nCmdSizeHigh) || (0 == nCmdSize)) + { + PostDisConnectMsg(); + break; + } + + nDataSize = nCmdSize; + nRemainSize = nCmdSize; + pData = new uint8_t[nDataSize]; + pDataEx = pData; + } + } + } + else + { + if (4 != nMaskCount) + { + uint8_t b = *pBuffer; + ++pBuffer; + --nBufferSize; + vMask[nMaskCount] = b; + ++nMaskCount; + } + else + { + int nWriteSize = HGMIN(nBufferSize, nRemainSize); + memcpy(pDataEx, pBuffer, nWriteSize); + pBuffer += nWriteSize; + nBufferSize -= nWriteSize; + pDataEx += nWriteSize; + nRemainSize -= nWriteSize; + + if (0 == nRemainSize) + { + assert(pDataEx == pData + nDataSize); + + for (int i = 0; i < nDataSize; ++i) + { + int j = i % 4; + pData[i] = pData[i] ^ vMask[j]; + vAllData.push_back(pData[i]); + } + + delete[] pData; + pData = NULL; + nDataSize = 0; + nMaskCount = 0; + + if (bHandle) + { + PostCmdMsg(&vAllData[0], vAllData.size()); + + bHandle = false; + vAllData.clear(); + } + } + } + } + } + } + + if (NULL != pData) + { + delete[] pData; + pData = NULL; + nDataSize = 0; + nMaskCount = 0; + } + } + + bool WSUser::ShakeHand(const std::string& head) + { + std::string requestMethod; + std::string requestURIPath; + HttpPairs requestURIQueryInfos; + std::string requestURIFragment; + std::string httpVersion; + HttpPairs headInfos; + HttpHead::AnalysisHead(head, requestMethod, requestURIPath, requestURIQueryInfos, + requestURIFragment, httpVersion, headInfos); + + if ("Upgrade" != HttpHead::GetValue(headInfos, "Connection")) + return false; + if ("websocket" != HttpHead::GetValue(headInfos, "Upgrade")) + return false; + + std::string key = HttpHead::GetValue(headInfos, "Sec-WebSocket-Key"); + if (key.empty()) + return false; + + key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + + unsigned int message_digest[5]; + SHA1 sha; + sha.Reset(); + sha << key.c_str(); + sha.Result(message_digest); + + for (int i = 0; i < 5; ++i) + message_digest[i] = htonl(message_digest[i]); + std::string serverKey = base64_encode((const unsigned char*)message_digest, 20); + + std::string handShakeResp = "HTTP/1.1 101 Switching Protocols\r\n"; + handShakeResp += "Upgrade: websocket\r\n"; + handShakeResp += "Connection: Upgrade\r\n"; + handShakeResp += "Sec-WebSocket-Accept:"; + handShakeResp += serverKey; + handShakeResp += "\r\n\r\n"; + send(m_sockConn, handShakeResp.c_str(), (int)handShakeResp.length(), 0); + return true; + } + + void WSUser::Pong() + { + uint8_t vHead[2]; + vHead[0] = 0x80 | 0x0A; + vHead[1] = 0; + + HGBase_EnterLock(m_cs); + send(m_sockConn, (const char*)vHead, 2, 0); + HGBase_LeaveLock(m_cs); + } + + bool WSUser::SendResponse(const HGByte* data, HGUInt size, HGBool text) + { + if (NULL == data || 0 == size) + { + return false; + } + + uint32_t nHeadLen = 0; + + uint8_t vHead[20] = { 0 }; + vHead[0] = text ? (0x80 | 0x01) : (0x80 | 0x02); + if (size <= 125) + { + vHead[1] = (uint8_t)size; + nHeadLen = 2; + } + else if (size <= 0xFFFF) + { + vHead[1] = 126; + uint16_t payloadLength16b = htons((uint16_t)size); + memcpy(&vHead[2], &payloadLength16b, 2); + nHeadLen = 4; + } + else + { + vHead[1] = 127; + vHead[2] = 0; + vHead[3] = 0; + vHead[4] = 0; + vHead[5] = 0; + uint32_t payloadLength32b = htonl(size); + memcpy(&vHead[6], &payloadLength32b, 4); + nHeadLen = 10; + } + + HGBase_EnterLock(m_cs); + send(m_sockConn, (const char*)vHead, nHeadLen, 0); + send(m_sockConn, (const char*)data, size, 0); + HGBase_LeaveLock(m_cs); + return true; + } +} \ No newline at end of file diff --git a/sdk/webservice/WSUser.h b/sdk/webservice/WSUser.h index e69de29b..875d944e 100644 --- a/sdk/webservice/WSUser.h +++ b/sdk/webservice/WSUser.h @@ -0,0 +1,32 @@ +#pragma once + +#include "WebUser.h" +#include "Msg.h" + +namespace ver_2 +{ + class WSUser : public WebUser + { + public: +#if defined(HG_CMP_MSC) + WSUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, SOCKET sockConn); +#else + WSUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, int sockConn); +#endif + virtual ~WSUser(); + + ManagerV2* GetManager(); + void HandleCmd(const WSCmdParam* param); + void HandleEvent(const WSEvtParam* param); + + protected: + void PostCmdMsg(const HGByte* data, HGUInt dataSize); + void PostEventMsg(const HGByte* data, HGUInt dataSize); + virtual void ThreadFunc(); + + private: + bool ShakeHand(const std::string& head); + void Pong(); + bool SendResponse(const HGByte* data, HGUInt size, HGBool text); + }; +} diff --git a/sdk/webservice/WebServer.cpp b/sdk/webservice/WebServer.cpp index 3b6b03cb..8386ec85 100644 --- a/sdk/webservice/WebServer.cpp +++ b/sdk/webservice/WebServer.cpp @@ -2,212 +2,203 @@ #include "WebUser.h" #include "base/HGInfo.h" -namespace ver_1 +WebServer::WebServer(HGMsgPump msgPump) { - WebServer::WebServer(HGMsgPump msgPump, Manager* manager) + m_msgPump = msgPump; + + m_currUserId = 1; +#if defined(HG_CMP_MSC) + m_sockServer = INVALID_SOCKET; +#else + m_sockServer = -1; +#endif + m_listenThread = NULL; +} + +WebServer::~WebServer() +{ + +} + +HGMsgPump WebServer::GetMsgPump() +{ + return m_msgPump; +} + +bool WebServer::Open(HGUShort port) +{ +#if defined(HG_CMP_MSC) + if (INVALID_SOCKET != m_sockServer) +#else + if (-1 != m_sockServer) +#endif { - m_msgPump = msgPump; - m_manager = manager; - - m_currUserId = 1; -#if defined(HG_CMP_MSC) - m_sockServer = INVALID_SOCKET; -#else - m_sockServer = -1; -#endif - m_listenThread = NULL; - } - - WebServer::~WebServer() - { - - } - - HGMsgPump WebServer::GetMsgPump() - { - return m_msgPump; - } - - Manager* WebServer::GetManager() - { - return m_manager; - } - - bool WebServer::Open(HGUShort port) - { -#if defined(HG_CMP_MSC) - if (INVALID_SOCKET != m_sockServer) -#else - if (-1 != m_sockServer) -#endif - { - return false; - } - -#if defined(HG_CMP_MSC) - SOCKET sockServer = socket(AF_INET, SOCK_STREAM, 0); - if (INVALID_SOCKET == sockServer) -#else - int sockServer = socket(AF_INET, SOCK_STREAM, 0); - if (-1 == sockServer) -#endif - { - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "open webserver failed 1, port=%u", port); - return false; - } - - // bind -#if defined(HG_CMP_MSC) - SOCKADDR_IN addrServer; - addrServer.sin_addr.S_un.S_addr = INADDR_ANY; - addrServer.sin_family = AF_INET; - addrServer.sin_port = htons(port); - if (0 != bind(sockServer, (SOCKADDR*)&addrServer, sizeof(SOCKADDR_IN))) -#else - struct sockaddr_in addrServer; - addrServer.sin_addr.s_addr = htonl(INADDR_ANY); - addrServer.sin_family = AF_INET; - addrServer.sin_port = htons(port); - if (0 != bind(sockServer, (struct sockaddr*)&addrServer, sizeof(addrServer))) -#endif - { -#if defined(HG_CMP_MSC) - closesocket(sockServer); -#else - close(sockServer); -#endif - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "open webserver failed 2, port=%u", port); - return false; - } - - // listen - if (0 != listen(sockServer, 5)) - { -#if defined(HG_CMP_MSC) - closesocket(sockServer); -#else - close(sockServer); -#endif - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "open webserver failed 3, port=%u", port); - return false; - } - - m_sockServer = sockServer; - HGBase_OpenThread(ThreadFunc, this, &m_listenThread); - assert(NULL != m_listenThread); - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "open webserver success, port=%u", port); - return true; - } - - bool WebServer::Close() - { -#if defined(HG_CMP_MSC) - if (INVALID_SOCKET == m_sockServer) -#else - if (-1 == m_sockServer) -#endif - { - return false; - } - - while (!m_vectorUser.empty()) - { - WebUser* pUser = m_vectorUser[0]; - m_vectorUser.erase(m_vectorUser.begin()); - delete pUser; - pUser = NULL; - } - -#if defined(HG_CMP_MSC) - closesocket(m_sockServer); - m_sockServer = INVALID_SOCKET; -#else - close(m_sockServer); - m_sockServer = -1; -#endif - HGBase_CloseThread(m_listenThread); - m_listenThread = NULL; - return true; - } - - void WebServer::DisConnect(const DisConnectParam* param) - { - assert(NULL != param && this == param->svr); - - int nIndex = GetUserIndex(param->usrId); - if (-1 != nIndex) - { - WebUser* pUser = m_vectorUser[nIndex]; - m_vectorUser.erase(m_vectorUser.begin() + nIndex); - delete pUser; - pUser = NULL; - } + return false; } #if defined(HG_CMP_MSC) - void WebServer::PostConnectMsg(const char* ip, uint16_t port, SOCKET sockConn) + SOCKET sockServer = socket(AF_INET, SOCK_STREAM, 0); + if (INVALID_SOCKET == sockServer) #else - void WebServer::PostConnectMsg(const char* ip, uint16_t port, int sockConn) + int sockServer = socket(AF_INET, SOCK_STREAM, 0); + if (-1 == sockServer) #endif { - ConnectParam* param = new ConnectParam; - param->svr = this; - strcpy(param->ip, ip); - param->port = port; - param->socket = sockConn; + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "open webserver failed 1, port=%u", port); + return false; + } - HGMsg msg; - msg.id = MSGID_CONNECT; - msg.data = param; - if (HGBASE_ERR_OK != HGBase_PostPumpMessage(m_msgPump, &msg)) - { + // bind #if defined(HG_CMP_MSC) - closesocket(param->socket); + SOCKADDR_IN addrServer; + addrServer.sin_addr.S_un.S_addr = INADDR_ANY; + addrServer.sin_family = AF_INET; + addrServer.sin_port = htons(port); + if (0 != bind(sockServer, (SOCKADDR*)&addrServer, sizeof(SOCKADDR_IN))) #else - close(param->socket); + struct sockaddr_in addrServer; + addrServer.sin_addr.s_addr = htonl(INADDR_ANY); + addrServer.sin_family = AF_INET; + addrServer.sin_port = htons(port); + if (0 != bind(sockServer, (struct sockaddr*)&addrServer, sizeof(addrServer))) #endif - delete param; + { +#if defined(HG_CMP_MSC) + closesocket(sockServer); +#else + close(sockServer); +#endif + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "open webserver failed 2, port=%u", port); + return false; + } + + // listen + if (0 != listen(sockServer, 5)) + { +#if defined(HG_CMP_MSC) + closesocket(sockServer); +#else + close(sockServer); +#endif + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "open webserver failed 3, port=%u", port); + return false; + } + + m_sockServer = sockServer; + HGBase_OpenThread(ThreadFunc, this, &m_listenThread); + assert(NULL != m_listenThread); + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "open webserver success, port=%u", port); + return true; +} + +bool WebServer::Close() +{ +#if defined(HG_CMP_MSC) + if (INVALID_SOCKET == m_sockServer) +#else + if (-1 == m_sockServer) +#endif + { + return false; + } + + while (!m_vectorUser.empty()) + { + WebUser* pUser = m_vectorUser[0]; + m_vectorUser.erase(m_vectorUser.begin()); + delete pUser; + pUser = NULL; + } + +#if defined(HG_CMP_MSC) + closesocket(m_sockServer); + m_sockServer = INVALID_SOCKET; +#else + close(m_sockServer); + m_sockServer = -1; +#endif + HGBase_CloseThread(m_listenThread); + m_listenThread = NULL; + return true; +} + +void WebServer::DisConnect(const DisConnectParam* param) +{ + assert(NULL != param && this == param->svr); + + int nIndex = GetUserIndex(param->usrId); + if (-1 != nIndex) + { + WebUser* pUser = m_vectorUser[nIndex]; + m_vectorUser.erase(m_vectorUser.begin() + nIndex); + delete pUser; + pUser = NULL; + } +} + +#if defined(HG_CMP_MSC) +void WebServer::PostConnectMsg(const std::string& ip, uint16_t port, SOCKET sockConn) +#else +void WebServer::PostConnectMsg(const std::string& ip, uint16_t port, int sockConn) +#endif +{ + ConnectParam* param = new ConnectParam; + param->svr = this; + param->ip = ip; + param->port = port; + param->socket = sockConn; + + HGMsg msg; + msg.id = MSGID_CONNECT; + msg.data = param; + if (HGBASE_ERR_OK != HGBase_PostPumpMessage(m_msgPump, &msg)) + { +#if defined(HG_CMP_MSC) + closesocket(param->socket); +#else + close(param->socket); +#endif + delete param; + } +} + +int WebServer::GetUserIndex(HGUInt id) +{ + int nIndex = -1; + for (int i = 0; i < (int)m_vectorUser.size(); ++i) + { + if (id == m_vectorUser[i]->GetId()) + { + nIndex = i; + break; } } - int WebServer::GetUserIndex(HGUInt id) + return nIndex; +} + +void WebServer::ThreadFunc(HGThread thread, HGPointer param) +{ + WebServer* p = (WebServer*)param; + + while (1) { - int nIndex = -1; - for (int i = 0; i < (int)m_vectorUser.size(); ++i) - { - if (id == m_vectorUser[i]->GetId()) - { - nIndex = i; - break; - } - } - - return nIndex; - } - - void WebServer::ThreadFunc(HGThread thread, HGPointer param) - { - WebServer* p = (WebServer*)param; - - while (1) - { #if defined(HG_CMP_MSC) - SOCKADDR_IN addrClient; - int len = sizeof(SOCKADDR_IN); - SOCKET socketConn = accept(p->m_sockServer, (SOCKADDR*)&addrClient, &len); - if (INVALID_SOCKET == socketConn) + SOCKADDR_IN addrClient; + int len = sizeof(SOCKADDR_IN); + SOCKET socketConn = accept(p->m_sockServer, (SOCKADDR*)&addrClient, &len); + if (INVALID_SOCKET == socketConn) #else - struct sockaddr_in addrClient; - socklen_t len = sizeof(addrClient); - int socketConn = accept(p->m_sockServer, (struct sockaddr*)&addrClient, &len); - if (-1 == socketConn) + struct sockaddr_in addrClient; + socklen_t len = sizeof(addrClient); + int socketConn = accept(p->m_sockServer, (struct sockaddr*)&addrClient, &len); + if (-1 == socketConn) #endif - { - // Ƿرm_sockServer - break; - } - - p->PostConnectMsg(inet_ntoa(addrClient.sin_addr), ntohs(addrClient.sin_port), socketConn); + { + // Ƿرm_sockServer + break; } + + p->PostConnectMsg(inet_ntoa(addrClient.sin_addr), ntohs(addrClient.sin_port), socketConn); } } \ No newline at end of file diff --git a/sdk/webservice/WebServer.h b/sdk/webservice/WebServer.h index 6e5ec69a..702c041f 100644 --- a/sdk/webservice/WebServer.h +++ b/sdk/webservice/WebServer.h @@ -7,45 +7,37 @@ #include "Msg.h" #include -namespace ver_1 +class WebServer { - class Manager; +public: + WebServer(HGMsgPump msgPump); + virtual ~WebServer(); - class WebServer - { - public: - WebServer(HGMsgPump msgPump, Manager* manager); - virtual ~WebServer(); + HGMsgPump GetMsgPump(); + bool Open(HGUShort port); + bool Close(); - HGMsgPump GetMsgPump(); - Manager* GetManager(); + virtual void Connect(const ConnectParam* param) = 0; + void DisConnect(const DisConnectParam* param); - bool Open(HGUShort port); - bool Close(); - - virtual void Connect(const ConnectParam* param) = 0; - void DisConnect(const DisConnectParam* param); - - protected: +protected: #if defined(HG_CMP_MSC) - void PostConnectMsg(const char* ip, uint16_t port, SOCKET sockConn); + void PostConnectMsg(const std::string &ip, uint16_t port, SOCKET sockConn); #else - void PostConnectMsg(const char* ip, uint16_t port, int sockConn); + void PostConnectMsg(const std::string &ip, uint16_t port, int sockConn); #endif - int GetUserIndex(HGUInt id); - static void ThreadFunc(HGThread thread, HGPointer param); + int GetUserIndex(HGUInt id); + static void ThreadFunc(HGThread thread, HGPointer param); - protected: - HGMsgPump m_msgPump; - Manager* m_manager; +protected: + HGMsgPump m_msgPump; - HGUInt m_currUserId; + HGUInt m_currUserId; #if defined(HG_CMP_MSC) - SOCKET m_sockServer; + SOCKET m_sockServer; #else - int m_sockServer; + int m_sockServer; #endif - HGThread m_listenThread; - std::vector m_vectorUser; - }; -} \ No newline at end of file + HGThread m_listenThread; + std::vector m_vectorUser; +}; \ No newline at end of file diff --git a/sdk/webservice/WebUser.cpp b/sdk/webservice/WebUser.cpp index ef5e7d9c..b74f8925 100644 --- a/sdk/webservice/WebUser.cpp +++ b/sdk/webservice/WebUser.cpp @@ -2,82 +2,74 @@ #include "WebServer.h" #include "base/HGInfo.h" -namespace ver_1 +#if defined(HG_CMP_MSC) +WebUser::WebUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, SOCKET sockConn) +#else +WebUser::WebUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, int sockConn) +#endif +{ + m_server = server; + HGBase_CreateLock(&m_cs); + m_id = id; + m_ip = ip; + m_port = port; + + m_sockConn = sockConn; + m_thread = NULL; +} + +WebUser::~WebUser() { #if defined(HG_CMP_MSC) - WebUser::WebUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, SOCKET sockConn) + closesocket(m_sockConn); + m_sockConn = INVALID_SOCKET; #else - WebUser::WebUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, int sockConn) + close(m_sockConn); + m_sockConn = -1; #endif + HGBase_CloseThread(m_thread); + m_thread = NULL; + + m_port = 0; + m_ip.clear(); + m_id = 0; + HGBase_DestroyLock(m_cs); + m_server = NULL; +} + +void WebUser::Open() +{ + HGBase_OpenThread(ThreadFunc, this, &m_thread); + assert(NULL != m_thread); +} + +HGUInt WebUser::GetId() +{ + return m_id; +} + +void WebUser::PostDisConnectMsg() +{ + DisConnectParam* param = new DisConnectParam; + param->svr = m_server; + param->usrId = m_id; + + HGMsg msg; + msg.id = MSGID_DISCONNECT; + msg.data = param; + if (HGBASE_ERR_OK != HGBase_PostPumpMessage(m_server->GetMsgPump(), &msg)) { - m_server = server; - HGBase_CreateLock(&m_cs); - m_id = id; - strcpy(m_ip, ip); - m_port = port; - - m_sockConn = sockConn; - m_thread = NULL; - } - - WebUser::~WebUser() - { -#if defined(HG_CMP_MSC) - closesocket(m_sockConn); - m_sockConn = INVALID_SOCKET; -#else - close(m_sockConn); - m_sockConn = -1; -#endif - HGBase_CloseThread(m_thread); - m_thread = NULL; - - m_port = 0; - memset(m_ip, 0, sizeof(m_ip)); - m_id = 0; - HGBase_DestroyLock(m_cs); - m_server = NULL; - } - - void WebUser::Open() - { - HGBase_OpenThread(ThreadFunc, this, &m_thread); - assert(NULL != m_thread); - } - - HGUInt WebUser::GetId() - { - return m_id; - } - - Manager* WebUser::GetManager() - { - return m_server->GetManager(); - } - - void WebUser::PostDisConnectMsg() - { - DisConnectParam* param = new DisConnectParam; - param->svr = m_server; - param->usrId = m_id; - - HGMsg msg; - msg.id = MSGID_DISCONNECT; - msg.data = param; - if (HGBASE_ERR_OK != HGBase_PostPumpMessage(m_server->GetMsgPump(), &msg)) - { - delete param; - } - } - - void WebUser::ThreadFunc() - { - HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "WebUser::ThreadFunc"); - } - - void WebUser::ThreadFunc(HGThread thread, HGPointer param) - { - WebUser* p = (WebUser*)param; - p->ThreadFunc(); + delete param; } } + +void WebUser::ThreadFunc() +{ + HGBase_WriteInfo(HGBASE_INFOTYPE_DESC, "WebUser::ThreadFunc"); +} + +void WebUser::ThreadFunc(HGThread thread, HGPointer param) +{ + WebUser* p = (WebUser*)param; + p->ThreadFunc(); +} diff --git a/sdk/webservice/WebUser.h b/sdk/webservice/WebUser.h index 0eaecd05..2636ada3 100644 --- a/sdk/webservice/WebUser.h +++ b/sdk/webservice/WebUser.h @@ -5,45 +5,41 @@ #include "base/HGLock.h" #include "base/HGThread.h" #include "base/HGMsgPump.h" +#include -namespace ver_1 +class WebServer; + +class WebUser { - class WebServer; - class Manager; - - class WebUser - { - public: +public: #if defined(HG_CMP_MSC) - WebUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, SOCKET sockConn); + WebUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, SOCKET sockConn); #else - WebUser(WebServer* server, HGUInt id, const char* ip, uint16_t port, int sockConn); + WebUser(WebServer* server, HGUInt id, const std::string& ip, uint16_t port, int sockConn); #endif - virtual ~WebUser(); + virtual ~WebUser(); - void Open(); - HGUInt GetId(); - Manager* GetManager(); + void Open(); + HGUInt GetId(); - protected: - void PostDisConnectMsg(); - virtual void ThreadFunc(); +protected: + void PostDisConnectMsg(); + virtual void ThreadFunc(); - private: - static void ThreadFunc(HGThread thread, HGPointer param); +private: + static void ThreadFunc(HGThread thread, HGPointer param); - protected: - WebServer* m_server; - HGLock m_cs; - HGUInt m_id; - char m_ip[16]; - uint16_t m_port; +protected: + WebServer* m_server; + HGLock m_cs; + HGUInt m_id; + std::string m_ip; + uint16_t m_port; #if defined(HG_CMP_MSC) - SOCKET m_sockConn; + SOCKET m_sockConn; #else - int m_sockConn; + int m_sockConn; #endif - HGThread m_thread; - }; -} + HGThread m_thread; +}; diff --git a/sdk/webservice/main.cpp b/sdk/webservice/main.cpp index aeee4761..8c4eda95 100644 --- a/sdk/webservice/main.cpp +++ b/sdk/webservice/main.cpp @@ -3,7 +3,8 @@ #include "base/HGThread.h" #include "base/HGUtility.h" #include "base/HGMsgPump.h" -#include "Manager.h" +#include "ManagerV1.h" +#include "ManagerV2.h" #include "HttpServer.h" #include "SockIoServer.h" #include "WSServer.h" @@ -22,7 +23,7 @@ static void ThreadFunc(HGThread thread, HGPointer param) HGBase_GetProfileInt(cfgPath, "version", "verNum", 2, &verNum); if (1 == verNum) // 使用V1版本接口 { - ver_1::Manager manager(msgPump); + ver_1::ManagerV1 manager(msgPump); ver_1::HttpServer httpServer(msgPump, &manager); ver_1::SockIoServer sockIoServer(msgPump, &manager); @@ -34,7 +35,12 @@ static void ThreadFunc(HGThread thread, HGPointer param) } else // 使用V2版本接口 { - + ver_2::ManagerV2 manager(msgPump); + ver_2::WSServer wsServer(msgPump, &manager); + + wsServer.Open(38999); + HGBase_RunMsgPump(msgPump, ver_2::HGMsgPumpCallback, NULL); + wsServer.Close(); } } diff --git a/utility/HGString.cpp b/utility/HGString.cpp index 4c4ff71e..aa056041 100644 --- a/utility/HGString.cpp +++ b/utility/HGString.cpp @@ -32,20 +32,20 @@ static std::string Utf8ToAnsi(const char* text) } #endif -std::string Utf8ToStdString(const char* utf8) +std::string Utf8ToStdString(const std::string& utf8Str) { #if defined(HG_CMP_MSC) - return Utf8ToAnsi(utf8); + return Utf8ToAnsi(utf8Str.c_str()); #else - return utf8; + return utf8Str; #endif } -std::string StdStringToUtf8(const char* str) +std::string StdStringToUtf8(const std::string& stdStr) { #if defined(HG_CMP_MSC) - return AnsiToUtf8(str); + return AnsiToUtf8(stdStr.c_str()); #else - return str; + return stdStr; #endif } \ No newline at end of file diff --git a/utility/HGString.h b/utility/HGString.h index 79c0180e..5040d1e3 100644 --- a/utility/HGString.h +++ b/utility/HGString.h @@ -6,9 +6,9 @@ // 标准字符串:windows下为ansi编码,linux下为utf8编码 // UTF8转标准字符串 -std::string Utf8ToStdString(const char* utf8); +std::string Utf8ToStdString(const std::string& utf8Str); // 标准字符串转UTF8 -std::string StdStringToUtf8(const char* str); +std::string StdStringToUtf8(const std::string& stdStr); #endif /* __HGSTRING_H__ */ \ No newline at end of file