commit 78baf7a4714d97cfacd7ba6fc4ccf161df59597b Author: DESKTOP-LBGFPFF\CHAOS-PC Date: Sat Sep 18 13:45:24 2021 +0800 第一次上传 diff --git a/.cproject b/.cproject new file mode 100644 index 0000000..40c9b67 --- /dev/null +++ b/.cproject @@ -0,0 +1,192 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + all + true + true + true + + + make + + clear + true + true + true + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6db035b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +Debug/ +Release/ diff --git a/.project b/.project new file mode 100644 index 0000000..e525552 --- /dev/null +++ b/.project @@ -0,0 +1,27 @@ + + + WirelessGateway + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/.settings/language.settings.xml b/.settings/language.settings.xml new file mode 100644 index 0000000..b743081 --- /dev/null +++ b/.settings/language.settings.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.settings/org.eclipse.cdt.codan.core.prefs b/.settings/org.eclipse.cdt.codan.core.prefs new file mode 100644 index 0000000..6ac0e36 --- /dev/null +++ b/.settings/org.eclipse.cdt.codan.core.prefs @@ -0,0 +1,74 @@ +eclipse.preferences.version=1 +org.eclipse.cdt.codan.checkers.errnoreturn=Warning +org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"No return\\")",implicit\=>false} +org.eclipse.cdt.codan.checkers.errreturnvalue=Error +org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused return value\\")"} +org.eclipse.cdt.codan.checkers.nocommentinside=-Error +org.eclipse.cdt.codan.checkers.nocommentinside.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Nesting comments\\")"} +org.eclipse.cdt.codan.checkers.nolinecomment=-Error +org.eclipse.cdt.codan.checkers.nolinecomment.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Line comments\\")"} +org.eclipse.cdt.codan.checkers.noreturn=Error +org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"No return value\\")",implicit\=>false} +org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error +org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Abstract class cannot be instantiated\\")"} +org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error +org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Ambiguous problem\\")"} +org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=Warning +org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Assignment in condition\\")"} +org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=Error +org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Assignment to itself\\")"} +org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=Warning +org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"No break at end of case\\")",no_break_comment\=>"no break",last_case_param\=>false,empty_case_param\=>false,enable_fallthrough_quickfix_param\=>false} +org.eclipse.cdt.codan.internal.checkers.CatchByReference=Warning +org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Catching by reference is recommended\\")",unknown\=>false,exceptions\=>()} +org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error +org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Circular inheritance\\")"} +org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=Warning +org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Class members should be properly initialized\\")",skip\=>true} +org.eclipse.cdt.codan.internal.checkers.DecltypeAutoProblem=Error +org.eclipse.cdt.codan.internal.checkers.DecltypeAutoProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid 'decltype(auto)' specifier\\")"} +org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error +org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Field cannot be resolved\\")"} +org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error +org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Function cannot be resolved\\")"} +org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error +org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid arguments\\")"} +org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error +org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid template argument\\")"} +org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error +org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Label statement not found\\")"} +org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error +org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Member declaration not found\\")"} +org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error +org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Method cannot be resolved\\")"} +org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info +org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Name convention for function\\")",pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} +org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=Warning +org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Class has a virtual method and non-virtual destructor\\")"} +org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error +org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid overload\\")"} +org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error +org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid redeclaration\\")"} +org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error +org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid redefinition\\")"} +org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning +org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Return with parenthesis\\")"} +org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning +org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Format String Vulnerability\\")"} +org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=Warning +org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Statement has no effect\\")",macro\=>true,exceptions\=>()} +org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=Warning +org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Suggested parenthesis around expression\\")",paramNot\=>false} +org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=Warning +org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Suspicious semicolon\\")",else\=>false,afterelse\=>false} +org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error +org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Type cannot be resolved\\")"} +org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=Warning +org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused function declaration\\")",macro\=>true} +org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=Warning +org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused static function\\")",macro\=>true} +org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=Warning +org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused variable declaration in file scope\\")",macro\=>true,exceptions\=>("@(\#)","$Id")} +org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error +org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Symbol is not resolved\\")"} +useParentScope=false diff --git a/API_log/SH_log.cpp b/API_log/SH_log.cpp new file mode 100644 index 0000000..ecd9a5e --- /dev/null +++ b/API_log/SH_log.cpp @@ -0,0 +1,88 @@ +#include "SH_log.h" + +#include +#include +#include +#include +#include +#include +#include + + +struct _LogParam { + pthread_mutex_t *m_mutex; + int m_limit_size; + int m_log_buf_size; + int m_today; + FILE *m_fp; + char m_log_full_name[256]; + char *m_buf; +} gLogParam; + + +int log_init(const char* file_name, int log_buf_size, int limit_size) +{ + memset(gLogParam.m_log_full_name, 0, 256); + gLogParam.m_mutex = new pthread_mutex_t; + pthread_mutex_init(gLogParam.m_mutex, NULL); + + gLogParam.m_log_buf_size = log_buf_size; + gLogParam.m_buf = new char[gLogParam.m_log_buf_size]; + memset(gLogParam.m_buf, '\0', sizeof(char) * gLogParam.m_log_buf_size); + gLogParam.m_limit_size = limit_size; + + strcpy(gLogParam.m_log_full_name, file_name); + + return 0; +} + +void log_write(const char *level, const char* format, ...) +{ + FILE *fp = fopen(gLogParam.m_log_full_name, "a"); + if(fp == NULL) { + return; + } + + memset(gLogParam.m_buf, 0, sizeof(char)*gLogParam.m_log_buf_size); + + struct timeval now = {0,0}; + gettimeofday(&now, NULL); + time_t t = now.tv_sec; + struct tm* sys_tm = localtime(&t); + + + pthread_mutex_lock(gLogParam.m_mutex); + + int n = snprintf(gLogParam.m_buf, 64, "%d-%02d-%02d %02d:%02d:%02d %s: ", sys_tm->tm_year+1900, sys_tm->tm_mon+1, sys_tm->tm_mday, + sys_tm->tm_hour, sys_tm->tm_min, sys_tm->tm_sec, level); + + + int old_seek = ftell(fp); + fseek(fp, 0, SEEK_END); + int file_size = ftell(fp); + fseek(fp, old_seek, SEEK_SET); + if (file_size > gLogParam.m_limit_size) { + fclose(fp); + + char cmd[256] = { 0 }; + sprintf(cmd, "cp %s %s_bak", gLogParam.m_log_full_name, gLogParam.m_log_full_name); + system(cmd); + remove(gLogParam.m_log_full_name); + fp = fopen(gLogParam.m_log_full_name, "a"); + if(fp == NULL) { + return; + } + } + + va_list valst; + va_start(valst, format); + + int m = vsnprintf(gLogParam.m_buf + n, gLogParam.m_log_buf_size -n -1, format, valst); + gLogParam.m_buf[n + m - 1] = '\n'; + fwrite(gLogParam.m_buf, n + m, 1, fp); + + va_end(valst); + fclose(fp); + + pthread_mutex_unlock(gLogParam.m_mutex); +} diff --git a/API_log/SH_log.h b/API_log/SH_log.h new file mode 100644 index 0000000..9a8b222 --- /dev/null +++ b/API_log/SH_log.h @@ -0,0 +1,21 @@ + +#ifndef LOG_H +#define LOG_H + +#include +#include +#include + +#define LEVEL_DEBUG (char *)"[debug]" +#define LEVEL_INFO (char *)"[info]" +#define LEVEL_WARN (char *)"[warn]" +#define LEVEL_ERR (char *)"[err]" + +int log_init(const char* file_name, int log_buf_size, int limit_size); +void log_write(const char *level, const char *format, ...); + +#define LOG_DEBUG(format, ...) log_write(LEVEL_DEBUG, format, ##__VA_ARGS__) +#define LOG_INFO(format, ...) log_write(LEVEL_INFO, format, ##__VA_ARGS__) +#define LOG_WARN(format, ...) log_write(LEVEL_WARN, format, ##__VA_ARGS__) +#define LOG_ERROR(format, ...) log_write(LEVEL_ERR, format, ##__VA_ARGS__) +#endif diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..481d64f --- /dev/null +++ b/Makefile @@ -0,0 +1,71 @@ +TARGET = Cidn-SH +OBJ_PATH = $(shell pwd)/debug +PREFIX_BIN = + +CC = arm-linux-gnueabihf-g++ +STRIP = arm-linux-gnueabihf-strip +INCLUDES = -I../third_party/boost/include \ + -I../third_party/fftw/include \ + -I../third_party/jsoncpp/include \ + -I../third_party/sqlite/include/ + +LIBS = -L../third_party/boost/lib \ + -L../third_party/fftw/lib \ + -L../third_party/ssl/lib \ + -L../third_party/jsoncpp \ + -L../third_party/mqtt1410/lib \ + -L../third_party/sqlite/lib \ + -lsqlite3 -lboost_system -lpthread -lboost_thread -lboost_date_time -lfftw3 -lssl -lcrypto -ljson -lmosquitto + +CFLAGS = -O2 #-Wall -Werror +LINKFLAGS = + +AllDirs :=$(shell ls -R | grep '^\./.*:' | awk '{if( \ + substr($$1,3,5) != "debug") {gsub(":",""); print}}') . + +Sources := $(foreach n,$(AllDirs) , $(wildcard $(n)/*.cpp)) + +#C_SOURCES = $(wildcard *.c) +C_SRCDIR = $(AllDirs) +C_SOURCES = $(foreach d,$(C_SRCDIR),$(wildcard $(d)/*.c) ) +C_OBJS = $(patsubst %.c, $(OBJ_PATH)/%.o, $(C_SOURCES)) + +#CPP_SOURCES = $(wildcard *.cpp) +CPP_SRCDIR = $(AllDirs) +CPP_SOURCES = $(foreach d,$(CPP_SRCDIR),$(wildcard $(d)/*.cpp) ) +CPP_OBJS = $(patsubst %.cpp, $(OBJ_PATH)/%.o, $(CPP_SOURCES)) + +default:init compile strip + +$(C_OBJS):$(OBJ_PATH)/%.o:%.c + $(CC) -c $(CFLAGS) $(INCLUDES) $< -o $@ + +$(CPP_OBJS):$(OBJ_PATH)/%.o:%.cpp + $(CC) -c $(CFLAGS) $(INCLUDES) $< -o $@ + +init: + $(foreach d,$(AllDirs), mkdir -p $(OBJ_PATH)/$(d);) + +test: + @echo "C_SOURCES: $(C_SOURCES)" + @echo "C_OBJS: $(C_OBJS)" + @echo "CPP_SOURCES: $(CPP_SOURCES)" + @echo "CPP_OBJS: $(CPP_OBJS)" + +compile:$(C_OBJS) $(CPP_OBJS) + $(CC) -O2 -o $(TARGET) $^ $(LINKFLAGS) $(LIBS) + +clean: + rm -rf $(OBJ_PATH) + rm -f $(TARGET) + +install: $(TARGET) + cp $(TARGET) $(PREFIX_BIN) + +uninstall: + rm -f $(PREFIX_BIN)/$(TARGET) +strip: + $(STRIP) $(TARGET) + cp $(TARGET) ~/tftpboot + +rebuild: clean compile diff --git a/Makefile_mips b/Makefile_mips new file mode 100644 index 0000000..866244d --- /dev/null +++ b/Makefile_mips @@ -0,0 +1,76 @@ +TARGET = Cidw-mips +OBJ_PATH = $(shell pwd)/debug +PREFIX_BIN = + +CC = g++ +STRIP = strip +INCLUDES = -I../cidw_lib \ + -I../cidw_lib/ibtdms-gpl-0.3/include \ + -I../cidw_lib/include \ + -I../third_party/boost/include \ + -I../third_party/fftw/include \ + -I../third_party/curl/include \ + -I../third_party/Jsoncpp/include \ + -I/usr/include/python2.7 + +LIBS = -L../cidw_lib/mips \ + -L/usr/lib/python2.7 \ + -L../third_party/boost/lib \ + -L../third_party/fftw/lib \ + -L../third_party/curl/lib \ + -L../third_party/ssl/lib \ + -L../third_party/Jsoncpp/libs \ + -L../third_party/mqtt/lib \ + -lpython2.7 -lsqlite3 -lboost_system -lpthread -lboost_thread -lboost_date_time -lboost_atomic -lfftw3 -lssl -lcrypto -lcurl -ljson -lmosquitto + +CFLAGS = -O2 #-Wall -Werror +LINKFLAGS = + +AllDirs :=$(shell ls -R | grep '^\./.*:' | awk '{if( \ + substr($$1,3,5) != "debug") {gsub(":",""); print}}') . + +Sources := $(foreach n,$(AllDirs) , $(wildcard $(n)/*.cpp)) + +#C_SOURCES = $(wildcard *.c) +C_SRCDIR = $(AllDirs) +C_SOURCES = $(foreach d,$(C_SRCDIR),$(wildcard $(d)/*.c) ) +C_OBJS = $(patsubst %.c, $(OBJ_PATH)/%.o, $(C_SOURCES)) + +#CPP_SOURCES = $(wildcard *.cpp) +CPP_SRCDIR = $(AllDirs) +CPP_SOURCES = $(foreach d,$(CPP_SRCDIR),$(wildcard $(d)/*.cpp) ) +CPP_OBJS = $(patsubst %.cpp, $(OBJ_PATH)/%.o, $(CPP_SOURCES)) + +default:init compile strip + +$(C_OBJS):$(OBJ_PATH)/%.o:%.c + $(CC) -c $(CFLAGS) $(INCLUDES) $< -o $@ + +$(CPP_OBJS):$(OBJ_PATH)/%.o:%.cpp + $(CC) -c $(CFLAGS) $(INCLUDES) $< -o $@ + +init: + $(foreach d,$(AllDirs), mkdir -p $(OBJ_PATH)/$(d);) + +test: + @echo "C_SOURCES: $(C_SOURCES)" + @echo "C_OBJS: $(C_OBJS)" + @echo "CPP_SOURCES: $(CPP_SOURCES)" + @echo "CPP_OBJS: $(CPP_OBJS)" + +compile:$(C_OBJS) $(CPP_OBJS) + $(CC) -O2 -o $(TARGET) $^ $(LINKFLAGS) $(LIBS) + +clean: + rm -rf $(OBJ_PATH) + rm -f $(TARGET) + +install: $(TARGET) + cp $(TARGET) $(PREFIX_BIN) + +uninstall: + rm -f $(PREFIX_BIN)/$(TARGET) +strip: + $(STRIP) $(TARGET) + +rebuild: clean compile diff --git a/aes/aes.c b/aes/aes.c new file mode 100644 index 0000000..b62d0bb --- /dev/null +++ b/aes/aes.c @@ -0,0 +1,571 @@ +/* + +This is an implementation of the AES algorithm, specifically ECB, CTR and CBC mode. +Block size can be chosen in aes.h - available choices are AES128, AES192, AES256. + +The implementation is verified against the test vectors in: + National Institute of Standards and Technology Special Publication 800-38A 2001 ED + +ECB-AES128 +---------- + + plain-text: + 6bc1bee22e409f96e93d7e117393172a + ae2d8a571e03ac9c9eb76fac45af8e51 + 30c81c46a35ce411e5fbc1191a0a52ef + f69f2445df4f9b17ad2b417be66c3710 + + key: + 2b7e151628aed2a6abf7158809cf4f3c + + resulting cipher + 3ad77bb40d7a3660a89ecaf32466ef97 + f5d3d58503b9699de785895a96fdbaaf + 43b1cd7f598ece23881b00e3ed030688 + 7b0c785e27e8ad3f8223207104725dd4 + + +NOTE: String length must be evenly divisible by 16byte (str_len % 16 == 0) + You should pad the end of the string with zeros if this is not the case. + For AES192/256 the key size is proportionally larger. + +*/ + + +/*****************************************************************************/ +/* Includes: */ +/*****************************************************************************/ +#include // CBC mode, for memset +#include "aes.h" + +/*****************************************************************************/ +/* Defines: */ +/*****************************************************************************/ +// The number of columns comprising a state in AES. This is a constant in AES. Value=4 +#define Nb 4 + +#if defined(AES256) && (AES256 == 1) + #define Nk 8 + #define Nr 14 +#elif defined(AES192) && (AES192 == 1) + #define Nk 6 + #define Nr 12 +#else + #define Nk 4 // The number of 32 bit words in a key. + #define Nr 10 // The number of rounds in AES Cipher. +#endif + +// jcallan@github points out that declaring Multiply as a function +// reduces code size considerably with the Keil ARM compiler. +// See this link for more information: https://github.com/kokke/tiny-AES-C/pull/3 +#ifndef MULTIPLY_AS_A_FUNCTION + #define MULTIPLY_AS_A_FUNCTION 0 +#endif + + + + +/*****************************************************************************/ +/* Private variables: */ +/*****************************************************************************/ +// state - array holding the intermediate results during decryption. +typedef uint8_t state_t[4][4]; + + + +// The lookup-tables are marked const so they can be placed in read-only storage instead of RAM +// The numbers below can be computed dynamically trading ROM for RAM - +// This can be useful in (embedded) bootloader applications, where ROM is often limited. +static const uint8_t sbox[256] = { + //0 1 2 3 4 5 6 7 8 9 A B C D E F + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; + +static const uint8_t rsbox[256] = { + 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, + 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, + 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, + 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, + 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, + 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, + 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, + 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, + 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, + 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, + 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, + 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, + 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, + 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, + 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }; + +// The round constant word array, Rcon[i], contains the values given by +// x to the power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8) +static const uint8_t Rcon[11] = { + 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 }; + +/* + * Jordan Goulder points out in PR #12 (https://github.com/kokke/tiny-AES-C/pull/12), + * that you can remove most of the elements in the Rcon array, because they are unused. + * + * From Wikipedia's article on the Rijndael key schedule @ https://en.wikipedia.org/wiki/Rijndael_key_schedule#Rcon + * + * "Only the first some of these constants are actually used – up to rcon[10] for AES-128 (as 11 round keys are needed), + * up to rcon[8] for AES-192, up to rcon[7] for AES-256. rcon[0] is not used in AES algorithm." + */ + + +/*****************************************************************************/ +/* Private functions: */ +/*****************************************************************************/ +/* +static uint8_t getSBoxValue(uint8_t num) +{ + return sbox[num]; +} +*/ +#define getSBoxValue(num) (sbox[(num)]) +/* +static uint8_t getSBoxInvert(uint8_t num) +{ + return rsbox[num]; +} +*/ +#define getSBoxInvert(num) (rsbox[(num)]) + +// This function produces Nb(Nr+1) round keys. The round keys are used in each round to decrypt the states. +static void KeyExpansion(uint8_t* RoundKey, const uint8_t* Key) +{ + unsigned i, j, k; + uint8_t tempa[4]; // Used for the column/row operations + + // The first round key is the key itself. + for (i = 0; i < Nk; ++i) + { + RoundKey[(i * 4) + 0] = Key[(i * 4) + 0]; + RoundKey[(i * 4) + 1] = Key[(i * 4) + 1]; + RoundKey[(i * 4) + 2] = Key[(i * 4) + 2]; + RoundKey[(i * 4) + 3] = Key[(i * 4) + 3]; + } + + // All other round keys are found from the previous round keys. + for (i = Nk; i < Nb * (Nr + 1); ++i) + { + { + k = (i - 1) * 4; + tempa[0]=RoundKey[k + 0]; + tempa[1]=RoundKey[k + 1]; + tempa[2]=RoundKey[k + 2]; + tempa[3]=RoundKey[k + 3]; + + } + + if (i % Nk == 0) + { + // This function shifts the 4 bytes in a word to the left once. + // [a0,a1,a2,a3] becomes [a1,a2,a3,a0] + + // Function RotWord() + { + const uint8_t u8tmp = tempa[0]; + tempa[0] = tempa[1]; + tempa[1] = tempa[2]; + tempa[2] = tempa[3]; + tempa[3] = u8tmp; + } + + // SubWord() is a function that takes a four-byte input word and + // applies the S-box to each of the four bytes to produce an output word. + + // Function Subword() + { + tempa[0] = getSBoxValue(tempa[0]); + tempa[1] = getSBoxValue(tempa[1]); + tempa[2] = getSBoxValue(tempa[2]); + tempa[3] = getSBoxValue(tempa[3]); + } + + tempa[0] = tempa[0] ^ Rcon[i/Nk]; + } +#if defined(AES256) && (AES256 == 1) + if (i % Nk == 4) + { + // Function Subword() + { + tempa[0] = getSBoxValue(tempa[0]); + tempa[1] = getSBoxValue(tempa[1]); + tempa[2] = getSBoxValue(tempa[2]); + tempa[3] = getSBoxValue(tempa[3]); + } + } +#endif + j = i * 4; k=(i - Nk) * 4; + RoundKey[j + 0] = RoundKey[k + 0] ^ tempa[0]; + RoundKey[j + 1] = RoundKey[k + 1] ^ tempa[1]; + RoundKey[j + 2] = RoundKey[k + 2] ^ tempa[2]; + RoundKey[j + 3] = RoundKey[k + 3] ^ tempa[3]; + } +} + +void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key) +{ + KeyExpansion(ctx->RoundKey, key); +} +#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1)) +void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv) +{ + KeyExpansion(ctx->RoundKey, key); + memcpy (ctx->Iv, iv, AES_BLOCKLEN); +} +void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv) +{ + memcpy (ctx->Iv, iv, AES_BLOCKLEN); +} +#endif + +// This function adds the round key to state. +// The round key is added to the state by an XOR function. +static void AddRoundKey(uint8_t round, state_t* state, const uint8_t* RoundKey) +{ + uint8_t i,j; + for (i = 0; i < 4; ++i) + { + for (j = 0; j < 4; ++j) + { + (*state)[i][j] ^= RoundKey[(round * Nb * 4) + (i * Nb) + j]; + } + } +} + +// The SubBytes Function Substitutes the values in the +// state matrix with values in an S-box. +static void SubBytes(state_t* state) +{ + uint8_t i, j; + for (i = 0; i < 4; ++i) + { + for (j = 0; j < 4; ++j) + { + (*state)[j][i] = getSBoxValue((*state)[j][i]); + } + } +} + +// The ShiftRows() function shifts the rows in the state to the left. +// Each row is shifted with different offset. +// Offset = Row number. So the first row is not shifted. +static void ShiftRows(state_t* state) +{ + uint8_t temp; + + // Rotate first row 1 columns to left + temp = (*state)[0][1]; + (*state)[0][1] = (*state)[1][1]; + (*state)[1][1] = (*state)[2][1]; + (*state)[2][1] = (*state)[3][1]; + (*state)[3][1] = temp; + + // Rotate second row 2 columns to left + temp = (*state)[0][2]; + (*state)[0][2] = (*state)[2][2]; + (*state)[2][2] = temp; + + temp = (*state)[1][2]; + (*state)[1][2] = (*state)[3][2]; + (*state)[3][2] = temp; + + // Rotate third row 3 columns to left + temp = (*state)[0][3]; + (*state)[0][3] = (*state)[3][3]; + (*state)[3][3] = (*state)[2][3]; + (*state)[2][3] = (*state)[1][3]; + (*state)[1][3] = temp; +} + +static uint8_t xtime(uint8_t x) +{ + return ((x<<1) ^ (((x>>7) & 1) * 0x1b)); +} + +// MixColumns function mixes the columns of the state matrix +static void MixColumns(state_t* state) +{ + uint8_t i; + uint8_t Tmp, Tm, t; + for (i = 0; i < 4; ++i) + { + t = (*state)[i][0]; + Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ; + Tm = (*state)[i][0] ^ (*state)[i][1] ; Tm = xtime(Tm); (*state)[i][0] ^= Tm ^ Tmp ; + Tm = (*state)[i][1] ^ (*state)[i][2] ; Tm = xtime(Tm); (*state)[i][1] ^= Tm ^ Tmp ; + Tm = (*state)[i][2] ^ (*state)[i][3] ; Tm = xtime(Tm); (*state)[i][2] ^= Tm ^ Tmp ; + Tm = (*state)[i][3] ^ t ; Tm = xtime(Tm); (*state)[i][3] ^= Tm ^ Tmp ; + } +} + +// Multiply is used to multiply numbers in the field GF(2^8) +// Note: The last call to xtime() is unneeded, but often ends up generating a smaller binary +// The compiler seems to be able to vectorize the operation better this way. +// See https://github.com/kokke/tiny-AES-c/pull/34 +#if MULTIPLY_AS_A_FUNCTION +static uint8_t Multiply(uint8_t x, uint8_t y) +{ + return (((y & 1) * x) ^ + ((y>>1 & 1) * xtime(x)) ^ + ((y>>2 & 1) * xtime(xtime(x))) ^ + ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ + ((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))); /* this last call to xtime() can be omitted */ + } +#else +#define Multiply(x, y) \ + ( ((y & 1) * x) ^ \ + ((y>>1 & 1) * xtime(x)) ^ \ + ((y>>2 & 1) * xtime(xtime(x))) ^ \ + ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ \ + ((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))) \ + +#endif + +#if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1) +// MixColumns function mixes the columns of the state matrix. +// The method used to multiply may be difficult to understand for the inexperienced. +// Please use the references to gain more information. +static void InvMixColumns(state_t* state) +{ + int i; + uint8_t a, b, c, d; + for (i = 0; i < 4; ++i) + { + a = (*state)[i][0]; + b = (*state)[i][1]; + c = (*state)[i][2]; + d = (*state)[i][3]; + + (*state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09); + (*state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d); + (*state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b); + (*state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e); + } +} + + +// The SubBytes Function Substitutes the values in the +// state matrix with values in an S-box. +static void InvSubBytes(state_t* state) +{ + uint8_t i, j; + for (i = 0; i < 4; ++i) + { + for (j = 0; j < 4; ++j) + { + (*state)[j][i] = getSBoxInvert((*state)[j][i]); + } + } +} + +static void InvShiftRows(state_t* state) +{ + uint8_t temp; + + // Rotate first row 1 columns to right + temp = (*state)[3][1]; + (*state)[3][1] = (*state)[2][1]; + (*state)[2][1] = (*state)[1][1]; + (*state)[1][1] = (*state)[0][1]; + (*state)[0][1] = temp; + + // Rotate second row 2 columns to right + temp = (*state)[0][2]; + (*state)[0][2] = (*state)[2][2]; + (*state)[2][2] = temp; + + temp = (*state)[1][2]; + (*state)[1][2] = (*state)[3][2]; + (*state)[3][2] = temp; + + // Rotate third row 3 columns to right + temp = (*state)[0][3]; + (*state)[0][3] = (*state)[1][3]; + (*state)[1][3] = (*state)[2][3]; + (*state)[2][3] = (*state)[3][3]; + (*state)[3][3] = temp; +} +#endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1) + +// Cipher is the main function that encrypts the PlainText. +static void Cipher(state_t* state, const uint8_t* RoundKey) +{ + uint8_t round = 0; + + // Add the First round key to the state before starting the rounds. + AddRoundKey(0, state, RoundKey); + + // There will be Nr rounds. + // The first Nr-1 rounds are identical. + // These Nr-1 rounds are executed in the loop below. + for (round = 1; round < Nr; ++round) + { + SubBytes(state); + ShiftRows(state); + MixColumns(state); + AddRoundKey(round, state, RoundKey); + } + + // The last round is given below. + // The MixColumns function is not here in the last round. + SubBytes(state); + ShiftRows(state); + AddRoundKey(Nr, state, RoundKey); +} + +#if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1) +static void InvCipher(state_t* state, const uint8_t* RoundKey) +{ + uint8_t round = 0; + + // Add the First round key to the state before starting the rounds. + AddRoundKey(Nr, state, RoundKey); + + // There will be Nr rounds. + // The first Nr-1 rounds are identical. + // These Nr-1 rounds are executed in the loop below. + for (round = (Nr - 1); round > 0; --round) + { + InvShiftRows(state); + InvSubBytes(state); + AddRoundKey(round, state, RoundKey); + InvMixColumns(state); + } + + // The last round is given below. + // The MixColumns function is not here in the last round. + InvShiftRows(state); + InvSubBytes(state); + AddRoundKey(0, state, RoundKey); +} +#endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1) + +/*****************************************************************************/ +/* Public functions: */ +/*****************************************************************************/ +#if defined(ECB) && (ECB == 1) + + +void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf) +{ + // The next function call encrypts the PlainText with the Key using AES algorithm. + Cipher((state_t*)buf, ctx->RoundKey); +} + +void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf) +{ + // The next function call decrypts the PlainText with the Key using AES algorithm. + InvCipher((state_t*)buf, ctx->RoundKey); +} + + +#endif // #if defined(ECB) && (ECB == 1) + + + + + +#if defined(CBC) && (CBC == 1) + + +static void XorWithIv(uint8_t* buf, const uint8_t* Iv) +{ + uint8_t i; + for (i = 0; i < AES_BLOCKLEN; ++i) // The block in AES is always 128bit no matter the key size + { + buf[i] ^= Iv[i]; + } +} + +void AES_CBC_encrypt_buffer(struct AES_ctx *ctx, uint8_t* buf, uint32_t length) +{ + uintptr_t i; + uint8_t *Iv = ctx->Iv; + for (i = 0; i < length; i += AES_BLOCKLEN) + { + XorWithIv(buf, Iv); + Cipher((state_t*)buf, ctx->RoundKey); + Iv = buf; + buf += AES_BLOCKLEN; + //printf("Step %d - %d", i/16, i); + } + /* store Iv in ctx for next call */ + memcpy(ctx->Iv, Iv, AES_BLOCKLEN); +} + +void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length) +{ + uintptr_t i; + uint8_t storeNextIv[AES_BLOCKLEN]; + for (i = 0; i < length; i += AES_BLOCKLEN) + { + memcpy(storeNextIv, buf, AES_BLOCKLEN); + InvCipher((state_t*)buf, ctx->RoundKey); + XorWithIv(buf, ctx->Iv); + memcpy(ctx->Iv, storeNextIv, AES_BLOCKLEN); + buf += AES_BLOCKLEN; + } + +} + +#endif // #if defined(CBC) && (CBC == 1) + + + +#if defined(CTR) && (CTR == 1) + +/* Symmetrical operation: same function for encrypting as for decrypting. Note any IV/nonce should never be reused with the same key */ +void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length) +{ + uint8_t buffer[AES_BLOCKLEN]; + + unsigned i; + int bi; + for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi) + { + if (bi == AES_BLOCKLEN) /* we need to regen xor compliment in buffer */ + { + + memcpy(buffer, ctx->Iv, AES_BLOCKLEN); + Cipher((state_t*)buffer,ctx->RoundKey); + + /* Increment Iv and handle overflow */ + for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi) + { + /* inc will overflow */ + if (ctx->Iv[bi] == 255) + { + ctx->Iv[bi] = 0; + continue; + } + ctx->Iv[bi] += 1; + break; + } + bi = 0; + } + + buf[i] = (buf[i] ^ buffer[bi]); + } +} + +#endif // #if defined(CTR) && (CTR == 1) + diff --git a/aes/aes.h b/aes/aes.h new file mode 100644 index 0000000..87f1471 --- /dev/null +++ b/aes/aes.h @@ -0,0 +1,90 @@ +#ifndef _AES_H_ +#define _AES_H_ + +#include + +// #define the macros below to 1/0 to enable/disable the mode of operation. +// +// CBC enables AES encryption in CBC-mode of operation. +// CTR enables encryption in counter-mode. +// ECB enables the basic ECB 16-byte block algorithm. All can be enabled simultaneously. + +// The #ifndef-guard allows it to be configured before #include'ing or at compile time. +#ifndef CBC + #define CBC 1 +#endif + +#ifndef ECB + #define ECB 1 +#endif + +#ifndef CTR + #define CTR 1 +#endif + + +#define AES128 1 +//#define AES192 1 +//#define AES256 1 + +#define AES_BLOCKLEN 16 //Block length in bytes AES is 128b block only + +#if defined(AES256) && (AES256 == 1) + #define AES_KEYLEN 32 + #define AES_keyExpSize 240 +#elif defined(AES192) && (AES192 == 1) + #define AES_KEYLEN 24 + #define AES_keyExpSize 208 +#else + #define AES_KEYLEN 16 // Key length in bytes + #define AES_keyExpSize 176 +#endif + +struct AES_ctx +{ + uint8_t RoundKey[AES_keyExpSize]; +#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1)) + uint8_t Iv[AES_BLOCKLEN]; +#endif +}; + +void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key); +#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1)) +void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv); +void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv); +#endif + +#if defined(ECB) && (ECB == 1) +// buffer size is exactly AES_BLOCKLEN bytes; +// you need only AES_init_ctx as IV is not used in ECB +// NB: ECB is considered insecure for most uses +void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf); +void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf); + +#endif // #if defined(ECB) && (ECB == !) + + +#if defined(CBC) && (CBC == 1) +// buffer size MUST be mutile of AES_BLOCKLEN; +// Suggest https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme +// NOTES: you need to set IV in ctx via AES_init_ctx_iv() or AES_ctx_set_iv() +// no IV should ever be reused with the same key +void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length); +void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length); + +#endif // #if defined(CBC) && (CBC == 1) + + +#if defined(CTR) && (CTR == 1) + +// Same function for encrypting as for decrypting. +// IV is incremented for every block, and used after encryption as XOR-compliment for output +// Suggesting https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme +// NOTES: you need to set IV in ctx with AES_init_ctx_iv() or AES_ctx_set_iv() +// no IV should ever be reused with the same key +void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length); + +#endif // #if defined(CTR) && (CTR == 1) + + +#endif //_AES_H_ diff --git a/aes/aes.hpp b/aes/aes.hpp new file mode 100644 index 0000000..ade1642 --- /dev/null +++ b/aes/aes.hpp @@ -0,0 +1,12 @@ +#ifndef _AES_HPP_ +#define _AES_HPP_ + +#ifndef __cplusplus +#error Do not include the hpp header in a c project! +#endif //__cplusplus + +extern "C" { +#include "aes.h" +} + +#endif //_AES_HPP_ diff --git a/calculation/Calculation.cpp b/calculation/Calculation.cpp new file mode 100644 index 0000000..38f9aa5 --- /dev/null +++ b/calculation/Calculation.cpp @@ -0,0 +1,317 @@ +#include "Calculation.hpp" + + + +Calculation::Calculation() +{ +} + +Calculation::~Calculation() +{ +} + + + +/************************************************************************/ +/* 一维数据的复数快速傅里叶变换 */ +/************************************************************************/ +void Calculation::FFT(int n, fftw_complex* in, fftw_complex* out) +{ + if (in == NULL || out == NULL) return; + fftw_plan p; + p = fftw_plan_dft_1d(n, in, out, FFTW_FORWARD, FFTW_ESTIMATE); + fftw_execute(p); + fftw_destroy_plan(p); + fftw_cleanup(); +} + +/************************************************************************/ +/* 一维数据的实数快速傅里叶变换 */ +/************************************************************************/ +void Calculation::FFT_R(int n, std::vector & vecData, fftw_complex* out) +{ + double in[n]; + for (int i = 0; i < n; i++) { + in[i] = vecData[i]; + } + + for (int i = 0; i < n; i++) + { + out[i][0] = (double)vecData[i]; + out[i][1] = 0; + } + //create a DFT plan and execute it + fftw_plan plan = fftw_plan_dft_r2c_1d(n, in, out, FFTW_ESTIMATE); + fftw_execute(plan); + //destroy the plan to prevent a memory leak + fftw_destroy_plan(plan); + fftw_cleanup(); +} + +/************************************************************************/ +/* 一维数据的快速傅里叶逆变换 */ +/************************************************************************/ +void Calculation::iFFT(int n, fftw_complex* in, fftw_complex* out) +{ + if (in == NULL || out == NULL) return; + fftw_plan p; + p = fftw_plan_dft_1d(n, in, out, FFTW_BACKWARD, FFTW_ESTIMATE); + fftw_execute(p); + fftw_destroy_plan(p); + fftw_cleanup(); +} + +//************************************ +// Method: caculateAmp_Pha +// FullName: Calculation::caculateAmp_Pha +// Access: public static +// Returns: void +// Qualifier: +// Parameter: int n +// Parameter: fftw_complex * in +// Parameter: int frequency +// Parameter: double & amplitude +// Parameter: double & phase +// 函数功能是计算特定频率的幅值和相位,原来的讨论中是传入一个特定的频率,然后在给定的频率左右范围内找幅值和相位 +// 目前的函数实现是计算FFT变换后特定点的幅值和相位 +// 然后还有一个地方需要修改,即给定频率和FFT变换结果序列 +//************************************ +void Calculation::caculateAmp_Pha(int n, fftw_complex* in, int frequency, double &litude, double &phase) +{ + int index = frequency; + amplitude = 2 * sqrt((in[index][0] / n) * (in[index][0] / n) + (in[index][1] / n) * (in[index][1] / n)); + phase = 180 * atan(in[index][1] / in[index][0]) / M_PI; +} + + +float Calculation::max(std::vector & vecData) +{ + std::vector::iterator it; + it = std::max_element(vecData.begin(), vecData.end()); + if (it != vecData.end()) { + return *it; + } + return 0; +} + +float Calculation::min(std::vector & vecData) +{ + std::vector::iterator it; + it = std::min_element(vecData.begin(), vecData.end()); + if (it != vecData.end()) { + return *it; + } + return 0; +} + + +void Calculation::absVec(std::vector & vecAbsData, std::vector & vecData) +{ + for (int i = 0; i < vecData.size(); i++) { + vecAbsData.push_back(fabs(vecData[i])); + } + return; +} + + +float Calculation::mean(std::vector & vecData) +{ + double meanTemp = 0; + for (int i = 0; i < vecData.size(); i++) { + meanTemp = meanTemp += vecData[i]; + } + return meanTemp / vecData.size(); +} + + +void Calculation::drop_mean(std::vector & vecDropMeanData, std::vector & vecData) +{ + float fMean = mean(vecData); + for (int i = 0; i < vecData.size(); i++) { + vecDropMeanData.push_back(vecData[i] - fMean); + } + return; +} + +float Calculation::srm(std::vector & vecData) +{ + double dSrmTemp = 0; + for (int i = 0; i < vecData.size(); i++){ + dSrmTemp = dSrmTemp + sqrt(vecData[i]); + } + dSrmTemp = dSrmTemp / vecData.size(); + return dSrmTemp * dSrmTemp; +} + + +float Calculation::rms(std::vector & vecData) +{ + double rmsTemp = 0; + for (int i = 0; i < vecData.size(); i++) { + rmsTemp = rmsTemp += (vecData[i] * vecData[i]); + } + rmsTemp = rmsTemp / vecData.size(); + return sqrt(rmsTemp); +} + + +float Calculation::variance(std::vector & vecDropMeanData) +{ + double varianceTemp = 0; + for (int i = 0; i < vecDropMeanData.size(); i++) { + varianceTemp = varianceTemp += (vecDropMeanData[i] * vecDropMeanData[i]); + } + return varianceTemp/vecDropMeanData.size(); +} + + +float Calculation::skew_state(std::vector & vecDropMeanData, float fVariance) +{ + double tempSkew = 0; + for (int i = 0; i < vecDropMeanData.size(); i++) { + tempSkew = tempSkew + pow(vecDropMeanData[i], 3); + } + tempSkew = tempSkew / vecDropMeanData.size(); + tempSkew = tempSkew / pow(fVariance, 1.5); + return tempSkew; +} + + +float Calculation::kurtosis(std::vector & vecDropMeanData, float fVariance) +{ + double tempkurtosis = 0; + for (int i = 0; i < vecDropMeanData.size(); i++) { + tempkurtosis = tempkurtosis + pow(vecDropMeanData[i], 4); + } + tempkurtosis = tempkurtosis / vecDropMeanData.size(); + tempkurtosis = tempkurtosis / pow(fVariance, 2); + return tempkurtosis; +} + +void Calculation::hilbert(std::vector & vecData, std::vector & vecHilbertData, int N) +{ + + double in[N]; + for (int i = 0; i < N; i++) { + in[i] = vecData[i]; + } + fftw_complex *out; + out = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * N); + + for (int i = 0; i < N; ++i) + { + out[i][0] = (double)vecData[i]; + out[i][1] = 0; + } + //create a DFT plan and execute it + fftw_plan plan = fftw_plan_dft_r2c_1d(N, in, out, FFTW_ESTIMATE); + fftw_execute(plan); + //destroy the plan to prevent a memory leak + fftw_destroy_plan(plan); + int hN = N >> 1; // half of the length (N /2) + int numRem = hN; // the number of remaining elements + // multiply the appropriate values by 2 + // (those that should be multiplied by 1 are left intact because they wouldn't change) + for (int i = 1; i < hN; ++i) // 1,2,...,N/2 - 1 的项乘以2 + { + out[i][0] *= 2; + out[i][1] *= 2; + } + // if the length is even, the number of remaining elements decreases by 1 + if (N % 2 == 0) + numRem--; + // if it's odd and greater than 1, the middle value must be multiplied by 2 + else if (N > 1) // 奇数非空 + { + out[hN][0] *= 2; + out[hN][1] *= 2; + } + // set the remaining values to 0 + // (multiplying by 0 gives 0, so we don't care about the multiplicands) + memset(&out[hN + 1][0], 0, numRem * sizeof(fftw_complex)); + // create an IDFT plan and execute it + plan = fftw_plan_dft_1d(N, out, out, FFTW_BACKWARD, FFTW_ESTIMATE); + fftw_execute(plan); + // do some cleaning + fftw_destroy_plan(plan); + fftw_cleanup(); + // scale the IDFT output + for (int i = 0; i < N; ++i) + { + out[i][0] /= N; + out[i][1] /= N; + } + + for( int n=0; n & vecData, std::vector & vecFFTSpecData) +{ + fftw_complex *inFFt, *outFFt; + inFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size()); + outFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size()); + printf("1---------------------------------------------->%d\n",vecData.size()); + + for (int j = 0; j < vecData.size(); j++) { + inFFt[j][0] = (double)vecData[j]; + inFFt[j][1] = 0; + } + FFT(vecData.size(),inFFt, outFFt); + for(int j = 0; j < vecData.size()/2; j++) { + vecFFTSpecData.push_back(sqrt(outFFt[j][0]*outFFt[j][0] + outFFt[j][1]*outFFt[j][1])*2/vecData.size()); + } + +} + +void Calculation::envSpec(std::vector & vecData, std::vector & vecEnvSpecData) +{ + std::vector vecDropMeanData; + drop_mean(vecDropMeanData, vecData); + + std::vector vecHilbertData; + hilbert(vecDropMeanData, vecHilbertData, vecDropMeanData.size()); + + fftw_complex *inHilFFt, *outHilFFt; + inHilFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecHilbertData.size()); + outHilFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecHilbertData.size()); + + for (int j = 0; j < vecHilbertData.size(); j++) { + inHilFFt[j][0] = (double)vecHilbertData[j]; + inHilFFt[j][1] = 0; + } + + FFT(vecHilbertData.size(), inHilFFt, outHilFFt); + fftShift(outHilFFt, vecHilbertData.size()); + + vecEnvSpecData.push_back(0); + for (int i = vecHilbertData.size() / 2 + 1; i < vecHilbertData.size(); i++) { + float ftemp = 2 * sqrt(outHilFFt[i][0] * outHilFFt[i][0] + outHilFFt[i][1] * outHilFFt[i][1]) / vecHilbertData.size(); + vecEnvSpecData.push_back(ftemp); + } +} diff --git a/calculation/Calculation.hpp b/calculation/Calculation.hpp new file mode 100644 index 0000000..3e26611 --- /dev/null +++ b/calculation/Calculation.hpp @@ -0,0 +1,155 @@ +#ifndef CALCULATION_H_ + +#define CALCULATION_H_ + + + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include "../utility/SH_MySingleton.hpp" + + + +#define pi 3.1415 + + + +typedef struct + +{ + + float real,imag; + +}complex; + + + +class Calculation : public MySingleton +{ + +public: + + Calculation(); + + ~Calculation(); + + + + //最大值 + + float max(std::vector & vecData); + + + + //最小值 + + float min(std::vector & vecData); + + + + //将数据取绝对值 + + void absVec(std::vector & vecAbsData, std::vector & vecData); + + + + //将数据取平均值 + + float mean(std::vector & vecData); + + + + //将数据平方处理 数据有效值 + + float rms(std::vector & vecData); + + + + //去数据的直流分量 + + void drop_mean(std::vector & vecDropMeanData, std::vector & vecData); + + + + //方根幅值 + + float srm(std::vector & vecData); + + + + //方差 + + float variance(std::vector & vecDropMeanData); + + + + //偏态指标 + + float skew_state(std::vector & vecDropMeanData, float fVariance); + + + + //峭度指标 + + float kurtosis(std::vector & vecDropMeanData, float fVariance); + + + + //快速傅里叶变换函数 + + void FFT(int n, fftw_complex* in, fftw_complex* out); + + + + //快速傅里叶实数变换函数 + + void FFT_R(int n, std::vector & vecData, fftw_complex* out); + + + + //快速傅里叶逆变换 + + void iFFT(int n, fftw_complex* in, fftw_complex* out); + + + + //通道幅值和相位提取 + + //输入为FFT变换后的数据长度及数据,指定的频率,输出为计算后得到的幅值 和 相位 + + void caculateAmp_Pha(int n, fftw_complex* in, int frequency, double &litude, double &phase); + + + + //希尔伯特变换 + + void hilbert(std::vector & vecData, std::vector & vecHilbertData, int N); + + + + + + //FFT shift + + void fftShift(fftw_complex* in, int l); + //频谱图数据 + void FFTSpec(std::vector & vecData, std::vector & vecFFTSpecData); + //包络图谱数据 + void envSpec(std::vector & vecData, std::vector & vecEnvSpecData); +}; + + + +#endif diff --git a/common/SH_CommonFunc.cpp b/common/SH_CommonFunc.cpp new file mode 100644 index 0000000..08c5e9e --- /dev/null +++ b/common/SH_CommonFunc.cpp @@ -0,0 +1,633 @@ +#include +#include +#include "SH_global.h" +#include "SH_CommonFunc.hpp" + + + +static boost::mutex s_config_mu; + +int CheckFileVersion(int argc, char** argv) +{ + std::string strVersion = GlobalConfig::Version; + int optionchar; /*选项字�??*/ + if (argc >= 2) { + if (strcmp(argv[1], "--debugmode") == 0){ + GlobalConfig::RUN_MODE = 1; + return 0; + } + optionchar = getopt(argc, argv, "vVhH?"); + switch (optionchar) { + case 'v': + case 'V': + GlobalConfig::RUN_MODE = 1; + print_debug("Compile time:%s %s\n", __DATE__, __TIME__); + print_debug("The internal version is:%s.\n", strVersion.c_str()); + break; + case 'h': + case 'H': + case '?': + printf("Please input -v or -V to get the file version.\n"); + break; + default: + break; + } + return 1; + } + return 0; +} + + +std::string GetCurrentTime() +{ + struct tm nowtime; + struct timeval tv; + char time_now[128]; + gettimeofday(&tv, NULL); + localtime_r(&tv.tv_sec,&nowtime); + + sprintf(time_now,"%d-%d-%d %d:%d:%d.%03d ", + nowtime.tm_year+1900, + nowtime.tm_mon+1, + nowtime.tm_mday, + nowtime.tm_hour, + nowtime.tm_min, + nowtime.tm_sec, + (int)(tv.tv_usec/1000) + ); + + std::string strtime_now = std::string((char*)time_now); + return strtime_now; +} + +int system_custom(const char *cmd, char *buf) +{ + FILE * fp; + int res; + char temp[1024] = {0}; + if (cmd == NULL) { + return -1; + } + + if ((fp = popen(cmd, "r") ) == NULL) { + print_error("popen error\n"); + return -1; + } else { + buf[0] = '\0'; + while (fgets(temp, sizeof(temp), fp)) { + strcat(buf, temp); + } + res = pclose(fp); + } + + char *p; + int pos = 0; + p = strstr(buf, "\n"); + if(p != NULL){ + pos = p - buf; + buf[pos] = '\0'; + } + + return res; +} + + +std::string GetDayDate() +{ + time_t t = time(0); + char tmp[64]; + strftime(tmp, sizeof(tmp), "%Y-%m-%d",localtime(&t)); + std::string data = std::string((char*)tmp); + return data; +} + + +void GetTimeNet(char* timebuf,int type) +{ + struct timeval tv; + gettimeofday(&tv, NULL); + int millisecond = tv.tv_usec / 1000; + if(type == 0){ + sprintf(timebuf, "%ld%03d", tv.tv_sec, millisecond); + } else { + sprintf(timebuf, "%ld", tv.tv_sec); + } + +} + +void GetTime_(char time_buff[],TIME_SIZE len) +{ + int i = sizeof(time_buff); + memset(time_buff, 0, i); + time_t timep; + time(&timep); + strcpy(time_buff, ctime(&timep)); + std::string strtemp = time_buff; + strtemp = strtemp.substr(11, len); + memset(time_buff, 0, strlen(time_buff)); + strcpy(time_buff, strtemp.c_str()); +} + +std::string ReadStrByOpt(std::string filename, std::string config, std::string option) +{ + boost::mutex::scoped_lock lock(s_config_mu); + Json::Value root; + Json::Reader reader; + std::string value; + std::fstream is; + is.open(filename.c_str(), std::ios::in); + if (reader.parse(is, root)) { + value = root[config]["option"][option].asString(); + } + is.close(); + return value; +} + +int WriteStr2Config(std::string filename, std::string config, std::string option, std::string value, bool listable) +{ + boost::mutex::scoped_lock lock(s_config_mu); + Json::Value root; + Json::Value subroot; + Json::Value list; + Json::Value op; + Json::Reader reader; + std::fstream is; + is.open(filename.c_str(), std::ios::in); + if (reader.parse(is, root)) { + subroot = root[config]; + if (listable) + list = root[config]["list"]; + else + op = root[config]["option"]; + } + is.close(); + + if (listable) { + list[option].append(Json::Value(value)); + subroot["list"] = list; + } else { + op[option] = Json::Value(value); + subroot["option"] = op; + } + root[config] = subroot; + Json::StyledWriter sw; + std::ofstream os; + os.open(filename.c_str()); + os << sw.write(root); + os.close(); + return 0; +} + + +std::string GetLocalMac() +{ + int sock_mac; + struct ifreq ifr_mac; + char mac_addr[30]; + sock_mac = socket( AF_INET, SOCK_STREAM, 0 ); + if( sock_mac == -1) { + perror("create socket falise...mac/n"); + return ""; + } + memset(&ifr_mac,0,sizeof(ifr_mac)); + strncpy(ifr_mac.ifr_name, "eth0", sizeof(ifr_mac.ifr_name)-1); + if( (ioctl( sock_mac, SIOCGIFHWADDR, &ifr_mac)) < 0) { + printf("mac ioctl error/n"); + return ""; + } + sprintf(mac_addr,"%02x%02x%02x%02x%02x%02x", + (unsigned char)ifr_mac.ifr_hwaddr.sa_data[0], + (unsigned char)ifr_mac.ifr_hwaddr.sa_data[1], + (unsigned char)ifr_mac.ifr_hwaddr.sa_data[2], + (unsigned char)ifr_mac.ifr_hwaddr.sa_data[3], + (unsigned char)ifr_mac.ifr_hwaddr.sa_data[4], + (unsigned char)ifr_mac.ifr_hwaddr.sa_data[5]); + printf("local mac:%s /n",mac_addr); + close( sock_mac ); + return std::string( mac_addr ); +} + +std::string GetGwIp_(const char *eth_name) +{ + int sockfd; + char gwip_[16] = {0}; + if (-1 == (sockfd = socket(PF_INET, SOCK_STREAM, 0))) { + perror_info("socket"); + return ""; + } + struct ifreq req; + struct sockaddr_in *host; + + bzero(&req, sizeof(struct ifreq)); + strcpy(req.ifr_name, eth_name); + print_info("eth_name = %s\n",eth_name); + ioctl(sockfd, SIOCGIFADDR, &req); + host = (struct sockaddr_in*) &req.ifr_addr; + close(sockfd); + if (host) { + strcpy(gwip_, inet_ntoa(host->sin_addr)); + } + return std::string(gwip_); +} + +std::string IpAddrInit() +{ + const char *WLAN0 = "wlan0"; + const char *ETH0 = "eth0"; + std::string strip; + strip = GetGwIp_(ETH0); + if (strip.compare("0.0.0.0") == 0) { + strip = GetGwIp_(WLAN0); + } + return strip; +} + +std::string GetWorkNic() +{ + const char *WLAN0 = "wlan0"; + const char *ETH0 = "eth0"; + std::string strip; + strip = GetGwIp_(WLAN0); + if (strip.compare("0.0.0.0") != 0) { + return std::string(WLAN0); + } + strip = GetGwIp_(ETH0); + if (strip.compare("0.0.0.0") != 0) { + return std::string(ETH0); + } + return std::string(ETH0); +} + +std::string& ClearAllSpace(std::string &str) +{ + int index = 0; + if( !str.empty()) { + while( (index = str.find(' ',index)) != string::npos) { + str.erase(index,1); + } + }return str; +} + +std::string GetSysInfo() +{ + const char * getCpuUse = "top -b -n 1 |grep Cpu | cut -d \",\" -f 1 | cut -d \":\" -f 2 |tr -d ' us'"; + char chRes[100] = {0}; + system_custom(getCpuUse, chRes); + std::string CpuUse = std::string(chRes); + + const char * getCpuSys = "top -b -n 1 |grep Cpu | cut -d \",\" -f 2 |tr -d ' sy'"; + memset(chRes, 0, 100); + system_custom(getCpuSys, chRes); + std::string CpuSys = std::string(chRes); + + const char * getMemtotal = "cat /proc/meminfo | grep MemTotal | awk -F"":"" '{print $2}' |tr -d ' kB'"; + memset(chRes, 0, 100); + system_custom(getMemtotal, chRes); + std::string MemTotal = std::string(chRes); + + const char * getMemFree = "cat /proc/meminfo | grep MemFree | awk -F"":"" '{print $2}' |tr -d ' kB'"; + memset(chRes, 0, 100); + system_custom(getMemFree, chRes); + std::string MemFree = std::string(chRes); + + float a = boost::lexical_cast(MemFree); + float b = boost::lexical_cast(MemTotal); + float c = (1 - a/b)*100; + + const char * getEmmcInfo = "df -h | grep /dev/root"; + memset(chRes, 0, 100); + system_custom(getEmmcInfo, chRes); + std::string Emmcinfo = std::string(chRes); + std::size_t found = Emmcinfo.find("%"); + if (found != std::string::npos) { + Emmcinfo = Emmcinfo.substr(found-3, 3); + } + Emmcinfo = ClearAllSpace(Emmcinfo); + + char sysinfo[128] = {0}; + sprintf(sysinfo, "%-13s%-13s%-13s%-13s ", boost::lexical_cast(c).substr(0,4).c_str(), CpuSys.c_str(), CpuUse.c_str(), Emmcinfo.c_str()); + return std::string(sysinfo); +} + +void StartWriteToDat() +{ + print_info("start writetoDat\n"); +} + + +float * ReSample(int WaveDataLength, int N, int *NewWaveDataLength, std::vector & WaveData) +{ + if (N <= 0) + return NULL; + int NewLength = (int)WaveDataLength / N; + float * _OutputData = new float[NewLength]; + for(int i = 0; i < NewLength; i++) { + _OutputData[i] = WaveData[i * N]; + } + *NewWaveDataLength = NewLength; + return _OutputData; +} + + +int SetTime(unsigned long seconds, int milliseconds) +{ + struct timeval tv; + time_t timep = (time_t)seconds; + tv.tv_sec = timep; + tv.tv_usec = milliseconds*1000; + return settimeofday(&tv, NULL); +} + +void RemoveConfig() +{ + char cmd[32] = { 0 }; + sprintf(cmd, "rm /CIDW/config/*"); + system(cmd); + exit(0); +} + +extern void ZoneConfig(std::string zoneid) +{ + int a = 0; + std::string zonelists[] = {"UTC+12","UTC+11","UTC+10","UTC+9","UTC+8","UTC+7","UTC+6","UTC+5","UTC+4","UTC+3","UTC+2","UTC+1","UTC+0","UTC-1","UTC-2","UTC-3","UTC-4","UTC-5","UTC-6","UTC-7","UTC-8","UTC-9","UTC-10","UTC-11"}; + for (int i = 0;i < sizeof(zonelists);i++) + { + if (zoneid.compare(zonelists[i]) == 0) { + a = i; + cout << "a = " << a << endl; + break; + } + } + switch(a){ + case 0:zoneid = "GMT-12";break; + case 1:zoneid = "GMT-11";break; + case 2:zoneid = "GMT-10";break; + case 3:zoneid = "GMT-9";break; + case 4:zoneid = "GMT-8";break; + case 5:zoneid = "GMT-7";break; + case 6:zoneid = "GMT-6";break; + case 7:zoneid = "GMT-5";break; + case 8:zoneid = "GMT-4";break; + case 9:zoneid = "GMT-3";break; + case 10:zoneid = "GMT-2";break; + case 11:zoneid = "GMT-1";break; + case 12:zoneid = "GMT-0";break; + case 13:zoneid = "GMT+1";break; + case 14:zoneid = "GMT+2";break; + case 15:zoneid = "GMT+3";break; + case 16:zoneid = "GMT+4";break; + case 17:zoneid = "GMT+5";break; + case 18:zoneid = "GMT+6";break; + case 19:zoneid = "GMT+7";break; + case 20:zoneid = "GMT+8";break; + case 21:zoneid = "GMT+9";break; + case 22:zoneid = "GMT+10";break; + case 23:zoneid = "GMT+11";break; + } + char cmd[256] = { 0 }; + // sprintf(cmd, "rm /etc/localtime"); + // system(cmd); + memset(cmd, 0, 256); + sprintf(cmd, "sudo ln -sf /usr/share/zoneinfo/Etc/%s /etc/localtime", zoneid.c_str()); + system(cmd); + print_info("change timezone success!\n"); +} + +std::string GetFileContent(std::string filename, int line) +{ + std::string strFileContent(""); + std::ifstream ifileOut(filename.c_str()); + if(ifileOut.is_open()) { //文件打开 + int i = 1; + while (!ifileOut.eof()) { + if (line == 0) { + std::string strTemp(""); + getline(ifileOut, strTemp); + strFileContent += strTemp; + strFileContent += "\r\n"; + } + if (line != 0) { + std::string strTemp(""); + getline(ifileOut, strTemp); + if (line == i) { + strFileContent = strTemp; + break; + } + } + ++i; + } + ifileOut.close(); + } + return strFileContent; +} + + + + + + + + + + + + +// int StatusPub() +// { +// long mem_used = -1; +// long mem_free = -1; +// long mem_total = -1; +// long mem_cached = -1; +// char name1[20]; +// std::string strMemTotal = GetFileContent("/proc/meminfo", 1); +// std::string strMemFree = GetFileContent("/proc/meminfo", 2); +// std::string strMemCache = GetFileContent("/proc/meminfo", 5); + +// sscanf(strMemTotal.c_str(),"%s%ld",name1,&mem_total); +// sscanf(strMemFree.c_str(),"%s%ld",name1,&mem_free); +// sscanf(strMemCache.c_str(),"%s%ld",name1,&mem_cached); +// mem_used = mem_total - mem_free; +// float fMemRate = 1.0 * mem_used / mem_total; + +// float fCpuRate; +// char name[8]; +// double cpu_idle = -1; +// double cpu_sys = -1; +// double cpu_user = -1; +// double cpu_total = -1; +// double cpu_wait = -1; +// long int user,nice,sys,idle,iowait,irq,softirq; +// std::string strCpu1 = GetFileContent("/proc/stat", 1); +// sscanf(strCpu1.c_str(),"%s%ld%ld%ld%ld%ld%ld%d",name,&user,&nice,&sys,&idle,&iowait,&irq,&softirq); +// boost::this_thread::sleep(boost::posix_time::seconds(2)); +// long int userNext,niceNext,sysNext,idleNext,iowaitNext,irqNext,softirqNext; +// std::string strCpu2 = GetFileContent("/proc/stat", 1); +// sscanf(strCpu2.c_str(),"%s%ld%ld%ld%ld%ld%ld%d",name,&userNext,&niceNext,&sysNext,&idleNext,&iowaitNext,&irqNext,&softirqNext); +// cpu_total = (userNext+niceNext+sysNext+idleNext+iowaitNext+irqNext+softirqNext) - (user+nice+sys+idle+iowait+irq+softirq); +// cpu_user = userNext - user; +// cpu_sys = sysNext - sys; +// cpu_wait = iowaitNext - iowait; +// cpu_idle = idleNext - idle; +// fCpuRate = 1.0*(cpu_total - cpu_idle) / cpu_total; +// float rateUser = cpu_user *100.0/cpu_total; +// float rateSys = cpu_sys * 100.0/cpu_total; + +// if (rateUser > 95) { +// rateUser = 92; +// } + +// /*获取温度 */ +// std::string tempRaw = GetFileContent(TEMPER_RAW, 1); +// std::string temperOffset = GetFileContent(TEMPER_OFFSET, 1); +// std::string temperScale = GetFileContent(TEMPER_SCALE, 1); +// float temperature = ((boost::lexical_cast(tempRaw) + boost::lexical_cast(temperOffset)) * boost::lexical_cast(temperScale))/1000; + +// char hardName[32]; +// char hardTotal[32]; +// char hardUse[32]; +// char hardFree[32]; +// char rateHardUse[32]; +// const char * getEmmcInfo = "df -h | grep /dev/root"; +// char chRes[100]; +// memset(chRes, 0, 100); +// system_custom(getEmmcInfo, chRes); +// sscanf(chRes,"%s%s%s%s%s",hardName, hardTotal, hardUse, hardFree, rateHardUse); +// std::string strhardTotal(hardTotal); +// std::string strhardFree(hardFree); +// std::string strrateHardUse(rateHardUse); + +// Json::Value jsData; +// Json::FastWriter fw; +// jsData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; +// jsData["cpuUserUse"] = rateUser; +// jsData["memoryTotal"] = (int)mem_total; +// jsData["memoryFree"] = (int)mem_free; +// jsData["memoryUse"] = fMemRate * 100; +// jsData["hardDiskTotal"] = boost::lexical_cast(strhardTotal.substr(0,strhardTotal.length() - 1)); +// jsData["hardDiskFree"] = boost::lexical_cast(strhardFree.substr(0,strhardFree.length() - 1)); + +// double total = boost::lexical_cast(strhardTotal.substr(0,strhardTotal.length() - 1)); +// double free = boost::lexical_cast(strhardFree.substr(0,strhardFree.length() - 1)); +// double use = ((total - free) / free) * 100; +// // jsData["hardDiskUse"] = boost::lexical_cast(strrateHardUse.substr(0,strrateHardUse.length() - 1)); +// jsData["hardDiskUse"] = use; +// jsData["cpuSystemUse"] = rateSys; +// jsData["temperature"] = temperature; + +// char localtimestamp[32] = { 0 }; +// GetTimeNet(localtimestamp, 1); +// std::string nowTimetamp = std::string(localtimestamp); +// jsData["updateTime"] = nowTimetamp; +// std::string strJson = fw.write(jsData); +// data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubStatus.c_str()); + +// std::string strInfo = "mem:"+boost::lexical_cast(fMemRate * 100) + "tem:"+boost::lexical_cast(temperature); + + +// return 0; +// } + + +std::string GetSysStatus() +{ + long mem_used = -1; + long mem_free = -1; + long mem_total = -1; + long mem_cached = -1; + char name1[20]; + std::string strMemTotal = GetFileContent("/proc/meminfo", 1); + std::string strMemFree = GetFileContent("/proc/meminfo", 2); + std::string strMemCache = GetFileContent("/proc/meminfo", 5); + + sscanf(strMemTotal.c_str(),"%s%ld",name1,&mem_total); + sscanf(strMemFree.c_str(),"%s%ld",name1,&mem_free); + sscanf(strMemCache.c_str(),"%s%ld",name1,&mem_cached); + mem_used = mem_total - mem_free; + float fMemRate = 1.0 * mem_used / mem_total; + + float fCpuRate; + char name[8]; + double cpu_idle = -1; + double cpu_sys = -1; + double cpu_user = -1; + double cpu_total = -1; + double cpu_wait = -1; + long int user,nice,sys,idle,iowait,irq,softirq; + std::string strCpu1 = GetFileContent("/proc/stat", 1); + sscanf(strCpu1.c_str(),"%s%ld%ld%ld%ld%ld%ld%d",name,&user,&nice,&sys,&idle,&iowait,&irq,&softirq); + sleep(1); + long int userNext,niceNext,sysNext,idleNext,iowaitNext,irqNext,softirqNext; + std::string strCpu2 = GetFileContent("/proc/stat", 1); + sscanf(strCpu2.c_str(),"%s%ld%ld%ld%ld%ld%ld%d",name,&userNext,&niceNext,&sysNext,&idleNext,&iowaitNext,&irqNext,&softirqNext); + cpu_total = (userNext+niceNext+sysNext+idleNext+iowaitNext+irqNext+softirqNext) - (user+nice+sys+idle+iowait+irq+softirq); + cpu_user = userNext - user; + cpu_sys = sysNext - sys; + cpu_wait = iowaitNext - iowait; + cpu_idle = idleNext - idle; + fCpuRate = 1.0*(cpu_total - cpu_idle) / cpu_total; + float rateUser = cpu_user *100.0/cpu_total; + float rateSys = cpu_sys * 100.0/cpu_total; + if (rateUser > 95) { + rateUser = 92; + } + + char hardName[32]; + char hardTotal[32]; + char hardUse[32]; + char hardFree[32]; + char rateHardUse[32]; + const char * getEmmcInfo = "df -h | grep /opt"; + char chRes[100]; + memset(chRes, 0, 100); + system_custom(getEmmcInfo, chRes); + sscanf(chRes,"%s%s%s%s%s",hardName, hardTotal, hardUse, hardFree, rateHardUse); + std::string strhardTotal(hardTotal); + std::string strhardFree(hardFree); + std::string strrateHardUse(rateHardUse); + + + Json::Value jsData; + Json::FastWriter fw; + jsData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsData["cpuUserUse"] = rateUser; + jsData["memoryTotal"] = (int)mem_total; + jsData["memoryFree"] = (int)mem_free; + jsData["memoryUse"] = fMemRate * 100; + jsData["hardDiskTotal"] = boost::lexical_cast(strhardTotal.substr(0,strhardTotal.length() - 1)); + jsData["hardDiskFree"] = boost::lexical_cast(strhardFree.substr(0,strhardFree.length() - 1)); + + double total = boost::lexical_cast(strhardTotal.substr(0,strhardTotal.length() - 1)); + double free = boost::lexical_cast(strhardFree.substr(0,strhardFree.length() - 1)); + double use = ((total - free) / total) * 100; + // jsData["hardDiskUse"] = boost::lexical_cast(strrateHardUse.substr(0,strrateHardUse.length() - 1)); + jsData["hardDiskUse"] = use; + jsData["cpuSystemUse"] = rateSys; + + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + jsData["updateTime"] = nowTimetamp; + std::string strJson = fw.write(jsData); + return strJson; +} + +void swap(char *data) +{ + int tmp; + tmp = data[1]; + data[1] = data[0]; + data[0] = tmp; +} + +static const char* JSON_FIELD_CMD = "cmd";//协议: 命令字段 +static const char* JSON_FIELD_NAME = "dataWatchName";//协议: 终端名称 +static const char* JSON_FIELD_dataNodeGatewayNo = "dataNodeGatewayNo"; +static const char* JSON_FIELD_ASSETID = "dataWatchAssetId";//协议: 资产编号 字段 +static const char* JSON_FIELD_ADDEDBY = "dataWatchAddedBy";//协议: 添加人 字段 +static const char* JSON_FIELD_DEVICETYPE = "deviceType"; +static const char* JSON_FIELD_ADDEDDATE = "dataWatchAddedDate"; +static const char* JSON_FIELD_IPADDRESS = "dataWatchIpAddress"; +static const char* JSON_FIELD_SN = "serialNumber"; +static const char* JSON_FIELD_VERSION = "softVersion"; +static const char* JSON_FIELD_TIMEZONE = "timezone"; + diff --git a/common/SH_CommonFunc.hpp b/common/SH_CommonFunc.hpp new file mode 100644 index 0000000..2a953a1 --- /dev/null +++ b/common/SH_CommonFunc.hpp @@ -0,0 +1,579 @@ +#ifndef _COMMONFUNC_ +#define _COMMONFUNC_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include //ipc +#include +#include "dirent.h" + + + + +//配置文件位置 +#define NETWORK "/etc/network/interfaces" +#define SYSTEMINFOFILE "/opt/configenv/SystemInfo.json" //系统信息 +#define SERVERCONFIG "/opt/configenv/ServerConfig.json" +#define NETWORKCONFIG "/opt/configenv/NetWorkConfig.json" +#define SOFTWARE_RUN_LOG "/opt/configenv/cidn.log" +#define BOARDTYPE "/opt/configenv/boardtype" //设备类型 +#define ZIGBEECONFIG "/opt/configenv/ZigbeeConfig.json" + + +#define SN "/opt/system/sn" //设备序列号 +#define SYSTEMSTART "/opt/system/start" //系统启动类型标志 0:正常启动 1:重启 2: + +#define GENERAL_BUF_SIZE 128*1024 + +using namespace std; + +enum TIME_SIZE{ + TIME_MINUTE=5, + TIME_SECEOND=8 +}; + +struct DevData{ + char mData[128]; + char mDataMing[128]; + int mLen; + DevData():mLen(0){ + memset(mData, 0, 128); + memset(mDataMing, 0, 128); + } +}; + +struct DevDataOfGwid{ + std::string mDevdata; + std::string mDevid; + bool mIsSimulate; + DevDataOfGwid():mDevdata(""),mDevid(""),mIsSimulate(false){ + } +}; + +typedef void (*onReceiveUart) (DevDataOfGwid &devData); + +struct sys_data { + char data[10240]; +}; + +typedef struct { + int total; + int count; + int type; + int number; + int flag; + char channelId[16]; + char SensorEngineeringUnit[32]; + float waveData[32000]; +} WAVE_CONTAIN; + + + +struct ZigbeeInfo { + int DevMode; + int Channel; + std::string PanID; + std::string MyAddr; + std::string DstAddr; +}; + +struct ZIGBEE { + char reserve[4]; + char DevName[16]; + char DevPwd[16]; + unsigned char DevMode; + unsigned char Chan; + short PanID; + short MyAddr; + unsigned char MyIEEE[8]; + short DstAddr; + unsigned char DstIEEE[8]; + unsigned char Reserve0; + unsigned char PowerLevel; + unsigned char RetryNum; + unsigned char TranTimeout; + unsigned char Serial_Rate; + unsigned char Serial_DataB; + unsigned char Serial_StopB; + unsigned char Serial_ParityB; + unsigned char Reserve[10]; +}; + + +struct RecvData { + unsigned char Head[3]; + unsigned char ShortAddr[2]; + unsigned char Type; + unsigned char Order; + unsigned char Data[92]; + unsigned char Crc; +}; + +struct DataNodeInfo { + int InitFlag; + int AccFlag; + int ZigbeeFlag; + int TemTopFlag; + int TemBotFlag; + int EquipSta;//设备状态 + std::string HardVersion; + std::string SoftVersion; + std::string BpNo; + std::string SerialNo; + std::string FirstPowerTime; + int ConfigFlag; + std::string StartBrands; + std::string StopBrands; + unsigned int FeatureInterVal; + unsigned int WaveInterVal; + int SamplingRate;//采样率 + int Range;//量程 + std::string EnvelopeBandPass; + std::string FaultFrequency; + std::string ZigbeePanId; + int ZigbeeChannel; + std::string ZigbeeShortAddr; + std::string ZigbeeLongAddr; + std::string ZigbeeDesAddr; + std::string ConfigDate; + int VIntegralFilterFrequency;//速度积分滤波频率 + + int RSSI; // 接收信号强度 +}; + +struct DataRecvStatic { + float TemTop; + float TemBot; + int Dip; + int Voltage; +}; + +struct DataRecvDym { + float DiagnosisPk; + float IntegratPk; + float IntegratRMS; + float RmsValues; + float EnvelopEnergy; + float Amp1; + float Amp2; + float Amp3; + float Amp4; + float Amp5; + float Phase1; + float Phase2; + float Phase3; + float Phase4; +}; + +struct TopicList{ + std::string mPubData; //每秒特征数据上传主题 + std::string mPubStatus; //状态上传主题 + std::string mPubHeart; + std::string mPubConfig; //上传配置主题 + std::string mSubData; //订阅主题 + std::string mPubWaveData; //原始数据发布主题 + std::string mPubWaveSecondData; //原始数据发布主题 + std::string mPubCmd; //命令控制发布主题 + std::string mPubRep; + + std::string mPubLocalWifi; + std::string mPubLocalWaveServer; + std::string mPubLocalWaveQt; + std::string mPubLocalTrigger; + std::string mPubLocalConfig; + std::string mPubLocalCmd; +}; + + +//系统描述文件数据定义 +typedef struct +{ + string siteID; //Unique ID for each site + string siteName; //Controller site name + string siteCountry; //Controller location country + string siteProvince; //province + string siteCity; //city + double siteLongitude; //longitude + double siteLatitude; //latitude + string siteTimeZone; + string plantName; //Unique plant number + string plantNo; + string equipmentName; //Equipment Description in the plant + string equipmentNo; + string dataWatchName; //DNS Name for the DataWatch + long dataWachAddedDate; //Date of settings’ creation (Time Stamp) + string dataWatchAssetID; //Unique equipment Asset ID + string deviceType; + string dataWachAddedBy; //User who edited settings + string serialNumber; + string softVersion; + +}SystemInfo; + +typedef struct { + int number; + std::string SensorEngineeringUnit; + float waveData[GENERAL_BUF_SIZE]; +} WAVE_GENERAL; + + +struct Param_01 { + int mMode; //0:登陆 1:更改密码 + std::string mUserName; + std::string mPassWord; + std::string mPassWordNew; + Param_01():mMode(0), mUserName(""), mPassWord(""), mPassWordNew(""){}; +}; + +struct Param_02 { + int mMode; //0:配置时间 1:获取时间 + int mTimeStamp; + Param_02():mMode(0),mTimeStamp(0){}; +}; + + +struct Param_20 { + int mMode; //0: 配置 1:获取 + std::string mCmdSerial; + std::string mDataWatchName; + std::string mDataWatchAssetId; + std::string mDataWatchAddedBy; + Param_20():mMode(0), mCmdSerial(""), mDataWatchName(""), mDataWatchAssetId(""), mDataWatchAddedBy(""){}; +}; + + +struct Param_22 { + int mMode; + std::string mCmdSerial; + std::string mTimeZone; + Param_22():mMode(0),mCmdSerial(""), mTimeZone(""){}; +}; + + +struct Param_23 { + int mMode; + std::string mCmdSerial; + std::string mServerIp; + std::string mPort; + std::string mCommMode; // 通信模式,有线通信模式 = 1;4G LTE 无线通信模式 = 2 + Param_23():mMode(0),mCmdSerial(""), mServerIp(""),mPort(""),mCommMode(""){}; +}; + + +struct Param_24 { + int mMode; + std::string mCmdSerial; + std::string mFileServerIp; + std::string mFilePort; + std::string mFileServerSwitch; + Param_24():mMode(0),mCmdSerial(""), mFileServerIp(""),mFilePort(""),mFileServerSwitch(""){}; +}; + +struct Param_25 { + int mMode; + std::string mCmdSerial; + std::string mDnsName; + std::string mNetworkPortStatus; + std::string mGateway; + std::string mSubnetMask; + std::string mIp; + std::string mHostName; + Param_25():mMode(0),mCmdSerial(""), mDnsName(""),mGateway(""),mSubnetMask(""),mIp(""),mHostName(""){}; +}; + + +struct Param_26 { + int mMode; + std::string mCmdSerial; + std::string mDataNodeNo; + Param_26():mMode(0),mCmdSerial(""),mDataNodeNo(""){}; + +}; + +struct Param_27 { + int mMode; + std::string mCmdSerial; + std::string mDataNodeNo; + Param_27():mMode(0),mCmdSerial(""),mDataNodeNo(""){}; + +}; + + +struct Param_28 { + int mMode; + std::string mDataNodeNo; + std::string mDataNodeName; + Param_28():mMode(0),mDataNodeNo(""),mDataNodeName(""){}; +}; + +struct Param_29 { + int mMode; + std::string mCmdSerial; + std::string mChannelId; + std::string mDataNodeNo; + int mPackageFlag; + Param_29():mMode(0),mCmdSerial(""),mChannelId(""),mDataNodeNo(""),mPackageFlag(0){}; +}; + +struct Param_30 { + int mMode; + std::string mChannelId; + std::string mDataNodeNo; + int mPackageFlag; + Param_30():mMode(0),mChannelId(""),mDataNodeNo(""),mPackageFlag(0){}; +}; + +struct Param_31 { + int mMode; + //int mChannelId; + std::string mChannelId; + Param_31():mMode(0),mChannelId(""){}; +}; + +struct Param_32 { + int mMode; + std::string mChannelId; + int mPackageFlag; + Param_32():mMode(0),mChannelId(""),mPackageFlag(0){}; +}; + +struct Param_33 { + int mMode; + std::string mUnit; + Param_33():mMode(0),mUnit(""){}; +}; + +struct Param_34 { + int mMode; + std::string mBeforeTime; + std::string mAfterTime; + Param_34():mMode(0),mBeforeTime(""),mAfterTime(""){}; +}; + +struct Param_35 { + int mMode; + std::string mTriggerInterValTime; + std::string mTriggerInterValSwitch; + Param_35():mMode(0),mTriggerInterValTime(""),mTriggerInterValSwitch(){}; +}; + +struct Param_36 { + int mMode; + std::string mTriggerTime; + std::string mTriggerTimeSwitch; + Param_36():mMode(0),mTriggerTime(""),mTriggerTimeSwitch(){}; +}; + +struct Param_37 { + int mMode; + std::string mTriggerDelayTime; + std::string mTriggerDelaySwitch; + Param_37():mMode(0),mTriggerDelayTime(""),mTriggerDelaySwitch(){}; +}; + +struct Param_39 { + int mMode; + int mPage; + int mNumber; +}; + +struct Param_45 { + int mMode; //0: 配置 1:获取 + std::string mCmdSerial; + std::string mCountryId; + std::string mProvincesId ; + std::string mCityListId; + Param_45():mMode(0),mCmdSerial(""), mCountryId(""),mProvincesId(""),mCityListId(""){}; +}; + +struct Param_46 { + int mMode; + std::string mFileName; + Param_46():mMode(0),mFileName(""){}; +}; + +struct Param_47 { + int mMode; + std::string mFileName; + Param_47():mMode(0),mFileName(""){}; +}; + + + + + +/** +* @brief 系统运行时输入入参进行系统软件版本查询 +* @param argv 输入参数 -vV版本查询 --debugmode日志调试模式 +* @return 函数返回0执行成功 +*/ +extern int CheckFileVersion(int argc, char** argv); + +/** +* @brief 获取当前实时时间 +* @return 时间string 例:2018-11-18 17:16:10 +*/ +extern std::string GetCurrentTime(); + +/** +* @brief 和系统交互函数 +* @param cmd 要发出的系统命令 例:ls +* @param buf 系统返回的数据存在buf里 +* @return -1:失败 0:成功 +*/ +extern int system_custom(const char *cmd, char *buf); + + +//extern int uartreadhandle(); + +/** +* @brief 向日志写入内存信息 +*/ +extern void WriteMemoryInfo(); + + +/** +* @brief 获取当前日期 +* @return 当前日期的string +*/ +extern std::string GetDayDate(); + +/** +* @brief 获取当前时间 例 12:00 +* @return void +*/ +extern void GetTime_(char * time_buff,TIME_SIZE len) ; + +/** +* @brief 获取当前时间戳 +* @param timebuf 定义的buf存储数据 +* @param type 0 是毫秒级的时间戳 1 秒级的时间戳 +* @return void +*/ +extern void GetTimeNet(char* timebuf, int type); + +/** +* @brief 从配置文件中读取数据 +* @param filename 配置文件名 +* @param config 配置选项 +* @param option 具体配置参数 +* @return std::string 返回要获取的参数数据 +*/ +extern std::string ReadStrByOpt(std::string filename, std::string config, std::string option); + +/** +* @brief 写配置文件 +* @param filename 配置文件名 +* @param config 配置选项 +* @param option 具体配置参数 +* @param value 具体的数据值 +* @return int 0:配置成功 +*/ +extern int WriteStr2Config(std::string filename, std::string config, std::string option, std::string value, bool listable = false); + +/** +* @brief 获取设备的MAC地址做为设备的唯一标识 +* @return std::string Mac地址 +*/ +extern std::string GetLocalMac(); + +/** +* @brief 获取设备IP +* @return std::string IP地址 +*/ +extern std::string IpAddrInit(); + +/** +* @brief 获取正在工作的网卡 +* @return std::string +*/ +extern std::string GetWorkNic(); + +/** +* @brief 获取系统基本信息 +* @return std::string CPU MEM DISK info +*/ +extern std::string GetSysInfo(); + +/** +* @brief 去掉字符串所有空格 +* @return std::string +*/ +extern std::string & ClearAllSpace(std::string &str); + +/** +* @brief 调用接口写入data数据 +* @return void +*/ +extern void StartWriteToDat(); + +/** +* @brief 循环检测文件 +* @return void +*/ +extern void BackupDatFile(); + +/** +* @brief 降采样 +* @return double +*/ +extern float * ReSample(int WaveDataLength, int N, int *NewWaveDataLength, std::vector & WaveData); + +/** +* @brief 设置系统时间 +* @return int +*/ +extern int SetTime(unsigned long seconds, int milliseconds = 0); + +/** +* @brief 删除配置文件 +* @return int +*/ +extern void RemoveConfig(); + +/** +* @brief 获取文件内容 +* @param filename 文件名 +* @param line 第几行 +* @return std::string +*/ +extern std::string GetFileContent(std::string filename, int line); + +/** +* @brief 配置时区 +* @param zoneid 时区ID +* @return void +*/ +extern void ZoneConfig(std::string zoneid); + +/** +* @brief 获取系统基本信息 +* @return std::string CPU MEM DISK info +*/ +extern std::string GetSysStatus(); + + +extern void swap(char *data); + + +#endif diff --git a/common/SH_global.h b/common/SH_global.h new file mode 100644 index 0000000..c416dec --- /dev/null +++ b/common/SH_global.h @@ -0,0 +1,149 @@ +#ifndef _GLOBALCONFIG_H_ +#define _GLOBALCONFIG_H_ +#include +#include +#include +#include +#include +#include +#include "../API_log/SH_log.h" +#include "SH_CommonFunc.hpp" +#include "../mqttclient/SH_MqttClient.h" + +//******************** 全局变量********************** +enum enumZigBeeTransmitStatus { + NO_ENTER_TRANSMITTING_STATUS = 0, + ENTER_TRANSMITTING_STATUS +}; + +class GlobalConfig +{ +public : + static int RUN_MODE; //1调试模式 0运行模式 + static int QuitFlag_G; //程序退出标志 + static int LinkStatus_G; //和服务器连接状态 + static int LinkCount; + static std::string Version; //软件版本号 + static std::string MacAddr_G; //设备MAC地址 + static std::string IpAddr_G; //设备IP + static std::string DbName_G; //数据库名字 + static std::string ServerIP; //服务器地址 + static int ServerPort; //服务器端口 + static std::string UartName_G; + static TopicList Topic_G; //发布的主题 + static ZigbeeInfo ZigbeeInfo_G; //gateway zigbee info + static ZIGBEE Zigbee_G; + + static enumZigBeeTransmitStatus EnterZigBeeWaveTransmittingFlag_G; // 进入ZigBee网络原始数据传输状态标志 + static int EnterZigBeeWaveTransmittingCnt_G; // 进入ZigBee网络原始数据传输状态计数器,以秒为单位进行计数 +}; + +#define NONE "\033[m" +#define RED "\033[0;32;31m" +#define LIGHT_RED "\033[1;31m" +#define GREEN "\033[0;32;32m" +#define LIGHT_GREEN "\033[1;32m" +#define BLUE "\033[0;32;34m" +#define LIGHT_BLUE "\033[1;34m" +#define DARY_GRAY "\033[1;30m" +#define CYAN "\033[0;36m" +#define LIGHT_CYAN "\033[1;36m" +#define PURPLE "\033[0;35m" +#define LIGHT_PURPLE "\033[1;35m" +#define BROWN "\033[0;33m" +#define YELLOW "\033[1;33m" +#define LIGHT_GRAY "\033[0;37m" +#define WHITE "\033[1;37m" + +#define perror_info(info) { \ + if (GlobalConfig::RUN_MODE) { \ + perror(info); \ + }\ + } + +#define print_dev(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(YELLOW"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} + +#define print_error(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(LIGHT_RED"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} + +#define print_purple(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(PURPLE"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} + +#define print_control(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(GREEN"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} + +#define print_red(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(RED"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} +#define print_light_green(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(LIGHT_GREEN"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} +#define print_blue(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(BLUE"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), GetCurrentTime().c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} +#define print_light_blue(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(LIGHT_BLUE"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid),boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} +#define print_dary_gray(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(DARY_GRAY"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} +#define print_cyan(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(CYAN info"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} +#define print_debug(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(LIGHT_CYAN info NONE, ##__VA_ARGS__);\ + }\ +} +#define print_light_purple(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(LIGHT_PURPLE"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} +#define print_brown(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(BROWN"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} +#define print_info(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(LIGHT_GRAY"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} +#define print_white(info,...) {\ + if (GlobalConfig::RUN_MODE) {\ + printf(WHITE"[threadid:%ld][%s][%s:%d]" info NONE, syscall(SYS_gettid), boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()).c_str(),__FUNCTION__, __LINE__, ##__VA_ARGS__);\ + }\ +} + +//按8 取整 +#define Length_(len) do{ \ + len = ((((len>>3) + ((len&0x7)>0?1:0))<<4) + 8); \ + } while (0) + +#endif diff --git a/dbaccess/SH_SqlDB.cpp b/dbaccess/SH_SqlDB.cpp new file mode 100644 index 0000000..10e7335 --- /dev/null +++ b/dbaccess/SH_SqlDB.cpp @@ -0,0 +1,511 @@ +#include "SH_SqlDB.hpp" +#include "../API_log/SH_log.h" +#include "../common/SH_global.h" +#include + +bool SqlSwitch() +{ + if (access("./sql", 0) >= 0) { + return true; + } + return false; +} + +SqliteDB *sql_ctl = SqliteDB::instance(); + +SqliteDB::SqliteDB() +{ +} + +SqliteDB::~SqliteDB() +{ +} + +void SqliteDB::SqliteInit(const char *pDbName, bool isDB2) +{ + char sql_exec[2048]; + memset(sql_exec, 0, 2048); + + //创建传感器信息存储表 + memset(sql_exec, 0, 2048); + sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);", + T_SENSOR_INFO(TNAME), + T_SENSOR_INFO(DATANODENO), + T_SENSOR_INFO(DATANODENAME), + T_SENSOR_INFO(INITFLAG), + T_SENSOR_INFO(ACCFLAG), + T_SENSOR_INFO(ZIGBEEFLAG), + T_SENSOR_INFO(TEMTOPFLAG), + T_SENSOR_INFO(TEMBOTFLAG), + T_SENSOR_INFO(EQUIPSTA), + T_SENSOR_INFO(HARDVERSION), + T_SENSOR_INFO(SOFTVERSION), + T_SENSOR_INFO(BPNO), + T_SENSOR_INFO(SERIALNO), + T_SENSOR_INFO(FIRSTPOWERNO), + T_SENSOR_INFO(CONFIGFLAG), + T_SENSOR_INFO(STARTBRANDS), + T_SENSOR_INFO(STOPBRANDS), + T_SENSOR_INFO(FEATUREINTERVAL), + T_SENSOR_INFO(WAVEINTERVAL), + T_SENSOR_INFO(SAMPLINGRATE), + T_SENSOR_INFO(SCOPE), + T_SENSOR_INFO(RANGE), + T_SENSOR_INFO(ENVELOPEBANDPASS), + T_SENSOR_INFO(FAULTFREQUENCY), + T_SENSOR_INFO(ZIGBEEPANID), + T_SENSOR_INFO(ZIGBEECHANNEL), + T_SENSOR_INFO(ZIGBEESHORTADDR), + T_SENSOR_INFO(ZIGBEELONGADDR), + T_SENSOR_INFO(ZIGBEEDESADDR), + T_SENSOR_INFO(STATUS), + T_SENSOR_INFO(TIMESTAMP), + T_SENSOR_INFO(VIFF), + T_SENSOR_INFO(RSSI)), + CreateTable(sql_exec, isDB2); + + //创建传感器数据存储表 + memset(sql_exec, 0, 2048); + sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);", + T_DATA_INFO(TNAME), + T_DATA_INFO(DATANODENO), + T_DATA_INFO(CHANNELID), + T_DATA_INFO(DIAGNOSISEAK), + T_DATA_INFO(INTEGRATPK), + T_DATA_INFO(INTEGRATRMS), + T_DATA_INFO(RMSVALUES), + T_DATA_INFO(ENVELOPNERGY), + T_DATA_INFO(AMP1), + T_DATA_INFO(AMP2), + T_DATA_INFO(AMP3), + T_DATA_INFO(AMP4), + T_DATA_INFO(AMP5), + T_DATA_INFO(PHASE1), + T_DATA_INFO(PHASE2), + T_DATA_INFO(PHASE3), + T_DATA_INFO(PHASE4), + T_DATA_INFO(TIMESTAMP)); + CreateTable(sql_exec, isDB2); + + + + //创建传感器静态数据存储表 + memset(sql_exec, 0, 2048); + sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s);", + T_DATASTATIC_INFO(TNAME), + T_DATASTATIC_INFO(DATANODENO), + T_DATASTATIC_INFO(CHANNELID), + T_DATASTATIC_INFO(TEMTOP), + T_DATASTATIC_INFO(TEMBOT), + T_DATASTATIC_INFO(DIP), + T_DATASTATIC_INFO(VOLTAGE), + T_DATASTATIC_INFO(TIMESTAMP)); + CreateTable(sql_exec, isDB2); +} + +bool SqliteDB::OpenDB(const char *pDbName, bool isDB2) +{ + if (isDB2 == false) { + int ret = 0; + ret = sqlite3_open(pDbName, &mDBAcess); + if (ret == SQLITE_OK) { + sqlite3_exec(mDBAcess, "PRAGMA synchronous = NORMAL;", 0, 0, 0); + sqlite3_exec(mDBAcess, "PRAGMA cache_size=8000;", 0, 0, 0); + sqlite3_exec(mDBAcess, "PRAGMA temp_store = MEMORY;", 0, 0, 0); + sqlite3_exec(mDBAcess, "PRAGMA auto_vacuum = 1;", 0, 0, 0); + print_info("Success To Open DataBase!\n"); + } + else { + print_error("Fail To Open DataBase!\n"); + return false; + } + } + else { + int ret = 0; + ret = sqlite3_open(pDbName, &mDb2); + if (ret == SQLITE_OK) { + sqlite3_exec(mDb2, "PRAGMA synchronous = NORMAL;", 0, 0, 0); + sqlite3_exec(mDb2, "PRAGMA cache_size=8000;", 0, 0, 0); + sqlite3_exec(mDb2, "PRAGMA temp_store = MEMORY;", 0, 0, 0); + sqlite3_exec(mDb2, "PRAGMA auto_vacuum = 1;", 0, 0, 0); + print_info("Success To Open DataBase!\n"); + } + else { + print_error("Fail To Open DataBase!\n"); + return false; + } + } + return true; +} + +int SqliteDB::CloseDB() +{ + return sqlite3_close(mDBAcess); +} + +sqlite3 *SqliteDB::GetDbHandle(bool isDB2) +{ + if (isDB2 == false) { + return mDBAcess; + } + else { + return mDb2; + } +} + +int SqliteDB::CreateTable(const char *sql, bool isDB2) +{ + print_light_green("%s\n", sql); + // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", sql); + char *msg; + int iRet = sqlite3_exec(GetDbHandle(isDB2), sql, 0, 0, &msg); + if (iRet != SQLITE_OK) { + print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); + sqlite3_free(msg); + } + return iRet; +} + +int SqliteDB::GetTableColumnCount(const char *tablename, bool isDB2) +{ + std::string strSql = "select * from "; + int count = 0; + sqlite3_stmt *stmt; + strSql = strSql + tablename + ";"; + print_light_green("%s\n", strSql.c_str()); + // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + sqlite3_prepare_v2(GetDbHandle(isDB2), strSql.c_str(), -1, &stmt, 0); + count = sqlite3_column_count(stmt); + sqlite3_finalize(stmt); + return count; +} + +int SqliteDB::GetTableRows(const char *tablename, const char *whereCon) +{ + int nRow = 0; + std::string strSql = "select count(*) from "; + if (whereCon != NULL) { + strSql = strSql + tablename + " where " + whereCon + ";"; + } + else { + strSql = strSql + tablename + ";"; + } + print_light_green("%s\n", strSql.c_str()); + // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + sqlite3_stmt *stmt; + if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) { + print_error("sqlite3_prepare_v2:%s\n",sqlite3_errmsg(mDBAcess)); + sqlite3_finalize(stmt); + return -1; + } + int retStep = sqlite3_step(stmt); + if (retStep == SQLITE_ROW) { + nRow = sqlite3_column_int(stmt, 0); + } + sqlite3_finalize(stmt); + return nRow; +} + +int SqliteDB::AlterTable(const char *tablename, const char *column, bool isAdd, bool isDB2) +{ + int iRet = SQLITE_ERROR; + if (isAdd) { + std::string strSql = "alter table "; + strSql = strSql + tablename + " add " + column + ";"; + print_light_green("%s\n", strSql.c_str()); + // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + iRet = sqlite3_exec(GetDbHandle(isDB2), strSql.c_str(), 0, 0, NULL); + if (iRet != SQLITE_OK) { + perror_info("sqlite3_exec"); + } + } + else { + } + return iRet; +} + +vec_t SqliteDB::GetDataSingleLine(const char *tablename, const char *column, const char *whereCon) +{ + vec_t vecResult; + std::string strSql = "select "; + if (whereCon != NULL) { + strSql = strSql + column + " from " + tablename + " where " + whereCon + ";"; + } + else { + strSql = strSql + column + " from " + tablename + ";"; + } + print_light_green("%s\n", strSql.c_str()); + // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + sqlite3_stmt *stmt; + if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) { + print_error("sqlite3_prepare_v2:%s\n", sqlite3_errmsg(mDBAcess)); + sqlite3_finalize(stmt); + return vecResult; + } + int retStep = sqlite3_step(stmt); + int column_count = sqlite3_column_count(stmt); + if (retStep == SQLITE_ROW) { + for (int iCol = 0; iCol < column_count; iCol++) { + char *columninfo = (char*)sqlite3_column_text(stmt, iCol); + std::string str = columninfo != NULL ? columninfo : ""; + vecResult.push_back(str); + } + } + sqlite3_finalize(stmt); + return vecResult; +} + + + +std::string SqliteDB::GetData(const char *tablename, const char *column, const char *whereCon) +{ + std::string strRes; + std::string strSql = "select "; + if (whereCon != NULL) { + strSql = strSql + column + " from " + tablename + " where " + whereCon + ";"; + } + else { + strSql = strSql + column + " from " + tablename + ";"; + } + print_light_green("%s\n", strSql.c_str()); + // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + sqlite3_stmt *stmt; + if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) { + print_error("sqlite3_prepare_v2:%s\n", sqlite3_errmsg(mDBAcess)); + sqlite3_finalize(stmt); + return strRes; + } + int retStep = sqlite3_step(stmt); + if (retStep == SQLITE_ROW) { + char *columninfo = (char*)sqlite3_column_text(stmt, 0); + strRes = columninfo != NULL ? columninfo : ""; + } + sqlite3_finalize(stmt); + return strRes; +} + +array_t SqliteDB::GetDataMultiLine(const char *tablename, const char *column, const char *whereCon) +{ + array_t arrResult; + std::string strSql = "select "; + if (whereCon != NULL) { + strSql = strSql + column + " from " + tablename + " where " + whereCon + ";"; + } + else { + strSql = strSql + column + " from " + tablename + ";"; + } + print_light_green("%s\n", strSql.c_str()); +// if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + sqlite3_stmt *stmt; + if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) { + print_error("sqlite3_prepare_v2:%s\n", sqlite3_errmsg(mDBAcess)); + sqlite3_finalize(stmt); + return arrResult; + } + int retStep = sqlite3_step(stmt); + int column_count = sqlite3_column_count(stmt); + while (retStep == SQLITE_ROW) { + vec_t vecResult; + for (int iCol = 0; iCol < column_count; iCol++) { + char *columninfo = (char*)sqlite3_column_text(stmt, iCol); + std::string str = columninfo != NULL ? columninfo : ""; + vecResult.push_back(str); + } + arrResult.push_back(vecResult); + retStep = sqlite3_step(stmt); + } + sqlite3_finalize(stmt); + return arrResult; +} + +vec_t SqliteDB::GetDataMultiLineOfOneColumn(const char *tablename, const char *column, const char *whereCon) +{ + vec_t vecResult; + std::string strSql = "select "; + if (whereCon != NULL) { + strSql = strSql + column + " from " + tablename + " where " + whereCon + ";"; + } + else { + strSql = strSql + column + " from " + tablename + ";"; + } + print_light_green("%s\n", strSql.c_str()); + // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + sqlite3_stmt *stmt; + if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) { + print_error("sqlite3_prepare_v2:%s\n", sqlite3_errmsg(mDBAcess)); + sqlite3_finalize(stmt); + return vecResult; + } + int retStep = sqlite3_step(stmt); + while (retStep == SQLITE_ROW) { + char *columninfo = (char*)sqlite3_column_text(stmt, 0); + std::string str = columninfo != NULL ? columninfo : ""; + vecResult.push_back(str); + retStep = sqlite3_step(stmt); + } + sqlite3_finalize(stmt); + return vecResult; +} + + + +int SqliteDB::DeleteTableData(const char* tablename, const char* whereCond, bool isDB2) +{ + std::string strSql = "delete from "; + if (whereCond != NULL) { + strSql = strSql + tablename + " where " + whereCond + ";"; + } + else { + strSql = strSql + tablename + ";"; + } + print_light_green("%s\n", strSql.c_str()); + // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + char *msg; + int iRet = sqlite3_exec(GetDbHandle(isDB2), strSql.c_str(), 0, 0, &msg); + + if (iRet != SQLITE_OK) { + print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); + sqlite3_free(msg); + } + return iRet; +} + +int SqliteDB::DeleteTableDataOneConditon(const char* tablename, const char* condColumnName, const char * condColumnValue, bool isDB2) +{ + std::string strSql = "delete from "; + if (condColumnName != NULL) { + strSql = strSql + tablename + " where " + condColumnName + "='" + condColumnValue + "';"; + } + else { + strSql = strSql + tablename + ";"; + } + print_light_green("%s\n", strSql.c_str()); +// if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + char *msg; + int iRet = sqlite3_exec(GetDbHandle(isDB2), strSql.c_str(), 0, 0, &msg); + + if (iRet != SQLITE_OK) { + print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); + sqlite3_free(msg); + } + return iRet; +} + +int SqliteDB::UpdateTableData(const char* tablename, const char* updateColumn, const char* whereCond, bool isDB2) +{ + std::string strSql = "update "; + if (whereCond != NULL) { + strSql = strSql + tablename + " set " + updateColumn + " where " + whereCond + ";"; + } + else { + strSql = strSql + tablename + " set " + updateColumn + ";"; + } + print_light_green("%s\n", strSql.c_str()); +// if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + char *msg; + int iRet = sqlite3_exec(GetDbHandle(isDB2), strSql.c_str(), 0, 0, &msg); + + if (iRet != SQLITE_OK) { + print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); + sqlite3_free(msg); + } + return iRet; +} + +int SqliteDB::UpdateTableData(const char* directSql, bool isDB2) +{ + print_light_green("%s\n", directSql); +// if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", directSql); + char *msg; + int iRet = sqlite3_exec(GetDbHandle(isDB2), directSql, 0, 0, &msg); + + if (iRet != SQLITE_OK) { + print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); + sqlite3_free(msg); + } + return iRet; +} + +int SqliteDB::UpdateTableDataOneColumn(const char* tablename, const char* columnName, const char* columnValue, const char* whereColName, const char * whereColValue, bool isDB2) +{ + std::string strSql = "update "; + if (whereColName != NULL) { + strSql = strSql + tablename + " set " + columnName + "='" + columnValue + "'" + " where " + whereColName + "='" + whereColValue + "';"; + } + else { + strSql = strSql + tablename + " set " + columnName + "='" + columnValue + "';"; + } + print_light_green("%s\n", strSql.c_str()); + // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + char *msg; + int iRet = sqlite3_exec(GetDbHandle(isDB2), strSql.c_str(), 0, 0, &msg); + + if (iRet != SQLITE_OK) { + print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); + sqlite3_free(msg); + } + return iRet; +} + +int SqliteDB::InsertData(const char* tablename, const char* insertValues, int replace, bool expandable, bool isDB2) +{ + char *msg; + int iRet = 0; + if (expandable) { + char *strSql = (char *)malloc(4096); + if (strSql == NULL) { + print_error("malloc error\n"); + abort(); + } + char strReplace[] = "replace into "; + memset(strSql, 0, 4096); + if (replace == 0) { + memset(strReplace, 0, sizeof(strSql)); + } + sprintf(strSql, "%s %s%s %s %s %s", "insert into", strReplace, tablename, "values(", insertValues, ");"); + print_light_green("%s\n", strSql); +// if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql); + iRet = sqlite3_exec(GetDbHandle(isDB2), strSql, 0, 0, &msg); + + free(strSql); + } else { + std::string strSql = "insert into "; + if (replace != 0) { + strSql = "replace into "; + } + strSql = strSql + tablename + " values(" + insertValues + ");"; + print_light_green("%s\n", strSql.c_str()); +// if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); + iRet = sqlite3_exec(GetDbHandle(isDB2), strSql.c_str(), 0, 0, &msg); + } + if (iRet != SQLITE_OK) { + print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); + sqlite3_free(msg); + } + return iRet; +} + +int SqliteDB::TransBegin() +{ + return sqlite3_exec(mDBAcess, "begin;", 0, 0, 0); +} + +int SqliteDB::TransRollback() +{ + return sqlite3_exec(mDBAcess, "rollback;", 0, 0, 0); +} + +int SqliteDB::TransCommit() +{ + return sqlite3_exec(mDBAcess, "commit;", 0, 0, 0); +} + +void SqliteDB::HandError(int code) +{ + if (code == SQLITE_CORRUPT) { + /* + * 用system 删除数据库 + */ + exit(1); + } +} diff --git a/dbaccess/SH_SqlDB.hpp b/dbaccess/SH_SqlDB.hpp new file mode 100644 index 0000000..43f942e --- /dev/null +++ b/dbaccess/SH_SqlDB.hpp @@ -0,0 +1,127 @@ +#ifndef _SQLDB_H_L +#define _SQLDB_H_L +extern "C"{ +#include +} +#include +#include +#include +#include +#include +#include +#include "../utility/SH_MySingleton.hpp" + +#define T_SENSOR_INFO(x) T_SENSOR_INFO[T_SENSOR_INFO_##x] +#define T_DATA_INFO(x) T_DATA_INFO[T_DATA_INFO_##x] +#define T_DATASTATIC_INFO(x) T_DATASTATIC_INFO[T_DATASTATIC_INFO_##x] + +typedef std::map map_t; +typedef std::vector vec_t; +typedef std::vector array_t; + +class SqliteDB : public MySingleton < SqliteDB > { +public: + explicit SqliteDB(); + virtual ~SqliteDB(); + bool OpenDB(const char *pDbName, bool isDB2=false); + void SqliteInit(const char *pDbName, bool isDB2=false); + int TransBegin(); + int TransRollback(); + int TransCommit(); + int CreateTable(const char *sql, bool isDB2=false); + int GetTableColumnCount(const char *tablename, bool isDB2 = false); + int GetTableRows(const char *tablename, const char *whereCon); + int AlterTable(const char *tablename, const char *column, bool isAdd = true, bool isDB2=false); + vec_t GetDataSingleLine(const char *tablename, const char *column, const char *whereCon); + std::string GetData(const char *tablename, const char *column, const char *whereCon); + array_t GetDataMultiLine(const char *tablename, const char *column, const char *whereCon); + vec_t GetDataMultiLineOfOneColumn(const char *tablename, const char *column, const char *whereCon); + int DeleteTableData(const char* tablename, const char* whereCond = NULL, bool isDB2=false); + int DeleteTableDataOneConditon(const char* tablename, const char* condColumnName, const char * condColumnValue, bool isDB2=false); + int UpdateTableData(const char* tablename, const char* updateColumn, const char* whereCond, bool isDB2 = false); + int UpdateTableDataOneColumn(const char* tablename, const char* columnName, const char* columnValue, const char* whereColName = NULL, const char * whereColValue = NULL, bool isDB2 = false); + int UpdateTableData(const char* directSql, bool isDB2 = false); + int InsertData(const char* tablename, const char* insertValues, int replace = 0, bool expandalbe = false, bool isDB2 = false); + int CloseDB(); + +private: + sqlite3 *GetDbHandle(bool isDB2); + void HandError(int code); + sqlite3 *mDBAcess; + sqlite3 *mDb2; +}; +extern SqliteDB *sql_ctl; + +typedef enum { + T_SENSOR_INFO_TNAME = 0, + T_SENSOR_INFO_DATANODENO, + T_SENSOR_INFO_DATANODENAME, + T_SENSOR_INFO_INITFLAG, + T_SENSOR_INFO_ACCFLAG, + T_SENSOR_INFO_ZIGBEEFLAG, + T_SENSOR_INFO_TEMTOPFLAG, + T_SENSOR_INFO_TEMBOTFLAG, + T_SENSOR_INFO_EQUIPSTA, + T_SENSOR_INFO_HARDVERSION, + T_SENSOR_INFO_SOFTVERSION, + T_SENSOR_INFO_BPNO, + T_SENSOR_INFO_SERIALNO, + T_SENSOR_INFO_FIRSTPOWERNO, + T_SENSOR_INFO_CONFIGFLAG, + T_SENSOR_INFO_STARTBRANDS, + T_SENSOR_INFO_STOPBRANDS, + T_SENSOR_INFO_FEATUREINTERVAL, + T_SENSOR_INFO_WAVEINTERVAL, + T_SENSOR_INFO_SAMPLINGRATE, + T_SENSOR_INFO_SCOPE, + T_SENSOR_INFO_RANGE, + T_SENSOR_INFO_ENVELOPEBANDPASS, + T_SENSOR_INFO_FAULTFREQUENCY, + T_SENSOR_INFO_ZIGBEEPANID, + T_SENSOR_INFO_ZIGBEECHANNEL, + T_SENSOR_INFO_ZIGBEESHORTADDR, + T_SENSOR_INFO_ZIGBEELONGADDR, + T_SENSOR_INFO_ZIGBEEDESADDR, + T_SENSOR_INFO_STATUS, + T_SENSOR_INFO_TIMESTAMP, + T_SENSOR_INFO_VIFF, + T_SENSOR_INFO_RSSI +}T_SENSOR_INFO_Index; +const static char* T_SENSOR_INFO[] = { "t_sensor_info", "dataNodeNo", "dataNodeName", "initFlag", "accFlag","zigbeeFlag","temTopFlag","temBotFlag","equipSta","hardVersion", "softVersion","bpNo","serialNo","firstPowerTime","configFlag","startBrands","stopBrands","featureInterVal","waveInterVal","samplingRate","scope","range","envelopeBandPass","faultFrequency","zigbeePanId","zigbeeChannel","zigbeeShortAddr","zigbeeLongAddr","zigbeeDesAddr","status","timeStamp","viff","RSSI"}; + +typedef enum { + T_DATA_INFO_TNAME = 0, + T_DATA_INFO_DATANODENO, + T_DATA_INFO_CHANNELID, + T_DATA_INFO_DIAGNOSISEAK, + T_DATA_INFO_INTEGRATPK, + T_DATA_INFO_INTEGRATRMS, + T_DATA_INFO_RMSVALUES, + T_DATA_INFO_ENVELOPNERGY, + T_DATA_INFO_AMP1, + T_DATA_INFO_AMP2, + T_DATA_INFO_AMP3, + T_DATA_INFO_AMP4, + T_DATA_INFO_AMP5, + T_DATA_INFO_PHASE1, + T_DATA_INFO_PHASE2, + T_DATA_INFO_PHASE3, + T_DATA_INFO_PHASE4, + T_DATA_INFO_TIMESTAMP, +}T_DATA_INFO_Index; +const static char* T_DATA_INFO[] = { "t_data_info", "dataNodeNo", "channelID", "diagnosisPk", "integratPk","integratRMS","rmsValues","envelopEnergy","Amp1","Amp2","Amp3","Amp4","Amp5","Phase1","Phase2","Phase3","Phase4","timeStamp"}; + + +typedef enum { + T_DATASTATIC_INFO_TNAME = 0, + T_DATASTATIC_INFO_DATANODENO, + T_DATASTATIC_INFO_CHANNELID, + T_DATASTATIC_INFO_TEMTOP, + T_DATASTATIC_INFO_TEMBOT, + T_DATASTATIC_INFO_DIP, + T_DATASTATIC_INFO_VOLTAGE, + T_DATASTATIC_INFO_TIMESTAMP, +}T_DATASTATIC_INFO_Index; +const static char* T_DATASTATIC_INFO[] = { "t_datastatic_info","dataNodeNo","channelID","temTop","temBot","dip","voltage","timeStamp"}; + +#endif diff --git a/jsonparse/SH_JsonCmd.cpp b/jsonparse/SH_JsonCmd.cpp new file mode 100644 index 0000000..d5f8511 --- /dev/null +++ b/jsonparse/SH_JsonCmd.cpp @@ -0,0 +1,1226 @@ +#include "SH_JsonCmd.hpp" +#include "../dbaccess/SH_SqlDB.hpp" +#include "../platform/SH_PlatformInit.hpp" + +namespace{ + PlatformInit *platform = PlatformInit::instance(); + Calculation *pCalculation = Calculation::instance(); + Uart *pUart = Uart::instance(); +} + + +std::string JsonData::JsonCmd_20(Param_20 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = ""; + if (0 == param.mMode) { + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayName", param.mDataWatchName); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAssetId", param.mDataWatchAssetId); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy", param.mDataWatchAddedBy); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedDate", nowTimetamp); + } + + std::string boardtype = GetFileContent(BOARDTYPE, 1); + std::string ip = IpAddrInit(); + std::string sn = GetFileContent(SN, 1); + jsonVal[JSON_FIELD_CMD] = "20"; + jsonVal[JSON_FIELD_dataNodeGatewayNo] = GlobalConfig::MacAddr_G; + jsonVal["cmdSerial"] = param.mCmdSerial; + + Json::Value jsSystemInfo; + Json::Value jsBody; + + jsSystemInfo[JSON_FIELD_NAME] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayName"); + jsSystemInfo[JSON_FIELD_dataNodeGatewayNo] = GlobalConfig::MacAddr_G; + jsSystemInfo[JSON_FIELD_ASSETID] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAssetId"); + jsSystemInfo[JSON_FIELD_ADDEDBY] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy"); + jsSystemInfo[JSON_FIELD_ADDEDDATE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedDate"); + jsSystemInfo[JSON_FIELD_DEVICETYPE] = boardtype; + jsSystemInfo[JSON_FIELD_IPADDRESS] = ip; + jsSystemInfo[JSON_FIELD_SN] = sn; + jsSystemInfo[JSON_FIELD_VERSION] = GlobalConfig::Version; + jsSystemInfo[JSON_FIELD_TIMEZONE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "timezone"); + jsSystemInfo["zigbeePanId"] = GlobalConfig::ZigbeeInfo_G.PanID; + jsSystemInfo["zigbeeChannel"] = GlobalConfig::ZigbeeInfo_G.Channel; + jsSystemInfo["zigbeeAddr"] = GlobalConfig::ZigbeeInfo_G.MyAddr; + jsBody["SystemInfo"] = jsSystemInfo; + + std::string dataBody = showValue.write(jsBody); + jsonVal["cmdBody"] = dataBody; + return showValue.write(jsonVal); +} + + +std::string JsonData::JsonCmd_22(Param_22 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = ""; + if (0 == param.mMode) { + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "timezone", param.mTimeZone); + } + + jsonVal[JSON_FIELD_CMD] = "22"; + jsonVal[JSON_FIELD_dataNodeGatewayNo] = GlobalConfig::MacAddr_G; + jsonVal["cmdSerial"] = param.mCmdSerial; + + Json::Value jsSystemSetting; + Json::Value jsBody; + jsBody[JSON_FIELD_TIMEZONE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "timezone"); + + std::string dataBody = showValue.write(jsBody); + jsonVal["cmdBody"] = dataBody; + + return showValue.write(jsonVal); +} + + +std::string JsonData::JsonCmd_23(Param_23 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = ""; + if (0 == param.mMode) { + + WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", param.mServerIp); + WriteStr2Config(SERVERCONFIG, "Server", "localServerPort", param.mPort); + WriteStr2Config(SERVERCONFIG, "Server", "CommMode", param.mCommMode); + printf("param.mCommMode = %s\n",param.mCommMode.c_str()); + if("1" == param.mCommMode){//有线连接 + system("mv /etc/init.d/S91quectel-CM.sh /etc/init.d/wireless.sh"); + }else if("2" == param.mCommMode){//无线连接 + system("mv /etc/init.d/wireless.sh /etc/init.d/S91quectel-CM.sh"); + } + sleep(1); + system("reboot"); + } + + + jsonVal[JSON_FIELD_CMD] = "23"; + jsonVal[JSON_FIELD_dataNodeGatewayNo] = GlobalConfig::MacAddr_G; + jsonVal["cmdSerial"] = param.mCmdSerial; + + Json::Value jsSystemSetting; + Json::Value jsBody; + + jsBody[JSON_FIELD_SERVERIP] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress"); + jsBody[JSON_FIELD_SERVERPORT] = boost::lexical_cast(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort")); + jsBody[JSON_FIELD_CommMode] = boost::lexical_cast(ReadStrByOpt(SERVERCONFIG, "Server", "CommMode")); + std::string dataBody = showValue.write(jsBody); + jsonVal["cmdBody"] = dataBody; + + return showValue.write(jsonVal); +} + + + + +std::string JsonData::JsonCmd_25(Param_25 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = ""; + if (0 == param.mMode) { + WriteStr2Config(NETWORKCONFIG, "Net", "dnsName", param.mDnsName); + WriteStr2Config(NETWORKCONFIG, "Net", "networkPortStatus", param.mNetworkPortStatus); + WriteStr2Config(NETWORKCONFIG, "Net", "gateway", param.mGateway); + WriteStr2Config(NETWORKCONFIG, "Net", "subnetMask", param.mSubnetMask); + WriteStr2Config(NETWORKCONFIG, "Net", "ipAddress", param.mIp); + WriteStr2Config(NETWORKCONFIG, "Net", "hostName", param.mHostName); + } + + jsonVal["cmd"] = "25"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["cmdSerial"] = param.mCmdSerial; + + Json::Value jsSystemSetting; + Json::Value jsBody; + + + jsBody["dnsName"] = ReadStrByOpt(NETWORKCONFIG, "Net", "dnsName"); + jsBody["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, "Net", "networkPortStatus"); + jsBody["gateway"] = ReadStrByOpt(NETWORKCONFIG, "Net", "gateway"); + jsBody["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, "Net", "subnetMask"); + jsBody["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, "Net", "ipAddress"); + jsBody["hostName"] = ReadStrByOpt(NETWORKCONFIG, "Net", "hostName"); + + std::string dataBody = showValue.write(jsBody); + jsonVal["cmdBody"] = dataBody; + + return showValue.write(jsonVal); +} + + +std::string JsonData::JsonCmd_26(Param_26 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["cmd"] = "26"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["cmdSerial"] = param.mCmdSerial; + jsonVal["success"] = true; + jsonVal["message"] = "查询成功"; + Json::Value jsArray; + array_t arrRes; + arrRes = sql_ctl->GetDataMultiLine(T_SENSOR_INFO(TNAME), "*", NULL); + int iResult = arrRes.size(); + if (iResult > 0) { + for (int j = 0; j < iResult; j++) { + Json::Value jsSensorData; + jsSensorData["dataNodeNo"] = arrRes[j][0]; + jsSensorData["dataNodeName"] = arrRes[j][1]; + jsSensorData["initFlag"] = boost::lexical_cast(arrRes[j][2]); + jsSensorData["accFlag"] = boost::lexical_cast(arrRes[j][3]); + jsSensorData["zigbeeFlag"] = boost::lexical_cast(arrRes[j][4]); + jsSensorData["temTopFlag"] = boost::lexical_cast(arrRes[j][5]); + jsSensorData["temBotFlag"] = boost::lexical_cast(arrRes[j][6]); + jsSensorData["hardVersion"] = arrRes[j][8]; + jsSensorData["softVersion"] = arrRes[j][9]; + jsSensorData["bpNo"] = arrRes[j][10]; + jsSensorData["serialNo"] = arrRes[j][11]; + jsSensorData["firstPowerTime"] = arrRes[j][12]; + jsSensorData["configFlag"] = boost::lexical_cast(arrRes[j][13]); + jsSensorData["startBrands"] = arrRes[j][14]; + jsSensorData["stopBrands"] = arrRes[j][15]; + jsSensorData["featureInterVal"] = boost::lexical_cast(arrRes[j][16]); + jsSensorData["waveInterVal"] = boost::lexical_cast(arrRes[j][17]); + jsSensorData["samplingRate"] = boost::lexical_cast(arrRes[j][18]); + jsSensorData["envelopeBandPass"] = arrRes[j][21]; + jsSensorData["faultFrequency"] = arrRes[j][22]; + jsSensorData["zigbeePanId"] = arrRes[j][23]; + jsSensorData["zigbeeChannel"] = boost::lexical_cast(arrRes[j][24]); + jsSensorData["zigbeeAddr"] = arrRes[j][25]; + jsSensorData["zigbeeDesAddr"] = arrRes[j][27]; + jsSensorData["status"] = boost::lexical_cast(arrRes[j][28]); + jsSensorData["timeStamp"] = arrRes[j][29]; + jsArray.append(jsSensorData); + } + } else { + jsArray.resize(0); + jsonVal["success"] = false; + jsonVal["message"] = "查询失败"; + } + + Json::Value jsBody; + jsBody["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsBody["dataNodeArray"] = jsArray; + std::string dataBody = showValue.write(jsBody); + jsonVal["cmdBody"] = dataBody; + return showValue.write(jsonVal); + +} + + +std::string JsonData::JsonCmd_27(Json::Value & recvBody) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = ""; + jsonVal["cmd"] = "27"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + + int nSize = recvBody["dataNodeArray"].size(); + + if (nSize > 0) { + for (int i = 0; i < nSize; i++) { + char whereCon[128] = { 0 }; + sprintf(whereCon, "%s= '%s'", T_SENSOR_INFO(DATANODENO), recvBody["dataNodeArray"][i].asString().c_str()); + sql_ctl->DeleteTableData(T_SENSOR_INFO(TNAME), whereCon); + sql_ctl->DeleteTableData(T_DATA_INFO(TNAME), whereCon); + sql_ctl->DeleteTableData(T_DATASTATIC_INFO(TNAME), whereCon); + } + } else { + jsonVal["success"] = false; + jsonVal["message"] = "没有传感器号"; + } + return showValue.write(jsonVal); +} + + + +std::string JsonData::JsonCmd_29(Param_29 ¶m) +{ + Json::Value jsonVal; + Json::Value jsBody; + Json::Value SystemSetting; + jsonVal.clear(); + jsonVal["cmd"] = "29"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["cmdSerial"] = param.mCmdSerial; + + array_t arrRes; + arrRes = sql_ctl->GetDataMultiLine(T_SENSOR_INFO(TNAME), "*", NULL); + int iResult = arrRes.size(); + if (iResult > 0) { + for (int i = 0; i < iResult; i++) { + Json::Value jsDataNode; + jsDataNode["dataNodeNo"] = arrRes[i][1]; + jsDataNode["status"] = boost::lexical_cast(arrRes[i][24]); + jsBody["dataNodeArray"].append(jsDataNode); + } + } + + std::string strBody = showValue.write(jsBody); + jsonVal["cmdBody"] = strBody; + + return showValue.write(jsonVal); +} + + + +void JsonData::JsonCmd_38(Json::Value &recvBody) +{ + Json::Value jsChannel = recvBody["channelArray"]; + print_info("jsChannel size : %d\n", jsChannel.size()); + if (jsChannel.isArray()) { + for (int i = 0; i < jsChannel.size(); i++) { + std::string strChannelid = jsChannel[i].asString(); + WAVE_GENERAL wavedata; + + WAVE_CONTAIN wave; + memset(wave.channelId, 0, 16); + sprintf(wave.channelId, "%s", strChannelid.c_str()); + + memset(wave.SensorEngineeringUnit, 0, 32); + sprintf(wave.SensorEngineeringUnit,"%s", wavedata.SensorEngineeringUnit.c_str()); + + wave.total = 1; + wave.count = 1; + wave.type = 0; + wave.flag = 0; + wave.number = wavedata.number; + memcpy(wave.waveData, wavedata.waveData, wavedata.number * sizeof(float)); + // data_publish_wave(&wave, GlobalConfig::Topic_G.mPubSecond.c_str()); + } + } +} +void JsonData::JsonCmd_39(Json::Value &recvBody) +{ + std::ifstream inFile("/opt/update/a.bin",ios::in|ios::binary); + if (!inFile) { + print_error("read data error\n"); + } else { + + unsigned char szUpdatePackage[93]={0x00}; + while (inFile.read(szUpdatePackage, 92)) { + + } + } +} +void JsonData::DataNodeStatusCheck() +{ + vec_t vetRes = sql_ctl->GetDataMultiLineOfOneColumn(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(DATANODENO), NULL); + int nSize = vetRes.size(); + + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + int lNowTime = boost::lexical_cast(nowTimetamp); + + if (nSize > 0) { + for (int i = 0; i < nSize; i++) { + std::string strDataNodeNo = vetRes[i]; + std::string strChannelId= strDataNodeNo + "-X"; + char whereCon[64] = {}; + sprintf(whereCon, "dataNodeNo='%s' and channelID='%s'", strDataNodeNo.c_str(), strChannelId.c_str()); + array_t arrRes; + std::string strTimeRes = sql_ctl->GetData(T_DATA_INFO(TNAME), T_DATA_INFO(TIMESTAMP), whereCon); + if (strTimeRes.length() > 0) { + int llastTime = boost::lexical_cast(strTimeRes); + int lTimeTemp = lNowTime - llastTime; + lTimeTemp = abs(lTimeTemp); + if (lTimeTemp > 21600) { + char whereCon[32] = { 0 }; + sprintf(whereCon, "dataNodeNo='%s'", strDataNodeNo.c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), "status='0'", whereCon); + } + } + } + } + +} +/***************************嵌入式Web协议******************************/ + +std::string JsonData::JsonCmd_Cgi_01(Param_01 ¶m) +{ + Json::Value jsonVal; + Json::Value jsBody; + jsonVal.clear(); + std::string userName = ReadStrByOpt(SYSTEMINFOFILE, "UserInfo", "UserName"); + std::string adminPassword = ReadStrByOpt(SYSTEMINFOFILE, "UserInfo", "adminPassword"); + std::string userPassword = ReadStrByOpt(SYSTEMINFOFILE, "UserInfo", "userPassword"); + std::string message = " "; + bool success = true; + + if (0 == param.mMode) { + jsBody["type"] = "login"; + if (0 != param.mUserName.compare(userName)) { + message = "0101"; + success = false; + } else { + if (0 == param.mPassWord.compare(adminPassword) || 0 == param.mPassWord.compare(userPassword)) { + + } else { + message = "0102"; + success = false; + } + } + } else if (1 == param.mMode) { + jsBody["type"] = "upDate"; + if (0 != param.mUserName.compare(userName)) { + message = "0101"; + } else { + if (0 == param.mPassWord.compare(adminPassword) || 0 == param.mPassWord.compare(userPassword)) { + WriteStr2Config(SYSTEMINFOFILE, "UserInfo", "userPassword", param.mPassWordNew); + } else { + message = "0103"; + success = false; + } + } + } else { + message = "格式错误"; + success = false; + } + + jsonVal["cmd"] = "01"; + jsonVal["success"] = success; + jsonVal["message"] = message; + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_02(Param_02 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["success"] = true; + jsonVal["message"] = "校时成功"; + + jsonVal["cmd"] = "02"; + if (0 == param.mMode) { + jsonVal["type"] = "SET"; + SetTime((unsigned long)param.mTimeStamp); + boost::this_thread::sleep(boost::posix_time::milliseconds(200)); + system("hwclock -w"); + } else if (1 == param.mMode) { + char cmd[256] = { 0 }; + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + jsonVal["type"] = "GET"; + jsonVal["timeStamp"] = boost::lexical_cast(nowTimetamp); + } + return showValue.write(jsonVal); + +} + + +std::string JsonData::JsonCmd_Cgi_07() +{ + Json::Value jsonVal; + jsonVal.clear(); + std::string sysStatus = GetSysStatus(); + + print_info("sysStatus : %s\n", sysStatus.c_str()); + Json::Features f = Json::Features::strictMode(); + Json::Reader recvReader(f); + Json::Value recvSys; + jsonVal[JSON_FIELD_CMD] = "07"; + jsonVal["success"] = true; + jsonVal["message"] = " "; + if (recvReader.parse(sysStatus, recvSys)){ + jsonVal["content"] = recvSys; + } else { + jsonVal["success"] = false; + jsonVal["message"] = "状态获取失败"; + } + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_08() +{ + Json::Value jsonVal; + jsonVal.clear(); + std::string sysStatus = GetSysStatus(); + + Json::Features f = Json::Features::strictMode(); + Json::Reader recvReader(f); + Json::Value recvSys; + jsonVal[JSON_FIELD_CMD] = "08"; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_09() +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal[JSON_FIELD_CMD] = "09"; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + vec_t vetRes = sql_ctl->GetDataMultiLineOfOneColumn(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(DATANODENO), NULL); + int nSize = vetRes.size(); + + if (nSize > 0) { + for (int i = 0; i < nSize; i++) { + print_info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@vetRes=%s\n",vetRes[i].c_str()); + Json::Value jsSensor; + std::string strDataNodeNo = vetRes[i]; + char whereCon[64] = {}; + sprintf(whereCon, "dataNodeNo='%s'", strDataNodeNo.c_str()); + // 自数据库获取传感器特征数据 + array_t arrRes; + arrRes = sql_ctl->GetDataMultiLine(T_DATA_INFO(TNAME), "*", whereCon); + int iResult = arrRes.size(); + if (iResult > 0) { + for (int j = 0; j < iResult; j++) { + Json::Value jsChannelData; + jsChannelData["ChannelId"] = arrRes[j][1]; + jsChannelData["ChannelType"] = "ACCELEROMETER"; + jsChannelData["DiagnosisPeak"] = boost::lexical_cast(arrRes[j][2]); + jsChannelData["IntegratPk2Pk/2"] = boost::lexical_cast(arrRes[j][3]); + jsChannelData["IntegratRMS"] = boost::lexical_cast(arrRes[j][4]); + jsChannelData["RMSValues"] = boost::lexical_cast(arrRes[j][5]); + jsChannelData["EnvelopEnergy"] = boost::lexical_cast(arrRes[j][6]); + jsChannelData["1xAmp"] = boost::lexical_cast(arrRes[j][7]); + jsChannelData["2xAmp"] = boost::lexical_cast(arrRes[j][8]); + jsChannelData["3xAmp"] = boost::lexical_cast(arrRes[j][9]); + jsChannelData["4xAmp"] = boost::lexical_cast(arrRes[j][10]); + jsChannelData["5xAmp"] = boost::lexical_cast(arrRes[j][11]); + jsChannelData["1xPhase"] = boost::lexical_cast(arrRes[j][12]); + jsChannelData["2xPhase"] = boost::lexical_cast(arrRes[j][13]); + jsChannelData["3xPhase"] = boost::lexical_cast(arrRes[j][14]); + jsChannelData["4xPhase"] = boost::lexical_cast(arrRes[j][15]); + jsChannelData["TimeStamp"] = boost::lexical_cast(arrRes[j][16]); + jsSensor.append(jsChannelData); + } + } + + char selectCon[128] = { 0 }; + sprintf(selectCon, "dataNodeNo='%s'", strDataNodeNo.c_str()); + vec_t vecRes = sql_ctl->GetDataSingleLine(T_DATASTATIC_INFO(TNAME), "*", selectCon); + Json::Value jsStaticData; + if(vecRes.size()>0){ + jsStaticData["TemperatureTop"] = boost::lexical_cast(vecRes[2]); + jsStaticData["TemperatureBot"] = boost::lexical_cast(vecRes[3]); + jsStaticData["Dip"] = boost::lexical_cast(vecRes[4]); + jsStaticData["Voltage"] = boost::lexical_cast(vecRes[5]); + jsStaticData["ChannelType"] = "STATUS"; + jsStaticData["ChannelId"] = vecRes[1]; + jsStaticData["TimeStamp"] = vecRes[6]; + jsStaticData["dataNodeNo"] = strDataNodeNo; + } + + jsSensor.append(jsStaticData); + + jsonVal["content"].append(jsSensor); + } + } else { + jsonVal["content"].resize(0); + } + + return showValue.write(jsonVal); +} + + + + +std::string JsonData::JsonCmd_Cgi_20(Param_20 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + if (0 == param.mMode) { + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayName", param.mDataWatchName); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAssetId", param.mDataWatchAssetId); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy", param.mDataWatchAddedBy); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedDate", nowTimetamp); + } + + std::string boardtype = GetFileContent(BOARDTYPE, 1); + std::string ip = IpAddrInit(); + std::string sn = GetFileContent(SN, 1); + jsonVal[JSON_FIELD_CMD] = "20"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = ""; + jsonVal["cmdSerial"] = param.mCmdSerial; + + Json::Value jsSystemInfo; + Json::Value jsBody; + + jsSystemInfo[JSON_FIELD_NAME] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayName"); + jsSystemInfo["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsSystemInfo[JSON_FIELD_ASSETID] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAssetId"); + jsSystemInfo[JSON_FIELD_ADDEDBY] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy"); + jsSystemInfo[JSON_FIELD_ADDEDDATE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedDate"); + jsSystemInfo[JSON_FIELD_DEVICETYPE] = boardtype; + jsSystemInfo[JSON_FIELD_IPADDRESS] = ip; + jsSystemInfo[JSON_FIELD_SN] = sn; + jsSystemInfo[JSON_FIELD_VERSION] = GlobalConfig::Version; + jsSystemInfo[JSON_FIELD_TIMEZONE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "timezone"); + jsSystemInfo["zigbeePanId"] = GlobalConfig::ZigbeeInfo_G.PanID; + jsSystemInfo["zigbeeChannel"] = GlobalConfig::ZigbeeInfo_G.Channel; + jsSystemInfo["zigbeeAddr"] = GlobalConfig::ZigbeeInfo_G.MyAddr; + + jsBody["SystemInfo"] = jsSystemInfo; + + // std::string dataBody = showValue.write(jsBody); + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); +} + + +std::string JsonData::JsonCmd_Cgi_22(Param_22 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + + if (0 == param.mMode) { + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "timezone", param.mTimeZone); + } + + jsonVal[JSON_FIELD_CMD] = "22"; + jsonVal[JSON_FIELD_dataNodeGatewayNo] = GlobalConfig::MacAddr_G; + jsonVal["cmdSerial"] = param.mCmdSerial; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + Json::Value jsSystemSetting; + Json::Value jsBody; + jsSystemSetting[JSON_FIELD_TIMEZONE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "timezone"); + jsBody["SystemSettings"] = jsSystemSetting; + + jsonVal["content"] = jsBody; + + return showValue.write(jsonVal); +} + + +std::string JsonData::JsonCmd_Cgi_23(Param_23 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + // SET 指令,则param.mMode = 0,将设置的数据写入配置文件中 SERVERCONFIG "/opt/configenv/ServerConfig.json" + if (0 == param.mMode) { + WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", param.mServerIp); + WriteStr2Config(SERVERCONFIG, "Server", "localServerPort", param.mPort); + WriteStr2Config(SERVERCONFIG, "Server", "communicationMode", param.mCommMode); + } + + jsonVal[JSON_FIELD_CMD] = "23"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["cmdSerial"] = param.mCmdSerial; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + Json::Value jsSystemSetting; + Json::Value jsBody; + + jsSystemSetting["ServerIpAddress"] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress"); + jsSystemSetting["ServerPort"] = boost::lexical_cast(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort")); + jsSystemSetting["CommMode"] = boost::lexical_cast(ReadStrByOpt(SERVERCONFIG, "Server", "communicationMode")); + + jsBody["SystemSettings"] = jsSystemSetting; + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); +} + + + + +std::string JsonData::JsonCmd_Cgi_25(Param_25 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["cmd"] = "25"; + if (0 == param.mMode) { + WriteStr2Config(NETWORKCONFIG, "Net", "dnsName", param.mDnsName); + WriteStr2Config(NETWORKCONFIG, "Net", "networkPortStatus", param.mNetworkPortStatus); + WriteStr2Config(NETWORKCONFIG, "Net", "gateway", param.mGateway); + WriteStr2Config(NETWORKCONFIG, "Net", "subnetMask", param.mSubnetMask); + WriteStr2Config(NETWORKCONFIG, "Net", "ipAddress", param.mIp); + WriteStr2Config(NETWORKCONFIG, "Net", "hostName", param.mHostName); + platform->EquipIpInit(); + } + jsonVal["success"] = true; + jsonVal["message"] = " "; + jsonVal["content"]["dnsName"] = ReadStrByOpt(NETWORKCONFIG, "Net", "dnsName"); + jsonVal["content"]["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, "Net", "networkPortStatus"); + jsonVal["content"]["gateway"] = ReadStrByOpt(NETWORKCONFIG, "Net", "gateway"); + jsonVal["content"]["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, "Net", "subnetMask"); + jsonVal["content"]["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, "Net", "ipAddress"); + jsonVal["content"]["hostName"] = ReadStrByOpt(NETWORKCONFIG, "Net", "hostName"); + return showValue.write(jsonVal); +} + + +std::string JsonData::JsonCmd_Cgi_26() +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["cmd"] = "26"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + Json::Value jsArray; + array_t arrRes; + arrRes = sql_ctl->GetDataMultiLine(T_SENSOR_INFO(TNAME), "*", NULL); + int iResult = arrRes.size(); + if (iResult > 0) { + for (int j = 0; j < iResult; j++) { + Json::Value jsSensorData; + jsSensorData["dataNodeNo"] = arrRes[j][0]; + jsSensorData["dataNodeName"] = arrRes[j][1]; + jsSensorData["initFlag"] = boost::lexical_cast(arrRes[j][2]); + jsSensorData["accFlag"] = boost::lexical_cast(arrRes[j][3]); + jsSensorData["zigbeeFlag"] = boost::lexical_cast(arrRes[j][4]); + jsSensorData["temTopFlag"] = boost::lexical_cast(arrRes[j][5]); + jsSensorData["temBotFlag"] = boost::lexical_cast(arrRes[j][6]); + jsSensorData["equipsta"] = boost::lexical_cast(arrRes[j][7]); + jsSensorData["hardVersion"] = arrRes[j][8]; + jsSensorData["softVersion"] = arrRes[j][9]; + jsSensorData["bpNo"] = arrRes[j][10]; + jsSensorData["serialNo"] = arrRes[j][11]; + jsSensorData["firstPowerTime"] = arrRes[j][12]; + jsSensorData["configFlag"] = boost::lexical_cast(arrRes[j][13]); + jsSensorData["startBrands"] = arrRes[j][14]; + jsSensorData["stopBrands"] = arrRes[j][15]; + jsSensorData["featureInterVal"] = boost::lexical_cast(arrRes[j][16]); + jsSensorData["waveInterVal"] = boost::lexical_cast(arrRes[j][17]); + jsSensorData["samplingRate"] = boost::lexical_cast(arrRes[j][18]); + jsSensorData["scope"] = arrRes[j][19]; + jsSensorData["range"] = boost::lexical_cast(arrRes[j][20]);; + jsSensorData["envelopeBandPass"] = arrRes[j][21]; + jsSensorData["faultFrequency"] = arrRes[j][12]; + jsSensorData["zigbeePanId"] = arrRes[j][23]; + jsSensorData["zigbeeChannel"] = boost::lexical_cast(arrRes[j][24]); + jsSensorData["zigbeeAddr"] = arrRes[j][25]; + jsSensorData["zigbeeLongAddr"] = arrRes[j][26]; + jsSensorData["zigbeeDesAddr"] = arrRes[j][27]; + jsSensorData["status"] = boost::lexical_cast(arrRes[j][28]); + jsSensorData["timeStamp"] = arrRes[j][29]; + jsSensorData["viff"] = boost::lexical_cast(arrRes[j][30]); + jsSensorData["RSSI"] = boost::lexical_cast(arrRes[j][31]); + jsArray.append(jsSensorData); + } + } else { + jsArray.resize(0); + } + jsonVal["content"]["dataNodeArray"] = jsArray; + return showValue.write(jsonVal); +} + + +std::string JsonData::JsonCmd_Cgi_27(Param_27 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["cmd"] = "27"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + if (param.mDataNodeNo.length() > 0) { + char whereCon[128] = { 0 }; + sprintf(whereCon, "%s= '%s'", T_SENSOR_INFO(DATANODENO), param.mDataNodeNo.c_str()); + sql_ctl->DeleteTableData(T_SENSOR_INFO(TNAME), whereCon); + sql_ctl->DeleteTableData(T_DATA_INFO(TNAME), whereCon); + sql_ctl->DeleteTableData(T_DATASTATIC_INFO(TNAME), whereCon); + } else { + jsonVal["success"] = false; + jsonVal["message"] = "没有传感器号"; + } + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_28(Param_28 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["cmd"] = "28"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = ""; + + if (param.mDataNodeNo.length() > 0) { + char updateColumn[128] = { 0 }; + char whereCon[64] = { 0 }; + sprintf(whereCon, "dataNodeNo='%s'", param.mDataNodeNo.c_str()); + sprintf(updateColumn, "dataNodeName='%s'", param.mDataNodeName.c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateColumn, whereCon); + } else { + jsonVal["success"] = false; + jsonVal["message"] = "没有传感器号"; + } + return showValue.write(jsonVal); +} + + +std::string JsonData::JsonCmd_Cgi_29(Param_29 ¶m) +{ + Json::Value jsonVal; + Json::Value jsBody; + Json::Value SystemSetting; + jsonVal.clear(); + jsonVal["cmd"] = "29"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = " "; + std::string strWaveData = ""; + std::string filename = "/opt/data/" + param.mChannelId + ".dat"; + if (access(filename.c_str(), 0) >= 0) { + std::ifstream inFile(filename.c_str(),ios::in|ios::binary); + if (!inFile) { + print_error("read channel data error\n"); + jsonVal["success"] = false; + jsonVal["message"] = "error"; + } else { + float fTemp = 0; + std::vector vecWave; + while (inFile.read((char *)&fTemp, sizeof(fTemp))) { + vecWave.push_back(fTemp); + } + int flag = param.mPackageFlag; + flag = (flag + 1) * 1024; + int number = vecWave.size(); + int start = param.mPackageFlag * 1024; + if (number < 1024) { + flag = number; + start = 0; + } + char buf[32]; + for (int i = start; i < flag; i++) { + if ( i == start ) { + memset(buf, 0, 32); + sprintf(buf, "%.2f", vecWave[i]); + std::string waveTemp(buf); + strWaveData = waveTemp; + + } else { + memset(buf, 0, 32); + sprintf(buf, "%.2f", vecWave[i]); + std::string waveTemp(buf); + strWaveData = strWaveData + "," + waveTemp; + } + } + + int max = number / 1024; + if (max == 0 && number > 0) { + max = 1; + } + jsBody["packageMax"] = max; + } + + } else { + jsonVal["success"] = false; + jsonVal["message"] = "没有数据文件"; + } + + jsBody["channelId"] = param.mChannelId; + jsBody["package"] = param.mPackageFlag; + jsBody["Data"] = strWaveData; + + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); + +} + +std::string JsonData::JsonCmd_Cgi_30(Param_30 ¶m) +{ + /*Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["cmd"] = "30"; + jsonVal["success"] = true; + jsonVal["message"] = ""; + Json::Value jsBody; + std::string strWaveData; + // if (GlobalConfig::WaveCgi.flag == 1) { + // int number = GlobalConfig::WaveCgi.number; + // char buf[32]; + // int flag = param.mPackageFlag; + // flag = (flag + 1) * 1024; + // int start = param.mPackageFlag * 1024; + // if ( number < 1024) { + // flag = number; + // start = 0; + // } + + // for (int i = start; i < flag; i++) { + // if ( i == start ) { + // strWaveData = (boost::lexical_cast(GlobalConfig::WaveCgi.waveData[i])).substr(0.4); + // } else { + // memset(buf, 0, 32); + // sprintf(buf, "%.2f", GlobalConfig::WaveCgi.waveData[i]); + // std::string waveTemp(buf); + // strWaveData = strWaveData + "," + waveTemp; + // } + // } + // int max = number / 1024; + // if (max == 0 && number > 0) { + // max = 1; + // } + // jsBody["packageMax"] = max; + // } else { + // jsonVal["success"] = false; + // jsonVal["message"] = "数据获取失败"; + // } + + + jsBody["channelId"] = param.mChannelId; + jsBody["package"] = param.mPackageFlag; + jsBody["Data"] = strWaveData; + + jsonVal["content"] = jsBody; + return showValue.write(jsonVal);*/ + Json::Value jsonVal; + Json::Value jsBody; + Json::Value SystemSetting; + jsonVal.clear(); + + jsonVal["cmd"] = "30"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = ""; + int i = 0; + std::string strWaveData; + std::string filename = "/opt/data/" + param.mChannelId + ".dat"; + if (access(filename.c_str(), 0) >= 0) + { + std::ifstream inFile(filename.c_str(),ios::in|ios::binary); + if(!inFile) + { + print_error("read channel data error\n"); + jsonVal["success"] = "false"; + jsonVal["message"] = "error"; + }else{ + float fTemp = 0; + std::vector vecWave; + std::vector fftWave; + while(inFile.read((char *)&fTemp,sizeof(fTemp))) + { // 取8K进行计算 + if(i < 8192) + { + vecWave.push_back(fTemp); + }else{ + break; + } + i++; + } + /*std::string strWaveData1 = ""; + char buff[32] = {0}; + for(int j=0;j %s,vecWave.size()=%d\n", strWaveData1.c_str(),vecWave.size());*/ + //进行傅立叶变换 + pCalculation->FFTSpec(vecWave, fftWave); + printf("2---------------------------------------------->%d\n",fftWave.size()); + /*std::string strWaveData2 = ""; + char bufff[32] = {0}; + for(int k=0;kfftWave.size()=%d\n", fftWave.size()); + //print_info("after fft---------------------------------------------------> %s,fftWave.size()=%d\n", strWaveData2.c_str(),fftWave.size()); + int flag = param.mPackageFlag; + //print_info("*********************************param.mPackageFlag=%d\n",param.mPackageFlag); + flag = (flag + 1) * 1024; + int number = fftWave.size(); + int start = param.mPackageFlag * 1024; + if (number < 1024) + { + flag = number; + start = 0; + } + char buf[32] = {0}; + //print_info("start=%d,flag=%d\n",start,flag); + for (int i = start; i < flag; i++) + { + if (i == start) + { + memset(buf, 0, 32); + sprintf(buf, "%.2f", fftWave[i]); + std::string waveTemp(buf); + if (0 == i) + { + strWaveData = boost::lexical_cast(0); + }else{ + strWaveData = waveTemp; + } + }else{ + memset(buf, 0, 32); + sprintf(buf, "%.2f", fftWave[i]); + std::string waveTemp(buf); + strWaveData = strWaveData + "," + waveTemp; + } + } + //print_info("@strwavedata=%s@,strWaveData.sizeof=%d,fftWave.size()=%d\n",strWaveData.c_str(),strWaveData.size(),fftWave.size()); + int max = number / 1024; + //print_info("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&max=%d\n",max); + if (max == 0 && number > 0) + { + max = 1; + } + jsBody["packageMax"] = max; + } + } else { + jsonVal["success"] = false; + jsonVal["message"] = "数据获取失败"; + } + + + jsBody["channelId"] = param.mChannelId; + jsBody["package"] = param.mPackageFlag; + jsBody["Data"] = strWaveData; + /* 新增代码 */ + char whereCon[64] = {}; + sprintf(whereCon, "dataNodeNo='%s'",param.mDataNodeNo.c_str()); + std::string sample_rate = sql_ctl->GetData(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(SAMPLINGRATE), whereCon); + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%s\n",sample_rate.c_str()); + int SampleRate = boost::lexical_cast(sample_rate.c_str()); + double resolution = (double)SampleRate / 8192; + printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@the sample rate is %d,the resolution %f\n",SampleRate,resolution); + char buf[32]; + memset(buf, 0, 32); + sprintf(buf, "%f", resolution); + jsBody["resolution"] = std::string(buf); + + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_31(Param_31 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["cmd"] = "31"; + if(0 == param.mMode) + { + /*char buf[32]; + memset(buf, 0, 32); + sprintf(buf, "%d", param.mChannelId); + print_red("@@@@@@@@@@@@@@@@,,,,,%s\n",buf); + WriteStr2Config(ZIGBEECONFIG, "Zigbee", "channel", std::string(buf));*/ + WriteStr2Config(ZIGBEECONFIG, "Zigbee", "channel", param.mChannelId); + //pUart->ZigbeeInit(); + //pUart->UpdateZigbeeInfoCtrl(); + } + Json::Value jsBody; + jsonVal["message"] = "设置完成"; + jsonVal["success"] = true; + jsBody["channel"] = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "channel"); + jsBody["panID"] = GlobalConfig::ZigbeeInfo_G.PanID; + jsBody["status"] = "1"; + jsonVal["content"] = jsBody; + + return showValue.write(jsonVal); + + + +} + + + +std::string JsonData::JsonCmd_Cgi_32(Param_32 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["cmd"] = "32"; + jsonVal["success"] = true; + jsonVal["message"] = ""; + Json::Value jsBody; + std::string strWaveData; + // if (GlobalConfig::WaveFFtCgi.flag == 1) { + // int number = GlobalConfig::WaveFFtCgi.number; + // char buf[32]; + // int flag = param.mPackageFlag; + // flag = (flag + 1) * 1024; + // int start = param.mPackageFlag * 1024; + // if ( number < 1024) { + // flag = number; + // start = 0; + // } + // for (int i = start; i < flag; i++) { + // if ( i == start ) { + // strWaveData = (boost::lexical_cast(GlobalConfig::WaveFFtCgi.waveData[i])).substr(0.4); + // } else { + // memset(buf, 0, 32); + // sprintf(buf, "%.2f", GlobalConfig::WaveFFtCgi.waveData[i]); + // std::string waveTemp(buf); + // strWaveData = strWaveData + "," + waveTemp; + // } + // } + // int max = number / 1024; + // if (max == 0 && number > 0) { + // max = 1; + // } + // jsBody["packageMax"] = max; + // } else { + // jsonVal["success"] = false; + // jsonVal["message"] = "数据获取失败"; + // } + + + jsBody["channelId"] = param.mChannelId; + jsBody["package"] = param.mPackageFlag; + jsBody["Data"] = strWaveData; + + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); +} + + + + +std::string JsonData::JsonCmd_Cgi_43() +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = ""; + + // int flag = CheckNic("eth0"); + // Json::Value jsBody; + // if (0 == flag) { + // jsBody["status"] = 1; + // } else { + // jsBody["status"] = 0; + // } + // jsonVal["content"] = jsBody; + return showValue.write(jsonVal); +} + + + +std::string JsonData::JsonCmd_Cgi_default() +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = false; + jsonVal["message"] = "功能不支持"; + + return showValue.write(jsonVal); +} + + + +std::string JsonData::JsonCmd_Cgi_45(Param_45 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + if (0 == param.mMode) { + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + WriteStr2Config(SYSTEMINFOFILE, "Area", "countryId", param.mCountryId); + WriteStr2Config(SYSTEMINFOFILE, "Area", "provincesId", param.mProvincesId); + WriteStr2Config(SYSTEMINFOFILE, "Area", "cityListId", param.mCityListId); + } + + jsonVal[JSON_FIELD_CMD] = "45"; + jsonVal["success"] = true; + jsonVal["message"] = "区域配置成功"; + + Json::Value jsBody; + jsBody["countryId"] = ReadStrByOpt(SYSTEMINFOFILE, "Area", "countryId"); + jsBody["provincesId"] = ReadStrByOpt(SYSTEMINFOFILE, "Area", "provincesId"); + jsBody["cityListId"] = ReadStrByOpt(SYSTEMINFOFILE, "Area", "cityListId"); + + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_46(Param_46 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal[JSON_FIELD_CMD] = "46"; + jsonVal["success"] = true; + jsonVal["message"] = "升级失败"; + + std::string strFile = "/var/" + param.mFileName; + if (access(strFile.c_str(), 0) >= 0) { + std::string strCmd = "mv " + strFile + " /tmp/upgrade.tar.gz"; + system(strCmd.c_str()); + system("/etc/init.d/sysupgrade.sh"); + } else { + jsonVal["success"] = false; + jsonVal["message"] = "没有升级包"; + return showValue.write(jsonVal); + } + + return showValue.write(jsonVal); +} + + +std::string JsonData::JsonCmd_Cgi_47(Param_47 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal[JSON_FIELD_CMD] = "47"; + jsonVal["success"] = true; + jsonVal["message"] = "logo配置成功"; + + std::string strFile = "/var/" + param.mFileName; + if (access(strFile.c_str(), 0) >= 0) { + std::string strCmd = "mv " + strFile + " /var/www/html/static/media/logo.svg"; + system(strCmd.c_str()); + } else { + jsonVal["success"] = false; + jsonVal["message"] = "没有找到logo"; + return showValue.write(jsonVal); + } + + return showValue.write(jsonVal); +} + + diff --git a/jsonparse/SH_JsonCmd.hpp b/jsonparse/SH_JsonCmd.hpp new file mode 100644 index 0000000..0f8e04a --- /dev/null +++ b/jsonparse/SH_JsonCmd.hpp @@ -0,0 +1,116 @@ +#ifndef _JSONCMD_H_ +#define _JSONCMD_H_ +#include +#include +#include +#include +#include +#include +#include +#include "../common/SH_global.h" +#include "../common/SH_CommonFunc.hpp" +#include "../calculation/Calculation.hpp" +#include "../uart/SH_Uart.hpp" + + +class JsonData { +public : + void DataNodeStatusCheck(); + std::string JsonCmd_20(Param_20 ¶m); + // std::string JsonCmd_21(Param_21 ¶m); + std::string JsonCmd_22(Param_22 ¶m); //时区配置 + std::string JsonCmd_23(Param_23 ¶m); //服务器配置 + std::string JsonCmd_25(Param_25 ¶m); + std::string JsonCmd_26(Param_26 ¶m); + std::string JsonCmd_27(Json::Value & recvBody); + std::string JsonCmd_29(Param_29 ¶m); //系统配置信息 + void JsonCmd_38(Json::Value &recvBody); //获取原始数据 + void JsonCmd_39(Json::Value &recvBody); //更新传感器程序 + + // std::string JsonCmd_Cgi_error(); + std::string JsonCmd_Cgi_01(Param_01 ¶m); //用户操作处理 + std::string JsonCmd_Cgi_02(Param_02 ¶m); //时间校准接口 + std::string JsonCmd_Cgi_07(); //获取系统内存温度硬盘等信息 + std::string JsonCmd_Cgi_08(); //重启 + std::string JsonCmd_Cgi_09(); //实时数据获取 + std::string JsonCmd_Cgi_20(Param_20 ¶m); //终端信息获取 + std::string JsonCmd_Cgi_22(Param_22 ¶m); //时区配置 + std::string JsonCmd_Cgi_23(Param_23 ¶m); //服务器配置 + std::string JsonCmd_Cgi_25(Param_25 ¶m); //网口配置 + + std::string JsonCmd_Cgi_26(); + std::string JsonCmd_Cgi_27(Param_27 ¶m); + std::string JsonCmd_Cgi_28(Param_28 ¶m); + std::string JsonCmd_Cgi_29(Param_29 ¶m); //获取原始数据 + std::string JsonCmd_Cgi_30(Param_30 ¶m); //获取频域数据 + std::string JsonCmd_Cgi_31(Param_31 ¶m);//配置通信通道 + std::string JsonCmd_Cgi_32(Param_32 ¶m); // + std::string JsonCmd_Cgi_43(); //检测网口状态 + + std::string JsonCmd_Cgi_45(Param_45 ¶m); //国家区域配置 + std::string JsonCmd_Cgi_46(Param_46 ¶m); //升级固件 + std::string JsonCmd_Cgi_47(Param_47 ¶m); //替换Logo + std::string JsonCmd_Cgi_default(); + +private : + Json::FastWriter showValue; +}; + +//cmd "20" +static const char* JSON_FIELD_CMD = "cmd";//协议: 命令字段 +static const char* JSON_FIELD_NAME = "dataNodeGatewayName";//协议: 终端名称 +static const char* JSON_FIELD_dataNodeGatewayNo = "dataNodeGatewayNo"; +static const char* JSON_FIELD_ASSETID = "dataNodeGatewayAssetId";//协议: 资产编号 字段 +static const char* JSON_FIELD_ADDEDBY = "dataNodeGatewayAddedBy";//协议: 添加人 字段 +static const char* JSON_FIELD_DEVICETYPE = "deviceType"; +static const char* JSON_FIELD_ADDEDDATE = "dataNodeGatewayAddedDate"; +static const char* JSON_FIELD_IPADDRESS = "dataNodeGatewayIpAddress"; +static const char* JSON_FIELD_SN = "serialNumber"; +static const char* JSON_FIELD_VERSION = "softVersion"; +static const char* JSON_FIELD_TIMEZONE = "timezone"; + + + +//cmd "21" +// static const char* JSON_FIELD_CMD = "cmd";//协议: 命令字段 +// static const char* JSON_FIELD_NAME = "dataWatchName";//协议: 终端名称 +// static const char* JSON_FIELD_ASSETID = "dataWatchAssetId";//协议: 资产编号 字段 +// static const char* JSON_FIELD_ASSETID = "dataWatchAddedBy";//协议: 添加人 字段 + + +//cmd "23" +static const char* JSON_FIELD_SERVERIP = "localServerIpAddress"; +static const char* JSON_FIELD_SERVERPORT = "localServerPort"; +static const char* JSON_FIELD_CommMode = "CommMode"; +static const char* JSON_FIELD_SERVERSECOND = "writingPeriodLocalServer"; + +//cmd "24" +static const char* JSON_FIELD_FILESERVERIP = "fileServerIpAddress"; +static const char* JSON_FIELD_FILESERVERPORT = "fileServerPort"; + + +//cmd "25" + +// ps pl +// static const char* JSON_FIELD_FILESERVERIP = "fileServerIpAddress"; +// static const char* JSON_FIELD_FILESERVERPORT = "ServerPort"; +// static const char* JSON_FIELD_FILESERVERSECOND = "secondaryDataPath"; + + + +// static const char* JSON_FIELD_FILESERVERIP = "fileServerIpAddress"; +// static const char* JSON_FIELD_FILESERVERPORT = "ServerPort"; +// static const char* JSON_FIELD_FILESERVERSECOND = "secondaryDataPath"; + + +//cmd "26" +static const char* JSON_FIELD_EMAILSERVERIP = "ServerIpAddress"; +static const char* JSON_FIELD_PORT = "ServerPort"; +static const char* JSON_FIELD_FILESERVERSECOND = "secondaryDataPath"; + + +#define CMD_TYPE_20 20 +#define CMD_TYPE_21 21 +#define CMD_TYPE_22 22 + +#endif diff --git a/localserver/SH_LocalServer.cpp b/localserver/SH_LocalServer.cpp new file mode 100644 index 0000000..1fb049a --- /dev/null +++ b/localserver/SH_LocalServer.cpp @@ -0,0 +1,417 @@ +#include "SH_LocalServer.hpp" + +namespace { + PlatformInit *platform = PlatformInit::instance(); +} + +LocalServer::LocalServer() +{ + +} + +LocalServer::~LocalServer() +{ + print_info("~LocalServer is called!\n"); +} + +void LocalServer::HandleFromServer(const char *pData_r, int pLen, const char *topic) +{ + if(pLen == 0) { + return; + } + + std::string data_r = (std::string)(pData_r); + print_brown("pData base : %s \n", data_r.c_str()); + char *base64_data = new char[data_r.length()]; + memset(base64_data, 0, data_r.length()); + Secure::instance()->Base64Decode(data_r.c_str(), (unsigned char*)base64_data); + std::string pData = std::string(base64_data); + delete[] base64_data; + + print_brown("pData : %s \n", pData.c_str()); + Json::Reader recvReader; + Json::Value recvValue; + Json::Value recvBody; + if (recvReader.parse(pData, recvValue)) { + /* std::string cmdBody = recvValue["cmdBody"].asString(); + if (!recvReader.parse(cmdBody, recvBody)) { + print_error("recv body error"); + return; + }*/ + recvBody = recvValue["cmdBody"]; + std::string str = recvBody["timestamp"].asString(); + int cmdType = atoi(recvValue["cmd"].asString().c_str()); + switch (cmdType) { + case 10:{ + recvValue["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + recvValue["status"] = "ACK"; + Json::FastWriter fw; + std::string strjson = fw.write(recvValue); + data_publish(strjson.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + system("echo 1 > /CIDW/start"); + boost::this_thread::sleep(boost::posix_time::seconds(1)); + system("reboot"); + } + break; + case 12:{ + /* std::string strBody = recvValue["cmdBody"].asString(); + Json::Value jsBody; + if (!recvReader.parse(strBody, jsBody)) { + return; + }*/ + std::string timestamp = recvBody["timestamp"].asString(); + unsigned long itimestamp = boost::lexical_cast(timestamp); + SetTime(itimestamp); + boost::this_thread::sleep(boost::posix_time::milliseconds(200)); + system("hwclock -w"); + if (!recvValue["ZoneId"].isNull() && recvValue["ZoneId"].asString().length() > 0) { + std::string zoneid = recvValue["ZoneId"].asString(); + ZoneConfig(zoneid); + } + Json::Value retVal; + retVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + retVal["cmd"] = 12; + retVal["success"] = true; + retVal["message"] = "校时成功"; + Json::FastWriter fw; + std::string strjson = fw.write(retVal); + data_publish(strjson.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + } + break; + case 13:{ + std::string type = recvValue["type"].asString(); + if (type.compare("delete") == 0) { + WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", "0.0.0.0"); + GlobalConfig::ServerIP.clear(); + exit(0); + } + } + break; + case 20:{ + Param_20 param; + param.mCmdSerial = recvValue["cmdSerial"].asString(); + std::string type = recvBody["type"].asString(); + if (0 == type.compare("SET")) { + param.mMode = 0; + param.mDataWatchName = recvBody["SystemInfo"]["dataNodeGatewayName"].asString(); + param.mDataWatchAssetId = recvBody["SystemInfo"]["dataNodeGatewayAssetId"].asString(); + param.mDataWatchAddedBy = recvBody["SystemInfo"]["dataNodeGatewayAddedBy"].asString(); + } else { + param.mMode = 1; + } + JsonData jd; + std::string data = jd.JsonCmd_20(param); + print_info("20 data: %s\n", data.c_str()); + data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + } + break; + case 22:{ + Param_22 param; + std::string type = recvBody["type"].asString(); + param.mCmdSerial = recvValue["cmdSerial"].asString(); + + if (0 == type.compare("SET")) { + param.mMode = 0; + param.mTimeZone = recvBody["timezone"].asString(); + ZoneConfig(param.mTimeZone); + } else { + param.mMode = 1; + } + JsonData jd; + std::string data = jd.JsonCmd_22(param); + data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + } + break; + case 23:{ + std::string type = recvBody["type"].asString(); + Param_23 param; + param.mCmdSerial = recvValue["cmdSerial"].asString(); + if (0 == type.compare("SET")) { + param.mMode = 0; + param.mServerIp = recvBody["localServerIpAddress"].asString(); + param.mPort = boost::lexical_cast(recvBody["localServerPort"].asInt()); + param.mCommMode = boost::lexical_cast(recvBody["CommMode"].asInt()); + } else { + param.mMode = 1; + } + JsonData jd; + std::string data = jd.JsonCmd_23(param); + data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + } + break; + case 25:{ + Param_25 param; + param.mCmdSerial = recvValue["cmdSerial"].asString(); + std::string type = recvBody["type"].asString(); + if (0 == type.compare("SET")) { + param.mDnsName = recvBody["dnsName"].asString(); + param.mGateway = recvBody["gateway"].asString(); + param.mHostName = recvBody["hostName"].asString(); + param.mIp = recvBody["dataWatchIpAddress"].asString(); + param.mSubnetMask = recvBody["subnetMask"].asString(); + param.mNetworkPortStatus = recvBody["networkPortStatus"].asString(); + param.mMode = 0; + } else { + param.mMode = 1; + } + JsonData jd; + std::string data = jd.JsonCmd_25(param); + data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + // platform->EquipIpInit(); + } + break; + case 26:{ + Param_26 param; + param.mCmdSerial = recvValue["cmdSerial"].asString(); + std::string type = recvBody["type"].asString(); + if (0 == type.compare("GET")) { + param.mMode = 0; + } else { + param.mMode = 1; + } + JsonData jd; + std::string data = jd.JsonCmd_26(param); + data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + // platform->EquipIpInit(); + } + break; + case 27:{ + Param_27 param; + param.mCmdSerial = recvValue["cmdSerial"].asString(); + + JsonData jd; + std::string data = jd.JsonCmd_27(recvBody); + data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + } + break; + default: + // data_publish_local(pData.c_str(), GlobalConfig::Topic_G.mPubLocalCmd.c_str()); + break; + } + print_brown("cmdType : %d \n", cmdType); + + } else { + print_error("parase fail \n"); + } + +} + +std::string LocalServer::HandleCgi_cmd(std::string &pData) +{ +try{ + print_purple("HandleCgi Data = %s \n", pData.c_str()); + Json::Features f = Json::Features::strictMode(); + Json::Reader recvReader(f); + Json::Value recvValue; + Json::Value recvBody; + if (recvReader.parse(pData, recvValue)){ + int cmdType = atoi(recvValue["cmd"].asString().c_str()); + std::string cmdBody = ""; + if (!recvValue["cmdBody"].isNull() ) { + recvBody = recvValue["cmdBody"]; + Json::FastWriter fw; + cmdBody = fw.write(recvBody); + } + switch (cmdType) { + case 1:{ + Param_01 param; + std::string type = recvBody["type"].asString(); + if ( 0 == type.compare("login")) { + param.mMode = 0; + param.mUserName = recvBody["userName"].asString(); + param.mPassWord = recvBody["passWord"].asString(); + } else if ( 0 == type.compare("upDate")) { + param.mMode = 1; + param.mUserName = recvBody["userName"].asString(); + param.mPassWord = recvBody["passWord"].asString(); + param.mPassWordNew = recvBody["passWordNew"].asString(); + } + JsonData jd; + std::string data = jd.JsonCmd_Cgi_01(param); + return data; + } + break; + case 2:{ + Param_02 param; + std::string type = recvBody["type"].asString(); + if ( 0 == type.compare("SET")) { + param.mMode = 0; + param.mTimeStamp = recvBody["timeStamp"].asInt(); + } else if (0 == type.compare("GET")) { + param.mMode = 1; + } + JsonData jd; + std::string data = jd.JsonCmd_Cgi_02(param); + return data; + } + break; + case 7:{ + JsonData jd; + std::string data = jd.JsonCmd_Cgi_07(); + return data; + } + break; + case 8:{ + JsonData jd; + std::string data = jd.JsonCmd_Cgi_08(); + system("reboot"); + return data; + } + break; + case 9:{ + JsonData jd; + std::string data = jd.JsonCmd_Cgi_09(); + return data; + } + break; + case 20:{ + Param_20 param; + std::string type = recvBody["type"].asString(); + if (0 == type.compare("SET")) { + param.mMode = 0; + param.mDataWatchName = recvBody["SystemInfo"]["dataNodeGatewayName"].asString(); + param.mDataWatchAssetId = recvBody["SystemInfo"]["dataNodeGatewayAssetId"].asString(); + param.mDataWatchAddedBy = recvBody["SystemInfo"]["dataNodeGatewayAddedBy"].asString(); + } else { + param.mMode = 1; + } + JsonData jd; + std::string data = jd.JsonCmd_Cgi_20(param); + return data; + } + break; + case 22:{ + Param_22 param; + std::string type = recvBody["type"].asString(); + param.mCmdSerial = recvValue["cmdSerial"].asString(); + + if (0 == type.compare("SET")) { + param.mMode = 0; + param.mTimeZone = recvBody["SystemSettings"]["timezone"].asString(); + ZoneConfig(param.mTimeZone); + } else { + param.mMode = 1; + } + JsonData jd; + std::string data = jd.JsonCmd_Cgi_22(param); + return data; + } + break; + case 23:{ + std::string type = recvBody["type"].asString(); + Param_23 param; + param.mCmdSerial = recvValue["cmdSerial"].asString(); + if (0 == type.compare("SET")) { + param.mMode = 0; + param.mServerIp = recvBody["SystemSettings"]["ServerIpAddress"].asString(); + param.mPort = boost::lexical_cast(recvBody["SystemSettings"]["ServerPort"].asInt()); + param.mCommMode = boost::lexical_cast(recvBody["SystemSettings"]["CommMode"].asInt()); + } else { + param.mMode = 1; + } + JsonData jd; + std::string data = jd.JsonCmd_Cgi_23(param); + return data; + } + break; + case 25:{ + Param_25 param; + std::string type = recvBody["type"].asString(); + if (0 == type.compare("SET")) { + param.mDnsName = recvBody["dnsName"].asString(); + param.mGateway = recvBody["gateway"].asString(); + param.mHostName = recvBody["hostName"].asString(); + param.mIp = recvBody["dataWatchIpAddress"].asString(); + param.mSubnetMask = recvBody["subnetMask"].asString(); + param.mNetworkPortStatus = recvBody["networkPortStatus"].asString(); + param.mMode = 0; + }else{ + param.mMode = 1; + } + JsonData jd; + std::string data = jd.JsonCmd_Cgi_25(param); + //platform->EquipIpInit(); + return data; + } + break; + case 26:{ + JsonData jd; + std::string data = jd.JsonCmd_Cgi_26(); + return data; + } + break; + case 27:{ + Param_27 param; + param.mDataNodeNo = recvBody["dataNodeNo"].asString(); + JsonData jd; + std::string data = jd.JsonCmd_Cgi_27(param); + return data; + } + break; + case 28:{ + Param_28 param; + param.mDataNodeNo = recvBody["dataNodeNo"].asString(); + param.mDataNodeName = recvBody["dataNodeName"].asString(); + JsonData jd; + std::string data = jd.JsonCmd_Cgi_28(param); + return data; + } + break; + case 29:{ + JsonData jd; + Param_29 param; + param.mChannelId = recvBody["channelId"].asString(); + param.mPackageFlag = recvBody["package"].asInt(); + param.mDataNodeNo = recvBody["dataNodeNo"].asString(); + std::string data = jd.JsonCmd_Cgi_29(param); + return data; + } + break; + case 30:{ + JsonData jd; + Param_30 param; + param.mChannelId = recvBody["channelId"].asString(); + param.mPackageFlag = recvBody["package"].asInt(); + param.mDataNodeNo = recvBody["dataNodeNo"].asString(); + std::string data = jd.JsonCmd_Cgi_30(param); + return data; + } + break; + case 31:{ + JsonData jd; + Param_31 param; + std::string data; + std::string type = recvBody["type"].asString(); + if(0 == type.compare("SET")) + { + param.mMode = 0; + param.mChannelId = recvBody["channel"].asString(); + //param.mChannelId = recvBody["channel"].asInt(); + data = jd.JsonCmd_Cgi_31(param); + sleep(1); + system("reboot"); + + }else{ + param.mMode = 1; + data = jd.JsonCmd_Cgi_31(param); + } + // std::string data = jd.JsonCmd_Cgi_31(param); + return data; + } + break; + default: + JsonData jd; + std::string data = jd.JsonCmd_Cgi_default(); + return data; + break; + } + } +} catch(...){ + Json::Value jsVal; + jsVal["success"] = false; + jsVal["message"] = "未知错误"; + Json::FastWriter fw; + return fw.write(jsVal); +} +} + diff --git a/localserver/SH_LocalServer.hpp b/localserver/SH_LocalServer.hpp new file mode 100644 index 0000000..3d1b517 --- /dev/null +++ b/localserver/SH_LocalServer.hpp @@ -0,0 +1,30 @@ +#ifndef _LOCALSERVER_H_ +#define _LOCALSERVER_H_ +#include +#include +#include +#include +#include +#include +#include +#include "../utility/SH_MySingleton.hpp" +#include "../common/SH_global.h" +#include "../platform/SH_PlatformInit.hpp" +#include "../secure/SH_Secure.hpp" +#include "../jsonparse/SH_JsonCmd.hpp" + + +class LocalServer : public MySingleton +{ +private: + boost::mutex mMutex; + // _Event mWaveEvent; + std::vector m_VecFileName; +public: + LocalServer(); + virtual ~LocalServer(); + void HandleFromServer(const char *pData, int pLen, const char *topic); + std::string HandleCgi_cmd(std::string &pData); + +}; +#endif \ No newline at end of file diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..5d6297c --- /dev/null +++ b/main.cpp @@ -0,0 +1,97 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "platform/SH_PlatformInit.hpp" +#include "common/SH_CommonFunc.hpp" +#include "API_log/SH_log.h" +#include "common/SH_global.h" +#include "threadfunc/SH_ThreadFunc.hpp" +#include "secure/SH_Secure.hpp" +#include "aes/aes.h" +#include "dbaccess/SH_SqlDB.hpp" +#include "uart/SH_Uart.hpp" + +namespace{ + PlatformInit *platform = PlatformInit::instance(); + Uart *pUart = Uart::instance(); +} + + +int main(int argc, char *argv[]) +{ + // 初始化日志记录,日志缓存区,记录数,未使用,后期,命令启动 + log_init(SOFTWARE_RUN_LOG, 1380, 160 * 1024); + LOG_INFO("####CIDNSOFT start####\n"); + + // 查看版本信息 + if (CheckFileVersion(argc, argv)) { + return 0; + } + + // 设置线程属性之栈空间大小 + boost::thread::attributes attrs; + attrs.set_stack_size(1024*1024*2); + + // 初始化平台配置文件 + platform->PlatFormInit(); + + // UDP,接收客户端发来的组播消息,用于外接 QT 专家系统,屏蔽之 + boost::thread searchT(attrs,SearchThread); + searchT.detach(); + + // 串口处理线程,用于与 ZigBee 模块通信,通过ZigBee无线通信技术与无线传感器通信 + boost::thread uartReadTh(UartStart); + uartReadTh.detach(); + + // 休眠2秒,等待串口线程初始化完毕 + boost::this_thread::sleep(boost::posix_time::seconds(2)); + + // 串口数据处理,读取传感器原始波形数据 + boost::thread uartWaveReadTh(UartStartWave); + uartWaveReadTh.detach(); + + //启动 mqtt客户端 + boost::thread startMqtt(StartMqttClient); + startMqtt.detach(); + + //启动 mqtt 心跳 + boost::thread startHeart(HeartRep); + startHeart.detach(); + + // 通过UDP接收数据 + boost::thread StartConnectSys(attrs, StartUdpSys); + StartConnectSys.detach(); + + //循环检测线程 + boost::thread normalCheckThread(attrs,CheckThread); + normalCheckThread.detach(); + + //启动软件升级线程 + boost::thread StartDownloadThread(attrs, RecvUpdateFile); + StartDownloadThread.detach(); + + //启动cgi server + boost::thread startTcpCgi(attrs,StartCgiServer); + startTcpCgi.detach(); + + //pUart->UpdateZigbeeInfoCtrl(); + pUart->ZigbeeInit(); + pUart->UpdateZigbeeInfoCtrl(); + boost::this_thread::sleep(boost::posix_time::seconds(5)); + + while (GlobalConfig::QuitFlag_G) { + boost::this_thread::sleep(boost::posix_time::seconds(20)); + // data_publish(senddata.c_str(), GlobalConfig::Topic_G.mPubData.c_str()); + + } + return 0; +} + + diff --git a/mqttclient/SH_MqttClient.cpp b/mqttclient/SH_MqttClient.cpp new file mode 100644 index 0000000..6735cb8 --- /dev/null +++ b/mqttclient/SH_MqttClient.cpp @@ -0,0 +1,347 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include "SH_MqttClient.h" +#include "../common/SH_global.h" +#include "../secure/SH_Secure.hpp" + +static char res_topic[100]; +static char req_topic[100]; +struct mosquitto *mosq = NULL; +static int mid_sent = 0; +struct userdata ud; +connect_callback my_connect_callback = NULL; +disconnect_callback my_disconnect_callback = NULL; +message_callback my_message_callback = NULL; +subscribe_callback my_subscribe_callback = NULL; +log_callback my_log_callback = NULL; +publish_callback my_publish_callback = NULL; + + +void register_collback(connect_callback connect_c, + message_callback message_c, + subscribe_callback subscribe_c, + log_callback log_c, + disconnect_callback disconnect_c, + publish_callback publish_c) +{ + my_connect_callback = connect_c; + my_message_callback = message_c; + my_subscribe_callback = subscribe_c; + my_log_callback = log_c; + my_disconnect_callback = disconnect_c; + my_publish_callback = publish_c; +} + +int data_publish(const char *str, const char *topic) +{ + int iRet = -1; + if(mosq != NULL){ + print_blue("data_publish: %s %s\n", str, topic); + std::string strTopic = std::string(topic); + if (strTopic.find("cmd") != std::string::npos) { + std::string pData = (std::string)str; + char *base64_aes = new char[pData.length() * 2]; + memset(base64_aes, 0, pData.length() * 2); + Secure::instance()->Base64Encode((unsigned char*)pData.c_str(), base64_aes, pData.length()); + iRet = mosquitto_publish(mosq, &mid_sent, topic, strlen(base64_aes), base64_aes, ud.topic_qos, false); + print_blue("data_publish: %s \n",base64_aes); + // free(out); + } else { + iRet = mosquitto_publish(mosq, &mid_sent, topic, strlen(str), str, ud.topic_qos, false); + } + + } + return iRet; +} + +int data_publish_wave(WAVE_CONTAIN *str, const char *topic) +{ + int iRet = -1; + if(mosq != NULL){ + print_blue("data_publish:Unit : %s type:%d flag : %d channelid : %s total : %d count : %d number :%d floats:%f floate:%f\n",str->SensorEngineeringUnit, str->type, str->flag, str->channelId, str->total, str->count,str->number,str->waveData[0],str->waveData[(str->number-2)]); + iRet = mosquitto_publish(mosq, &mid_sent, topic, sizeof(WAVE_CONTAIN), str, ud.topic_qos, false); + } + return iRet; +} + +int subscribe(const char* topic, int qos) +{ + int iret = mosquitto_subscribe(mosq, NULL, topic, qos); + return iret; +} + +int unsubscribe(const char* topic) +{ + int iret = mosquitto_unsubscribe(mosq, NULL, topic); + return iret; +} + +int disconnect() +{ + return mosquitto_disconnect(mosq); +} + +int start_client(const char *boardname, const char *gwid, const char* gwip, const char *gwver, const char *gwcode, std::string &salt) +{ + char *id = NULL; + char *id_prefix = NULL; + char *host; + int port = 51613; + char *bind_address = NULL; + int keepalive = 60; + bool clean_session = true; + bool debug = true; + int rc = 0; + char hostname[256]; + char err[1024]; + int len; + char will_payload[100]; + long will_payloadlen = 0; + int will_qos = 0; + bool will_retain = false; + char *will_topic = NULL; + bool insecure = false; + char *tls_version = NULL; + char *psk = NULL; + char *psk_identity = NULL; + char *ciphers = NULL; + bool use_srv = false; + mqttsdata_t mqttsdata; + signal(SIGCHLD, SIG_IGN);//signal函数作用:为一个信号注册一个信号处理函数。其中SIGCHLD:在一个进程终止或者停止时,将SIGCHLD信号发送给父进程。而信号处理函数是一个函数指针,不过它使用的是预定义函数SIG_IGN(忽视信号) + signal(SIGPIPE, SIG_IGN); + int reconnect = 0; + if (my_connect_callback == NULL || my_message_callback == NULL || my_subscribe_callback == NULL || my_log_callback == NULL) { + printf("please call the register_collback function first.\n"); + return -1; + } + + + mosquitto_lib_init();//使用mosquitto库函数前需进行初始化 + memset(&mqttsdata, 0, sizeof(mqttsdata_t)); + memcpy(mqttsdata.gwid, gwid, strlen(gwid)); + + // mqttsdata.username = "admin"; + // mqttsdata.password = "password"; + salt = std::string(mqttsdata.salt); + memset(&ud, 0, sizeof(struct userdata)); + ud.eol = true; + char localip[100]; + sprintf(localip, "%s", gwip); + host = localip; + mqttsdata.port = GlobalConfig::ServerPort; + port = GlobalConfig::ServerPort; + + // std::string username = "root"; + // std::string password = "xom!*283#@XHG"; + + std::string username = "chaos"; + std::string password = "HSD272*#xkd"; + + char userName[100]; + sprintf(userName, "%s", username.c_str()); + + char passWord[100]; + sprintf(passWord, "%s", password.c_str()); + + ud.username = userName; + ud.password = passWord; + + ud.gwid = mqttsdata.gwid; + ud.dataUrl = mqttsdata.dataUrl; + ud.fsUrl = mqttsdata.fsUrl; + will_qos = mqttsdata.qos; + ud.topic_count++; + ud.topics = (char**)realloc(ud.topics, ud.topic_count*sizeof(char *)); + if (ud.topics == NULL) { + return 1; + } + + memset(req_topic, 0, 100); + sprintf(req_topic, "dev/cidwcc"); + ud.topics[ud.topic_count - 1] = req_topic; + ud.verbose = 1; + fprintf(stderr, "topic = %s!!!!!!!!!!!\n", ud.topics[ud.topic_count - 1]); + memset(res_topic, 0, 100); + sprintf(res_topic, "gw/will"); + printf("res_topic:%s\n", res_topic); + will_topic = res_topic; + ud.resp_topic = res_topic; + sprintf(will_payload, "{\"cmd\":\"15\",\"gwID\":\"%s\"}", mqttsdata.gwid); + will_payloadlen = strlen(will_payload); + printf("will_payload:%s,will_payloadlen:%ld\n", will_payload, will_payloadlen); + if (clean_session == false && (id_prefix || !id)){ + if (!ud.quiet) fprintf(stderr, "Error: You must provide a client id if you are using the -c option.\n"); + return 1; + } + + if (ud.topic_count == 0){ + fprintf(stderr, "Error: You must specify a topic to subscribe to.\n"); + return 1; + } + if (will_payload && !will_topic){ + fprintf(stderr, "Error: Will payload given, but no will topic given.\n"); + return 1; + } + if (will_retain && !will_topic){ + fprintf(stderr, "Error: Will retain given, but no will topic given.\n"); + return 1; + } + if (ud.password && !ud.username){ + if (!ud.quiet) fprintf(stderr, "Warning: Not using password since username not set.\n"); + } + if (psk && !psk_identity){ + if (!ud.quiet) fprintf(stderr, "Error: --psk-identity required if --psk used.\n"); + return 1; + } + if (id_prefix){ + id = (char*)malloc(strlen(id_prefix) + 10); + if (!id){ + if (!ud.quiet) fprintf(stderr, "Error: Out of memory.\n"); + mosquitto_lib_cleanup(); + return 1; + } + snprintf(id, strlen(id_prefix) + 10, "%s%d", id_prefix, getpid()); + } else if (!id){ + hostname[0] = '\0'; + gethostname(hostname, 256); + hostname[255] = '\0'; + len = strlen("mosqsub/-") + 6 + strlen(hostname); + id = (char*)malloc(len); + if (!id){ + if (!ud.quiet) fprintf(stderr, "Error: Out of memory.\n"); + mosquitto_lib_cleanup(); + return 1; + } + snprintf(id, len, "mosqsub/%d-%s", getpid(), hostname); + if (strlen(id) > MOSQ_MQTT_ID_MAX_LENGTH){ + /* Enforce maximum client id length of 23 characters */ + id[MOSQ_MQTT_ID_MAX_LENGTH] = '\0'; + } + } + printf("id:%s\n", id); + mosq = mosquitto_new(id, clean_session, &ud); + if (!mosq){ + switch (errno){ + case ENOMEM: + if (!ud.quiet) fprintf(stderr, "Error: Out of memory.\n"); + break; + case EINVAL: + if (!ud.quiet) fprintf(stderr, "Error: Invalid id and/or clean_session .\n"); + break; + } + mosquitto_lib_cleanup(); + return 1; + } + if (debug){ + mosquitto_log_callback_set(mosq, my_log_callback); + } + + if (!psk) { + psk = (char *)malloc(32 * sizeof(char)); + if (!psk) { + fprintf(stderr, "Error: No free space %d\n", __LINE__); + return -1; + } + memset(psk, 0, 32); + snprintf(psk, 32, "%ld", getpid()); + psk_identity = (char *)malloc(32 * sizeof(char)); + if (!psk_identity) { + fprintf(stderr, "Error: No free space %d\n", __LINE__); + free(psk); + return -1; + } + strncpy(psk_identity, psk, 32); + } + if (will_topic && mosquitto_will_set(mosq, will_topic, will_payloadlen, will_payload, will_qos, will_retain)) { + if (!ud.quiet) fprintf(stderr, "Error: Problem setting will.\n"); + mosquitto_lib_cleanup(); + free(psk); + free(psk_identity); + return 1; + } + + if (ud.username && mosquitto_username_pw_set(mosq, ud.username, ud.password)) { + if (!ud.quiet) fprintf(stderr, "Error: Problem setting username and password.\n"); + mosquitto_lib_cleanup(); + free(psk); + free(psk_identity); + return 1; + } + + // if (insecure && mosquitto_tls_insecure_set(mosq, false)){ + // if (!ud.quiet) fprintf(stderr, "Error: Problem setting TLS insecure option.\n"); + // mosquitto_lib_cleanup(); + // free(psk); + // free(psk_identity); + // return 1; + // } + + // if (psk && mosquitto_tls_psk_set(mosq, psk, psk_identity, NULL)){ + // if (!ud.quiet) fprintf(stderr, "Error: Problem setting TLS-PSK options.\n"); + // mosquitto_lib_cleanup(); + // return 1; + // } + + // if (tls_version && mosquitto_tls_opts_set(mosq, 0, tls_version, ciphers)){ + // if (!ud.quiet) fprintf(stderr, "Error: Problem setting TLS options.\n"); + // mosquitto_lib_cleanup(); + // return 1; + // } + + + mosquitto_connect_callback_set(mosq, my_connect_callback); + mosquitto_disconnect_callback_set(mosq, my_disconnect_callback); + mosquitto_message_callback_set(mosq, my_message_callback); + mosquitto_publish_callback_set(mosq, my_publish_callback); + + if (debug){ + mosquitto_subscribe_callback_set(mosq, my_subscribe_callback); + } + + if (use_srv){ + rc = mosquitto_connect_srv(mosq, host, keepalive, bind_address); + } + else{ + rc = mosquitto_connect_bind(mosq, host, port, keepalive, bind_address); + } + if (rc){ + if (!ud.quiet){ + if (rc == MOSQ_ERR_ERRNO){ + strerror_r(errno, err, 1024); + fprintf(stderr, "Error_: %s\n", err); + } + else{ + fprintf(stderr, "Unable to connect (%d).\n", rc); + } + } + goto mosq_free; + } + rc = mosquitto_loop_forever(mosq, -1, 1); + if (rc) + { + fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc)); + } +mosq_free: + mosquitto_destroy(mosq); + mosquitto_lib_cleanup(); + free(ud.topics); + free(id); + free(psk); + free(psk_identity); + ud.topics = NULL; + id = NULL; + mosq = NULL; + sleep(1); +} diff --git a/mqttclient/SH_MqttClient.h b/mqttclient/SH_MqttClient.h new file mode 100644 index 0000000..89cb9aa --- /dev/null +++ b/mqttclient/SH_MqttClient.h @@ -0,0 +1,70 @@ +#ifndef MQTTCLIENT_H +#define MQTTCLIENT_H + +#include "../common/SH_CommonFunc.hpp" +#ifdef __cplusplus +extern "C" { +#endif +#include "mosquitto.h" + + +struct userdata { + char **topics; + int topic_count; + int topic_qos; + char **filter_outs; + int filter_out_count; + char *username; + char *password; + char *resp_topic; + char *gwid; + char *dataUrl; + char *fsUrl; + int verbose; + bool quiet; + bool no_retain; + bool eol; +}; + +typedef struct mqttsinfo +{ + char domain[100]; + char devicekey[36]; + char gwid[21]; + int port; + char username[100]; + char password[100]; + char dataUrl[100]; + char fsUrl[100]; + char salt[100]; + int ssl; + int qos; + int encrypt; +}mqttsdata_t; + +extern struct userdata ud; +typedef void(*connect_callback)(struct mosquitto *mosq, void *obj, int result); +typedef void(*disconnect_callback)(struct mosquitto *mosq, void *obj, int result); +typedef void(*message_callback)(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message); +typedef void(*subscribe_callback)(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos); +typedef void(*log_callback)(struct mosquitto *mosq, void *obj, int level, const char *str); +typedef void(*publish_callback)(struct mosquitto *mosq, void *obj, int mid); + + +//mqtt注册 +extern void register_collback(connect_callback connect_c, + message_callback message_c, + subscribe_callback subscribe_c, + log_callback log_c, + disconnect_callback disconnect_c, + publish_callback publish_c); +extern int data_publish(const char *str, const char* topic); +extern int data_publish_wave(WAVE_CONTAIN *str, const char *topic); +extern int disconnect(); +extern int subscribe(const char* topic, int qos); +extern int unsubscribe(const char* topic); +extern int start_client(const char *boardname, const char *gwid, const char* gwip, const char *gwver, const char *gwcode, std::string &salt); +#ifdef __cplusplus +} +#endif +#endif diff --git a/mqttclient/mosquitto.h b/mqttclient/mosquitto.h new file mode 100644 index 0000000..7fa8241 --- /dev/null +++ b/mqttclient/mosquitto.h @@ -0,0 +1,1536 @@ +/* +Copyright (c) 2010-2014 Roger Light + +All rights reserved. This program and the accompanying materials +are made available under the terms of the Eclipse Public License v1.0 +and Eclipse Distribution License v1.0 which accompany this distribution. + +The Eclipse Public License is available at + http://www.eclipse.org/legal/epl-v10.html +and the Eclipse Distribution License is available at + http://www.eclipse.org/org/documents/edl-v10.php. + +Contributors: + Roger Light - initial implementation and documentation. +*/ + +#ifndef _MOSQUITTO_H_ +#define _MOSQUITTO_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(WIN32) && !defined(WITH_BROKER) +# ifdef libmosquitto_EXPORTS +# define libmosq_EXPORT __declspec(dllexport) +# else +# define libmosq_EXPORT __declspec(dllimport) +# endif +#else +# define libmosq_EXPORT +#endif + +#ifdef WIN32 +# ifndef __cplusplus +# define bool char +# define true 1 +# define false 0 +# endif +#else +# ifndef __cplusplus +# include +# endif +#endif + +#define LIBMOSQUITTO_MAJOR 1 +#define LIBMOSQUITTO_MINOR 4 +#define LIBMOSQUITTO_REVISION 9 +/* LIBMOSQUITTO_VERSION_NUMBER looks like 1002001 for e.g. version 1.2.1. */ +#define LIBMOSQUITTO_VERSION_NUMBER (LIBMOSQUITTO_MAJOR*1000000+LIBMOSQUITTO_MINOR*1000+LIBMOSQUITTO_REVISION) + +/* Log types */ +#define MOSQ_LOG_NONE 0x00 +#define MOSQ_LOG_INFO 0x01 +#define MOSQ_LOG_NOTICE 0x02 +#define MOSQ_LOG_WARNING 0x04 +#define MOSQ_LOG_ERR 0x08 +#define MOSQ_LOG_DEBUG 0x10 +#define MOSQ_LOG_SUBSCRIBE 0x20 +#define MOSQ_LOG_UNSUBSCRIBE 0x40 +#define MOSQ_LOG_WEBSOCKETS 0x80 +#define MOSQ_LOG_ALL 0xFFFF + +/* Error values */ +enum mosq_err_t { + MOSQ_ERR_CONN_PENDING = -1, + MOSQ_ERR_SUCCESS = 0, + MOSQ_ERR_NOMEM = 1, + MOSQ_ERR_PROTOCOL = 2, + MOSQ_ERR_INVAL = 3, + MOSQ_ERR_NO_CONN = 4, + MOSQ_ERR_CONN_REFUSED = 5, + MOSQ_ERR_NOT_FOUND = 6, + MOSQ_ERR_CONN_LOST = 7, + MOSQ_ERR_TLS = 8, + MOSQ_ERR_PAYLOAD_SIZE = 9, + MOSQ_ERR_NOT_SUPPORTED = 10, + MOSQ_ERR_AUTH = 11, + MOSQ_ERR_ACL_DENIED = 12, + MOSQ_ERR_UNKNOWN = 13, + MOSQ_ERR_ERRNO = 14, + MOSQ_ERR_EAI = 15, + MOSQ_ERR_PROXY = 16 +}; + + +/* Error values */ +enum mosq_opt_t { + MOSQ_OPT_PROTOCOL_VERSION = 1, +}; + +/* MQTT specification restricts client ids to a maximum of 23 characters */ +#define MOSQ_MQTT_ID_MAX_LENGTH 23 + +#define MQTT_PROTOCOL_V31 3 +#define MQTT_PROTOCOL_V311 4 + +struct mosquitto_message{ + int mid; + char *topic; + void *payload; + int payloadlen; + int qos; + bool retain; +}; + +struct mosquitto; + +/* + * Topic: Threads + * libmosquitto provides thread safe operation, with the exception of + * which is not thread safe. + * + * If your application uses threads you must use to + * tell the library this is the case, otherwise it makes some optimisations + * for the single threaded case that may result in unexpected behaviour for + * the multi threaded case. + */ +/*************************************************** + * Important note + * + * The following functions that deal with network operations will return + * MOSQ_ERR_SUCCESS on success, but this does not mean that the operation has + * taken place. An attempt will be made to write the network data, but if the + * socket is not available for writing at that time then the packet will not be + * sent. To ensure the packet is sent, call mosquitto_loop() (which must also + * be called to process incoming network data). + * This is especially important when disconnecting a client that has a will. If + * the broker does not receive the DISCONNECT command, it will assume that the + * client has disconnected unexpectedly and send the will. + * + * mosquitto_connect() + * mosquitto_disconnect() + * mosquitto_subscribe() + * mosquitto_unsubscribe() + * mosquitto_publish() + ***************************************************/ + +/* + * Function: mosquitto_lib_version + * + * Can be used to obtain version information for the mosquitto library. + * This allows the application to compare the library version against the + * version it was compiled against by using the LIBMOSQUITTO_MAJOR, + * LIBMOSQUITTO_MINOR and LIBMOSQUITTO_REVISION defines. + * + * Parameters: + * major - an integer pointer. If not NULL, the major version of the + * library will be returned in this variable. + * minor - an integer pointer. If not NULL, the minor version of the + * library will be returned in this variable. + * revision - an integer pointer. If not NULL, the revision of the library will + * be returned in this variable. + * + * Returns: + * LIBMOSQUITTO_VERSION_NUMBER, which is a unique number based on the major, + * minor and revision values. + * See Also: + * , + */ +libmosq_EXPORT int mosquitto_lib_version(int *major, int *minor, int *revision); + +/* + * Function: mosquitto_lib_init + * + * Must be called before any other mosquitto functions. + * + * This function is *not* thread safe. + * + * Returns: + * MOSQ_ERR_SUCCESS - always + * + * See Also: + * , + */ +libmosq_EXPORT int mosquitto_lib_init(void); + +/* + * Function: mosquitto_lib_cleanup + * + * Call to free resources associated with the library. + * + * Returns: + * MOSQ_ERR_SUCCESS - always + * + * See Also: + * , + */ +libmosq_EXPORT int mosquitto_lib_cleanup(void); + +/* + * Function: mosquitto_new + * + * Create a new mosquitto client instance. + * + * Parameters: + * id - String to use as the client id. If NULL, a random client id + * will be generated. If id is NULL, clean_session must be true. + * clean_session - set to true to instruct the broker to clean all messages + * and subscriptions on disconnect, false to instruct it to + * keep them. See the man page mqtt(7) for more details. + * Note that a client will never discard its own outgoing + * messages on disconnect. Calling or + * will cause the messages to be resent. + * Use to reset a client to its + * original state. + * Must be set to true if the id parameter is NULL. + * obj - A user pointer that will be passed as an argument to any + * callbacks that are specified. + * + * Returns: + * Pointer to a struct mosquitto on success. + * NULL on failure. Interrogate errno to determine the cause for the failure: + * - ENOMEM on out of memory. + * - EINVAL on invalid input parameters. + * + * See Also: + * , , + */ +libmosq_EXPORT struct mosquitto *mosquitto_new(const char *id, bool clean_session, void *obj); + +/* + * Function: mosquitto_destroy + * + * Use to free memory associated with a mosquitto client instance. + * + * Parameters: + * mosq - a struct mosquitto pointer to free. + * + * See Also: + * , + */ +libmosq_EXPORT void mosquitto_destroy(struct mosquitto *mosq); + +/* + * Function: mosquitto_reinitialise + * + * This function allows an existing mosquitto client to be reused. Call on a + * mosquitto instance to close any open network connections, free memory + * and reinitialise the client with the new parameters. The end result is the + * same as the output of . + * + * Parameters: + * mosq - a valid mosquitto instance. + * id - string to use as the client id. If NULL, a random client id + * will be generated. If id is NULL, clean_session must be true. + * clean_session - set to true to instruct the broker to clean all messages + * and subscriptions on disconnect, false to instruct it to + * keep them. See the man page mqtt(7) for more details. + * Must be set to true if the id parameter is NULL. + * obj - A user pointer that will be passed as an argument to any + * callbacks that are specified. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * + * See Also: + * , + */ +libmosq_EXPORT int mosquitto_reinitialise(struct mosquitto *mosq, const char *id, bool clean_session, void *obj); + +/* + * Function: mosquitto_will_set + * + * Configure will information for a mosquitto instance. By default, clients do + * not have a will. This must be called before calling . + * + * Parameters: + * mosq - a valid mosquitto instance. + * topic - the topic on which to publish the will. + * payloadlen - the size of the payload (bytes). Valid values are between 0 and + * 268,435,455. + * payload - pointer to the data to send. If payloadlen > 0 this must be a + * valid memory location. + * qos - integer value 0, 1 or 2 indicating the Quality of Service to be + * used for the will. + * retain - set to true to make the will a retained message. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large. + */ +libmosq_EXPORT int mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain); + +/* + * Function: mosquitto_will_clear + * + * Remove a previously configured will. This must be called before calling + * . + * + * Parameters: + * mosq - a valid mosquitto instance. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + */ +libmosq_EXPORT int mosquitto_will_clear(struct mosquitto *mosq); + +/* + * Function: mosquitto_username_pw_set + * + * Configure username and password for a mosquitton instance. This is only + * supported by brokers that implement the MQTT spec v3.1. By default, no + * username or password will be sent. + * If username is NULL, the password argument is ignored. + * This must be called before calling mosquitto_connect(). + * + * This is must be called before calling . + * + * Parameters: + * mosq - a valid mosquitto instance. + * username - the username to send as a string, or NULL to disable + * authentication. + * password - the password to send as a string. Set to NULL when username is + * valid in order to send just a username. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + */ +libmosq_EXPORT int mosquitto_username_pw_set(struct mosquitto *mosq, const char *username, const char *password); + +/* + * Function: mosquitto_connect + * + * Connect to an MQTT broker. + * + * Parameters: + * mosq - a valid mosquitto instance. + * host - the hostname or ip address of the broker to connect to. + * port - the network port to connect to. Usually 1883. + * keepalive - the number of seconds after which the broker should send a PING + * message to the client if no other messages have been exchanged + * in that time. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * + * See Also: + * , , , , + */ +libmosq_EXPORT int mosquitto_connect(struct mosquitto *mosq, const char *host, int port, int keepalive); + +/* + * Function: mosquitto_connect_bind + * + * Connect to an MQTT broker. This extends the functionality of + * by adding the bind_address parameter. Use this function + * if you need to restrict network communication over a particular interface. + * + * Parameters: + * mosq - a valid mosquitto instance. + * host - the hostname or ip address of the broker to connect to. + * port - the network port to connect to. Usually 1883. + * keepalive - the number of seconds after which the broker should send a PING + * message to the client if no other messages have been exchanged + * in that time. + * bind_address - the hostname or ip address of the local network interface to + * bind to. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * + * See Also: + * , , + */ +libmosq_EXPORT int mosquitto_connect_bind(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address); + +/* + * Function: mosquitto_connect_async + * + * Connect to an MQTT broker. This is a non-blocking call. If you use + * your client must use the threaded interface + * . If you need to use , you must use + * to connect the client. + * + * May be called before or after . + * + * Parameters: + * mosq - a valid mosquitto instance. + * host - the hostname or ip address of the broker to connect to. + * port - the network port to connect to. Usually 1883. + * keepalive - the number of seconds after which the broker should send a PING + * message to the client if no other messages have been exchanged + * in that time. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * + * See Also: + * , , , , + */ +libmosq_EXPORT int mosquitto_connect_async(struct mosquitto *mosq, const char *host, int port, int keepalive); + +/* + * Function: mosquitto_connect_bind_async + * + * Connect to an MQTT broker. This is a non-blocking call. If you use + * your client must use the threaded interface + * . If you need to use , you must use + * to connect the client. + * + * This extends the functionality of by adding the + * bind_address parameter. Use this function if you need to restrict network + * communication over a particular interface. + * + * May be called before or after . + * + * Parameters: + * mosq - a valid mosquitto instance. + * host - the hostname or ip address of the broker to connect to. + * port - the network port to connect to. Usually 1883. + * keepalive - the number of seconds after which the broker should send a PING + * message to the client if no other messages have been exchanged + * in that time. + * bind_address - the hostname or ip address of the local network interface to + * bind to. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * + * See Also: + * , , + */ +libmosq_EXPORT int mosquitto_connect_bind_async(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address); + +/* + * Function: mosquitto_connect_srv + * + * Connect to an MQTT broker. This is a non-blocking call. If you use + * your client must use the threaded interface + * . If you need to use , you must use + * to connect the client. + * + * This extends the functionality of by adding the + * bind_address parameter. Use this function if you need to restrict network + * communication over a particular interface. + * + * May be called before or after . + * + * Parameters: + * mosq - a valid mosquitto instance. + * host - the hostname or ip address of the broker to connect to. + * keepalive - the number of seconds after which the broker should send a PING + * message to the client if no other messages have been exchanged + * in that time. + * bind_address - the hostname or ip address of the local network interface to + * bind to. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * + * See Also: + * , , + */ +libmosq_EXPORT int mosquitto_connect_srv(struct mosquitto *mosq, const char *host, int keepalive, const char *bind_address); + +/* + * Function: mosquitto_reconnect + * + * Reconnect to a broker. + * + * This function provides an easy way of reconnecting to a broker after a + * connection has been lost. It uses the values that were provided in the + * call. It must not be called before + * . + * + * Parameters: + * mosq - a valid mosquitto instance. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * + * See Also: + * , , + */ +libmosq_EXPORT int mosquitto_reconnect(struct mosquitto *mosq); + +/* + * Function: mosquitto_reconnect_async + * + * Reconnect to a broker. Non blocking version of . + * + * This function provides an easy way of reconnecting to a broker after a + * connection has been lost. It uses the values that were provided in the + * or calls. It must not be + * called before . + * + * Parameters: + * mosq - a valid mosquitto instance. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * + * See Also: + * , + */ +libmosq_EXPORT int mosquitto_reconnect_async(struct mosquitto *mosq); + +/* + * Function: mosquitto_disconnect + * + * Disconnect from the broker. + * + * Parameters: + * mosq - a valid mosquitto instance. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. + */ +libmosq_EXPORT int mosquitto_disconnect(struct mosquitto *mosq); + +/* + * Function: mosquitto_publish + * + * Publish a message on a given topic. + * + * Parameters: + * mosq - a valid mosquitto instance. + * mid - pointer to an int. If not NULL, the function will set this + * to the message id of this particular message. This can be then + * used with the publish callback to determine when the message + * has been sent. + * Note that although the MQTT protocol doesn't use message ids + * for messages with QoS=0, libmosquitto assigns them message ids + * so they can be tracked with this parameter. + * topic - null terminated string of the topic to publish to. + * payloadlen - the size of the payload (bytes). Valid values are between 0 and + * 268,435,455. + * payload - pointer to the data to send. If payloadlen > 0 this must be a + * valid memory location. + * qos - integer value 0, 1 or 2 indicating the Quality of Service to be + * used for the message. + * retain - set to true to make the message retained. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. + * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the + * broker. + * MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large. + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain); + +/* + * Function: mosquitto_subscribe + * + * Subscribe to a topic. + * + * Parameters: + * mosq - a valid mosquitto instance. + * mid - a pointer to an int. If not NULL, the function will set this to + * the message id of this particular message. This can be then used + * with the subscribe callback to determine when the message has been + * sent. + * sub - the subscription pattern. + * qos - the requested Quality of Service for this subscription. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. + */ +libmosq_EXPORT int mosquitto_subscribe(struct mosquitto *mosq, int *mid, const char *sub, int qos); + +/* + * Function: mosquitto_unsubscribe + * + * Unsubscribe from a topic. + * + * Parameters: + * mosq - a valid mosquitto instance. + * mid - a pointer to an int. If not NULL, the function will set this to + * the message id of this particular message. This can be then used + * with the unsubscribe callback to determine when the message has been + * sent. + * sub - the unsubscription pattern. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. + */ +libmosq_EXPORT int mosquitto_unsubscribe(struct mosquitto *mosq, int *mid, const char *sub); + +/* + * Function: mosquitto_message_copy + * + * Copy the contents of a mosquitto message to another message. + * Useful for preserving a message received in the on_message() callback. + * + * Parameters: + * dst - a pointer to a valid mosquitto_message struct to copy to. + * src - a pointer to a valid mosquitto_message struct to copy from. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_message_copy(struct mosquitto_message *dst, const struct mosquitto_message *src); + +/* + * Function: mosquitto_message_free + * + * Completely free a mosquitto_message struct. + * + * Parameters: + * message - pointer to a mosquitto_message pointer to free. + * + * See Also: + * + */ +libmosq_EXPORT void mosquitto_message_free(struct mosquitto_message **message); + +/* + * Function: mosquitto_loop + * + * The main network loop for the client. You must call this frequently in order + * to keep communications between the client and broker working. If incoming + * data is present it will then be processed. Outgoing commands, from e.g. + * , are normally sent immediately that their function is + * called, but this is not always possible. will also attempt + * to send any remaining outgoing messages, which also includes commands that + * are part of the flow for messages with QoS>0. + * + * An alternative approach is to use to run the client + * loop in its own thread. + * + * This calls select() to monitor the client network socket. If you want to + * integrate mosquitto client operation with your own select() call, use + * , , and + * . + * + * Threads: + * + * Parameters: + * mosq - a valid mosquitto instance. + * timeout - Maximum number of milliseconds to wait for network activity + * in the select() call before timing out. Set to 0 for instant + * return. Set negative to use the default of 1000ms. + * max_packets - this parameter is currently unused and should be set to 1 for + * future compatibility. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. + * MOSQ_ERR_CONN_LOST - if the connection to the broker was lost. + * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the + * broker. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * See Also: + * , , + */ +libmosq_EXPORT int mosquitto_loop(struct mosquitto *mosq, int timeout, int max_packets); + +/* + * Function: mosquitto_loop_forever + * + * This function call loop() for you in an infinite blocking loop. It is useful + * for the case where you only want to run the MQTT client loop in your + * program. + * + * It handles reconnecting in case server connection is lost. If you call + * mosquitto_disconnect() in a callback it will return. + * + * Parameters: + * mosq - a valid mosquitto instance. + * timeout - Maximum number of milliseconds to wait for network activity + * in the select() call before timing out. Set to 0 for instant + * return. Set negative to use the default of 1000ms. + * max_packets - this parameter is currently unused and should be set to 1 for + * future compatibility. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. + * MOSQ_ERR_CONN_LOST - if the connection to the broker was lost. + * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the + * broker. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * + * See Also: + * , + */ +libmosq_EXPORT int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets); + +/* + * Function: mosquitto_loop_start + * + * This is part of the threaded client interface. Call this once to start a new + * thread to process network traffic. This provides an alternative to + * repeatedly calling yourself. + * + * Parameters: + * mosq - a valid mosquitto instance. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOT_SUPPORTED - if thread support is not available. + * + * See Also: + * , , , + */ +libmosq_EXPORT int mosquitto_loop_start(struct mosquitto *mosq); + +/* + * Function: mosquitto_loop_stop + * + * This is part of the threaded client interface. Call this once to stop the + * network thread previously created with . This call + * will block until the network thread finishes. For the network thread to end, + * you must have previously called or have set the force + * parameter to true. + * + * Parameters: + * mosq - a valid mosquitto instance. + * force - set to true to force thread cancellation. If false, + * must have already been called. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOT_SUPPORTED - if thread support is not available. + * + * See Also: + * , + */ +libmosq_EXPORT int mosquitto_loop_stop(struct mosquitto *mosq, bool force); + +/* + * Function: mosquitto_socket + * + * Return the socket handle for a mosquitto instance. Useful if you want to + * include a mosquitto client in your own select() calls. + * + * Parameters: + * mosq - a valid mosquitto instance. + * + * Returns: + * The socket for the mosquitto client or -1 on failure. + */ +libmosq_EXPORT int mosquitto_socket(struct mosquitto *mosq); + +/* + * Function: mosquitto_loop_read + * + * Carry out network read operations. + * This should only be used if you are not using mosquitto_loop() and are + * monitoring the client network socket for activity yourself. + * + * Parameters: + * mosq - a valid mosquitto instance. + * max_packets - this parameter is currently unused and should be set to 1 for + * future compatibility. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. + * MOSQ_ERR_CONN_LOST - if the connection to the broker was lost. + * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the + * broker. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * + * See Also: + * , , + */ +libmosq_EXPORT int mosquitto_loop_read(struct mosquitto *mosq, int max_packets); + +/* + * Function: mosquitto_loop_write + * + * Carry out network write operations. + * This should only be used if you are not using mosquitto_loop() and are + * monitoring the client network socket for activity yourself. + * + * Parameters: + * mosq - a valid mosquitto instance. + * max_packets - this parameter is currently unused and should be set to 1 for + * future compatibility. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. + * MOSQ_ERR_CONN_LOST - if the connection to the broker was lost. + * MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the + * broker. + * MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno + * contains the error code, even on Windows. + * Use strerror_r() where available or FormatMessage() on + * Windows. + * + * See Also: + * , , , + */ +libmosq_EXPORT int mosquitto_loop_write(struct mosquitto *mosq, int max_packets); + +/* + * Function: mosquitto_loop_misc + * + * Carry out miscellaneous operations required as part of the network loop. + * This should only be used if you are not using mosquitto_loop() and are + * monitoring the client network socket for activity yourself. + * + * This function deals with handling PINGs and checking whether messages need + * to be retried, so should be called fairly frequently. + * + * Parameters: + * mosq - a valid mosquitto instance. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NO_CONN - if the client isn't connected to a broker. + * + * See Also: + * , , + */ +libmosq_EXPORT int mosquitto_loop_misc(struct mosquitto *mosq); + +/* + * Function: mosquitto_want_write + * + * Returns true if there is data ready to be written on the socket. + * + * Parameters: + * mosq - a valid mosquitto instance. + * + * See Also: + * , , + */ +libmosq_EXPORT bool mosquitto_want_write(struct mosquitto *mosq); + +/* + * Function: mosquitto_threaded_set + * + * Used to tell the library that your application is using threads, but not + * using . The library operates slightly differently when + * not in threaded mode in order to simplify its operation. If you are managing + * your own threads and do not use this function you will experience crashes + * due to race conditions. + * + * When using , this is set automatically. + * + * Parameters: + * mosq - a valid mosquitto instance. + * threaded - true if your application is using threads, false otherwise. + */ +libmosq_EXPORT int mosquitto_threaded_set(struct mosquitto *mosq, bool threaded); + +/* + * Function: mosquitto_opts_set + * + * Used to set options for the client. + * + * Parameters: + * mosq - a valid mosquitto instance. + * option - the option to set. + * value - the option specific value. + * + * Options: + * MOSQ_OPT_PROTOCOL_VERSION - value must be an int, set to either + * MQTT_PROTOCOL_V31 or MQTT_PROTOCOL_V311. Must + * be set before the client connects. Defaults to + * MQTT_PROTOCOL_V31. + */ +libmosq_EXPORT int mosquitto_opts_set(struct mosquitto *mosq, enum mosq_opt_t option, void *value); + + +/* + * Function: mosquitto_tls_set + * + * Configure the client for certificate based SSL/TLS support. Must be called + * before . + * + * Cannot be used in conjunction with . + * + * Define the Certificate Authority certificates to be trusted (ie. the server + * certificate must be signed with one of these certificates) using cafile. + * + * If the server you are connecting to requires clients to provide a + * certificate, define certfile and keyfile with your client certificate and + * private key. If your private key is encrypted, provide a password callback + * function or you will have to enter the password at the command line. + * + * Parameters: + * mosq - a valid mosquitto instance. + * cafile - path to a file containing the PEM encoded trusted CA + * certificate files. Either cafile or capath must not be NULL. + * capath - path to a directory containing the PEM encoded trusted CA + * certificate files. See mosquitto.conf for more details on + * configuring this directory. Either cafile or capath must not + * be NULL. + * certfile - path to a file containing the PEM encoded certificate file + * for this client. If NULL, keyfile must also be NULL and no + * client certificate will be used. + * keyfile - path to a file containing the PEM encoded private key for + * this client. If NULL, certfile must also be NULL and no + * client certificate will be used. + * pw_callback - if keyfile is encrypted, set pw_callback to allow your client + * to pass the correct password for decryption. If set to NULL, + * the password must be entered on the command line. + * Your callback must write the password into "buf", which is + * "size" bytes long. The return value must be the length of the + * password. "userdata" will be set to the calling mosquitto + * instance. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * + * See Also: + * , , + */ +libmosq_EXPORT int mosquitto_tls_set(struct mosquitto *mosq, + const char *cafile, const char *capath, + const char *certfile, const char *keyfile, + int (*pw_callback)(char *buf, int size, int rwflag, void *userdata)); + +/* + * Function: mosquitto_tls_insecure_set + * + * Configure verification of the server hostname in the server certificate. If + * value is set to true, it is impossible to guarantee that the host you are + * connecting to is not impersonating your server. This can be useful in + * initial server testing, but makes it possible for a malicious third party to + * impersonate your server through DNS spoofing, for example. + * Do not use this function in a real system. Setting value to true makes the + * connection encryption pointless. + * Must be called before . + * + * Parameters: + * mosq - a valid mosquitto instance. + * value - if set to false, the default, certificate hostname checking is + * performed. If set to true, no hostname checking is performed and + * the connection is insecure. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_tls_insecure_set(struct mosquitto *mosq, bool value); + +/* + * Function: mosquitto_tls_opts_set + * + * Set advanced SSL/TLS options. Must be called before . + * + * Parameters: + * mosq - a valid mosquitto instance. + * cert_reqs - an integer defining the verification requirements the client + * will impose on the server. This can be one of: + * * SSL_VERIFY_NONE (0): the server will not be verified in any way. + * * SSL_VERIFY_PEER (1): the server certificate will be verified + * and the connection aborted if the verification fails. + * The default and recommended value is SSL_VERIFY_PEER. Using + * SSL_VERIFY_NONE provides no security. + * tls_version - the version of the SSL/TLS protocol to use as a string. If NULL, + * the default value is used. The default value and the + * available values depend on the version of openssl that the + * library was compiled against. For openssl >= 1.0.1, the + * available options are tlsv1.2, tlsv1.1 and tlsv1, with tlv1.2 + * as the default. For openssl < 1.0.1, only tlsv1 is available. + * ciphers - a string describing the ciphers available for use. See the + * "openssl ciphers" tool for more information. If NULL, the + * default ciphers will be used. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_tls_opts_set(struct mosquitto *mosq, int cert_reqs, const char *tls_version, const char *ciphers); + +/* + * Function: mosquitto_tls_psk_set + * + * Configure the client for pre-shared-key based TLS support. Must be called + * before . + * + * Cannot be used in conjunction with . + * + * Parameters: + * mosq - a valid mosquitto instance. + * psk - the pre-shared-key in hex format with no leading "0x". + * identity - the identity of this client. May be used as the username + * depending on the server settings. + * ciphers - a string describing the PSK ciphers available for use. See the + * "openssl ciphers" tool for more information. If NULL, the + * default ciphers will be used. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_tls_psk_set(struct mosquitto *mosq, const char *psk, const char *identity, const char *ciphers); + +/* + * Function: mosquitto_connect_callback_set + * + * Set the connect callback. This is called when the broker sends a CONNACK + * message in response to a connection. + * + * Parameters: + * mosq - a valid mosquitto instance. + * on_connect - a callback function in the following form: + * void callback(struct mosquitto *mosq, void *obj, int rc) + * + * Callback Parameters: + * mosq - the mosquitto instance making the callback. + * obj - the user data provided in + * rc - the return code of the connection response, one of: + * + * * 0 - success + * * 1 - connection refused (unacceptable protocol version) + * * 2 - connection refused (identifier rejected) + * * 3 - connection refused (broker unavailable) + * * 4-255 - reserved for future use + */ +libmosq_EXPORT void mosquitto_connect_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int)); + +/* + * Function: mosquitto_disconnect_callback_set + * + * Set the disconnect callback. This is called when the broker has received the + * DISCONNECT command and has disconnected the client. + * + * Parameters: + * mosq - a valid mosquitto instance. + * on_disconnect - a callback function in the following form: + * void callback(struct mosquitto *mosq, void *obj) + * + * Callback Parameters: + * mosq - the mosquitto instance making the callback. + * obj - the user data provided in + * rc - integer value indicating the reason for the disconnect. A value of 0 + * means the client has called . Any other value + * indicates that the disconnect is unexpected. + */ +libmosq_EXPORT void mosquitto_disconnect_callback_set(struct mosquitto *mosq, void (*on_disconnect)(struct mosquitto *, void *, int)); + +/* + * Function: mosquitto_publish_callback_set + * + * Set the publish callback. This is called when a message initiated with + * has been sent to the broker successfully. + * + * Parameters: + * mosq - a valid mosquitto instance. + * on_publish - a callback function in the following form: + * void callback(struct mosquitto *mosq, void *obj, int mid) + * + * Callback Parameters: + * mosq - the mosquitto instance making the callback. + * obj - the user data provided in + * mid - the message id of the sent message. + */ +libmosq_EXPORT void mosquitto_publish_callback_set(struct mosquitto *mosq, void (*on_publish)(struct mosquitto *, void *, int)); + +/* + * Function: mosquitto_message_callback_set + * + * Set the message callback. This is called when a message is received from the + * broker. + * + * Parameters: + * mosq - a valid mosquitto instance. + * on_message - a callback function in the following form: + * void callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) + * + * Callback Parameters: + * mosq - the mosquitto instance making the callback. + * obj - the user data provided in + * message - the message data. This variable and associated memory will be + * freed by the library after the callback completes. The client + * should make copies of any of the data it requires. + * + * See Also: + * + */ +libmosq_EXPORT void mosquitto_message_callback_set(struct mosquitto *mosq, void (*on_message)(struct mosquitto *, void *, const struct mosquitto_message *)); + +/* + * Function: mosquitto_subscribe_callback_set + * + * Set the subscribe callback. This is called when the broker responds to a + * subscription request. + * + * Parameters: + * mosq - a valid mosquitto instance. + * on_subscribe - a callback function in the following form: + * void callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) + * + * Callback Parameters: + * mosq - the mosquitto instance making the callback. + * obj - the user data provided in + * mid - the message id of the subscribe message. + * qos_count - the number of granted subscriptions (size of granted_qos). + * granted_qos - an array of integers indicating the granted QoS for each of + * the subscriptions. + */ +libmosq_EXPORT void mosquitto_subscribe_callback_set(struct mosquitto *mosq, void (*on_subscribe)(struct mosquitto *, void *, int, int, const int *)); + +/* + * Function: mosquitto_unsubscribe_callback_set + * + * Set the unsubscribe callback. This is called when the broker responds to a + * unsubscription request. + * + * Parameters: + * mosq - a valid mosquitto instance. + * on_unsubscribe - a callback function in the following form: + * void callback(struct mosquitto *mosq, void *obj, int mid) + * + * Callback Parameters: + * mosq - the mosquitto instance making the callback. + * obj - the user data provided in + * mid - the message id of the unsubscribe message. + */ +libmosq_EXPORT void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq, void (*on_unsubscribe)(struct mosquitto *, void *, int)); + +/* + * Function: mosquitto_log_callback_set + * + * Set the logging callback. This should be used if you want event logging + * information from the client library. + * + * mosq - a valid mosquitto instance. + * on_log - a callback function in the following form: + * void callback(struct mosquitto *mosq, void *obj, int level, const char *str) + * + * Callback Parameters: + * mosq - the mosquitto instance making the callback. + * obj - the user data provided in + * level - the log message level from the values: + * MOSQ_LOG_INFO + * MOSQ_LOG_NOTICE + * MOSQ_LOG_WARNING + * MOSQ_LOG_ERR + * MOSQ_LOG_DEBUG + * str - the message string. + */ +libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq, void (*on_log)(struct mosquitto *, void *, int, const char *)); + +/* + * Function: mosquitto_reconnect_delay_set + * + * Control the behaviour of the client when it has unexpectedly disconnected in + * or after . The default + * behaviour if this function is not used is to repeatedly attempt to reconnect + * with a delay of 1 second until the connection succeeds. + * + * Use reconnect_delay parameter to change the delay between successive + * reconnection attempts. You may also enable exponential backoff of the time + * between reconnections by setting reconnect_exponential_backoff to true and + * set an upper bound on the delay with reconnect_delay_max. + * + * Example 1: + * delay=2, delay_max=10, exponential_backoff=False + * Delays would be: 2, 4, 6, 8, 10, 10, ... + * + * Example 2: + * delay=3, delay_max=30, exponential_backoff=True + * Delays would be: 3, 6, 12, 24, 30, 30, ... + * + * Parameters: + * mosq - a valid mosquitto instance. + * reconnect_delay - the number of seconds to wait between + * reconnects. + * reconnect_delay_max - the maximum number of seconds to wait + * between reconnects. + * reconnect_exponential_backoff - use exponential backoff between + * reconnect attempts. Set to true to enable + * exponential backoff. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + */ +libmosq_EXPORT int mosquitto_reconnect_delay_set(struct mosquitto *mosq, unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff); + +/* + * Function: mosquitto_max_inflight_messages_set + * + * Set the number of QoS 1 and 2 messages that can be "in flight" at one time. + * An in flight message is part way through its delivery flow. Attempts to send + * further messages with will result in the messages being + * queued until the number of in flight messages reduces. + * + * A higher number here results in greater message throughput, but if set + * higher than the maximum in flight messages on the broker may lead to + * delays in the messages being acknowledged. + * + * Set to 0 for no maximum. + * + * Parameters: + * mosq - a valid mosquitto instance. + * max_inflight_messages - the maximum number of inflight messages. Defaults + * to 20. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid. + */ +libmosq_EXPORT int mosquitto_max_inflight_messages_set(struct mosquitto *mosq, unsigned int max_inflight_messages); + +/* + * Function: mosquitto_message_retry_set + * + * Set the number of seconds to wait before retrying messages. This applies to + * publish messages with QoS>0. May be called at any time. + * + * Parameters: + * mosq - a valid mosquitto instance. + * message_retry - the number of seconds to wait for a response before + * retrying. Defaults to 20. + */ +libmosq_EXPORT void mosquitto_message_retry_set(struct mosquitto *mosq, unsigned int message_retry); + +/* + * Function: mosquitto_user_data_set + * + * When is called, the pointer given as the "obj" parameter + * will be passed to the callbacks as user data. The + * function allows this obj parameter to be updated at any time. This function + * will not modify the memory pointed to by the current user data pointer. If + * it is dynamically allocated memory you must free it yourself. + * + * Parameters: + * mosq - a valid mosquitto instance. + * obj - A user pointer that will be passed as an argument to any callbacks + * that are specified. + */ +libmosq_EXPORT void mosquitto_user_data_set(struct mosquitto *mosq, void *obj); + +/* ============================================================================= + * + * Section: SOCKS5 proxy functions + * + * ============================================================================= + */ + +/* + * Function: mosquitto_socks5_set + * + * Configure the client to use a SOCKS5 proxy when connecting. Must be called + * before connecting. "None" and "username/password" authentication is + * supported. + * + * Parameters: + * mosq - a valid mosquitto instance. + * host - the SOCKS5 proxy host to connect to. + * port - the SOCKS5 proxy port to use. + * username - if not NULL, use this username when authenticating with the proxy. + * password - if not NULL and username is not NULL, use this password when + * authenticating with the proxy. + */ +libmosq_EXPORT int mosquitto_socks5_set(struct mosquitto *mosq, const char *host, int port, const char *username, const char *password); + +/* ============================================================================= + * + * Section: Utility functions + * + * ============================================================================= + */ + +/* + * Function: mosquitto_strerror + * + * Call to obtain a const string description of a mosquitto error number. + * + * Parameters: + * mosq_errno - a mosquitto error number. + * + * Returns: + * A constant string describing the error. + */ +libmosq_EXPORT const char *mosquitto_strerror(int mosq_errno); + +/* + * Function: mosquitto_connack_string + * + * Call to obtain a const string description of an MQTT connection result. + * + * Parameters: + * connack_code - an MQTT connection result. + * + * Returns: + * A constant string describing the result. + */ +libmosq_EXPORT const char *mosquitto_connack_string(int connack_code); + +/* + * Function: mosquitto_sub_topic_tokenise + * + * Tokenise a topic or subscription string into an array of strings + * representing the topic hierarchy. + * + * For example: + * + * subtopic: "a/deep/topic/hierarchy" + * + * Would result in: + * + * topics[0] = "a" + * topics[1] = "deep" + * topics[2] = "topic" + * topics[3] = "hierarchy" + * + * and: + * + * subtopic: "/a/deep/topic/hierarchy/" + * + * Would result in: + * + * topics[0] = NULL + * topics[1] = "a" + * topics[2] = "deep" + * topics[3] = "topic" + * topics[4] = "hierarchy" + * + * Parameters: + * subtopic - the subscription/topic to tokenise + * topics - a pointer to store the array of strings + * count - an int pointer to store the number of items in the topics array. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + * + * Example: + * + * > char **topics; + * > int topic_count; + * > int i; + * > + * > mosquitto_sub_topic_tokenise("$SYS/broker/uptime", &topics, &topic_count); + * > + * > for(i=0; i printf("%d: %s\n", i, topics[i]); + * > } + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_sub_topic_tokenise(const char *subtopic, char ***topics, int *count); + +/* + * Function: mosquitto_sub_topic_tokens_free + * + * Free memory that was allocated in . + * + * Parameters: + * topics - pointer to string array. + * count - count of items in string array. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_sub_topic_tokens_free(char ***topics, int count); + +/* + * Function: mosquitto_topic_matches_sub + * + * Check whether a topic matches a subscription. + * + * For example: + * + * foo/bar would match the subscription foo/# or +/bar + * non/matching would not match the subscription non/+/+ + * + * Parameters: + * sub - subscription string to check topic against. + * topic - topic to check. + * result - bool pointer to hold result. Will be set to true if the topic + * matches the subscription. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if the input parameters were invalid. + * MOSQ_ERR_NOMEM - if an out of memory condition occurred. + */ +libmosq_EXPORT int mosquitto_topic_matches_sub(const char *sub, const char *topic, bool *result); + +/* + * Function: mosquitto_pub_topic_check + * + * Check whether a topic to be used for publishing is valid. + * + * This searches for + or # in a topic and checks its length. + * + * This check is already carried out in and + * , there is no need to call it directly before them. It + * may be useful if you wish to check the validity of a topic in advance of + * making a connection for example. + * + * Parameters: + * topic - the topic to check + * + * Returns: + * MOSQ_ERR_SUCCESS - for a valid topic + * MOSQ_ERR_INVAL - if the topic contains a + or a #, or if it is too long. + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_pub_topic_check(const char *topic); + +/* + * Function: mosquitto_sub_topic_check + * + * Check whether a topic to be used for subscribing is valid. + * + * This searches for + or # in a topic and checks that they aren't in invalid + * positions, such as with foo/#/bar, foo/+bar or foo/bar#, and checks its + * length. + * + * This check is already carried out in and + * , there is no need to call it directly before them. + * It may be useful if you wish to check the validity of a topic in advance of + * making a connection for example. + * + * Parameters: + * topic - the topic to check + * + * Returns: + * MOSQ_ERR_SUCCESS - for a valid topic + * MOSQ_ERR_INVAL - if the topic contains a + or a # that is in an invalid + * position, or if it is too long. + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_sub_topic_check(const char *topic); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/platform/SH_PlatformInit.cpp b/platform/SH_PlatformInit.cpp new file mode 100644 index 0000000..41be7df --- /dev/null +++ b/platform/SH_PlatformInit.cpp @@ -0,0 +1,250 @@ +#include +#include "SH_PlatformInit.hpp" +#include "../common/SH_global.h" +#include "../dbaccess/SH_SqlDB.hpp" +#include "../API_log/SH_log.h" + +/*********************全局变量声明***********************/ +int GlobalConfig::RUN_MODE = 0; +int GlobalConfig::QuitFlag_G = 1; +int GlobalConfig::LinkStatus_G = 0; +int GlobalConfig::LinkCount = 0; + + + +std::string GlobalConfig::Version = "2.0.11"; +std::string GlobalConfig::MacAddr_G = ""; +std::string GlobalConfig::IpAddr_G = ""; +std::string GlobalConfig::ServerIP = ""; +int GlobalConfig::ServerPort = 0; + + +TopicList GlobalConfig::Topic_G; +ZigbeeInfo GlobalConfig::ZigbeeInfo_G; +ZIGBEE GlobalConfig::Zigbee_G; +std::string GlobalConfig::DbName_G = "/opt/configenv/cidn.db"; //数据库名称 +std::string GlobalConfig::UartName_G = "/dev/ttymxc4"; + +// 处理ZigBee网络接收过程的PanID切换 +enumZigBeeTransmitStatus GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; +int GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + +PlatformInit::PlatformInit() +{ + +} + +PlatformInit::~PlatformInit() +{ +} + +void PlatformInit::PlatFormInit() +{ +try{ + GlobalConfig::MacAddr_G = GetLocalMac(); + transform(GlobalConfig::MacAddr_G.begin(), GlobalConfig::MacAddr_G.end(), GlobalConfig::MacAddr_G.begin(), ::toupper); + GlobalConfig::IpAddr_G = IpAddrInit(); + print_info("GlobalConfig::IpAddr_G : %s\n", GlobalConfig::IpAddr_G.c_str()); + this->ConfigFileCheck(); + this->TopicInit(); + this->ServerIpInit(); + this->Sqlite3Init(); + + print_info("ServerIP : %s \n", GlobalConfig::ServerIP.c_str()); + // sleep(10); + } catch(...){ + print_error("PlatFormInit exception happend.\n"); + std::string errorinfo = "系统初始化异常"; + } +} + +void PlatformInit::TopicInit() +{ + GlobalConfig::Topic_G.mPubData = "wireless/statisticData/" + GlobalConfig::MacAddr_G; + + GlobalConfig::Topic_G.mPubStatus = "wireless/status/" + GlobalConfig::MacAddr_G; + + GlobalConfig::Topic_G.mPubHeart = "wireless/heart/" + GlobalConfig::MacAddr_G;// + + GlobalConfig::Topic_G.mPubConfig = "wireless/configureInfor/" + GlobalConfig::MacAddr_G; + + GlobalConfig::Topic_G.mPubWaveData = "wireless/realTimeData/" + GlobalConfig::MacAddr_G; + + GlobalConfig::Topic_G.mPubWaveSecondData = "wireless/secondTimeData/" + GlobalConfig::MacAddr_G; + + GlobalConfig::Topic_G.mPubCmd = "wireless/cmd/" + GlobalConfig::MacAddr_G;// + + GlobalConfig::Topic_G.mSubData = "cmd/" + GlobalConfig::MacAddr_G;// + + GlobalConfig::Topic_G.mPubRep = "wireless/resp/" + GlobalConfig::MacAddr_G; + + + GlobalConfig::Topic_G.mPubLocalWifi = "up/" + GlobalConfig::MacAddr_G + "/recive/wifi"; + + GlobalConfig::Topic_G.mPubLocalWaveServer = "up/" + GlobalConfig::MacAddr_G + "/recive/waveserver"; + + GlobalConfig::Topic_G.mPubLocalWaveQt = "up/" + GlobalConfig::MacAddr_G + "/recive/waveqt"; + + GlobalConfig::Topic_G.mPubLocalConfig = "up/" + GlobalConfig::MacAddr_G + "/recive/config"; + + GlobalConfig::Topic_G.mPubLocalTrigger = "up/" + GlobalConfig::MacAddr_G + "/recive/trigger"; + + GlobalConfig::Topic_G.mPubLocalCmd= "up/" + GlobalConfig::MacAddr_G + "/recive/cmd"; +} + + +void PlatformInit::ConfigFileCheck() +{ + if (access(SYSTEMINFOFILE, 0) < 0) { + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayName", ""); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAssetId", ""); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy", ""); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedDate", ""); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "timezone", "UTC+8"); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayNo", GlobalConfig::MacAddr_G); + WriteStr2Config(SYSTEMINFOFILE, "Area", "countryId", ""); + WriteStr2Config(SYSTEMINFOFILE, "Area", "provincesId", ""); + WriteStr2Config(SYSTEMINFOFILE, "Area", "cityListId", ""); + WriteStr2Config(SYSTEMINFOFILE, "Uint", "uint", "ST"); + + } + + if (access(NETWORKCONFIG, 0) < 0) { + WriteStr2Config(NETWORKCONFIG, "Net", "dnsName", " "); + WriteStr2Config(NETWORKCONFIG, "Net", "networkPortStatus", "DHCP"); + WriteStr2Config(NETWORKCONFIG, "Net", "gateway", "0.0.0.0"); + WriteStr2Config(NETWORKCONFIG, "Net", "subnetMask", "0.0.0.0"); + WriteStr2Config(NETWORKCONFIG, "Net", "ipAddress", "0.0.0.0"); + WriteStr2Config(NETWORKCONFIG, "Net", "hostName", "0.0.0.0"); + } + + if (access(SERVERCONFIG, 0) < 0) { + WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", "0.0.0.0"); + WriteStr2Config(SERVERCONFIG, "Server", "localServerPort", "51613"); + } +} + +int PlatformInit::ServerIpInit() +{ + if (access(SERVERCONFIG, 0) >= 0) { + GlobalConfig::ServerIP = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress"); + GlobalConfig::ServerPort = boost::lexical_cast(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort")); + } + +} + +void PlatformInit::Sqlite3Init() +{ + sql_ctl->OpenDB(GlobalConfig::DbName_G.c_str()); + sql_ctl->SqliteInit(GlobalConfig::DbName_G.c_str()); + print_info("Sqlite3Init \n"); +} + +void PlatformInit::SystemInfoInit() +{ + std::ifstream ifileOut(SYSTEMINFOFILE); + Json::Reader recvReader; + Json::Value Systeminfo; + //从配置文件中读取json数据 + if (ifileOut.is_open()) { + print_blue("open %s\n", SYSTEMINFOFILE); + } + if (!recvReader.parse(ifileOut, Systeminfo, false)) { + if (ifileOut.is_open()) { + ifileOut.close(); + } else { + return; + } + } + ifileOut.close(); + + Systeminfo["dataWatchIpAddress"] = GlobalConfig::IpAddr_G; + Systeminfo["softVersion"] = GlobalConfig::Version; + + std::string strSerialNumber = GetFileContent(SN, 1); + Systeminfo["serialNumber"] = strSerialNumber; + + Json::StyledWriter sw; + std::ofstream os; + os.open(SYSTEMINFOFILE); + os << sw.write(Systeminfo); + os.close(); +} + + +void PlatformInit::UserInit() +{ + std::string userName = ReadStrByOpt(SYSTEMINFOFILE, "UserInfo", "UserName"); + if (userName.length() == 0) { + WriteStr2Config(SYSTEMINFOFILE, "UserInfo", "UserName", "Admin"); + WriteStr2Config(SYSTEMINFOFILE, "UserInfo", "adminPassword", "njchaos"); + WriteStr2Config(SYSTEMINFOFILE, "UserInfo", "userPassword", ""); + } +} + +void PlatformInit::EquipIpInit() +{ + //eth0 初始化 + int flag = 0; + std::string networkPortStatus = ReadStrByOpt(NETWORKCONFIG, "Net", "networkPortStatus"); + std::string subnetMask = ReadStrByOpt(NETWORKCONFIG, "Net", "subnetMask"); + std::string gateway = ReadStrByOpt(NETWORKCONFIG, "Net", "gateway"); + std::string dataWatchIpAddress = ReadStrByOpt(NETWORKCONFIG, "Net", "ipAddress"); + std::string strStatus = GetFileContent(NETWORK, 18); + print_red("strStatus:%s\n networkPortStatus:%s dataWatchIpAddress:%s subnetMask:%s gateway:%s\n",strStatus.c_str(),networkPortStatus.c_str(),dataWatchIpAddress.c_str(),subnetMask.c_str(),gateway.c_str()); + + if(0 == networkPortStatus.compare("DHCP")) + { + print_white("dhcp config\n"); + std::string cmd = ""; + system("sed -i '17c auto eth0' /etc/network/interfaces"); + system("sed -i '18c iface eth0 inet dhcp' /etc/network/interfaces"); + system("sed -i '20c ' /etc/network/interfaces"); + system("sed -i '21c ' /etc/network/interfaces"); + system("sed -i '22c ' /etc/network/interfaces"); + flag = 0; + } + if(0 == networkPortStatus.compare("STATIC")) + { + std::string cmd = ""; + print_red("static config\n"); + + system("sed -i '18c iface eth0 inet static' /etc/network/interfaces"); + if(dataWatchIpAddress.length() > 0) + { + cmd = "sed -i '20c address " + dataWatchIpAddress + "' /etc/network/interfaces"; + }else{ + cmd = "sed -i '20c address 0.0.0.0' /etc/network/interfaces"; + } + system(cmd.c_str()); + cmd.clear(); + + if(subnetMask.length() > 0) + { + cmd = "sed -i '21c netmask " + subnetMask + "' /etc/network/interfaces"; + }else{ + cmd = "sed -i '21c netmask 255.255.255.0' /etc/network/interfaces"; + } + system(cmd.c_str()); + cmd.clear(); + + if(gateway.length() > 0) + { + cmd = "sed -i '22c gateway " + gateway + "' /etc/network/interfaces"; + }else{ + cmd = "sed -i '22c gateway 0.0.0.0' /etc/network/interfaces"; + } + system(cmd.c_str()); + cmd.clear(); + flag = 1; + } + + if(1 == flag){ //静态直接更新 + system("source /etc/config.sh"); + } + if(0 == flag) //动态重新启动获取 + { + system("reboot"); + } +} + diff --git a/platform/SH_PlatformInit.hpp b/platform/SH_PlatformInit.hpp new file mode 100644 index 0000000..3d2c04d --- /dev/null +++ b/platform/SH_PlatformInit.hpp @@ -0,0 +1,66 @@ +#ifndef _PLATFORMINIT_H_ +#define _PLATFORMINIT_H_ + +#include +#include +#include "../utility/SH_MySingleton.hpp" +#include "../common/SH_CommonFunc.hpp" + + + +class PlatformInit : public MySingleton +{ +public : + PlatformInit(); + virtual ~PlatformInit(); + + /** + * @brief 初始化系统配置文件,初始化时间戳,初始化数据库,初始化时区 + * @return void + */ + void PlatFormInit(); + + /** + * @brief 初始化系统配置文件,初始化时间戳,初始化数据库,初始化时区 + * @return void + */ + void ConfigFileCheck(); + + /** + * @brief 服务器IP初始化 + * @return void + */ + int ServerIpInit(); + + /** + * @brief 设备信息重新校验 + * @return void + */ + void SystemInfoInit(); + + /** + * @brief cgi用户信息初始化 + * @return void + */ + void UserInit(); + + /** + * @brief 数据库初始化 + * @return void + */ + void Sqlite3Init(); + /** + *@eth0 初始化 + */ + void EquipIpInit(); +private: + + /** + * @brief mqtt主题初始化 + * @return void + */ + void TopicInit(); + +}; + +#endif diff --git a/searchdev/SH_SearchDev.cpp b/searchdev/SH_SearchDev.cpp new file mode 100644 index 0000000..1f5dedc --- /dev/null +++ b/searchdev/SH_SearchDev.cpp @@ -0,0 +1,146 @@ +#include +#include +#include +#include +#include +#include "SH_SearchDev.hpp" + + +static const char* MULTICAST_HOST_NAME1 = "224.0.0.1"; //组播接收平台搜索信号地址 +static const int MULTICAST_PORT_RECV1 = 7301; //组播接收端口 +static const int MULTICAST_PORT_SEND = 7302; //根据接收组播udp发送端口 + + +SearchDev::SearchDev(boost::asio::io_service& ioservice):mSockRecv_1(ioservice), + mListenEP1(ip::udp::v4(),MULTICAST_PORT_RECV1), + mSendEndpoint1(ip::address::from_string(MULTICAST_HOST_NAME1),MULTICAST_PORT_SEND) +{ + Init(); +} + +SearchDev::~SearchDev() +{ + Stop(); +} + +void SearchDev::Init() +{ + // GwRouteInit(); + //设置组播接收地址1 + try { + mSockRecv_1.open(mListenEP1.protocol()); + mSockRecv_1.set_option(ip::udp::socket::reuse_address(true)); + mSockRecv_1.bind(mListenEP1); + mSockRecv_1.set_option(ip::multicast::join_group(ip::address_v4::from_string(MULTICAST_HOST_NAME1))); + mSockRecv_1.set_option(boost::asio::ip::multicast::enable_loopback(false)); + } catch(boost::system::system_error& e) { + std::cout << e.what() << std::endl; + } +} + + +void SearchDev::GwRouteInit() { + + // system("route > scan_test"); + // std::fstream fileOut; + // int find = 0; + // fileOut.open("scan_test",std::ios::in | std::ios::app); + // if (fileOut.is_open()) {//文件打开 + // while (!fileOut.eof()) { + // std::string tmpStr(""); + // getline(fileOut,tmpStr); + // //fileOut >> tmpStr; + // print_info("%s\n",tmpStr.c_str()); + // if (strstr(tmpStr.c_str(), "224.0.0.0")) { + // find = 1; + // } + // } + // } + // fileOut.close(); + + // if (!find) { + // char cmd[128]="route add -net 224.0.0.0 netmask 224.0.0.0 dev "; + // strcat(cmd,GlobalConfig::KEthname.c_str()); + // print_info("%s\n",cmd); + // system(cmd); + // } + // system("rm scan_test"); +} + +void SearchDev::HandleSend_1(const char *pMsg,const boost::system::error_code &pEc) +{ + if (pEc) { + print_info("send udp error 7302\n"); + } else { + print_info("send udp ok 7302\n"); + } +} + + + +void SearchDev::MultiCastRecv() { + MultiCastRecv_1(); +} + +void SearchDev::MultiCastRecv_1() +{ + memset(mRecvBuf1,0,BUF_LENGTH); + + mSockRecv_1.async_receive_from(boost::asio::buffer(mRecvBuf1,BUF_LENGTH),mRecvEP1, + boost::bind(&SearchDev::HandleRecv_1,this,boost::asio::placeholders::error, + boost::asio::placeholders::bytes_transferred)); +} + +void SearchDev::HandleRecv_1(const boost::system::error_code &pEc,size_t pBytesRecv) +{ + if (!pEc) { + print_info("mRecvBuf1 : %s\n", mRecvBuf1); + std::string data = std::string(mRecvBuf1); + Json::Value jsData; + Json::Reader recvReader; + Json::Value JsonVal; + Json::FastWriter fw; + if (recvReader.parse(data, jsData)) { + int cmdType = atoi(jsData["cmd"].asString().c_str()); + switch (cmdType) { + case 4:{ + std::string status = jsData["status"].asString(); + if(status.compare("REQ") == 0) { + jsData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G.c_str(); + jsData["localServerIpAddress"] = GlobalConfig::ServerIP; + jsData["status"] = "ACK"; + std::string strData = fw.write(jsData); + print_info("send info %s ip: %s\n", strData.c_str(), mRecvEP1.address().to_string().c_str()); + ip::udp::endpoint remoteEP(ip::address::from_string(mRecvEP1.address().to_string()), + MULTICAST_PORT_SEND); + mSockRecv_1.async_send_to(boost::asio::buffer(strData),remoteEP, + boost::bind(&SearchDev::HandleSend_1,this,"SockRecv_1_1",boost::asio::placeholders::error)); + } + } + break; + default: + break; + } + } + MultiCastRecv_1(); + } else { + } +} + +void SearchDev::Run() +{ + // mIoSev.run(); +} + +void SearchDev::Stop() +{ + // if (!mIoSev.stopped()) + // mIoSev.stop(); +} + +void SearchDev::Restart() +{ + Init(); +} + + diff --git a/searchdev/SH_SearchDev.hpp b/searchdev/SH_SearchDev.hpp new file mode 100644 index 0000000..c083cb3 --- /dev/null +++ b/searchdev/SH_SearchDev.hpp @@ -0,0 +1,39 @@ +#ifndef _WL_SEARCHDEV_ +#define _WL_SEARCHDEV_ +#include +#include +#include +#include "../common/SH_global.h" +#include "../utility/SH_MySingleton.hpp" +#include "../common/SH_CommonFunc.hpp" + +using namespace boost::asio; +//using boost::system::error_code; + +class SearchDev : public MySingleton +{ +public : + SearchDev(boost::asio::io_service& ioservice); + ~SearchDev(); + void MultiCastRecv(); + void MultiCastRecv_1(); + void Run(); + void Stop(); + void Restart(); +private: + void Init(); + void GwRouteInit(); + void HandleRecv_1(const boost::system::error_code &pEc,size_t pBytesRecv ); + void HandleSend_1(const char *pMsg,const boost::system::error_code &pEc); +private : + enum{BUF_LENGTH = 128}; + //io_service mIoSev; + ip::udp::socket mSockRecv_1;//组播地址1 + ip::udp::endpoint mRecvEP1; + ip::udp::endpoint mListenEP1; + ip::udp::endpoint mSendEndpoint1;//组播发送端点 + char mRecvBuf1[BUF_LENGTH]; + char mSendBuf1[BUF_LENGTH]; +}; + +#endif diff --git a/secure/SH_Secure.cpp b/secure/SH_Secure.cpp new file mode 100644 index 0000000..00346c2 --- /dev/null +++ b/secure/SH_Secure.cpp @@ -0,0 +1,1436 @@ +#include +#include +#include +#include +#include +#include +#include +#include "SH_Secure.hpp" + +#define AES_ENCRYPT 2 +#define AES_DECRYPT 0 + +#define Length_(len) do{ \ + len = ((((len>>3) + ((len&0x7)>0?1:0))<<4) + 8); \ + } while (0) + +namespace DEScrypt { +//u_char C[17][28], D[17][28], K[17][48]; +int iip_tab_p[64] = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, + 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, + 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; +int _iip_tab_p[64] = { 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, + 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, + 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 }; + +void Fexpand0(u_char *in, u_char *out) { + int divide; + int i, j; + for (i = 0; i < 8; i++) { + divide = 0x80; + for (j = 0; j < 8; j++) { + *out++ = (in[i] / divide) & 1; + divide /= 2; + } + } +} + +void Fcompress0(u_char *out, u_char *in) +{ + int times; + int i, j; + for (i = 0; i < 8; i++) { + times = 0x80; + in[i] = 0; + for (j = 0; j < 8; j++) { + in[i] += (*out++) * times; + times /= 2; + } + } +} + +void Fcompress016(u_char *out, u_char *in) +{ + int times; + int i, j; + for (i = 0; i < 16; i++) { + times = 0x8; + in[i] = '0'; + for (j = 0; j < 4; j++) { + in[i] += (*out++) * times; + times /= 2; + } + } +} + +int pc_1_cp[28] = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, + 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36 }; +int pc_1_dp[28] = { 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, + 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 }; +int pc_2p[48] = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, + 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, + 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; + +int ls_countp[16] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; + +void FLS(u_char *bits, u_char *buffer, int count) +{ + for (int i = 0; i < 28; i++) { + buffer[i] = bits[(i + count) % 28]; + } +} + +void Fson(u_char *cc, u_char *dd, u_char *kk) +{ + int i; + u_char buffer[56]; + for (i = 0; i < 28; i++) { + buffer[i] = *cc++; + } + for (i = 28; i < 56; i++) { + buffer[i] = *dd++; + } + for (i = 0; i < 48; i++) { + *kk++ = buffer[pc_2p[i] - 1]; + } +} + +void Fsetkeystar(u_char bits[64], u_char K[17][48]) +{ + int i, j; + u_char C[17][28], D[17][28]; + for (i = 0; i < 28; i++) { + C[0][i] = bits[pc_1_cp[i] - 1]; + } + for (i = 0; i < 28; i++) { + D[0][i] = bits[pc_1_dp[i] - 1]; + } + for (j = 0; j < 16; j++) { + FLS(C[j], C[j + 1], ls_countp[j]); + FLS(D[j], D[j + 1], ls_countp[j]); + Fson(C[j + 1], D[j + 1], K[j + 1]); + } +} + +void Fiip(u_char *text, u_char *ll, u_char *rr) +{ + u_char buffer[64]; + Fexpand0(text, buffer); + int i; + for (i = 0; i < 32; i++) { + ll[i] = buffer[iip_tab_p[i] - 1]; + } + for (i = 0; i < 32; i++) { + rr[i] = buffer[iip_tab_p[i + 32] - 1]; + } +} + +void _Fiip(u_char *text, u_char *ll, u_char *rr) +{ + u_char tmp[64]; + int i; + for (i = 0; i < 32; i++) { + tmp[i] = ll[i]; + } + for (i = 32; i < 64; i++) { + tmp[i] = rr[i - 32]; + } + for (i = 0; i < 64; i++) { + text[i] = tmp[_iip_tab_p[i] - 1]; + } +} + +int e_r_p[48] = { 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, + 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 }; + +int local_PP[32] = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, + 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; +int ccom_SSS_p[8][4][16] = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, + 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,/* err on */ + 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, + 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13, + + 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, + 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, + 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, + 9, + + 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, + 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, + 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, + 12, + + 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, + 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, + 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, + 14, /* err on */ + + 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, + 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, /* err on */ + 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, + 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3, + + 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, + 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, + 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, + 13, + + 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, + 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, + 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, + 12, + + 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, + 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, + 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, + 11 }; + +void Fs_box(u_char *aa, u_char *bb) +{ + int i, j, k, m; + int y, z; + u_char ss[8]; + m = 0; + for (i = 0; i < 8; i++) { + j = 6 * i; + y = aa[j] * 2 + aa[j + 5]; + z = aa[j + 1] * 8 + aa[j + 2] * 4 + aa[j + 3] * 2 + aa[j + 4]; + ss[i] = ccom_SSS_p[i][y][z]; + y = 0x08; + for (k = 0; k < 4; k++) { + bb[m++] = (ss[i] / y) & 1; + y /= 2; + } + } +} + +void FF(int n, u_char *ll, u_char *rr, u_char *LL, u_char *RR,u_char K[17][48]) +{ + int i; + u_char buffer[64], tmp[64]; + for (i = 0; i < 48; i++) { + buffer[i] = rr[e_r_p[i] - 1]; + } + for (i = 0; i < 48; i++) { + buffer[i] = (buffer[i] + K[n][i]) & 1; + } + Fs_box(buffer, tmp); + for (i = 0; i < 32; i++) { + buffer[i] = tmp[local_PP[i] - 1]; + } + for (i = 0; i < 32; i++) { + RR[i] = (buffer[i] + ll[i]) & 1; + } + for (i = 0; i < 32; i++) { + LL[i] = rr[i]; + } +} + +void Fencrypt0(u_char *text, u_char *mtext, u_char k[17][48]) +{ + u_char ll[64], rr[64], LL[64], RR[64]; + u_char tmp[64]; + int i, j; + Fiip(text, ll, rr); + for (i = 1; i < 17; i++) { + FF(i, ll, rr, LL, RR,k); + for (j = 0; j < 32; j++) { + ll[j] = LL[j]; + rr[j] = RR[j]; + } + } + _Fiip(tmp, rr, ll); + Fcompress0(tmp, mtext); +} + +void Fdiscrypt0(u_char *mtext, u_char *text, u_char k[17][48]) +{ + u_char ll[64], rr[64], LL[64], RR[64]; + u_char tmp[64]; + int i, j; + Fiip(mtext, ll, rr); + for (i = 16; i > 0; i--) { + FF(i, ll, rr, LL, RR,k); + for (j = 0; j < 32; j++) { + ll[j] = LL[j]; + rr[j] = RR[j]; + } + } + _Fiip(tmp, rr, ll); + Fcompress0(tmp, text); +} + +void FDES(u_char *key, u_char *text, u_char *mtext, u_char k[17][48]) +{ + u_char tmp[64]; + Fexpand0(key, tmp); + Fsetkeystar(tmp,k); + Fencrypt0(text, mtext,k); +} + +void _FDES(u_char *key, u_char *mtext, u_char *text,u_char k[17][48]) +{ + u_char tmp[64]; + Fexpand0(key, tmp); + Fsetkeystar(tmp,k); + Fdiscrypt0(mtext, text,k); +} +} + +namespace TEAcrypt { +const u_char TEA_key[16] = { 0x02, 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, + 0x09, 0x09, 0x0A, 0x0A, 0x0B, 0x0B, 0x0C, 0x0C }; +#define MX (z>>5^y<<2)+(y>>3^z<<4)^(sum^y)+(k[p&3^e]^z) +#define DELTA 0x9e3779b9 +#define S_LOOPTIME 1 //5 +#define BLOCK_SIZE 31 //PAGE_SIZE,根据你所要加密的数据包长度修改此参数(单位:字节) + +void btea_encrypt(u_char* buf, u_char len) +{ + u_char n = len >> 2; + u_long *v = (u_long *) buf; + u_long *k = (u_long *) TEA_key; + u_long z = v[n - 1], y = v[0], sum = 0, e; + u_char p, q; + // Coding Part + if (n == 0) { + return; + } + q = S_LOOPTIME + 52 / n; + while (q-- > 0) { + sum += DELTA; + e = sum >> 2 & 3; + for (p = 0; p < n - 1; p++) + y = v[p + 1], z = v[p] += MX; + y = v[0]; + z = v[n - 1] += MX; + } +} + +void btea_decrpyt(u_char* buf, u_char len) +{ + u_char n = len >> 2; + u_long *v = (u_long *) buf; + u_long *k = (u_long *) TEA_key; + u_long z = v[n - 1], y = v[0], sum = 0, e; + u_char p, q; + //Decoding Part... + if (n == 0) { + return; + } + q = S_LOOPTIME + 52 / n; + sum = q * DELTA; + while (sum != 0) { + e = sum >> 2 & 3; + for (p = n - 1; p > 0; p--) + z = v[p - 1], y = v[p] -= MX; + z = v[n - 1]; + y = v[0] -= MX; + sum -= DELTA; + } +} +} + +namespace MD5crypt { +typedef struct { + u_long i[2]; /* number of _bits_ handled mod 2^64 */ + u_long buf[4]; /* scratch buffer */ + unsigned char in[64]; /* input buffer */ + unsigned char digest[16]; /* actual digest after MD5Final call */ +} MD5_CTX; + +unsigned char PADDING[64] = { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + +/* F, G and H are basic MD5 functions: selection, majority, parity */ +#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) +#define G(x, y, z) (((x) & (z)) | ((y) & (~z))) +#define H(x, y, z) ((x) ^ (y) ^ (z)) +#define I(x, y, z) ((y) ^ ((x) | (~z))) + +/* ROTATE_LEFT rotates x left n bits */ +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) + +/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4 */ +/* Rotation is separate from addition to prevent recomputation */ +#define FF(a, b, c, d, x, s, ac) \ +{(a) += F ((b), (c), (d)) + (x) + (u_long)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ +} +#define GG(a, b, c, d, x, s, ac) \ +{(a) += G ((b), (c), (d)) + (x) + (u_long)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ +} +#define HH(a, b, c, d, x, s, ac) \ +{(a) += H ((b), (c), (d)) + (x) + (u_long)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ +} +#define II(a, b, c, d, x, s, ac) \ +{(a) += I ((b), (c), (d)) + (x) + (u_long)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ +} + +/* Basic MD5 step. Transform buf based on in. + */ +void Transform(u_long *buf, u_long *in) { + u_long a = buf[0], b = buf[1], c = buf[2], d = buf[3]; + + /* Round 1 */ +#define S11 7 +#define S12 12 +#define S13 17 +#define S14 22 + FF ( a, b, c, d, in[ 0], S11, 3614090360UL); /* 1 */ + FF ( d, a, b, c, in[ 1], S12, 3905402710UL); /* 2 */ + FF ( c, d, a, b, in[ 2], S13, 606105819UL); /* 3 */ + FF ( b, c, d, a, in[ 3], S14, 3250441966UL); /* 4 */ + FF ( a, b, c, d, in[ 4], S11, 4118548399UL); /* 5 */ + FF ( d, a, b, c, in[ 5], S12, 1200080426UL); /* 6 */ + FF ( c, d, a, b, in[ 6], S13, 2821735955UL); /* 7 */ + FF ( b, c, d, a, in[ 7], S14, 4249261313UL); /* 8 */ + FF ( a, b, c, d, in[ 8], S11, 1770035416UL); /* 9 */ + FF ( d, a, b, c, in[ 9], S12, 2336552879UL); /* 10 */ + FF ( c, d, a, b, in[10], S13, 4294925233UL); /* 11 */ + FF ( b, c, d, a, in[11], S14, 2304563134UL); /* 12 */ + FF ( a, b, c, d, in[12], S11, 1804603682UL); /* 13 */ + FF ( d, a, b, c, in[13], S12, 4254626195UL); /* 14 */ + FF ( c, d, a, b, in[14], S13, 2792965006UL); /* 15 */ + FF ( b, c, d, a, in[15], S14, 1236535329UL); /* 16 */ + + /* Round 2 */ +#define S21 5 +#define S22 9 +#define S23 14 +#define S24 20 + GG ( a, b, c, d, in[ 1], S21, 4129170786UL); /* 17 */ + GG ( d, a, b, c, in[ 6], S22, 3225465664UL); /* 18 */ + GG ( c, d, a, b, in[11], S23, 643717713UL); /* 19 */ + GG ( b, c, d, a, in[ 0], S24, 3921069994UL); /* 20 */ + GG ( a, b, c, d, in[ 5], S21, 3593408605UL); /* 21 */ + GG ( d, a, b, c, in[10], S22, 38016083UL); /* 22 */ + GG ( c, d, a, b, in[15], S23, 3634488961UL); /* 23 */ + GG ( b, c, d, a, in[ 4], S24, 3889429448UL); /* 24 */ + GG ( a, b, c, d, in[ 9], S21, 568446438UL); /* 25 */ + GG ( d, a, b, c, in[14], S22, 3275163606UL); /* 26 */ + GG ( c, d, a, b, in[ 3], S23, 4107603335UL); /* 27 */ + GG ( b, c, d, a, in[ 8], S24, 1163531501UL); /* 28 */ + GG ( a, b, c, d, in[13], S21, 2850285829UL); /* 29 */ + GG ( d, a, b, c, in[ 2], S22, 4243563512UL); /* 30 */ + GG ( c, d, a, b, in[ 7], S23, 1735328473UL); /* 31 */ + GG ( b, c, d, a, in[12], S24, 2368359562UL); /* 32 */ + + /* Round 3 */ +#define S31 4 +#define S32 11 +#define S33 16 +#define S34 23 + HH ( a, b, c, d, in[ 5], S31, 4294588738UL); /* 33 */ + HH ( d, a, b, c, in[ 8], S32, 2272392833UL); /* 34 */ + HH ( c, d, a, b, in[11], S33, 1839030562UL); /* 35 */ + HH ( b, c, d, a, in[14], S34, 4259657740UL); /* 36 */ + HH ( a, b, c, d, in[ 1], S31, 2763975236UL); /* 37 */ + HH ( d, a, b, c, in[ 4], S32, 1272893353UL); /* 38 */ + HH ( c, d, a, b, in[ 7], S33, 4139469664UL); /* 39 */ + HH ( b, c, d, a, in[10], S34, 3200236656UL); /* 40 */ + HH ( a, b, c, d, in[13], S31, 681279174UL); /* 41 */ + HH ( d, a, b, c, in[ 0], S32, 3936430074UL); /* 42 */ + HH ( c, d, a, b, in[ 3], S33, 3572445317UL); /* 43 */ + HH ( b, c, d, a, in[ 6], S34, 76029189UL); /* 44 */ + HH ( a, b, c, d, in[ 9], S31, 3654602809UL); /* 45 */ + HH ( d, a, b, c, in[12], S32, 3873151461UL); /* 46 */ + HH ( c, d, a, b, in[15], S33, 530742520UL); /* 47 */ + HH ( b, c, d, a, in[ 2], S34, 3299628645UL); /* 48 */ + + /* Round 4 */ +#define S41 6 +#define S42 10 +#define S43 15 +#define S44 21 + II ( a, b, c, d, in[ 0], S41, 4096336452UL); /* 49 */ + II ( d, a, b, c, in[ 7], S42, 1126891415UL); /* 50 */ + II ( c, d, a, b, in[14], S43, 2878612391UL); /* 51 */ + II ( b, c, d, a, in[ 5], S44, 4237533241UL); /* 52 */ + II ( a, b, c, d, in[12], S41, 1700485571UL); /* 53 */ + II ( d, a, b, c, in[ 3], S42, 2399980690UL); /* 54 */ + II ( c, d, a, b, in[10], S43, 4293915773UL); /* 55 */ + II ( b, c, d, a, in[ 1], S44, 2240044497UL); /* 56 */ + II ( a, b, c, d, in[ 8], S41, 1873313359UL); /* 57 */ + II ( d, a, b, c, in[15], S42, 4264355552UL); /* 58 */ + II ( c, d, a, b, in[ 6], S43, 2734768916UL); /* 59 */ + II ( b, c, d, a, in[13], S44, 1309151649UL); /* 60 */ + II ( a, b, c, d, in[ 4], S41, 4149444226UL); /* 61 */ + II ( d, a, b, c, in[11], S42, 3174756917UL); /* 62 */ + II ( c, d, a, b, in[ 2], S43, 718787259UL); /* 63 */ + II ( b, c, d, a, in[ 9], S44, 3951481745UL); /* 64 */ + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +} + +void MD5Init(MD5_CTX *mdContext) +{ + mdContext->i[0] = mdContext->i[1] = (u_long) 0; + + /* Load magic initialization constants. + */ + mdContext->buf[0] = (u_long) 0x67452301; + mdContext->buf[1] = (u_long) 0xefcdab89; + mdContext->buf[2] = (u_long) 0x98badcfe; + mdContext->buf[3] = (u_long) 0x10325476; +} + +void MD5Update(MD5_CTX *mdContext, unsigned char *inBuf, unsigned int inLen) +{ + u_long in[16]; + int mdi; + unsigned int i, ii; + + /* compute number of bytes mod 64 */ + mdi = (int) ((mdContext->i[0] >> 3) & 0x3F); + + /* update number of bits */ + if ((mdContext->i[0] + ((u_long) inLen << 3)) < mdContext->i[0]) + mdContext->i[1]++; + mdContext->i[0] += ((u_long) inLen << 3); + mdContext->i[1] += ((u_long) inLen >> 29); + + while (inLen--) { + /* add new character to buffer, increment mdi */ + mdContext->in[mdi++] = *inBuf++; + + /* transform if necessary */ + if (mdi == 0x40) { + for (i = 0, ii = 0; i < 16; i++, ii += 4) + in[i] = (((u_long) mdContext->in[ii + 3]) << 24) + | (((u_long) mdContext->in[ii + 2]) << 16) + | (((u_long) mdContext->in[ii + 1]) << 8) + | ((u_long) mdContext->in[ii]); + Transform(mdContext->buf, in); + mdi = 0; + } + } +} + +void MD5Final(MD5_CTX *mdContext) +{ + u_long in[16]; + int mdi; + unsigned int i, ii; + unsigned int padLen; + + /* save number of bits */ + in[14] = mdContext->i[0]; + in[15] = mdContext->i[1]; + + /* compute number of bytes mod 64 */ + mdi = (int) ((mdContext->i[0] >> 3) & 0x3F); + + /* pad out to 56 mod 64 */ + padLen = (mdi < 56) ? (56 - mdi) : (120 - mdi); + MD5Update(mdContext, PADDING, padLen); + + /* append length in bits and transform */ + for (i = 0, ii = 0; i < 14; i++, ii += 4) + in[i] = (((u_long) mdContext->in[ii + 3]) << 24) + | (((u_long) mdContext->in[ii + 2]) << 16) + | (((u_long) mdContext->in[ii + 1]) << 8) + | ((u_long) mdContext->in[ii]); + Transform(mdContext->buf, in); + + /* store buffer in digest */ + for (i = 0, ii = 0; i < 4; i++, ii += 4) { + mdContext->digest[ii] = (unsigned char) (mdContext->buf[i] & 0xFF); + mdContext->digest[ii + 1] = (unsigned char) ((mdContext->buf[i] >> 8) + & 0xFF); + mdContext->digest[ii + 2] = (unsigned char) ((mdContext->buf[i] >> 16) + & 0xFF); + mdContext->digest[ii + 3] = (unsigned char) ((mdContext->buf[i] >> 24) + & 0xFF); + } +} + +} + + +namespace AEScrypt { + +/* +* Forward S-box +*/ +static const unsigned char FSb[256] = +{ + 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, + 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, + 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, + 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, + 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, + 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, + 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, + 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, + 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, + 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, + 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, + 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, + 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, + 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, + 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, + 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, + 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, + 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, + 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, + 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, + 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, + 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, + 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, + 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, + 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, + 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, + 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, + 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, + 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, + 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, + 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, + 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 +}; + +/* +* Forward tables +*/ +#define FT \ + \ + V(A5,63,63,C6), V(84,7C,7C,F8), V(99,77,77,EE), V(8D,7B,7B,F6), \ + V(0D,F2,F2,FF), V(BD,6B,6B,D6), V(B1,6F,6F,DE), V(54,C5,C5,91), \ + V(50,30,30,60), V(03,01,01,02), V(A9,67,67,CE), V(7D,2B,2B,56), \ + V(19,FE,FE,E7), V(62,D7,D7,B5), V(E6,AB,AB,4D), V(9A,76,76,EC), \ + V(45,CA,CA,8F), V(9D,82,82,1F), V(40,C9,C9,89), V(87,7D,7D,FA), \ + V(15,FA,FA,EF), V(EB,59,59,B2), V(C9,47,47,8E), V(0B,F0,F0,FB), \ + V(EC,AD,AD,41), V(67,D4,D4,B3), V(FD,A2,A2,5F), V(EA,AF,AF,45), \ + V(BF,9C,9C,23), V(F7,A4,A4,53), V(96,72,72,E4), V(5B,C0,C0,9B), \ + V(C2,B7,B7,75), V(1C,FD,FD,E1), V(AE,93,93,3D), V(6A,26,26,4C), \ + V(5A,36,36,6C), V(41,3F,3F,7E), V(02,F7,F7,F5), V(4F,CC,CC,83), \ + V(5C,34,34,68), V(F4,A5,A5,51), V(34,E5,E5,D1), V(08,F1,F1,F9), \ + V(93,71,71,E2), V(73,D8,D8,AB), V(53,31,31,62), V(3F,15,15,2A), \ + V(0C,04,04,08), V(52,C7,C7,95), V(65,23,23,46), V(5E,C3,C3,9D), \ + V(28,18,18,30), V(A1,96,96,37), V(0F,05,05,0A), V(B5,9A,9A,2F), \ + V(09,07,07,0E), V(36,12,12,24), V(9B,80,80,1B), V(3D,E2,E2,DF), \ + V(26,EB,EB,CD), V(69,27,27,4E), V(CD,B2,B2,7F), V(9F,75,75,EA), \ + V(1B,09,09,12), V(9E,83,83,1D), V(74,2C,2C,58), V(2E,1A,1A,34), \ + V(2D,1B,1B,36), V(B2,6E,6E,DC), V(EE,5A,5A,B4), V(FB,A0,A0,5B), \ + V(F6,52,52,A4), V(4D,3B,3B,76), V(61,D6,D6,B7), V(CE,B3,B3,7D), \ + V(7B,29,29,52), V(3E,E3,E3,DD), V(71,2F,2F,5E), V(97,84,84,13), \ + V(F5,53,53,A6), V(68,D1,D1,B9), V(00,00,00,00), V(2C,ED,ED,C1), \ + V(60,20,20,40), V(1F,FC,FC,E3), V(C8,B1,B1,79), V(ED,5B,5B,B6), \ + V(BE,6A,6A,D4), V(46,CB,CB,8D), V(D9,BE,BE,67), V(4B,39,39,72), \ + V(DE,4A,4A,94), V(D4,4C,4C,98), V(E8,58,58,B0), V(4A,CF,CF,85), \ + V(6B,D0,D0,BB), V(2A,EF,EF,C5), V(E5,AA,AA,4F), V(16,FB,FB,ED), \ + V(C5,43,43,86), V(D7,4D,4D,9A), V(55,33,33,66), V(94,85,85,11), \ + V(CF,45,45,8A), V(10,F9,F9,E9), V(06,02,02,04), V(81,7F,7F,FE), \ + V(F0,50,50,A0), V(44,3C,3C,78), V(BA,9F,9F,25), V(E3,A8,A8,4B), \ + V(F3,51,51,A2), V(FE,A3,A3,5D), V(C0,40,40,80), V(8A,8F,8F,05), \ + V(AD,92,92,3F), V(BC,9D,9D,21), V(48,38,38,70), V(04,F5,F5,F1), \ + V(DF,BC,BC,63), V(C1,B6,B6,77), V(75,DA,DA,AF), V(63,21,21,42), \ + V(30,10,10,20), V(1A,FF,FF,E5), V(0E,F3,F3,FD), V(6D,D2,D2,BF), \ + V(4C,CD,CD,81), V(14,0C,0C,18), V(35,13,13,26), V(2F,EC,EC,C3), \ + V(E1,5F,5F,BE), V(A2,97,97,35), V(CC,44,44,88), V(39,17,17,2E), \ + V(57,C4,C4,93), V(F2,A7,A7,55), V(82,7E,7E,FC), V(47,3D,3D,7A), \ + V(AC,64,64,C8), V(E7,5D,5D,BA), V(2B,19,19,32), V(95,73,73,E6), \ + V(A0,60,60,C0), V(98,81,81,19), V(D1,4F,4F,9E), V(7F,DC,DC,A3), \ + V(66,22,22,44), V(7E,2A,2A,54), V(AB,90,90,3B), V(83,88,88,0B), \ + V(CA,46,46,8C), V(29,EE,EE,C7), V(D3,B8,B8,6B), V(3C,14,14,28), \ + V(79,DE,DE,A7), V(E2,5E,5E,BC), V(1D,0B,0B,16), V(76,DB,DB,AD), \ + V(3B,E0,E0,DB), V(56,32,32,64), V(4E,3A,3A,74), V(1E,0A,0A,14), \ + V(DB,49,49,92), V(0A,06,06,0C), V(6C,24,24,48), V(E4,5C,5C,B8), \ + V(5D,C2,C2,9F), V(6E,D3,D3,BD), V(EF,AC,AC,43), V(A6,62,62,C4), \ + V(A8,91,91,39), V(A4,95,95,31), V(37,E4,E4,D3), V(8B,79,79,F2), \ + V(32,E7,E7,D5), V(43,C8,C8,8B), V(59,37,37,6E), V(B7,6D,6D,DA), \ + V(8C,8D,8D,01), V(64,D5,D5,B1), V(D2,4E,4E,9C), V(E0,A9,A9,49), \ + V(B4,6C,6C,D8), V(FA,56,56,AC), V(07,F4,F4,F3), V(25,EA,EA,CF), \ + V(AF,65,65,CA), V(8E,7A,7A,F4), V(E9,AE,AE,47), V(18,08,08,10), \ + V(D5,BA,BA,6F), V(88,78,78,F0), V(6F,25,25,4A), V(72,2E,2E,5C), \ + V(24,1C,1C,38), V(F1,A6,A6,57), V(C7,B4,B4,73), V(51,C6,C6,97), \ + V(23,E8,E8,CB), V(7C,DD,DD,A1), V(9C,74,74,E8), V(21,1F,1F,3E), \ + V(DD,4B,4B,96), V(DC,BD,BD,61), V(86,8B,8B,0D), V(85,8A,8A,0F), \ + V(90,70,70,E0), V(42,3E,3E,7C), V(C4,B5,B5,71), V(AA,66,66,CC), \ + V(D8,48,48,90), V(05,03,03,06), V(01,F6,F6,F7), V(12,0E,0E,1C), \ + V(A3,61,61,C2), V(5F,35,35,6A), V(F9,57,57,AE), V(D0,B9,B9,69), \ + V(91,86,86,17), V(58,C1,C1,99), V(27,1D,1D,3A), V(B9,9E,9E,27), \ + V(38,E1,E1,D9), V(13,F8,F8,EB), V(B3,98,98,2B), V(33,11,11,22), \ + V(BB,69,69,D2), V(70,D9,D9,A9), V(89,8E,8E,07), V(A7,94,94,33), \ + V(B6,9B,9B,2D), V(22,1E,1E,3C), V(92,87,87,15), V(20,E9,E9,C9), \ + V(49,CE,CE,87), V(FF,55,55,AA), V(78,28,28,50), V(7A,DF,DF,A5), \ + V(8F,8C,8C,03), V(F8,A1,A1,59), V(80,89,89,09), V(17,0D,0D,1A), \ + V(DA,BF,BF,65), V(31,E6,E6,D7), V(C6,42,42,84), V(B8,68,68,D0), \ + V(C3,41,41,82), V(B0,99,99,29), V(77,2D,2D,5A), V(11,0F,0F,1E), \ + V(CB,B0,B0,7B), V(FC,54,54,A8), V(D6,BB,BB,6D), V(3A,16,16,2C) + +#define V(a,b,c,d) 0x##a##b##c##d +static const unsigned int FT0[256] = { FT }; +#undef V + +#define V(a,b,c,d) 0x##b##c##d##a +static const unsigned int FT1[256] = { FT }; +#undef V + +#define V(a,b,c,d) 0x##c##d##a##b +static const unsigned int FT2[256] = { FT }; +#undef V + +#define V(a,b,c,d) 0x##d##a##b##c +static const unsigned int FT3[256] = { FT }; +#undef V + +#undef FT + +/* +* Reverse S-box +*/ +static const unsigned char RSb[256] = +{ + 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, + 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, + 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, + 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, + 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, + 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, + 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, + 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, + 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, + 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, + 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, + 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, + 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, + 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, + 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, + 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, + 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, + 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, + 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, + 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, + 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, + 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, + 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, + 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, + 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, + 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, + 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, + 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, + 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, + 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, + 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D +}; + +/* +* Reverse tables +*/ +#define RT \ + \ + V(50,A7,F4,51), V(53,65,41,7E), V(C3,A4,17,1A), V(96,5E,27,3A), \ + V(CB,6B,AB,3B), V(F1,45,9D,1F), V(AB,58,FA,AC), V(93,03,E3,4B), \ + V(55,FA,30,20), V(F6,6D,76,AD), V(91,76,CC,88), V(25,4C,02,F5), \ + V(FC,D7,E5,4F), V(D7,CB,2A,C5), V(80,44,35,26), V(8F,A3,62,B5), \ + V(49,5A,B1,DE), V(67,1B,BA,25), V(98,0E,EA,45), V(E1,C0,FE,5D), \ + V(02,75,2F,C3), V(12,F0,4C,81), V(A3,97,46,8D), V(C6,F9,D3,6B), \ + V(E7,5F,8F,03), V(95,9C,92,15), V(EB,7A,6D,BF), V(DA,59,52,95), \ + V(2D,83,BE,D4), V(D3,21,74,58), V(29,69,E0,49), V(44,C8,C9,8E), \ + V(6A,89,C2,75), V(78,79,8E,F4), V(6B,3E,58,99), V(DD,71,B9,27), \ + V(B6,4F,E1,BE), V(17,AD,88,F0), V(66,AC,20,C9), V(B4,3A,CE,7D), \ + V(18,4A,DF,63), V(82,31,1A,E5), V(60,33,51,97), V(45,7F,53,62), \ + V(E0,77,64,B1), V(84,AE,6B,BB), V(1C,A0,81,FE), V(94,2B,08,F9), \ + V(58,68,48,70), V(19,FD,45,8F), V(87,6C,DE,94), V(B7,F8,7B,52), \ + V(23,D3,73,AB), V(E2,02,4B,72), V(57,8F,1F,E3), V(2A,AB,55,66), \ + V(07,28,EB,B2), V(03,C2,B5,2F), V(9A,7B,C5,86), V(A5,08,37,D3), \ + V(F2,87,28,30), V(B2,A5,BF,23), V(BA,6A,03,02), V(5C,82,16,ED), \ + V(2B,1C,CF,8A), V(92,B4,79,A7), V(F0,F2,07,F3), V(A1,E2,69,4E), \ + V(CD,F4,DA,65), V(D5,BE,05,06), V(1F,62,34,D1), V(8A,FE,A6,C4), \ + V(9D,53,2E,34), V(A0,55,F3,A2), V(32,E1,8A,05), V(75,EB,F6,A4), \ + V(39,EC,83,0B), V(AA,EF,60,40), V(06,9F,71,5E), V(51,10,6E,BD), \ + V(F9,8A,21,3E), V(3D,06,DD,96), V(AE,05,3E,DD), V(46,BD,E6,4D), \ + V(B5,8D,54,91), V(05,5D,C4,71), V(6F,D4,06,04), V(FF,15,50,60), \ + V(24,FB,98,19), V(97,E9,BD,D6), V(CC,43,40,89), V(77,9E,D9,67), \ + V(BD,42,E8,B0), V(88,8B,89,07), V(38,5B,19,E7), V(DB,EE,C8,79), \ + V(47,0A,7C,A1), V(E9,0F,42,7C), V(C9,1E,84,F8), V(00,00,00,00), \ + V(83,86,80,09), V(48,ED,2B,32), V(AC,70,11,1E), V(4E,72,5A,6C), \ + V(FB,FF,0E,FD), V(56,38,85,0F), V(1E,D5,AE,3D), V(27,39,2D,36), \ + V(64,D9,0F,0A), V(21,A6,5C,68), V(D1,54,5B,9B), V(3A,2E,36,24), \ + V(B1,67,0A,0C), V(0F,E7,57,93), V(D2,96,EE,B4), V(9E,91,9B,1B), \ + V(4F,C5,C0,80), V(A2,20,DC,61), V(69,4B,77,5A), V(16,1A,12,1C), \ + V(0A,BA,93,E2), V(E5,2A,A0,C0), V(43,E0,22,3C), V(1D,17,1B,12), \ + V(0B,0D,09,0E), V(AD,C7,8B,F2), V(B9,A8,B6,2D), V(C8,A9,1E,14), \ + V(85,19,F1,57), V(4C,07,75,AF), V(BB,DD,99,EE), V(FD,60,7F,A3), \ + V(9F,26,01,F7), V(BC,F5,72,5C), V(C5,3B,66,44), V(34,7E,FB,5B), \ + V(76,29,43,8B), V(DC,C6,23,CB), V(68,FC,ED,B6), V(63,F1,E4,B8), \ + V(CA,DC,31,D7), V(10,85,63,42), V(40,22,97,13), V(20,11,C6,84), \ + V(7D,24,4A,85), V(F8,3D,BB,D2), V(11,32,F9,AE), V(6D,A1,29,C7), \ + V(4B,2F,9E,1D), V(F3,30,B2,DC), V(EC,52,86,0D), V(D0,E3,C1,77), \ + V(6C,16,B3,2B), V(99,B9,70,A9), V(FA,48,94,11), V(22,64,E9,47), \ + V(C4,8C,FC,A8), V(1A,3F,F0,A0), V(D8,2C,7D,56), V(EF,90,33,22), \ + V(C7,4E,49,87), V(C1,D1,38,D9), V(FE,A2,CA,8C), V(36,0B,D4,98), \ + V(CF,81,F5,A6), V(28,DE,7A,A5), V(26,8E,B7,DA), V(A4,BF,AD,3F), \ + V(E4,9D,3A,2C), V(0D,92,78,50), V(9B,CC,5F,6A), V(62,46,7E,54), \ + V(C2,13,8D,F6), V(E8,B8,D8,90), V(5E,F7,39,2E), V(F5,AF,C3,82), \ + V(BE,80,5D,9F), V(7C,93,D0,69), V(A9,2D,D5,6F), V(B3,12,25,CF), \ + V(3B,99,AC,C8), V(A7,7D,18,10), V(6E,63,9C,E8), V(7B,BB,3B,DB), \ + V(09,78,26,CD), V(F4,18,59,6E), V(01,B7,9A,EC), V(A8,9A,4F,83), \ + V(65,6E,95,E6), V(7E,E6,FF,AA), V(08,CF,BC,21), V(E6,E8,15,EF), \ + V(D9,9B,E7,BA), V(CE,36,6F,4A), V(D4,09,9F,EA), V(D6,7C,B0,29), \ + V(AF,B2,A4,31), V(31,23,3F,2A), V(30,94,A5,C6), V(C0,66,A2,35), \ + V(37,BC,4E,74), V(A6,CA,82,FC), V(B0,D0,90,E0), V(15,D8,A7,33), \ + V(4A,98,04,F1), V(F7,DA,EC,41), V(0E,50,CD,7F), V(2F,F6,91,17), \ + V(8D,D6,4D,76), V(4D,B0,EF,43), V(54,4D,AA,CC), V(DF,04,96,E4), \ + V(E3,B5,D1,9E), V(1B,88,6A,4C), V(B8,1F,2C,C1), V(7F,51,65,46), \ + V(04,EA,5E,9D), V(5D,35,8C,01), V(73,74,87,FA), V(2E,41,0B,FB), \ + V(5A,1D,67,B3), V(52,D2,DB,92), V(33,56,10,E9), V(13,47,D6,6D), \ + V(8C,61,D7,9A), V(7A,0C,A1,37), V(8E,14,F8,59), V(89,3C,13,EB), \ + V(EE,27,A9,CE), V(35,C9,61,B7), V(ED,E5,1C,E1), V(3C,B1,47,7A), \ + V(59,DF,D2,9C), V(3F,73,F2,55), V(79,CE,14,18), V(BF,37,C7,73), \ + V(EA,CD,F7,53), V(5B,AA,FD,5F), V(14,6F,3D,DF), V(86,DB,44,78), \ + V(81,F3,AF,CA), V(3E,C4,68,B9), V(2C,34,24,38), V(5F,40,A3,C2), \ + V(72,C3,1D,16), V(0C,25,E2,BC), V(8B,49,3C,28), V(41,95,0D,FF), \ + V(71,01,A8,39), V(DE,B3,0C,08), V(9C,E4,B4,D8), V(90,C1,56,64), \ + V(61,84,CB,7B), V(70,B6,32,D5), V(74,5C,6C,48), V(42,57,B8,D0) + +#define V(a,b,c,d) 0x##a##b##c##d +static const unsigned int RT0[256] = { RT }; +#undef V + +#define V(a,b,c,d) 0x##b##c##d##a +static const unsigned int RT1[256] = { RT }; +#undef V + +#define V(a,b,c,d) 0x##c##d##a##b +static const unsigned int RT2[256] = { RT }; +#undef V + +#define V(a,b,c,d) 0x##d##a##b##c +static const unsigned int RT3[256] = { RT }; +#undef V + +#undef RT + +/* +* Round constants +*/ +static const unsigned int RCON[10] = +{ + 0x00000001, 0x00000002, 0x00000004, 0x00000008, + 0x00000010, 0x00000020, 0x00000040, 0x00000080, + 0x0000001B, 0x00000036 +}; + +#define AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ + { \ + X0 = *RK++ ^ FT0[ ( Y0 ) & 0xFF ] ^ \ + FT1[ ( Y1 >> 8 ) & 0xFF ] ^ \ + FT2[ ( Y2 >> 16 ) & 0xFF ] ^ \ + FT3[ ( Y3 >> 24 ) & 0xFF ]; \ + \ + X1 = *RK++ ^ FT0[ ( Y1 ) & 0xFF ] ^ \ + FT1[ ( Y2 >> 8 ) & 0xFF ] ^ \ + FT2[ ( Y3 >> 16 ) & 0xFF ] ^ \ + FT3[ ( Y0 >> 24 ) & 0xFF ]; \ + \ + X2 = *RK++ ^ FT0[ ( Y2 ) & 0xFF ] ^ \ + FT1[ ( Y3 >> 8 ) & 0xFF ] ^ \ + FT2[ ( Y0 >> 16 ) & 0xFF ] ^ \ + FT3[ ( Y1 >> 24 ) & 0xFF ]; \ + \ + X3 = *RK++ ^ FT0[ ( Y3 ) & 0xFF ] ^ \ + FT1[ ( Y0 >> 8 ) & 0xFF ] ^ \ + FT2[ ( Y1 >> 16 ) & 0xFF ] ^ \ + FT3[ ( Y2 >> 24 ) & 0xFF ]; \ + } + +#define AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ + { \ + X0 = *RK++ ^ RT0[ ( Y0 ) & 0xFF ] ^ \ + RT1[ ( Y3 >> 8 ) & 0xFF ] ^ \ + RT2[ ( Y2 >> 16 ) & 0xFF ] ^ \ + RT3[ ( Y1 >> 24 ) & 0xFF ]; \ + \ + X1 = *RK++ ^ RT0[ ( Y1 ) & 0xFF ] ^ \ + RT1[ ( Y0 >> 8 ) & 0xFF ] ^ \ + RT2[ ( Y3 >> 16 ) & 0xFF ] ^ \ + RT3[ ( Y2 >> 24 ) & 0xFF ]; \ + \ + X2 = *RK++ ^ RT0[ ( Y2 ) & 0xFF ] ^ \ + RT1[ ( Y1 >> 8 ) & 0xFF ] ^ \ + RT2[ ( Y0 >> 16 ) & 0xFF ] ^ \ + RT3[ ( Y3 >> 24 ) & 0xFF ]; \ + \ + X3 = *RK++ ^ RT0[ ( Y3 ) & 0xFF ] ^ \ + RT1[ ( Y2 >> 8 ) & 0xFF ] ^ \ + RT2[ ( Y1 >> 16 ) & 0xFF ] ^ \ + RT3[ ( Y0 >> 24 ) & 0xFF ]; \ + } + +void aes_crypt_ecb_update(Secure::aes_context* ctx, int mode, const unsigned char input[16], unsigned char output[16]) +{ + int i; + unsigned int* RK; + unsigned int X[4], Y[4]; + + RK = ctx->rk; + + for (i = 0; i < 4; i++) + { + X[i] = (*((unsigned int*)input + i)) ^ (*RK++); + } + + if (mode == AES_DECRYPT) + { + for (i = (ctx->nr >> 1) - 1; i > 0; i--) + { + AES_RROUND(Y[0], Y[1], Y[2], Y[3], X[0], X[1], X[2], X[3]); + AES_RROUND(X[0], X[1], X[2], X[3], Y[0], Y[1], Y[2], Y[3]); + } + + AES_RROUND(Y[0], Y[1], Y[2], Y[3], X[0], X[1], X[2], X[3]); + + X[0] = *RK++ ^ \ + ((unsigned int)RSb[(Y[0]) & 0xFF]) ^ + ((unsigned int)RSb[(Y[3] >> 8) & 0xFF] << 8) ^ + ((unsigned int)RSb[(Y[2] >> 16) & 0xFF] << 16) ^ + ((unsigned int)RSb[(Y[1] >> 24) & 0xFF] << 24); + + X[1] = *RK++ ^ \ + ((unsigned int)RSb[(Y[1]) & 0xFF]) ^ + ((unsigned int)RSb[(Y[0] >> 8) & 0xFF] << 8) ^ + ((unsigned int)RSb[(Y[3] >> 16) & 0xFF] << 16) ^ + ((unsigned int)RSb[(Y[2] >> 24) & 0xFF] << 24); + + X[2] = *RK++ ^ \ + ((unsigned int)RSb[(Y[2]) & 0xFF]) ^ + ((unsigned int)RSb[(Y[1] >> 8) & 0xFF] << 8) ^ + ((unsigned int)RSb[(Y[0] >> 16) & 0xFF] << 16) ^ + ((unsigned int)RSb[(Y[3] >> 24) & 0xFF] << 24); + + X[3] = *RK++ ^ \ + ((unsigned int)RSb[(Y[3]) & 0xFF]) ^ + ((unsigned int)RSb[(Y[2] >> 8) & 0xFF] << 8) ^ + ((unsigned int)RSb[(Y[1] >> 16) & 0xFF] << 16) ^ + ((unsigned int)RSb[(Y[0] >> 24) & 0xFF] << 24); + } + else /* AES_ENCRYPT */ + { + for (i = (ctx->nr >> 1) - 1; i > 0; i--) + { + AES_FROUND(Y[0], Y[1], Y[2], Y[3], X[0], X[1], X[2], X[3]); + AES_FROUND(X[0], X[1], X[2], X[3], Y[0], Y[1], Y[2], Y[3]); + } + + AES_FROUND(Y[0], Y[1], Y[2], Y[3], X[0], X[1], X[2], X[3]); + + X[0] = *RK++ ^ \ + ((unsigned int)FSb[(Y[0]) & 0xFF]) ^ + ((unsigned int)FSb[(Y[1] >> 8) & 0xFF] << 8) ^ + ((unsigned int)FSb[(Y[2] >> 16) & 0xFF] << 16) ^ + ((unsigned int)FSb[(Y[3] >> 24) & 0xFF] << 24); + + X[1] = *RK++ ^ \ + ((unsigned int)FSb[(Y[1]) & 0xFF]) ^ + ((unsigned int)FSb[(Y[2] >> 8) & 0xFF] << 8) ^ + ((unsigned int)FSb[(Y[3] >> 16) & 0xFF] << 16) ^ + ((unsigned int)FSb[(Y[0] >> 24) & 0xFF] << 24); + + X[2] = *RK++ ^ \ + ((unsigned int)FSb[(Y[2]) & 0xFF]) ^ + ((unsigned int)FSb[(Y[3] >> 8) & 0xFF] << 8) ^ + ((unsigned int)FSb[(Y[0] >> 16) & 0xFF] << 16) ^ + ((unsigned int)FSb[(Y[1] >> 24) & 0xFF] << 24); + + X[3] = *RK++ ^ \ + ((unsigned int)FSb[(Y[3]) & 0xFF]) ^ + ((unsigned int)FSb[(Y[0] >> 8) & 0xFF] << 8) ^ + ((unsigned int)FSb[(Y[1] >> 16) & 0xFF] << 16) ^ + ((unsigned int)FSb[(Y[2] >> 24) & 0xFF] << 24); + } + + memcpy(output, X, 16); +} +} + + + +Secure::Secure() +{ + memset(KEY,0,KEYLen); + memset(result,0,sizeof(result)); +} + +Secure::~Secure() +{ +} + +void Secure::GetKey(std::string gwmac) +{ + std::string keyStr = FnMD5CACL((unsigned char*)(gwmac.c_str()), gwmac.length()); + keyStr= keyStr.substr(0, 8); + strcpy(KEY, keyStr.c_str()); +} + +void Secure::GetKey(char *pKey,std::string pImeiId) +{ + std::string keyStr = FnMD5CACL((unsigned char *) (pImeiId.c_str()), + pImeiId.length()); + keyStr = keyStr.substr(0, 8); + strcpy(pKey, keyStr.c_str()); +} + +char * Secure::Base64Encode(const unsigned char * bindata, char * base64, int binlength) +{ + int i, j; + unsigned char current; + const char * base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + for (i = 0, j = 0; i < binlength; i += 3) + { + current = (bindata[i] >> 2); + current &= (unsigned char)0x3F; + base64[j++] = base64char[(int)current]; + + current = ((unsigned char)(bindata[i] << 4)) & ((unsigned char)0x30); + if (i + 1 >= binlength) + { + base64[j++] = base64char[(int)current]; + base64[j++] = '='; + base64[j++] = '='; + break; + } + current |= ((unsigned char)(bindata[i + 1] >> 4)) & ((unsigned char)0x0F); + base64[j++] = base64char[(int)current]; + + current = ((unsigned char)(bindata[i + 1] << 2)) & ((unsigned char)0x3C); + if (i + 2 >= binlength) + { + base64[j++] = base64char[(int)current]; + base64[j++] = '='; + break; + } + current |= ((unsigned char)(bindata[i + 2] >> 6)) & ((unsigned char)0x03); + base64[j++] = base64char[(int)current]; + + current = ((unsigned char)bindata[i + 2]) & ((unsigned char)0x3F); + base64[j++] = base64char[(int)current]; + } + base64[j] = '\0'; + return base64; +} + +int Secure::Base64Decode( const char * base64, unsigned char * bindata) +{ + int i, j; + unsigned char k; + unsigned char temp[4]; + const char * base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + for ( i = 0, j = 0; base64[i] != '\0' ; i += 4 ) + { + memset( temp, 0xFF, sizeof(temp) ); + for ( k = 0 ; k < 64 ; k ++ ) + { + if ( base64char[k] == base64[i] ) + temp[0]= k; + } + for ( k = 0 ; k < 64 ; k ++ ) + { + if ( base64char[k] == base64[i+1] ) + temp[1]= k; + } + for ( k = 0 ; k < 64 ; k ++ ) + { + if ( base64char[k] == base64[i+2] ) + temp[2]= k; + } + for ( k = 0 ; k < 64 ; k ++ ) + { + if ( base64char[k] == base64[i+3] ) + temp[3]= k; + } + + bindata[j++] = ((unsigned char)(((unsigned char)(temp[0] << 2))&0xFC)) | + ((unsigned char)((unsigned char)(temp[1]>>4)&0x03)); + if ( base64[i+2] == '=' ) + break; + + bindata[j++] = ((unsigned char)(((unsigned char)(temp[1] << 4))&0xF0)) | + ((unsigned char)((unsigned char)(temp[2]>>2)&0x0F)); + if ( base64[i+3] == '=' ) + break; + + bindata[j++] = ((unsigned char)(((unsigned char)(temp[2] << 6))&0xF0)) | + ((unsigned char)(temp[3]&0x3F)); + } + return j; +} + +int Secure::ZigbeeDataEncrypt(char *pData)//zigbee数据加密 +{ + assert(pData!=NULL); + int dataLen = strlen(pData); + if (dataLen > 9) { + if (strstr(pData, "\r\n")) { + dataLen = dataLen - 2; + } + BteaEncrypt((unsigned char *)pData,dataLen); + return dataLen + 2; + } + return dataLen; +} + +int Secure::ZigbeeDataEncrypt_Hex(char *pData, int len)//zigbee数据加密, 限制长度,包含\r\n +{ + assert(pData!=NULL); + int dataLen = len; + if (dataLen > 9) { + dataLen = dataLen - 2; //除去\r\n长度 + BteaEncrypt((unsigned char *)pData,dataLen); + return dataLen + 2; + } + return dataLen; +} + +void Secure::ZigbeeDataDecrypt(char *pData,int pLen)//zigbee数据解密 +{ + assert(pData!=NULL); + //if (pLen > 9) { + BteaDecrpyt((u_char *)pData, pLen - 2); + //} +} + +/* +* pMing : 明文 +* pMi : 密文 +* pKey : key +*/ +int Secure::NetDataEncrypt(char* pMing, char* pMi, char* pKey)//网络数据加密 +{ + int i = 0; + int lenMing = strlen(pMing); + if (strlen(pKey) == 0) { +#ifdef _SOFTWARE_DEBUG_ + strncpy(pMi,pMing,lenMing); + strcat(pMi, "\r\n"); + Length_(lenMing); + return lenMing; +#else + return 0; +#endif + } + int lenMi = lenMing; + char *ming = new char[lenMing + 8];//明文长度,长度不对加密错误 + memset(ming, 0, lenMing + 8); + strncpy(ming,pMing,lenMing); + Length_(lenMi); + char *miTmp = new char[lenMi];//存储密文 + memset(miTmp,0,lenMi); + lenMing = Encrypt((u_char*)ming, (u_char *) miTmp,lenMing, + (u_char *) pKey); + while (i < lenMing) + { + sprintf(&pMi[i*2], "%02X", miTmp[i]&0x00FF); + i++; + } + if (!strstr(pMi, "\r\n")) { + strcat(pMi, "\r\n"); + } + delete[] ming; + delete[] miTmp; + return strlen(pMi); +} + +int Secure::NetDataDecrypt(char* pMing, char* pMi,int pLen,char* pKey)//网络数据解密 +{ + //if ((pMi==NULL)||(pKey==NULL)) + // return -1; + int j, k,buf_len; + buf_len = pLen+1; + char *buff = new char[buf_len]; //中间数据 + memset(buff, 0, buf_len); + char temp[4] = { 0 }; + //密文每2个字节数据(前一字节作为高4 位,后一字节作为低4 位), + //合为1字节数据,然后进行解密如"C1" = C*16+1=109 + for (j = 0, k = 0; j < buf_len && k < buf_len; j += 2, k++) { + strncpy(temp, &pMi[j], 2); + unsigned char ss = strtol(temp, NULL, 16); + buff[k] = ss; + } + Decrypt((u_char *) pMing, (u_char *) buff, k-1, (u_char *) pKey); + delete[] buff; + return k-1; +} + +int Secure::NetDataDecrypt(char* pMing, char* pMi,char* pKey)//网络数据解密 +{ + if ((pMi==NULL)||(pKey==NULL)) + return -1; + int j, k,buf_len; + std::string mi(pMi); + buf_len = strlen(pMi) + 1; + char *buff = new char[buf_len]; //中间数据 + memset(buff, 0, buf_len); + char temp[4] = { 0 }; + //密文每2个字节数据(前一字节作为高4 位,后一字节作为低4 位), + //合为1字节数据,然后进行解密如"C1" = C*16+1=109 + for (j = 0, k = 0; j < buf_len && k < buf_len; j += 2, k++) { + strncpy(temp, mi.substr(j, 2).c_str(), sizeof temp); + unsigned char ss = strtol(temp, NULL, 16); + buff[k] = ss; + } + Decrypt((u_char *) pMing, (u_char *) buff, k-1, (u_char *) pKey); + delete [] buff; + return k-1; +} + +void Secure::aes_setkey_enc(aes_context* ctx, const unsigned char* key, int keysize) +{ + int i; + unsigned int* RK; + + switch (keysize) + { + case 128: + ctx->nr = 10; + break; + case 192: + ctx->nr = 12; + break; + case 256: + ctx->nr = 14; + break; + default: + keysize = 128; + ctx->nr = 10; + break; + } + + ctx->rk = RK = ctx->buf; + + memcpy(RK, key, keysize >> 3); + + switch (ctx->nr) + { + case 10: + for (i = 0; i < 10; i++, RK += 4) + { + RK[4] = RK[0] ^ AEScrypt::RCON[i] ^ + ((unsigned int)AEScrypt::FSb[(RK[3] >> 8) & 0xFF]) ^ + ((unsigned int)AEScrypt::FSb[(RK[3] >> 16) & 0xFF] << 8) ^ + ((unsigned int)AEScrypt::FSb[(RK[3] >> 24) & 0xFF] << 16) ^ + ((unsigned int)AEScrypt::FSb[(RK[3]) & 0xFF] << 24); + + RK[5] = RK[1] ^ RK[4]; + RK[6] = RK[2] ^ RK[5]; + RK[7] = RK[3] ^ RK[6]; + } + break; + case 12: + for (i = 0; i < 8; i++, RK += 6) + { + RK[6] = RK[0] ^ AEScrypt::RCON[i] ^ + ((unsigned int)AEScrypt::FSb[(RK[5] >> 8) & 0xFF]) ^ + ((unsigned int)AEScrypt::FSb[(RK[5] >> 16) & 0xFF] << 8) ^ + ((unsigned int)AEScrypt::FSb[(RK[5] >> 24) & 0xFF] << 16) ^ + ((unsigned int)AEScrypt::FSb[(RK[5]) & 0xFF] << 24); + + RK[7] = RK[1] ^ RK[6]; + RK[8] = RK[2] ^ RK[7]; + RK[9] = RK[3] ^ RK[8]; + RK[10] = RK[4] ^ RK[9]; + RK[11] = RK[5] ^ RK[10]; + } + break; + case 14: + for (i = 0; i < 7; i++, RK += 8) + { + RK[8] = RK[0] ^ AEScrypt::RCON[i] ^ + ((unsigned int)AEScrypt::FSb[(RK[7] >> 8) & 0xFF]) ^ + ((unsigned int)AEScrypt::FSb[(RK[7] >> 16) & 0xFF] << 8) ^ + ((unsigned int)AEScrypt::FSb[(RK[7] >> 24) & 0xFF] << 16) ^ + ((unsigned int)AEScrypt::FSb[(RK[7]) & 0xFF] << 24); + + RK[9] = RK[1] ^ RK[8]; + RK[10] = RK[2] ^ RK[9]; + RK[11] = RK[3] ^ RK[10]; + + RK[12] = RK[4] ^ + ((unsigned int)AEScrypt::FSb[(RK[11]) & 0xFF]) ^ + ((unsigned int)AEScrypt::FSb[(RK[11] >> 8) & 0xFF] << 8) ^ + ((unsigned int)AEScrypt::FSb[(RK[11] >> 16) & 0xFF] << 16) ^ + ((unsigned int)AEScrypt::FSb[(RK[11] >> 24) & 0xFF] << 24); + + RK[13] = RK[5] ^ RK[12]; + RK[14] = RK[6] ^ RK[13]; + RK[15] = RK[7] ^ RK[14]; + } + break; + } +} + + +void Secure::aes_setkey_dec(aes_context* ctx, const unsigned char* key, int keysize) +{ + int i, j; + aes_context cty; + unsigned int* RK; + unsigned int* SK; + + ctx->rk = RK = ctx->buf; + + aes_setkey_enc(&cty, key, keysize); + ctx->nr = cty.nr; + SK = cty.rk + (cty.nr << 2); + + memcpy(RK, SK, sizeof(unsigned int) << 2); + RK += 4; + SK -= 4; + + for (i = ctx->nr - 1; i > 0; i--, SK -= 8) + { + for (j = 0; j < 4; j++, SK++) + { + *RK++ = AEScrypt::RT0[AEScrypt::FSb[(*SK) & 0xFF]] ^ + AEScrypt::RT1[AEScrypt::FSb[(*SK >> 8) & 0xFF]] ^ + AEScrypt::RT2[AEScrypt::FSb[(*SK >> 16) & 0xFF]] ^ + AEScrypt::RT3[AEScrypt::FSb[(*SK >> 24) & 0xFF]]; + } + } + + memcpy(RK, SK, sizeof(unsigned int) << 2); +} + +// free later +unsigned char* Secure::aes_crypt_ecb(aes_context* ctx, int mode, const unsigned char* input, int slen, int* dlen) +{ + register int i; + register int n; + unsigned char* output; + unsigned char buff[16]; + + if (mode == AES_ENCRYPT) + { + n = 16 - (slen & 15); + *dlen = slen + n; + + output = (unsigned char*)malloc(*dlen); + if (!output) + { + return NULL; + } + memset(output, 0, *dlen); + memset(buff, n, sizeof(buff)); + if (slen & 15) + { + memcpy(buff, input + (slen & ~15), slen & 15); + } + + n = (slen >> 4); + for (i = 0; i < n; i++) + { + AEScrypt::aes_crypt_ecb_update(ctx, AES_ENCRYPT, \ + input + (i << 4), output + (i << 4)); + } + AEScrypt::aes_crypt_ecb_update(ctx, AES_ENCRYPT, buff, output + (i << 4)); + } + else + { + output = (unsigned char*)malloc(slen); + if (!output) + { + return NULL; + } + memset(output, 0, *dlen); + n = (slen >> 4); + for (i = 0; i < n; i++) + { + AEScrypt::aes_crypt_ecb_update(ctx, AES_DECRYPT, \ + input + (i << 4), output + (i << 4)); + } + *dlen = slen - (int)output[slen - 1]; + } + + return output; +} + +int Secure::Encrypt(u_char *plaintext, u_char *ciphertext, int p_len, u_char *key) +{ + int i; + u_char K[17][48]; + for (i = 0; i < p_len; i += 8) { + DEScrypt::FDES(key, plaintext + i, ciphertext + i,K); + } + return i; +} + +int Secure::Decrypt(u_char *plaintext, u_char *ciphertext, int p_len, u_char *key) +{ + int i; + u_char K[17][48]; + for (i = 0; i < p_len; i += 8) { + DEScrypt::_FDES(key, ciphertext + i, plaintext + i,K); + } + return i; +} + +void Secure::BteaEncrypt(u_char* buf, u_char len) +{ + TEAcrypt::btea_encrypt(buf, len); +} + +void Secure::BteaDecrpyt(u_char* buf, u_char len) +{ + TEAcrypt::btea_decrpyt(buf, len); +} + +char* Secure::FnMD5CACL(u_char *buf, int len) +{ + memset(result, 0, sizeof result); + MD5crypt::MD5_CTX p_ctx; + MD5crypt::MD5Init(&p_ctx); + MD5crypt::MD5Update(&p_ctx, buf, len); + MD5crypt::MD5Final(&p_ctx); + for (int i = 0; i < 16; i++) { + sprintf(&result[i * 2], "%02x", p_ctx.digest[i]); + } + return result; +} + +char* Secure::Md5Sum(const char* filename) +{ + unsigned char data_buf[1024]; + unsigned char md5[16]; + MD5crypt::MD5_CTX ctx; + int data_fd; + int nread; + int i; + data_fd = open(filename, O_RDONLY); + if (data_fd == -1) + { + printf("open file error\n"); + } + MD5crypt::MD5Init(&ctx); + while (nread = read(data_fd, data_buf, sizeof(data_buf)), nread > 0) + { + MD5crypt::MD5Update(&ctx, data_buf, nread); + } + MD5crypt::MD5Final(&ctx); + memset(result, 0, sizeof result); + for (i = 0; i < 16; ++i) + { + sprintf(&result[i * 2], "%02x", ctx.digest[i]); + } + return result; +} \ No newline at end of file diff --git a/secure/SH_Secure.hpp b/secure/SH_Secure.hpp new file mode 100644 index 0000000..000e79e --- /dev/null +++ b/secure/SH_Secure.hpp @@ -0,0 +1,53 @@ +#ifndef _WL_SECUREAPI_H_ +#define _WL_SECUREAPI_H_ +#include +#include "../utility/SH_MySingleton.hpp" + +typedef unsigned char u_char; +typedef unsigned long u_long; +/************************ +* +* 所有的加密与解密都只针对一条指令 +* +*************************/ +class Secure : public MySingleton{ +public: + Secure(); + virtual ~Secure(); + void GetKey(char *pKey,std::string pImeiId);//获取手机KEY + void GetKey(std::string gwmac);//获取连接云服务器的KEY + + char *Base64Encode(const unsigned char * bindata, char * base65, int binlength); + int Base64Decode( const char * base64, unsigned char * bindata); + + int ZigbeeDataEncrypt(char *pData);//zigbee数据加密 + int ZigbeeDataEncrypt_Hex(char *pData, int len);//zigbee数据加密 HEX格式 + void ZigbeeDataDecrypt(char *pData,int pLen);//zigbee数据解密 + + int NetDataEncrypt(char* pMing, char* pMi, char* pKey);//网络数据加密 + int NetDataDecrypt(char* pMing, char* pMi, char* pKey);//网络数据解密 + int NetDataDecrypt(char* pMing, char* pMi,int pLen,char* pKey); + + char *Md5Sum(const char* filename); + int Encrypt(u_char *plaintext, u_char *expectText, int c_len, u_char *key); + int Decrypt(u_char *expectText, u_char *currentText, int c_len, u_char *key); + void BteaEncrypt(u_char* buf, u_char len); + void BteaDecrpyt(u_char* buf, u_char len); + char* FnMD5CACL(u_char *buf, int len); + + enum{KEYLen = 16}; + char KEY[KEYLen]; + typedef struct + { + int nr; /*!< number of rounds */ + unsigned int* rk; /*!< AES round keys */ + unsigned int buf[68]; /*!< unaligned data */ + }aes_context; + void aes_setkey_enc(aes_context* ctx, const unsigned char* key, int keysize); + void aes_setkey_dec(aes_context* ctx, const unsigned char* key, int keysize); + unsigned char* aes_crypt_ecb(aes_context* ctx, int mode, const unsigned char* input, int slen, int* dlen); +private: + char result[33]; +}; + +#endif \ No newline at end of file diff --git a/tcpcgi/TcpCgi.cpp b/tcpcgi/TcpCgi.cpp new file mode 100644 index 0000000..510f1f3 --- /dev/null +++ b/tcpcgi/TcpCgi.cpp @@ -0,0 +1,72 @@ +#include "TcpCgi.hpp" + + +namespace{ +LocalServer *cidwServer = LocalServer::instance(); +} + +TcpCgi::TcpCgi() +{ + print_light_green("TcpCgi Init\n"); +} + +void TcpCgi::startCgiServer() +{ + int listenfd, connfd; + int mw_optval = 1; + + struct sockaddr_in servaddr; + char buff[40960]; + int n; + if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ){ + printf("create socket error: %s(errno: %d)\n",strerror(errno),errno); + return; + } + setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (char *)&mw_optval,sizeof(mw_optval)); + + memset(&servaddr, 0, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = htonl(INADDR_ANY); + servaddr.sin_port = htons(7305); + + if( bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){ + printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno); + return; + } + + if( listen(listenfd, 10) == -1){ + printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno); + return; + } + + while(1){ + if( (connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1) { + printf("accept socket error: %s(errno: %d)",strerror(errno),errno); + continue; + } + n = recv(connfd, buff, 40960, 0); + if ( n <= 0) { + print_info("recv fail\n"); + close(connfd); + } else { + buff[n] = '\0'; + + std::string recvData = std::string(buff); + std::string reqData = cidwServer->HandleCgi_cmd(recvData); + print_info("send cgi : %s\n", reqData.c_str()); + if( send(connfd, reqData.c_str(), reqData.length(), 0) < 0){ + printf("send msg error: %s(errno: %d)\n", strerror(errno), errno); + } + close(connfd); + } + } + close(listenfd); + return; + +} + +TcpCgi::~TcpCgi() +{ + +} + diff --git a/tcpcgi/TcpCgi.hpp b/tcpcgi/TcpCgi.hpp new file mode 100644 index 0000000..c2b30b3 --- /dev/null +++ b/tcpcgi/TcpCgi.hpp @@ -0,0 +1,31 @@ +#ifndef TCPCGI_H +#define TCPCGI_H + +#include +#include +#include +#include +#include +#include +#include +#include "../common/SH_CommonFunc.hpp" +#include "../API_log/SH_log.h" +#include "../utility/SH_MySingleton.hpp" +#include "../common/SH_global.h" +#include "../localserver/SH_LocalServer.hpp" + + +class TcpCgi : public MySingleton { + +public: + TcpCgi(); + ~TcpCgi(); + + void startCgiServer(); +}; + +#endif + + + + diff --git a/threadfunc/SH_ThreadFunc.cpp b/threadfunc/SH_ThreadFunc.cpp new file mode 100644 index 0000000..594d581 --- /dev/null +++ b/threadfunc/SH_ThreadFunc.cpp @@ -0,0 +1,401 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "SH_ThreadFunc.hpp" +#include "../API_log/SH_log.h" +#include "../uart/SH_Uart.hpp" + +namespace{ +Uart *pUart = Uart::instance(); +LocalServer *cidwServer = LocalServer::instance(); +} + +static std::string serverPort; +static std::string uptime; +static long long connect_lost_time = 0; //ms +static long long connect_time = 0; //ms + +void CheckThread() +{ + print_info("ENTER CHECK THREAD \n"); + std::string runinfo = "系统循环检测模块启动"; + + int heart_count = 0; + + int time_check = 0; + int reset_flag = 0; + int online_check = 0; + + while (GlobalConfig::QuitFlag_G) { + if (10 == heart_count) { + // StatusPub(); + if (GlobalConfig::LinkCount > 30) { + exit(0); + } + std::string ipTemp = IpAddrInit(); + if ( 0 != ipTemp.compare(GlobalConfig::IpAddr_G)) { + exit(0); + } + heart_count = 0; + } + + if (600 == time_check) { + char buf[256] = {0}; + sprintf(buf, "{\"dataNodeGatewayNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}", + GlobalConfig::MacAddr_G.c_str()); + std::string str = std::string(buf); + data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + time_check = 0; + } + + + if (21600 == online_check) { + JsonData jd; + jd.DataNodeStatusCheck(); + + Param_29 param; + std::string cmd29 = jd.JsonCmd_29(param); + data_publish(cmd29.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + online_check = 0; + } + + if ( reset_flag > 7200) { + reset_flag = 0; + //exit(0); + } + reset_flag++; + time_check++; + heart_count++; + online_check++; + + if(GlobalConfig::EnterZigBeeWaveTransmittingFlag_G == ENTER_TRANSMITTING_STATUS) { + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G ++; + if(GlobalConfig::EnterZigBeeWaveTransmittingCnt_G >= 180) { + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + LOG_ERROR("[---- ZigBee error--!] ZigBee PanID is 9999 over time for 3 minutes !\n"); + // 重新写入 0x8888 + unsigned short shortAddr = 0x8888; + pUart->WriteShortAddr2Zigbee(shortAddr); + // 延时1秒 + boost::this_thread::sleep(boost::posix_time::seconds(1)); + // 重新读回 GlobalConfig::ZigbeeInfo_G.PanID + pUart->UpdateZigbeeInfoCtrl(); + // 延时1秒 + boost::this_thread::sleep(boost::posix_time::seconds(1)); + std::string str("8888"); + if( GlobalConfig::ZigbeeInfo_G.MyAddr.compare(str) == 0 ){ + LOG_INFO("[---- ZigBee INFO ----!] ZigBee PanID come back to be 8888 !\n"); + } + else { + LOG_ERROR("[---- ZigBee error--!] ZigBee PanID cannot come back to be 8888 !\n"); + } + } + } + + boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); + } +} + +void StartCgiServer() +{ + print_info("start deal cgi\n"); + TcpCgi *tcpCgi = TcpCgi::instance(); + while (1) { + tcpCgi->startCgiServer(); + boost::this_thread::sleep(boost::posix_time::seconds(10)); + } +} + + +void HeartRep() +{ + while(1) { + Json::Value jsHeart; + Json::FastWriter fw; + jsHeart["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsHeart["status"] = "online"; + std::string strJson = fw.write(jsHeart); + data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubHeart.c_str()); + boost::this_thread::sleep(boost::posix_time::seconds(10)); + } +} + +void UartStart() +{ + // onReceiveUart cb = (onReceiveUart)&ProtoConvert::HandleFromUart; + // pUart->setCallBack(cb); + while (GlobalConfig::QuitFlag_G) { + pUart->InitUart(); + pUart->UpdateZigbeeInfoCtrl(); + pUart->ReadFromUart(); + pUart->Run(); + pUart->Stop(); + boost::this_thread::sleep(boost::posix_time::seconds(1)); + } +} + +void UartStartWave() +{ + pUart->DealWaveThread(); +} + +void StartUdpSys() +{ + UdpSys *udpsys = UdpSys::instance(); + udpsys->StartConnectSysUdp(); +} + +static const char* LOCAL_WILL_TOPIC = "up/uart/will"; +void my_publish_callback(struct mosquitto *mosq, void *obj, int mid) +{ + +} + +void my_connect_callback(struct mosquitto *mosq, void *obj, int result) +{ + struct userdata *ud; + ud = (struct userdata *)obj; + + if (!result){ + for (int i = 0; i < ud->topic_count; i++){ + print_purple("mosquitto_subscribe ud->topics[%d]:%s\n", i, ud->topics[i]); + int iret = mosquitto_subscribe(mosq, NULL, ud->topics[i], ud->topic_qos); + print_purple("mosquitto_subscribe ret:%d\n", iret); + } + + int iret = mosquitto_subscribe(mosq, NULL, GlobalConfig::Topic_G.mSubData.c_str(), 1); + print_debug("mosquitto_subscribe's return value: %d\n", iret); + + char gwTime[32] = { 0 }; + GetTimeNet(gwTime, 0); + connect_time = strtoll(gwTime, NULL, 10); + print_debug("connect_time:%lld\n", connect_time); + long long difftime_ms = connect_time - connect_lost_time; + //if (difftime_ms > 20*1000) { // 超过20秒,判定为连接断开 + char reply_string[256] = {0}; + std::string startStatus = "0"; + if (access(SYSTEMSTART, 0) >= 0) { + startStatus = GetFileContent(SYSTEMSTART, 1); + } + sprintf(reply_string, "{\"dataNodeGatewayNo\":\"%s\",\"softVersion\":\"%s\",\"status\":\"%s\"}", + GlobalConfig::MacAddr_G.c_str(), GlobalConfig::Version.c_str(), startStatus.c_str()); + + Json::Value jsData; + Json::Value jsVal; + Json::FastWriter fw; + jsData["cmd"] = "15"; + jsData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + // jsData["cmdBody"] = ""; + + std::string strCmd15 = fw.write(jsData); + data_publish(strCmd15.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + + std::string instr = std::string(reply_string); + std::string topic = "equipment/state/" + GlobalConfig::MacAddr_G; + int ret = data_publish(instr.c_str(), topic.c_str()); + system("echo 0 > /CIDW/start"); + if (ret != MOSQ_ERR_SUCCESS) { + print_debug("Publish failed:%d, %s\n", ret, instr.c_str()); + disconnect(); + } + //} + GlobalConfig::LinkStatus_G = 1; + print_debug("Connect to server success.\n"); + + // std::string cmd20 = JsonCmd_Cgi_20(); + // data_publish(cmd20.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + + char buf[256] = {0}; + sprintf(buf, "{\"dataNodeGatewayNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}", + GlobalConfig::MacAddr_G.c_str()); + std::string str = std::string(buf); + data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + std::string runinfo = "本地服务器连接成功"; + + } + else{ + if (result && !ud->quiet){ + fprintf(stderr, "%s\n", mosquitto_connack_string(result)); + if(result == 1) { + //Connection Refused: unacceptable protocol version + } else if (result == 2) { + //Connection Refused: identifier rejected + } else if (result == 3) { + //Connection Refused: server unavailable + } else if (result == 4) { + //Connection Refused: bad user name or password + // exit(0); + } else if (result == 5) { + //Connection Refused: not authorized + } + } + } +} + +void my_disconnect_callback(struct mosquitto *mosq, void *obj, int result) +{ + int ret = 0; + ret = disconnect(); + // LOG_ERROR("The uart connection lost:%d\n", ret); + print_debug("The uart connection lost\n"); + char gwTime[32] = { 0 }; + GetTimeNet(gwTime, 0); + uptime = std::string(gwTime); + connect_lost_time = strtoll(uptime.c_str(), NULL, 10); + print_debug("connect_lost_time:%lld\n", connect_lost_time); + GlobalConfig::LinkStatus_G = 0; + GlobalConfig::LinkCount = GlobalConfig::LinkCount + 1; +} + +void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) +{ + struct userdata *ud; + bool res; + assert(obj); + ud = (struct userdata *)obj; + + if (message->retain && ud->no_retain) return; + if (ud->filter_outs) { + for (int i = 0; i < ud->filter_out_count; i++) { + mosquitto_topic_matches_sub(ud->filter_outs[i], message->topic, &res); + if (res) return; + } + } + + if (ud->verbose) { + if (message->payloadlen) { + std::string strtopic(message->topic); + print_info("strtopic : %s \n", strtopic.c_str()); + cidwServer->HandleFromServer((const char *)message->payload,message->payloadlen,message->topic); + if (ud->eol) { + print_brown("\n"); + } + } else { + if (ud->eol) { + print_brown("%s (null)\n", message->topic); + } + } + fflush(stdout); + } else { + if (message->payloadlen) { + fwrite(message->payload, 1, message->payloadlen, stdout); + if (ud->eol) { + print_red("\n"); + } + fflush(stdout); + } + } +} + +void my_subscribe_callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) +{ + int i; + struct userdata *ud; + assert(obj); + ud = (struct userdata *)obj; + if (!ud->quiet) print_brown("Subscribed (mid: %d): %d", mid, granted_qos[0]); + for (i = 1; i < qos_count; i++){ + if (!ud->quiet) print_brown(", %d", granted_qos[i]); + } +} + +void my_log_callback(struct mosquitto *mosq, void *obj, int level, const char *str) +{ + if (level == MOSQ_LOG_ERR) { + //LOG_ERROR("%s\n", str); + } else if (level == MOSQ_LOG_WARNING) { + // LOG_WARN("%s\n", str); + } else if (level == MOSQ_LOG_NOTICE) { + //LOG_INFO("%s\n", str); + } +} + +void StartMqttClient() +{ + print_info("start mqtt \n"); + std::string runinfo = "MQTT通信模块启动"; + + while (1) { + if (GlobalConfig::ServerIP.length() > 0) { + std::string strEqupNo = GlobalConfig::MacAddr_G; + std::string strVersion = GlobalConfig::Version; + std::string salt; + register_collback(my_connect_callback, my_message_callback, my_subscribe_callback, my_log_callback, my_disconnect_callback, my_publish_callback); + start_client(strEqupNo.c_str(), GlobalConfig::MacAddr_G.c_str(), GlobalConfig::ServerIP.c_str(), strVersion.c_str(), "11111111", salt); + } + boost::this_thread::sleep(boost::posix_time::seconds(3)); + } +} + + +void SearchThread() +{ + std::string runinfo = "设备搜索模块启动"; + + while (GlobalConfig::QuitFlag_G) { + if (GlobalConfig::IpAddr_G.length() > 0 && 0 != GlobalConfig::IpAddr_G.compare("0.0.0.0")) { + boost::asio::io_service io_service; + SearchDev *searchDevObj = new SearchDev(io_service); + searchDevObj->MultiCastRecv(); + io_service.run(); + delete searchDevObj; + } + boost::this_thread::sleep(boost::posix_time::seconds(5)); + print_error("SearchThred restart.\n"); + } +} + + +void RecvUpdateFile() +{ + boost::asio::io_service iosev; + boost::asio::ip::tcp::acceptor acceptor(iosev, + boost::asio::ip::tcp::endpoint( + boost::asio::ip::tcp::v4(), 7304)); + for(;;) { + boost::asio::ip::tcp::socket socket(iosev); + acceptor.accept(socket); + boost::system::error_code ec; + if(ec) { + print_error("%s\n", boost::system::system_error(ec).what()); + //return -1; + } + FILE *fp; + char buffer[1024]; + size_t len = 0; + int write_len; + bzero(buffer,1024); + fp = fopen("/tmp/upgrade.tar.gz", "w"); + if(NULL == fp ) { + print_info("File:\t Can Not Open To Write\n"); + exit(1); + } + while(len = socket.read_some(boost::asio::buffer(buffer),ec)) { + if(len < 0) { + print_info("Receive Data From Server Failed! \n"); + break; + } + write_len = fwrite(buffer, sizeof(char), len, fp); + if(write_len < len) { + print_info("File:test Write Failed!\n"); + break; + } + bzero(buffer, 1024); + } + print_info("Receive File From Server Finished! \n"); + fclose(fp); + Json::Value jsData; + Json::FastWriter fw; + jsData["cmd"] = "03"; + jsData["updatefilename"] = "updatefile"; + std::string str = fw.write(jsData); + system("/etc/init.d/sysupgrade.sh"); + } +} + diff --git a/threadfunc/SH_ThreadFunc.hpp b/threadfunc/SH_ThreadFunc.hpp new file mode 100644 index 0000000..38a4e4b --- /dev/null +++ b/threadfunc/SH_ThreadFunc.hpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../common/SH_global.h" +#include "../common/SH_CommonFunc.hpp" +#include "../mqttclient/SH_MqttClient.h" +#include "../localserver/SH_LocalServer.hpp" +#include "../searchdev/SH_SearchDev.hpp" +#include "../tcpcgi/TcpCgi.hpp" +#include "../udpqt/SH_UdpQt.hpp" + + +/*********************************** +*************线程处理函数*********** +************************************/ + +extern void CheckThread(); //循环检测线程 +extern void StartMqttClient(); //启动mqtt服务 +extern void SearchThread(); //组播功能, 提供发现设备功能 +extern void RecvUpdateFile(); //更新升级包 +extern void StartCgiServer(); //启动cgi处理服务端 +extern void HeartRep(); +extern void UartStart(); // +extern void UartStartWave(); +extern void StartUdpSys(); //组播通信 diff --git a/uart/SH_Uart.cpp b/uart/SH_Uart.cpp new file mode 100644 index 0000000..fa94cb2 --- /dev/null +++ b/uart/SH_Uart.cpp @@ -0,0 +1,2029 @@ +#include +#include +#include +#include +#include +#include +#include +#include "../uart/SH_Uart.hpp" + +namespace{ + Uart *pUart = Uart::instance(); +} + + +// namespace{ +// PlatformInit *platform = PlatformInit::instance(); +// LocalServer *wlServer = LocalServer::instance(); +// GenericFunc *genericFunc = GenericFunc::instance(); +// } +using namespace boost::asio; +const UINT CharSize = 8; +const UINT UartBaud = 115200; + +Uart::Uart():mUart(mIoSev),mStrand(mIoSev) +{ + mRdLength = 0; + memset(mUartRecvBuf,0,BUF_LENGTH); +} + +void Uart::InitUart() +{ + //*.reset()作用重置对象,为run()的调用做准备 + mUart.get_io_service().reset(); + mStrand.get_io_service().reset(); + // ThreadInit(); + mRdLength = 0; + //errcode用来接收错误类型 + boost::system::error_code errcode; + //打开/dev/ttymxc4串口文件 + mUart.open(GlobalConfig::UartName_G,errcode); + if ( errcode) { + print_error("Fail To Open Uart!\n"); + // LOG_ERROR("Fail To Open Uart!\n"); + return ; + } else { + if (mUart.is_open()) { + print_info("Success To Open Uart!\n"); + } + } + //设置串口的波特率 数据位 流控 奇偶校验位 停止位 + mUart.set_option( serial_port::baud_rate(UartBaud), errcode); + mUart.set_option( serial_port::flow_control(serial_port::flow_control::none),errcode ); + mUart.set_option( serial_port::parity(serial_port::parity::none),errcode ); + mUart.set_option( serial_port::stop_bits(serial_port::stop_bits::one),errcode ); + mUart.set_option( serial_port::character_size(CharSize),errcode ); + + + // WriteToUart(); + // mUart.set_option( serial_port::baud_rate(UartBaud), errcode); + +} + +Uart::~Uart() +{ + if (mUart.is_open()) + mUart.close(); +} + +void Uart::WriteToUart(const char *strSend,int pLen) +{ +//#ifdef ZIGBEE_TEST + print_debug("Write To Uart Start:\n"); + for(int i=0; iWriteToUart(pData.mData,pData.mLen); + // LOG_INFO("WriteToUart:%s", pData.mDataMing); + boost::this_thread::sleep(boost::posix_time::milliseconds(110)); +} + +void Uart::UpdateZigbeeInfoCtrl() +{ + char buf[5] = {0xAB, 0xBC, 0xCD, 0xD1, 0x05}; + WriteToUart(buf, 5); + boost::this_thread::sleep(boost::posix_time::seconds(1)); +} + +void Uart::UpdateZigbeeInfo(const char *pData) +{ + + print_info("update gateway zigbee info\n"); + GlobalConfig::Zigbee_G = *((ZIGBEE *)pData); + char buff[8]; + sprintf(buff, "%02d", pData[36]&0xFF); + GlobalConfig::ZigbeeInfo_G.DevMode = boost::lexical_cast(buff); + + memset(buff, 0, 8); + sprintf(buff, "%02d", pData[37]&0xFF); + GlobalConfig::ZigbeeInfo_G.Channel = boost::lexical_cast(buff); + + memset(buff, 0, 8); + sprintf(buff, "%02x%02x", pData[38]&0xFF, pData[39]&0xFF); + GlobalConfig::ZigbeeInfo_G.PanID = std::string(buff); + + memset(buff, 0, 8); + sprintf(buff, "%02x%02x", pData[40]&0xFF, pData[41]&0xFF); + GlobalConfig::ZigbeeInfo_G.MyAddr = std::string(buff); + + + memset(buff, 0, 8); + sprintf(buff, "%02x%02x", pData[50]&0xFF, pData[51]&0xFF); + GlobalConfig::ZigbeeInfo_G.DstAddr = std::string(buff); + + print_info("local zigbee module info Mode : %d Chan : %d PanID : %s MyAddr : %s DstAddr : %s\n", GlobalConfig::ZigbeeInfo_G.DevMode, GlobalConfig::ZigbeeInfo_G.Channel, + GlobalConfig::ZigbeeInfo_G.PanID.c_str(),GlobalConfig::ZigbeeInfo_G.MyAddr.c_str(), GlobalConfig::ZigbeeInfo_G.DstAddr.c_str()); + LOG_INFO("[UpdateZigbeeInfo---] ZigBee PanID: %s ; Channel: %d ; MyAddr : %s ",GlobalConfig::ZigbeeInfo_G.PanID.c_str(),GlobalConfig::ZigbeeInfo_G.Channel,GlobalConfig::ZigbeeInfo_G.MyAddr.c_str()); + +} + + +void Uart::DealRecvData(const char *pData) +{ + char buf[8]; + sprintf(buf, "%02d", pData[5]&0xFF); + int flag = boost::lexical_cast(buf); + print_info("the data package type(1,2,3,4,5,6) is %s,%x\n",buf,pData[5]&0xFF); + switch (flag) + { + case 1:{ + DealDataNodeInfo(pData); + } + break; + case 2:{ + DealDataNodeFeature(pData, 0); + } + break; + case 3:{ + DealDataNodeWave(pData); + } + break; + case 4:{ + DealDataNodeWave(pData); + } + break; + case 5:{ + DealDataNodeWave(pData); + } + break; + case 6:{ + DealDataNodeFeature(pData, 1); + } + break; + default: + break; + } +} + + +void Uart::DealDataNodeInfo(const char *pData) +{ + print_info("recv remote zigbee module info\n"); + RecvData * pRecvData = (RecvData *)pData; + char buf[32] = {0}; + char chTemp = pRecvData->Data[0]; + DataNodeInfo dataNodeInfo; + dataNodeInfo.EquipSta = boost::lexical_cast(chTemp >> 2 & 0x1); + dataNodeInfo.TemTopFlag = boost::lexical_cast(chTemp >> 3 & 0x1); + dataNodeInfo.TemBotFlag = boost::lexical_cast(chTemp >> 4 & 0x1); + dataNodeInfo.ZigbeeFlag = boost::lexical_cast(chTemp >> 5 & 0x1); + dataNodeInfo.AccFlag = boost::lexical_cast(chTemp >> 6 & 0x1); + dataNodeInfo.InitFlag = boost::lexical_cast(chTemp >> 7 & 0x1); + + sprintf(buf, "%02x%02x%02x%02x%02x%02x%02x%02x", pRecvData->Data[1], pRecvData->Data[2], pRecvData->Data[3], pRecvData->Data[4], + pRecvData->Data[5], pRecvData->Data[6], pRecvData->Data[7],pRecvData->Data[8]); + dataNodeInfo.ZigbeeLongAddr = std::string(buf); + + chTemp = pRecvData->Data[9]; + memset(buf, 0, 32); + sprintf(buf, "%02x", chTemp); + dataNodeInfo.HardVersion = std::string(buf); + + chTemp = pRecvData->Data[10]; + memset(buf, 0, 32); + //sprintf(buf, "%02x", chTemp); + sprintf(buf, "%.1f", 0.1*chTemp); + dataNodeInfo.SoftVersion = std::string(buf); + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x%02x%02x", pRecvData->Data[11], pRecvData->Data[12], pRecvData->Data[13], pRecvData->Data[14]); + dataNodeInfo.BpNo = std::string(buf); + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x%02x%02x", pRecvData->Data[15], pRecvData->Data[16], pRecvData->Data[17], pRecvData->Data[18]); + dataNodeInfo.SerialNo = std::string(buf); + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x%02x%02x", pRecvData->Data[19], pRecvData->Data[20], pRecvData->Data[21], pRecvData->Data[22]); + dataNodeInfo.FirstPowerTime = std::string(buf); + + //23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38=>序号13 无线信号强度 + // 获取 RSSI + chTemp = pRecvData->Data[38]; + memset(buf, 0, 32); + sprintf(buf, "%d", chTemp); + dataNodeInfo.RSSI = boost::lexical_cast(buf); + + chTemp = pRecvData->Data[39]; + memset(buf, 0, 32); + sprintf(buf, "%02x", chTemp); + dataNodeInfo.ConfigFlag = ((0 == std::string(buf).compare("aa")) ? 1 : 0); + + memset(buf, 0, 32); + sprintf(buf, "%u%u", pRecvData->Data[40], pRecvData->Data[41]); + dataNodeInfo.FeatureInterVal = boost::lexical_cast(buf); + + chTemp = pRecvData->Data[42]; + memset(buf, 0, 32); + // sprintf(buf, "%02x", chTemp); + sprintf(buf, "%d",(unsigned int)chTemp); // yxq + dataNodeInfo.WaveInterVal = boost::lexical_cast(buf); + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[43], pRecvData->Data[44]); + dataNodeInfo.ZigbeePanId = std::string(buf); + + chTemp = pRecvData->Data[45]; + memset(buf, 0, 32); + sprintf(buf, "%d", chTemp); + dataNodeInfo.ZigbeeChannel = boost::lexical_cast(buf); + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[46], pRecvData->Data[47]); + dataNodeInfo.ZigbeeShortAddr = std::string(buf); + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[48], pRecvData->Data[49]); + dataNodeInfo.ZigbeeDesAddr = std::string(buf); + //50 51 52=》序号23 zigbee重试间隔 + + chTemp = pRecvData->Data[53]; + dataNodeInfo.Range = boost::lexical_cast(chTemp >> 2 & 0x3); + dataNodeInfo.SamplingRate = boost::lexical_cast(chTemp & 0x3); + // 54=》序号25 ACC采样时间 + int iTemp = 0; + //使用了55 56 59 60 63 64 67 68 71 72 + for (int i = 0; i < 5; i++) { + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[55 + i * 4], pRecvData->Data[55 + i * 4 + 1]); + iTemp = (int)strtol(buf, NULL, 16); + + if (0 == i) { + dataNodeInfo.StartBrands = boost::lexical_cast(iTemp); + } else { + dataNodeInfo.StartBrands += ("," + boost::lexical_cast(iTemp)); + } + } + //使用了57 58 61 62 65 66 69 70 73 74 + for (int j = 0; j < 5; j++) { + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[57 + j * 4], pRecvData->Data[57 + j * 4 + 1]); + iTemp = (int)strtol(buf, NULL, 16); + if (0 == j) { + dataNodeInfo.StopBrands = boost::lexical_cast(iTemp); + } else { + dataNodeInfo.StopBrands += ("," + boost::lexical_cast(iTemp)); + } + } + + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[75], pRecvData->Data[76]); + iTemp = (int)strtol(buf, NULL, 16); + dataNodeInfo.EnvelopeBandPass = boost::lexical_cast(iTemp); + + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[77], pRecvData->Data[78]); + iTemp = (int)strtol(buf, NULL, 16); + dataNodeInfo.EnvelopeBandPass += ("," + boost::lexical_cast(iTemp)); + //使用了79 80 81 82 83 84 85 86 + for (int j = 0; j < 4; j++) { + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[79 + j * 2], pRecvData->Data[79 + j * 2 + 1]); + iTemp = (int)strtol(buf, NULL, 16); + + if (0 == j) { + dataNodeInfo.FaultFrequency = boost::lexical_cast(iTemp); + } else { + dataNodeInfo.FaultFrequency += ("," + boost::lexical_cast(iTemp)); + } + } + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x%02x%02x", pRecvData->Data[87], pRecvData->Data[88], pRecvData->Data[89],pRecvData->Data[90]); + long lTimeStamp = strtol(buf, NULL, 16); + dataNodeInfo.ConfigDate = boost::lexical_cast(lTimeStamp); + + chTemp = pRecvData->Data[91]; + memset(buf, 0, 32); + sprintf(buf, "%d", chTemp); + dataNodeInfo.VIntegralFilterFrequency = boost::lexical_cast(buf); + + char whereCon[64] = {0}; + sprintf(whereCon, "dataNodeNo='%s'", dataNodeInfo.ZigbeeLongAddr.c_str()); + if (sql_ctl->GetTableRows(T_SENSOR_INFO(TNAME), whereCon) > 0) { + sql_ctl->DeleteTableData(T_SENSOR_INFO(TNAME), whereCon); + } + + char insertSql[1024] = { 0 }; + sprintf(insertSql, "'%s','%s','%d','%d','%d','%d','%d','%d','%s','%s','%s','%s','%s','%d','%s','%s','%u','%d','%d','%s','%d','%s','%s','%s','%d','%s','%s','%s','%s','%s','%d','%d'", + dataNodeInfo.ZigbeeLongAddr.c_str(), " ", dataNodeInfo.InitFlag, dataNodeInfo.AccFlag, dataNodeInfo.ZigbeeFlag, dataNodeInfo.TemTopFlag, dataNodeInfo.TemBotFlag,dataNodeInfo.EquipSta,\ + dataNodeInfo.HardVersion.c_str(), dataNodeInfo.SoftVersion.c_str(), dataNodeInfo.BpNo.c_str(), dataNodeInfo.SerialNo.c_str(), dataNodeInfo.FirstPowerTime.c_str(), dataNodeInfo.ConfigFlag, dataNodeInfo.StartBrands.c_str(), \ + dataNodeInfo.StopBrands.c_str(), dataNodeInfo.FeatureInterVal, dataNodeInfo.WaveInterVal, dataNodeInfo.SamplingRate, "range", dataNodeInfo.Range, dataNodeInfo.EnvelopeBandPass.c_str(), dataNodeInfo.FaultFrequency.c_str(),\ + dataNodeInfo.ZigbeePanId.c_str(), dataNodeInfo.ZigbeeChannel, dataNodeInfo.ZigbeeShortAddr.c_str(), dataNodeInfo.ZigbeeLongAddr.c_str(), dataNodeInfo.ZigbeeDesAddr.c_str(), "1", dataNodeInfo.ConfigDate.c_str(),dataNodeInfo.VIntegralFilterFrequency,dataNodeInfo.RSSI); + sql_ctl->InsertData(T_SENSOR_INFO(TNAME), insertSql); + + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["cmd"] = "26"; + + Json::Value jsBody; + jsBody["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsBody["dataNodeNo"] = dataNodeInfo.ZigbeeLongAddr; + jsBody["type"] = "insert"; + + Json::Value jsSensorData; + jsSensorData["dataNodeNo"] = dataNodeInfo.ZigbeeLongAddr; + jsSensorData["dataNodeName"] = ""; + jsSensorData["initFlag"] = dataNodeInfo.InitFlag; + jsSensorData["accFlag"] = dataNodeInfo.AccFlag; + jsSensorData["zigbeeFlag"] = dataNodeInfo.ZigbeeFlag; + jsSensorData["temTopFlag"] = dataNodeInfo.TemTopFlag; + jsSensorData["temBotFlag"] = dataNodeInfo.TemBotFlag; + jsSensorData["equipsta"] = dataNodeInfo.EquipSta; + jsSensorData["hardVersion"] = dataNodeInfo.HardVersion; + jsSensorData["softVersion"] = dataNodeInfo.SoftVersion; + jsSensorData["bpNo"] = dataNodeInfo.BpNo; + jsSensorData["serialNo"] = dataNodeInfo.SerialNo; + jsSensorData["firstPowerTime"] = dataNodeInfo.FirstPowerTime; + jsSensorData["configFlag"] = dataNodeInfo.ConfigFlag; + jsSensorData["startBrands"] = dataNodeInfo.StartBrands; + jsSensorData["stopBrands"] = dataNodeInfo.StopBrands; + jsSensorData["featureInterVal"] = dataNodeInfo.FeatureInterVal; + jsSensorData["waveInterVal"] = dataNodeInfo.WaveInterVal; + jsSensorData["samplingRate"] = dataNodeInfo.SamplingRate; + jsSensorData["range"] = dataNodeInfo.Range; + jsSensorData["envelopeBandPass"] = dataNodeInfo.EnvelopeBandPass; + jsSensorData["faultFrequency"] = dataNodeInfo.FaultFrequency; + jsSensorData["zigbeePanId"] = dataNodeInfo.ZigbeePanId; + jsSensorData["zigbeeChannel"] = dataNodeInfo.ZigbeeChannel; + jsSensorData["zigbeeAddr"] = dataNodeInfo.ZigbeeLongAddr; + jsSensorData["zigbeeDesAddr"] = dataNodeInfo.ZigbeeDesAddr; + jsSensorData["status"] = 1; + jsSensorData["timeStamp"] = dataNodeInfo.ConfigDate; + jsSensorData["VIntegralFilterFrequency"] = dataNodeInfo.VIntegralFilterFrequency; + jsSensorData["RSSI"] = dataNodeInfo.RSSI; + + jsBody["dataNodeInfo"] = jsSensorData; + + Json::FastWriter showValue; + std::string dataBody = showValue.write(jsBody); + jsonVal["cmdBody"] = dataBody; + std::string strCmd27 = showValue.write(jsonVal); + //传感器发来的数据包中的表示设备信息的数据转化为json格式后,通过调用data_publish将数据传给mqttclient : Topic:wireless/cmd/60294D203717 + data_publish(strCmd27.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + + print_info("remote wireless sensor device info AccFlag : %d EquipSta : %d BpNo : %s ConfigFlag : %d EnvelopeBandPass : %s FaultFrequency : %s FeatureInterVal : %u FirstPowerTime : %s HardVersion : %s InitFlag : %d SamplingRate : %d range : %d SerialNo : %s\ + SoftVersion : %s StartBrands : %s StopBrands : %s TemBotFlag : %d TemTopFlag : %d WaveInterVal : %d ZigbeeChannel : %d ZigbeeDesAddr : %s ZigbeeFlag : %d ZigbeeLongAddr : %s panid : %s ZigbeeShortAddr : %s Configdate : %s vintegralfilterfrequency : %d RSSI : %d \n", \ + dataNodeInfo.AccFlag, dataNodeInfo.EquipSta, dataNodeInfo.BpNo.c_str(), dataNodeInfo.ConfigFlag, dataNodeInfo.EnvelopeBandPass.c_str(), dataNodeInfo.FaultFrequency.c_str(),\ + dataNodeInfo.FeatureInterVal, dataNodeInfo.FirstPowerTime.c_str(), dataNodeInfo.HardVersion.c_str(), dataNodeInfo.InitFlag, dataNodeInfo.SamplingRate, dataNodeInfo.Range, dataNodeInfo.SerialNo.c_str(),\ + dataNodeInfo.SoftVersion.c_str(), dataNodeInfo.StartBrands.c_str(), dataNodeInfo.StopBrands.c_str(), dataNodeInfo.TemBotFlag, dataNodeInfo.TemTopFlag, dataNodeInfo.WaveInterVal,\ + dataNodeInfo.ZigbeeChannel, dataNodeInfo.ZigbeeDesAddr.c_str(), dataNodeInfo.ZigbeeFlag, dataNodeInfo.ZigbeeLongAddr.c_str(), dataNodeInfo.ZigbeePanId.c_str(), dataNodeInfo.ZigbeeShortAddr.c_str(), dataNodeInfo.ConfigDate.c_str(), dataNodeInfo.VIntegralFilterFrequency, dataNodeInfo.RSSI); + +} + + +void Uart::DealDataNodeFeature(const char *pData, int flag) +{ + if (1 == flag) { + print_info("recv wave minute\n"); + unsigned short shortAddr = 0x9999; + WriteShortAddr2Zigbee(shortAddr); + LOG_INFO("[DealDataNodeFeature] ZigBee PanID: %s ; Channel: %d ; MyAddr : %4x ",GlobalConfig::ZigbeeInfo_G.PanID.c_str(),GlobalConfig::ZigbeeInfo_G.Channel, + (unsigned short)GlobalConfig::Zigbee_G.MyAddr); + // 进入传输原始数据状态,启动计数 60秒 + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + } + + print_info("recv feature\n"); + RecvData * pRecvData = (RecvData *)pData; + + char buf[8]; + sprintf(buf, "%02x%02x", pRecvData->ShortAddr[0], pRecvData->ShortAddr[1]); + std::string strShortAddr = std::string(buf); + char getLongAddr_sql[32] = { 0 }; + //根据数据包中的传感器的短地址获取数据库中长地址(MAC),在下面判断该传感器是否存在,如果不存在则把数据包丢弃 + sprintf(getLongAddr_sql, "zigbeeShortAddr='%s'", strShortAddr.c_str()); + std::string strLongAddr = sql_ctl->GetData(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(ZIGBEELONGADDR), getLongAddr_sql); + print_info("--------->the remote sensor short addr:%s strLongAddr=%s\n",buf,strLongAddr.c_str()); + + if (0 == strLongAddr.length()) { + print_error("device info not found\n"); + return; + } + + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + + int iTemp = 0; + unsigned char highbit = 0; + unsigned int lowbit = 0; + float n = 0; + + DataRecvStatic dataStatic; + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[5], pRecvData->Data[4]); + print_blue("!!!!!!!!!!!!!!!!!!!!!!%s\n",buf); + iTemp = (int)strtol(buf, NULL, 16); + dataStatic.Dip = iTemp; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[1], pRecvData->Data[0]); + print_blue("@@@@@@@@@@@@@@@@@%s\n",buf); + iTemp = (int)strtol(buf, NULL, 16); + dataStatic.TemBot = iTemp * 0.0625; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[3], pRecvData->Data[2]); + iTemp = (int)strtol(buf, NULL, 16); + dataStatic.TemTop = iTemp * 0.0625; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[7], pRecvData->Data[6]); + iTemp = (int)strtol(buf, NULL, 16); + dataStatic.Voltage = iTemp; + + + print_info("dataStatic.TemTop : %f dataStatic.TemBot : %f dataStatic.Dip :%d dataStatic.Voltage : %d\n", dataStatic.TemTop\ + , dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage); + char whereCon[64] = {0}; + sprintf(whereCon, "channelID='%s'", (strLongAddr + "-S").c_str()); + if ( 0 == sql_ctl->GetTableRows(T_DATASTATIC_INFO(TNAME), whereCon) ) { + print_info("insert static data to sql\n"); + char insertSql[1024] = { 0 }; + sprintf(insertSql, "'%s','%s','%f','%f','%d','%d','%s'", + strLongAddr.c_str(), (strLongAddr + "-S").c_str(), dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, nowTimetamp.c_str()); + sql_ctl->InsertData(T_DATASTATIC_INFO(TNAME), insertSql); + } else { + print_info("update static data to sql\n"); + char updateSql[1024] = { 0 }; + sprintf(updateSql, "temTop='%f',temBot='%f',dip='%d',voltage='%d',timeStamp='%s'",\ + dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, nowTimetamp.c_str()); + sql_ctl->UpdateTableData(T_DATASTATIC_INFO(TNAME), updateSql, whereCon); + } + + DataRecvDym dataDymX; + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[9], pRecvData->Data[8]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.DiagnosisPk = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[11], pRecvData->Data[10]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.RmsValues = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[13], pRecvData->Data[12]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.IntegratPk = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[15], pRecvData->Data[14]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.IntegratRMS = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[17], pRecvData->Data[16]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.Amp1 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[19], pRecvData->Data[18]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.Amp2 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[21], pRecvData->Data[20]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.Amp3 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[23], pRecvData->Data[22]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.Amp4 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[25], pRecvData->Data[24]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.Amp5 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[27], pRecvData->Data[26]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.EnvelopEnergy = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[29], pRecvData->Data[28]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.Phase1 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[31], pRecvData->Data[30]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.Phase2 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[33], pRecvData->Data[32]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.Phase3 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[35], pRecvData->Data[34]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymX.Phase4 = lowbit * n; + + memset(whereCon, 0, 64); + sprintf(whereCon, "channelID='%s'", (strLongAddr + "-X").c_str()); + if ( 0 == sql_ctl->GetTableRows(T_DATA_INFO(TNAME), whereCon) ) { + char insertSql[1024] = { 0 }; + sprintf(insertSql, "'%s','%s','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%s'", + strLongAddr.c_str(), (strLongAddr + "-X").c_str(), dataDymX.DiagnosisPk, dataDymX.IntegratPk, dataDymX.IntegratRMS, dataDymX.RmsValues, dataDymX.EnvelopEnergy,\ + dataDymX.Amp1, dataDymX.Amp2, dataDymX.Amp3, dataDymX.Amp4, dataDymX.Amp5,dataDymX.Phase1, dataDymX.Phase2, dataDymX.Phase3, dataDymX.Phase4, nowTimetamp.c_str()); + sql_ctl->InsertData(T_DATA_INFO(TNAME), insertSql); + } else { + char updateSql[1024] = { 0 }; + sprintf(updateSql, "diagnosisPk='%f',integratPk='%f',integratRMS='%f',rmsValues='%f',envelopEnergy='%f',\ + Amp1='%f',Amp2='%f',Amp3='%f',Amp4='%f',Amp5='%f',Phase1='%f',Phase2='%f',Phase3='%f',Phase4='%f',timeStamp='%s'",\ + dataDymX.DiagnosisPk, dataDymX.IntegratPk, dataDymX.IntegratRMS, dataDymX.RmsValues, dataDymX.EnvelopEnergy,\ + dataDymX.Amp1, dataDymX.Amp2, dataDymX.Amp3, dataDymX.Amp4, dataDymX.Amp5,dataDymX.Phase1, dataDymX.Phase2, dataDymX.Phase3, dataDymX.Phase4, nowTimetamp.c_str()); + sql_ctl->UpdateTableData(T_DATA_INFO(TNAME), updateSql, whereCon); + } + print_info("x:%s,%s,diagnosisPk=%f,integratPk=%f,integratRMS=%f,rmsValues=%f,envelopEnergy=%f,Amp1=%f,Amp2=%f,Amp3=%f,Amp4=%f,Amp5=%f,Phase1=%f,Phase2=%f,Phase3=%f,Phase4=%f,timeStamp=%s\n",\ + strLongAddr.c_str(), (strLongAddr + "-X").c_str(), dataDymX.DiagnosisPk, dataDymX.IntegratPk, dataDymX.IntegratRMS, dataDymX.RmsValues, dataDymX.EnvelopEnergy,\ + dataDymX.Amp1, dataDymX.Amp2, dataDymX.Amp3, dataDymX.Amp4, dataDymX.Amp5,dataDymX.Phase1, dataDymX.Phase2, dataDymX.Phase3, dataDymX.Phase4, nowTimetamp.c_str()); + + Json::Value valNodeData; + Json::Value valNodeFeature; + valNodeFeature["dataNodeNo"] = strLongAddr; + valNodeFeature["channelID"] = strLongAddr + "-X"; + valNodeFeature["diagnosisPk"] = dataDymX.DiagnosisPk; + valNodeFeature["integratPk"] = dataDymX.IntegratPk; + valNodeFeature["integratRMS"] = dataDymX.IntegratRMS; + valNodeFeature["rmsValues"] = dataDymX.RmsValues; + valNodeFeature["envelopEnergy"] = dataDymX.EnvelopEnergy; + valNodeFeature["Amp1"] = dataDymX.Amp1; + valNodeFeature["Amp2"] = dataDymX.Amp2; + valNodeFeature["Amp3"] = dataDymX.Amp3; + valNodeFeature["Amp4"] = dataDymX.Amp4; + valNodeFeature["Amp5"] = dataDymX.Amp5; + valNodeFeature["Phase1"] = dataDymX.Phase1; + valNodeFeature["Phase2"] = dataDymX.Phase2; + valNodeFeature["Phase3"] = dataDymX.Phase3; + valNodeFeature["Phase4"] = dataDymX.Phase4; + valNodeFeature["timeStamp"] = nowTimetamp; + valNodeData.append(valNodeFeature); + DataRecvDym dataDymY; + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[37], pRecvData->Data[36]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.DiagnosisPk = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[39], pRecvData->Data[38]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.RmsValues = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[41], pRecvData->Data[40]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.IntegratPk = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[43], pRecvData->Data[42]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.IntegratRMS = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[45], pRecvData->Data[44]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.Amp1 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[47], pRecvData->Data[46]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.Amp2 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[49], pRecvData->Data[48]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.Amp3 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[51], pRecvData->Data[50]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.Amp4 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[53], pRecvData->Data[52]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.Amp5 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[55], pRecvData->Data[54]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.EnvelopEnergy = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[57], pRecvData->Data[56]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.Phase1 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[59], pRecvData->Data[58]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.Phase2 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[61], pRecvData->Data[60]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.Phase3 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[63], pRecvData->Data[62]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymY.Phase4 = lowbit * n; + + memset(whereCon, 0, 64); + sprintf(whereCon, "channelID='%s'", (strLongAddr + "-Y").c_str()); + if ( 0 == sql_ctl->GetTableRows(T_DATA_INFO(TNAME), whereCon) ) { + char insertSql[1024] = { 0 }; + sprintf(insertSql, "'%s','%s','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%s'", + strLongAddr.c_str(), (strLongAddr + "-Y").c_str(), dataDymY.DiagnosisPk, dataDymY.IntegratPk, dataDymY.IntegratRMS, dataDymY.RmsValues, dataDymY.EnvelopEnergy,\ + dataDymY.Amp1, dataDymY.Amp2, dataDymY.Amp3, dataDymY.Amp4, dataDymY.Amp5,dataDymY.Phase1, dataDymY.Phase2, dataDymY.Phase3, dataDymY.Phase4, nowTimetamp.c_str()); + sql_ctl->InsertData(T_DATA_INFO(TNAME), insertSql); + } else { + char updateSql[1024] = { 0 }; + sprintf(updateSql, "diagnosisPk='%f',integratPk='%f',integratRMS='%f',rmsValues='%f',envelopEnergy='%f',\ + Amp1='%f',Amp2='%f',Amp3='%f',Amp4='%f',Amp5='%f',Phase1='%f',Phase2='%f',Phase3='%f',Phase4='%f',timeStamp='%s'",\ + dataDymY.DiagnosisPk, dataDymY.IntegratPk, dataDymY.IntegratRMS, dataDymY.RmsValues, dataDymY.EnvelopEnergy,\ + dataDymY.Amp1, dataDymY.Amp2, dataDymY.Amp3, dataDymY.Amp4, dataDymY.Amp5,dataDymY.Phase1, dataDymY.Phase2, dataDymY.Phase3, dataDymY.Phase4, nowTimetamp.c_str()); + sql_ctl->UpdateTableData(T_DATA_INFO(TNAME), updateSql, whereCon); + } + print_info("y: %s,%s,diagnosisPk=%f,integratPk=%f,integratRMS=%f,rmsValues=%f,envelopEnergy=%f,Amp1=%f,Amp2=%f,Amp3=%f,Amp4=%f,Amp5=%f,Phase1=%f,Phase2=%f,Phase3=%f,Phase4=%f,timeStamp=%s\n",\ + strLongAddr.c_str(), (strLongAddr + "-Y").c_str(), dataDymY.DiagnosisPk, dataDymY.IntegratPk, dataDymY.IntegratRMS, dataDymY.RmsValues, dataDymY.EnvelopEnergy,\ + dataDymY.Amp1, dataDymY.Amp2, dataDymY.Amp3, dataDymY.Amp4, dataDymY.Amp5,dataDymY.Phase1, dataDymY.Phase2, dataDymY.Phase3, dataDymY.Phase4, nowTimetamp.c_str()); + + + valNodeFeature["dataNodeNo"] = strLongAddr; + valNodeFeature["channelID"] = strLongAddr + "-Y"; + valNodeFeature["diagnosisPk"] = dataDymY.DiagnosisPk; + valNodeFeature["integratPk"] = dataDymY.IntegratPk; + valNodeFeature["integratRMS"] = dataDymY.IntegratRMS; + valNodeFeature["rmsValues"] = dataDymY.RmsValues; + valNodeFeature["envelopEnergy"] = dataDymY.EnvelopEnergy; + valNodeFeature["Amp1"] = dataDymY.Amp1; + valNodeFeature["Amp2"] = dataDymY.Amp2; + valNodeFeature["Amp3"] = dataDymY.Amp3; + valNodeFeature["Amp4"] = dataDymY.Amp4; + valNodeFeature["Amp5"] = dataDymY.Amp5; + valNodeFeature["Phase1"] = dataDymY.Phase1; + valNodeFeature["Phase2"] = dataDymY.Phase2; + valNodeFeature["Phase3"] = dataDymY.Phase3; + valNodeFeature["Phase4"] = dataDymY.Phase4; + valNodeFeature["timeStamp"] = nowTimetamp; + valNodeData.append(valNodeFeature); + + DataRecvDym dataDymZ; + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[65], pRecvData->Data[64]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.DiagnosisPk = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[67], pRecvData->Data[66]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.RmsValues = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[69], pRecvData->Data[68]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.IntegratPk = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[71], pRecvData->Data[70]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.IntegratRMS = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[73], pRecvData->Data[72]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.Amp1 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[75], pRecvData->Data[74]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.Amp2 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[77], pRecvData->Data[76]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.Amp3 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[79], pRecvData->Data[78]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.Amp4 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[81], pRecvData->Data[80]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.Amp5 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[83], pRecvData->Data[82]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.EnvelopEnergy = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[85], pRecvData->Data[84]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.Phase1 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[87], pRecvData->Data[86]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.Phase2 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[89], pRecvData->Data[88]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.Phase3 = lowbit * n; + + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", pRecvData->Data[91], pRecvData->Data[90]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataDymZ.Phase4 = lowbit * n; + + memset(whereCon, 0, 64); + sprintf(whereCon, "channelID='%s'", (strLongAddr + "-Z").c_str()); + if ( 0 == sql_ctl->GetTableRows(T_DATA_INFO(TNAME), whereCon) ) { + char insertSql[1024] = { 0 }; + sprintf(insertSql, "'%s','%s','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%s'", + strLongAddr.c_str(), (strLongAddr + "-Z").c_str(), dataDymZ.DiagnosisPk, dataDymZ.IntegratPk, dataDymZ.IntegratRMS, dataDymZ.RmsValues, dataDymZ.EnvelopEnergy,\ + dataDymZ.Amp1, dataDymZ.Amp2, dataDymZ.Amp3, dataDymZ.Amp4, dataDymZ.Amp5,dataDymZ.Phase1, dataDymZ.Phase2, dataDymZ.Phase3, dataDymZ.Phase4, nowTimetamp.c_str()); + sql_ctl->InsertData(T_DATA_INFO(TNAME), insertSql); + } else { + char updateSql[1024] = { 0 }; + sprintf(updateSql, "diagnosisPk='%f',integratPk='%f',integratRMS='%f',rmsValues='%f',envelopEnergy='%f',\ + Amp1='%f',Amp2='%f',Amp3='%f',Amp4='%f',Amp5='%f',Phase1='%f',Phase2='%f',Phase3='%f',Phase4='%f',timeStamp='%s'",\ + dataDymZ.DiagnosisPk, dataDymZ.IntegratPk, dataDymZ.IntegratRMS, dataDymZ.RmsValues, dataDymZ.EnvelopEnergy,\ + dataDymZ.Amp1, dataDymZ.Amp2, dataDymZ.Amp3, dataDymZ.Amp4, dataDymZ.Amp5,dataDymZ.Phase1, dataDymZ.Phase2, dataDymZ.Phase3, dataDymZ.Phase4, nowTimetamp.c_str()); + sql_ctl->UpdateTableData(T_DATA_INFO(TNAME), updateSql, whereCon); + } + print_info("Z: %s,%s,diagnosisPk=%f,integratPk=%f,integratRMS=%f,rmsValues=%f,envelopEnergy=%f,Amp1=%f,Amp2=%f,Amp3=%f,Amp4=%f,Amp5=%f,Phase1=%f,Phase2=%f,Phase3=%f,Phase4=%f,timeStamp=%s\n",\ + strLongAddr.c_str(), (strLongAddr + "-Z").c_str(), dataDymZ.DiagnosisPk, dataDymZ.IntegratPk, dataDymZ.IntegratRMS, dataDymZ.RmsValues, dataDymZ.EnvelopEnergy,\ + dataDymZ.Amp1, dataDymZ.Amp2, dataDymZ.Amp3, dataDymZ.Amp4, dataDymZ.Amp5,dataDymZ.Phase1, dataDymZ.Phase2, dataDymZ.Phase3, dataDymZ.Phase4, nowTimetamp.c_str()); + + //无线传感器Z信息 + valNodeFeature["dataNodeNo"] = strLongAddr; + valNodeFeature["channelID"] = strLongAddr + "-Z"; + valNodeFeature["diagnosisPk"] = dataDymZ.DiagnosisPk; + valNodeFeature["integratPk"] = dataDymZ.IntegratPk; + valNodeFeature["integratRMS"] = dataDymZ.IntegratRMS; + valNodeFeature["rmsValues"] = dataDymZ.RmsValues; + valNodeFeature["envelopEnergy"] = dataDymZ.EnvelopEnergy; + valNodeFeature["Amp1"] = dataDymZ.Amp1; + valNodeFeature["Amp2"] = dataDymZ.Amp2; + valNodeFeature["Amp3"] = dataDymZ.Amp3; + valNodeFeature["Amp4"] = dataDymZ.Amp4; + valNodeFeature["Amp5"] = dataDymZ.Amp5; + valNodeFeature["Phase1"] = dataDymZ.Phase1; + valNodeFeature["Phase2"] = dataDymZ.Phase2; + valNodeFeature["Phase3"] = dataDymZ.Phase3; + valNodeFeature["Phase4"] = dataDymZ.Phase4; + valNodeFeature["timeStamp"] = nowTimetamp; + valNodeData.append(valNodeFeature); + + //无线传感器信息 + Json::Value root; + Json::Value valdatastatic; + valdatastatic["TemperatureTop"] = dataStatic.TemTop; + valdatastatic["TemperatureBot"] = dataStatic.TemBot; + valdatastatic["Dip"] = dataStatic.Dip; + valdatastatic["Voltage"] = dataStatic.Voltage; + valdatastatic["ChannelType"] = "STATUS"; + valdatastatic["ChannelId"] = strLongAddr + "-S"; + valdatastatic["TimeStamp"] = nowTimetamp; + valdatastatic["dataNodeNo"] = strLongAddr; + valNodeData.append(valdatastatic); + + root["data"] = valNodeData; + root["TimeStamp"] = nowTimetamp; + root["dataNodeNo"] = strLongAddr; + root["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + Json::FastWriter featureValue; + std::string strstatisticData = featureValue.write(root); + //传感器发来的数据包中的表示设备信息的数据转化为json格式后,通过调用data_publish将数据传给mqttclient : Topic:wireless/cmd/60294D203717 + data_publish(strstatisticData.c_str(), GlobalConfig::Topic_G.mPubData.c_str()); + //综上代码,把静态数据,x y z轴的特征值存放到sql数据库中(如果数据原来不存在,则插入新数据;如果存在,则更新数据) + print_info("Dip : %d TemBot : %f TemBot : %f Voltage : %d\n", dataStatic.Dip, dataStatic.TemBot, dataStatic.TemTop, dataStatic.Voltage); + +} + +void Uart::DealDataNodeWave(const char *pData) +{ + print_info("recv wave\n"); + RecvData * pRecvData = (RecvData *)pData; + m_VecWaveData.push_back(*pRecvData); + print_blue("wave data size is(m_VecWaveData.size) : %d\n",m_VecWaveData.size()); + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + // 接收到原始数据信息,则更新时间戳,如果三秒种未收到原始数据,则重新从短地址 9999 切换回 短地址 8888 + m_TimeStamp = strtol(localtimestamp, NULL, 10); +} + + +void Uart::DealWaveThread() //连续三秒没有原始数据,则处理缓存的原始数据 +{ + unsigned long nowTimeStamp = 0; + unsigned long tmpTimeStamp = 0; + + while (1) + { + // 接收到原始波形,则 m_TimeStamp 不为零 + // 如果当前时间与记录时间超过3秒,要求,m_TimeStamp不变化,而数据在传输,则一定小于3秒 + if (0 == m_TimeStamp) { + boost::this_thread::sleep(boost::posix_time::seconds(1)); + continue; + } + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + nowTimeStamp = strtol(localtimestamp, NULL, 10); + // 避免在未同步时钟导致数据错误 + if(nowTimeStamp >= m_TimeStamp) { + tmpTimeStamp = nowTimeStamp - m_TimeStamp; + } + else { + tmpTimeStamp = m_TimeStamp - nowTimeStamp; + } + //if ((nowTimeStamp - m_TimeStamp) > 3) { 时间戳需要修改为绝对值,可能丢失时钟,或工作一会儿,才同步时钟,可能减出异常值 + if (tmpTimeStamp > 3) { // TODO: 时间戳需要修改为绝对值,可能丢失时钟,或工作一会儿,才同步时钟,可能减出异常值 print_info("yes!The time difference is more than 3,nowTimeStamp : %ld m_TimeStamp : %ld\n", nowTimeStamp, m_TimeStamp); + DealWave(); + m_TimeStamp = 0; + pUart->UpdateZigbeeInfoCtrl(); + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + // 准备重新恢复到 8888 PanID,正常接收特征数据 + ZigbeeInit(); + } else { + print_info("NO! The time difference is less than 3,nowTimeStamp : %ld m_TimeStamp : %ld\n", nowTimeStamp, m_TimeStamp); + } + + boost::this_thread::sleep(boost::posix_time::seconds(1)); + } +} + +void Uart::DealWave() +{ + print_info("begin deal Wave data !\n"); + std::string strShortAddr = ""; + std::string strShortAddrTemp; + std::string strLongAddr = ""; + std::string strFileName = ""; + int iChannel = 0; + int iChannelTemp = 0; + long iTemp = 0; + std::vector vecData; + char buf[8]; + RecvData recvTemp; + + print_info("all wave data size is(m_VecWaveData.size) : %d\n", m_VecWaveData.size()); + while (m_VecWaveData.size() > 0) { //对每个传感器的每个通道进行遍历然后处理数据,例如:传感器1x轴的数据处理完后,再去处理y轴的。传感器1的所有数据处理完后,再处理传感器2的 + std::vector::iterator iter = m_VecWaveData.begin(); + recvTemp = *iter; + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", recvTemp.ShortAddr[0], recvTemp.ShortAddr[1]); + strShortAddr = std::string(buf); + + memset(buf, 0, 8); + sprintf(buf, "%02d", recvTemp.Type&0xFF); + iChannel = boost::lexical_cast(buf); + + char getLongAddr_sql[32] = { 0 }; + sprintf(getLongAddr_sql, "zigbeeShortAddr='%s'", strShortAddr.c_str()); + strLongAddr = sql_ctl->GetData(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(ZIGBEELONGADDR), getLongAddr_sql); + //print_info("3.1.2.3--->strLongAddr : %s\n", strLongAddr.c_str()); + if ( 0 == strLongAddr.length() ) { + boost::this_thread::sleep(boost::posix_time::seconds(1)); + continue; + } + + std::string ran = ""; + int n = 0; + int range = 0; + float coe = 0; + char getrange[32] = {0}; + std::string str = "range"; + sprintf(getrange, "scope='%s'", str.c_str()); + ran = sql_ctl->GetData(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(RANGE), getrange); + //print_info("@@@@@@@@@@@@@@@@@@@@@@ran=%s\n",ran.c_str()); + memset(getrange, 0, 32); + sprintf(getrange, "%s", ran.c_str()); + n = (int)strtol(getrange, NULL, 32); + //print_light_purple("!!!!!!!!!!!!!n=%d\n",n); + switch (n) + { + case 0:{ + range = 8; + coe = 8*1.0/32767; + } + break; + case 1:{ + range = 16; + coe = 16*1.0/32767; + } + break; + case 2:{ + range = 32; + coe = 32*1.0/32767; + } + break; + case 3:{ + range = 64; + coe = 64*1.0/32767; + } + break; + } + //print_blue("##############range = %d,%f\n",range,coe); + for(; iter != m_VecWaveData.end();) + { + recvTemp = *iter; + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", recvTemp.ShortAddr[0], recvTemp.ShortAddr[1]); + strShortAddrTemp = std::string(buf); + + memset(buf, 0, 8); + sprintf(buf, "%02d", recvTemp.Type & 0xFF); + iChannelTemp = boost::lexical_cast(buf); + + if( 0 == strShortAddr.compare(strShortAddrTemp) && (iChannel == iChannelTemp) ) { + float fTemp; + for (int i = 0; i < 46; i++) { + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", recvTemp.Data[2*i+1],recvTemp.Data[i*2]); + iTemp = strtol(buf, NULL, 16); + if (iTemp < 0x8000) { + fTemp = iTemp * coe; + } else { + fTemp = (((~iTemp)&0xffff) + 1) * -coe; + } + //print_blue("wave data is %u,%f\n",iTemp,fTemp); + vecData.push_back(fTemp); + } + iter = m_VecWaveData.erase(iter); + } else { + iter++; + } + } + + + /*char getLongAddr_sql[32] = { 0 }; + sprintf(getLongAddr_sql, "zigbeeShortAddr='%s'", strShortAddr.c_str()); + strLongAddr = sql_ctl->GetData(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(ZIGBEELONGADDR), getLongAddr_sql); + + print_info("strLongAddr : %s\n", strLongAddr.c_str());*/ + if ( 0 == strLongAddr.length() ) { + boost::this_thread::sleep(boost::posix_time::seconds(1)); + continue; + } + std::string strChannelID = ""; + switch (iChannel) + { + case 3:{ + strFileName = "/opt/data/" + strLongAddr + "-X.dat"; + strChannelID = strLongAddr + "-X"; + } + break; + case 4:{ + strFileName = "/opt/data/" + strLongAddr + "-Y.dat"; + strChannelID = strLongAddr + "-Y"; + } + break; + case 5:{ + strFileName = "/opt/data/" + strLongAddr + "-Z.dat"; + strChannelID = strLongAddr + "-Z"; + } + break; + default: + break; + } + + if (access(strFileName.c_str(), 0) > 0) { //如果存在原始数据删除原来的,只保留一份 + std::string strCmd = "rm " + strFileName; + system(strCmd.c_str()); + } + + + FILE *fp = fopen(strFileName.c_str(), "w"); + print_info("fopen FIle vecData.size : %d\n", vecData.size()); + float frTemp; + char buf[33]={0x00}; + std::string strWaveData = ""; + for (int i = 0; i < vecData.size(); i++) { + frTemp = vecData[i]; + fwrite(&frTemp,sizeof(float),1,fp); + memset(buf,0x00,sizeof(buf)); + sprintf(buf, "%.2f", vecData[i]); + std::string waveTemp(buf); + if(i == 0) + strWaveData = waveTemp; + strWaveData = strWaveData + "," + waveTemp; + } + vecData.clear(); + fclose(fp); + // + Json::Value valWaveData; + valWaveData["number"] = strWaveData.length(); + valWaveData["channelId"] = strChannelID; + valWaveData["dataNodeNo"] = strLongAddr; + valWaveData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + valWaveData["SensorEngineeringUnit"] = ""; + valWaveData["waveData"] = strWaveData; + Json::FastWriter WaveValue; + std::string WaveData = WaveValue.write(valWaveData); + //传感器发来的数据包中的表示设备信息的数据转化为json格式后,通过调用data_publish将数据传给mqttclient : Topic:wireless/cmd/60294D203717 + data_publish(WaveData.c_str(), GlobalConfig::Topic_G.mPubWaveData.c_str()); + print_info("write data to filename %s\n", strFileName.c_str()); + boost::this_thread::sleep(boost::posix_time::seconds(1)); + } + + + // memset(buf, 0, 8); + // sprintf(buf, "%02x%02x", recvTemp.ShortAddr[0], recvTemp.ShortAddr[1]); + // std::string strShortAddr = std::string(buf); + +} + +void Uart::modify_info(unsigned short id, char * zigbee) +{ + int i, j, ret,con; + char command[100]; + char command1[20]; + char tmp = 0; + command[0] = 0xab; + command[1] = 0xbc; + command[2] = 0xcd; + command[3] = 0xd6; + command[4] = ((char *)&id)[1]; + command[5] = ((char *)&id)[0]; + command[6] = 0; + if (zigbee != NULL) { + con = 71; + memcpy(&(command[6]), zigbee + 4, 65); + } else { + con = 6; + } + for(i = 0; i < con; i++) + { + tmp += command[i]; + } + command[i] = tmp; + WriteToUart(command, i+1); + boost::this_thread::sleep(boost::posix_time::seconds(1)); +} + +void Uart::zigbee_reset(unsigned short pad, unsigned short type) +{ + char command[10],tmp = 0,i; + command[0] = 0xab; + command[1] = 0xbc; + command[2] = 0xcd; + command[3] = 0xd9; + command[4] = ((char *)&pad)[1]; + command[5] = ((char *)&pad)[0]; + command[6] = ((char *)&type)[1]; + command[7] = ((char *)&type)[0]; + for(i = 0; i<8; i++) + { + tmp += command[i]; + } + command[8] = tmp; + WriteToUart(command, 9); +} + +void Uart::WriteChanl2Zigbee(unsigned char pad) +{ + print_info("WriteChanl2Zigbee : %d\n", pad); + unsigned char pad1 = pad; + unsigned short tmp; + tmp = GlobalConfig::Zigbee_G.MyAddr; + //swap((char *)&pad1); + swap((char *)&tmp); + GlobalConfig::Zigbee_G.Chan = pad1; + modify_info(tmp, (char *)& GlobalConfig::Zigbee_G); + zigbee_reset(tmp, 1); +} + +void Uart::WritePanId2Zigbee(unsigned short pad) +{ + print_info("WritePanId2Zigbee : %d\n", pad); + unsigned short pad1 = pad,tmp; + tmp = GlobalConfig::Zigbee_G.MyAddr; + swap((char *)&pad1); + swap((char *)&tmp); + GlobalConfig::Zigbee_G.PanID = pad1; + modify_info(tmp, (char *)&GlobalConfig::Zigbee_G); + zigbee_reset(tmp, 1); +} + + +void Uart::WriteShortAddr2Zigbee(unsigned short pad) +{ + print_info("WriteShortAddr2Zigbee : %4x\n", (unsigned short)pad); + unsigned short pad1 = pad,tmp; + tmp = GlobalConfig::Zigbee_G.MyAddr; + swap((char *)&pad1); + swap((char *)&tmp); + GlobalConfig::Zigbee_G.MyAddr = pad1; + modify_info(tmp, (char *)& GlobalConfig::Zigbee_G); + zigbee_reset(tmp, 1); +} + +void Uart::ZigbeeInit() +{ + + std::string strPanId = GlobalConfig::MacAddr_G.substr(8); + print_info("strPanId : %s\n", strPanId.c_str()); + // 新增管理ZigBee代码 + std::string strchan = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "channel"); + unsigned char Chan = (unsigned char)strtol(strchan.c_str(), NULL, 10); + printf("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%the chan = %u\n",Chan); + print_info("ZigbeeInfo_G.Channel=%d\n",GlobalConfig::ZigbeeInfo_G.Channel); + if(Chan > 10 && Chan < 27) + { + if (Chan != GlobalConfig::ZigbeeInfo_G.Channel) { + printf("the chanl is different\n"); + WriteChanl2Zigbee(Chan); + boost::this_thread::sleep(boost::posix_time::seconds(1)); + } + } + + if (0 != GlobalConfig::ZigbeeInfo_G.PanID.compare(strPanId.c_str())) { + long lShortAddr = strtol(strPanId.c_str(), NULL, 16); + unsigned short panid = lShortAddr & 0xffff; + print_info("the panid is different\n"); + WritePanId2Zigbee(panid); + boost::this_thread::sleep(boost::posix_time::seconds(1)); + } + + if (0 != GlobalConfig::ZigbeeInfo_G.MyAddr.compare("8888")) { + unsigned short shortAddr = 0x8888; + print_info("the short addr is different\n"); + WriteShortAddr2Zigbee(shortAddr); + boost::this_thread::sleep(boost::posix_time::seconds(1)); + LOG_INFO("[ZigbeeInit---------] ZigBee PanID: %s ; Channel: %d ; MyAddr : %4x ",GlobalConfig::ZigbeeInfo_G.PanID.c_str(),GlobalConfig::ZigbeeInfo_G.Channel, + (unsigned short)GlobalConfig::Zigbee_G.MyAddr); + // 更新GlobalConfig::ZigbeeInfo_G.MyAddr,用于外部显示 + char tmp[16]; + sprintf(tmp,"%4x",(unsigned short)GlobalConfig::Zigbee_G.MyAddr); + std::string strTmp(tmp); + GlobalConfig::ZigbeeInfo_G.MyAddr = strTmp; + } + print_info("ZigbeeInfo_G.MyAddr=%s\n",GlobalConfig::ZigbeeInfo_G.MyAddr.c_str()); + +} + + diff --git a/uart/SH_Uart.hpp b/uart/SH_Uart.hpp new file mode 100644 index 0000000..55524a1 --- /dev/null +++ b/uart/SH_Uart.hpp @@ -0,0 +1,71 @@ +#ifndef _UART_H_ +#define _UART_H_ +#include +#include +#include +#include +#include +#include +#include +#include "../utility/SH_MySingleton.hpp" +#include "../common/SH_CommonFunc.hpp" +#include "../common/SH_global.h" +#include "../dbaccess/SH_SqlDB.hpp" + + + +//using namespace boost::asio; +//using std::string; +//using boost::system::error_code; +typedef unsigned int UINT; + + +class Uart : public MySingleton +{ +private : + boost::posix_time::ptime mLocalTime; + boost::asio::io_service mIoSev; + boost::asio::serial_port mUart; + int mRdLength; + enum{BUF_LENGTH = 1024}; + char mUartRecvBuf[BUF_LENGTH]; + boost::mutex mLock; + boost::asio::io_service::strand mStrand; + +public : + Uart(); + void InitUart(); + ~Uart(); + void WriteToUart(const char *strSend,int pLen); + void ReadFromUart(); + void setCallBack(onReceiveUart _callback); + void Run(); + void Stop(); + void UpdateZigbeeInfoCtrl(); + void UpdateZigbeeInfo(const char *pData); + void DealRecvData(const char *pData); + void DealDataNodeInfo(const char *pData); + void DealDataNodeFeature(const char *pData, int flag); + void DealDataNodeWave(const char *pData); + void DealWaveThread(); + void DealWave(); + void ZigbeeInit(); + + void modify_info(unsigned short id, char * zigbee); + void zigbee_reset(unsigned short pad, unsigned short type); + void WriteChanl2Zigbee(unsigned char pad); + void WritePanId2Zigbee(unsigned short pad); + void WriteShortAddr2Zigbee(unsigned short pad); + virtual void DataAnalysis_R(DevDataOfGwid &pData); + virtual void DataAnalysis_W(DevData &pData,bool pFlag); + virtual void ThreadInit(); +private : + void ReadHandle(const boost::system::error_code &ec,size_t bytesRead); + void WriteHandle(const char *strSend,const boost::system::error_code &ec,size_t bytesWrite); + onReceiveUart m_callback; + std::vector m_VecWaveData; + unsigned long m_TimeStamp; +}; + + +#endif diff --git a/udpqt/SH_UdpQt.cpp b/udpqt/SH_UdpQt.cpp new file mode 100644 index 0000000..e692297 --- /dev/null +++ b/udpqt/SH_UdpQt.cpp @@ -0,0 +1,194 @@ +#include "SH_UdpQt.hpp" +#include "../common/SH_CommonFunc.hpp" +#include "../common/SH_global.h" +#include "../API_log/SH_log.h" + + + +UdpSys::UdpSys(): + mIoSev(), udpSock(mIoSev, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 7303)) +{ + print_light_green("UdpQt Init\n"); +} + + +void UdpSys::ClearConnect() +{ + remoteIp.clear(); + status = false; +} + +void UdpSys::StartConnectSysUdp() +{ + print_light_green("start connect QT\n"); + if (udpSock.is_open()) { + boost::asio::socket_base::linger option1(true, 0); + udpSock.set_option(option1); + boost::asio::socket_base::send_buffer_size option4(125000); + udpSock.set_option(option4); + remoteEndPoint = boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 9998); + remoteEndPoint.address(boost::asio::ip::address::from_string("127.0.0.1")); + recvUdpData(); + // boost::thread sendHeartTh(boost::bind(&UdpQt::ConfirmStatus, this)); + // sendHeartTh.detach(); + mIoSev.run(); + } +} + +void UdpSys::handle_send_to(const boost::system::error_code& ec, + size_t trans) +{ + if (ec) { + print_error("send the udp to sys error! \n"); + } else { + print_info("send the udp to sys ok! \n"); + } +} + +void UdpSys::SendUdpToSingle(std::string pData) +{ + boost::mutex::scoped_lock lock(udpMutex); + int len = pData.length(); + if (len <= 0) + return ; + char *mi = new char[len + 3]; + memset(mi, 0, len + 3); + strcpy(mi, pData.c_str()); + strcat(mi, "\r\n"); +// std::cout << "sys send single:" << pData << remoteEndPoint.address() << remoteEndPoint.port() <0){ + AnalysisDataSys(read_cmd); + } + } + recvUdpData(); +} + +void UdpSys::AnalysisDataSys(std::string cmd) +{ + printf("%s", cmd.c_str()); + Json::Reader recvReader; + Json::Value JsonVal; + if(recvReader.parse(cmd,JsonVal)) { + int cmdType = atoi(JsonVal["cmd"].asString().c_str()); + switch (cmdType) { + case 3:{ //配置服务器 + std::string strServerIp = JsonVal["localServerIpAddress"].asString(); + int localServerPort = JsonVal["localServerPort"].asInt(); + + std::string strDataWatchAddedBy = "system"; + if (!JsonVal["dataNodeGatewayAddedBy"].isNull()) { + strDataWatchAddedBy = JsonVal["dataNodeGatewayAddedBy"].asString(); + WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy", strDataWatchAddedBy); + } + + print_info("strServerIp : %s \n", strServerIp.c_str()); + if (strServerIp.compare(GlobalConfig::ServerIP) != 0 || localServerPort != GlobalConfig::ServerPort) + { + GlobalConfig::ServerIP = strServerIp; + GlobalConfig::ServerPort = localServerPort; + + WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", GlobalConfig::ServerIP); + WriteStr2Config(SERVERCONFIG, "Server", "localServerPort", boost::lexical_cast(GlobalConfig::ServerPort)); + + std::string fileserver = ReadStrByOpt(SERVERCONFIG, "FileServer", "FileServerIpAddress"); + if (0 == fileserver.compare("0.0.0.0") || 0 == fileserver.length()) { + WriteStr2Config(SERVERCONFIG, "FileServer", "FileServerIpAddress", GlobalConfig::ServerIP); + } + + JsonVal["status"] = "ACK"; + Json::FastWriter fw; + std::string str = fw.write(JsonVal); + print_info("send info : %s \n", str.c_str()); + boost::asio::ip::udp::endpoint remoteEP(boost::asio::ip::address::from_string(senderEndPoint.address().to_string()), + MULTICAST_PORT_SEND); + udpSock.async_send_to(boost::asio::buffer(str),remoteEP, + boost::bind(&UdpSys::handle_send_to,this,boost::asio::placeholders::error, + boost::asio::placeholders::bytes_transferred)); + + // Json::Value jsValue; + // Json::FastWriter fw1; + // jsValue["type"] = "set"; + // std::string data = fw1.write(jsValue); + // data_publish_local(data.c_str(), GlobalConfig::Topic_G.mPubLocalConfig.c_str()); + + // boost::this_thread::sleep(boost::posix_time::seconds(2)); + // exit(0); + } else { + // char reply_string[256] = {0}; + // sprintf(reply_string, "{\"dataNodeGatewayNo\":\"%s\",\"softVersion\":\"%s\",\"status\":\"0\"}", + // GlobalConfig::MacAddr_G.c_str(), GlobalConfig::Version.c_str()); + + // std::string instr = std::string(reply_string); + // std::string topic = "equipment/state/" + GlobalConfig::MacAddr_G; + + // int ret = data_publish(instr.c_str(), topic.c_str()); + + // std::string cmd20 = JsonCmd_Cgi_20(); + // data_publish(cmd20.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + } + } + break; + case 4:{ + Json::FastWriter fw; + std::string status = JsonVal["status"].asString(); + if(status.compare("REQ") == 0) + { + JsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G.c_str(); + JsonVal["localServerIpAddress"] = GlobalConfig::ServerIP; + JsonVal["status"] = "ACK"; + std::string data = fw.write(JsonVal); + boost::asio::ip::udp::endpoint remoteEP(boost::asio::ip::address::from_string(senderEndPoint.address().to_string()), + MULTICAST_PORT_SEND); + udpSock.async_send_to(boost::asio::buffer(data),remoteEP, + boost::bind(&UdpSys::handle_send_to,this,boost::asio::placeholders::error, + boost::asio::placeholders::bytes_transferred)); + } + } + break; + default: + break; + } + }else + { + print_error("json parse failed"); + } +} + +UdpSys::~UdpSys() +{ + if (udpSock.is_open()) + udpSock.close(); +} \ No newline at end of file diff --git a/udpqt/SH_UdpQt.hpp b/udpqt/SH_UdpQt.hpp new file mode 100644 index 0000000..6c095df --- /dev/null +++ b/udpqt/SH_UdpQt.hpp @@ -0,0 +1,105 @@ +#ifndef UDPQT_H +#define UDPQT_H + +#include +#include +#include +#include +#include +#include +#include +#include "../utility/SH_MySingleton.hpp" +#include "../common/SH_global.h" + + + +#define MULTICAST_PORT_SEND 7302 //根据接收组播udp发送端口 + +#define SYSUDPIP "127.0.0.1" +#define SYSUDPPORT "9999" + +#define RECIEVE_CONNECT_STATUS 1 //QT连接确认 +#define RECIEVE_CONFIG_GET 3 //获取配置信息 +#define RECIEVE_WIFI_CONTROL 4 //wifi操作 +#define RECIEVE_WAVEDATA_CONTROL 7 //原始数据操作 + + +#define CMD_TYPE_CONNECTQT 1 +#define RECIEVE_CONFIG_GET 3 +#define RECIEVE_WIFI_CONTROL 4 +#define RECIEVE_WAVEDATA_CONTROL 7 + + +class UdpSys : public MySingleton { +public: + UdpSys(); + ~UdpSys(); + /** + * @brief 发送数据 + * @param pData 发送的字符串数据 + * @return void + */ + void SendUdpToSingle(std::string pData); + + /** + * @brief 连接子程序 + * @return void + */ + void StartConnectSysUdp(); + + /** + * @brief 清除连接 + * @return void + */ + void ClearConnect(); + + /** + * @brief 确认连接 + * @return void + */ + // void ConfirmStatus(); + +private: + + /** + * @brief 发送数据的回调函数 + * @return void + */ + void handle_send_to(const boost::system::error_code& ec, + size_t trans); + + /** + * @brief 接收数据 + * @return void + */ + void recvUdpData(); + + /** + * @brief 数据分析 + * @return void + */ + void AnalysisDataSys(std::string cmd); + + /** + * @brief 接收数据的回调函数 + * @return void + */ + void HandleRead(const boost::system::error_code& pEc, + std::size_t pBytesTransferred); +private: + boost::mutex udpMutex; + std::string remoteIp; + int remoteport; + boost::asio::ip::udp::endpoint remoteEndPoint; + boost::asio::ip::udp::endpoint senderEndPoint; + boost::asio::io_service mIoSev; + boost::asio::ip::udp::socket udpSock; + boost::array m_buffer; + std::string mData; + bool status; + int times; +}; + + +#endif + diff --git a/utility/Caculation.h b/utility/Caculation.h new file mode 100644 index 0000000..4851e0f --- /dev/null +++ b/utility/Caculation.h @@ -0,0 +1,201 @@ +#ifndef CACULATION_H_ +#define CACULATION_H_ + +#include +#include +#include +using namespace std; + +class Caculation +{ +public: + Caculation(); + ~Caculation(); + + template + static T maxValue(T(&data)[N]); + + template + static T minValue(T(&data)[N]); + + template //����ƽ��ֵ + static T dcValue(T(&data)[N]); + + + + template //����RMS + static T caculateRMS(T(&data)[N]); + + template //������ֵ + static T caculatePKtoPk(T(&data)[N]); + + + //���ٸ���Ҷ�任���� + static void FFT(int n, fftw_complex* in, fftw_complex* out); + + //ͨ����ֵ����λ��ȡ + //����ΪFFT�任������ݳ��ȼ����ݣ�ָ����Ƶ�ʣ����Ϊ�����õ��ķ�ֵ �� ��λ + static void caculateAmp_Pha(int n, fftw_complex* in, int frequency, double &litude, double &phase); + + template //����hanning���� + static vector hanning(int N, T amp); + + template //����hamming���� + static vector hamming(int N, T amp); + + //ͳ�Ƽ��� +}; + +Caculation::Caculation() +{ +} + +Caculation::~Caculation() +{ +} + +/************************************************************************/ +/*�����������ݵ����ֵ */ +/************************************************************************/ +template +T Caculation::maxValue(T(&data)[N]) +{ + if (0 == N) return 0; + T max = data[0]; + for (int i = 1; i < N; i++) + if (max < data[i]) + max = data[i]; + return max; +} + +/************************************************************************/ +/*�����������ݵ���Сֵ */ +/************************************************************************/ +template +T Caculation::minValue(T(&data)[N]) +{ + if (0 == N) return 0; + T min = data[0]; + for (int i = 1; i < N; i++) + if (min > data[i]) + min = data[i]; + return min; +} + +/************************************************************************/ +/*�����������ݵ�ƽ��ֵ */ +/************************************************************************/ +template +T Caculation::dcValue(T(&data)[N]) +{ + if (0 == N) return 0; + T sum = 0; + for (int i = 0; i < N; i++) + sum += data[i]; + return sum / N; +} + + +/************************************************************************/ +/* ������������RMS */ +/************************************************************************/ +template +T Caculation::caculateRMS(T(&data)[N]) +{ + if (0 == N) return 0; + T fSum = 0; + for (int i = 0; i < N; i++) + fSum += data[i] * data[i]; + return sqrt(fSum / N); +} + +/************************************************************************/ +/* �����������ݷ��ֵ */ +/************************************************************************/ +template +T Caculation::caculatePKtoPk(T(&data)[N]) +{ + if (0 == N) return 0; + T min = data[0]; + T max = data[0]; + for (int i = 1; i < N; i++) + { + if (data[i] < min) min = data[i]; + if (data[i] > max) max = data[i]; + } + return max - min; +} + +/************************************************************************/ +/* һά���ݵĿ��ٸ���Ҷ�任 */ +/************************************************************************/ +void Caculation::FFT(int n, fftw_complex* in, fftw_complex* out) +{ + if (in == NULL || out == NULL) return; + fftw_plan p; + p = fftw_plan_dft_1d(n, in, out, FFTW_FORWARD, FFTW_ESTIMATE); + fftw_execute(p); + fftw_destroy_plan(p); + fftw_cleanup(); +} + +//************************************ +// Method: caculateAmp_Pha +// FullName: Caculation::caculateAmp_Pha +// Access: public static +// Returns: void +// Qualifier: +// Parameter: int n +// Parameter: fftw_complex * in +// Parameter: int frequency +// Parameter: double & amplitude +// Parameter: double & phase +// ���������Ǽ����ض�Ƶ�ʵķ�ֵ����λ��ԭ�����������Ǵ���һ���ض���Ƶ�ʣ�Ȼ���ڸ�����Ƶ�����ҷ�Χ���ҷ�ֵ����λ +// Ŀǰ�ĺ���ʵ���Ǽ���FFT�任���ض���ķ�ֵ����λ +// Ȼ����һ���ط���Ҫ�޸ģ�������Ƶ�ʺ�FFT�任������� +//************************************ +void Caculation::caculateAmp_Pha(int n, fftw_complex* in, int frequency, double &litude, double &phase) +{ + int index = frequency; + amplitude = 2 * sqrt((in[index][0] / n) * (in[index][0] / n) + (in[index][1] / n) * (in[index][1] / n)); + phase = 180 * atan(in[index][1] / in[index][0]) / M_PI; +} + +/************************************************************************/ +/* ����hanning���� */ +/************************************************************************/ +template +vector Caculation::hanning(int N, T amp) +{ + vector win(N); + + for (int i = 0; i < (N + 1) / 2; ++i) + { + win[i] = amp * T(0.5 - 0.5*cos(2 * M_PI*i / (N - 1))); + win[N - 1 - i] = win[i]; + } + + return win; +} + + +/************************************************************************/ +/* ����hamming���� */ +/************************************************************************/ +template +vector Caculation::hamming(int N, T amp) +{ + vector win(N); + + for (int i = 0; i < (N + 1) / 2; ++i) + { + win[i] = amp * T(0.54 - 0.46*cos(2 * M_PI*i / (N - 1.0))); + win[N - 1 - i] = win[i]; + } + + return win; +} + +#endif + + diff --git a/utility/RuleCheck.cpp b/utility/RuleCheck.cpp new file mode 100644 index 0000000..869d342 --- /dev/null +++ b/utility/RuleCheck.cpp @@ -0,0 +1,44 @@ +#include +#include + +/*************************************************************************** +* Function Name: valiFoldername +* Description: The ength of folder name should be less than 255. +* Illegal characters are \<>()[]&:,/|?* \0 ~ \31 +* Return: 0 for success, otherwise 1. +****************************************************************************/ +#define MAX_FOLDER_NAME_LEN 255 + +int validFoldername(const char *pName) +{ + int ret = 0; + unsigned int u32Length = 0, u32Index = 0; + const char u8SpecialChar[] = { '\\','<','>','(',')','[',']','&',':',',','/','|','?','*' }; + const unsigned char u8CtrlCharBegin = 0x0, u8CtrlCharEnd = 0x31; + + if (pName == NULL) + { + ret = 1; + } + else + { + u32Length = strlen(pName); + if (u32Length >= MAX_FOLDER_NAME_LEN) + ret = 1; + } + for (u32Index = 0; (u32Index < u32Length) && (ret == 0); + u32Index++) + { + if (u8CtrlCharBegin <= pName[u32Index] <= u8CtrlCharEnd) + { + ret = 1; + } + else if (strchr(u8SpecialChar, pName[u32Index]) != NULL) + { + ret = 1; + } + } + + return ret; +} + diff --git a/utility/SH_MySingleton.hpp b/utility/SH_MySingleton.hpp new file mode 100644 index 0000000..d70b24a --- /dev/null +++ b/utility/SH_MySingleton.hpp @@ -0,0 +1,23 @@ +#ifndef MYSINGLETON_H_ +#define MYSINGLETON_H_ + +template +class MySingleton { +public: + static T* instance() { + static T _instance; + return &_instance; + } + ; +protected: + MySingleton() { + } + ; + virtual ~MySingleton() { + } + ; + MySingleton(const MySingleton &); + MySingleton& operator=(const MySingleton &); +}; + +#endif