Commit 58ac7830 by wangquyuan

Initial commit

0 parents
cmake_minimum_required(VERSION 2.8)
project(YgydServer)
set(SOLUTION_DIR ${CMAKE_CURRENT_SOURCE_DIR})
# gether moduls
list(APPEND CMAKE_MODULE_PATH ${SOLUTION_DIR}/cmake)
# install dir
set(CMAKE_INSTALL_PREFIX ${SOLUTION_DIR}/build CACHE STRING "set install prefix" FORCE)
# set base flags
set(CMAKE_CFLAGS "${CMAKE_C_FLAGS} -fvisibility=hidden -Wall")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -Wall -std=c++14 -fpermissive -mavx2 -mfma")
set(CMAKE_CFLAGS "${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
# option for platform
set(PLATFORM "x64" CACHE STRING "auto, x86 or x64")
set(CONFIGURATION "Debug" CACHE STRING "Debug or Release")
# env
include(LOCAL_ENV)
#include(INC_ORZ)
#include(INC_SEETA_LOCK)
add_definitions(-D_WEBSOCKETPP_CPP11_STL_)
add_definitions(-DASIO_STANDALONE)
if ("${PLATFORM}" STREQUAL "x86")
message(STATUS "Platform: " ${PLATFORM})
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32")
elseif ("${PLATFORM}" STREQUAL "x64")
message(STATUS "Platform: " ${PLATFORM})
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m64")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m64")
endif()
if ("${CONFIGURATION}" STREQUAL "Debug")
message(STATUS "Configuration: " ${CONFIGURATION})
set(CMAKE_CX_FLAGS "${CMAKE_CX_FLAGS} -O0 -g -ggdb")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -g -ggdb")
else()
message(STATUS "Configuration: " ${CONFIGURATION})
set(CMAKE_CX_FLAGS "${CMAKE_CX_FLAGS} -O3")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3")
endif()
add_subdirectory(${SOLUTION_DIR}/src)
#add_subdirectory(${SOLUTION_DIR}/example)
No preview for this file type
{
"bindip":"",
"http_port":4000,
"http_work_threads":5,
"work_timeout":10,
"logpath":"/tmp",
"models": {
"face_detector":"SeetaFaceDetector6.0.IPC.sta",
"face_landmarker81":"SeetaFaceLandmarker5.0.pts81.tsm.sta",
"face_landmarker5":"SeetaFaceLandmarker5.0.pts5.tsm.sta",
"face_recognizer":"SeetaFaceRecognizer6.0.Resnet101.Arcface.20200713.tsm.json",
"pose_model":"SeetaPoseEstimation1.1.0.sta",
"actionunit_model":"SeetaActionUnit1.0.0.ext.sta",
"emotion_model":"SeetaEmotionRecognizer1.0.tsm.sta",
"eye_model":"SeetaEyeBlink.squeezenet.4class.214000.1010.sta"
}
}
The file could not be displayed because it is too large.
The file could not be displayed because it is too large.
No preview for this file type
{
"backbone": {
"tsm": "@file@resnet101_arcface_lffd-plfd_0713.tsm"
},
"required": "2020-07-13",
"global": {
"threshold": 0.7,
"input": {
"channels": 3,
"width": 112,
"height": 112,
"format": "HWC"
},
"compare": {
"op": "dot"
},
"similarity": {
"op": "none"
},
"output": {
"size": 512
}
},
"post_processor": {
"normalize": true,
"sqrt_times": 0
},
"alignment":{
"version": "arcface",
"width": 112,
"height": 112,
"channels": 3
},
"pre_processor": [
{
"op": "to_float"
},
{
"scale": 0.00392156862745098,
"op": "scale"
},
{
"op": "to_chw"
}
]
}
\ No newline at end of file
No preview for this file type
The file could not be displayed because it is too large.
# include orz
# option
if (MSVC)
set(ORZ_ROOT_DIR "D:/3rd/local" CACHE STRING "The ORZ library")
else()
set(ORZ_ROOT_DIR "/usr/local" CACHE STRING "The ORZ library")
endif()
message(STATUS "Found ORZ in ${ORZ_ROOT_DIR}")
# build
message(STATUS "Build with ORZ")
include_directories(${ORZ_ROOT_DIR}/${ENV_HEADER_DIR})
link_directories(${ORZ_ROOT_DIR}/${ENV_ARCHIVE_DIR})
link_directories(${ORZ_ROOT_DIR}/lib)
find_library(LIB_ORZ_PATH ORZ_static${ENV_SUFFIX} ${ORZ_ROOT_DIR}/${ENV_ARCHIVE_DIR})
message(STATUS ${ORZ_ROOT_DIR}/${ENV_ARCHIVE_DIR})
target_link_libraries(${PROJECT_NAME} ${LIB_ORZ_PATH})
# include seeta_lock
# option
if (MSVC)
set(SEETA_LOCK_ROOT_DIR "D:/3rd/local" CACHE STRING "The ORZ library")
else()
set(SEETA_LOCK_ROOT_DIR "/wqy/seeta_sdk/sdk/sdk6.0/common/seetaauthorize" CACHE STRING "The ORZ library")
endif()
message(STATUS "Found SeetaLock in ${SEETA_LOCK_ROOT_DIR}")
message(STATUS "Build with SeetaLock")
include_directories(${SEETA_LOCK_ROOT_DIR}/${ENV_HEADER_DIR})
link_directories(${SEETA_LOCK_ROOT_DIR}/${ENV_ARCHIVE_DIR})
link_directories(${SEETA_LOCK_ROOT_DIR}/lib)
#option
option(SEETA_LOCK_SDK "Using SeetaLock" OFF)
option(SEETA_LOCK_SDK_ONLINE "Using SeetaLock online" OFF)
option(SEETA_LOCK_SDK_LOCAL "Using SeetaLock local" OFF)
option(SEETA_LOCK_MODEL "Using SeetaLock lock model" OFF)
#option(TIME_LOCK "Using Time Lock" OFF)
#set(TIME_LOCK_YEAR "2017" CACHE STRING "Set limit year")
#set(TIME_LOCK_MONTH "9" CACHE STRING "Set limit mouth")
#set(TIME_LOCK_DAY "30" CACHE STRING "Set limit day")
set(SEETA_LOCK_ABILITY "" CACHE STRING "local check ability, like 1002 1003")
set(SEETA_LOCK_FINCID "" CACHE STRING "auto check func_id, like 1002")
set(SEETA_LOCK_KEY "" CACHE STRING "lock key, like XJ37DUTJ")
set(SEETA_LOCK_MODEL_KEY "" CACHE STRING "lock model key, like XJ37DUTJ")
if (SEETA_LOCK_SDK_ONLINE)
set(SEETA_LOCK_SDK ON)
add_definitions(-DSEETA_LOCK_SDK_ONLINE)
message(STATUS "SeetaLock online: ON")
else()
message(STATUS "SeetaLock online: OFF")
endif()
if (SEETA_LOCK_SDK_LOCAL)
set(SEETA_LOCK_SDK ON)
add_definitions(-DSEETA_LOCK_SDK_LOCAL)
message(STATUS "SeetaLock local: ON")
else()
message(STATUS "SeetaLock local: OFF")
endif()
if (SEETA_LOCK_MODEL)
set(SEETA_LOCK_SDK ON)
add_definitions(-DSEETA_LOCK_MODEL)
message(STATUS "SeetaLock model: ON")
else()
message(STATUS "SeetaLock model: OFF")
endif()
if (SEETA_LOCK_ABILITY STREQUAL "")
else()
add_definitions(-DSEETA_LOCK_ABILITY=${SEETA_LOCK_ABILITY})
message(STATUS "SeetaLock ability: ${SEETA_LOCK_ABILITY}")
endif()
if (SEETA_LOCK_FINCID STREQUAL "")
else()
add_definitions(-DSEETA_LOCK_FINCID=${SEETA_LOCK_FINCID})
message(STATUS "SeetaLock funcid: ${SEETA_LOCK_FINCID}")
endif()
if (SEETA_LOCK_KEY STREQUAL "")
else()
add_definitions(-DSEETA_LOCK_KEY=${SEETA_LOCK_KEY})
message(STATUS "SeetaLock key: ${SEETA_LOCK_KEY}")
endif()
if (SEETA_LOCK_MODEL_KEY STREQUAL "")
set(SEETA_LOCK_MODEL_KEY ${SEETA_LOCK_KEY})
endif()
if (SEETA_LOCK_MODEL_KEY STREQUAL "")
else()
add_definitions(-DSEETA_LOCK_MODEL_KEY=${SEETA_LOCK_MODEL_KEY})
message(STATUS "SeetaLock model key: ${SEETA_LOCK_MODEL_KEY}")
endif()
if (SEETA_LOCK_SDK)
add_definitions(-DSEETA_LOCK_SDK)
message(STATUS "SeetaLock: ON")
else()
message(STATUS "SeetaLock: OFF")
endif()
# set flags
set(ENV_RUNTIME_DIR "bin")
set(ENV_LIBRARY_DIR "lib")
set(ENV_ARCHIVE_DIR "lib")
set(ENV_HEADER_DIR "include")
set(ENV_SUFFIX "")
if (MSVC)
if ("${PLATFORM}" STREQUAL "")
elseif("${PLATFORM}" STREQUAL "auto")
else ()
set(ENV_RUNTIME_DIR ${ENV_RUNTIME_DIR}/${PLATFORM})
set(ENV_LIBRARY_DIR ${ENV_LIBRARY_DIR}/${PLATFORM})
set(ENV_ARCHIVE_DIR ${ENV_ARCHIVE_DIR}/${PLATFORM})
endif ()
elseif (MINGW)
if ("${PLATFORM}" STREQUAL "")
elseif("${PLATFORM}" STREQUAL "auto")
else ()
set(ENV_RUNTIME_DIR ${ENV_RUNTIME_DIR}/${PLATFORM})
set(ENV_LIBRARY_DIR ${ENV_LIBRARY_DIR}/${PLATFORM})
set(ENV_ARCHIVE_DIR ${ENV_ARCHIVE_DIR}/${PLATFORM})
endif ()
else()
if ("${PLATFORM}" STREQUAL "x86")
set(ENV_RUNTIME_DIR ${ENV_RUNTIME_DIR})
set(ENV_LIBRARY_DIR ${ENV_LIBRARY_DIR}32)
set(ENV_ARCHIVE_DIR ${ENV_ARCHIVE_DIR}32)
elseif ("${PLATFORM}" STREQUAL "x64")
set(ENV_RUNTIME_DIR ${ENV_RUNTIME_DIR})
set(ENV_LIBRARY_DIR ${ENV_LIBRARY_DIR}64)
set(ENV_ARCHIVE_DIR ${ENV_ARCHIVE_DIR}64)
endif()
endif()
if ("${CONFIGURATION}" STREQUAL "Debug")
set(ENV_SUFFIX "d")
endif ()
set(ENV_INCLUDE_DIR ${ENV_HEADER_DIR})
#!/usr/bin/env bash
export BUILD_DIR=build.linux.x64
export BUILD_TYPE=Debug
export PLATFORM_TARGET=x64
export PLATFORM=x64
export ORZ_HOME=/usr/local
export SSL_HOME=/usr
HOME=$(cd `dirname $0`; pwd)
cd $HOME
mkdir "$BUILD_DIR"
cd "$BUILD_DIR"
cmake "$HOME/.." \
-DCMAKE_BUILD_TYPE="$BUILD_TYPE" \
-DCONFIGURATION="$BUILD_TYPE" \
-DPLATFORM="$PLATFORM_TARGET" \
-DOPENSSL_ROOT_DIR="$SSL_HOME" \
-DORZ_ROOT_DIR="$ORZ_HOME" \
-DCMAKE_INSTALL_PREFIX="$INSTALL_DIR" \
-DCMAKE_MODULE_PATH="/wqy/works/http/FaceDetectorServer/cmake;/wqy/seeta_sdk/sdk/sdk6.0/common/FaceRecognizer/cmake;/wqy/seeta_sdk/sdk/sdk6.0/common/SeetaCV/cmake;/wqy/seeta_sdk/sdk/sdk6.0/common/Landmarker/cmake;/wqy/seeta_sdk/sdk/sdk6.0/common/faceboxes/cmake;/wqy/seeta_sdk/sdk/sdk6.0/common/TenniS/cmake;/wqy/seeta_sdk/sdk/sdk6.0/common/seetaauthorize/cmake" \
-DSEETA_AUTHORIZE=OFF \
-DSEETA_MODEL_ENCRYPT=ON
make -j16
#make install
# execute in subdir
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
#add_definitions(-DVIPL_EXPORTS)
#add_definitions(-DSEETA_EXPORTS)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
file(GLOB ROOT_SRC_FILES
${CMAKE_CURRENT_SOURCE_DIR}/*.c
${CMAKE_CURRENT_SOURCE_DIR}/*.cc
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
)
file(GLOB_RECURSE SEETA_SRC_FILES
${CMAKE_CURRENT_SOURCE_DIR}/seeta/*.c
${CMAKE_CURRENT_SOURCE_DIR}/seeta/*.cc
${CMAKE_CURRENT_SOURCE_DIR}/seeta/*.cpp
)
#file(GLOB_RECURSE ORZ_SRC_FILES
# ${CMAKE_CURRENT_SOURCE_DIR}/orz/*.c
# ${CMAKE_CURRENT_SOURCE_DIR}/orz/*.cc
# ${CMAKE_CURRENT_SOURCE_DIR}/orz/*.cpp
# )
file(GLOB_RECURSE SEETA_API_SRC_FILES
${CMAKE_CURRENT_SOURCE_DIR}/src/*.c
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cc
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp
)
file(GLOB_RECURSE SEETA_INCLUDE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/include/*.h
${CMAKE_CURRENT_SOURCE_DIR}/include/*.hh
${CMAKE_CURRENT_SOURCE_DIR}/include/*.hpp
)
list(APPEND SRC_FILES ${SEETA_SRC_FILES})
#list(APPEND SRC_FILES ${ORZ_SRC_FILES})
list(APPEND SRC_FILES ${ROOT_SRC_FILES})
list(APPEND SRC_FILES ${SEETA_API_SRC_FILES})
# add library
#add_library(${PROJECT_NAME}_SHARED SHARED ${SRC_FILES})
add_executable(${PROJECT_NAME} ${SRC_FILES})
# simple lock
#if (SIMPLE_LOCK)
# target_link_libraries(${PROJECT_NAME}_SHARED -lsimple_crypto -lcrypto)
#endif()
# link SeetaLock
#if (SEETA_LOCK_SDK)
# target_link_libraries(${PROJECT_NAME}_SHARED SeetaLock_static${ENV_SUFFIX})
#endif()
# link ORZ
#target_link_libraries(${PROJECT_NAME}_SHARED ORZ_static${ENV_SUFFIX})
# link OpenSSL
#find_package(OpenSSL REQUIRED)
#include_directories(${OPENSSL_INCLUDE_DIR})
#target_link_libraries(${PROJECT_NAME} ${OPENSSL_CRYPTO_LIBRARY})
#target_link_libraries(${PROJECT_NAME} ${OPENSSL_SSL_LIBRARY})
include_directories(/wqy/tools/openssl1.1.1.c/include)
target_link_libraries(${PROJECT_NAME} -L/wqy/tools/openssl1.1.1.c/lib -lssl -lcrypto)
include(INC_ORZ)
#find_package(LibEvent REQUIRED)
#include_directories(${LIBEVENT_INCLUDE_DIRS})
#target_link_libraries(${PROJECT_NAME} ${LIBEVENT_LIBRARIES})
include_directories(/wqy/package/asio-1.18.1/include)
include_directories(/wqy/package/websocketpp)
include_directories(/usr/local/include)
#target_link_libraries(${PROJECT_NAME} -L/usr/local/lib -lmysqlcppconn)
#include_directories(/wqy/seeta_sdk/sdk/SeetaAIP/include)
#include_directories(/wqy/test/test/libevhtp-master/include)
#target_link_libraries(${PROJECT_NAME} -L/wqy/test/test/libevhtp-master/build -levhtp)
#include_directories(/usr/local/include/log4cxx)
#target_link_libraries(${PROJECT_NAME} -L/usr/local/lib -llog4cxx)
#include_directories(/usr/include)
#target_link_libraries(${PROJECT_NAME} -L/usr/lib/x86_64-linux-gnu -lsqlite3)
#include_directories(/usr/local/include)
#target_link_libraries(${PROJECT_NAME} -L/usr/local/lib -lprotobuf -lgrpc++ -lgrpc -lgpr -lz -lssl -lcrypto -lgrpc++_reflection -ldl)
#include_directories(/wqy/test/test2/srpc/_include)
#target_link_libraries(${PROJECT_NAME} -L/usr/local/lib -lz -lssl -lcrypto -ldl)
#include_directories(/wqy/test/test2/srpc/workflow/_include)
#target_link_libraries(${PROJECT_NAME} -L/wqy/test/test2/srpc/example -lsrpc -lworkflow -lprotobuf)
target_link_libraries(${PROJECT_NAME} -L/usr/local/lib -lORZ_static)
#include_directories(/usr/local/include)
#target_link_libraries(${PROJECT_NAME} -L/usr/local/lib -lmysqlcppconn)
#include_directories(/usr/local/mysql/connector-c++-8.0/include)
#target_link_libraries(${PROJECT_NAME} -L/usr/local/mysql/connector-c++-8.0/lib64 -lmysqlcppconn8)
#find_package(SeetaFaceDetector REQUIRED)
#include_directories(${SeetaFaceDetector_INCLUDE_DIRS})
#target_link_libraries(${PROJECT_NAME} ${SeetaFaceDetector_LIBRARIES})
#find_package(SeetaFaceLandmarker REQUIRED)
#include_directories(${SeetaFaceLandmarker_INCLUDE_DIRS})
#target_link_libraries(${PROJECT_NAME} ${SeetaFaceLandmarker_LIBRARIES})
#find_package(SeetaFaceRecognizer REQUIRED)
#include_directories(${SeetaFaceRecognizer_INCLUDE_DIRS})
#target_link_libraries(${PROJECT_NAME} ${SeetaFaceRecognizer_LIBRARIES})
#find_package(SeetaCV REQUIRED)
#include_directories(${SeetaCV_INCLUDE_DIRS})
#target_link_libraries(${PROJECT_NAME} ${SeetaCV_LIBRARIES})
#include_directories(/wqy/tools/opencv4_home/include/opencv4)
#target_link_libraries(${PROJECT_NAME} -L/wqy/tools/opencv4_home/lib -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_imgcodecs)
target_link_libraries(${PROJECT_NAME} -pthread -lrt)
# more link library
#include(holiday)
#include_directories(${HOLIDAY_INCLUDE_DIRS})
#target_link_libraries(${PROJECT_NAME}_SHARED ${HOLIDAY_LIBRARIES})
#target_link_libraries(${PROJECT_NAME}_SHARED -lTensorStack)
#target_link_libraries(${PROJECT_NAME}_SHARED -lopencv_core -lopencv_imgproc -lopencv_highgui)
#find_package(SeetaPoseEstimation REQUIRED)
#include_directories(${SeetaPoseEstimation_INCLUDE_DIRS})
#target_link_libraries(${PROJECT_NAME}_SHARED ${SeetaPoseEstimation_LIBRARIES})
#find_package(TensorStack REQUIRED)
#include_directories(${TensorStack_INCLUDE_DIRS})
#target_link_libraries(${PROJECT_NAME}_SHARED ${TensorStack_LIBRARIES})
#find_package(TenniS REQUIRED)
#include_directories(${TenniS_INCLUDE_DIRS})
#target_link_libraries(${PROJECT_NAME}_SHARED ${TenniS_LIBRARIES})
# set library properties
#if ("${CONFIGURATION}" STREQUAL "Debug")
# set_target_properties(${PROJECT_NAME}_SHARED PROPERTIES OUTPUT_NAME ${PROJECT_NAME}d)
#else()
# set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME ${PROJECT_NAME})
#endif()
# build dir
set(OUT_DIR ${SOLUTION_DIR}/build)
#create install dir
file(MAKE_DIRECTORY ${OUT_DIR})
set(EXECUTABLE_OUTPUT_PATH ${OUT_DIR})
#set(LIBRARY_OUTPUT_PATH ${OUT_DIR}/${ENV_LIBRARY_DIR})
# add command to copy header files
#add_custom_command(TARGET ${PROJECT_NAME}
# PRE_BUILD
# COMMAND ${CMAKE_COMMAND} -E make_directory ${OUT_DIR}/${ENV_INCLUDE_DIR}
# )
#add_custom_command(TARGET ${PROJECT_NAME}
# PRE_BUILD
# COMMAND ${CMAKE_COMMAND} -E make_directory ${OUT_DIR}/${ENV_INCLUDE_DIR}/seeta
# )
# copy every header files
#foreach(header ${INCLUDE_FILES})
# add_custom_command(TARGET ${PROJECT_NAME}
# POST_BUILD
# COMMAND ${CMAKE_COMMAND} -E copy_if_different ${header} ${OUT_DIR}/${ENV_INCLUDE_DIR}
# )
#endforeach()
#foreach(header ${SEETA_INCLUDE_FILES})
# add_custom_command(TARGET ${PROJECT_NAME}
# POST_BUILD
# COMMAND ${CMAKE_COMMAND} -E copy_if_different ${header} ${OUT_DIR}/${ENV_INCLUDE_DIR}/seeta
# )
#endforeach()
#install(FILES ${INCLUDE_FILES} DESTINATION ${CMAKE_INSTALL_PREFIX}/${ENV_INCLUDE_DIR})
#install(FILES ${SEETA_INCLUDE_FILES} DESTINATION ${CMAKE_INSTALL_PREFIX}/${ENV_INCLUDE_DIR}/seeta)
No preview for this file type
#ifndef __CONDITIONVARIABLEQUEUE__H__
#define __CONDITIONVARIABLEQUEUE__H__
#include <pthread.h>
#include <list>
//////////////////////////////////
template <class T>
class CConditionVariableQueue {
private:
pthread_mutex_t m_mutex;
pthread_cond_t m_cond;
volatile bool m_bexit;
std::list<T *> m_datalst;
// unsigned int m_maxsize;
// unsigned int m_used;
public:
CConditionVariableQueue() {
pthread_cond_init( &m_cond, NULL );
pthread_mutex_init( &m_mutex, NULL );
// m_maxsize = 10000;
// m_used = 0;
m_bexit = false;
}
~CConditionVariableQueue() {
clearQueue();
pthread_mutex_destroy( &m_mutex );
pthread_cond_destroy( &m_cond );
}
unsigned int size() {
unsigned int nret = 0;
pthread_mutex_lock( &m_mutex );
nret = m_datalst.size();
// nret = m_used + m_datalst.size();
pthread_mutex_unlock( &m_mutex );
return nret;
}
/*
unsigned int decrease()
{
unsigned int nret = 0;
pthread_mutex_lock(&m_mutex);
if(m_used > 0)
m_used--;
nret = m_used;
pthread_mutex_unlock(&m_mutex);
return nret;
}
unsigned int increase()
{
unsigned int nret = 0;
pthread_mutex_lock(&m_mutex);
m_used++;
nret = m_used;
pthread_mutex_unlock(&m_mutex);
return nret;
}
*/
void clearQueueWithoutDel() {
pthread_mutex_lock( &m_mutex );
m_datalst.clear();
pthread_mutex_unlock( &m_mutex );
}
void clearQueue() {
pthread_mutex_lock( &m_mutex );
typename std::list<T *>::iterator iter;
for( iter = m_datalst.begin(); iter != m_datalst.end(); ++iter ) {
if( *iter ) delete *iter;
}
m_datalst.clear();
pthread_mutex_unlock( &m_mutex );
}
bool empty() {
bool bret;
pthread_mutex_lock( &m_mutex );
bret = m_datalst.empty();
pthread_mutex_unlock( &m_mutex );
return bret;
}
void push( T *data ) {
pthread_mutex_lock( &m_mutex );
m_datalst.push_back( data );
// m_count++;
pthread_mutex_unlock( &m_mutex );
pthread_cond_signal( &m_cond );
}
T *try_pop() {
T *ptr = NULL;
pthread_mutex_lock( &m_mutex );
if( !m_datalst.empty() ) {
ptr = m_datalst.front();
m_datalst.pop_front();
// m_used++;
}
pthread_mutex_unlock( &m_mutex );
return ptr;
}
T *wait_and_pop( int timeout ) { // mileseconds
struct timespec ntimeout;
ntimeout.tv_sec = timeout / 1000;
ntimeout.tv_nsec = 0;
T *ptr = NULL;
pthread_mutex_lock( &m_mutex );
while( m_datalst.empty() ) {
if( pthread_cond_timedwait( &m_cond, &m_mutex, &ntimeout ) != 0 ) {
pthread_mutex_unlock( &m_mutex );
return ptr;
}
}
if( !m_datalst.empty() ) {
ptr = m_datalst.front();
m_datalst.pop_front();
// m_used++;
}
pthread_mutex_unlock( &m_mutex );
return ptr;
}
};
#endif
#ifndef __SEQUENCE_H__
#define __SEQUENCE_H__
#include <mutex>
//#include <iostream>
#include <sys/types.h>
//#include <stdint.h>
class CSequence
{
public:
CSequence(u_int64_t nbegin, u_int64_t nend=0xFFFFFFFF)
{
m_maxsequence = nend;
//m_sequence = nbegin ;
//m_prefix = prefix;
//u_int64_t value = prefix;
//value = (value << 60);
m_sequence = nbegin + 1;// + value + 1;
//std::cout << "begin:" << nbegin << ",prefix:" << (int)prefix << std::endl;
//std::cout << "value:" << value << std::endl;
//std::cout << "seq:" << m_sequence << std::endl;
}
~CSequence()
{
}
u_int64_t GetValue()
{
u_int64_t nret = 0;
m_lock.lock();
nret = m_sequence;
if(m_sequence + 1 == m_maxsequence)
{
//m_sequence = m_prefix;
m_sequence = 1;//(m_sequence << 60);
}else
{
m_sequence++;
}
m_lock.unlock();
return nret;
}
private:
u_int64_t m_sequence;
//u_int64_t m_minsequence;
u_int64_t m_maxsequence;
//unsigned char m_prefix;
std::mutex m_lock;
};
#endif
#ifndef __BASE64_H__
#define __BASE64_H__
#include <string>
std::string base64_encode(const std::string &bin);
std::string base64_decode(const std::string &codes);
#endif
#ifndef __CONFIG_H__
#define __CONFIG_H__
#include "orz/io/jug/jugbinder.h"
#include <string>
class MysqlConfig : public orz::JSONObject {
public:
using self = MysqlConfig;
JSONField( self, std::string, host );
JSONField( self, std::string, user );
JSONField( self, std::string, passwd );
JSONField( self, std::string, db);
};
class ModelsConfig : public orz::JSONObject {
public:
using self = ModelsConfig;
JSONField( self, std::string, face_detector);
JSONField( self, std::string, face_landmarker81);
JSONField( self, std::string, face_landmarker5);
JSONField( self, std::string, face_recognizer);
JSONField( self, std::string, pose_model);
JSONField( self, std::string, actionunit_model);
JSONField( self, std::string, emotion_model);
JSONField( self, std::string, eye_model);
};
class Config : public orz::JSONObject {
public:
using self = Config;
JSONField( self, std::string, logpath );
JSONField( self, std::string, bindip );
JSONField( self, unsigned short, http_port );
JSONField( self, int, http_work_threads );
JSONField( self, int, work_timeout ) = 10;
//JSONField( self, MysqlConfig, db );
JSONField( self, ModelsConfig, models );
};
Config *parse_config( const std::string &name );
#endif
#ifndef __DO_REQUEST_H__
#define __DO_REQUEST_H__
#include <string>
#include <websocketpp/config/asio.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
struct bone_config : public websocketpp::config::asio
{
// pull default settings from our core config
typedef websocketpp::config::asio core;
typedef core::concurrency_type concurrency_type;
typedef core::request_type request_type;
typedef core::response_type response_type;
typedef core::message_type message_type;
typedef core::con_msg_manager_type con_msg_manager_type;
typedef core::endpoint_msg_manager_type endpoint_msg_manager_type;
typedef core::alog_type alog_type;
typedef core::elog_type elog_type;
typedef core::rng_type rng_type;
typedef core::endpoint_base endpoint_base;
static bool const enable_multithreading = true;
static size_t const max_message_size = 2048 * 1000 * 1000;
struct transport_config : public core::transport_config
{
typedef core::concurrency_type concurrency_type;
typedef core::elog_type elog_type;
typedef core::alog_type alog_type;
typedef core::request_type request_type;
typedef core::response_type response_type;
static bool const enable_multithreading = true;
};
typedef websocketpp::transport::asio::endpoint<transport_config>
transport_type;
static const websocketpp::log::level elog_level =
websocketpp::log::elevel::all;
static const websocketpp::log::level alog_level =
websocketpp::log::alevel::all;
};
/*
struct bone_config : public websocketpp::config::asio_tls
{
// pull default settings from our core config
typedef websocketpp::config::asio core;
typedef core::concurrency_type concurrency_type;
typedef core::request_type request_type;
typedef core::response_type response_type;
typedef core::message_type message_type;
typedef core::con_msg_manager_type con_msg_manager_type;
typedef core::endpoint_msg_manager_type endpoint_msg_manager_type;
typedef core::alog_type alog_type;
typedef core::elog_type elog_type;
typedef core::rng_type rng_type;
typedef core::endpoint_base endpoint_base;
static bool const enable_multithreading = true;
struct transport_config : public core::transport_config
{
typedef core::concurrency_type concurrency_type;
typedef core::elog_type elog_type;
typedef core::alog_type alog_type;
typedef core::request_type request_type;
typedef core::response_type response_type;
static bool const enable_multithreading = true;
};
typedef websocketpp::transport::asio::endpoint<transport_config>
transport_type;
static const websocketpp::log::level elog_level =
websocketpp::log::elevel::all;
static const websocketpp::log::level alog_level =
websocketpp::log::alevel::all;
};
*/
//typedef websocketpp::server<websocketpp::config::asio_tls> httpsserver;
typedef websocketpp::server<bone_config> httpserver;
//typedef websocketpp::lib::shared_ptr<websocketpp::lib::asio::ssl::context> context_ptr;
//typedef httpserver::context_ptr context_ptr;
//typedef websocketpp::server<bone_config> server;
//typedef server::message_ptr message_ptr;
void on_http( httpserver *s, websocketpp::connection_hdl hdl );
#endif
#ifndef __ERRORCODE_H__
#define __ERRORCDOE_H__
#include <vector>
#include <string>
struct ErrorCode
{
int code;
std::string msg;
};
std::string GetError(int code);
#endif
#ifndef __SIMPLELOG_HPP__
#define __SIMPLELOG_HPP__
//#include "common.hpp"
//#include "lock.hpp" //Add by xiajw@asiainfo 2008/04/02 for http core
//#include "singleton.hpp"
#include <iostream>
#include <string>
#include <string.h>
//using std::string;
typedef enum
{
LL_ERROR = 1,
LL_WARN,
LL_INFO,
LL_DEBUG,
} LOGLEVEL;
#define _ERROR_ __FILE__, __LINE__, LL_ERROR
#define _WARN_ __FILE__, __LINE__, LL_WARN
#define _INFO_ __FILE__, __LINE__, LL_INFO
#define _DEBUG_ __FILE__, __LINE__, LL_DEBUG
#define GETNULLPTR(s) (s) == nullptr || strlen((s)) <= 0 ? "NULL" : (s)
#define GETNULLSTR(s) (s).empty() ? "NULL" : (s).c_str()
// Note:
// we must call the initLogFile(logfile, loglevel)
// before run the log thread.
//
class CSimpleLog {
public:
CSimpleLog() {
m_ltLevel = LL_INFO;
m_ltLogFile = "";
m_ltInitFlag = false;
m_debug = false;
}
//constructor
CSimpleLog( std::string logfile, LOGLEVEL level )
: m_ltLogFile( logfile ), m_ltLevel( level ) {
m_ltLogFile = "";
m_ltLevel = LL_INFO;
m_ltInitFlag = false;
m_debug = false;
}
virtual ~CSimpleLog() {
}
public:
//write normal log info
void writeLog( const std::string &filename, int line,
LOGLEVEL level, const char *fmt, ... );
//write binary log info
void writeHex( const std::string &filename, int line, LOGLEVEL level,
const std::string &title, const char *buf, int buflen );
//cout normal log info
void coutLog( const std::string &filename, int line,
LOGLEVEL level, const char *fmt, ... );
//cout binary log info
void coutHex( const std::string &filename, int line, LOGLEVEL level,
const std::string &title, const char *buf, int buflen );
public:
//init log file
int initLogFile( const std::string &logfile, LOGLEVEL level );
public:
//Helpers
LOGLEVEL &logLevel() {
return m_ltLevel;
}
void setDebugMode( bool value ) {
m_debug = value;
}
static CSimpleLog *m_log;
static CSimpleLog *instance();
private:
//get level string
std::string getLevelString( LOGLEVEL level );
private:
//log file name
std::string m_ltLogFile;
//log level that permitted output
LOGLEVEL m_ltLevel;
bool m_debug;
//flag to indicate whether initialized
bool m_ltInitFlag;
};
#define LOG CSimpleLog::instance()->writeLog
#define LOGHEX CSimpleLog::instance()->writeHex
#endif
#ifndef __UTIL_H__
#define __UTIL_H__
#include <map>
#include <string>
#include <vector>
std::string get_uuid(const std::string &prefix);
std::string create_transactionid(const std::string &prefix);
std::string get_format_date();
std::string md5(const std::string &data);
int GetExePathAndName( std::string &exepath, std::string &exename );
std::string &trim( std::string &text );
int splits( const std::string &str, const std::string &strsplit, std::vector<std::string> &vec );
int createdir( const std::string &dest );
//int hex2dec(char c);
//char dec2hex(short c);
unsigned char ToHex( unsigned char x );
unsigned char FromHex( unsigned char x );
//std::string urlencode( const std::string &url );
//std::string urldecode( const std::string &url );
int checkinstance();
std::string encodeuricomponent( const std::string &str );
std::string decodeuricomponent( const std::string &str );
void geturlparameters(const std::string &str, std::map<std::string, std::string> &params);
std::string encodetojson(const std::string &str);
#endif
No preview for this file type
No preview for this file type
#include "base64.h"
static const char base64_encode_map[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const int base64_decode_map[] =
{
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 1
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, // 2
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, // 3
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 4
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, // 5
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 6
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 // 7
};
std::string base64_encode( const std::string &bin )
{
std::string codes;
std::string buff = bin;
size_t un = buff.length() % 3;
size_t extending = 0;
if( un ) extending = 3 - un;
for( size_t i = 0; i < extending; ++i ) buff.push_back( '\0' );
for( size_t i = 2; i < buff.size(); i += 3 )
{
int bin_code = ( buff[i - 2] & 0xff ) << 16;
bin_code |= ( buff[i - 1] & 0xff ) << 8;
bin_code |= ( buff[i] & 0xff );
codes.push_back( base64_encode_map[bin_code >> 18 & 0x3f] );
codes.push_back( base64_encode_map[bin_code >> 12 & 0x3f] );
codes.push_back( base64_encode_map[bin_code >> 6 & 0x3f] );
codes.push_back( base64_encode_map[bin_code & 0x3f] );
}
for( size_t i = 0; i < extending; ++i ) codes[codes.size() - 1 - i] = '=';
return std::move( codes );
}
std::string base64_decode( const std::string &codes )
{
std::string bin;
auto &buff = codes;
int equal_sign_count = 0;
int bin_code = 0;
int bin_code_count = 0;
for( size_t i = 0; i < buff.size(); ++i )
{
char ch = buff[i];
if( ch & 0x80 )
{
return "";
}
auto idx = base64_decode_map[int( ch )];
if( idx < 0 )
{
if( ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' ) continue;
else if( ch == '=' ) equal_sign_count++;
else
{
return "";
}
}
if( equal_sign_count > 0 && idx >= 0 )
{
return "";
}
bin_code = ( bin_code << 6 ) | ( idx & 0xff );
if( ++bin_code_count < 4 ) continue;
bin.push_back( char( bin_code >> 16 & 0xff ) );
bin.push_back( char( bin_code >> 8 & 0xff ) );
bin.push_back( char( bin_code & 0xff ) );
bin_code = 0;
bin_code_count = 0;
}
if( bin_code != 0 )
{
return "";
}
if( equal_sign_count > 2 )
{
return "";
}
for( int i = 0; i < equal_sign_count; ++i ) bin.pop_back();
return std::move( bin );
}
#include "config.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include "orz/codec/json.h"
Config *parse_config( const std::string &name )
{
std::ifstream t( name.c_str() );
if( !t.is_open() )
{
std::cout << "read config:" << name << " failed" << std::endl;
return NULL;
}
std::stringstream buffer;
buffer << t.rdbuf();
std::string contents( buffer.str() );
Config *config = new Config;
try
{
orz::jug configjug = orz::json2jug( contents );
config->parse( configjug );
if( config->bindip.length() < 1 )
{
config->bindip = "0.0.0.0";
}
}
catch( std::exception &e )
{
delete config;
std::cout << "parse config file failed:" << e.what() << std::endl;
return NULL;
}
return config;
}
#include "do_request.h"
//#include <websocketpp/config/asio_no_tls.hpp>
//#include <websocketpp/server.hpp>
#include <iostream>
#include <fstream>
#include <map>
#include <list>
#include <mutex>
#include <future>
#include <chrono>
#include <set>
//#include "eupulogger4system.h"
#include "util.h"
#include "errorcode.h"
//#include "MysqlConnectPool.h"
//#include "data_model.h"
#include "include/config.h"
#include "include/simplelog.h"
#include "include/base64.h"
//#include "include/protocol.h"
#include "include/Sequence.h"
//#include "include/param_update.h"
#include "orz/io/jug/piece.h"
#include "orz/codec/json.h"
//#include "user.h"
extern CSequence *g_seq;
using std::string;
extern Config *g_config;
std::mutex g_mutex;
/*
std::map<std::string, PotInfo *> g_pots;
std::map<void *, std::list<PotInfo *> * > g_cons;
std::map<void *, std::string > g_devices;
//std::map<void *, std::time_t > g_keepalives;
std::map<websocketpp::connection_hdl, std::time_t, std::owner_less<websocketpp::connection_hdl> > g_keepalives;
std::map<unsigned int, std::promise<std::string> *> g_futures;
server::timer_ptr g_timer;
*/
//std::map<std::string, std::string> g_data_trans;
//std::map<std::string, std::set<std::string> > g_param_trans;
//std::set<std::string > g_trans;
//ParamUpdate g_paramupdate;
//DataTableUpdate g_datatableupdate;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
// pull out the type of messages sent by our config
//typedef server::message_ptr message_ptr;
/*
void on_socket_init(websocketpp::connection_hdl, websocketpp::lib::asio::ip::tcp::socket & s) {
websocketpp::lib::asio::ip::tcp::no_delay option(true);
s.set_option(option);
}
*/
/*
void on_socket_init(websocketpp :: connection_hdl hdl,boost:: asio :: ssl :: stream< ; boost :: asio :: ip :: tcp :: socket>& s){
boost :: asio :: ip :: tcp :: no_delay option(true);
s.lowest_layer()。set_option(option);
}
*/
void create_http_response( httpserver::connection_ptr con, const std::string &body, int status )
{
con->set_body( body );
con->set_status( ( websocketpp::http::status_code::value )status ); //websocketpp::http::status_code::ok
//con->append_header("Access-Control-Allow-Headers","X-Requested-With,Content-Type,Authorization");
//con->append_header("Access-Control-Allow-Origin","*");
//con->append_header("Access-Control-Expose-Headers","Authorization");
con->append_header( "Content-Type", "application/json; charset=UTF-8" );
//con->append_header( "Content-Length", std::to_string(body.length()) );
//con->append_header("Keep-Alive","50");
//con->append_header("Connection","Keep-alive");
//con->append_header("Transfer-Encoding","chunked");
//con->append_header("Accept","application/json, text/plain, */*");
//con->append_header("Accept-Encoding","gzip, deflate");
//con->append_header("Access-Control-Request-Method","POST,GET");
}
static std::string do_query_device( const std::string &body )
{
std::string strresponse;
try
{
/*
orz::jug devicejug = orz::json2jug( body );
QueryDeviceJson dev;
dev.parse( devicejug );
bool bfind = false;
g_mutex.lock();
std::map<std::string, PotInfo *>::iterator iter = g_pots.find( dev.potuid );
if( iter != g_pots.end() )
{
bfind = true;
strresponse = "{\"code\":0,\"msg\":\"ok\",\"servers\":";
strresponse += "{\"secretkey\":\"" + iter->second->secretkey + "\",\"ip\":";
strresponse += "\"" + iter->second->ip + "\",\"port\":" ;
strresponse += std::to_string( iter->second->port ) + ",\"desc\":\"";
strresponse += iter->second->desc + "\"}}";
}
g_mutex.unlock();
if( !bfind )
{
PotInfo info;
std::string sql = "select deviceid,appid,ip,port,state,type,secretkey,description,create_date,";
sql += "update_date ,potuid,os from " + g_config->db.db + ".pots where potuid='" + dev.potuid + "'";
int nret = doQueryMySql_pots( sql, info );
if( nret > 0 )
{
strresponse = "{\"code\":0,\"msg\":\"ok\",\"servers\":";
strresponse += "{\"secretkey\":\"" + info.secretkey + "\",\"ip\":";
strresponse += "\"" + info.ip + "\",\"port\":" ;
strresponse += std::to_string( info.port ) + ",\"desc\":\"";
strresponse += info.desc + "\"}}";
}
else
{
LOG( _ERROR_, "access db failed:%s", GETNULLSTR( sql ) );
strresponse = "{\"code\":8,\"msg\":\"" + GetError( 8 ) + "\"}";
}
}
*/
//create_http_response( con, strresponse, 200 );
}
catch( std::exception &e )
{
LOG( _ERROR_, "parse message failed:%s", GETNULLPTR( e.what() ) );
//std::cout << "parse message failed:" << e.what() << std::endl;
strresponse = "{\"code\":1,\"msg\":\"" + GetError( 1 ) + "\"}";
}
return strresponse;
}
void on_http( httpserver *s, websocketpp::connection_hdl hdl )
{
httpserver::connection_ptr con = s->get_con_from_hdl( hdl );
websocketpp::http::parser::request rt = con->get_request();
const std::string &strUri = rt.get_uri();
const std::string &strMethod = rt.get_method();
const std::string &strBody = rt.get_body();
const std::string &strVersion = rt.get_version();
//std::string token = rt.get_header("token");
//std::cout << "recv a:" << strMethod.c_str() << "request:" << strUri.c_str() << "thread ID=" << pthread_self() << std::endl;
//websocketpp::http::parser::response rp;
//string strContent = rt.raw();
//rp.consume(strContent.c_str(), strContent.size());
std::stringstream ss;
//string strHost = rt.get_header("Host");
//if(strHost.length() > 0)
//{
// std::cout << "----Host:" << strHost << std::endl;
//con->append_header("Remote Address",strHost);
//con->append_header("Access-Control-Allow-Origin",strHost);
//}
int nret = 0;
int nstatus = 200;
std::string strresponse;
if( strMethod == "POST" )
{
//std::cout << "post:body:" << strBody << std::endl;
if( strUri == "/query/device" )
{
strresponse = do_query_device( strBody );
create_http_response( con, strresponse, 200 );
}
else
{
//std::cout << "----no method:" << strMethod << std::endl;
strresponse = "the request is not implement";
LOG( _WARN_, "no support get method:%s", GETNULLSTR( strUri ) );
create_http_response( con, strresponse, 404 );
}
}
else if( strMethod == "GET" )
{
std::string method;
std::string parameters;
int nfind = strUri.find("?");
if(nfind >= 0)
{
method = strUri.substr(0, nfind);
parameters = strUri.substr(nfind + 1);
}else
{
method = strUri;
}
std::cout << "header:" << parameters << std::endl;
std::map<std::string, std::string>::iterator iter;
std::map<std::string, std::string> params;
geturlparameters(parameters, params);
if( method == "/query/pots" )
{
//strresponse = do_query_pots( strBody );
create_http_response( con, strresponse, 200 );
}else
{
strresponse = "the request is not implement";
LOG( _WARN_, "no support get method:%s", GETNULLSTR( strUri ) );
create_http_response( con, strresponse, 404 );
}
}
else
{
create_http_response( con, "not support request", 404 );
LOG( _WARN_, "no support get method:%s", GETNULLSTR( strUri ) );
}
}
#include "errorcode.h"
static std::vector<ErrorCode> errors =
{
{0, "ok"},
{1, "json format is incorrect"},
{2, "signature is incorrect" },
{3, "authorization parameter is incorrect"},
{4, "parameters are incorrect"},
{5, "request is not support yet"},
{6, "database is not avilable"},
{7, "request format is incorrect"},
{8, "this pot is not existed"},
{9, "this pot is offline"},
{10, "this pot is timeout"},
{11, "this transactionid is invalid"},
{12, "this template's child template is not empty"},
{13, "this template is being used by pots"},
{14, "this parameter version is not found"},
{15, "this table is not existed"},
{16, "this data version is too old"},
{17, "this table already exists"},
{18, "this template already exists"},
{19, "this pot's parameter is empty"},
{20, "this template is not existed"},
{21, "user do not register"},
{22, "user do not login"},
{23, "do not find token parameter"},
{24, "the image size is more than 64k"},
{25, "the username already exists"},
{26, "the insert data do not match the table columns"},
{27, "this template type already exists"},
};
std::string GetError( int code )
{
if( ( code >= 0 ) && ( code < errors.size() ) )
{
return errors[code].msg;
}
return std::string( "" );
}
#include "simplelog.h"
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <stdarg.h>
#include <unistd.h>
#include <mutex>
#include <string.h>
using std::string;
using std::cout;
using std::endl;
#define MAX_MSGSIZE 1500
//SIMPLELOG_S instance
CSimpleLog *CSimpleLog::m_log = NULL;
CSimpleLog *CSimpleLog::instance()
{
static std::once_flag checker_instance;
std::call_once( checker_instance, []()
{
m_log = new CSimpleLog;
} );
return m_log;
}
static string cmnGetFileNameWithDayStamp( const string &filename )
{
string dsname = filename;
//parameter check
if( dsname.empty() )
{
return dsname;
}
struct timeval tmv;
struct tm tme;
char buf[128];
memset( buf, 0, sizeof( buf ) );
memset( &tmv, 0, sizeof( tmv ) );
memset( &tme, 0, sizeof( tme ) );
gettimeofday( &tmv, NULL );
localtime_r( &tmv.tv_sec, &tme );
snprintf( buf, sizeof( buf ) - 1, "%04d%02d%02d",
tme.tm_year + 1900, tme.tm_mon + 1, tme.tm_mday );
dsname += ".";
dsname += string( buf );
return dsname;
}
static std::string ConvertStr2Hex( const char *buf, int32_t buflen )
{
char sbuf[MAX_MSGSIZE * 3];
int32_t binlen = sizeof( sbuf );
if( !buf || ( buflen < 0 ) || ( binlen < buflen * 3 + 1 ) )
{
return "";
}
memset( sbuf, 0, binlen );
unsigned char ch;
for( int32_t i = 0; i < buflen; i++ )
{
ch = ( unsigned char )buf[i];
snprintf( sbuf + 3 * i, MAX_MSGSIZE * 3, "%2.2x ", ch );
}
return std::string( sbuf );
}
//
// init the log file
//
int CSimpleLog::initLogFile( const string &logfile, LOGLEVEL level )
{
if( m_ltInitFlag )
{
return 0;
}
//save information
m_ltLogFile = logfile;
m_ltLevel = level;
m_ltInitFlag = true;
return 0;
}
void CSimpleLog::writeLog( const string &filename, int line, LOGLEVEL level, const char *fmt, ... )
{
//check whether log initialized
if( m_ltLogFile.empty() )
{
return;
}
//check the level
if( level > m_ltLevel )
{
//level lower
return;
}
//get real log file name
string dsname = cmnGetFileNameWithDayStamp( m_ltLogFile );
int fd = open( dsname.c_str(), O_RDWR | O_APPEND | O_CREAT | O_LARGEFILE, 0644 );
if( 0 > fd )
{
return;
}
char msgbuf[MAX_MSGSIZE];
char buf[MAX_MSGSIZE + 1024];
struct timeval tmv;
struct tm tme;
va_list arglist;
memset( msgbuf, 0, sizeof( msgbuf ) );
memset( buf, 0, sizeof( buf ) );
memset( &tmv, 0, sizeof( tmv ) );
memset( &tme, 0, sizeof( tme ) );
gettimeofday( &tmv, NULL );
localtime_r( &tmv.tv_sec, &tme );
va_start( arglist, fmt );
vsnprintf( msgbuf, sizeof( msgbuf ) - 1, fmt, arglist );
va_end( arglist );
//get the log string
snprintf( buf, sizeof( buf ) - 1, "%04d/%02d/%02d %02d:%02d:%02d:%06u [0x%08x, 0x%08x] <%-8s> (%s, %06d) %s\n",
tme.tm_year + 1900, tme.tm_mon + 1, tme.tm_mday, tme.tm_hour, tme.tm_min, tme.tm_sec, ( unsigned int )tmv.tv_usec,
( int )getpid(), ( int )pthread_self(), getLevelString( level ).c_str(), filename.c_str(), line, msgbuf );
//write to log file
write( fd, buf, strlen( buf ) );
//close the file descriptor
close( fd );
if( m_debug )
{
std::cout << buf << std::endl;
}
return;
}
void CSimpleLog::coutLog( const string &filename, int line, LOGLEVEL level, const char *fmt, ... )
{
char msgbuf[MAX_MSGSIZE];
char buf[MAX_MSGSIZE + 1024];
struct timeval tmv;
struct tm tme;
va_list arglist;
//check the level
if( level > m_ltLevel )
{
return;
}
memset( msgbuf, 0, sizeof( msgbuf ) );
memset( buf, 0, sizeof( buf ) );
memset( &tmv, 0, sizeof( tmv ) );
memset( &tme, 0, sizeof( tme ) );
gettimeofday( &tmv, NULL );
localtime_r( &tmv.tv_sec, &tme );
va_start( arglist, fmt );
vsnprintf( msgbuf, sizeof( msgbuf ) - 1, fmt, arglist );
va_end( arglist );
//get the log string
snprintf( buf, sizeof( buf ) - 1, "%04d/%02d/%02d %02d:%02d:%02d:%06u [0x%08x, 0x%08x] <%-8s> (%s, %06d) %s\n",
tme.tm_year + 1900, tme.tm_mon + 1, tme.tm_mday, tme.tm_hour, tme.tm_min, tme.tm_sec, ( unsigned int )tmv.tv_usec,
( int )getpid(), ( int )pthread_self(), getLevelString( level ).c_str(), filename.c_str(), line, msgbuf );
cout << buf;
return;
};
void CSimpleLog::writeHex( const string &filename, int line, LOGLEVEL level,
const string &title, const char *buf, int buflen )
{
//check whether log initialized
if( m_ltLogFile.empty() )
{
return;
}
//parameter check
if( !buf || ( buflen <= 0 ) )
{
return;
}
//check the level
if( level > m_ltLevel )
{
//level lower
return;
}
//get real log file name
string dsname = cmnGetFileNameWithDayStamp( m_ltLogFile );
int fd = open( dsname.c_str(), O_RDWR | O_APPEND | O_CREAT | O_LARGEFILE, 0644 );
if( 0 > fd )
{
return;
}
char msgbuf[MAX_MSGSIZE];
struct timeval tmv;
struct tm tme;
memset( msgbuf, 0, sizeof( msgbuf ) );
memset( &tmv, 0, sizeof( tmv ) );
memset( &tme, 0, sizeof( tme ) );
gettimeofday( &tmv, NULL );
localtime_r( &tmv.tv_sec, &tme );
string hexdata = ConvertStr2Hex( buf, buflen );
//write to buf
//get the log string
snprintf( msgbuf, sizeof( msgbuf ) - 1, "%04d/%02d/%02d %02d:%02d:%02d:%06u [0x%08x, 0x%08x] <%-8s> (%s, %06d) %s: \n%s\n",
tme.tm_year + 1900, tme.tm_mon + 1, tme.tm_mday, tme.tm_hour, tme.tm_min, tme.tm_sec, ( unsigned int )tmv.tv_usec,
( int )getpid(), ( int )pthread_self(), getLevelString( level ).c_str(), filename.c_str(),
line, title.c_str(), hexdata.c_str() );
//write to file
write( fd, msgbuf, strlen( msgbuf ) );
//close fd
close( fd );
if( m_debug )
{
std::cout << msgbuf << std::endl;
}
return;
}
void CSimpleLog::coutHex( const string &filename, int line, LOGLEVEL level,
const string &title, const char *buf, int buflen )
{
char msgbuf[MAX_MSGSIZE];
struct timeval tmv;
struct tm tme;
//parameter check
if( !buf || ( buflen <= 0 ) )
{
return;
}
//check the level
if( level > m_ltLevel )
{
return;
}
memset( msgbuf, 0, sizeof( msgbuf ) );
memset( &tmv, 0, sizeof( tmv ) );
memset( &tme, 0, sizeof( tme ) );
gettimeofday( &tmv, NULL );
localtime_r( &tmv.tv_sec, &tme );
string hexdata = ConvertStr2Hex( buf, buflen );
//write to buf
//get the log string
snprintf( msgbuf, sizeof( msgbuf ) - 1, "%04d/%02d/%02d %02d:%02d:%02d:%06u [0x%08x, 0x%08x] <%-8s> (%s, %06d) %s: \n%s\n",
tme.tm_year + 1900, tme.tm_mon + 1, tme.tm_mday, tme.tm_hour, tme.tm_min, tme.tm_sec, ( unsigned int )tmv.tv_usec,
( int )getpid(), ( int )pthread_self(), getLevelString( level ).c_str(), filename.c_str(),
line, title.c_str(), hexdata.c_str() );
cout << msgbuf;
return;
}
string CSimpleLog::getLevelString( LOGLEVEL level )
{
string levelstr = "UNKNOWN";
switch( level )
{
case LL_ERROR:
levelstr = "ERROR";
break;
case LL_WARN:
levelstr = "WARN";
break;
case LL_INFO:
levelstr = "INFO";
break;
case LL_DEBUG:
levelstr = "DEBUG";
break;
};
return levelstr;
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!