commit 83183b011ed46e4f7450005d539d443334f88b5b Author: pandx Date: Sat Oct 19 16:02:41 2024 +0800 first init. diff --git a/API_log/SH_log.cpp b/API_log/SH_log.cpp new file mode 100644 index 0000000..d26b3a1 --- /dev/null +++ b/API_log/SH_log.cpp @@ -0,0 +1,110 @@ +#include "SH_log.h" + +#include +#include +#include +#include +#include +#include +#include +#include "../common/SH_global.h" +#include "../common/SH_CommonFunc.hpp" + +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; + + struct timeval now = {0,0}; + gettimeofday(&now, NULL); + time_t t ; + t = now.tv_sec; + struct tm* sys_tm = localtime(&t); + char fileTime[20]={0x00}; + char fileName[100]={0x00}; + int n = snprintf(fileTime, 64, "%d-%02d-%02d.log", sys_tm->tm_year+1900, sys_tm->tm_mon+1, sys_tm->tm_mday); + sprintf(fileName,"%s%s",file_name,fileTime); + strcpy(gLogParam.m_log_full_name, fileName); + + return 0; +} + +void log_write(const char *level, const char* format, ...) +{ + struct timeval now = {0,0}; + gettimeofday(&now, NULL); + time_t t; + t = now.tv_sec; + struct tm* sys_tm = localtime(&t); + char fileTime[20]={0x00}; + char fileName[100]={0x00}; + int n = snprintf(fileTime, 64, "%d-%02d-%02d.log", sys_tm->tm_year+1900, sys_tm->tm_mon+1, sys_tm->tm_mday); + sprintf(fileName,"%s%s",SOFTWARE_RUN_LOG,fileTime); + strcpy(gLogParam.m_log_full_name, fileName); + 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); + + + pthread_mutex_lock(gLogParam.m_mutex); + + 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); + + int iRet = system(cmd); + if (iRet == -1) + { + perror("system() error"); + } + + print_brown("iRet = %d,cmd = %s\n",iRet,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/API_log/subdir.mk b/API_log/subdir.mk new file mode 100644 index 0000000..7c085e4 --- /dev/null +++ b/API_log/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../API_log/SH_log.cpp + +CPP_DEPS += \ +./API_log/SH_log.d + +OBJS += \ +./API_log/SH_log.o + + +# Each subdirectory must supply rules for building sources it contributes +API_log/%.o: ../API_log/%.cpp API_log/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-API_log + +clean-API_log: + -$(RM) ./API_log/SH_log.d ./API_log/SH_log.o + +.PHONY: clean-API_log + diff --git a/MD5/md5.cpp b/MD5/md5.cpp new file mode 100644 index 0000000..6c9cd15 --- /dev/null +++ b/MD5/md5.cpp @@ -0,0 +1,304 @@ +#include "md5.h" + +#ifndef HAVE_OPENSSL + + #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) + #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) + #define H(x, y, z) ((x) ^ (y) ^ (z)) + #define I(x, y, z) ((y) ^ ((x) | ~(z))) + #define STEP(f, a, b, c, d, x, t, s) \ + (a) += f((b), (c), (d)) + (x) + (t); \ + (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ + (a) += (b); + + #if defined(__i386__) || defined(__x86_64__) || defined(__vax__) + #define SET(n) \ + (*(MD5_u32 *)&ptr[(n) * 4]) + #define GET(n) \ + SET(n) + #else + #define SET(n) \ + (ctx->block[(n)] = \ + (MD5_u32)ptr[(n) * 4] | \ + ((MD5_u32)ptr[(n) * 4 + 1] << 8) | \ + ((MD5_u32)ptr[(n) * 4 + 2] << 16) | \ + ((MD5_u32)ptr[(n) * 4 + 3] << 24)) + #define GET(n) \ + (ctx->block[(n)]) + #endif + + typedef unsigned int MD5_u32; + + typedef struct { + MD5_u32 lo, hi; + MD5_u32 a, b, c, d; + unsigned char buffer[64]; + MD5_u32 block[16]; + } MD5_CTX; + + static void MD5_Init(MD5_CTX *ctx); + static void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size); + static void MD5_Final(unsigned char *result, MD5_CTX *ctx); + + static const void *body(MD5_CTX *ctx, const void *data, unsigned long size){ + const unsigned char *ptr; + MD5_u32 a, b, c, d; + MD5_u32 saved_a, saved_b, saved_c, saved_d; + + ptr = (const unsigned char*)data; + + a = ctx->a; + b = ctx->b; + c = ctx->c; + d = ctx->d; + + do { + saved_a = a; + saved_b = b; + saved_c = c; + saved_d = d; + + STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) + STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) + STEP(F, c, d, a, b, SET(2), 0x242070db, 17) + STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) + STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) + STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) + STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) + STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) + STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) + STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) + STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) + STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) + STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) + STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) + STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) + STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) + STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) + STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) + STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) + STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) + STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) + STEP(G, d, a, b, c, GET(10), 0x02441453, 9) + STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) + STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) + STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) + STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) + STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) + STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) + STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) + STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) + STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) + STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) + STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) + STEP(H, d, a, b, c, GET(8), 0x8771f681, 11) + STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) + STEP(H, b, c, d, a, GET(14), 0xfde5380c, 23) + STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) + STEP(H, d, a, b, c, GET(4), 0x4bdecfa9, 11) + STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) + STEP(H, b, c, d, a, GET(10), 0xbebfbc70, 23) + STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) + STEP(H, d, a, b, c, GET(0), 0xeaa127fa, 11) + STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) + STEP(H, b, c, d, a, GET(6), 0x04881d05, 23) + STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) + STEP(H, d, a, b, c, GET(12), 0xe6db99e5, 11) + STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) + STEP(H, b, c, d, a, GET(2), 0xc4ac5665, 23) + STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) + STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) + STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) + STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) + STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) + STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) + STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) + STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) + STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) + STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) + STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) + STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) + STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) + STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) + STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) + STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) + + a += saved_a; + b += saved_b; + c += saved_c; + d += saved_d; + + ptr += 64; + } while (size -= 64); + + ctx->a = a; + ctx->b = b; + ctx->c = c; + ctx->d = d; + + return ptr; + } + + void MD5_Init(MD5_CTX *ctx){ + ctx->a = 0x67452301; + ctx->b = 0xefcdab89; + ctx->c = 0x98badcfe; + ctx->d = 0x10325476; + + ctx->lo = 0; + ctx->hi = 0; + } + + void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size){ + MD5_u32 saved_lo; + unsigned long used, free; + + saved_lo = ctx->lo; + if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) + ctx->hi++; + ctx->hi += size >> 29; + used = saved_lo & 0x3f; + + if (used){ + free = 64 - used; + if (size < free) { + memcpy(&ctx->buffer[used], data, size); + return; + } + + memcpy(&ctx->buffer[used], data, free); + data = (unsigned char *)data + free; + size -= free; + body(ctx, ctx->buffer, 64); + } + + if (size >= 64) { + data = body(ctx, data, size & ~(unsigned long)0x3f); + size &= 0x3f; + } + + memcpy(ctx->buffer, data, size); + } + + void MD5_Final(unsigned char *result, MD5_CTX *ctx){ + unsigned long used, free; + used = ctx->lo & 0x3f; + ctx->buffer[used++] = 0x80; + free = 64 - used; + + if (free < 8) { + memset(&ctx->buffer[used], 0, free); + body(ctx, ctx->buffer, 64); + used = 0; + free = 64; + } + + memset(&ctx->buffer[used], 0, free - 8); + + ctx->lo <<= 3; + ctx->buffer[56] = ctx->lo; + ctx->buffer[57] = ctx->lo >> 8; + ctx->buffer[58] = ctx->lo >> 16; + ctx->buffer[59] = ctx->lo >> 24; + ctx->buffer[60] = ctx->hi; + ctx->buffer[61] = ctx->hi >> 8; + ctx->buffer[62] = ctx->hi >> 16; + ctx->buffer[63] = ctx->hi >> 24; + body(ctx, ctx->buffer, 64); + result[0] = ctx->a; + result[1] = ctx->a >> 8; + result[2] = ctx->a >> 16; + result[3] = ctx->a >> 24; + result[4] = ctx->b; + result[5] = ctx->b >> 8; + result[6] = ctx->b >> 16; + result[7] = ctx->b >> 24; + result[8] = ctx->c; + result[9] = ctx->c >> 8; + result[10] = ctx->c >> 16; + result[11] = ctx->c >> 24; + result[12] = ctx->d; + result[13] = ctx->d >> 8; + result[14] = ctx->d >> 16; + result[15] = ctx->d >> 24; + memset(ctx, 0, sizeof(*ctx)); + } +#else + #include +#endif + + +using namespace std; + +/* Return Calculated raw result(always little-endian), the size is always 16 */ +void md5bin(const void* dat, size_t len, unsigned char out[16]) { + MD5_CTX c; + MD5_Init(&c); + MD5_Update(&c, dat, len); + MD5_Final(out, &c); +} + +static char hb2hex(unsigned char hb) { + hb = hb & 0xF; + return hb < 10 ? '0' + hb : hb - 10 + 'a'; +} + +string md5file(const char* filename){ + printf("file = %s\n",filename); + FILE* file = fopen(filename, "rb"); + string res = md5file(file); + fclose(file); + return res; +} + +string md5file(FILE* file){ + + MD5_CTX c; + MD5_Init(&c); + + char buff[BUFSIZ]; + unsigned char out[16]; + size_t len = 0; + while( ( len = fread(buff ,sizeof(char), BUFSIZ, file) ) > 0) { + MD5_Update(&c, buff, len); + } + MD5_Final(out, &c); + + string res; + for(size_t i = 0; i < 16; ++ i) { + res.push_back(hb2hex(out[i] >> 4)); + res.push_back(hb2hex(out[i])); + } + return res; +} + +string md5(const void* dat, size_t len) { + string res; + unsigned char out[16]; + md5bin(dat, len, out); + for(size_t i = 0; i < 16; ++ i) { + res.push_back(hb2hex(out[i] >> 4)); + res.push_back(hb2hex(out[i])); + } + return res; +} + +std::string md5(std::string dat){ + return md5(dat.c_str(), dat.length()); +} + +/* Generate shorter md5sum by something like base62 instead of base16 or base10. 0~61 are represented by 0-9a-zA-Z */ +string md5sum6(const void* dat, size_t len){ + static const char* tbl = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + string res; + unsigned char out[16]; + md5bin(dat, len, out); + for(size_t i = 0; i < 6; ++i) { + res.push_back(tbl[out[i] % 62]); + } + return res; +} + +std::string md5sum6(std::string dat){ + return md5sum6(dat.c_str(), dat.length() ); +} diff --git a/MD5/md5.h b/MD5/md5.h new file mode 100644 index 0000000..f63ab34 --- /dev/null +++ b/MD5/md5.h @@ -0,0 +1,16 @@ +#ifndef MD5_H +#define MD5_H + +#define _CRT_SECURE_NO_WARNINGS +#include +#include +#include + +std::string md5(std::string dat); +std::string md5(const void* dat, size_t len); +extern std::string md5file(const char* filename); +std::string md5file(FILE* file); +std::string md5sum6(std::string dat); +std::string md5sum6(const void* dat, size_t len); + +#endif // end of MD5_H diff --git a/MD5/subdir.mk b/MD5/subdir.mk new file mode 100644 index 0000000..e382cc2 --- /dev/null +++ b/MD5/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../MD5/md5.cpp + +CPP_DEPS += \ +./MD5/md5.d + +OBJS += \ +./MD5/md5.o + + +# Each subdirectory must supply rules for building sources it contributes +MD5/%.o: ../MD5/%.cpp MD5/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-MD5 + +clean-MD5: + -$(RM) ./MD5/md5.d ./MD5/md5.o + +.PHONY: clean-MD5 + diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..54d941c --- /dev/null +++ b/Makefile @@ -0,0 +1,73 @@ +TARGET = Cidn-SH +OBJ_PATH = $(shell pwd)/debug +PREFIX_BIN = + +CC = ${CXX} +STRIP = aarch64-poky-linux-strip +INCLUDES = -I../Tools/GatewayThirdParty/boost/include \ + -I../Tools/GatewayThirdParty/fftw/include \ + -I../Tools/GatewayThirdParty/jsoncpp/include \ + -I../Tools/GatewayThirdParty/sqlite/include/ \ + -I../Tools/GatewayThirdParty/curl/include/ \ + -I ./ \ + +LIBS = -L../Tools/renesas_thirdparty/lib \ + -L../Tools/renesas_thirdparty/lib \ + -L../Tools/renesas_thirdparty/lib \ + -L../Tools/renesas_thirdparty/lib \ + -L../Tools/renesas_thirdparty/lib \ + -L../Tools/renesas_thirdparty/lib \ + -lsqlite3 -lboost_system -lpthread -lboost_thread -lboost_date_time -lfftw3 -ljsoncpp -lmosquitto -lcurl + +CFLAGS = -O0 -fpermissive #-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/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/aes/subdir.mk b/aes/subdir.mk new file mode 100644 index 0000000..9c32942 --- /dev/null +++ b/aes/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../aes/aes.c + +C_DEPS += \ +./aes/aes.d + +OBJS += \ +./aes/aes.o + + +# Each subdirectory must supply rules for building sources it contributes +aes/%.o: ../aes/%.c aes/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross GCC Compiler' + arm-linux-gnueabihf-gcc -O0 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-aes + +clean-aes: + -$(RM) ./aes/aes.d ./aes/aes.o + +.PHONY: clean-aes + diff --git a/calculation/Calculation.cpp b/calculation/Calculation.cpp new file mode 100644 index 0000000..d19d964 --- /dev/null +++ b/calculation/Calculation.cpp @@ -0,0 +1,546 @@ +#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(); +} +void Calculation::_iFFT( std::vector & vecrealData,std::vector & vecimageData,std::vector & veciFFTData) +{ + fftw_complex *inFFt, *outFFt; + int N = vecrealData.size(); + inFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * N); + outFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * N); + + for (int j = 0; j < N; j++) { + inFFt[j][0] = (double)vecrealData[j]; + inFFt[j][1] = (double)vecimageData[j]; + } + iFFT(N,inFFt, outFFt); + for (int i = 0; i < N; i++) { + outFFt[i][0] *= 1./N; + outFFt[i][1] *= 1./N; + veciFFTData.push_back(outFFt[i][0]); + } + fftw_free(inFFt); + fftw_free(outFFt); +} +void Calculation::_FFT(std::vector & vecData, std::vector & vecFFTrealData,std::vector & vecFFTimageData) +{ + fftw_complex *inHilFFt, *outHilFFt; + inHilFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size()); + outHilFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size()); + + for (int j = 0; j < vecData.size(); j++) { + inHilFFt[j][0] = (double)vecData[j]; + inHilFFt[j][1] = 0; + } + + FFT(vecData.size(), inHilFFt, outHilFFt); + //fftShift(outHilFFt, vecData.size()); + for (int i = 0; i < vecData.size(); i++) { + vecFFTrealData.push_back(outHilFFt[i][0]); + vecFFTimageData.push_back(outHilFFt[i][1]); + } + fftw_free(inHilFFt); + fftw_free(outHilFFt); +} +//************************************ +// 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::getSample_variance(std::vector a) +{ + float ss = 0; + float s = 0; + float mx = mean(a); + int len = a.size(); + for (int i = 0; i < len; i++) { + s = a[i] - mx; + ss += pow(s, 2); + } + return ss / (len - 1); +} + + + +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::Hanning(std::vector & vecData,std::vector & vecHanningData) +{ + int N = vecData.size(); + + float* w = NULL; + w = (float*)calloc(N, sizeof(float)); + int half, i, idx; + if (N % 2 == 0) + { + half = N / 2; + for (i = 0; i < half; i++) //CALC_HANNING Calculates Hanning window samples. + w[i] = 0.5 * (1 - cos(2 * pi * (i + 1) / (N + 1))); + + + idx = half - 1; + for (i = half; i < N; i++) { + w[i] = w[idx]; + idx--; + } + } + else + { + half = (N + 1) / 2; + for (i = 0; i < half; i++) //CALC_HANNING Calculates Hanning window samples. + w[i] = 0.5 * (1 - cos(2 * pi * (i + 1) / (N + 1))); + + idx = half - 2; + for (i = half; i < N; i++) { + w[i] = w[idx]; + idx--; + } + } + for(int j = 0; j < N;j++){ + vecHanningData.push_back(w[j]); + } + free(w); +} +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()); + + 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,int StartFrequency,int EndFrequency) +{ + /*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); + }*/ + std::vector vecFFTrealData,vecFFTimageData; + std::vector vecRealData,vecImageData; + std::vector veciFFtData; + std::vector veciFFtData2; + std::vector vecHilbertData; + _FFT(vecData,vecFFTrealData,vecFFTimageData); + for(int i = 0; i < vecFFTrealData.size();i++){ + if(i > StartFrequency && i < EndFrequency){ + vecRealData.push_back(vecFFTrealData.at(i)); + vecImageData.push_back(vecFFTimageData.at(i)); + }else{ + vecRealData.push_back(0); + vecImageData.push_back(0); + } + } + _iFFT(vecRealData,vecImageData,veciFFtData); + for(int j = 0; j < veciFFtData.size();j++){ + veciFFtData2.push_back(veciFFtData[j]*2); + } + hilbert(veciFFtData2,vecHilbertData,veciFFtData2.size()); + FFTSpec(vecHilbertData, vecEnvSpecData); +} + + +void Calculation::GenerateSin(std::vector & vecData) +{ + double frequency = 800.0; // Frequency of the sine wave in Hz + double sampling_rate = 12800.0; // Sampling rate in Hz (8 kHz) + size_t num_samples = 12800; // Total number of samples (1 second of data) + double dt = 1.0 / sampling_rate; // Time step in seconds + + // Vector to hold the sine wave data + //std::vector sine_wave(num_samples); + + // Generate the sine wave + for (size_t i = 0; i < num_samples; ++i) { + vecData.push_back(std::sin(2 * M_PI * frequency * i * dt)); + } + +} + +void Calculation::Integration(std::vector & vecData,std::vector& retData,double & resolution) +{ + + std::vector realshiftfft; + std::vector imageshiftfft; + std::vector realvalue,imagevalue,ifftData; + _FFT(vecData,realshiftfft,imageshiftfft); + + + //在频域上进行5-1000 Hz的带通滤波 + for (int i = 0; i < vecData.size() / 2 + 1; ++i) { + double frequency = i * resolution; // 计算当前频率分量 + if (frequency < 5 || frequency > 1000) { + // 将5 Hz 到 1000 Hz 之外的频率成分设置为0 + realshiftfft[i] = 0.0; + realshiftfft[i] = 0.0; + imageshiftfft[i] = 0.0; + imageshiftfft[i] = 0.0; + } + } + + + for(int k = 1; k < realshiftfft.size()+1;k++){ + double frequency = k * resolution; // 计算当前频率分量 + realvalue.push_back((realshiftfft.at(k-1)/(frequency*2*M_PI))*1000 * 2);//单位转换mm/s,*1000 *2 精度损失 + imagevalue.push_back((imageshiftfft.at(k-1)/(frequency*2*M_PI))*1000 * 2);//单位转换mm/s,*1000 + } + + _iFFT(realvalue,imagevalue,retData); + + // for (size_t i = 0; i < ifftData.size(); i++) + // { + // retData.push_back( ifftData[i] * 2); + // } + + + +} + +/*void acceleration_to_velocity(int fs, int N, float *data, int min_freq, int max_freq, float *out_data) { + fftwf_execute_dft_r2c(forward_plan[fft_plan_id(N)], data, forward_out); + + float df = fs * 1.0f / N; + int ni = round(min_freq / df); + int na = round(max_freq / df); + float dw = 2 * fcl_pi * df; + + int double_id = get_idle_double_res(); + if (double_id < 0) { + return; + } + float *w11 = get_double_res_ptr(double_id); + + int len = 0; + int max_f = round((0.5 * fs - df) / df); + + for (int i = 0; i <= max_f; ++i) { + w11[i] = i * dw; + ++len; + } + + for (int i = 0; i < max_f; ++i) { + w11[len] = -2 * fcl_pi * (0.5 * fs - df) + i * dw; + ++len; + } + + forward_out[0][0] = forward_out[0][1] = forward_out[N - 1][0] = forward_out[N - 1][1] = 0; + float tmp_real, tmp_imag; + for (int i = 1; i < N - 1; ++i) { + tmp_real = forward_out[i][1] / w11[i]; + tmp_imag = -forward_out[i][0] / w11[i]; + forward_out[i][0] = tmp_real; // real + forward_out[i][1] = tmp_imag; // imag + } + + free_double_res(double_id); + + for (int i = 0; i < N; ++i) { + backward_in[i][0] = 0; + backward_in[i][1] = 0; + } + + for (int i = ni - 1; i < na; ++i) { + backward_in[i][0] = forward_out[i][0]; + backward_in[i][1] = forward_out[i][1]; + } + + for (int i = N - na; i < N - ni + 1; ++i) { + backward_in[i][0] = forward_out[i][0]; + backward_in[i][1] = forward_out[i][1]; + } + + fftwf_execute_dft(backward_plan[fft_plan_id(N)], backward_in, backward_out); + + for (int i = 0; i < N; ++i) { + out_data[i] = backward_out[i][0] / N * 2 * 1000; // *1000 是单位换算, 跟python保持一致 + } +}*/ diff --git a/calculation/Calculation.hpp b/calculation/Calculation.hpp new file mode 100644 index 0000000..a3deae1 --- /dev/null +++ b/calculation/Calculation.hpp @@ -0,0 +1,160 @@ +#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); + + //获取样本方差 + float getSample_variance(std::vector a); + + //去数据的直流分量 + + 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); + + //hanning 窗 + void Hanning(std::vector & vecData,std::vector & vecHanningData); + + //快速傅里叶变换函数 + + 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); + void _iFFT(std::vector & vecData, std::vector & vecFFTSpecData,std::vector & veciFFTData); + void _FFT(std::vector & vecData, std::vector & vecFFTrealData,std::vector & vecFFTimageData); + + //通道幅值和相位提取 + + //输入为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); + + + + //生成正弦信号 + void GenerateSin(std::vector & vecData); + + //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,int StartFrequency,int EndFrequency); + + void Integration(std::vector & vecData,std::vector& retData,double & resolution); +}; + + + +#endif diff --git a/calculation/subdir.mk b/calculation/subdir.mk new file mode 100644 index 0000000..c9eba4e --- /dev/null +++ b/calculation/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../calculation/Calculation.cpp + +CPP_DEPS += \ +./calculation/Calculation.d + +OBJS += \ +./calculation/Calculation.o + + +# Each subdirectory must supply rules for building sources it contributes +calculation/%.o: ../calculation/%.cpp calculation/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-calculation + +clean-calculation: + -$(RM) ./calculation/Calculation.d ./calculation/Calculation.o + +.PHONY: clean-calculation + diff --git a/common/Mutex.h b/common/Mutex.h new file mode 100644 index 0000000..ece4f02 --- /dev/null +++ b/common/Mutex.h @@ -0,0 +1,20 @@ +#ifndef _MY_COMM_H_ +#define _MY_COMM_H_ +#include + +class Mutex { +private: + pthread_mutex_t mutex; +public: + Mutex() { mutex = PTHREAD_MUTEX_INITIALIZER;pthread_mutex_init(&mutex,NULL); /*printf("\n pthread_mutex_init \n");*/} + virtual ~Mutex() {pthread_mutex_destroy(&mutex); /*printf("\n pthread_mutex_destroy \n");*/} + void Lock() {pthread_mutex_lock(&mutex); /*printf("\n mutex lock \n");*/} + void UnLock() {pthread_mutex_unlock(&mutex); /*printf("\n mutex unlock \n");*/} +}; +//Mutex g_Mutex; + + + + + +#endif //_MY_COMM_H_ diff --git a/common/SH_CommonFunc.cpp b/common/SH_CommonFunc.cpp new file mode 100644 index 0000000..9715b29 --- /dev/null +++ b/common/SH_CommonFunc.cpp @@ -0,0 +1,2574 @@ +#include +#include +#include "SH_global.h" +#include "SH_CommonFunc.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../dbaccess/SH_SqlDB.hpp" + +#define ETHTOOL_GLINK 0x0000000a /* Get link status (ethtool_value) */ +#define MAX_WAIT_TIME 1 +#define MAX_NO_PACKETS 1 +#define ICMP_HEADSIZE 8 +#define PACKET_SIZE 4096 +struct timeval tvsend,tvrecv; +struct sockaddr_in dest_addr,recv_addr; +int sockfd; +pid_t pid; +char sendpacket[PACKET_SIZE]; +char recvpacket[PACKET_SIZE]; + +static boost::mutex s_config_mu; +Mutex g_tDbMutex; +string GetLocalTimeWithMs(void) +{ + string defaultTime = "19700101000000000"; + try + { + struct timeval curTime; + gettimeofday(&curTime, NULL); + int milli = curTime.tv_usec / 1000; + + char buffer[80] = {0}; + struct tm nowTime; + localtime_r(&curTime.tv_sec, &nowTime);//把得到的值存入临时分配的内存中,线程安全 + strftime(buffer, sizeof(buffer), "%Y%m%d%H%M%S", &nowTime); + + char currentTime[84] = {0}; + snprintf(currentTime, sizeof(currentTime), "%s%03d", buffer, milli); + + return currentTime; + } + catch(const std::exception& e) + { + return defaultTime; + } + catch (...) + { + return defaultTime; + } +} +int code_convert(const char *from_charset, const char *to_charset, char *inbuf, size_t inlen, + char *outbuf, size_t outlen) { + iconv_t cd; + char **pin = &inbuf; + char **pout = &outbuf; + + cd = iconv_open(to_charset, from_charset); + if (cd == 0) + return -1; + + memset(outbuf, 0, outlen); + + if ((int)iconv(cd, pin, &inlen, pout, &outlen) == -1) + { + iconv_close(cd); + return -1; + } + iconv_close(cd); + *pout = '\0'; + + return 0; +} + +int u2g(char *inbuf, size_t inlen, char *outbuf, size_t outlen) { + return code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, outlen); +} + +int g2u(char *inbuf, size_t inlen, char *outbuf, size_t outlen) { + return code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, outlen); +} + +std::string GBKToUTF8(const std::string& strGBK) +{ + int length = strGBK.size()*2+1; + + char *temp = (char*)malloc(sizeof(char)*length); + + if(g2u((char*)strGBK.c_str(),strGBK.size(),temp,length) >= 0) + { + std::string str_result; + str_result.append(temp); + free(temp); + return str_result; + }else + { + free(temp); + return ""; + } +} + +std::string UTFtoGBK(const char* utf8) +{ + int length = strlen(utf8); + + char *temp = (char*)malloc(sizeof(char)*length); + + if(u2g((char*)utf8,length,temp,length) >= 0) + { + std::string str_result; + str_result.append(temp); + free(temp); + + return str_result; + }else + { + free(temp); + return ""; + } +} +std::string convertEncoding(const std::string& input, const char* fromEncoding, const char* toEncoding) { + iconv_t conv = iconv_open(toEncoding, fromEncoding); + if (conv == (iconv_t)-1) { + throw std::runtime_error("iconv_open failed"); + } + + size_t inBytesLeft = input.size(); + size_t outBytesLeft = inBytesLeft * 2; // GBK may require up to twice the space of UTF-8 + char* inBuf = const_cast(input.c_str()); + char* outBuf = new char[outBytesLeft]; + char* outPtr = outBuf; + + if (iconv(conv, &inBuf, &inBytesLeft, &outPtr, &outBytesLeft) == (size_t)-1) { + delete[] outBuf; + iconv_close(conv); + throw std::runtime_error("iconv failed"); + } + + std::string result(outBuf, outPtr); + delete[] outBuf; + iconv_close(conv); + return result; +} + +void InitGpio(unsigned int gpioN,unsigned int inout) +{ + int fd = 0; + char tmp[100] = {0}; + //打开gpio设备文件 + fd = open("/sys/class/gpio/export", O_WRONLY); + if(-1 == fd) + { + printf("[%s]:[%d] open gpio export file error\r\n", __FUNCTION__, __LINE__); + } + //申请gpio + sprintf(tmp,"%d",gpioN); + if(write(fd, tmp, strlen(tmp)) < 0) + { + printf("write file operation error %s\r\n",tmp); + + } + close(fd); + sleep(1); + //配置gpio方向 +#ifdef G2UL_GATEWAY + char tmp2[100] = {0}; + if(gpioN == 507) + memcpy(tmp2,"P18_3",5); + else if(gpioN == 499) + memcpy(tmp2,"P17_3",5); + else if(gpioN == 496) + memcpy(tmp2,"P17_0",5); + else if(gpioN == 130) + memcpy(tmp2,"P9_0",4); + else if(gpioN == 408) + memcpy(tmp2,"P6_0",4); + else if(gpioN == 363) + memcpy(tmp2,"P0_3",4); + else if(gpioN == 498) + memcpy(tmp2,"P17_2",5); + else if(gpioN == 466) + memcpy(tmp2,"P13_2",5); + else if(gpioN == 488) + memcpy(tmp2,"P16_0",5); + else if(gpioN == 474) + memcpy(tmp2,"P14_2",5); + else if(gpioN == 497) + memcpy(tmp2,"P17_1",5); + else if(gpioN == 409) + memcpy(tmp2,"P6_1",4); + else if(gpioN == 410) + memcpy(tmp2,"P6_2",4); + else if(gpioN == 449) + memcpy(tmp2,"P11_1",5); + else if(gpioN == 489) + memcpy(tmp2,"P16_1",5); + sprintf(tmp,"/sys/class/gpio/%s/direction",tmp2); +#else if IMX6UL_GATEWAY + sprintf(tmp,"/sys/class/gpio/gpio%d/direction",gpioN); +#endif + + print_info("open GPIO = %s\n",tmp); + fd = open(tmp, O_WRONLY); + if(-1 == fd) + { + printf("[%s]:[%d] open gpio direction file error\r\n", __FUNCTION__, __LINE__); + close(fd); + } + + if(inout == 0) + { + print_info("=====InitGpio=====in\n"); + if(-1 == write(fd, "in", sizeof("in"))) + { + print_info("[%s]:[%d] [%d]write operation direction error\r\n", __FUNCTION__, __LINE__,gpioN); + close(fd); + } + } + else if( inout == 1) + { + print_info("=====InitGpio=====out\n"); + if(-1 == write(fd, "out", sizeof("out"))) + { + print_info("[%s]:[%d] [%d]write operation direction error\r\n", __FUNCTION__, __LINE__,gpioN); + close(fd); + } + } + close(fd); +// printf("gpio%d init %d\r\n",gpioN,inout); +} +int gpio_set(unsigned int gpioN,char x) +{ + int fd = 0; + char tmp[100] = {0}; +#ifdef G2UL_GATEWAY + char tmp2[100] = {0}; + if(gpioN == 507) + memcpy(tmp2,"P18_3",5); + else if(gpioN == 499) + memcpy(tmp2,"P17_3",5); + else if(gpioN == 496) + memcpy(tmp2,"P17_0",5); + else if(gpioN == 130) + memcpy(tmp2,"P9_0",4); + else if(gpioN == 408) + memcpy(tmp2,"P6_0",4); + else if(gpioN == 363) + memcpy(tmp2,"P0_3",4); + else if(gpioN == 498) + memcpy(tmp2,"P17_2",5); + else if(gpioN == 466) + memcpy(tmp2,"P13_2",5); + else if(gpioN == 488) + memcpy(tmp2,"P16_0",5); + else if(gpioN == 474) + memcpy(tmp2,"P14_2",5); + else if(gpioN == 497) + memcpy(tmp2,"P17_1",5); + else if(gpioN == 409) + memcpy(tmp2,"P6_1",4); + else if(gpioN == 410) + memcpy(tmp2,"P6_2",4); + else if(gpioN == 449) + memcpy(tmp2,"P11_1",5); + else if(gpioN == 489) + memcpy(tmp2,"P16_1",5); + sprintf(tmp,"/sys/class/gpio/%s/value",tmp2); +#else if IMX6UL_GATEWAY + sprintf(tmp,"/sys/class/gpio/gpio%d/value",gpioN); +#endif +// printf("%s\r\n",tmp); + //print_info("set GPIO = %s\n",tmp); + //打开gpio value文件 + fd = open(tmp, O_WRONLY); + if(-1 == fd) + { + print_red("[%s]:[%d][%s] open gpio export file error\r\n", __FUNCTION__, __LINE__,tmp); + close(fd); + return (-1);//exit(1); + } + //设置电平 + if(x) + { + if(-1 == write(fd, "1", sizeof("1"))) + { + print_red("[%s]:[%d] %d write operation value error\r\n", __FUNCTION__, __LINE__,gpioN); + close(fd); + return (-1);//exit(1); + } + } + else + { + if(-1 == write(fd, "0", sizeof("0"))) + { + print_red("[%s]:[%d] %d write operation value error\r\n", __FUNCTION__, __LINE__,gpioN); + close(fd); + return (-1);//exit(1); + } + } +// printf("gpio%d set %d ok\r\n",gpioN,x); + close(fd); + return 0; +} +int gpio_read(unsigned int gpioN) +{ + int fd = 0; + char value; + + char tmp[100] = {0}; + +#ifdef G2UL_GATEWAY + char tmp2[100] = {0}; + if(gpioN == 507) + memcpy(tmp2,"P18_3",5); + else if(gpioN == 499) + memcpy(tmp2,"P17_3",5); + else if(gpioN == 496) + memcpy(tmp2,"P17_0",5); + else if(gpioN == 130) + memcpy(tmp2,"P9_0",4); + else if(gpioN == 408) + memcpy(tmp2,"P6_0",4); + else if(gpioN == 363) + memcpy(tmp2,"P0_3",4); + else if(gpioN == 498) + memcpy(tmp2,"P17_2",5); + else if(gpioN == 466) + memcpy(tmp2,"P13_2",5); + else if(gpioN == 488) + memcpy(tmp2,"P16_0",5); + else if(gpioN == 474) + memcpy(tmp2,"P14_2",5); + else if(gpioN == 497) + memcpy(tmp2,"P17_1",5); + else if(gpioN == 409) + memcpy(tmp2,"P6_1",4); + else if(gpioN == 410) + memcpy(tmp2,"P6_2",4); + else if(gpioN == 449) + memcpy(tmp2,"P11_1",5); + else if(gpioN == 489) + memcpy(tmp2,"P16_1",5); + sprintf(tmp,"/sys/class/gpio/%s/value",tmp2); +#else if IMX6UL_GATEWAY + sprintf(tmp,"/sys/class/gpio/gpio%d/value",gpioN); +#endif + //打开gpio value文件 + fd = open(tmp, O_RDONLY); + if(-1 == fd) + { + print_red("[%s]:[%d] %d open gpio export file error\r\n", __FUNCTION__, __LINE__,gpioN); + return (-1);//exit(1); + } + //读取 value文件 + if(-1 == read(fd, &value, sizeof(value))) + { + print_red("[%s]:[%d] %d read gpiovalue is fail\r\n", __FUNCTION__, __LINE__,gpioN); + close(fd); + return (-1);//exit(1); + } + close(fd); + //printf("gpio%d get %d\r\n",gpioN,value); + return value; +} + +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; +} +int config_uart(const char* Port,speed_t speed) +{ + int iFd = open(Port,O_RDWR | O_NOCTTY); + if(iFd < 0) { + return -1; + } + struct termios opt; + tcgetattr(iFd, &opt); + cfsetispeed(&opt, speed); + cfsetospeed(&opt, speed); + if (tcgetattr(iFd, &opt)<0) { + return -1; + } + opt.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); + opt.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); + opt.c_oflag &= ~(OPOST); + opt.c_cflag &= ~(CSIZE | PARENB | CBAUD); + opt.c_cflag |= (CS8 | speed); + opt.c_cc[VMIN] = 255; + opt.c_cc[VTIME] = 5; + if (tcsetattr(iFd, TCSANOW, &opt)<0) { + return -1; + } + tcflush(iFd,TCIOFLUSH); + + return iFd; +} + +int write_data(int fd, char *buff, int len) +{ + int ret; + char buf[100]; + ret = write(fd, buff, len); + if (ret < 0) { + return -1; + } + return ret; +} +int read_data(int fd, char *buff, int len, int timeout) +{ + int ret; + struct timeval to; + fd_set rdfds; + + to.tv_sec = 0; + to.tv_usec = timeout; + + FD_ZERO(&rdfds); + FD_SET(fd, &rdfds); + + if (timeout > 0) { + ret = select(fd+1, &rdfds, NULL, NULL, &to); + if (ret <= 0) { + // printf("zigbee doesn't respond!\n"); + return ret; + } + } + // if (ioctl(fd, FIONREAD, &len) == -1) { + // return -1; + // } + + ret = read(fd,buff,len); + if(ret < 0) { + perror("read_data"); + return -1; + } + buff[ret] = '\0'; + return ret; +} +int ModifyMac(char* buff) +{ + FILE *fp = fopen("/opt/system/mac", "w"); + fprintf(fp, buff); + fprintf(fp, "\n"); + fclose(fp); + system("cp /opt/system/mac /opt/system/macbak"); + system("/opt/Cidn/init.sh"); +} +void mssleep(unsigned long microseconds) +{ + + struct timespec req; + struct timespec rem; + + req.tv_sec = microseconds / 1000000; + req.tv_nsec = (microseconds % 1000000) * 1000; + + nanosleep(&req, &rem); +} +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; +} +tm *get_current_date( ) +{ + time_t t = time(NULL); + struct tm *tm_info = localtime(&t); + int iyear = 0;int imonth = 0;int day = 0;int hour = 0; + iyear = tm_info->tm_year + 1900; + imonth = tm_info->tm_mon + 1; + day = tm_info->tm_mday; + hour = tm_info->tm_hour; + print_info("year = %d,month = %d,day = %d\n",iyear,imonth,day); + return tm_info; +} +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); + } + +} +// 获取RTC时间 +std::string GetRTC(char* timestamp,int& millisecond) +{ + time_t rtc_timestamp; + struct tm tm; + struct timespec ts; + char rtcTime[100]={0x00}; + int fd = open("/dev/rtc0", O_RDONLY); + if (fd < 0) { + perror("open /dev/rtc0"); + } else { + struct rtc_time rtc_tm; + if (ioctl(fd, RTC_RD_TIME, &rtc_tm) < 0) { + perror("ioctl RTC_RD_TIME"); + } else { + clock_gettime(CLOCK_REALTIME, &ts); + millisecond = (int)(ts.tv_nsec / 1000000); + printf("RTC date/time is %d-%d-%d, %02d:%02d:%02d\n", + rtc_tm.tm_year + 1900, rtc_tm.tm_mon + 1, rtc_tm.tm_mday, + rtc_tm.tm_hour, rtc_tm.tm_min, rtc_tm.tm_sec); + sprintf(rtcTime,"%d-%d-%d, %02d:%02d:%02d",rtc_tm.tm_year + 1900, rtc_tm.tm_mon + 1, rtc_tm.tm_mday, + rtc_tm.tm_hour, rtc_tm.tm_min, rtc_tm.tm_sec); + + // 将rtc_time结构体转换为time_t时间戳 + tm.tm_year = rtc_tm.tm_year; + tm.tm_mon = rtc_tm.tm_mon; + tm.tm_mday = rtc_tm.tm_mday; + tm.tm_hour = rtc_tm.tm_hour; + tm.tm_min = rtc_tm.tm_min; + tm.tm_sec = rtc_tm.tm_sec; + tm.tm_isdst = -1; // 不使用夏令时 + + rtc_timestamp = mktime(&tm); + + if (rtc_timestamp == -1) { + perror("mktime"); + } + printf("RTC timestamp is %ld,millisecond = %d\n", rtc_timestamp,millisecond); + sprintf(timestamp,"%ld",rtc_timestamp); + } + } + close(fd); + return std::string(rtcTime); +} +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; +} +std::vector ReadStrUpdate(std::string filename) +{ + boost::mutex::scoped_lock lock(s_config_mu); + Json::Value root,hwVersion; + Json::Reader reader; + std::vector value; + std::vector vecDataNodeUpdate; + DataNodeUpdate datanodeUpdate; + std::fstream is; + is.open(filename.c_str(), std::ios::in); + if (reader.parse(is, root)) { + print_info("root = %d\n",root.size()); + for(int i = 0; i < root.size();i++){ + hwVersion = root[i]["hw_vesion"]; + for(int i = 0; i < hwVersion.size();i++){ + datanodeUpdate.hwVersion.push_back(hwVersion[i].asString()); + } + datanodeUpdate.strUpdataFileName = root[i]["fw_name"].asString(); + datanodeUpdate.strSoftVersion = root[i]["sf_vesion"].asString(); + print_info("strUpdataFileName = %s,strSoftVersion = %s\n",datanodeUpdate.strUpdataFileName.c_str(),\ + datanodeUpdate.strSoftVersion.c_str()); + vecDataNodeUpdate.push_back(datanodeUpdate); + } + + } + is.close(); + + return vecDataNodeUpdate; +} +void ReadStrConfig(std::string filename) +{ + Json::Value root,gateWay,dataNode; + std::fstream is; + Json::Reader reader; + is.open(filename.c_str(), std::ios::in); + string zigbeeChannel; + if (reader.parse(is, root)) { + gateWay = root["gateWay"]; + dataNode = root["dataNodeArray"]; + print_info("dataNode = %d\n",dataNode.size()); + for(int i = 0; i < dataNode.size();i++){ + string softVersion = dataNode[i]["softVersion"].asString(); + string bpNo = dataNode[i]["bpNo"].asString(); + print_info("bpNo = %s\n",bpNo.c_str()); + string wakeupTime = dataNode[i]["wakeupTime"].asString(); + int viff = dataNode[i]["viff"].asInt(); + string StaticTime = dataNode[i]["StaticTime"].asString(); + int configFlag = dataNode[i]["configFlag"].asInt(); + int rangeValue = dataNode[i]["range"].asInt(); + int updateValue = dataNode[i]["update"].asInt(); + string zigbeeLongAddr = dataNode[i]["zigbeeLongAddr"].asString(); + int accFlag = dataNode[i]["accFlag"].asInt(); + print_info("accFlag = %d\n",accFlag); + int temTopFlag = dataNode[i]["temTopFlag"].asInt(); + string startBrands = dataNode[i]["startBrands"].asString(); + int waveInterVal = dataNode[i]["waveInterVal"].asInt(); + string zigbeePanId = dataNode[i]["zigbeePanId"].asString(); + int waveTime = dataNode[i]["waveTime"].asInt(); + int zigbeePower = dataNode[i]["zigbeePower"].asInt(); + int zigbeeRetry = dataNode[i]["zigbeeRetry"].asInt(); + string stopBrands = dataNode[i]["stopBrands"].asString(); + int featureInterVal = dataNode[i]["featureInterVal"].asInt(); + int zigbeeFlag = dataNode[i]["zigbeeFlag"].asInt(); + string zigbeeDesAddr = dataNode[i]["zigbeeDesAddr"].asString(); + print_info("zigbeeDesAddr = %s\n",zigbeeDesAddr.c_str()); + int ZigbeeRetryGap = dataNode[i]["zigbeeRetryGap"].asInt(); + string dataNodeNo = dataNode[i]["dataNodeNo"].asString(); + int initFlag = dataNode[i]["initFlag"].asInt(); + string faultFrequency = dataNode[i]["faultFrequency"].asString(); + int temBotFlag = dataNode[i]["temBotFlag"].asInt(); + string bateryV = dataNode[i]["bateryV"].asString(); + int ACCSampleTime = dataNode[i]["ACCSampleTime"].asInt(); + print_info("ACCSampleTime = %d\n",ACCSampleTime); + string firstPowerTime = dataNode[i]["firstPowerTime"].asString(); + string serialNo = dataNode[i]["serialNo"].asString(); + string zigbeeAddr = dataNode[i]["zigbeeAddr"].asString(); + string productNo = dataNode[i]["productNo"].asString(); + string timeStamp = dataNode[i]["timeStamp"].asString(); + zigbeeChannel = dataNode[i]["zigbeeChannel"].asString(); + int RSSI = dataNode[i]["RSSI"].asInt(); + print_info("RSSI = %d\n",RSSI); + string hardVersion = dataNode[i]["hardVersion"].asString(); + string envelopeBandPass = dataNode[i]["envelopeBandPass"].asString(); + int samplingRate = dataNode[i]["samplingRate"].asInt(); + string dataNodeName = dataNode[i]["dataNodeName"].asString(); + int status = dataNode[i]["status"].asInt(); + int EquipSta = dataNode[i]["equipSta"].asInt(); + char insertSql[1024] = { 0 }; + char whereCon[100]={0x00}; + sprintf(whereCon,"dataNodeNo = '%s'",dataNodeNo.c_str()); + int rows = sql_ctl->GetTableRows(T_SENSOR_INFO(TNAME), whereCon); + if(rows > 0) + continue; + sprintf(insertSql, "'%s','%s','%d','%d','%d','%d','%d','%d',\ + '%s','%s','%s','%s','%s','%d',\ + '%d','%d','%d','%s','%d','%s',\ + '%s','%d','%d','%d','%s','%d','%s','%s',\ + '%s','%d','%s','%s','%s',\ + '%d','%d','%d','%d','%d','%s','%d','%d','%d','0','0,0'", + dataNodeNo.c_str(), dataNodeName.c_str(), initFlag, accFlag, zigbeeFlag, temTopFlag, temBotFlag,EquipSta,\ + hardVersion.c_str(), softVersion.c_str(), bpNo.c_str(), serialNo.c_str(), firstPowerTime.c_str(), atoi(wakeupTime.c_str()),\ + atoi(StaticTime.c_str()),waveTime,atoi(bateryV.c_str()),productNo.c_str(),configFlag, startBrands.c_str(), \ + stopBrands.c_str(), featureInterVal, waveInterVal, samplingRate,"",rangeValue, envelopeBandPass.c_str(), faultFrequency.c_str(),\ + zigbeePanId.c_str(), atoi(zigbeeChannel.c_str()), zigbeeAddr.c_str(), zigbeeLongAddr.c_str(), zigbeeDesAddr.c_str(), \ + zigbeePower,zigbeeRetry,ZigbeeRetryGap,ACCSampleTime,status, timeStamp.c_str(),viff,RSSI,updateValue); + sql_ctl->InsertData(T_SENSOR_INFO(TNAME), insertSql); + } + + /*WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", gateWay["Server"]["localServerIpAddress"].asString()); + WriteStr2Config(SERVERCONFIG, "Server", "localServerPort", gateWay["Server"]["localServerPort"].asString()); + WriteStr2Config(SERVERCONFIG, "Server", "CommMode", gateWay["Server"]["CommMode"].asString()); + WriteStr2Config(SERVERCONFIG, "Server", "UserName", gateWay["Server"]["UserName"].asString()); + WriteStr2Config(SERVERCONFIG, "Server", "Password", gateWay["Server"]["Password"].asString()); + + WriteStr2Config(NETWORKCONFIG, "Net", "dnsName", gateWay["Net"]["dnsName"].asString()); + WriteStr2Config(NETWORKCONFIG, "Net", "networkPortStatus", gateWay["Net"]["networkPortStatus"].asString()); + WriteStr2Config(NETWORKCONFIG, "Net", "gateway", gateWay["Net"]["gateway"].asString()); + WriteStr2Config(NETWORKCONFIG, "Net", "subnetMask", gateWay["Net"]["subnetMask"].asString()); + WriteStr2Config(NETWORKCONFIG, "Net", "ipAddress", gateWay["Net"]["ipAddress"].asString()); + WriteStr2Config(NETWORKCONFIG, "Net", "hostName", gateWay["Net"]["hostName"].asString()); + + WriteStr2Config(ZIGBEECONFIG, "Zigbee", "channel", zigbeeChannel);*/ + }else{ + print_info("parse error\n"); + } + is.close(); +} +void ImportConfig(std::string filename) +{ + Json::Value root,gateWay,dataNode; + std::fstream is; + Json::Reader reader; + is.open(filename.c_str(), std::ios::in); + string zigbeeChannel; + + Json::Value jsSystemSetting,jsonValnet,jsonValnet1,jsSystemInfo,jsonValZigbee,jsondataNodeArray; + if (reader.parse(is, root)) { + jsSystemInfo = root["SystemInfo"]; + jsonValZigbee = root["zigbee"]; + jsonValnet1 = root["eth1"]; + jsonValnet = root["eth0"]; + jsSystemSetting = root["ServerConfig"]; + jsondataNodeArray = root["dataNodeArray"]; + char insertSql[1024] = { 0 }; + for(int i = 0; i < jsondataNodeArray.size();i++){ + Json::Value valNode = jsondataNodeArray[i]; + vector vecDataNode; + for (size_t j = 0; j < valNode.size(); j++) + { + vecDataNode.push_back(string(valNode[j].asString())); + } + char dataNodeName[100]={0x00}; + hexToAscii(vecDataNode[1].c_str(),dataNodeName); + sprintf(insertSql, "'%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',\ + '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'", + vecDataNode[0].c_str(),dataNodeName,vecDataNode[2].c_str(),vecDataNode[3].c_str(),vecDataNode[4].c_str(),\ + vecDataNode[5].c_str(),vecDataNode[6].c_str(),vecDataNode[7].c_str(),vecDataNode[8].c_str(),vecDataNode[9].c_str(),\ + vecDataNode[10].c_str(),vecDataNode[11].c_str(),vecDataNode[12].c_str(),vecDataNode[13].c_str(),vecDataNode[14].c_str(),\ + vecDataNode[15].c_str(),vecDataNode[16].c_str(),vecDataNode[17].c_str(),vecDataNode[18].c_str(),vecDataNode[19].c_str(),\ + vecDataNode[20].c_str(),vecDataNode[21].c_str(),vecDataNode[22].c_str(),vecDataNode[23].c_str(),vecDataNode[24].c_str(),\ + vecDataNode[25].c_str(),vecDataNode[26].c_str(),vecDataNode[27].c_str(),vecDataNode[28].c_str(),vecDataNode[29].c_str(),\ + vecDataNode[30].c_str(),vecDataNode[31].c_str(),vecDataNode[32].c_str(),vecDataNode[33].c_str(),vecDataNode[34].c_str(),\ + vecDataNode[35].c_str(),vecDataNode[36].c_str(),vecDataNode[37].c_str(),vecDataNode[38].c_str(),vecDataNode[39].c_str(),\ + vecDataNode[40].c_str(),vecDataNode[41].c_str(),vecDataNode[42].c_str(),vecDataNode[43].c_str(),vecDataNode[44].c_str()); + sql_ctl->InsertData(T_SENSOR_INFO(TNAME), insertSql); + } + + WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", jsSystemSetting["ServerIpAddress"].asString()); + WriteStr2Config(SERVERCONFIG, "Server", "localServerPort", jsSystemSetting["ServerPort"].asString()); + WriteStr2Config(SERVERCONFIG, "Server", "CommMode", /*param.mCommMode*/"2"); + WriteStr2Config(SERVERCONFIG, "Server", "UserName", jsSystemSetting["UserName"].asString()); + WriteStr2Config(SERVERCONFIG, "Server", "Password", jsSystemSetting["Password"].asString()); + WriteStr2Config(SERVERCONFIG, "Server", "APN", jsSystemSetting["APN"].asString()); + char APN[100]={0x00}; + string apn = jsSystemSetting["APN"].asString(); + sprintf(APN,"sed -i '15c \t\t\t\t/opt/quectel-CM/quectel-CM -s %s > /dev/null &' /etc/init.d/S95check5G",apn.c_str()); + system(APN); + + WriteStr2Config(ZIGBEECONFIG, "Zigbee", "channel", jsonValZigbee["channel"].asString()); + WriteStr2Config(ZIGBEECONFIG, "Zigbee", "PanID", jsonValZigbee["PanID"].asString()); + + WriteStr2Config(SYSTEMINFOFILE, "Version", "GateWayVersion", jsSystemInfo["GateWayVersion"].asString()); + WriteStr2Config(SYSTEMINFOFILE, "Version", "SystemVersion", jsSystemInfo["SystemVersion"].asString()); + WriteStr2Config(SYSTEMINFOFILE, "Version", "WebVersion", jsSystemInfo["WebVersion"].asString()); + WriteStr2Config(SYSTEMINFOFILE, "Version", "GateWayHwVesion", jsSystemInfo["GateWayHwVesion"].asString()); + WriteStr2Config(SYSTEMINFOFILE, "Version", "GateWayProduct", jsSystemInfo["GateWayProduct"].asString()); + + } + //system("reboot"); +} +int UpdataDataNodeConfig(std::string filename) +{ + vector vecDataNode; //声明一个字符串向量 + //以读入方式打开文件 + ifstream csv_data(filename, ios::in); + int iRet = 0; + if (!csv_data.is_open()) + { + cout << "Error: opening file fail" << endl; + return -1; + } + else { + string line; + + vector words; //声明一个字符串向量 + string word; + + DataNodeInfo dataNode; + // ------------读取数据----------------- + // 读取标题行 + getline(csv_data, line); + + + istringstream sin; + // 按行读取数据 + while (getline(csv_data, line)) + { + words.clear(); + sin.clear(); + sin.str(line); + while (getline(sin, word, ',')) + { + cout << word << endl; + words.push_back(word); + + } + string mac = words[1]; + if(mac != GlobalConfig::MacAddr_G){ + iRet = -2; + break; + } + dataNode.ZigbeeLongAddr = words[7]; + dataNode.FeatureInterVal = atoi(words[16].c_str()); + dataNode.WaveInterVal = atoi(words[17].c_str()); + dataNode.SamplingRate = atoi(words[18].c_str()); + print_info("words[17] = %s\n",words[19].c_str()); + + if(words[19].find("8g") != string::npos){ + dataNode.Range = 0; + }else if(words[19].find("16g") != string::npos){ + dataNode.Range = 1; + }else if(words[19].find("32g") != string::npos){ + dataNode.Range = 2; + }else if(words[19].find("64g") != string::npos){ + dataNode.Range = 3; + }else if(words[19].find("50g") != string::npos){ + dataNode.Range = 0; + } + + dataNode.ACCSampleTime = atoi(words[20].c_str()); + dataNode.VIntegralFilterFrequency = atoi(words[21].c_str()); + dataNode.ZigbeePower = atoi(words[22].c_str()); + dataNode.ZigbeeRetry = atoi(words[23].c_str()); + int update = atoi(words[24].c_str()); + if(update == 1) + vecDataNode.push_back(dataNode); + } + csv_data.close(); + } + + char whereCon[1024] = {0}; + char updateSql[1024] = { 0 }; + if(vecDataNode.size() > 0){ + for(int i = 0; i < vecDataNode.size();i++){ + sprintf(updateSql, "featureInterVal='%d',waveInterVal='%d',range='%d',samplingRate='%d',AccSampleTime = '%d',viff ='%d' ,ZigbeePower = '%d',ZigbeeRetry = '%d',UpdateFlag = 0", + vecDataNode[i].FeatureInterVal, vecDataNode[i].WaveInterVal,vecDataNode[i].Range,\ + vecDataNode[i].SamplingRate,vecDataNode[i].ACCSampleTime,vecDataNode[i].VIntegralFilterFrequency,\ + vecDataNode[i].ZigbeePower,vecDataNode[i].ZigbeeRetry); + sprintf(whereCon, "dataNodeNo='%s'", vecDataNode[i].ZigbeeLongAddr.c_str()); + + int iRet = sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + memset(updateSql,0x00,sizeof(updateSql)); + } + iRet = vecDataNode.size() ; + }else{ + iRet = -3; + } + return iRet; +} +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(const char* net) +{ + 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, net, 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 ); + LOG_INFO("net : %s,mac:%s\n",net,mac_addr); + 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 *WLAN2 = "wlan2"; + const char *WLAN0 = "wlan0"; + const char *ETH0 = "eth0"; + const char *USB0 = "usb0"; + const char *WWAN0 = "wwan0"; + const char *ETH1 = "eth1"; + const char *ETH2 = "eth2"; + std::string strip = ""; + strip = GetGwIp_(WLAN0); + if (strip.compare("0.0.0.0") != 0) { + return strip; + } + strip = GetGwIp_(WLAN2); + if (strip.compare("0.0.0.0") != 0) { + return strip; + } + strip = GetGwIp_(ETH1); + if (strip.compare("0.0.0.0") != 0 && strip.compare("192.168.188.188") != 0) { + return strip; + } + strip = GetGwIp_(ETH2); + if (strip.compare("0.0.0.0") != 0 && strip.compare("192.168.188.188") != 0) { + return strip; + } + strip = GetGwIp_(ETH0); + if (strip.compare("0.0.0.0") != 0) { + return strip; + } + strip = GetGwIp_(USB0); + if (strip.compare("0.0.0.0") != 0) { + return strip; + } + strip = GetGwIp_(WWAN0); + if (strip.compare("0.0.0.0") != 0) { + return strip; + } + //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 = atof(MemFree.c_str()); + float b = atof(MemTotal.c_str()); + 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 ", to_string(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; +} + + +//BOOST用正则表达式验证ip地址合法 +bool CheckIP(const char *ip) +{ + boost::xpressive::cregex reg_ip = boost::xpressive::cregex::compile("(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])[.](25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])"); + return boost::xpressive::regex_match(ip, reg_ip); +} + +bool IsValidMask(std::string mask) { + int iRet = -1; + + // 将IP地址由“点分十进制”转换成 “二进制整数” + struct in_addr s; + iRet = inet_pton(AF_INET, mask.c_str(), &s); + + // 转换成功返回1,说明是有效的IP地址 + if (iRet == 1) { + // 从网络字节顺序转换为主机字节顺序 + unsigned int addr = ntohl(s.s_addr); + + // 转换为二进制字符串 + std::bitset<32> b((int)addr); + std::string strMask = b.to_string(); + + // 查找二进制字符串中的"01",如果不存在,说明是有效的子网掩码 + return (strMask.find("01") == std::string::npos); + } + + return false; +} +// 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"] = atof(strhardTotal.substr(0,strhardTotal.length() - 1)); +// jsData["hardDiskFree"] = atof(strhardFree.substr(0,strhardFree.length() - 1)); + +// double total = atof(strhardTotal.substr(0,strhardTotal.length() - 1)); +// double free = atof(strhardFree.substr(0,strhardFree.length() - 1)); +// double use = ((total - free) / free) * 100; +// // jsData["hardDiskUse"] = atof(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; +// } + +double GetHardDiskFree() +{ + 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); + double freeDisk = atof(strhardFree.substr(0,strhardFree.length() - 1).c_str()); + return freeDisk; +} +int getSysIntValue(char *key) +{ + FILE *fp = NULL; + int value = 0; + if(key == NULL)return 0; + + fp = fopen(key, "r"); + if (fp == NULL) { + printf("Error: could not open %s file\n",key); + return 1; + } + + fscanf(fp, "%d", &value); + fclose(fp);fp = NULL; + return value; +} +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); +#ifdef IMX6UL_GATEWAY + system_custom(getEmmcInfo, chRes); + sscanf(chRes,"%s%s%s%s%s",hardName, hardTotal, hardUse, hardFree, rateHardUse); +#endif +#ifdef G2UL_GATEWAY + getDiskInfo(hardTotal,hardFree); +#endif + + std::string strhardTotal(hardTotal); + std::string strhardFree(hardFree); + std::string strrateHardUse(rateHardUse); + + char key[128] = {0}; + memset(key,0,sizeof(key)); + sprintf(key,"/sys/class/thermal/thermal_zone0/temp"); + int temp = getSysIntValue(key); + + print_info("rateUser = %f,mem_total = %d,mem_free = %d,fMemRate = %f\n",rateUser,mem_total,mem_free,fMemRate); + 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"] = atof(strhardTotal.substr(0,strhardTotal.length() - 1).c_str()); + jsData["hardDiskFree"] = atof(strhardFree.substr(0,strhardFree.length() - 1).c_str()); + jsData["temperature"] = temp/1000.0; + jsData["temperatureNR5G"] = atoi(GlobalConfig::NR5GTemp.c_str()); + + double total = atof(strhardTotal.substr(0,strhardTotal.length() - 1).c_str()); + double free = atof(strhardFree.substr(0,strhardFree.length() - 1).c_str()); + double use = ((total - free) / total) * 100; + // jsData["hardDiskUse"] = atof(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; +} +// 将单个16进制字符转换为对应的字节值 +unsigned char hexCharToByte(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + return 0; // 对于无效的字符,返回0 +} + +// 将16进制字符串转换为字节数组 +int hexStringToBytes(const char* hexStr, unsigned char* bytes, size_t bytesSize) { + size_t hexLen = strlen(hexStr); + if (hexLen % 2 != 0) { + return -1; // Hex字符串长度应该是偶数 + } + if (bytesSize < hexLen / 2) { + return -1; // 字节数组的大小不足以容纳转换后的字节 + } + + for (size_t i = 0; i < hexLen; i += 2) { + unsigned char highNibble = hexCharToByte(hexStr[i]); + unsigned char lowNibble = hexCharToByte(hexStr[i + 1]); + bytes[i / 2] = (highNibble << 4) | lowNibble; + } + + return 0; // 成功 +} +void stringToHex(const char* str, char* hexStr) { + while (*str) { + sprintf(hexStr, "%02x", (unsigned char)*str); + hexStr += 2; + str++; + } + *hexStr = '\0'; +} +void hexToAscii(const char* hexStr, char* asciiStr) { + int len = strlen(hexStr); + int i, j = 0; + + for (i = 0; i < len; i += 2) { + // 读取两个字符并将其转换为整数 + int byte; + sscanf(&hexStr[i], "%2x", &byte); + // 将整数转换为对应的ASCII字符 + asciiStr[j++] = (char)byte; + } + // 添加字符串结束符 + asciiStr[j] = '\0'; +} +unsigned char ch2hex(char ch) +{ + static const char *hex="0123456789ABCDEF"; + for(unsigned char i=0;i!=16;++i) + if(ch==hex[i]) + return i; + return 0; +} +string tohex(const string& str) +{ + string ret; + static const char *hex="0123456789ABCDEF"; + for(int i=0;i!=str.size();++i) + { + ret.push_back(hex[(str[i]>>4)&0xf]); + ret.push_back( hex[str[i]&0xf]); + } + return ret; +} +char* solve(char *dest,const char *src) +{ + int i=0; + int cnt=0; + unsigned char*d=(unsigned char*)dest; + while(*src) + { + if(i&1) + { + d[cnt++]|=ch2hex(*src); + } + else + { + d[cnt]=ch2hex(*src)<<4; + } + src++; + i++; + } + return dest; +} + + +void swap(char *data) +{ + int tmp; + tmp = data[1]; + data[1] = data[0]; + data[0] = tmp; +} +int OpenWatchDog() +{ + int fd = -1; + InitGpio(GlobalConfig::GPIO_G.hardWatchDog,1); + gpio_set(GlobalConfig::GPIO_G.hardWatchDog,1);//高电平有效 + if(0 >(fd = open("/dev/watchdog",O_WRONLY))){ + print_info("Failed:Open /dev/watchdog"); + } + return fd; + +} +int WriteWatchDog(int fd) +{ + if(1 != write(fd,"0",1)){ + print_info("Failed:feeding watchdog"); + } +} +int CloseWatchDog(int fd) +{ + close(fd); +} +string TrimStringLeft(const char* szData, const char* szTargets) +{ + string strData = szData; + int nPos = 0; + nPos = strData.find(szTargets); + while (nPos == 0) + { + strData.erase(nPos, 1); + nPos = strData.find(szTargets); + } + return strData; +} + +string TrimStringRight(const char* szData, const char* szTargets) +{ + string strData = szData; + int nPos = 0; + nPos = strData.rfind(szTargets); + while ((nPos == (int)(strData.size() - 1)) && (nPos >= 0)) + { + strData.erase(nPos, 1); + nPos = strData.rfind(szTargets); + } + return strData; +} +string GetOneContent(const char* szData, int nRow, const char* szSeparate) +{ + string strParam = ""; + string strTemp = szData; + int nFirstPos = -1; + for (int i = 0; i < nRow; i++) + { + nFirstPos = strTemp.find(szSeparate, nFirstPos + 1); + if (nFirstPos < 0) + return strParam.c_str(); + } + + int nSecondPos = strTemp.find(szSeparate, nFirstPos + 1); + if (nSecondPos < 0) + { + strParam = strTemp.substr(nFirstPos + 1); + } + else + { + strParam = strTemp.substr(nFirstPos + 1, nSecondPos - nFirstPos - 1); + } + + { + strParam = TrimStringRight(strParam.c_str(), " "); + strParam = TrimStringLeft(strParam.c_str(), " "); + } + return strParam.c_str(); +} +int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop) +{ + struct termios newtio,oldtio; + if ( tcgetattr( fd,&oldtio) != 0) { //检测串口是否可用 + perror("SetupSerial 1"); + return -1; + } + bzero( &newtio, sizeof( newtio ) ); + newtio.c_cflag |= CLOCAL | CREAD; + newtio.c_cflag &= ~CSIZE; + + switch( nBits ) //设置数据位 + { + case 7: + newtio.c_cflag |= CS7; + break; + case 8: + newtio.c_cflag |= CS8; + break; + } + + switch( nEvent )//设置检验位 + { + case 'O': + newtio.c_cflag |= PARENB; + newtio.c_cflag |= PARODD; + newtio.c_iflag |= (INPCK | ISTRIP); + break; + case 'E': + newtio.c_iflag |= (INPCK | ISTRIP); + newtio.c_cflag |= PARENB; + newtio.c_cflag &= ~PARODD; + break; + case 'N': + newtio.c_cflag &= ~PARENB; + break; + } + + switch( nSpeed ) //设置波特率 + { + case 2400: + cfsetispeed(&newtio, B2400); + cfsetospeed(&newtio, B2400); + break; + case 4800: + cfsetispeed(&newtio, B4800); + cfsetospeed(&newtio, B4800); + break; + case 9600: + cfsetispeed(&newtio, B9600); + cfsetospeed(&newtio, B9600); + break; + case 115200: + cfsetispeed(&newtio, B115200); + cfsetospeed(&newtio, B115200); + break; + case 460800: + cfsetispeed(&newtio, B460800); + cfsetospeed(&newtio, B460800); + break; + default: + cfsetispeed(&newtio, B9600); + cfsetospeed(&newtio, B9600); + break; + } + if( nStop == 1 )//设置停止位 + newtio.c_cflag &= ~CSTOPB; + else if ( nStop == 2 ) + newtio.c_cflag |= CSTOPB; + newtio.c_cc[VTIME] = 0; + newtio.c_cc[VMIN] = 0; + tcflush(fd,TCIFLUSH); + if((tcsetattr(fd,TCSANOW,&newtio))!=0) //设置串口参数 + { + perror("com set error"); + return -1; + } + return 0; +} + +int getcsq() +{ + /*int fd = config_uart("/dev/ttyUSB2",115200); + print_info("fd = %d\n",fd); + if(fd < 0){ + printf("config_uart error\n"); + } + int len = write_data(fd,"AT+QENG=\"servingcell\"\r\n",27); + + sleep(1); + unsigned char rbuf[128]={0x00}; + len = read_data(fd,(char*)rbuf,100,10); + if(len < 0) { + print_info("Can't get /dev/ttyUSBx Serial Port data!\n"); + } + print_info("rbuf = %s\n",(char*)rbuf); + close(fd);*/ + + int ret = 0; + char csq[128] = {0}; + + int fd = 0, sig = 0; + + if((fd = open("/dev/ttyUSB2", O_RDWR | O_NOCTTY | O_NDELAY))<0){ + + //LOG_ERROR("open %s is FAILED\n\n","/dev/ttyUSB2"); + } + else{ + set_opt(fd, 9600, 8, 'N', 1); + } + set_opt(fd, 115200, 8, 'N', 1); + + //write(fd,"AT+QENG=\"servingcell\"\r\n",27);//开启定位 + write(fd,"AT+CSQ",6); + sleep(1); + unsigned char rbuf[128]={0x00}; + int len = read(fd, rbuf, sizeof(rbuf)); // 在串口读入字符串 + + print_info("rbuf = %s,len = %d\n",rbuf,len); + sleep(1); + if(len < 0) { + print_info("Can't get /dev/ttyUSBx Serial Port data!\n"); + } + + const char *str2 = "+QENG: "; + char *pdata = strstr((char*)rbuf, str2); + if(pdata) + strncpy(csq, pdata+7, sizeof(csq)); + else { + return -1; + } + //printf("SIM-CSQ: %s\n", csq); + GlobalConfig::NetStatus = GetOneContent(csq,1,","); + string signal = GetOneContent(csq,13,","); + GlobalConfig::NetSignal = atoi(signal.c_str()); + print_info("NetStatus = %s,NetSignal = %d\n",GlobalConfig::NetStatus.c_str(),GlobalConfig::NetSignal); + // ret = csq + close(fd); + /*if(csq[0] == ',') + ret = 0; + else if(csq[1] == ',') + ret = (int)csq[0] - '0'; + else if(csq[2] == ',') + ret = ((int)csq[0] - '0')*10 + (int)csq[1] - '0'; + + print_info("sig = %d\n", ret);*/ + return atoi(signal.c_str()); + +/* + int level; + char *str = NULL; + if (strstr(csq, "99,") || strstr(csq, "199,") ){ + printf("No signal ..\n"); + level = 0; + } + else { + char rssi_str[4]; + int rssi; + memset(rssi_str, 0, sizeof(rssi_str)); + if (*(csq+2) == ',') { + rssi_str[0] = *(csq+0+0); + rssi_str[1] = *(csq+0+1); + } + else if (isdigit(*(csq+2)) && isdigit(*(csq+3) == ',')) { + rssi_str[0] = *(csq+0+0); + rssi_str[1] = *(csq+0+1); + rssi_str[2] = *(csq+0+2); + } + rssi = atoi(rssi_str); + +printf("rssi = %d\n", rssi); + + int signal = -113 + (2 * rssi); + if(signal > -91) + level = 5; + else if (signal <= -91 && signal > -101) + level = 4; + else if(signal <= -101 && signal > -103) + level = 3; + else if(signal <= -103 && signal > -107) + level = 2; + else if(signal <= -107 && signal > -113) + level = 1; + else + level = 0; + printf("level = %d, signal: %d\n", rssi, signal); + } +*/ + +} +void IniReadValue(char* section, char* key, char* val, const char* file) +{ + FILE* fp; + int i = 0; + int lineContentLen = 0; + int position = 0; + char lineContent[LINE_CONTENT_MAX_LEN]; + bool bFoundSection = false; + bool bFoundKey = false; + fp = fopen(file, "r"); + if(fp == NULL) + { + printf("%s: Opent file %s failed.\n", __FILE__, file); + return; + } + while(feof(fp) == 0) + { + memset(lineContent, 0, LINE_CONTENT_MAX_LEN); + fgets(lineContent, LINE_CONTENT_MAX_LEN, fp); + if((lineContent[0] == ';') || (lineContent[0] == '\0') || (lineContent[0] == '\r') || (lineContent[0] == '\n')) + { + continue; + } + + //check section + if(strncmp(lineContent, section, strlen(section)) == 0) + { + bFoundSection = true; + //printf("Found section = %s\n", lineContent); + while(feof(fp) == 0) + { + memset(lineContent, 0, LINE_CONTENT_MAX_LEN); + fgets(lineContent, LINE_CONTENT_MAX_LEN, fp); + //check key + if(strncmp(lineContent, key, strlen(key)) == 0) + { + bFoundKey = true; + lineContentLen = strlen(lineContent); + //find value + for(i = strlen(key); i < lineContentLen; i++) + { + if(lineContent[i] == '=') + { + position = i + 1; + break; + } + } + if(i >= lineContentLen) break; + strncpy(val, lineContent + position, strlen(lineContent + position)); + lineContentLen = strlen(val); + for(i = 0; i < lineContentLen; i++) + { + if((lineContent[i] == '\0') || (lineContent[i] == '\r') || (lineContent[i] == '\n')) + { + val[i] = '\0'; + break; + } + } + } + else if(lineContent[0] == '[') + { + break; + } + } + break; + } + } + if(!bFoundSection){printf("No section = %s\n", section);} + else if(!bFoundKey){printf("No key = %s\n", key);} + fclose(fp); +} + +int readStringValue(const char* section, char* key, char* val, const char* file) +{ + char sect[SECTION_MAX_LEN]; + //printf("section = %s, key = %s, file = %s\n", section, key, file); + if (section == NULL || key == NULL || val == NULL || file == NULL) + { + printf("%s: input parameter(s) is NULL!\n", __func__); + return -1; + } + + memset(sect, 0, SECTION_MAX_LEN); + sprintf(sect, "[%s]", section); + //printf("reading value...\n"); + IniReadValue(sect, key, val, file); + + return 0; +} + +int readIntValue(const char* section, char* key, const char* file) +{ + char strValue[STRVALUE_MAX_LEN]; + memset(strValue, '\0', STRVALUE_MAX_LEN); + if(readStringValue(section, key, strValue, file) != 0) + { + printf("%s: error", __func__); + return 0; + } + return(atoi(strValue)); +} + +void IniWriteValue(const char* section, char* key, char* val, const char* file) +{ + FILE* fp; + int i = 0, n = 0, err = 0; + int lineContentLen = 0; + int position = 0; + char lineContent[LINE_CONTENT_MAX_LEN]; + char strWrite[LINE_CONTENT_MAX_LEN]; + bool bFoundSection = false; + bool bFoundKey = false; + + memset(lineContent, '\0', LINE_CONTENT_MAX_LEN); + memset(strWrite, '\0', LINE_CONTENT_MAX_LEN); + n = sprintf(strWrite, "%s=%s\n", key, val); + fp = fopen(file, "r+"); + if(fp == NULL) + { + printf("%s: Opent file %s failed.\n", __FILE__, file); + return; + } + while(feof(fp) == 0) + { + memset(lineContent, 0, LINE_CONTENT_MAX_LEN); + fgets(lineContent, LINE_CONTENT_MAX_LEN, fp); + if((lineContent[0] == ';') || (lineContent[0] == '\0') || (lineContent[0] == '\r') || (lineContent[0] == '\n')) + { + continue; + } + //check section + if(strncmp(lineContent, section, strlen(section)) == 0) + { + bFoundSection = true; + while(feof(fp) == 0) + { + memset(lineContent, 0, LINE_CONTENT_MAX_LEN); + fgets(lineContent, LINE_CONTENT_MAX_LEN, fp); + //check key + if(strncmp(lineContent, key, strlen(key)) == 0) + { + bFoundKey = true; + printf("%s: %s=%s\n", __func__, key, val); + fseek(fp, (0-strlen(lineContent)),SEEK_CUR); + err = fputs(strWrite, fp); + if(err < 0){printf("%s err.\n", __func__);} + break; + } + else if(lineContent[0] == '[') + { + break; + } + } + break; + } + } + if(!bFoundSection){printf("No section = %s\n", section);} + else if(!bFoundKey){printf("No key = %s\n", key);} + fclose(fp); +} + +int writeStringVlaue(const char* section, char* key, char* val, const char* file) +{ + char sect[SECTION_MAX_LEN]; + //printf("section = %s, key = %s, file = %s\n", section, key, file); + if (section == NULL || key == NULL || val == NULL || file == NULL) + { + printf("%s: input parameter(s) is NULL!\n", __func__); + return -1; + } + memset(sect, '\0', SECTION_MAX_LEN); + sprintf(sect, "[%s]", section); + IniWriteValue(sect, key, val, file); +} + +int writeIntValue(const char* section, char* key, int val, const char* file) +{ + char strValue[STRVALUE_MAX_LEN]; + memset(strValue, '\0', STRVALUE_MAX_LEN); + sprintf(strValue, "%d", val); + + writeStringVlaue(section, key, strValue, file); +} + +int getDiskInfo(char* diskTotal,char* diskFree) +{ + DISK diskInfo; +// pDISK pDiskInfo; +// char dpath[100]="/";//设置默认位置 +// int flag=0; +// if(NULL!=path) +// { +// strcpy(dpath,path); +// } +// if(-1==(flag=statfs("/tmp",pDiskInfo)))//获取包含磁盘空间信息的结构体 +// { +// perror("getDiskInfo statfs fail"); +// return 0; +// } +// unsigned long long total=0,avail=0,free=0,blockSize=0; +// +// blockSize=pDiskInfo->f_bsize;//每块包含字节大小 +// total=pDiskInfo->f_blocks*blockSize;//磁盘总空间 +// avail=pDiskInfo->f_bavail*blockSize;//非超级用户可用空间 +// free=pDiskInfo->f_bfree*blockSize;//磁盘所有剩余空间 +// //字符串转换 +// char diskTotal[30],diskAvail[30],diskFree[30]; +// flag=sprintf(diskTotal,"%llu",total>>20); +// flag=sprintf(diskAvail,"%llu",avail>>20); +// flag=sprintf(diskFree,"%llu",free>>20); +// print_info("diskTotal = %s,diskAvail = %s,diskFree = %s\n",diskTotal,diskAvail,diskFree); +// if(-1==flag) +// { +// return 0; +// } + /* 1.获取/home/下面的总容量 */ + statfs("/", &diskInfo); + unsigned long long blocksize = diskInfo.f_bsize; //每个block里包含的字节数 + unsigned long long totalsize = blocksize * diskInfo.f_blocks;//总的字节数,f_blocks为block的数目 + //printf("Total_size=%llu B =%llu KB =%llu MB = %llu GB\n",\ + totalsize,totalsize>>10,totalsize>>20, totalsize>>30); + + /* 2.获取一下剩余空间和可用空间的大小 */ + unsigned long long freeDisk = diskInfo.f_bfree * blocksize; //剩余空间的大小 + unsigned long long availableDisk = diskInfo.f_bavail * blocksize; //可用空间大小 + //printf("Disk_free=%llu MB =%llu GB Disk_available=%llu MB = %llu GB\n",\ + freeDisk>>20,freeDisk>>30,availableDisk>>20, availableDisk>>30); + sprintf(diskTotal,"%llu",totalsize>>20); + sprintf(diskFree,"%llu",freeDisk>>20); + return 1; +} +bool NetIsOk() +{ + + double rtt; + struct hostent *host; + struct protoent *protocol; + int i,recv_status; + +#ifdef _USE_DNS //如果定义该宏,则可以使用域名进行判断网络连接,例如www.baidu.com + /* 设置目的地址信息 */ + char hostname[32]; + sprintf(hostname,"%s","www.baidu.com") + bzero(&dest_addr, sizeof(dest_addr)); + dest_addr.sin_family = AF_INET; + + if((host=gethostbyname(hostname))==NULL) + { + LOG_ERROR("[NetStatus] error : Can't get serverhost info!\n"); + return false; + } + + bcopy((char*)host->h_addr,(char*)&dest_addr.sin_addr,host->h_length); +#else //如果不使用域名,则只能用ip地址直接发送icmp包, + dest_addr.sin_addr.s_addr = inet_addr(GlobalConfig::ServerIP.c_str()); +#endif + + + if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) + { /* 创建原始ICMP套接字 */ + LOG_ERROR("[NetStatus] error : socket %d\n",sockfd); + return false; + } + + int iFlag; + if(iFlag = fcntl(sockfd,F_GETFL,0)<0) + { + LOG_ERROR("[NetStatus] error : fcntl(sockfd,F_GETFL,0)"); + _CloseSocket(); + return false; + } + iFlag |= O_NONBLOCK; + if(iFlag = fcntl(sockfd,F_SETFL,iFlag)<0) + { + LOG_ERROR("[NetStatus] error : fcntl(sockfd,F_SETFL,iFlag )"); + _CloseSocket(); + return false; + } + print_info("================NetIsOk check=============\n"); + pid=getpid(); + for(i=0;i0) + { + _CloseSocket(); + return true; + } + + } + _CloseSocket(); + return false; +} + + + +int send_packet(int pkt_no,char *sendpacket) +{ + int packetsize; + packetsize=pack(pkt_no,sendpacket); + gettimeofday(&tvsend,NULL); + print_info("================NetIsOk send_packet=============\n"); + if(sendto(sockfd,sendpacket,packetsize,0,(struct sockaddr *)&dest_addr,sizeof(dest_addr) )<0) + { + LOG_ERROR("[NetStatus] error : sendto error"); + return -1; + } + return 1; +} + + +int pack(int pkt_no,char*sendpacket) +{ + int i,packsize; + struct icmp *icmp; + struct timeval *tval; + icmp=(struct icmp*)sendpacket; + icmp->icmp_type=ICMP_ECHO; //设置类型为ICMP请求报文 + icmp->icmp_code=0; + icmp->icmp_cksum=0; + icmp->icmp_seq=pkt_no; + icmp->icmp_id=pid; //设置当前进程ID为ICMP标示符 + packsize=ICMP_HEADSIZE+sizeof(struct timeval); + tval= (struct timeval *)icmp->icmp_data; + gettimeofday(tval,NULL); + icmp->icmp_cksum=cal_chksum( (unsigned short *)icmp,packsize); + return packsize; +} + + +unsigned short cal_chksum(unsigned short *addr,int len) +{ + int nleft=len; + int sum=0; + unsigned short *w=addr; + unsigned short answer=0; + while(nleft>1) //把ICMP报头二进制数据以2字节为单位累加起来 + { + sum+=*w++; + nleft-=2; + } + if( nleft==1) //若ICMP报头为奇数个字节,会剩下最后一字节.把最后一个字节视为一个2字节数据的高字节,这个2字节数据的低字节为0,继续累加 + { + *(unsigned char *)(&answer)=*(unsigned char *)w; + sum+=answer; + } + sum=(sum>>16)+(sum&0xffff); + sum+=(sum>>16); + answer=~sum; + return answer; +} + + +int recv_packet(int pkt_no,char *recvpacket) +{ + int n; + fd_set rfds; + FD_ZERO(&rfds); + FD_SET(sockfd,&rfds); + signal(SIGALRM,timeout); + unsigned int fromlen=sizeof(recv_addr); + alarm(MAX_WAIT_TIME); + print_info("================NetIsOk recv_packet=============\n"); + while(1) + { + select(sockfd+1, &rfds, NULL, NULL, NULL); + if (FD_ISSET(sockfd,&rfds)) + { + if( (n=recvfrom(sockfd,recvpacket,PACKET_SIZE,0,(struct sockaddr *)&recv_addr,&fromlen)) <0) + { + print_info("================NetIsOk recvfrom=============errno = %d\n",errno); + if(errno==EINTR){ + return -1; + LOG_ERROR("recvfrom error"); + return -2; + } + } + } + gettimeofday(&tvrecv,NULL); + if(unpack(pkt_no,recvpacket,n)==-1) + continue; + return 1; + } +} + +int unpack(int cur_seq,char *buf,int len) +{ + int iphdrlen; + struct ip *ip; + struct icmp *icmp; + ip=(struct ip *)buf; + iphdrlen=ip->ip_hl<<2; //求ip报头长度,即ip报头的长度标志乘4 + icmp=(struct icmp *)(buf+iphdrlen); //越过ip报头,指向ICMP报头 + len-=iphdrlen; //ICMP报头及ICMP数据报的总长度 + if( len<8) + return -1; + if( (icmp->icmp_type==ICMP_ECHOREPLY) && (icmp->icmp_id==pid) && (icmp->icmp_seq==cur_seq)) + return 0; + else return -1; +} + + +void timeout(int signo) +{ + LOG_ERROR("Request Timed Out\n"); + _CloseSocket(); +} + +void tv_sub(struct timeval *out,struct timeval *in) +{ + if( (out->tv_usec-=in->tv_usec)<0) + { + --out->tv_sec; + out->tv_usec+=1000000; + } + out->tv_sec-=in->tv_sec; +} + +void _CloseSocket() +{ + close(sockfd); + sockfd = 0; +} + +int socketHeart(const char* pSendData) +{ + print_info("socketHeart\n"); + int sockfd; // Socket文件描述符 + struct sockaddr_in serverAddr{}; // Server地址结构体 + + // 创建Socket + if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { + std::cerr << "Failed to create socket." << std::endl; + return 1; + } + + // 设置Server地址信息 + serverAddr.sin_family = AF_INET; + serverAddr.sin_port = htons(18393); // TCP默认端口号为80 + inet_pton(AF_INET, /*GlobalConfig::ServerIP.c_str()*/"192.168.1.147", &serverAddr.sin_addr); + + // 连接到Server + if (connect(sockfd, reinterpret_cast(&serverAddr), sizeof(serverAddr)) == -1) { + std::cerr << "Failed to connect to the server." << std::endl; + close(sockfd); + return 1; + } + + // 发送心跳数据包 + const char heartbeat[] = "Heartbeat"; + ssize_t bytesSent = send(sockfd, pSendData, strlen(pSendData), MSG_NOSIGNAL); + if (bytesSent == -1) { + std::cerr << "Failed to send heartbeat packet." << std::endl; + close(sockfd); + return 1; + } else if (static_cast(bytesSent) != strlen(pSendData)) { + std::cerr << "Partially sent heartbeat packet." << std::endl; + close(sockfd); + return 1; + } + + // 关闭Socket连接 + close(sockfd); + + return 0; +} +//unsigned short cal_chksum(unsigned short *addr, int len) +//{ +// int nleft=len; +// int sum=0; +// unsigned short *w=addr; +// unsigned short answer=0; +// +// while(nleft > 1) +// { +// sum += *w++; +// nleft -= 2; +// } +// +// if( nleft == 1) +// { +// *(unsigned char *)(&answer) = *(unsigned char *)w; +// sum += answer; +// } +// +// sum = (sum >> 16) + (sum & 0xffff); +// sum += (sum >> 16); +// answer = ~sum; +// +// return answer; +//} + +// Ping函数,timeout为超时时间,单位是ms,10000 毫秒=10 秒 +//成功:返回0,失败:返回1或-1 +int Ping( const char *ips, int timeout) +{ + struct timeval *tval; + int maxfds = 0; + fd_set readfds; + + int iRet = 0; + struct sockaddr_in addr; + struct sockaddr_in from; + // 设定Ip信息 + bzero(&addr,sizeof(addr)); + addr.sin_family = AF_INET; + + addr.sin_addr.s_addr = inet_addr(ips); + + int sockfd; + // 取得socket 。 如果没加sudo 这里会报错 + sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); + if (sockfd < 0) + { + print_error("ip:%s,socket error\n",ips); + return -1; + } + + struct timeval timeo; + // 设定TimeOut时间 + timeo.tv_sec = timeout / 1000; + timeo.tv_usec = timeout % 1000; + + if (setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeo, sizeof(timeo)) == -1) + { + print_error("ip:%s,setsockopt error\n",ips); + close(sockfd); + return -1; + } + + char sendpacket[2048]; + char recvpacket[2048]; + // 设定Ping包 + memset(sendpacket, 0, sizeof(sendpacket)); + + pid_t pid; + // 取得PID,作为Ping的Sequence ID + pid=getpid(); + + struct ip *iph; + struct icmp *icmp; + + + icmp=(struct icmp*)sendpacket; + icmp->icmp_type=ICMP_ECHO; //回显请求 + icmp->icmp_code=0; + icmp->icmp_cksum=0; + icmp->icmp_seq=0; + icmp->icmp_id=pid; + tval= (struct timeval *)icmp->icmp_data; + gettimeofday(tval,NULL); + icmp->icmp_cksum=cal_chksum((unsigned short *)icmp,sizeof(struct icmp)); //校验 + + int n = sendto(sockfd, (char *)&sendpacket, sizeof(struct icmp), 0, (struct sockaddr *)&addr, sizeof(addr)); + if (n < 1) + { + print_error("ip:%s,sendto error\n",ips); + close(sockfd); + return -1; + } + + // 接受 + // 由于可能接受到其他Ping的应答消息,所以这里要用循环 + int cnt=0; + while(1) + { + // 设定TimeOut时间,这次才是真正起作用的 + FD_ZERO(&readfds); + FD_SET(sockfd, &readfds); + maxfds = sockfd + 1; + n = select(maxfds, &readfds, NULL, NULL, &timeo); + if (n <= 0) + { + print_info("ip:%s,Time out error\n",ips); + close(sockfd); + iRet = -1; + break; + } + + // 接受 + memset(recvpacket, 0, sizeof(recvpacket)); + int fromlen = sizeof(from); + n = recvfrom(sockfd, recvpacket, sizeof(recvpacket), 0, (struct sockaddr *)&from, (socklen_t *)&fromlen); + print_info("recvfrom Len:%d\n",n); + if (n < 1) + { + close(sockfd); + iRet = 1; + break; + } + + char *from_ip = (char *)inet_ntoa(from.sin_addr); + // 判断是否是自己Ping的回复 + if (strcmp(from_ip,ips) != 0) + { + print_info("NowPingip:%s Fromip:%s NowPingip is not same to Fromip,so ping wrong!\n",ips,from_ip); + close(sockfd); + iRet = 1; + break; + + } + + iph = (struct ip *)recvpacket; + + icmp=(struct icmp *)(recvpacket + (iph->ip_hl<<2)); + + print_info("ip:%s,icmp->icmp_type:%d,icmp->icmp_id:%d\n",ips,icmp->icmp_type,icmp->icmp_id); + // 判断Ping回复包的状态 + if (icmp->icmp_type == ICMP_ECHOREPLY && icmp->icmp_id == pid) //ICMP_ECHOREPLY回显应答 + { + // 正常就退出循环 + print_info("icmp succecss ............. \n"); + break; + } + else if(cnt<3) + { + // 否则继续等 + cnt++; + continue; + } + else + { + close(sockfd); + iRet = -1; + break; + } + } + close(sockfd); + return iRet; +} +int get_netlink_status(const char *if_name) +{ + int skfd; + struct ifreq ifr; + struct ethtool_value edata; + edata.cmd = ETHTOOL_GLINK; + edata.data = 0; + memset(&ifr, 0, sizeof(ifr)); + strncpy(ifr.ifr_name, if_name, sizeof(ifr.ifr_name) - 1); + ifr.ifr_data = (char *)&edata; + if ((skfd = socket(AF_INET, SOCK_DGRAM, 0)) == 0) + return -1; + if (ioctl(skfd, SIOCETHTOOL, &ifr) == -1) + { + close(skfd); + return -1; + } + close(skfd); + return edata.data; +} +// 将版本号字符串拆分为整数组成的向量 +std::vector splitVersion(const std::string& version) { + std::vector parts; + std::stringstream ss(version); + std::string part; + + // 用点作为分隔符,分割版本号 + while (std::getline(ss, part, '.')) { + parts.push_back(std::stoi(part)); // 将分割后的部分转换为整数 + } + + return parts; +} + +// 比较两个版本号 +int compareVersions(const std::string& version1, const std::string& version2) { + std::vector v1 = splitVersion(version1); + std::vector v2 = splitVersion(version2); + + // 找到最长的版本号部分长度 + size_t maxLength = std::max(v1.size(), v2.size()); + + for (size_t i = 0; i < maxLength; ++i) { + int num1 = i < v1.size() ? v1[i] : 0; // 如果某部分不存在,视为0 + int num2 = i < v2.size() ? v2[i] : 0; + + if (num1 > num2) return 1; // version1 大于 version2 + if (num1 < num2) return -1; // version1 小于 version2 + } + + return 0; // 版本号相同 +} + +void Binary_Bit(unsigned char* p_data, unsigned char position, int flag) +{ + //二进制某位置零或者一 position为位数(从0 开始) + if (flag) + { + *p_data |= 0x01 << (position); + } + else + { + *p_data &= ~(0x01 << (position)); + } +} + +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..135a685 --- /dev/null +++ b/common/SH_CommonFunc.hpp @@ -0,0 +1,838 @@ +#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" +#include +#include +#include +#include +#include +#include +#include "Mutex.h" + +typedef struct statfs DISK,*pDISK; + +#define SECTION_MAX_LEN 256 +#define STRVALUE_MAX_LEN 256 +#define LINE_CONTENT_MAX_LEN 256 +//配置文件位置 +#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/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 BUILD_UINT16(x,y) (((x & 0x00FFu) << 8u) | (y & 0x00FFu)) +#define BUILD_UINT2(x,y) (((x) << 2u) | (y)) +// 生成UINT32 数据 +#define BUILD_UINT32(u,v,x,y) (((u & 0x00FFu) << 24u) | (v & 0x00FFu) << 16u) | (((x & 0x00FFu) << 8u) | (y & 0x00FFu)) +// 获取UINT32的高低字节 +#define UINT32_HIGH_1(x) ((x & 0xFF000000u) >> 24u) +#define UINT32_HIGH_2(x) ((x & 0x00FF0000u) >> 16u) +#define UINT32_LOW_1(x) ((x & 0x0000FF00u) >> 8u) +#define UINT32_LOW_2(x) ((x & 0x000000FFu)) +#define GET_BIT(x, bit) ((x & (1 << bit)) >> bit) /* 获取第bit位 */ +// 获取UINT32的高低字节 +#define UINT16_HIGH(x) ((x & 0xFF00u) >> 8u) +#define UINT16_LOW(x) ((x & 0x00FFu)) + + +#define GENERAL_BUF_SIZE 128*1024*10 +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 compressWaveChannel +{ + int compressChannelX; + int compressChannelY; + int compressChannelZ; + int CountX; + int CountY; + int CountZ; + compressWaveChannel(){ + compressChannelX = 0; + compressChannelY = 0; + compressChannelZ = 0; + CountX = 0; + CountY = 0; + CountZ = 0; + } +}; + +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; + std::string RetryNum; + std::string TranTimeout; +}; + +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 ZigbeeLongAddr; + std::string HardVersion; + std::string SoftVersion; + std::string BpNo; + std::string SerialNo; + std::string FirstPowerTime; + int WakeupTime; + int StaticTime; + int WaveTime; + int BateryV; + std::string ProductNo; + int RSSI; // 接收信号强度 + int ConfigFlag; + unsigned int FeatureInterVal; //特征值发送时间间隔,单位分钟 + unsigned int WaveInterVal; //原始数据发送时间间隔,单位分钟 + std::string ZigbeePanId; + int ZigbeeChannel; + std::string ZigbeeShortAddr; + std::string ZigbeeDesAddr; + int ZigbeePower; + int ZigbeeRetry; + int ZigbeeRetryGap; + int Range;//量程 + int SamplingRate;//采样率 + int ACCSampleTime;//采样时间 + + std::string StartBrands; //频带能量参数 1,2,3,4,5,START + std::string StopBrands; //频带能量参数 1,2,3,4,5,END + + std::string EnvelopeBandPass; //冲击带通频率 + std::string FaultFrequency; //故障频率1,2,3,4 + + std::string ConfigDate;//配置时间 + int VIntegralFilterFrequency;//速度积分滤波频率 + DataNodeInfo(){ + FeatureInterVal = 0;WaveInterVal = 0; + } + +}; + +struct DataRecvStatic { + float TemTop; + float TemBot; + int Dip; + int Voltage; + float nodeWorkTime; + float nodeSendTime; + +}; + +struct DataRecvDym { + float DiagnosisPk; + float IntegratPk; + float IntegratRMS; + float RmsValues; + float EnvelopEnergy; + float Amp1; + float Amp2; + float Amp3; + float Amp4; + float Amp5; + long Time; + 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 mPubTiming; //校时 + + 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; + + +typedef struct{ + int zigAckrep; + int zigAckreset; + int zigReset; + int zigDef; + int alarmLight; + int commPower;//4G,5G 电源开关 + int vol3_8;//5G 3.8v电源 + int commRest;//4G,5G复位 + int wifiPower;//WiFi 电源开关 + int wifiReset;//WiFi 复位 + int hardWatchDog; + int power; + int runLed; + int errorLed; + int netResetNet0; + int netResetNet1; +} GPIOInfo; + +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 mSetType; + int mTimeStamp; + Param_02():mMode(0),mSetType(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 + std::string mUserName; + std::string mPassword; + std::string mAPN; + Param_23():mMode(0),mCmdSerial(""), mServerIp(""),mPort(""),mCommMode(""),mUserName("chaos"),mPassword("HSD272*#xkd"),mAPN(""){}; +}; + + +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 mNet; + 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_09 { + int mPackageFlag; + Param_09():mPackageFlag(0){}; +}; +struct Param_10 { + std::string strDataNode; + std::string strStatic; + std::string straxis; + std::string timeStart; + std::string timeEnd; + std::string MeasurementID; + int mPackageFlag; + Param_10():strDataNode(""),strStatic(""),mPackageFlag(0){}; +}; +struct Param_11 { + std::string DataNodeNo; + Param_11():DataNodeNo(""){}; +}; +struct Param_26 { + int mMode; + std::string mCmdSerial; + std::string mDataNodeNo; + int mPackageFlag; + Param_26():mMode(0),mCmdSerial(""),mDataNodeNo(""),mPackageFlag(0){}; + +}; + +struct Param_27 { + int mMode; + std::string mCmdSerial; + std::string mDataNodeNo; + std::string mType; + Param_27():mMode(0),mCmdSerial(""),mDataNodeNo(""),mType(""){}; + +}; + + +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_40 { + int mMode; + std::string mChannelId; + std::string mDataNodeNo; + int mPackageFlag; + int StartFrequency; + int EndFrequency; + Param_40():mMode(0),mChannelId(""),mDataNodeNo(""),mPackageFlag(0),StartFrequency(0),EndFrequency(0){}; +}; +struct Param_41 { + std::string mdataNodeName; + std::string mdataNodeNo; + std::string mMeasurementID; + int mfeatureInterVal; + int mwaveInterVal; + int msamplingRate; + int mrange; + int mAccSampleTime; + std::string mstartBrands; + std::string mstopBrands; + std::string menvelopeBandPass; + int mviff; + std::string mfaultFrequency; + int ZigbeePower; + int ZigbeeRetry; + std::string nodeWaveSend; + Param_41():mdataNodeName(""),mdataNodeNo(""),mfeatureInterVal(0),mwaveInterVal(0),msamplingRate(0),mrange(0),mAccSampleTime(0),\ + mstartBrands(""),mstopBrands(""),menvelopeBandPass(""),mviff(0),mfaultFrequency(""),mMeasurementID{""},nodeWaveSend{""}{}; +}; +struct Param_42 { + string fileName; + Param_42():fileName(""){}; +}; + +struct Param_31 { + int mMode; + //int mChannelId; + std::string mChannelId; + std::string mPanID; + Param_31():mMode(0),mChannelId(""),mPanID(""){}; +}; + + +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(""){}; +}; +struct Param_51 { + int mMode; + string strGateWayMAC; + string strGateWayLocation; + Param_51():mMode(-1),strGateWayLocation(""){}; +}; +struct Param_52 { + int mMode; + std::string mCmdSerial; + string mSsid; + string mPassWord; +}; +struct Param_53 { + int mMode; + string mdataNodeNo; + string mUpdateKey; + string mUpdateValue; + string mUpdateKey2; + string mUpdateValue2; + string mUpdateKey3; + string mUpdateValue3; + Param_53():mUpdateKey2(""),mUpdateValue2(""),mUpdateKey3(""),mUpdateValue3(""){}; +}; +struct Param_54 { + int mMode; + std::string mCmdSerial; + std::string mDataNodeNo; + int mPackageFlag; + Param_54():mMode(0),mCmdSerial(""),mDataNodeNo(""),mPackageFlag(0){}; + +}; + +struct Param_55 { + int mMode; + std::string mChannelId; + std::string mDataNodeNo; + int mPackageFlag; + int StartFrequency; + int EndFrequency; + Param_55():mMode(0),mChannelId(""),mDataNodeNo(""),mPackageFlag(0),StartFrequency(0),EndFrequency(0){}; +}; + +struct Param_56 { + int mMode; + std::string mChannelId; + std::string mDataNodeNo; + int mPackageFlag; + int StartFrequency; + int EndFrequency; + Param_56():mMode(0),mChannelId(""),mDataNodeNo(""),mPackageFlag(0),StartFrequency(0),EndFrequency(0){}; +}; +struct Param_57 { + int mMode; + int mZigbeePowerEnable; + Param_57():mZigbeePowerEnable(0){}; +}; +typedef struct DataNodeUpdate{ + std::string strUpdataFileName; + std::string strSoftVersion; + std::vector hwVersion; +}; + + +struct ethtool_value { + unsigned int cmd; + unsigned int data; +}; + +extern std::string GBKToUTF8(const std::string& strGBK); +extern std::string UTFtoGBK(const char* utf8); +extern void hexToAscii(const char* hexStr, char* asciiStr); +extern void stringToHex(const char* str, char* hexStr); +extern string GetLocalTimeWithMs(void); +extern void InitGpio(unsigned int gpioN,unsigned int inout); +extern int gpio_set(unsigned int gpioN,char x); +extern int gpio_read(unsigned int gpioN); +extern int config_uart(const char* Port,speed_t speed); +extern int write_data(int fd, char *buff, int len); +extern int read_data(int fd, char *buff, int len, int timeout); +extern int ModifyMac(char* buff); +extern void mssleep(unsigned long microseconds); +//extern int str_recv(int fd, char srcshow,char* buffer); +/** +* @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(); + +extern tm *get_current_date() ; +/** +* @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); +extern std::string GetRTC(char* timebuf, int& millisecond); +/** +* @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(const char* net); + +/** +* @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(); +double GetHardDiskFree(); +extern bool CheckIP(const char *ip); + +bool IsValidMask(std::string mask); +//read update config file +extern std::vector ReadStrUpdate(std::string filename); + +extern void ReadStrConfig(std::string filename); +extern void ImportConfig(std::string filename); +extern int UpdataDataNodeConfig(std::string filename); +extern char* solve(char *dest,const char *src); +extern void swap(char *data); +extern int hexStringToBytes(const char* hexStr, unsigned char* bytes, size_t bytesSize); + +extern int OpenWatchDog(); +extern int WriteWatchDog(int fd); +extern int CloseWatchDog(int fd); +//获取4G信号强度 +extern int getcsq(); +extern std::string GetGwIp_(const char *eth_name); +extern string GetOneContent(const char* szData, int nRow, const char* szSeparate); +extern int readStringValue(const char* section, char* key, char* val, const char* file); +extern int writeStringVlaue(const char* section, char* key, char* val, const char* file); +extern int readIntValue(const char* section, char* key, const char* file); +extern int writeIntValue(const char* section, char* key, int val, const char* file); + +int getDiskInfo(char* diskTotal,char* diskFree); + +void timeout(int signo); +unsigned short cal_chksum(unsigned short *addr,int len); +int pack(int pkt_no,char *sendpacket); +int send_packet(int pkt_no,char *sendpacket); +int recv_packet(int pkt_no,char *recvpacket); +int unpack(int cur_seq,char *buf,int len); +void tv_sub(struct timeval *out,struct timeval *in); +void _CloseSocket(); + +int socketHeart(const char* pSendData); + +extern bool NetIsOk(); +extern int Ping( const char *ips, int timeout); +extern int get_netlink_status(const char *if_name); +extern int compareVersions(const std::string& version1, const std::string& version2); +extern void Binary_Bit(unsigned char* p_data, unsigned char position, int flag); +extern Mutex g_tDbMutex; +#endif diff --git a/common/SH_global.h b/common/SH_global.h new file mode 100644 index 0000000..614818d --- /dev/null +++ b/common/SH_global.h @@ -0,0 +1,182 @@ +#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" +#include "../minilzo-2.10/minilzo.h" + + +#define SECTION_MAX_LEN 1024 +//******************** 全局变量********************** +enum enumZigBeeTransmitStatus { + NO_ENTER_TRANSMITTING_STATUS = 0, + ENTER_TRANSMITTING_STATUS +}; + + +//#define NR5G_MODULE +//#define Q4G_MODULE +//#define WIFI_MODULE +//#define NR5G_MEIGE +//#define G2UL_GATEWAY +#define IMX6UL_GATEWAY + +class GlobalConfig +{ +public : + static int RUN_MODE; //1调试模式 0运行模式 + static int QuitFlag_G; //程序退出标志 + static int LinkStatus_G; //和服务器连接状态 + static int LinkCount; + static int NetSignal; + static int serverStatus; + static int net0Status; + static std::string NR5GTemp; + static std::string NetStatus; + static std::string NetType; + static std::string Version; //软件版本号 + static std::string MacAddr_G; //设备MAC地址 + static std::string MacAddr_G2; //设备光纤MAC地址 + static std::string IpAddr_G; //设备IP + static std::string DbName_G; //数据库名字 + static std::string Config_G; //配置文件 + static std::string ServerIP; //服务器地址 + static int ServerPort; //服务器端口 + static int threadStatus; + static std::string UartName_G; + static TopicList Topic_G; //发布的主题 + static ZigbeeInfo ZigbeeInfo_G; //gateway zigbee info + static ZIGBEE Zigbee_G; + static GPIOInfo GPIO_G; + static enumZigBeeTransmitStatus EnterZigBeeWaveTransmittingFlag_G; // 进入ZigBee网络原始数据传输状态标志 + static int EnterZigBeeWaveTransmittingCnt_G; // 进入ZigBee网络原始数据传输状态计数器,以秒为单位进行计数 + static int day; + +}; + +#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" + +#ifdef IMX6UL_GATEWAY +#define SAVE_COUNT 4320 +#define OneWeek 432000 //5天 +#endif +#ifdef G2UL_GATEWAY +#define SAVE_COUNT 4800*4 +#define OneWeek 604800*7 +#endif + + + +#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/common/subdir.mk b/common/subdir.mk new file mode 100644 index 0000000..1cb96f3 --- /dev/null +++ b/common/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../common/SH_CommonFunc.cpp + +CPP_DEPS += \ +./common/SH_CommonFunc.d + +OBJS += \ +./common/SH_CommonFunc.o + + +# Each subdirectory must supply rules for building sources it contributes +common/%.o: ../common/%.cpp common/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-common + +clean-common: + -$(RM) ./common/SH_CommonFunc.d ./common/SH_CommonFunc.o + +.PHONY: clean-common + diff --git a/common/u2g.h b/common/u2g.h new file mode 100644 index 0000000..83cf184 --- /dev/null +++ b/common/u2g.h @@ -0,0 +1 @@ +void utf2gbk(char *utf,char* gbk); diff --git a/datatransfer/SH_Datatrans.cpp b/datatransfer/SH_Datatrans.cpp new file mode 100644 index 0000000..7c44c71 --- /dev/null +++ b/datatransfer/SH_Datatrans.cpp @@ -0,0 +1,581 @@ +#include "SH_Datatrans.hpp" +#include "dirent.h" +#include + + +DataTrans *pDataTrans = DataTrans::instance(); + + + +struct DowloadFile { + + const char *filename; + FILE *stream; + +}; +DataTrans::DataTrans(): +m_bDebug(false) +{ +} + +DataTrans::~DataTrans() +{ +} + +static int OnDebug(CURL *, curl_infotype itype, char * pData, size_t size, void *) +{ + if(itype == CURLINFO_TEXT) { + //printf("[TEXT]%s\n", pData); + } else if(itype == CURLINFO_HEADER_IN) { + print_info("[HEADER_IN]%s\n", pData); + } else if(itype == CURLINFO_HEADER_OUT) { + print_info("[HEADER_OUT]%s\n", pData); + } else if(itype == CURLINFO_DATA_IN) { + print_info("[DATA_IN]%s\n", pData); + } else if(itype == CURLINFO_DATA_OUT) { + print_info("[DATA_OUT]%s\n", pData); + } + return 0; +} + + + +static size_t OnWriteData(void* buffer, size_t size, size_t nmemb, void* lpVoid) +{ + std::string* str = dynamic_cast((std::string *)lpVoid); + if( NULL == str || NULL == buffer ) { + return -1; + } + char* pData = (char*)buffer; + str->append(pData, size * nmemb); + return nmemb; +} + + +static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream) +{ + printf("size = %d\n",size); + struct DowloadFile *out=(struct DowloadFile *)stream; + if(out && !out->stream) { + out->stream=fopen(out->filename, "wb");//打开文件进行写入 + if(!out->stream) + return -1; + } + return fwrite(buffer, size, nmemb, out->stream); + +} + +int DataTrans::download(char* pFilename,string& strUrl,string& strResponse,bool bDownload) +{ + CURL *curl = NULL; + CURLcode res; + struct DowloadFile dlfile={ + pFilename, //定义下载到本地的文件位置和路径 + NULL + }; + curl_global_init(CURL_GLOBAL_DEFAULT); + curl = curl_easy_init(); //初始化一个curl指针 + if(curl) { //curl对象存在的情况下执行的操作 + //设置远端地址 + curl_easy_setopt(curl, CURLOPT_URL,strUrl.c_str()); + if(bDownload){ + //执行写入文件流操作 + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);//当有数据被写入,回调函数被调用, + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &dlfile); //设置结构体的指针传递给回调函数 + }else{ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse); + } + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 8);//连接超时,这个数值如果设置太短可能导致数据请求不到就断开了 + curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);//接收数据时超时设置,如果10秒内数据未接收完,直接退出 + //启用时会汇报所有的信息,存放在STDERR或指定的CURLOPT_STDERR中 + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_USERPWD, "SUREN:SUREN"); + + //写入文件 + res = curl_easy_perform(curl); + //释放curl对象 + curl_easy_cleanup(curl); + if(res != CURLE_OK) + { + cout<= 0) { + timeout.tv_sec = curl_timeo / 1000; + if (timeout.tv_sec > 1) + timeout.tv_sec = 1; + else + timeout.tv_usec = (curl_timeo % 1000) * 1000; + } + + /* get file descriptors from the transfers */ + curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd); + /* In a real-world program you OF COURSE check the return code of the + function calls. On success, the value of maxfd is guaranteed to be + greater or equal than -1. We call select(maxfd + 1, ...), specially in + case of (maxfd == -1), we call select(0, ...), which is basically equal + to sleep. */ + rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + switch (rc) { + case -1: + break; + case 0: + default: + /* timeout or readable/writable sockets */ + print_info("perform!\n"); + curl_multi_perform(multi_handle, &still_running); + print_info("running: %d!\n", still_running); + break; + } + } while (still_running); + curl_multi_cleanup(multi_handle); + /* always cleanup */ + curl_easy_cleanup(curl); + /* then cleanup the formpost chain */ + curl_formfree(formpost); + /* free slist */ + curl_slist_free_all(headerlist); + } + return 0; + +} + +// int DataTrans::Send_file_socket(const std::string &filename) +// { +// int socketfd; +// struct sockaddr_in s_add,c_add; +// unsigned short portnum = 9092; +// int len; +// char buffer[4096]; +// FILE *fp ; +// int file_block_length = 0; +// /* +// *创建socket +// */ +// if((socketfd = socket(AF_INET,SOCK_STREAM,0)) < 0) +// { +// print_error("Socket create error! \n"); +// return -1; +// } +// /* +// *设置地址 +// */ + +// bzero(&s_add,sizeof(struct sockaddr_in)); +// s_add.sin_family = AF_INET; +// //s_add.sin_addr.s_addr = inet_addr(GlobalConfig::ServerIP.c_str()); +// s_add.sin_addr.s_addr = inet_addr("192.168.1.19"); +// s_add.sin_port = htons(portnum); + + +// if (connect(socketfd,(struct sockaddr *)(&s_add),sizeof(struct sockaddr)) < 0) +// { +// print_error("Connect failure!\n"); +// return -1; +// } +// else +// print_info("Connect Success!\n"); +// std::string filename = filename.substr(); +// int file_name_length = (int)strlen(filename.c_str()); +// if(send(socketfd,(char *)&file_name_length, sizeof(int), 0) < 0) +// { +// print_error("Send File_Name_Length Failed!\n"); +// }else +// { +// print_info("Send File_Name_Length Success!\n"); +// } +// //发送文件名 +// if(send(socketfd,filename.c_str(),file_name_length,0) < 0) +// { +// print_error("Send File_Name Failed!\n"); +// }else +// { +// print_info("Send File_Name Success!\n"); +// } +// /* +// *发送文件 +// */ +// fp = fopen(filename.c_str(), "r"); + +// if (fp == NULL) +// { +// print_error("File: %s Not Found!\n", filename.c_str()); +// } +// else +// { +// bzero(buffer, BUFFER_SIZE); +// while( (file_block_length = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0) +// { +// print_info("file_block_length = %d\n", file_block_length); +// /* +// *把数据写入buffer +// */ +// if (send(socketfd, buffer, file_block_length, 0) < 0) +// { +// print_error("Send File:%s Failed!\n", filename.c_str()); +// break; +// } +// bzero(buffer, sizeof(buffer)); +// } +// fclose(fp); +// print_info("File: %s Transfer Finished!\n", filename.c_str()); +// } +// close(socketfd); +// return 0; +// } + +int DataTrans::Send_file_socket(const std::string &filename) +{ + + return 0; +} + +int DataTrans::Send_Dir_socket(const char *dirname) +{ + DIR *dirp; + std::vector v; + std::string temp; + struct dirent *dp; + dirp = opendir(dirname); + while ((dp = readdir(dirp)) != NULL) { + if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) + continue; + v.push_back(std::string(dp->d_name)); + } + + int socketfd = socket(AF_INET,SOCK_STREAM,0); + struct sockaddr_in s_add,c_add; + unsigned short portnum = 12345; + int len; + char buffer[BUFFER_SIZE]; + FILE *fp ; + int file_block_length = 0; + /* + *创建socket + */ + if(socketfd < 0) { + print_error("Socket create error! \n"); + return -1; + } else { + print_info("Socket create success!\n"); + } + /* + *设置地址 + */ + + bzero(&s_add,sizeof(struct sockaddr_in)); + s_add.sin_family = AF_INET; + s_add.sin_addr.s_addr = inet_addr(GlobalConfig::ServerIP.c_str()); + s_add.sin_port = htons(PORT); + + if (connect(socketfd,(struct sockaddr *)(&s_add),sizeof(struct sockaddr)) < 0) { + print_error("Connect failure!\n"); + return -1; + } else { + print_info("Connect Success!\n"); + } + std::vector::iterator iter; + for(iter = v.begin();iter != v.end();++iter) { + temp = *iter; + cout << temp.c_str() < 0) { + print_info("file_block_length = %d\n", file_block_length); + /* + *把数据写入buffer + */ + if (send(socketfd, buffer, file_block_length, 0) < 0) { + print_error("Send File:%s Failed!\n", filename.c_str()); + break; + } + bzero(buffer, sizeof(buffer)); + } + fclose(fp); + print_info("File: %s Transfer Finished!\n", filename.c_str()); + } + close(socketfd); + return 0; + } +} +void DataTrans::SetDebug(bool bDebug) +{ + m_bDebug = bDebug; +} diff --git a/datatransfer/SH_Datatrans.hpp b/datatransfer/SH_Datatrans.hpp new file mode 100644 index 0000000..d2439b5 --- /dev/null +++ b/datatransfer/SH_Datatrans.hpp @@ -0,0 +1,108 @@ +#ifndef _DATATRANS_H_ +#define _DATATRANS_H_ + +#include +#include +#include +#include +#include +#include +#include "../common/SH_global.h" +#include "../utility/SH_MySingleton.hpp" + +#define BUFFER_SIZE 4096 + +#define IP "127.0.0.1" +#define PORT 12345 + +class DataTrans : public MySingleton +{ +public: + DataTrans(); + ~DataTrans(); + + /** + * @brief HTTP POST请求 + * @param strUrl 输入参数,请求的Url地址,如:http://www.baidu.com + * @param strPost 输入参数,使用如下格式para1=val1¶2=val2&… + * @param strResponse 输出参数,返回的内容 + * @return 返回是否Post成功 + */ + int Post(const std::string & strUrl, const std::string & strPost, std::string & strResponse); + + /** + * @brief HTTP GET请求 + * @param strUrl 输入参数,请求的Url地址,如:http://www.baidu.com + * @param strResponse 输出参数,返回的内容 + * @return 返回是否Post成功 + */ + + int Get(const std::string & strUrl, std::string & strResponse); + + /** + * @brief HTTPS POST请求,无证书版本 + * @param strUrl 输入参数,请求的Url地址,如:https://www.baidu.com + * @param strPost 输入参数,使用如下格式para1=val1¶2=val2&… + * @param strResponse 输出参数,返回的内容 + * @param pCaPath 输入参数,为CA证书的路径.如果输入为NULL,则不验证服务器端证书的有效性. + * @return 返回是否Post成功 + */ + + int Posts(const std::string & strUrl, const std::string & strPost, std::string & strResponse, const char * pCaPath = NULL); + + /** + * @brief HTTPS GET请求,无证书版本 + * @param strUrl 输入参数,请求的Url地址,如:https://www.baidu.com + * @param strResponse 输出参数,返回的内容 + * @param pCaPath 输入参数,为CA证书的路径.如果输入为NULL,则不验证服务器端证书的有效性. + * @return 返回是否Post成功 + */ + + int Gets(const std::string & strUrl, std::string & strResponse, const char * pCaPath = NULL); + + /** + * @brief HTTP 上传文件 + * @param strUrl 输入参数,请求的Url地址,如:http://localcast:8080/source + * @param strResponse 输出参数,返回的内容 + * @param filename 文件的绝对地址,如/home/usr/cidw.log + * @return 函数返回0执行成功 + */ + + int upload_file(const std::string &strUrl, const std::string &filename, std::string &strResponse); + + /** + * @brief 下载文件,如果板子支持wget下载会方便很多接口保留,待确认后在开发 + * @param strUrl 输入参数,请求的Url地址,如:http://localcast:8080/source + * @param strResponse 输出参数,返回的内容 + * @param filename 文件的绝对地址,如/home/usr/cidw.log + * @return 函数返回0执行成功 + */ + + // int download_file(const std::string &strUrl, const std::string &filename, std::string &strResponse); + + /** + * @brief 通过socket发送文件 + * @param filename 文件名 + * @return 函数返回0执行成功 + */ + int Send_file_socket(const std::string &filename); + + /** + * @brief 通过socket发送文件夹下所有文件 + * @param dirname 文件名 + * @return 函数返回0执行成功 + */ + int Send_Dir_socket(const char *dirname); + + int download(char* pFilename,string& strUrl,string& strResponse,bool bDownload); + int dl_curl_post_req(const string &url, const string &postParams, string& filename); +public: + void SetDebug(bool bDebug); +private: + bool m_bDebug; +}; + +extern DataTrans *pDataTrans; +#endif + + diff --git a/datatransfer/subdir.mk b/datatransfer/subdir.mk new file mode 100644 index 0000000..685cc07 --- /dev/null +++ b/datatransfer/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../datatransfer/SH_Datatrans.cpp + +CPP_DEPS += \ +./datatransfer/SH_Datatrans.d + +OBJS += \ +./datatransfer/SH_Datatrans.o + + +# Each subdirectory must supply rules for building sources it contributes +datatransfer/%.o: ../datatransfer/%.cpp datatransfer/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-datatransfer + +clean-datatransfer: + -$(RM) ./datatransfer/SH_Datatrans.d ./datatransfer/SH_Datatrans.o + +.PHONY: clean-datatransfer + diff --git a/dbaccess/SH_SqlDB.cpp b/dbaccess/SH_SqlDB.cpp new file mode 100644 index 0000000..7b01612 --- /dev/null +++ b/dbaccess/SH_SqlDB.cpp @@ -0,0 +1,1577 @@ +#include "SH_SqlDB.hpp" +#include "../API_log/SH_log.h" +#include "../common/SH_global.h" +#include +#include "../calculation/Calculation.hpp" + +bool SqlSwitch() +{ + if (access("./sql", 0) >= 0) { + return true; + } + return false; +} + +SqliteDB *sql_ctl = SqliteDB::instance(); +Calculation *pCalculation = Calculation::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,%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), + "WakeupTime", + "StaticTime", + "WaveTime", + "BateryV", + "ProductNo", + 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), + "ZigbeePower", + "ZigbeeRetry", + "ZigbeeRetryGap", + "ACCSampleTime", + T_SENSOR_INFO(STATUS), + T_SENSOR_INFO(TIMESTAMP), + T_SENSOR_INFO(VIFF), + T_SENSOR_INFO(RSSI), + "UpdateFlag", + "LooseValue", + "batteryPower"), + CreateTable(sql_exec, isDB2); + + int iRet = GetTableRows(" sqlite_master "," name = 't_sensor_info' and sql LIKE '%LooseValue%' "); + if(iRet == 0){ + CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'LooseValue'"); + } + + iRet = GetTableRows(" sqlite_master "," name = 't_sensor_info' and sql LIKE '%batteryPower%' "); + if(iRet == 0){ + CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'batteryPower'"); + } + iRet = GetTableRows(" sqlite_master "," name = 't_sensor_info' and sql LIKE '%MeasurementID%' "); + if(iRet == 0){ + CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'MeasurementID'"); + } + iRet = GetTableRows(" sqlite_master "," name = 't_sensor_info' and sql LIKE '%NodeWaveSend%' "); + if(iRet == 0){ + CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'NodeWaveSend'"); + } + + memset(sql_exec, 0, 2048); + sprintf(sql_exec,"update t_sensor_info set MeasurementID = dataNodeNo where MeasurementID IS NULL ;"); + UpdateTableData(sql_exec,isDB2); + memset(sql_exec, 0, 2048); + sprintf(sql_exec,"update t_sensor_info set MeasurementID = dataNodeNo where MeasurementID = '' ;"); + UpdateTableData(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 integer,%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(STATICINDEX), + T_DATA_INFO(TIMESTAMP), + T_DATA_INFO(SENDMSG), + T_DATA_INFO(NODERESEND)); + CreateTable(sql_exec, isDB2); + + iRet = GetTableRows(" sqlite_master "," name = 't_data_info' and sql LIKE '%nodeResend%' "); + if(iRet == 0){ + CreateTable("ALTER TABLE t_data_info ADD COLUMN 'nodeResend'"); + } + + //创建传感器静态数据存储表 + memset(sql_exec, 0, 2048); + sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s integer,%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), + "Battery", + T_DATASTATIC_INFO(STATICINDEX), + T_DATASTATIC_INFO(TIMESTAMP), + T_DATASTATIC_INFO(SENDMSG), + T_DATASTATIC_INFO(NODERESEND)); + CreateTable(sql_exec, isDB2); + iRet = GetTableRows(" sqlite_master "," name = 't_datastatic_info' and sql LIKE '%nodeResend%' "); + if(iRet == 0){ + CreateTable("ALTER TABLE t_datastatic_info ADD COLUMN 'nodeResend'"); + } + + 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);", + T_GATEWAY_INFO(TNAME), + T_GATEWAY_INFO(GATEWAYMAC), + T_GATEWAY_INFO(SENSORVER), + T_GATEWAY_INFO(GATEWAYLOCATION), + T_GATEWAY_INFO(ZIGBEEPANID), + T_GATEWAY_INFO(ZIGBEECHANNEL), + T_GATEWAY_INFO(COMMUNICATIONTYPE), + T_GATEWAY_INFO(SIGNAL), + T_GATEWAY_INFO(LOCALIP), + T_GATEWAY_INFO(SYSTEMVERSION), + T_GATEWAY_INFO(PROGRAMVERSION), + T_GATEWAY_INFO(WEBVERSION), + T_GATEWAY_INFO(SERVERIP), + T_GATEWAY_INFO(SERVERPORT), + T_GATEWAY_INFO(STATUS), + T_GATEWAY_INFO(GATEWAYUPDATE), + T_GATEWAY_INFO(MAC2)); + CreateTable(sql_exec, isDB2); + + memset(sql_exec, 0, 2048); + sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s);", + "t_data_waveSend","channelID","waveName","timeStamp","sendMsg","save"); + CreateTable(sql_exec, isDB2); + + iRet = GetTableRows(" sqlite_master "," name = 't_data_waveSend' and sql LIKE '%sendMsg%' "); + if(iRet == 0){ + CreateTable("ALTER TABLE t_data_waveSend ADD COLUMN 'sendMsg'"); + } + iRet = GetTableRows(" sqlite_master "," name = 't_data_waveSend' and sql LIKE '%save%' "); + if(iRet == 0){ + CreateTable("ALTER TABLE t_data_waveSend ADD COLUMN 'save'"); + } + + memset(sql_exec, 0, 2048); + sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s);", + T_BATTERY_INFO(TNAME), + T_BATTERY_INFO(DATANODENO), + T_BATTERY_INFO(DIP), + T_BATTERY_INFO(TEMBOT), + T_BATTERY_INFO(NODEWORKTIME), + T_BATTERY_INFO(NODESENDTIME), + T_BATTERY_INFO(BATTERYVOLTAGE), + T_BATTERY_INFO(BATTERYUSAGE), + T_BATTERY_INFO(BATTERYREMAIN), + T_BATTERY_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,%s,%s);", + "t_battery_history", + T_BATTERY_INFO(DATANODENO), + T_BATTERY_INFO(DIP), + T_BATTERY_INFO(TEMBOT), + T_BATTERY_INFO(NODEWORKTIME), + T_BATTERY_INFO(NODESENDTIME), + T_BATTERY_INFO(BATTERYVOLTAGE), + T_BATTERY_INFO(BATTERYUSAGE), + T_BATTERY_INFO(BATTERYREMAIN), + T_BATTERY_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 integer,%s integer ,%s integer ,%s integer,%s integer);", + T_DATANODE_TIME(TNAME), + T_DATANODE_TIME(DATANODENO), + T_DATANODE_TIME(SHORTADDR), + T_DATANODE_TIME(STATICCYCLE), + T_DATANODE_TIME(WAVECYCLE), + T_DATANODE_TIME(NODEGROUP), + T_DATANODE_TIME(NODEINDEX), + T_DATANODE_TIME(NODEWAVEINDEX), + T_DATANODE_TIME(STATICTIME), + T_DATANODE_TIME(STATICSTARTTIME)); + CreateTable(sql_exec, isDB2);*/ + +} +void SqliteDB::Createtable(const char *ptableName) +{ + char sql_exec[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 integer,%s,%s,%s);", + ptableName, + 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), + "StaticIndex", + T_DATA_INFO(TIMESTAMP), + "sendMsg", + "nodeResend"); + CreateTable(sql_exec, 0); + memset(sql_exec, 0, 2048); + sprintf(sql_exec,"CREATE INDEX %s_1 \ + ON %s (%s)",ptableName,ptableName,T_DATA_INFO(DATANODENO)); + CreateTable(sql_exec, 0); +} + +void SqliteDB::SqliteInitDel(const char *pDbName) +{ + Deletetable(T_DATA_INFO(TNAME)); + Deletetable(T_DATASTATIC_INFO(TNAME)); + vec_t vecResult = GetDataMultiLineOfOneColumn(T_SENSOR_INFO(TNAME),T_SENSOR_INFO(ZIGBEELONGADDR),NULL); + for(int i = 0; i < vecResult.size() && vecResult.size() > 0;i++) + { + char sztableName[100]={0x00}; + sprintf(sztableName,"t_data_%s",vecResult[i].c_str()); + Deletetable(sztableName); + sprintf(sztableName,"t_dataStatic_%s",vecResult[i].c_str()); + Deletetable(sztableName); + } +} +void SqliteDB::Deletetable(const char *ptableName) +{ + char sql_exec[2048]; + //创建传感器数据存储表 + memset(sql_exec, 0, 2048); + sprintf(sql_exec,"DROP TABLE %s ;",ptableName); + int iRet = sqlite3_exec(GetDbHandle(false), sql_exec, 0, 0, NULL); + if (iRet != SQLITE_OK) { + perror_info("sqlite3_exec"); + } + +} +void SqliteDB::CreatedataStatictable(const char *ptableName) +{ + char sql_exec[2048]; + //创建传感器数据存储表 + memset(sql_exec, 0, 2048); + sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s integer,%s,%s,%s,%s integer,%s,%s);", + ptableName, + T_DATASTATIC_INFO(DATANODENO), + T_DATASTATIC_INFO(CHANNELID), + T_DATASTATIC_INFO(TEMTOP), + T_DATASTATIC_INFO(TEMBOT), + T_DATASTATIC_INFO(DIP), + T_DATASTATIC_INFO(VOLTAGE), + "zigbeeSignal", + "StaticIndex", + T_DATASTATIC_INFO(TIMESTAMP), + "sendMsg", + "nodeResend", + "zigbeeSignalNode", + "statisticType", + "timing" + ); + CreateTable(sql_exec, 0); + memset(sql_exec, 0, 2048); + sprintf(sql_exec,"CREATE INDEX %s_1 \ + ON %s (%s)",ptableName,ptableName,T_DATA_INFO(DATANODENO)); + CreateTable(sql_exec, 0); +} +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::ExeSql(const char *sql, bool isDB2) +{ + print_light_green("%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; +} + +char* SqliteDB::GetDataChar(const char *tablename, const char *column, const char *whereCon) +{ + char szRes[100]={0x00}; + 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; + g_tDbMutex.Lock(); + 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); + g_tDbMutex.UnLock(); + return NULL; + } + int retStep = sqlite3_step(stmt); + if (retStep == SQLITE_ROW) { + char *columninfo = (char*)sqlite3_column_text(stmt, 0); + memcpy(szRes,columninfo,sizeof(szRes)); + } + sqlite3_finalize(stmt); + g_tDbMutex.UnLock(); + return szRes; +} + +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; + g_tDbMutex.Lock(); + 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); + g_tDbMutex.UnLock(); + 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); + g_tDbMutex.UnLock(); + 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; + g_tDbMutex.Lock(); + 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); + g_tDbMutex.UnLock(); + 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); + g_tDbMutex.UnLock(); + return arrResult; +} +array_t SqliteDB::GetDataMultiLineTransaction(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_exec(mDBAcess, "BEGIN", 0, 0, NULL); + 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; + } + sqlite3_reset(stmt); + sqlite3_bind_int(stmt, 1, 0); + 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); + sqlite3_exec(mDBAcess, "COMMIT", 0, 0, NULL); + 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; +} +vec_Value SqliteDB::GetDataMultiLineOfOneColumnDouble(const char *tablename, const char *column, const char *whereCon) +{ + vec_Value 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) { + double columninfo = sqlite3_column_double(stmt, 0); + vecResult.push_back(columninfo); + 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 + ";"; + } + // LOG_INFO("strSql = %s",strSql.c_str()); + 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::UpdateNodeNameData(const char* tablename, const char* updateColumn, const char* whereCond, bool isDB2) +{ + std::string strSql = "update "; + char szSql[1024] = {0x00}; + strcat(szSql,"update "); + if (whereCond != NULL) { + strcat(szSql,tablename); + strcat(szSql," set "); + strcat(szSql,updateColumn); + strcat(szSql," where "); + strcat(szSql,whereCond); + strcat(szSql,";"); + 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), szSql, 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; + g_tDbMutex.Lock(); + 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); + } + g_tDbMutex.UnLock(); + 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::InsertData(const char* insertSql) +{ + char *msg; + int iRet = sqlite3_exec(GetDbHandle(false), insertSql, 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::CalculateBattery() +{ + LOG_INFO("CalculateBattery start\n"); + char whereCon[1024] = {0}; + char selectSql[1024] = { 0 }; + memset(whereCon,0x00,sizeof(whereCon)); + memset(selectSql,0x00,sizeof(selectSql)); + char updateSql[1024] = { 0 }; + sprintf(selectSql," dataNodeNo,StaticTime,WaveTime,featureInterVal,waveInterVal,samplingRate,batteryPower "); + array_t vecRes = GetDataMultiLine(T_SENSOR_INFO(TNAME), selectSql, NULL); + print_info("res = %d\n",vecRes.size()); + if(vecRes.size() > 0){ + for(int i = 0; i < vecRes.size(); i++){ + float capacity = 0.0,startCapacity = 0.0; + memset(whereCon,0x00,sizeof(whereCon)); + memset(selectSql,0x00,sizeof(selectSql)); + sprintf(whereCon," dataNodeNo = '%s' and batteryRemain <> '' order by timeStamp desc limit 0,1 ",vecRes[i][0].c_str()); + vec_t vecResSig = sql_ctl->GetDataSingleLine(T_BATTERY_INFO(TNAME)," * ",whereCon); + vector vParam; + boost::split( vParam, vecRes[i][6], boost::is_any_of( "," ), boost::token_compress_on ); + if(vParam.size() <= 0 || vecResSig.size() <= 0){//第一次计算 + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon,"dataNodeNo = '%s' ",vecRes[i][0].c_str()); + string Dip = sql_ctl->GetData(T_DATASTATIC_INFO(TNAME)," dip ",whereCon); + if(Dip == ""){ + continue; + } + capacity = (0.9+0.1*(90-atoi(Dip.c_str()))/90)*19000;//mAh //电池总量 + startCapacity = capacity; + + sprintf(updateSql,"batteryPower = '%f,%f' ",startCapacity,startCapacity); + + int iRet = UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon," dataNodeNo = '%s' order by timeStamp asc limit 0,1 ",vecRes[i][0].c_str()); + vecResSig = sql_ctl->GetDataSingleLine(T_BATTERY_INFO(TNAME)," * ",whereCon); + if(vecResSig.size() <= 0){//一条数据都没有 + + continue; + } + + }else{ + capacity = atof(vecResSig[7].c_str()); + } + + print_info("dip = %d\n",atoi(vecResSig[1].c_str())); + + print_info("capacity = %f\n",capacity); + sprintf(whereCon," dataNodeNo = '%s' and timeStamp > '%s'",vecRes[i][0].c_str(),vecResSig[8].c_str()); + array_t vecResbattery = GetDataMultiLine(T_BATTERY_INFO(TNAME), " * ", whereCon); + print_info("vecResbattery size = %d\n",vecResbattery.size()); + if(vecResbattery.size() <= 0){ + continue; + } + int y10_mins = 10 * 365 * 24 * 60; + int d200_mins = 200 * 24 * 60; + int x1 = 25,x2 = 60; + int y1 = 2; + float y2 = (float)y10_mins/(float)d200_mins; + + float k = (y2-y1)/(x2-x1); + vector vecb; + vector vecworkTime; + vector vecsendTime; + float to_math = 0.0; + print_info("vecResbattery = %d,temp = %s\n",vecResbattery.size(),vecResbattery[0][2].c_str()); + //LOG_INFO("vecResbattery = %d,temp = %s\n",vecResbattery.size(),vecResbattery[0][2].c_str()); + for (size_t j = 0; j < vecResbattery.size(); j++) + { + float b = 2 - 25 * k; + float dpm = k * atoi(vecResbattery[j][2].c_str()) + b;//温度 + float cost_e = dpm * atoi(vecRes[i][3].c_str());//特征值时间间隔 + float cost_h = cost_e / 60; + vecworkTime.push_back(atol(vecResbattery[j][3].c_str())); + vecsendTime.push_back(atol(vecResbattery[j][4].c_str())); + to_math += cost_h; + } + + print_info("自放电 = %f\n",to_math); + //LOG_INFO("自放电 = %f\n",to_math); + long sumworkTime = 0.0,sumsendTime = 0.0; + for(size_t j = 0 ; j < vecworkTime.size();j++) + { + sumworkTime += vecworkTime[j]; + } + for(size_t j = 0 ; j < vecsendTime.size();j++) + { + sumsendTime += vecsendTime[j]; + } + print_info("sumworkTime = %ld,sumsendTime = %ld\n",sumworkTime,sumsendTime); + //LOG_INFO("sumworkTime = %ld,sumsendTime = %ld\n",sumworkTime,sumsendTime); + float usageworkTime = ((float)sumworkTime/3600000) * 4; + float usagesendTime = ((float)sumsendTime/3600000) * 39; + print_info("work = %f,send = %f\n",usageworkTime,usagesendTime); + //LOG_INFO("work = %f,send = %f\n",usageworkTime,usagesendTime); + if(to_math < 0) + to_math = 0; + float usageBattery = usageworkTime + usagesendTime + to_math; + print_info("已经使用 = %f\n",atof(vecResSig[6].c_str())); + + float remainBattery = capacity - usageBattery * 0.2; + if (remainBattery < 10) + { + remainBattery = 10; + } + + LOG_INFO("dataNodeNo = %s,batteryUsage = %f,batteryRemain = %f\n",vecRes[i][0].c_str(),atof(vecResSig[6].c_str()),remainBattery); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon," dataNodeNo = '%s' order by timeStamp desc limit 0,1 ",vecRes[i][0].c_str()); + string strtimeStamp = sql_ctl->GetData(T_BATTERY_INFO(TNAME)," timeStamp ",whereCon); + + sprintf(updateSql, "batteryUsage='%f',batteryRemain='%f'",usageBattery,remainBattery); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "dataNodeNo ='%s' and timeStamp = '%s'", vecRes[i][0].c_str(),strtimeStamp.c_str()); + sql_ctl->UpdateTableData(T_BATTERY_INFO(TNAME), updateSql, whereCon); + + memset(whereCon,0x00,sizeof(whereCon)); + memset(updateSql,0x00,sizeof(updateSql)); + + char insertSql[1024]={0x00},deleteSql[1024]={0x00}; + sprintf(insertSql,"insert into t_battery_history select * from t_battery_info where timeStamp < '%s' and dataNodeNo = '%s'",strtimeStamp.c_str(),vecRes[i][0].c_str()); + ExeSql(insertSql); + + sprintf(deleteSql,"delete from t_battery_info where timeStamp < '%s' and dataNodeNo = '%s'",strtimeStamp.c_str(),vecRes[i][0].c_str()); + ExeSql(deleteSql); + + sprintf(whereCon,"dataNodeNo = '%s' ",vecRes[i][0].c_str()); + if(startCapacity > 0){ + sprintf(updateSql,"batteryPower = '%f,%f' ",startCapacity,remainBattery); + }else{ + sprintf(updateSql,"batteryPower = '%s,%f' ",vParam[0].c_str(),remainBattery); + } + + int iRet = UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + } + } + LOG_INFO("CalculateBattery end\n"); + + + + + /*float dayStaticPower = 6.5,dayWavePower = 237;// + char whereCon[1024] = {0}; + char selectSql[1024] = { 0 }; + memset(whereCon,0x00,sizeof(whereCon)); + memset(selectSql,0x00,sizeof(selectSql)); + sprintf(selectSql," DataNodeNo,StaticTime,WaveTime,featureInterVal,waveInterVal,samplingRate "); + array_t vecRes ; + vecRes = GetDataMultiLine(T_SENSOR_INFO(TNAME), selectSql, NULL); + if(vecRes.size() > 0){ + for(int i = 0; i < vecRes.size(); i++){ + if(vecRes[i][5] == "12800"){ + + }else if(vecRes[i][5] == "3200"){ + + } + float dayStaticTime = 0.0; + float dayWaveTime = 0.0; + if(atoi(vecRes[i][3].c_str()) == 0){ + dayStaticTime = 0; + }else{ + dayStaticTime = 24*60/atoi(vecRes[i][3].c_str()); + } + if(atoi(vecRes[i][4].c_str()) == 0){ + dayWaveTime = 0; + }else{ + dayWaveTime = 24*60/atoi(vecRes[i][4].c_str()); + } + + float dayPower = dayStaticTime * dayStaticPower + dayWaveTime * dayWavePower + 24*3.26;//static + wave + sleep + float usePower = atoi(vecRes[i][1].c_str()) * dayStaticPower + atoi(vecRes[i][2].c_str()) * dayWavePower; + if(dayPower == 0) + dayPower = 1; + float remainDay = (19000000*0.5 - usePower)/dayPower; + float bateryProportion = remainDay/(19000000*0.5/dayPower); + char updateSql[1024] = { 0x00 }; + char tmpParam[1024] = {0x00}; + memset(whereCon,0x00,sizeof(whereCon)); + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(whereCon,"dataNodeNo = '%s' ",vecRes[i][0].c_str()); + sprintf(updateSql,"batteryPower = '%f,%f' ",bateryProportion,remainDay); + int iRet = UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + print_info("iRet = %d\n",iRet); + string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + } + }*/ + + print_info("CalculateBattery \n"); + return 0; +} +int SqliteDB::CalculateDip() +{ + char whereCon[1024] = {0}; + char selectSql[1024] = { 0 }; + char updateSql[1024] = { 0 }; + memset(whereCon,0x00,sizeof(whereCon)); + memset(selectSql,0x00,sizeof(selectSql)); + sprintf(selectSql," DataNodeNo"); + array_t vecRes ; + char looseValue[10]={0x00}; + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + readStringValue("config", "loose",looseValue,(char*)GlobalConfig::Config_G.c_str()); + vecRes = GetDataMultiLine(T_SENSOR_INFO(TNAME), " * ", NULL); + print_info("vecRes111 = %d\n",vecRes.size()); + for(int i = 0 ; i < vecRes.size(); i++){ + vector vParam; + print_info("vecRes =%s\n",vecRes[i][42].c_str()); + boost::split( vParam, vecRes[i][42], boost::is_any_of( "," ), boost::token_compress_on ); + print_info("vParam size = %d\n",vParam.size()); + if(vParam.size() < 2) + { + sprintf(updateSql,"LooseValue = '%f,0' ",atof(vParam[0].c_str())); + sprintf(whereCon,"dataNodeNo = '%s' ",vecRes[i][0].c_str()); + UpdateTableData(T_SENSOR_INFO(TNAME),updateSql,whereCon); + }else{ + char szTablename[32]={0x00}; + memset(whereCon,0x00,sizeof(whereCon)); + if(vParam[1] == "2"){//人工干预 + sprintf(whereCon," timeStamp > '%ld' ",atol(vParam[2].c_str())); + }else if(vParam[1] == "0"){//正常状态 + sprintf(whereCon," timeStamp > '%ld' ",atol(localtimestamp) - 86400);//一天数据 + }else if(vParam[1] == "1")//松动状态 + { + continue; + } + print_info("vParam[0]= %s,vParam[1]=%s\n",vParam[0].c_str(),vParam[1].c_str()); + + sprintf(szTablename,"t_dataStatic_%s",vecRes[i][0].c_str()); + vec_Value vecResDip = GetDataMultiLineOfOneColumnDouble(szTablename," Dip ", whereCon); + float sample_variance = pCalculation->getSample_variance(vecResDip); + print_info("sample_variance = %f\n",sample_variance); + memset(whereCon,0x00,sizeof(whereCon)); + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(whereCon,"dataNodeNo = '%s' ",vecRes[i][0].c_str()); + if(vParam[1] == "0"){ + if(sample_variance > atol(looseValue)){ + sprintf(updateSql,"LooseValue = '%f,1' ",sample_variance); + }else{ + sprintf(updateSql,"LooseValue = '%f,0' ",sample_variance); + } + }else if(vParam[1] == "1"){ + + }else if(vParam[1] == "2"){ + print_info("localtimestamp = %ld,vParam[2]=%d,%ld\n",atol(localtimestamp),atol(vParam[2].c_str()),atol(localtimestamp) - atol(vParam[2].c_str())); + if(atol(localtimestamp) - atol(vParam[2].c_str()) > 86400){ + sprintf(updateSql,"LooseValue = '%f,0' ",atof(vParam[0].c_str())); + }else{ + sprintf(updateSql,"LooseValue = '%f,2,",atof(vParam[0].c_str())); + string strUpdateSql = string(updateSql) + vParam[2] + "' " ; + memset(updateSql,0x00,sizeof(updateSql)); + memcpy(updateSql,strUpdateSql.c_str(),sizeof(updateSql)); + } + if(sample_variance > atol(looseValue)) + { + sprintf(updateSql,"LooseValue = '%f,1' ",sample_variance); + } + + } + } + + UpdateTableData(T_SENSOR_INFO(TNAME),updateSql,whereCon); + } + print_info("CalculateDip \n"); +} +int SqliteDB::InintGateway() +{ + //更新网关配置表 + string strIP = GetGwIp_("eth0"); + string strServerIP = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress"); + string strServerPort = ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort"); + string strwebVersion = ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion"); + string strsystemVersion = ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion"); + string strGatewayVersion = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayVersion"); + std::string strchan = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "channel"); + std::string strPanID = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "PanID"); + if(strPanID == ""){ + strPanID = GlobalConfig::MacAddr_G.substr(8); + } + if(0 == sql_ctl->GetTableRows(T_GATEWAY_INFO(TNAME), NULL)){ + + char strSql[1024] = { 0 }; + sprintf(strSql,"insert into t_gateway_info(gatewayMAC,zigbeePanID,zigbeeChannel,\ + localIP,systemVersion,programVersion,webVersion,serverIP,serverPort,MAC2)\ + values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s');",GlobalConfig::MacAddr_G.c_str(),strPanID.c_str(),strchan.c_str(),strIP.c_str(),\ + strsystemVersion.c_str(),strGatewayVersion.c_str(),strwebVersion.c_str(),strServerIP.c_str(),strServerPort.c_str(),GlobalConfig::MacAddr_G2.c_str()); + sql_ctl->InsertData(strSql); + print_info("strSql = %s\n",strSql); + }else{ + char whereCon[1024] = {0}; + char updateSql[1024] = { 0 }; + sprintf(updateSql, "zigbeePanID = '%s',zigbeeChannel = '%s',localIP = '%s',systemVersion='%s',programVersion='%s',webVersion='%s',serverIP='%s',serverPort='%s'",\ + strPanID.c_str(),strchan.c_str(),strIP.c_str(),\ + strsystemVersion.c_str(),strGatewayVersion.c_str(),strwebVersion.c_str(),strServerIP.c_str(),strServerPort.c_str()); + sprintf(whereCon, "gatewayMAC='%s'", GlobalConfig::MacAddr_G.c_str()); + sql_ctl->UpdateTableData(T_GATEWAY_INFO(TNAME), updateSql, whereCon); + } + + //上传网关配置到MQTT + Json::Value jsSystemSetting; + Json::Value jsBody; + Json::FastWriter showValue; + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["cmd"] = "23"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsSystemSetting["WebVersion"] = strwebVersion; + jsSystemSetting["SystemVersion"] = strsystemVersion; + jsSystemSetting["GateWayVersion"] = strGatewayVersion; + jsBody["localServerIpAddress"] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress"); + jsBody["localServerPort"] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str()); + jsBody["CommMode"] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "CommMode").c_str()); + jsBody["Password"] = (ReadStrByOpt(SERVERCONFIG, "Server", "Password")); + jsBody["UserName"] = (ReadStrByOpt(SERVERCONFIG, "Server", "UserName")); + std::string dataBody = showValue.write(jsBody); + jsonVal["cmdBody"] = dataBody; + data_publish(showValue.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + + jsBody.clear(); + jsonVal["cmd"] = "25"; + 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"); + + dataBody = showValue.write(jsBody); + jsonVal["cmdBody"] = dataBody; + data_publish(showValue.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); +} + +std::string SqliteDB::GetNodeConfigureInfor(const char* whereCon) +{ + Json::Value jsonVal; + Json::FastWriter showValue; + 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), "*", whereCon); + int iResult = arrRes.size(); + if (iResult > 0) { + for (int j = 0; j < iResult; j++) { + Json::Value jsSensorData; + jsSensorData["dataNodeNo"] = arrRes[j][44]; + jsSensorData["dataNodeName"] = arrRes[j][1]; + jsSensorData["initFlag"] = atoi(arrRes[j][2].c_str()); + jsSensorData["accFlag"] = atoi(arrRes[j][3].c_str()); + jsSensorData["zigbeeFlag"] = atoi(arrRes[j][4].c_str()); + jsSensorData["temTopFlag"] = atoi(arrRes[j][5].c_str()); + jsSensorData["temBotFlag"] = atoi(arrRes[j][6].c_str()); + jsSensorData["equipsta"] = atoi(arrRes[j][7].c_str()); + 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["WakeupTime"] = atoi(arrRes[j][13].c_str()); + jsSensorData["StaticTime"] = atoi(arrRes[j][14].c_str()); + jsSensorData["WaveTime"] = atoi(arrRes[j][15].c_str()); + jsSensorData["BateryV"] = arrRes[j][16]; + jsSensorData["ProductNo"] = arrRes[j][17]; + jsSensorData["configFlag"] = atoi(arrRes[j][18].c_str()); + jsSensorData["startBrands"] = arrRes[j][19]; + jsSensorData["stopBrands"] = arrRes[j][20]; + jsSensorData["featureInterVal"] = (arrRes[j][21]); + jsSensorData["waveInterVal"] = atoi(arrRes[j][22].c_str()); + jsSensorData["samplingRate"] = atoi(arrRes[j][23].c_str()); + jsSensorData["range"] = atoi(arrRes[j][25].c_str()); + jsSensorData["envelopeBandPass"] = arrRes[j][26]; + jsSensorData["faultFrequency"] = arrRes[j][27]; + jsSensorData["zigbeePanId"] = arrRes[j][28]; + jsSensorData["zigbeeChannel"] = (arrRes[j][29]); + jsSensorData["zigbeeAddr"] = arrRes[j][30]; + jsSensorData["zigbeeLongAddr"] = arrRes[j][31]; + jsSensorData["zigbeeDesAddr"] = arrRes[j][32]; + jsSensorData["ZigbeePower"] = atoi(arrRes[j][33].c_str()); + jsSensorData["ZigbeeRetry"] = atoi(arrRes[j][34].c_str()); + jsSensorData["ZigbeeRetryGap"] = atoi(arrRes[j][35].c_str()); + jsSensorData["ACCSampleTime"] = atoi(arrRes[j][36].c_str()); + jsSensorData["status"] = atoi(arrRes[j][37].c_str()); + jsSensorData["timeStamp"] = arrRes[j][38]; + jsSensorData["viff"] = atoi(arrRes[j][39].c_str()); + jsSensorData["RSSI"] = arrRes[j][40]; + jsSensorData["Update"] = atoi(arrRes[j][41].c_str()); + jsSensorData["looseValue"] = arrRes[j][42]; + jsSensorData["battery"] = arrRes[j][43]; + jsSensorData["MeasurementID"] = arrRes[j][44]; + jsSensorData["nodeWaveSend"] = arrRes[j][45]; + 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); +} + +int SqliteDB::QueryofflineData() +{ + array_t arrRetdataNode = GetDataMultiLine(T_SENSOR_INFO(TNAME)," dataNodeNo,MeasurementID ",NULL); + for(int i = 0; i < arrRetdataNode.size();i++){ + char StaticTableName[50]={0x00}; + sprintf(StaticTableName,"t_dataStatic_%s",arrRetdataNode[i][0].c_str()); + + array_t arrRetData = GetDataMultiLine(StaticTableName, "*","sendMsg = '0' order by timeStamp asc"); + LOG_INFO("mqttresend check datanodeNo %s,data count %d\n",arrRetdataNode[i][0].c_str(),arrRetData.size()); + if(arrRetData.size() < 1) + continue; + for(int j = 0; j < arrRetData.size();j++){ + char dataTableName[50]={0x00}; + sprintf(dataTableName,"t_data_%s",arrRetdataNode[i][0].c_str()); + char tmpWhere[128]={0x00}; + sprintf(tmpWhere,"sendMsg = '0' and timeStamp = '%s'",arrRetData[j][8].c_str()); + array_t arrRet = GetDataMultiLine(dataTableName, "*","sendMsg = '0'"); + if(arrRet.size() > 0){ + Json::Value valNodeData; + Json::Value valNodeFeature; + for(int k = 0; k < arrRet.size();k++){ + + valNodeFeature["dataNodeNo"] = arrRetdataNode[i][1].c_str(); + valNodeFeature["ChannelId"] = arrRet[k][1].c_str(); + valNodeFeature["diagnosisPk"] = atof(arrRet[k][2].c_str()); + valNodeFeature["integratPk"] = atof(arrRet[k][3].c_str()); + valNodeFeature["integratRMS"] = atof(arrRet[k][4].c_str()); + valNodeFeature["rmsValues"] = atof(arrRet[k][5].c_str()); + valNodeFeature["envelopEnergy"] = atof(arrRet[k][6].c_str()); + valNodeFeature["Amp1"] = atof(arrRet[k][7].c_str()); + valNodeFeature["Amp2"] = atof(arrRet[k][8].c_str()); + valNodeFeature["Amp3"] = atof(arrRet[k][9].c_str()); + valNodeFeature["Amp4"] = atof(arrRet[k][10].c_str()); + valNodeFeature["Amp5"] = atof(arrRet[k][1].c_str()); + valNodeFeature["Phase1"] = atof(arrRet[k][12].c_str()); + valNodeFeature["Phase2"] = atof(arrRet[k][13].c_str()); + valNodeFeature["Phase3"] = atof(arrRet[k][14].c_str()); + valNodeFeature["Phase4"] = atof(arrRet[k][15].c_str()); + valNodeFeature["timeStamp"] = atoi(arrRet[k][17].c_str()); + valNodeData.append(valNodeFeature); + } + } + //无线传感器信息 + Json::Value root; + Json::Value valdatastatic; + Json::Value valNodeData; + valdatastatic["TemperatureTop"] = atof(arrRetData[j][2].c_str()); + valdatastatic["TemperatureBot"] = atof(arrRetData[j][3].c_str()); + valdatastatic["Dip"] = atof(arrRetData[j][4].c_str()); + valdatastatic["Voltage"] = atof(arrRetData[j][5].c_str()); + valdatastatic["ChannelType"] = "STATUS"; + valdatastatic["ChannelId"] = (arrRetData[j][1].c_str()); + valdatastatic["TimeStamp"] = atoi(arrRetData[j][8].c_str()); + + valdatastatic["dataNodeNo"] = arrRetData[j][0].c_str(); + valNodeData.append(valdatastatic); + + root["data"] = valNodeData; + root["TimeStamp"] = atoi(arrRetData[j][8].c_str()); + root["dataNodeNo"] = arrRetdataNode[i][1].c_str(); + root["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + root["status"] = "resend"; + Json::FastWriter featureValue; + std::string strstatisticData = featureValue.write(root); + + int iRet = data_publish(strstatisticData.c_str(), GlobalConfig::Topic_G.mPubData.c_str()); + //print_info("dataNodeNo = '%s' and TimeStamp = '%s',MQTT ret = %d\n",arrRetData[j][0].c_str(),nowTimetamp.c_str(),iRet); + if(iRet == 0){ + char updateSql[1024] = { 0 }; + char whereCon[64] = { 0 }; + memset(whereCon, 0, 64); + sprintf(whereCon, "dataNodeNo = '%s' and TimeStamp = '%s'", arrRetData[j][0].c_str(),arrRetData[j][8].c_str()); + memcpy(updateSql, "sendMsg='1'",sizeof(updateSql)); + sql_ctl->UpdateTableData(StaticTableName, updateSql, whereCon); + sql_ctl->UpdateTableData(dataTableName, updateSql, whereCon); + //LOG_INFO("resend success dataNodeNo = %s,TimeStamp = '%s'\n",arrRetData[j][0].c_str(),arrRetData[j][8].c_str()); + } + } + } + char whereCon[1024] = {0x00}; + sprintf(whereCon, " SendMsg = 0 "); + array_t arrRetData = GetDataMultiLine("t_data_waveSend", "*",whereCon); + LOG_INFO("mqttresend check wave count %d\n",arrRetData.size()); + if(arrRetData.size() > 0){ + for(int i = 0; i < arrRetData.size();i++){ + std::string strWaveData = ""; + if (access(arrRetData[i][1].c_str(), 0) >= 0) + { + std::vector vecWave; + char localtimestamp[32] = { 0 }; + float fTemp = 0; + std::ifstream inFile(arrRetData[i][1].c_str(),ios::in|ios::binary); + inFile.read((char *)localtimestamp,sizeof(localtimestamp)); + while(inFile.read((char *)&fTemp,sizeof(fTemp))){ + vecWave.push_back(fTemp); + } + + for (int i = 0; i < vecWave.size(); i++) { + char buf[33]={0x00}; + memset(buf,0x00,sizeof(buf)); + sprintf(buf, "%.2f", vecWave[i]); + std::string waveTemp(buf); + if(i == 0){ + strWaveData = waveTemp; + } + strWaveData = strWaveData + "," + waveTemp; + } + inFile.close(); + } + Json::Value valWaveData; + int length = strWaveData.length(); + valWaveData["number"] = length; + valWaveData["channelId"] = arrRetData[i][0]; + valWaveData["dataNodeNo"] = arrRetData[i][0].substr(0,arrRetData[i][0].length()-2); + valWaveData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + valWaveData["SensorEngineeringUnit"] = ""; + valWaveData["timeStamp"] = arrRetData[i][2]; + valWaveData["waveData"] = strWaveData; + Json::FastWriter WaveValue; + std::string WaveData = WaveValue.write(valWaveData); + int iRet = data_publish(WaveData.c_str(), GlobalConfig::Topic_G.mPubWaveData.c_str()); + if(iRet == 0){ + char whereCon[1024] = {0x00}; + char updateSql[1024] = {0x00}; + sprintf(whereCon, "channelID='%s' and timeStamp = '%s' ", arrRetData[i][0].c_str(),arrRetData[i][2].c_str()); + sprintf(updateSql, "SendMsg = 1"); + sql_ctl->UpdateTableData("t_data_waveSend", updateSql, whereCon); + //char whereCon[64]={0x00}; + //sprintf(whereCon,"waveName = '%s'",arrRetData[i][1].c_str()); + //DeleteTableData("t_data_waveSend", whereCon); + std::string strCmd = "rm " + arrRetData[i][1]; + system(strCmd.c_str()); + //LOG_INFO("resend success waveName = %s\n",arrRetData[i][1].c_str()); + } + } + + } +} +int SqliteDB::CalculateData() +{ + array_t vecRet = GetDataMultiLine(T_SENSOR_INFO(TNAME)," dataNodeNo,MeasurementID,NodeWaveSend,featureInterVal,waveInterVal,ZigbeePower ",NULL); + if (vecRet.size() > 0) + { + + int planCount = 0,planCountStatistic = 0,StatisticCountTotal = 0,SixCountTotal = 0,TimingCountTotal = 0,CountWaveXTotal = 0,waveInterVal = 0,featureInterVal = 0; + int CountWaveYTotal = 0 , CountWaveZTotal = 0; + for (size_t i = 0; i < vecRet.size(); i++) + { + planCount = 1440 / atoi(vecRet[i][4].c_str()) ; + planCountStatistic = 1440 / atoi(vecRet[i][3].c_str()) ; + int rate = readIntValue( "config", "waveRate",(char*)GlobalConfig::Config_G.c_str()); + char tableName[50]={0x00}; + char whereCon[128]={0x00}; + sprintf(tableName,"t_dataStatic_%s",vecRet[i][0].c_str()); + const char *sql = + " timestamp >= strftime('%s', 'now', '-1 day', 'start of day','utc') " + "AND timestamp < strftime('%s', 'now', '-1 day','start of day','utc','+24 hours') "; + int StatisticCount = GetTableRows(tableName,sql); + + sql = "timeStamp >= strftime('%s', 'now', '-1 day', 'start of day','utc') AND timeStamp < strftime('%s', 'now', '-1 day','start of day','utc','+24 hours') and statisticType = '1' "; + int SixCount = GetTableRows(tableName,sql); + + sql = "timeStamp >= strftime('%s', 'now', '-1 day', 'start of day','utc') AND timeStamp < strftime('%s', 'now', '-1 day','start of day','utc','+24 hours') and statisticType = '1' and timing = '0'"; + int TimingCount = GetTableRows(tableName,sql); + print_info("nodeWaveSend = %s,waveInterVal = %s\n",vecRet[i][2].c_str(),vecRet[i][4].c_str()); + if(vecRet[i][2] == "") + continue; + vector nodeWaveSend ; + boost::split( nodeWaveSend, vecRet[i][2], boost::is_any_of( "," ), boost::token_compress_on ); + int CountWaveX = 0,CountWaveY = 0,CountWaveZ = 0; + int CountWaveX2 = 0,CountWaveY2 = 0,CountWaveZ2 = 0; + int CountWaveX3 = 0,CountWaveY3 = 0,CountWaveZ3 = 0; + int rateX = 0,rateY = 0,rateZ = 0; + if (nodeWaveSend.size() < 3) + { + continue; + } + sprintf(tableName,"t_data_waveSend"); + const char *sql1 = + "timeStamp >= strftime('%s', 'now', '-1 day', 'start of day','utc')" + " AND timeStamp < strftime('%s', 'now','-1 day', 'start of day','utc','+24 hours')"; + + const char *sql2 = + "timeStamp >= strftime('%s', 'now', '-2 day', 'start of day','utc')" + " AND timeStamp < strftime('%s', 'now','-2 day', 'start of day','utc','+24 hours')"; + + const char *sql3 = + "timeStamp >= strftime('%s', 'now', '-3 day', 'start of day','utc')" + " AND timeStamp < strftime('%s', 'now','-3 day', 'start of day','utc','+24 hours')"; + if (nodeWaveSend[0] == "0") + { + sprintf(whereCon," and channelID = '%s-X'",vecRet[i][1].c_str()); + string strsql = string(sql1) + string(whereCon); + printf("sql = %s\n",strsql.c_str()); + CountWaveX = GetTableRows(tableName,strsql.c_str()); + sprintf(whereCon," and channelID = '%s-X'",vecRet[i][1].c_str()); + strsql = string(sql2) + string(whereCon); + CountWaveX2 = GetTableRows(tableName,strsql.c_str()); + sprintf(whereCon," and channelID = '%s-X'",vecRet[i][1].c_str()); + strsql = string(sql3) + string(whereCon); + CountWaveX3 = GetTableRows(tableName,strsql.c_str()); + if ((CountWaveX > 0 && (CountWaveX / planCount > (rate/100))) && (CountWaveX2 > 0 && (CountWaveX2 / planCount > (rate/100))) && (CountWaveX3 > 0 && (CountWaveX3 / planCount > (rate/100)))) + { + rateX = 1; + }else{ + rateX = -1; + } + + } + if(nodeWaveSend[1] == "0"){ + + sprintf(whereCon," and channelID = '%s-Y'",vecRet[i][1].c_str()); + string strsql = string(sql1) + string(whereCon); + CountWaveY = GetTableRows(tableName,strsql.c_str()); + sprintf(whereCon," and channelID = '%s-Y'",vecRet[i][1].c_str()); + strsql = string(sql2) + string(whereCon); + CountWaveY2 = GetTableRows(tableName,strsql.c_str()); + sprintf(whereCon," and channelID = '%s-Y'",vecRet[i][1].c_str()); + strsql = string(sql3) + string(whereCon); + CountWaveY3 = GetTableRows(tableName,strsql.c_str()); + + if ((CountWaveY > 0 && (CountWaveY / planCount > (rate/100))) && (CountWaveY2 > 0 && (CountWaveY2 / planCount > (rate/100))) && (CountWaveY3 > 0 && (CountWaveY3 / planCount > (rate/100)))) + { + rateY = 1; + }else{ + rateY = -1; + } + + } + if(nodeWaveSend[2] == "0"){ + + sprintf(whereCon," and channelID = '%s-Z'",vecRet[i][1].c_str()); + string strsql = string(sql1) + string(whereCon); + CountWaveZ = GetTableRows(tableName,strsql.c_str()); + sprintf(whereCon," and channelID = '%s-Z'",vecRet[i][1].c_str()); + strsql = string(sql2) + string(whereCon); + CountWaveZ2 = GetTableRows(tableName,strsql.c_str()); + sprintf(whereCon," and channelID = '%s-Z'",vecRet[i][1].c_str()); + strsql = string(sql3) + string(whereCon); + CountWaveZ3 = GetTableRows(tableName,strsql.c_str()); + + if ((CountWaveZ > 0 && (CountWaveZ / planCount > (rate/100))) && (CountWaveZ2 > 0 && (CountWaveZ2 / planCount > (rate/100))) && (CountWaveZ3 > 0 && (CountWaveZ3 / planCount > (rate/100)))) + { + rateZ = 1; + }else{ + rateZ = -1; + } + } + StatisticCountTotal += StatisticCount; + SixCountTotal += SixCount; + TimingCountTotal += TimingCount; + CountWaveXTotal += CountWaveX; + CountWaveYTotal += CountWaveY; + CountWaveZTotal += CountWaveZ; + LOG_INFO("dataNodeNo = %s , Statistic Count = %d , 06 Count = %d , Timing Count = %d , CountWaveX = %d , CountWaveY = %d , CountWaveZ = %d , featureInterVal = %s , waveInterVal = %s , NodeWaveSend = %s\n"\ + ,vecRet[i][0].c_str(),StatisticCount,SixCount,TimingCount,CountWaveX,CountWaveY,CountWaveZ,vecRet[i][3].c_str(),vecRet[i][4].c_str(),vecRet[i][2].c_str()); + + int zigbeepowerEnable = readIntValue( "config", "zigbeepowerEnable",(char*)GlobalConfig::Config_G.c_str()); + if(zigbeepowerEnable){ + LOG_INFO("rateX = %d,rateY = %d,rateZ = %d,zigbeepower = %s \n",rateX,rateY,rateZ,vecRet[i][5].c_str()); + if (rateX != -1 && rateY != -1 && rateZ != -1 && vecRet[i][5] == "3") + { + char updateSql[50] = {0x00}; + sprintf(updateSql,"ZigbeePower = '2',UpdateFlag = 0 "); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon," dataNodeNo = '%s'",vecRet[i][0].c_str()); + UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + LOG_INFO("2 update ZigbeePower "); + } + + if ((rateX == -1 || rateY == -1 || rateZ == -1 ) && vecRet[i][5] == "2") + { + char updateSql[50] = {0x00}; + sprintf(updateSql,"ZigbeePower = '3',UpdateFlag = 0 "); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon," dataNodeNo = '%s'",vecRet[i][0].c_str()); + UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + LOG_INFO("3 update ZigbeePower "); + } + } + featureInterVal = atoi(vecRet[i][3].c_str()); + waveInterVal = atoi(vecRet[i][4].c_str()); + } + LOG_INFO("Node Count = %d , featureInterVal = %d , waveInterVal = %d\n",vecRet.size(),featureInterVal,waveInterVal); + LOG_INFO("plan Statistic Count = %d , 06 Count = %d , Timing Count = %d , CountWaveX = %d ",planCountStatistic * vecRet.size(),planCount * vecRet.size(),planCount * vecRet.size(),planCount * vecRet.size()); + LOG_INFO("reality Statistic Count = %d , 06 Count = %d , Timing Count = %d , CountWaveX = %d ,CountWaveY = %d ,CountWaveZ = %d ",StatisticCountTotal,SixCountTotal,TimingCountTotal,CountWaveXTotal,CountWaveYTotal,CountWaveZTotal); + + } + +} + +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..e3bac47 --- /dev/null +++ b/dbaccess/SH_SqlDB.hpp @@ -0,0 +1,204 @@ +#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] +#define T_GATEWAY_INFO(x) T_GATEWAY_INFO[T_GATEWAY_INFO_##x] +#define T_DATANODE_TIME(x) T_DATANODE_TIME[T_DATANODE_TIME_##x] +#define T_BATTERY_INFO(x) T_BATTERY_INFO[T_BATTERY_INFO_##x] + +typedef std::map map_t; +typedef std::vector vec_t; +typedef std::vector vec_Value; +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); + void SqliteInitDel(const char *pDbName); + void Createtable(const char *ptableName); + void Deletetable(const char *ptableName); + void CreatedataStatictable(const char *ptableName); + int TransBegin(); + int TransRollback(); + int TransCommit(); + int CreateTable(const char *sql, bool isDB2=false); + int ExeSql(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); + char* GetDataChar(const char *tablename, const char *column, const char *whereCon); + array_t GetDataMultiLine(const char *tablename, const char *column, const char *whereCon); + array_t GetDataMultiLineTransaction(const char *tablename, const char *column, const char *whereCon); + vec_t GetDataMultiLineOfOneColumn(const char *tablename, const char *column, const char *whereCon); + vec_Value GetDataMultiLineOfOneColumnDouble(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 UpdateNodeNameData(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 InsertData(const char* insertSql); + int CalculateBattery(); + int CalculateDip(); + int InintGateway(); + int QueryofflineData(); + int CalculateData(); + int CalculateWaveRate(); + std::string GetNodeConfigureInfor(const char* whereCon); + 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_STATICINDEX, + T_DATA_INFO_TIMESTAMP, + T_DATA_INFO_SENDMSG, + T_DATA_INFO_NODERESEND +}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","StaticIndex","timeStamp","sendMsg","nodeResend"}; + + +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_STATICINDEX, + T_DATASTATIC_INFO_TIMESTAMP, + T_DATASTATIC_INFO_SENDMSG, + T_DATASTATIC_INFO_NODERESEND +}T_DATASTATIC_INFO_Index; +const static char* T_DATASTATIC_INFO[] = { "t_datastatic_info","dataNodeNo","channelID","temTop","temBot","dip","voltage","StaticIndex","timeStamp","sendMsg","nodeResend"}; + +typedef enum { + T_DATANODE_TIME_TNAME = 0, + T_DATANODE_TIME_DATANODENO, + T_DATANODE_TIME_SHORTADDR, + T_DATANODE_TIME_STATICCYCLE, + T_DATANODE_TIME_WAVECYCLE, + T_DATANODE_TIME_NODEGROUP, + T_DATANODE_TIME_NODEINDEX, + T_DATANODE_TIME_NODEWAVEINDEX, + T_DATANODE_TIME_STATICTIME, + T_DATANODE_TIME_STATICSTARTTIME +}T_DATANODE_TIME_Index; +const static char* T_DATANODE_TIME[] = { "t_datanode_time","dataNodeNo","shortaddr","staticcycle","wavecycle","nodegroup","nodeindex","nodewaveindex","statictime","staticstarttime"}; + + +typedef enum { + T_GATEWAY_INFO_TNAME = 0, + T_GATEWAY_INFO_GATEWAYMAC, + T_GATEWAY_INFO_SENSORVER, + T_GATEWAY_INFO_GATEWAYLOCATION, + T_GATEWAY_INFO_ZIGBEEPANID, + T_GATEWAY_INFO_ZIGBEECHANNEL, + T_GATEWAY_INFO_COMMUNICATIONTYPE, + T_GATEWAY_INFO_SIGNAL, + T_GATEWAY_INFO_LOCALIP, + T_GATEWAY_INFO_SYSTEMVERSION, + T_GATEWAY_INFO_PROGRAMVERSION, + T_GATEWAY_INFO_WEBVERSION, + T_GATEWAY_INFO_SERVERIP, + T_GATEWAY_INFO_SERVERPORT, + T_GATEWAY_INFO_STATUS, + T_GATEWAY_INFO_GATEWAYUPDATE, + T_GATEWAY_INFO_MAC2, +}T_GATEWAY_INFO_Index; +const static char* T_GATEWAY_INFO[] = { "t_gateway_info","gatewayMAC","sensorVersion","gatewayLocation","zigbeePanID","zigbeeChannel","communicationType","signal","localIP","systemVersion","programVersion","webVersion","serverIP","serverPort","status","gateWayUpdate","MAC2"}; + +typedef enum { + T_BATTERY_INFO_TNAME = 0, + T_BATTERY_INFO_DATANODENO, + T_BATTERY_INFO_DIP, + T_BATTERY_INFO_TEMBOT, + T_BATTERY_INFO_NODEWORKTIME, + T_BATTERY_INFO_NODESENDTIME, + T_BATTERY_INFO_BATTERYVOLTAGE, + T_BATTERY_INFO_BATTERYUSAGE, + T_BATTERY_INFO_BATTERYREMAIN, + T_BATTERY_INFO_TIMESTAMP + +}T_BATTERY_INFO_Index; +const static char* T_BATTERY_INFO[] = { "t_battery_info","dataNodeNo","Dip","temBot","nodeWorkTime","nodeSendTime","batteryVoltage","batteryUsage","batteryRemain","timeStamp"}; +#endif diff --git a/dbaccess/subdir.mk b/dbaccess/subdir.mk new file mode 100644 index 0000000..e4fa2dc --- /dev/null +++ b/dbaccess/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../dbaccess/SH_SqlDB.cpp + +CPP_DEPS += \ +./dbaccess/SH_SqlDB.d + +OBJS += \ +./dbaccess/SH_SqlDB.o + + +# Each subdirectory must supply rules for building sources it contributes +dbaccess/%.o: ../dbaccess/%.cpp dbaccess/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-dbaccess + +clean-dbaccess: + -$(RM) ./dbaccess/SH_SqlDB.d ./dbaccess/SH_SqlDB.o + +.PHONY: clean-dbaccess + diff --git a/dial5G/Dial.cpp b/dial5G/Dial.cpp new file mode 100644 index 0000000..222ff65 --- /dev/null +++ b/dial5G/Dial.cpp @@ -0,0 +1,296 @@ +/* + * Dial.cpp + * + * Created on: 2023年6月13日 + * Author: chaos + */ +#include +#include +#include +#include +#include +#include +#include "../common/SH_CommonFunc.hpp" +#include "Dial.h" + + +Dial::Dial() { + // TODO Auto-generated constructor stub + m_fd = 0; + m_curState = CPIN; + m_dial = 0; + m_APN = 0; +} + +Dial::~Dial() { + // TODO Auto-generated destructor stub +} + +int Dial::openPort(const char* pPort) +{ + m_fd = config_uart(pPort,115200); + print_info("m_fd = %d\n",m_fd); + return m_fd; +} +int Dial::parseData(Event event,const char* pData) +{ + print_info("m_curState = %d,event = %d\n",m_curState,event); + string signal; + string ret; + std::string str; + int pos = 0; + switch(event){ + case Event_CPIN: + if(!strncmp(pData,"READY",5)){ + m_curState = QCFGNET; + }else if(!strncmp(pData,"NOT READY",9)){ + m_curState = CPIN; + GlobalConfig::NetStatus = "\"LIMSRV\""; + } + break; + case Event_QCFGNET: + case Event_QCFGSMS: + /*ret = GetOneContent(pData,1,","); + if(ret == "0") + { + m_curState = QICSGPAPN; + }*/ + break; + case Event_QICSGPAPN: + //if(!strcmp(pData,"OK")) + { + m_curState = QNETDEVCTL; + } + break; + case Event_QENG: + GlobalConfig::NetStatus = GetOneContent(pData,1,","); + GlobalConfig::NetType = GetOneContent(pData,2,","); + signal = GetOneContent(pData,12,","); + GlobalConfig::NetSignal = atoi(signal.c_str()); + print_info("NetStatus = %s,NetSignal = %d\n",GlobalConfig::NetStatus.c_str(),GlobalConfig::NetSignal); + break; + case Event_QNETDEVCTL: + print_info("m_curState Event_QNETDEVCTL = %d\n",m_curState); + if(m_dial == 1){ + m_curState = QNETDEVSTATUS; + } + break; + case Event_QNETDEVSTATUS: + ret = GetOneContent(pData,3,","); + if(ret == "0" || ret == "") + m_curState = QDCHPC; + else + m_curState = QNETDEVSTATUS; + break; + case Event_OK: + if(m_curState == QNETDEVCTL && m_dial == 1) + { + m_dial = 0; + m_curState = QNETDEVSTATUS; + } + if(m_curState == Event_QCFGNET){ + m_curState = QNETDEVCTL; + } + if(m_curState == QICSGPAPN && m_APN == 1) + { + m_APN = 0; + m_curState = QNETDEVCTL; + } + + break; + case Event_ERROR: + if(m_curState == CPIN && !strcmp(pData,"3")){ + m_curState = CPIN; + GlobalConfig::NetStatus = "\"LIMSRV\""; + } + if(m_curState == QNETDEVCTL){ + m_curState = QNETDEVSTATUS; + } + break; + case Event_TEMP: + str = string(pData); + pos = str.find("soc-thermal"); + if(pos > 0){ + std::string socTmp = str.substr(pos+14,2); + GlobalConfig::NR5GTemp = socTmp; + print_info("NR5GTemp = %s\n",GlobalConfig::NR5GTemp.c_str()); + } + + + break; + default: + break; + } +} +int Dial::recvData() +{ + + char szbuffer[200]={0x00}; + int offSize = 0; + int timeoutflag = 0; + while(1) + { + char buff[1024]={0x00}; + + int ret = read_data(m_fd, buff, 1024, 10); + if(ret <= 0){ + timeoutflag ++; + if(timeoutflag > 5) + { + timeoutflag = 0; + const char *strQENG = "+QENG: "; + const char *strQNETDEVCTL = "+QNETDEVCTL: "; + const char *strQICSGP = "+QICSGP: "; + const char *strQNETDEVSTATUS= "+QNETDEVSTATUS: "; + const char *strQCFG= "+QCFG: "; + const char *strCPIN= "+CPIN: "; + const char *strERROR= "+CME ERROR: "; + const char *strQTEMP= "+QTEMP: "; + const char *strOK= "OK"; + char data[128] = {0}; + char *pdata = strstr((char*)szbuffer, strQENG); + if(pdata){ + strncpy(data, pdata+7, sizeof(data)); + print_purple("strQENG = %s\n",data); + parseData(Event_QENG,data); + } + pdata = strstr((char*)szbuffer, strQNETDEVCTL); + if(pdata){ + strncpy(data, pdata+13, sizeof(data)); + print_purple("strQNETDEVCTL = %s\n",data); + parseData(Event_QNETDEVCTL,data); + } + pdata = strstr((char*)szbuffer, strQICSGP); + if(pdata){ + strncpy(data, pdata+9, sizeof(data)); + print_purple("strQICSGP = %s\n",data); + parseData(Event_QICSGPAPN,data); + } + pdata = strstr((char*)szbuffer, strQNETDEVSTATUS); + if(pdata){ + strncpy(data, pdata+16, sizeof(data)); + print_purple("strQNETDEVSTATUS = %s\n",data); + parseData(Event_QNETDEVSTATUS,data); + } + pdata = strstr((char*)szbuffer, strQCFG); + if(pdata){ + strncpy(data, pdata+7, sizeof(data)); + print_purple("strQCFG = %s\n",data); + parseData(Event_QCFGNET,data); + } + pdata = strstr((char*)szbuffer, strCPIN); + if(pdata){ + strncpy(data, pdata+7, sizeof(data)); + print_purple("strCPIN = %s\n",data); + parseData(Event_CPIN,data); + } + pdata = strstr((char*)szbuffer, strQTEMP); + if(pdata){ + strncpy(data, pdata+8, sizeof(data)); + print_purple("strQTEMP = %s\n",data); + parseData(Event_TEMP,data); + } + pdata = strstr((char*)szbuffer, strERROR); + if(pdata){ + strncpy(data, pdata+12, sizeof(data)); + print_purple("strERROR = %s\n",data); + parseData(Event_ERROR,data); + } + pdata = strstr((char*)szbuffer, strOK); + if(pdata){ + parseData(Event_OK,data); + } + memset(szbuffer,0x00,sizeof(szbuffer)); + offSize = 0; + } + mssleep(100); + }else if(ret > 0){ + print_info("ret = %d,buff = %s\n",ret,buff); + memcpy(szbuffer + offSize,buff,ret); + offSize = offSize + ret; + print_info("szbuffer = %s\n",szbuffer); + continue; + } + mssleep(500000); + } +} +int Dial::queryPin() +{ + int iRet = write_data(m_fd,"AT+CPIN?\r\n",12); +} +int Dial::configNet() +{ + write_data(m_fd,"AT+QCFG=\"NAT\"\r\n",19); +} +int Dial::configApn() +{ + m_APN = 1; + std::string strAPN = ReadStrByOpt(SERVERCONFIG, "Server", "APN"); + char szCmd[100]={0x00}; + sprintf(szCmd,"AT+QICSGP=1,1,\"%s\",\"\",\"\",1\r\n",strAPN.c_str()); + int iRet = write_data(m_fd,szCmd,strlen(strAPN.c_str()) + 34); + print_info("configApn = %d,data = %s\n",iRet,szCmd); +} +int Dial::getCsq() +{ + write_data(m_fd,"AT+QENG=\"servingcell\"\r\n",27); +} +int Dial::getTemp() +{ + write_data(m_fd,"AT+QTEMP\r\n",12); +} +int Dial::conncectUSB() +{ + int iRet = write_data(m_fd,"AT+QNETDEVCTL=1,1,1\r\n",23); + print_info("conncectUSB = %d\n",iRet); +} +int Dial::dial5G() +{ + while(1){ + + if(m_curState == CPIN){ + queryPin(); + } + if(m_curState == QCFGNET){ + configNet(); + //configims(); + } + if(m_curState == QICSGPAPN){ + configApn(); + } + if(m_curState == QENG){ + getCsq(); + + } + if(m_curState == QNETDEVCTL){ + conncectUSB(); + m_dial = 1; + } + if(m_curState == QNETDEVSTATUS){ + write_data(m_fd,"AT+QNETDEVSTATUS=1\r\n",22); + } + if(m_curState == QDCHPC){ + configdhcp(); + m_curState = QENG; + } + sleep(5); + getTemp(); + sleep(15); + } +} +int Dial::configims() +{ + write_data(m_fd,"AT+QCFG=\"ims\",0\r\n",21); +} +int Dial::configdhcp() +{ + system("busybox udhcpc -f -n -q -t 5 -i usb0"); +} +int Dial::setState() +{ + m_curState = CPIN; +} +int Dial::closePort() +{ + close(m_fd); +} diff --git a/dial5G/Dial.h b/dial5G/Dial.h new file mode 100644 index 0000000..e4b18cd --- /dev/null +++ b/dial5G/Dial.h @@ -0,0 +1,70 @@ +/* + * Dial.h + * + * Created on: 2023年6月13日 + * Author: chaos + */ + +#ifndef DIAL5G_DIAL_H_ +#define DIAL5G_DIAL_H_ +#include +#include "../common/SH_global.h" +using namespace std; +class Dial { +public: + Dial(); + virtual ~Dial(); + + //枚举所有状态 + enum State + { + CPIN = 0, + QCFGNET, + QICSGPAPN, + QCFGSMS, + QENG, + QNETDEVCTL, + QNETDEVSTATUS, + QDCHPC, + NORMAL + }; + + //枚举所有事件 + enum Event + { + Event_CPIN = 0, + Event_QCFGNET, + Event_QICSGPAPN, + Event_QCFGSMS, + Event_QENG, + Event_QNETDEVCTL, + Event_QNETDEVSTATUS, + Event_OK, + Event_ERROR, + Event_TEMP + }; + + State m_curState; + int m_fd; + int m_dial; + int m_APN; + int openPort(const char* pPort); + int closePort(); + int recvData(); + int queryPin(); + int configNet(); + int configApn(); + int getCsq(); + int getTemp(); + int conncectUSB(); + int dial5G(); + int configims(); + int configdhcp(); + int parseData(Event event,const char* pData); + int setState(); + + + +}; + +#endif /* DIAL5G_DIAL_H_ */ diff --git a/dial5G/subdir.mk b/dial5G/subdir.mk new file mode 100644 index 0000000..0a51972 --- /dev/null +++ b/dial5G/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../dial5G/Dial.cpp + +CPP_DEPS += \ +./dial5G/Dial.d + +OBJS += \ +./dial5G/Dial.o + + +# Each subdirectory must supply rules for building sources it contributes +dial5G/%.o: ../dial5G/%.cpp dial5G/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-dial5G + +clean-dial5G: + -$(RM) ./dial5G/Dial.d ./dial5G/Dial.o + +.PHONY: clean-dial5G + diff --git a/jsonparse/SH_JsonCmd.cpp b/jsonparse/SH_JsonCmd.cpp new file mode 100644 index 0000000..85bd59e --- /dev/null +++ b/jsonparse/SH_JsonCmd.cpp @@ -0,0 +1,2828 @@ +#include "SH_JsonCmd.hpp" +#include "../dbaccess/SH_SqlDB.hpp" +#include "../platform/SH_PlatformInit.hpp" +#include "../MD5/md5.h" + +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; + + string strwebVersion = ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion"); + string strsystemVersion = ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion"); + string strGatewayVersion = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayVersion"); + + jsSystemInfo["WebVersion"] = strwebVersion; + jsSystemInfo["SystemVersion"] = strsystemVersion; + jsSystemInfo["GateWayVersion"] = strGatewayVersion; + + 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; + jsSystemInfo[JSON_FIELD_SERVERIP] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress"); + jsSystemInfo[JSON_FIELD_SERVERPORT] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str()); + jsSystemInfo[JSON_FIELD_CommMode] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "CommMode").c_str()); + 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); + WriteStr2Config(SERVERCONFIG, "Server", "Password", param.mPassword); + WriteStr2Config(SERVERCONFIG, "Server", "UserName", param.mUserName); + print_info("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"); + system("mv /etc/init.d/S95check5G /etc/init.d/wireless5G"); + }else if("2" == param.mCommMode){//无线连接 4G + system("mv /etc/init.d/wireless4G /etc/init.d/S91check4G"); + system("mv /etc/init.d/S95check5G /etc/init.d/wireless5G"); + }else if("3" == param.mCommMode){//无线连接 5G + system("mv /etc/init.d/wireless5G /etc/init.d/S95check5G"); + system("mv /etc/init.d/S91check4G /etc/init.d/wireless4G"); + } + 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; + + Json::Value jsHeart; + Json::FastWriter fw; + jsHeart["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsHeart["status"] = "online_V3.0"; + std::string strJson = fw.write(jsHeart); + int iRet = data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubHeart.c_str()); + if(iRet == 0){ + jsBody["status"] = 0; + }else{ + jsBody["status"] = -1; + } + + jsBody[JSON_FIELD_SERVERIP] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress"); + jsBody[JSON_FIELD_SERVERPORT] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str()); + jsBody[JSON_FIELD_CommMode] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "CommMode").c_str()); + jsBody["Password"] = (ReadStrByOpt(SERVERCONFIG, "Server", "Password")); + jsBody["UserName"] = (ReadStrByOpt(SERVERCONFIG, "Server", "UserName")); + 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"] = " "; + jsonVal["cmd"] = "25"; + bool bFlag1 = CheckIP(param.mGateway.c_str()); + bool bFlag2 = IsValidMask(param.mSubnetMask); + bool bFlag3 = CheckIP(param.mIp.c_str()); + bool bFlag4 = false; + if(param.mDnsName.size()>0){ + bFlag4 = CheckIP(param.mDnsName.c_str()); + }else{ + bFlag4 = true; + } + print_info("bFlag1 = %d,bFlag2 = %d,bFlag3 = %d,bFlag4 = %d\n",bFlag1,bFlag2,bFlag3,bFlag4); +#ifdef IMX6UL_GATEWAY + param.mNet = "Net"; +#endif + if (0 == param.mMode &&(bFlag1 && bFlag2 && bFlag3 && bFlag4) && param.mNetworkPortStatus == "STATIC") { + WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", param.mDnsName); + WriteStr2Config(NETWORKCONFIG, param.mNet, "networkPortStatus", param.mNetworkPortStatus); + WriteStr2Config(NETWORKCONFIG, param.mNet, "gateway", param.mGateway); + WriteStr2Config(NETWORKCONFIG, param.mNet, "subnetMask", param.mSubnetMask); + WriteStr2Config(NETWORKCONFIG, param.mNet, "ipAddress", param.mIp); + WriteStr2Config(NETWORKCONFIG, param.mNet, "hostName", param.mHostName); + +#ifdef IMX6UL_GATEWAY + char GateWay[100]={0x00}; + sprintf(GateWay,"sed -i '7c route add default gw %s' /etc/init.d/S90start_userapp.sh",param.mGateway.c_str()); + print_info("GateWay = %s\n",GateWay); + system(GateWay); +#endif + platform->EquipIpInit(param.mNet); + + }else if(0 == param.mMode && param.mNetworkPortStatus == "DHCP"){ + WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", ""); + WriteStr2Config(NETWORKCONFIG, param.mNet, "networkPortStatus", param.mNetworkPortStatus); + WriteStr2Config(NETWORKCONFIG, param.mNet, "gateway", ""); + WriteStr2Config(NETWORKCONFIG, param.mNet, "subnetMask", ""); + WriteStr2Config(NETWORKCONFIG, param.mNet, "ipAddress", ""); + WriteStr2Config(NETWORKCONFIG, param.mNet, "hostName", ""); + +#ifdef IMX6UL_GATEWAY + system("sed -i '7c udhcpc -i eth0 > /dev/null &' /etc/init.d/S90start_userapp.sh"); +#endif + platform->EquipIpInit(param.mNet); + + }else if(0 == param.mMode &&(!bFlag1 || !bFlag2 || !bFlag3 || !bFlag4) && param.mNetworkPortStatus == "STATIC"){ + jsonVal["success"] = false; + } + + jsonVal["content"]["dnsName"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "dnsName"); + jsonVal["content"]["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "networkPortStatus"); + jsonVal["content"]["gateway"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "gateway"); + jsonVal["content"]["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "subnetMask"); + jsonVal["content"]["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "ipAddress"); + jsonVal["content"]["hostName"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "hostName"); + 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][44]; + jsSensorData["dataNodeName"] = arrRes[j][1]; + jsSensorData["initFlag"] = atoi(arrRes[j][2].c_str()); + jsSensorData["accFlag"] = atoi(arrRes[j][3].c_str()); + jsSensorData["zigbeeFlag"] = atoi(arrRes[j][4].c_str()); + jsSensorData["temTopFlag"] = atoi(arrRes[j][5].c_str()); + jsSensorData["temBotFlag"] = atoi(arrRes[j][6].c_str()); + jsSensorData["equipsta"] = atoi(arrRes[j][7].c_str()); + 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["WakeupTime"] = atoi(arrRes[j][13].c_str()); + jsSensorData["StaticTime"] = atoi(arrRes[j][14].c_str()); + jsSensorData["WaveTime"] = atoi(arrRes[j][15].c_str()); + jsSensorData["BateryV"] = arrRes[j][16]; + jsSensorData["ProductNo"] = arrRes[j][17]; + jsSensorData["configFlag"] = atoi(arrRes[j][18].c_str()); + jsSensorData["startBrands"] = arrRes[j][19]; + jsSensorData["stopBrands"] = arrRes[j][20]; + jsSensorData["featureInterVal"] = (arrRes[j][21]); + jsSensorData["waveInterVal"] = atoi(arrRes[j][22].c_str()); + jsSensorData["samplingRate"] = atoi(arrRes[j][23].c_str()); + // jsSensorData["scope"] = atoi(arrRes[j][24]); + jsSensorData["range"] = atoi(arrRes[j][25].c_str()); + jsSensorData["envelopeBandPass"] = arrRes[j][26]; + jsSensorData["faultFrequency"] = arrRes[j][27]; + jsSensorData["zigbeePanId"] = arrRes[j][28]; + jsSensorData["zigbeeChannel"] = (arrRes[j][29]); + jsSensorData["zigbeeAddr"] = arrRes[j][30]; + jsSensorData["zigbeeLongAddr"] = arrRes[j][31]; + jsSensorData["zigbeeDesAddr"] = arrRes[j][32]; + jsSensorData["ZigbeePower"] = atoi(arrRes[j][33].c_str()); + jsSensorData["ZigbeeRetry"] = atoi(arrRes[j][34].c_str()); + jsSensorData["ZigbeeRetryGap"] = atoi(arrRes[j][35].c_str()); + jsSensorData["ACCSampleTime"] = atoi(arrRes[j][36].c_str()); + jsSensorData["status"] = atoi(arrRes[j][37].c_str()); + jsSensorData["timeStamp"] = arrRes[j][38]; + jsSensorData["viff"] = atoi(arrRes[j][39].c_str()); + jsSensorData["RSSI"] = arrRes[j][40]; + jsSensorData["Update"] = atoi(arrRes[j][41].c_str()); + jsSensorData["looseValue"] = arrRes[j][42]; + jsSensorData["battery"] = arrRes[j][43]; + jsSensorData["MeasurementID"] = arrRes[j][44]; + jsSensorData["nodeWaveSend"] = arrRes[j][45]; + 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'", "MeasurementID", 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); + sql_ctl->DeleteTableData(T_DATANODE_TIME(TNAME), whereCon); + } + } else { + jsonVal["success"] = false; + jsonVal["message"] = "没有传感器号"; + } + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_50(Json::Value & recvBody) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = ""; + jsonVal["cmd"] = "50"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + + std::string updateDevice = recvBody["updateDevice"].asString();//1 DataNode 2 GateWay + std::string updateURL = recvBody["updateURL"].asString(); + std::string updateName = recvBody["updateName"].asString(); + std::string md5 = recvBody["MD5"].asString(); + std::string strResponse; + updateName = "/opt/" + updateName; + if (access(updateName.c_str(), 0) == 0){ + char cmd[100]={0x00}; + sprintf(cmd,"rm -rf %s",updateName.c_str()); + system(cmd); + } + sleep(2); +// int iRet = pDataTrans->download( (char*)updateName.c_str(),updateURL, strResponse, bDownload); + int iRet = pDataTrans->dl_curl_post_req( updateURL,"",updateName); + if(iRet != 0){ + jsonVal["success"] = false; + jsonVal["message"] = "download failed"; + return showValue.write(jsonVal); + } + string md5Val = md5file(updateName.c_str()); + printf("md5Val = %s\n",md5Val.c_str()); + printf("md5 = %s\n",md5.c_str()); + if(md5 != md5Val){ + jsonVal["success"] = false; + jsonVal["message"] = "download file check failed"; + return showValue.write(jsonVal); + } + if(updateDevice == "1"){ + string strcmd = "tar xvf "; + strcmd = strcmd + updateName; + strcmd = strcmd + " -C /opt/"; + system(strcmd.c_str()); + }else if (updateDevice == "2"){ + /* string strcmd = "tar xvf "; + strcmd = strcmd + updateName; + strcmd = strcmd + " -C /opt/update/"; + system(strcmd.c_str());*/ + sleep(3); + system("/opt/opt.sh"); + } + return showValue.write(jsonVal); +} +std::string JsonData::JsonCmd_51(Json::Value & recvBody) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = ""; + jsonVal["cmd"] = "51"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + std::string DataNodeNo = recvBody["dataNodeNo"].asString(); + std::string DataNodeName = recvBody["dataNodeName"].asString(); + char szSql[100]={0x00}; + sprintf(szSql,"update %s set dataNodeName = '%s' where MeasurementID = '%s' ",T_SENSOR_INFO(TNAME),\ + DataNodeName.c_str(),DataNodeNo.c_str()); + int iRet = sql_ctl->UpdateTableData(szSql); + if(iRet != 0){ + jsonVal["success"] = false; + jsonVal["message"] = "updata dataNodeName failed"; + } + return showValue.write(jsonVal); +} +std::string JsonData::JsonCmd_52() +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = ""; + char whereCon[512] = {}; + std::string strTimeStamp = ""; + char selectCon[128] = { 0 }; + memcpy(selectCon,"sendMsg = '0'",sizeof(selectCon)); + int count = sql_ctl->GetTableRows(T_DATASTATIC_INFO(TNAME), selectCon); + if(count < 1){ + return ""; + } + for(int i = 0 ; i < count ;i++) + { + Json::Value jsSensor; + std::string strDataNodeNo = ""; + jsonVal.clear(); + jsonVal["cmd"] = "52"; + memcpy(whereCon, "sendMsg = '0' ORDER BY timeStamp DESC LIMIT 0,3",sizeof(whereCon)); + // 自数据库获取传感器特征数据 + 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; + strDataNodeNo = arrRes[j][0]; + jsChannelData["ChannelId"] = arrRes[j][1]; + jsChannelData["ChannelType"] = "ACCELEROMETER"; + jsChannelData["DiagnosisPeak"] = atof(arrRes[j][2].c_str()); + jsChannelData["IntegratPk2Pk/2"] = atof(arrRes[j][3].c_str()); + jsChannelData["IntegratRMS"] = atof(arrRes[j][4].c_str()); + jsChannelData["RMSValues"] = atof(arrRes[j][5].c_str()); + jsChannelData["EnvelopEnergy"] = atof(arrRes[j][6].c_str()); + jsChannelData["1xAmp"] = atof(arrRes[j][7].c_str()); + jsChannelData["2xAmp"] = atof(arrRes[j][8].c_str()); + jsChannelData["3xAmp"] = atof(arrRes[j][9].c_str()); + jsChannelData["4xAmp"] = atof(arrRes[j][10].c_str()); + jsChannelData["5xAmp"] = atof(arrRes[j][11].c_str()); + jsChannelData["1xPhase"] = atof(arrRes[j][12].c_str()); + jsChannelData["2xPhase"] = atof(arrRes[j][13].c_str()); + jsChannelData["3xPhase"] = atof(arrRes[j][14].c_str()); + jsChannelData["4xPhase"] = atof(arrRes[j][15].c_str()); + jsChannelData["TimeStamp"] = atof(arrRes[j][17].c_str()); + strTimeStamp = std::string(arrRes[j][16]); + jsSensor.append(jsChannelData); + } + } + + memset(selectCon,0x00,sizeof(selectCon)); + sprintf(selectCon, "dataNodeNo='%s' and sendMsg = '0' ORDER BY timeStamp DESC LIMIT 0,1", strDataNodeNo.c_str()); + vec_t vecRes = sql_ctl->GetDataSingleLine(T_DATASTATIC_INFO(TNAME), "*", selectCon); + Json::Value jsStaticData; + if(vecRes.size()>0){ + jsStaticData["TemperatureTop"] = atof(vecRes[2].c_str()); + jsStaticData["TemperatureBot"] = atof(vecRes[3].c_str()); + jsStaticData["Dip"] = atof(vecRes[4].c_str()); + jsStaticData["Voltage"] = atof(vecRes[5].c_str()); + jsStaticData["ChannelType"] = "STATUS"; + jsStaticData["ChannelId"] = vecRes[1]; + jsStaticData["TimeStamp"] = vecRes[7]; + jsStaticData["dataNodeNo"] = strDataNodeNo; + } + + jsSensor.append(jsStaticData); + + jsonVal["content"].append(jsSensor); + std::string data = showValue.write(jsonVal); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon,"sendMsg = '0' and timeStamp = '%s'",strTimeStamp.c_str()); + int iRet = data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + if(iRet == 0){ + sql_ctl->DeleteTableData(T_DATA_INFO(TNAME),whereCon,0); + sql_ctl->DeleteTableData(T_DATASTATIC_INFO(TNAME),whereCon,0); + } + mssleep(100); + } + return ""; +} +std::string JsonData::JsonCmd_53(Json::Value & recvBody) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = ""; + jsonVal["cmd"] = "53"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + std::string looseValue = recvBody["looseValue"].asString(); + + int iRet = writeStringVlaue("config", "loose",(char*)looseValue.c_str(),(char*)GlobalConfig::Config_G.c_str()); + if(iRet != 0){ + jsonVal["success"] = false; + jsonVal["message"] = "update failed"; + } + 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(); +// LOG_INFO("iResult = %d",iResult); + if (iResult > 0) { + for (int i = 0; i < iResult; i++) { + Json::Value jsDataNode; + jsDataNode["dataNodeNo"] = arrRes[i][0]; + jsDataNode["status"] = atoi(arrRes[i][37].c_str()); + 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) +{ + +} +void JsonData::DataNodeStatusCheck() +{ + array_t vetRes = sql_ctl->GetDataMultiLine(T_SENSOR_INFO(TNAME), "*", NULL); + int nSize = vetRes.size(); + + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + int lNowTime = atoi(nowTimetamp.c_str()); + int onlineCheck = readIntValue( "config", "online",(char*)GlobalConfig::Config_G.c_str()); + int loseTime = readIntValue( "config", "loseTime",(char*)GlobalConfig::Config_G.c_str()); + int count = 0; + if (nSize > 0) { + for (int i = 0; i < nSize; i++) { + std::string strDataNodeNo = vetRes[i][0]; + std::string strMeasurementID = vetRes[i][44]; + std::string strChannelId = strMeasurementID + "-X"; + char whereCon[512] = {0x00},tablename[128]={0x00}; + sprintf(whereCon, "dataNodeNo='%s' and channelID='%s' ORDER BY timeStamp DESC LIMIT 0,1", strDataNodeNo.c_str(), strChannelId.c_str()); + sprintf(tablename,"t_data_%s",strDataNodeNo.c_str()); + std::string strTimeRes = sql_ctl->GetData(tablename, "timeStamp", whereCon); + if (strTimeRes.length() > 0) { + int llastTime = atoi(strTimeRes.c_str()); + int lTimeTemp = lNowTime - llastTime; + lTimeTemp = abs(lTimeTemp); + if (lTimeTemp > onlineCheck){ + LOG_DEBUG("offline DataNodeStatusCheck lNowTime = %d,llastTime = %d,interval = %s\n",lNowTime,llastTime,vetRes[i][21].c_str()); + char whereCon[32] = { 0 }; + sprintf(whereCon, "dataNodeNo='%s'", strDataNodeNo.c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), "status='0'", whereCon); + } + // }else if(lTimeTemp > (loseTime * atoi(vetRes[i][21].c_str()) * 60)){ + // LOG_DEBUG("掉线 DataNodeStatusCheck lNowTime = %d,llastTime = %d,interval = %s\n",lNowTime,llastTime,vetRes[i][21].c_str()); + // char whereCon[32] = { 0 }; + // sprintf(whereCon, "dataNodeNo='%s'", strDataNodeNo.c_str()); + // sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), "status='2'", whereCon); + // } + else { + char whereCon[32] = { 0 }; + sprintf(whereCon, "dataNodeNo='%s'", strDataNodeNo.c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), "status='1'", whereCon); + } + if (lTimeTemp > atoi(vetRes[i][21].c_str()) * 5 * 60 )//判定传感器是否超过五次未传特征值 + { + LOG_DEBUG("lTimeTemp = %d,featureInterVal = %d\n",lTimeTemp,atoi(vetRes[i][21].c_str())); + count ++; + } + } + } + if (count == nSize) + { + LOG_ERROR("ALL Node offline,count = %d\n",count); + exit(0); + } + + } + +} +/***************************嵌入式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"; + if(param.mMode == 0){//本地校时 + SetTime((unsigned long)param.mTimeStamp); + mssleep(200); + system("hwclock -w"); + }else if(param.mMode == 1){//与服务器校时 + char buf[256] = {0}; + sprintf(buf, "{\"dataNodeGatewayNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}", + GlobalConfig::MacAddr_G.c_str()); + std::string str = std::string(buf); + int iRet = data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + } + } 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"] = atoi(nowTimetamp.c_str()); + } + 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_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["cmdBody"] = sysStatus; + } 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(Param_09 ¶m) +{ + //LOG_INFO("09 start\n"); + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal[JSON_FIELD_CMD] = "09"; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + char looseValue[10]={0x00}; + readStringValue("config", "loose",looseValue,(char*)GlobalConfig::Config_G.c_str()); + + array_t arrResAll = sql_ctl->GetDataMultiLine(T_SENSOR_INFO(TNAME), " dataNodeNo,MeasurementID ", NULL); + int nSize = arrResAll.size(); + if (nSize > 0) { + int packgeNo = param.mPackageFlag; + int packgeMax = 0; + int packgeNum = 0; + jsonVal["package"] = packgeNo; + int lastSize = nSize % 10; + int index = nSize / 10; + if(lastSize > 0 && index > 0){ + packgeMax = index +1; + if(packgeNo +1 == packgeMax){ + packgeNum = nSize; + jsonVal["packageMax"] = index + 1; + } + else{ + packgeNum = (packgeNo+1) * 10; + jsonVal["packageMax"] = index +1; + } + } + else if(lastSize == 0 && index > 0){ + packgeNum = (packgeNo+1) * 10; + packgeMax = index; + jsonVal["packageMax"] = index; + }else if(lastSize > 0 && index == 0){ + packgeNum = lastSize; + packgeMax = index+1; + jsonVal["packageMax"] = index+1; + } + + printf("09 packgeNo = %d,packgeNum = %d,lastSize = %d,index = %d\n",packgeNo,packgeNum,lastSize,index); + for (int i = packgeNo * 10; i < packgeNum; i++) { + print_info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@vetRes=%s\n",arrResAll[i][1].c_str()); + Json::Value jsSensor; + std::string strMeasurementID = arrResAll[i][1]; + char whereCon[512] = {}; + sprintf(whereCon, "channelID like '%%%s%%' ORDER BY timeStamp DESC LIMIT 0,3", strMeasurementID.c_str()); + // 自数据库获取传感器特征数据 + array_t arrRes; + arrRes = sql_ctl->GetDataMultiLineTransaction(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"] = atof(arrRes[j][2].c_str()); + jsChannelData["IntegratPk2Pk/2"] = atof(arrRes[j][3].c_str()); + jsChannelData["IntegratRMS"] = atof(arrRes[j][4].c_str()); + jsChannelData["RMSValues"] = atof(arrRes[j][5].c_str()); + jsChannelData["EnvelopEnergy"] = atof(arrRes[j][6].c_str()); + jsChannelData["1xAmp"] = atof(arrRes[j][7].c_str()); + jsChannelData["2xAmp"] = atof(arrRes[j][8].c_str()); + jsChannelData["3xAmp"] = atof(arrRes[j][9].c_str()); + jsChannelData["4xAmp"] = atof(arrRes[j][10].c_str()); + jsChannelData["5xAmp"] = atof(arrRes[j][11].c_str()); + jsChannelData["1xPhase"] = atof(arrRes[j][12].c_str()); + jsChannelData["2xPhase"] = atof(arrRes[j][13].c_str()); + jsChannelData["3xPhase"] = atof(arrRes[j][14].c_str()); + jsChannelData["4xPhase"] = atof(arrRes[j][15].c_str()); + jsChannelData["TimeStamp"] = atof(arrRes[j][17].c_str()); + jsSensor.append(jsChannelData); + } + } + + char selectCon[128] = { 0 }; + char column[128]={0}; + char tablename[256]={0}; + sprintf(selectCon, " t_sensor_info.MeasurementID='%s' ",strMeasurementID.c_str()); + sprintf(column," %s.*,t_sensor_info.status,t_sensor_info.LooseValue,t_sensor_info.batteryPower ",T_DATASTATIC_INFO(TNAME)); + sprintf(tablename," %s LEFT JOIN t_sensor_info \ + ON %s.channelID like '%%%s%%' ",T_DATASTATIC_INFO(TNAME),T_DATASTATIC_INFO(TNAME),strMeasurementID.c_str()); + + vec_t vecRes = sql_ctl->GetDataSingleLine(tablename,column, selectCon); + Json::Value jsStaticData; + if(vecRes.size()>0){ + jsStaticData["TemperatureTop"] = atof(vecRes[2].c_str()); + jsStaticData["TemperatureBot"] = atof(vecRes[3].c_str()); + jsStaticData["Dip"] = atof(vecRes[4].c_str()); + jsStaticData["Voltage"] = atof(vecRes[5].c_str()); + jsStaticData["ChannelType"] = "STATUS"; + jsStaticData["ChannelId"] = vecRes[1]; + jsStaticData["TimeStamp"] = vecRes[8]; + jsStaticData["battery"] = vecRes[13]; + jsStaticData["MeasurementID"] = strMeasurementID; + jsStaticData["dataNodeNo"] = arrResAll[i][0]; + jsStaticData["status"] = vecRes[11]; + jsStaticData["loose"] = "0"; + + }else{ + jsStaticData["TemperatureTop"] = ""; + jsStaticData["TemperatureBot"] = ""; + jsStaticData["Dip"] = ""; + jsStaticData["Voltage"] = ""; + jsStaticData["ChannelType"] = "STATUS"; + jsStaticData["ChannelId"] = ""; + jsStaticData["TimeStamp"] = ""; + jsStaticData["battery"] = ""; + jsStaticData["MeasurementID"] = strMeasurementID; + jsStaticData["dataNodeNo"] = arrResAll[i][0]; + jsStaticData["status"] = "0"; + jsStaticData["loose"] = "0"; + } + jsSensor.append(jsStaticData); + jsonVal["content"].append(jsSensor); + } + + } else { + jsonVal["success"] = true; + jsonVal["content"].resize(0); + } + //LOG_INFO("09 end\n"); + return showValue.write(jsonVal); +} +std::string JsonData::JsonCmd_Cgi_10(Param_10 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal[JSON_FIELD_CMD] = "10"; + 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) { + char selectCon[256] = { 0 },szTableName[100] = {0x00},whereCon[256]={0x00}; + + sprintf(selectCon, "%s,channelID,timeStamp",param.strStatic.c_str()); + + if(param.straxis == "S") + { + sprintf(szTableName,"t_dataStatic_%s",param.strDataNode.c_str()); + }else{ + sprintf(szTableName,"t_data_%s",param.strDataNode.c_str()); + } + if(param.timeEnd == ""){ + + sprintf(whereCon,"channelID like '%%%s%%' and %s <> ''",\ + param.MeasurementID.c_str(),param.strStatic.c_str()); + + }else{ + + sprintf(whereCon," channelID like '%%%s%%' and %s <> '' and timeStamp < '%s' and timeStamp > '%s' ",\ + param.MeasurementID.c_str(),param.strStatic.c_str(),param.timeEnd.c_str(),param.timeStart.c_str()); + + } + + int rows = sql_ctl->GetTableRows(szTableName,whereCon); + int packgeNo = param.mPackageFlag; + int packgeMax = 0; + int packgeNum = 0; + jsonVal["package"] = packgeNo; + int lastSize = rows % 550; + int index = rows / 550; + if(lastSize > 0 && index > 0){ + packgeMax = index +1; + if(packgeNo +1 == packgeMax){ + packgeNum = rows-lastSize; + jsonVal["packageMax"] = index + 1; + } + else{ + packgeNum = (packgeNo) * 550; + jsonVal["packageMax"] = index +1;} + } + else if(lastSize == 0 && index > 0){ + packgeNum = (packgeNo+1) * 550; + packgeMax = index; + jsonVal["packageMax"] = index; + }else if(lastSize > 0 && index == 0){ + packgeNum = 0; + packgeMax = index+1; + jsonVal["packageMax"] = index; + } + + //printf("10 packgeNo = %d,packgeNum = %d,lastSize = %d,index = %d\n",packgeNo,packgeNum,lastSize,index); + memset(whereCon,0x00,sizeof(whereCon)); + + if(param.timeEnd == ""){ + sprintf(whereCon,"channelID like '%%%s%%' and %s <> '' order by timeStamp asc LIMIT %d OFFSET %d",\ + param.MeasurementID.c_str(),param.strStatic.c_str(),550,packgeNum); + }else{ + sprintf(whereCon,"channelID like '%%%s%%' and %s <> '' and timeStamp < '%s' and timeStamp > '%s' order by timeStamp asc LIMIT %d OFFSET %d",\ + param.MeasurementID.c_str(),param.strStatic.c_str(),param.timeEnd.c_str(),param.timeStart.c_str(),550,packgeNum); + } + array_t vecRes; + + vecRes = sql_ctl->GetDataMultiLine(szTableName, selectCon,whereCon); + print_info("vecRes = %d\n",vecRes.size()); + if(vecRes.size() > 0){ + Json::Value jsStaticData; + for(int i = 0 ; i < vecRes.size(); i++){ + Json::Value iTem; + if(vecRes[i][1] == param.MeasurementID + "-X"){ + iTem.append(vecRes[i][0]); + iTem.append(vecRes[i][2]); + jsStaticData["X"].append(iTem); + }if(vecRes[i][1] == param.MeasurementID + "-Y"){ + iTem.append(vecRes[i][0]); + iTem.append(vecRes[i][2]); + jsStaticData["Y"].append(iTem); + }if(vecRes[i][1] == param.MeasurementID + "-Z"){ + iTem.append(vecRes[i][0]); + iTem.append(vecRes[i][2]); + jsStaticData["Z"].append(iTem); + } + if(vecRes[i][1] == param.MeasurementID + "-S"){ + iTem.append(vecRes[i][0]); + iTem.append(vecRes[i][2]); + jsStaticData["S"].append(iTem); + } + } + if(jsStaticData.size() == 0){ + jsonVal["success"] = false; + jsonVal["content"].resize(0); + } + else{ + jsonVal["content"] = (jsStaticData); + } + jsonVal["Static"] = param.strStatic; + print_info("vecRes = %d,channelID = %s\n",vecRes.size(),vecRes[0][0].c_str()); + }else{ + jsonVal["success"] = false; + jsonVal["content"].resize(0); + } + }else{ + jsonVal["success"] = false; + jsonVal["content"].resize(0); + } + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_11(Param_11 ¶m) +{ + Json::Value jsonVal,jsSensor; + jsonVal.clear(); + + jsonVal[JSON_FIELD_CMD] = "11"; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + char whereCon[512] = {}; + sprintf(whereCon, "dataNodeNo='%s' ORDER BY timeStamp DESC LIMIT 0,3", param.DataNodeNo.c_str()); + // 自数据库获取传感器特征数据 + array_t arrRes; + arrRes = sql_ctl->GetDataMultiLineTransaction(T_DATA_INFO(TNAME), "*", whereCon); + int iResult = arrRes.size(); + print_info("iResult = %d\n",iResult); + if (iResult > 0) { + for (int j = 0; j < iResult; j++) { + Json::Value jsChannelData; + jsChannelData["ChannelId"] = arrRes[j][1]; + jsChannelData["ChannelType"] = "ACCELEROMETER"; + jsChannelData["DiagnosisPeak"] = atof(arrRes[j][2].c_str()); + jsChannelData["IntegratPk2Pk/2"] = atof(arrRes[j][3].c_str()); + jsChannelData["IntegratRMS"] = atof(arrRes[j][4].c_str()); + jsChannelData["RMSValues"] = atof(arrRes[j][5].c_str()); + jsChannelData["EnvelopEnergy"] = atof(arrRes[j][6].c_str()); + jsChannelData["1xAmp"] = atof(arrRes[j][7].c_str()); + jsChannelData["2xAmp"] = atof(arrRes[j][8].c_str()); + jsChannelData["3xAmp"] = atof(arrRes[j][9].c_str()); + jsChannelData["4xAmp"] = atof(arrRes[j][10].c_str()); + jsChannelData["5xAmp"] = atof(arrRes[j][11].c_str()); + jsChannelData["1xPhase"] = atof(arrRes[j][12].c_str()); + jsChannelData["2xPhase"] = atof(arrRes[j][13].c_str()); + jsChannelData["3xPhase"] = atof(arrRes[j][14].c_str()); + jsChannelData["4xPhase"] = atof(arrRes[j][15].c_str()); + jsChannelData["TimeStamp"] = atof(arrRes[j][17].c_str()); + jsSensor.append(jsChannelData); + } + }else { + jsonVal["success"] = false; + jsonVal["content"].resize(0); + } + jsonVal["content"] = jsSensor; + 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; + jsSystemInfo["GateWayVersion"] = GlobalConfig::Version; + jsSystemInfo["SystemVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion"); + jsSystemInfo["WebVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion"); + jsSystemInfo["GateWayHwVesion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayHwVesion"); + jsSystemInfo["GateWayProduct"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayProduct"); + jsSystemInfo["serverStatus"] = GlobalConfig::serverStatus ; + + if(GlobalConfig::NetType == "\"NR5G-SA\"" || GlobalConfig::NetType == "\"NR5G-NSA\"" || + GlobalConfig::NetType == "\"NR5G\""){ + GlobalConfig::NetType = "5G"; + }else if(GlobalConfig::NetType == "\"LTE\""){ + GlobalConfig::NetType = "4G"; + } + if(GlobalConfig::NetStatus == "\"NOCONN\"" || GlobalConfig::NetStatus == "\"CONNECT\""){ + + if(GlobalConfig::NetSignal == 0){ + jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",未知"; + } + else if(GlobalConfig::NetSignal > -80){ + jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",优"; + }else if(GlobalConfig::NetSignal > -90 && GlobalConfig::NetSignal < -80){ + jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",良"; + }else if(GlobalConfig::NetSignal > -105 && GlobalConfig::NetSignal < -90){ + jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",一般"; + }else if(GlobalConfig::NetSignal < -105){ + jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",弱"; + }else if(GlobalConfig::NetSignal < -115){ + jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",不稳定"; + } + + }else if(GlobalConfig::NetStatus == "\"SEARCH\""){ + jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",搜索网络"; + }else if(GlobalConfig::NetStatus == "\"LIMSRV\""){ + jsSystemInfo["communicationSignal"] = GlobalConfig::NetType + ",未插卡"; + }else{ + jsSystemInfo["communicationSignal"] = "未知"; + } + + + 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(); + jsonVal[JSON_FIELD_CMD] = "23"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["cmdSerial"] = param.mCmdSerial; + jsonVal["success"] = true; + jsonVal["message"] = " "; + // SET 指令,则param.mMode = 0,将设置的数据写入配置文件中 SERVERCONFIG "/opt/configenv/ServerConfig.json" + + if (0 == param.mMode && CheckIP(param.mServerIp.c_str())) { + + WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", param.mServerIp); + WriteStr2Config(SERVERCONFIG, "Server", "localServerPort", param.mPort); + WriteStr2Config(SERVERCONFIG, "Server", "CommMode", /*param.mCommMode*/"2"); + WriteStr2Config(SERVERCONFIG, "Server", "UserName", param.mUserName); + WriteStr2Config(SERVERCONFIG, "Server", "Password", param.mPassword); + WriteStr2Config(SERVERCONFIG, "Server", "APN", param.mAPN); + char APN[100]={0x00}; + sprintf(APN,"sed -i '15c \t\t\t\t/opt/quectel-CM/quectel-CM -s %s > /dev/null &' /etc/init.d/S95check5G",param.mAPN.c_str()); + system(APN); + system("reboot"); + }else if(0 == param.mMode && !(CheckIP(param.mServerIp.c_str()))){ + jsonVal["success"] = false; + } + + Json::Value jsSystemSetting; + Json::Value jsBody; + + jsSystemSetting["ServerIpAddress"] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress"); + jsSystemSetting["ServerPort"] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str()); + jsSystemSetting["CommMode"] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "CommMode").c_str()); + jsSystemSetting["ServerStatus"] = 1; + jsSystemSetting["UserName"] = ReadStrByOpt(SERVERCONFIG, "Server", "UserName"); + jsSystemSetting["Password"] = ReadStrByOpt(SERVERCONFIG, "Server", "Password"); + jsSystemSetting["APN"] = ReadStrByOpt(SERVERCONFIG, "Server", "APN"); + jsBody["SystemSettings"] = jsSystemSetting; + jsonVal["content"] = jsBody; + + + return showValue.write(jsonVal); +} + + + + +std::string JsonData::JsonCmd_Cgi_25(Param_25 ¶m) +{ + Json::Value jsonVal; + Json::Value jsonValnet; + jsonVal.clear(); + jsonVal["success"] = true; + jsonVal["message"] = " "; + jsonVal["cmd"] = "25"; + string strNet = ""; + bool bFlag1 = CheckIP(param.mGateway.c_str()); + bool bFlag2 = IsValidMask(param.mSubnetMask); + bool bFlag3 = CheckIP(param.mIp.c_str()); + bool bFlag4 = false; + if(param.mDnsName.size()>0){ + bFlag4 = CheckIP(param.mDnsName.c_str()); + }else{ + bFlag4 = true; + } + print_info("bFlag1 = %d,bFlag2 = %d,bFlag3 = %d,bFlag4 = %d\n",bFlag1,bFlag2,bFlag3,bFlag4); +#ifdef IMX6UL_GATEWAY + strNet = param.mNet; + param.mNet = "Net"; +#endif + if (0 == param.mMode &&(bFlag1 && bFlag2 && bFlag3 && bFlag4) && param.mNetworkPortStatus == "STATIC") { + WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", param.mDnsName); + WriteStr2Config(NETWORKCONFIG, param.mNet, "networkPortStatus", param.mNetworkPortStatus); + WriteStr2Config(NETWORKCONFIG, param.mNet, "gateway", param.mGateway); + WriteStr2Config(NETWORKCONFIG, param.mNet, "subnetMask", param.mSubnetMask); + WriteStr2Config(NETWORKCONFIG, param.mNet, "ipAddress", param.mIp); + WriteStr2Config(NETWORKCONFIG, param.mNet, "hostName", param.mHostName); + +#ifdef IMX6UL_GATEWAY + char GateWay[100]={0x00}; + sprintf(GateWay,"sed -i '7c route add default gw %s' /etc/init.d/S90start_userapp.sh",param.mGateway.c_str()); + print_info("GateWay = %s\n",GateWay); + system(GateWay); +#endif + platform->EquipIpInit(param.mNet); + + }else if(0 == param.mMode && param.mNetworkPortStatus == "DHCP"){ + WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", ""); + WriteStr2Config(NETWORKCONFIG, param.mNet, "networkPortStatus", param.mNetworkPortStatus); + WriteStr2Config(NETWORKCONFIG, param.mNet, "gateway", ""); + WriteStr2Config(NETWORKCONFIG, param.mNet, "subnetMask", ""); + WriteStr2Config(NETWORKCONFIG, param.mNet, "ipAddress", ""); + WriteStr2Config(NETWORKCONFIG, param.mNet, "hostName", ""); + +#ifdef IMX6UL_GATEWAY + system("sed -i '7c udhcpc -i eth0 > /dev/null &' /etc/init.d/S90start_userapp.sh"); +#endif + platform->EquipIpInit(param.mNet); + + }else if(0 == param.mMode &&(!bFlag1 || !bFlag2 || !bFlag3 || !bFlag4) && param.mNetworkPortStatus == "STATIC"){ + jsonVal["success"] = false; + } + + jsonValnet["dnsName"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "dnsName"); + jsonValnet["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "networkPortStatus"); + jsonValnet["gateway"] = ReadStrByOpt(NETWORKCONFIG, param.mNet ,"gateway"); + jsonValnet["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "subnetMask"); + jsonValnet["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "ipAddress"); + jsonValnet["hostName"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "hostName"); + jsonVal["content"]["eth0"] = jsonValnet; + jsonVal["content"]["gatewaytype"] = 0; + +#ifdef G2UL_GATEWAY + jsonValnet["dnsName"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "dnsName"); + jsonValnet["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "networkPortStatus"); + jsonValnet["gateway"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "gateway"); + jsonValnet["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "subnetMask"); + jsonValnet["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "ipAddress"); + jsonValnet["hostName"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "hostName"); + jsonVal["content"]["eth1"] =jsonValnet; + jsonVal["content"]["gatewaytype"] = 1; +#endif + return showValue.write(jsonVal); +} + + +std::string JsonData::JsonCmd_Cgi_26(Param_26 ¶m) +{ + //LOG_INFO("26 start\n"); + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["cmd"] = "26"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + char looseValue[10]={0x00}; + readStringValue("config", "loose",looseValue,(char*)GlobalConfig::Config_G.c_str()); + //print_debug("loose = %f \n",atof(looseValue)); + Json::Value jsArray; + array_t arrRes; + arrRes = sql_ctl->GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", NULL); + int iResult = arrRes.size(); + if (iResult > 0) { + int packgeNo = param.mPackageFlag; + int packgeMax = 0; + int packgeNum = 0; + jsonVal["package"] = packgeNo; + int lastSize = iResult % 10; + int index = iResult / 10; + if(lastSize > 0 && index > 0){ + packgeMax = index +1; + if(packgeNo +1 == packgeMax){ + packgeNum = iResult; + jsonVal["packageMax"] = index + 1; + } + else{ + packgeNum = (packgeNo+1) * 10; + jsonVal["packageMax"] = index +1;} + } + else if(lastSize == 0 && index > 0){ + packgeNum = (packgeNo+1) * 10; + packgeMax = index; + jsonVal["packageMax"] = index; + }else if(lastSize > 0 && index == 0){ + packgeNum = lastSize; + packgeMax = index+1; + jsonVal["packageMax"] = index; + } + + printf("26 packgeNo = %d,packgeNum = %d,lastSize = %d,index = %d\n",packgeNo,packgeNum,lastSize,index); + for (int j = packgeNo * 10; j < packgeNum; j++) { + Json::Value jsSensorData; + jsSensorData["dataNodeNo"] = arrRes[j][0]; + jsSensorData["dataNodeName"] = arrRes[j][1]; + jsSensorData["initFlag"] = atoi(arrRes[j][2].c_str()); + jsSensorData["accFlag"] = atoi(arrRes[j][3].c_str()); + jsSensorData["zigbeeFlag"] = atoi(arrRes[j][4].c_str()); + jsSensorData["temTopFlag"] = atoi(arrRes[j][5].c_str()); + jsSensorData["temBotFlag"] = atoi(arrRes[j][6].c_str()); + 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["WakeupTime"] = atoi(arrRes[j][13].c_str()); + jsSensorData["StaticTime"] = atoi(arrRes[j][14].c_str()); + jsSensorData["WaveTime"] = atoi(arrRes[j][15].c_str()); + jsSensorData["BateryV"] = arrRes[j][16]; + jsSensorData["ProductNo"] = arrRes[j][17]; + jsSensorData["configFlag"] = atoi(arrRes[j][18].c_str()); + jsSensorData["startBrands"] = arrRes[j][19]; + jsSensorData["stopBrands"] = arrRes[j][20]; + jsSensorData["featureInterVal"] = atoi(arrRes[j][21].c_str()); + jsSensorData["waveInterVal"] = atoi(arrRes[j][22].c_str()); + jsSensorData["samplingRate"] = atoi(arrRes[j][23].c_str()); + // jsSensorData["scope"] = atoi(arrRes[j][24]); + jsSensorData["range"] = atoi(arrRes[j][25].c_str()); + jsSensorData["envelopeBandPass"] = arrRes[j][26]; + jsSensorData["faultFrequency"] = arrRes[j][27]; + jsSensorData["zigbeePanId"] = arrRes[j][28]; + jsSensorData["zigbeeChannel"] = (arrRes[j][29]); + jsSensorData["zigbeeAddr"] = arrRes[j][30]; + jsSensorData["zigbeeLongAddr"] = arrRes[j][31]; + jsSensorData["zigbeeDesAddr"] = arrRes[j][32]; + jsSensorData["ZigbeePower"] = atoi(arrRes[j][33].c_str()); + jsSensorData["ZigbeeRetry"] = atoi(arrRes[j][34].c_str()); + jsSensorData["ZigbeeRetryGap"] = atoi(arrRes[j][35].c_str()); + jsSensorData["ACCSampleTime"] = atoi(arrRes[j][36].c_str()); + jsSensorData["status"] = atoi(arrRes[j][37].c_str()); + jsSensorData["timeStamp"] = arrRes[j][38]; + jsSensorData["viff"] = atoi(arrRes[j][39].c_str()); + vector vParam; + + print_info("loose = %s\n",arrRes[j][42].c_str()); + boost::split( vParam, arrRes[j][42], boost::is_any_of( "," ), boost::token_compress_on ); + + if(vParam.size() > 1) + jsSensorData["loose"] = vParam[1]; + else + jsSensorData["loose"] = "0"; + + vector vParamRSSI; + boost::split( vParamRSSI, arrRes[j][40], boost::is_any_of( "," ), boost::token_compress_on ); + if(vParamRSSI.size() > 1){ + jsSensorData["RSSI"] = arrRes[j][40]; + }else{ + jsSensorData["RSSI"] = "0," + arrRes[j][40]; + } + + jsSensorData["update"] = atoi(arrRes[j][41].c_str()); + jsSensorData["MeasurementID"] = arrRes[j][44]; + jsSensorData["battery"] = arrRes[j][43]; + jsSensorData["nodeWaveSend"] = arrRes[j][45]; + jsArray.append(jsSensorData); + } + } else { + jsArray.resize(0); + jsonVal["success"] = true; + } + //LOG_INFO("26 end\n"); + jsonVal["gatewayMac"] = GlobalConfig::MacAddr_G ; + jsonVal["gatewayIP"] = GlobalConfig::IpAddr_G ; + jsonVal["content"]["dataNodeArray"] = jsArray; + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_54(Param_54 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["cmd"] = "54"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + Json::Value jsArray,nodeArray,gatewayArray; + array_t arrRes; + arrRes = sql_ctl->GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", NULL); + int iResult = arrRes.size(); + if (iResult > 0) { + int packgeNo = param.mPackageFlag; + int packgeMax = 0; + int packgeNum = 0; + jsonVal["package"] = packgeNo; + int lastSize = iResult % 10; + int index = iResult / 10; + if(lastSize > 0 && index > 0){ + packgeMax = index +1; + if(packgeNo +1 == packgeMax){ + packgeNum = iResult; + jsonVal["packageMax"] = index + 1; + } + else{ + packgeNum = (packgeNo+1) * 10; + jsonVal["packageMax"] = index +1;} + } + else if(lastSize == 0 && index > 0){ + packgeNum = (packgeNo+1) * 10; + packgeMax = index; + jsonVal["packageMax"] = index; + }else if(lastSize > 0 && index == 0){ + packgeNum = lastSize; + packgeMax = index+1; + jsonVal["packageMax"] = index; + } + + for (int j = packgeNo * 10; j < packgeNum; j++) { + Json::Value nodeArray; + char hex[100]; + nodeArray.append(arrRes[j][0]); + stringToHex(arrRes[j][1].c_str(),hex); + print_info("hex = %s\n",hex); + nodeArray.append(hex); + nodeArray.append(arrRes[j][2]); + nodeArray.append(arrRes[j][3]); + nodeArray.append(arrRes[j][4]); + nodeArray.append(arrRes[j][5]); + nodeArray.append(arrRes[j][6]); + nodeArray.append(arrRes[j][7]); + nodeArray.append(arrRes[j][8]); + nodeArray.append(arrRes[j][9]); + nodeArray.append(arrRes[j][10]); + nodeArray.append(arrRes[j][11]); + nodeArray.append(arrRes[j][12]); + nodeArray.append(arrRes[j][13]); + nodeArray.append(arrRes[j][14]); + nodeArray.append(arrRes[j][15]); + nodeArray.append(arrRes[j][16]); + nodeArray.append(arrRes[j][17]); + nodeArray.append(arrRes[j][18]); + nodeArray.append(arrRes[j][19]); + nodeArray.append(arrRes[j][20]); + nodeArray.append(arrRes[j][21]); + nodeArray.append(arrRes[j][22]); + nodeArray.append(arrRes[j][23]); + nodeArray.append(arrRes[j][24]); + nodeArray.append(arrRes[j][25]); + nodeArray.append(arrRes[j][26]); + nodeArray.append(arrRes[j][27]); + nodeArray.append(arrRes[j][28]); + nodeArray.append(arrRes[j][29]); + nodeArray.append(arrRes[j][30]); + nodeArray.append(arrRes[j][31]); + nodeArray.append(arrRes[j][32]); + nodeArray.append(arrRes[j][33]); + nodeArray.append(arrRes[j][34]); + nodeArray.append(arrRes[j][35]); + nodeArray.append(arrRes[j][36]); + nodeArray.append(arrRes[j][37]); + nodeArray.append(arrRes[j][38]); + nodeArray.append(arrRes[j][39]); + nodeArray.append(arrRes[j][40]); + nodeArray.append(arrRes[j][41]); + nodeArray.append(arrRes[j][42]); + nodeArray.append(arrRes[j][43]); + nodeArray.append(arrRes[j][44]); + jsArray.append(nodeArray); + + } + + } else { + jsArray.resize(0); + jsonVal["success"] = true; + } + Json::Value jsSystemSetting,jsonValnet,jsonValnet1,jsSystemInfo,jsonValZigbee; + Json::Value jsBody; + + jsSystemSetting["ServerIpAddress"] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress"); + jsSystemSetting["ServerPort"] = (ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str()); + jsSystemSetting["CommMode"] = (ReadStrByOpt(SERVERCONFIG, "Server", "CommMode").c_str()); + jsSystemSetting["UserName"] = ReadStrByOpt(SERVERCONFIG, "Server", "UserName"); + jsSystemSetting["Password"] = ReadStrByOpt(SERVERCONFIG, "Server", "Password"); + jsSystemSetting["APN"] = ReadStrByOpt(SERVERCONFIG, "Server", "APN"); + jsBody["ServerConfig"] = jsSystemSetting; + jsonVal["content"] = jsBody; + +#ifdef G2UL_GATEWAY + jsonValnet1["dnsName"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "dnsName"); + jsonValnet1["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "networkPortStatus"); + jsonValnet1["gateway"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "gateway"); + jsonValnet1["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "subnetMask"); + jsonValnet1["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "ipAddress"); + jsonValnet1["hostName"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "hostName"); + jsonVal["content"]["eth1"] =jsonValnet1; + jsonVal["content"]["gatewaytype"] = 1; +#endif + + jsSystemInfo["GateWayVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayVersion"); + jsSystemInfo["SystemVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion"); + jsSystemInfo["WebVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion"); + jsSystemInfo["GateWayHwVesion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayHwVesion"); + jsSystemInfo["GateWayProduct"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayProduct"); + jsonVal["content"]["SystemInfo"] =jsSystemInfo; + + jsonValZigbee["channel"] = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "channel"); + jsonValZigbee["PanID"] = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "PanID"); + jsonVal["content"]["zigbee"] =jsonValZigbee; + + jsonVal["gatewayMac"] = GlobalConfig::MacAddr_G ; + jsonVal["gatewayIP"] = GlobalConfig::IpAddr_G ; + jsonVal["content"]["dataNodeArray"] = jsArray; + jsonVal["content"]["gateWay"] = gatewayArray; + 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"] = " "; + char whereCon[128] = { 0 }; + char localtimestamp[32] = { 0 }; + if (param.mDataNodeNo.length() > 0 && param.mType == "DELETE") { + 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); + sql_ctl->DeleteTableData(T_DATANODE_TIME(TNAME), whereCon); + sql_ctl->DeleteTableData(T_BATTERY_INFO(TNAME), whereCon); + char szTableName[50]={0x00}; + sprintf(szTableName,"DROP TABLE t_data_%s",param.mDataNodeNo.c_str()); + sql_ctl->CreateTable(szTableName, 0); + memset(szTableName,0x00,sizeof(szTableName)); + sprintf(szTableName,"DROP TABLE t_dataStatic_%s",param.mDataNodeNo.c_str()); + sql_ctl->CreateTable(szTableName, 0); + }else if(param.mDataNodeNo.length() > 0 && param.mType == "CORRECT"){ + char updateSql[1024] = { 0 }; + sprintf(whereCon, "%s= '%s'", T_SENSOR_INFO(DATANODENO), param.mDataNodeNo.c_str()); + GetTimeNet(localtimestamp, 1); + sprintf(updateSql,"LooseValue = '0,2,"); + string strUpdateSql = string(updateSql) + string(localtimestamp) + "' " ; + print_info("updateSql = %s\n",strUpdateSql.c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME),strUpdateSql.c_str(),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::vector vecWave; + /* 新增代码 */ + char whereCon[64] = {}; + sprintf(whereCon, "dataNodeNo='%s'",param.mDataNodeNo.c_str()); + vec_t res = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME)," * ",whereCon); + char localtimestamp[32] = { 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 hanningWave; + inFile.read((char *)localtimestamp,sizeof(localtimestamp)); + while (inFile.read((char *)&fTemp, sizeof(fTemp))) { + vecWave.push_back(fTemp); + } + //测试正弦波 + //pCalculation->GenerateSin(vecWave); + + //添加汉宁窗 + /*pCalculation->Hanning(vecWave, hanningWave); + for(int i = 0; i < vecWave.size();i++){ + vecWave[i] = (vecWave[i]*hanningWave[i]); + }*/ + + 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; + print_info("vecWave.size() = %d,sample = %d,second = %f\n",vecWave.size(),atoi(res[23].c_str()),float(vecWave.size()/atoi(res[23].c_str()))); + string::size_type comper = param.mChannelId.find("Z"); + if (comper != string::npos && res[17]=="02"){ + jsBody["second"] = float((float)vecWave.size()/(float)atoi(res[23].c_str())); + }else if(res[17]=="01"){ + jsBody["second"] = float((float)vecWave.size()/(float)atoi(res[23].c_str())); + }else{ + jsBody["second"] = 1; + } + + jsBody["Data"] = strWaveData; + jsBody["timestamp"] = string(localtimestamp); + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); + +} + +std::string JsonData::JsonCmd_Cgi_30(Param_30 ¶m) +{ + + 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"; + char localtimestamp[32] = { 0 }; + std::vector vecWave; + std::vector hanningWave; + std::vector addhanningWave; + std::vector fftWave; + int sampleRateReference = 0; + /* 新增代码 */ + char whereCon[64] = {}; + sprintf(whereCon, "dataNodeNo='%s'",param.mDataNodeNo.c_str()); + vec_t res = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME)," * ",whereCon); + 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; + + + inFile.read((char *)localtimestamp,sizeof(localtimestamp)); + string::size_type comper = param.mChannelId.find("Z"); + if (comper != string::npos && res[17]=="02") { + while(inFile.read((char *)&fTemp,sizeof(fTemp))) + { + vecWave.push_back(fTemp); + } + //进行傅立叶变换 + pCalculation->FFTSpec(vecWave, fftWave); + sampleRateReference = 1000; + + }else{ + while(inFile.read((char *)&fTemp,sizeof(fTemp))) + { // 取8K进行计算 + //if(i < 8192) + { + vecWave.push_back(fTemp); + } + // else{ + // break; + // } + // i++; + } + //测试正弦波 + //pCalculation->GenerateSin(vecWave); + + // if(vecWave.size() < 8192){ + // for(int i = vecWave.size(); i < 8192;i++){ + // vecWave.push_back(0); + // } + // } + //添加汉宁窗 + // pCalculation->Hanning(vecWave, hanningWave); + // for(int i = 0; i < vecWave.size();i++){ + // addhanningWave.push_back(vecWave[i]*hanningWave[i]); + // } + + //进行傅立叶变换 + pCalculation->FFTSpec(vecWave, fftWave); + sampleRateReference = 1024; + + } + /*for(int i = 0; i < fftWave.size();i++){ + fftWave[i] = fftWave[i]*2; + }*/ + printf("2---------------------------------------------->vecWave = %d,fftWave = %d\n",vecWave.size(),fftWave.size()); + + int flag = param.mPackageFlag; + flag = (flag + 1) * sampleRateReference; + int number = fftWave.size(); + printf("number---------------------------------------------->%d\n",number); + int start = param.mPackageFlag * sampleRateReference; + printf("param.mPackageFlag = %d\n",param.mPackageFlag); + printf("param.start = %d\n",start); + printf("param.flag = %d\n",flag); + if (number < sampleRateReference) { + flag = number; + start = 0; + } + char buf[32]; + for (int i = start; i < flag; i++) { + if ( i == start ) { + memset(buf, 0, 32); + sprintf(buf, "%.6f", fftWave[i]); + std::string waveTemp(buf); + strWaveData = waveTemp; + + } else { + memset(buf, 0, 32); + sprintf(buf, "%.6f", fftWave[i]); + std::string waveTemp(buf); + strWaveData = strWaveData + "," + waveTemp; + } + } + + int max = number / sampleRateReference; + 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["timestamp"] = string(localtimestamp); + jsBody["Data"] = strWaveData; + + double resolution = 0.0; + int SampleRate =0; + print_info("sensor type %s\n",res[17].c_str()); + if(res[17]=="01"){ + SampleRate = atoi(res[23].c_str()); + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d\n",SampleRate); + resolution = (((double)SampleRate/1000)*1016)/ vecWave.size(); + //resolution = (double)SampleRate/vecWave.size(); + + }else if(res[17]=="02"){ + string::size_type comper = param.mChannelId.find("Z"); + if (comper != string::npos) { + SampleRate = atoi(res[23].c_str()); + resolution = (double)SampleRate/vecWave.size(); + //resolution = (((double)vecWave.size()/1000)*1024)/ (SampleRate * ((vecWave.size()/SampleRate))); + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d,resolution = %f\n",SampleRate,resolution); + }else{ + SampleRate = 8192; + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d\n",SampleRate); + if (vecWave.size() < 8192) + { + resolution = (double)SampleRate/ vecWave.size(); + }else{ + + resolution = (double)SampleRate/ 8192; + } + } + } + + print_info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@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_40(Param_40 ¶m) +{ + + Json::Value jsonVal; + Json::Value jsBody; + Json::Value SystemSetting; + jsonVal.clear(); + + jsonVal["cmd"] = "40"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = ""; + int i = 0; + int sampleRateReference = 0; + std::vector vecWave; + /* 新增代码 */ + char whereCon[64] = {}; + sprintf(whereCon, "dataNodeNo='%s'",param.mDataNodeNo.c_str()); + vec_t res = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME)," * ",whereCon); + std::string strWaveData; + std::string filename = "/opt/data/" + param.mChannelId + ".dat"; + char localtimestamp[32] = { 0 }; + 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 envWave; + std::vector hanningWave; + std::vector addhanningWave; + inFile.read((char *)localtimestamp,sizeof(localtimestamp)); + string::size_type comper = param.mChannelId.find("Z"); + if (comper != string::npos && res[17]=="02") { + while(inFile.read((char *)&fTemp,sizeof(fTemp))) + { + vecWave.push_back(fTemp); + } + //添加汉宁窗 + pCalculation->Hanning(vecWave, hanningWave); + for(int i = 0; i < vecWave.size();i++){ + addhanningWave.push_back(vecWave[i]*hanningWave[i]); + } + + //进行傅立叶变换 + if(param.StartFrequency == 0){ + param.StartFrequency = 3000; + param.EndFrequency = 5000; + } + + pCalculation->envSpec(addhanningWave, envWave,param.StartFrequency,param.EndFrequency); + sampleRateReference = 1000; + + }else{ + while(inFile.read((char *)&fTemp,sizeof(fTemp))) + { // 取8K进行计算 + if(i < 8192) + { + vecWave.push_back(fTemp); + }else{ + break; + } + i++; + } + if(vecWave.size() < 8192){ + for(int i = vecWave.size(); i < 8192;i++){ + vecWave.push_back(0); + } + } + + //添加汉宁窗 + pCalculation->Hanning(vecWave, hanningWave); + for(int i = 0; i < vecWave.size();i++){ + addhanningWave.push_back(vecWave[i]*hanningWave[i]); + } + + //进行傅立叶变换 + if(param.StartFrequency == 0){ + param.StartFrequency = 3000; + param.EndFrequency = 5000; + } + + pCalculation->envSpec(addhanningWave, envWave,param.StartFrequency,param.EndFrequency); + sampleRateReference = 1024; + } + /*for(int i = 0; i < envWave.size();i++){ + envWave[i] = envWave[i]*2; + }*/ + + printf("2---------------------------------------------->%d\n",envWave.size()); + printf("2---------------------------------------------->%f\n",envWave[10]); + + print_info("after fft--------------------------------------------------->fftWave.size()=%d\n", envWave.size()); + + int flag = param.mPackageFlag; + flag = (flag + 1) * sampleRateReference; + int number = envWave.size(); + int start = param.mPackageFlag * sampleRateReference; + printf("param.mPackageFlag = %d\n",param.mPackageFlag); + printf("param.start = %d\n",start); + printf("param.flag = %d\n",flag); + if (number < sampleRateReference) { + flag = number; + start = 0; + } + char buf[32]; + for (int i = start; i < flag; i++) { + if ( i == start ) { + memset(buf, 0, 32); + sprintf(buf, "%.6f", envWave[i]); + std::string waveTemp(buf); + strWaveData = waveTemp; + + } else { + memset(buf, 0, 32); + sprintf(buf, "%.6f", envWave[i]); + std::string waveTemp(buf); + strWaveData = strWaveData + "," + waveTemp; + } + } + + int max = number / sampleRateReference; + 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["timestamp"] = string(localtimestamp); + jsBody["Data"] = strWaveData; + + double resolution = 0.0; + int SampleRate =0; + print_info("sensor type %s\n",res[17].c_str()); + if(res[17]=="01"){ + SampleRate = atoi(res[23].c_str()); + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d\n",SampleRate); + resolution = (((double)SampleRate/1000)*1016)/ 8192; + }else if(res[17]=="02"){ + string::size_type comper = param.mChannelId.find("Z"); + if (comper != string::npos) { + SampleRate = atoi(res[23].c_str()); + + resolution = (double)SampleRate/vecWave.size(); + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d,resolution = %f\n",SampleRate,resolution); + }else{ + SampleRate = 8000; + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d\n",SampleRate); + resolution = (((double)SampleRate/1000)*1024)/ 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_41(std::vector ¶m,int isServer) +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["cmd"] = "41"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + char whereCon[1024] = {0}; + char updateSql[1024] = { 0 }; + //int WaveInteerVal = param.mwaveInterVal/param.mfeatureInterVal; + + for(int i = 0; i < param.size();i++){ + char dataNodeName[100]={0x00}; + hexToAscii(param[i].mdataNodeName.c_str(),dataNodeName); + print_info("str = %s\n",dataNodeName); + print_info("dataNodeName = %s\n",param[i].mdataNodeName.c_str()); + int dataNodeNameLength = param[i].mdataNodeName.length(); + if(dataNodeNameLength != 0 ){ + sprintf(updateSql, "dataNodeName = '%s',ZigbeePower = '%d',ZigbeeRetry = '%d',featureInterVal='%d',waveInterVal='%d',range='%d',samplingRate='%d',AccSampleTime = '%d',\ + startBrands = '%s',stopBrands = '%s',envelopeBandPass = '%s',viff = '%d',faultFrequency = '%s' ,MeasurementID = '%s' ,UpdateFlag = -1", + dataNodeName,param[i].ZigbeePower,param[i].ZigbeeRetry,param[i].mfeatureInterVal, param[i].mwaveInterVal,param[i].mrange,\ + param[i].msamplingRate,param[i].mAccSampleTime, param[i].mstartBrands.c_str(),\ + param[i].mstopBrands.c_str(),param[i].menvelopeBandPass.c_str(),param[i].mviff,param[i].mfaultFrequency.c_str(),param[i].mMeasurementID.c_str()); + }else if(dataNodeNameLength == 0 ){ + sprintf(updateSql, "ZigbeePower = '%d',ZigbeeRetry = '%d',featureInterVal='%d',waveInterVal='%d',range='%d',samplingRate='%d',AccSampleTime = '%d',\ + startBrands = '%s',stopBrands = '%s',envelopeBandPass = '%s',viff = '%d',faultFrequency = '%s',MeasurementID = '%s',NodeWaveSend = '%s',UpdateFlag = 0", + param[i].ZigbeePower,param[i].ZigbeeRetry,param[i].mfeatureInterVal, param[i].mwaveInterVal,param[i].mrange,\ + param[i].msamplingRate,param[i].mAccSampleTime, param[i].mstartBrands.c_str(),\ + param[i].mstopBrands.c_str(),param[i].menvelopeBandPass.c_str(),param[i].mviff,param[i].mfaultFrequency.c_str(),param[i].mMeasurementID.c_str(),param[i].nodeWaveSend.c_str()); + } + if(!isServer) + sprintf(whereCon, "dataNodeNo='%s'", param[i].mdataNodeNo.c_str()); + else + sprintf(whereCon, "MeasurementID ='%s'", param[i].mdataNodeNo.c_str()); + + int iRet = sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + memset(updateSql,0x00,sizeof(updateSql)); + if(iRet != 0) + jsonVal["success"] = false; + } + return showValue.write(jsonVal); +} +std::string JsonData::JsonCmd_Cgi_42(Param_42 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + jsonVal["cmd"] = "42"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = "上传成功!"; + char cmd[100]={0x00}; + strcpy(cmd,"rm -rf /tmp/cgic*"); + system(cmd); + if(param.fileName == "DataNode.tar"){ + string strcmd = "tar xvf /opt/"; + strcmd = strcmd + param.fileName; + strcmd = strcmd + " -C /opt/"; + print_info("strcmd = %s\n",strcmd.c_str()); + system(strcmd.c_str()); + }else if(param.fileName == "rfsbu.tar"){ + LOG_INFO("update rfsbu.tar\n"); + sleep(3); + print_info("strcmd = %s\n",param.fileName.c_str()); + int iRet = system("/opt/opt.sh"); + print_info("iRet = %d\n",iRet); + if (iRet == -1) + { + perror("system() error"); + } + }else if(param.fileName == "update.json"){ + print_info("strcmd = %s\n",param.fileName.c_str()); + + ReadStrConfig("/opt/update.json"); + }else if(param.fileName == "backup.json"){ + ImportConfig("/opt/backup.json"); + }else if(param.fileName == "DataNode.csv"){ + print_info("strcmd = %s\n",param.fileName.c_str()); + + int iRet = UpdataDataNodeConfig("/opt/DataNode.csv"); + string str = to_string(iRet) + "个传感器更新成功"; + if(iRet < 0){ + jsonVal["success"] = false; + jsonVal["message"] = "更新失败!"; + }else{ + jsonVal["success"] = true; + jsonVal["message"] = str; + } + + }else { + jsonVal["success"] = false; + jsonVal["message"] = "文件名错误!"; + } + 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); + WriteStr2Config(ZIGBEECONFIG, "Zigbee", "PanID", param.mPanID); + //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["RetryNum"] = GlobalConfig::ZigbeeInfo_G.RetryNum; + jsBody["TranTimeout"] = GlobalConfig::ZigbeeInfo_G.TranTimeout; + 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); +} +std::string JsonData::JsonCmd_Cgi_50() +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal[JSON_FIELD_CMD] = "50"; + jsonVal["success"] = true; + jsonVal["message"] = ""; + + std::string strFileName = "",strSoftVersion = ""; + Json::Value root; + Json::Value jsBody; + Json::Reader reader; + std::vector value; + std::vector vecDataNodeUpdate; + DataNodeUpdate datanodeUpdate; + std::fstream is; + is.open("/opt/DataNode/config.json", std::ios::in); + if (reader.parse(is, root)) { + jsBody["sensor"] = root; + } + jsBody["GateWayVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayVersion"); + jsBody["SystemVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion"); + jsBody["WebVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion"); + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); +} +std::string JsonData::JsonCmd_Cgi_51(Param_51 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + Json::Value jsBody; + jsonVal[JSON_FIELD_CMD] = "51"; + jsonVal["success"] = true; + jsonVal["message"] = ""; + + char whereCon[1024] = {0}; + char updateSql[1024] = { 0 }; + string gatewayLocation = ""; + + sprintf(updateSql, "gatewayLocation='%s'", + param.strGateWayLocation.c_str()); + sprintf(whereCon, "gatewayMAC='%s'", param.strGateWayMAC.c_str()); + if(param.mMode == 0){ + int iRet = sql_ctl->UpdateTableData(T_GATEWAY_INFO(TNAME), updateSql, whereCon); + if(iRet != 0) + jsonVal["success"] = false; + }else{ + gatewayLocation = sql_ctl->GetData(T_GATEWAY_INFO(TNAME) ,"gatewayLocation", NULL); + jsBody["gateWayLocation"] = gatewayLocation; + } + + + + jsonVal["content"] = jsBody; + + return showValue.write(jsonVal); +} +std::string JsonData::JsonCmd_Cgi_52(Param_52 ¶m) +{ + Json::Value jsonVal; + Json::Value jsBody; + + jsonVal.clear(); + jsonVal["cmd"] = "52"; + jsonVal["dataWatchNo"] = GlobalConfig::MacAddr_G; + jsonVal["cmdSerial"] = param.mCmdSerial; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + if (0 == param.mMode) { // 扫描 + wifi::WPAClient wpa; + std::string netssid = wpa.GetNetSsid(); + std::vector vecSsid; + boost::split(vecSsid, netssid, boost::is_any_of("\n"), boost::token_compress_off); + jsBody["type"] = "SCAN"; + print_info("netssid : %s %d\n", netssid.c_str(), vecSsid.size()); + for (unsigned int i = 1; i < vecSsid.size() - 1; i++) { + std::vector data; + boost::split(data, vecSsid[i], boost::is_any_of("\t"), boost::token_compress_off); + Json::Value wifiInfo; + wifiInfo["bssid"] = data[0]; + wifiInfo["frequency"] = data[1]; + wifiInfo["signallevel"] = data[2]; + wifiInfo["secure"] = data[3]; + wifiInfo["ssid"] = data[4]; + jsBody["wifilist"].append(wifiInfo); + + } + } else if ( 1 == param.mMode) { // 设置 + print_info("set WiFi\n"); + wifi::WPAClient wpa; + jsBody["ssid"] = param.mSsid; + if (param.mPassWord.length() > 0) { + if (wpa.ConnectWiFi(param.mSsid.c_str(), param.mPassWord.c_str())) { + jsBody["status"] = true; + } else { + jsBody["status"] = false; + } + } else { + if (wpa.ConnectWiFiWithNoPassword(param.mSsid.c_str())) { + jsBody["status"] = true; + } else { + jsBody["status"] = false; + } + } + } else if ( 2 == param.mMode ) { // 获取 + wifi::WPAClient wpa; + std::string ssid = " "; + int rssi = 0; + ssid = wpa.GetCurrentSSID(); + rssi = wpa.GetWiFiRssi() ; + jsBody["ssid"] = ssid; + jsBody["rssi"] = rssi; + } else if ( 3 == param.mMode ) { + wifi::WPAClient wpa; + if (wpa.CleanWifi()) { + jsonVal["message"] = "wifi断开成功"; + } else { + jsonVal["message"] = "wifi断开失败"; + } + } + + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_53(std::vector ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + + jsonVal["cmd"] = "53"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = " "; + + char whereCon[1024] = {0}; + char updateSql[1024] = { 0 }; + for(int i = 0; i < param.size();i++){ + if(param[i].mUpdateKey2 == ""){ + sprintf(updateSql, "%s='%s',UpdateFlag = 0", + param[i].mUpdateKey.c_str(), param[i].mUpdateValue.c_str()); + }else if(param[i].mUpdateKey3 == "" && param[i].mUpdateKey2 != ""){ + sprintf(updateSql, "%s='%s',%s='%s',UpdateFlag = 0", + param[i].mUpdateKey.c_str(), param[i].mUpdateValue.c_str(),param[i].mUpdateKey2.c_str(), param[i].mUpdateValue2.c_str()); + }else if(param[i].mUpdateKey3 != "" && param[i].mUpdateKey2 != ""){ + sprintf(updateSql, "%s='%s',%s='%s',%s='%s',UpdateFlag = 0", + param[i].mUpdateKey.c_str(), param[i].mUpdateValue.c_str(),param[i].mUpdateKey2.c_str(), param[i].mUpdateValue2.c_str(),\ + param[i].mUpdateKey3.c_str(), param[i].mUpdateValue3.c_str()); + } + sprintf(whereCon, "dataNodeNo='%s'", param[i].mdataNodeNo.c_str()); + + int iRet = sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + memset(updateSql,0x00,sizeof(updateSql)); + if(iRet != 0) + jsonVal["success"] = false; + } + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_55(Param_55 ¶m) +{ + Json::Value jsonVal; + Json::Value jsBody; + Json::Value SystemSetting; + jsonVal.clear(); + jsonVal["cmd"] = "55"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = " "; + std::vector vecWave; + std::vector IntegrationWave; + /* 新增代码 */ + char whereCon[64] = {}; + sprintf(whereCon, "dataNodeNo='%s'",param.mDataNodeNo.c_str()); + vec_t res = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME)," * ",whereCon); + int SampleRate =0; + double resolution = 0.0; + SampleRate = atoi(res[23].c_str()); + print_info("sensor type %s\n",res[17].c_str()); + + char localtimestamp[32] = { 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 hanningWave; + inFile.read((char *)localtimestamp,sizeof(localtimestamp)); + while (inFile.read((char *)&fTemp, sizeof(fTemp))) { + vecWave.push_back(fTemp); + } + if(res[17]=="01"){ + + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d\n",SampleRate); + resolution = (((double)SampleRate/1000)*1016)/ vecWave.size(); + + }else if(res[17]=="02"){ + string::size_type comper = param.mChannelId.find("Z"); + if (comper != string::npos) { + resolution = (double)SampleRate/vecWave.size(); + //resolution = (((double)vecWave.size()/1000)*1024)/ (SampleRate * ((vecWave.size()/SampleRate))); + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d,resolution = %f\n",SampleRate,resolution); + }else{ + SampleRate = 8000; + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d\n",SampleRate); + resolution = (((double)SampleRate/1024)*1024)/ 8192; + } + } + + //积分 + pCalculation->Integration(vecWave, IntegrationWave,resolution); + + //测试正弦波 + // pCalculation->GenerateSin(vecWave); + // pCalculation->Integration(vecWave, IntegrationWave); + + //添加汉宁窗 + /*pCalculation->Hanning(vecWave, hanningWave); + for(int i = 0; i < vecWave.size();i++){ + vecWave[i] = (vecWave[i]*hanningWave[i]); + }*/ + + int flag = param.mPackageFlag; + flag = (flag + 1) * 1024; + int number = IntegrationWave.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", IntegrationWave[i]); + std::string waveTemp(buf); + strWaveData = waveTemp; + + } else { + memset(buf, 0, 32); + sprintf(buf, "%.2f", IntegrationWave[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; + print_info("vecWave.size() = %d,sample = %d,second = %f\n",IntegrationWave.size(),atoi(res[23].c_str()),float(IntegrationWave.size()/atoi(res[23].c_str()))); + string::size_type comper = param.mChannelId.find("Z"); + if (comper != string::npos && res[17]=="02"){ + jsBody["second"] = float((float)IntegrationWave.size()/(float)atoi(res[23].c_str())); + }else if(res[17]=="01"){ + jsBody["second"] = float((float)IntegrationWave.size()/(float)atoi(res[23].c_str())); + }else{ + jsBody["second"] = 1; + } + + jsBody["Data"] = strWaveData; + jsBody["timestamp"] = string(localtimestamp); + jsonVal["content"] = jsBody; + return showValue.write(jsonVal); +} + +std::string JsonData::JsonCmd_Cgi_56(Param_56 ¶m) +{ + Json::Value jsonVal; + Json::Value jsBody; + Json::Value SystemSetting; + jsonVal.clear(); + + jsonVal["cmd"] = "56"; + jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsonVal["success"] = true; + jsonVal["message"] = ""; + int i = 0; + std::string strWaveData; + std::string filename = "/opt/data/" + param.mChannelId + ".dat"; + char localtimestamp[32] = { 0 }; + std::vector vecWave; + std::vector hanningWave; + std::vector addhanningWave; + std::vector fftWave; + std::vector IntegrationWave; + int sampleRateReference = 0; + /* 新增代码 */ + char whereCon[64] = {}; + sprintf(whereCon, "dataNodeNo='%s'",param.mDataNodeNo.c_str()); + vec_t res = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME)," * ",whereCon); + int SampleRate =0; + double resolution = 0.0; + SampleRate = atoi(res[23].c_str()); + print_info("sensor type %s\n",res[17].c_str()); + + + 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; + + + inFile.read((char *)localtimestamp,sizeof(localtimestamp)); + string::size_type comper = param.mChannelId.find("Z"); + if (comper != string::npos && res[17]=="02") { + while(inFile.read((char *)&fTemp,sizeof(fTemp))) + { + vecWave.push_back(fTemp); + } + //积分 + resolution = (double)SampleRate/vecWave.size(); + pCalculation->Integration(vecWave, IntegrationWave,resolution); + pCalculation->FFTSpec(IntegrationWave, fftWave); + sampleRateReference = 1000; + + }else{ + while(inFile.read((char *)&fTemp,sizeof(fTemp))) + { // 取8K进行计算 + //if(i < 8192) + { + vecWave.push_back(fTemp); + } + // else{ + // break; + // } + // i++; + } + if(res[17]=="01"){ + + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d\n",SampleRate); + resolution = (((double)SampleRate/1000)*1016)/ vecWave.size(); + //resolution = (double)SampleRate/vecWave.size(); + + }else if(res[17]=="02"){ + string::size_type comper = param.mChannelId.find("Z"); + if (comper != string::npos) { + SampleRate = atoi(res[23].c_str()); + resolution = (double)SampleRate/vecWave.size(); + //resolution = (((double)vecWave.size()/1000)*1024)/ (SampleRate * ((vecWave.size()/SampleRate))); + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d,resolution = %f\n",SampleRate,resolution); + }else{ + SampleRate = 8192; + printf("@@@@@@@@@@@@@@@@@@@@sample_rate=%d\n",SampleRate); + if (vecWave.size() < 8192) + { + resolution = (double)SampleRate/ vecWave.size(); + }else{ + resolution = (double)SampleRate/ 8192; + } + } + } + //测试正弦波 + //pCalculation->GenerateSin(vecWave); + + // if(vecWave.size() < 8192){ + // for(int i = vecWave.size(); i < 8192;i++){ + // vecWave.push_back(0); + // } + // } + // //添加汉宁窗 + // pCalculation->Hanning(vecWave, hanningWave); + // for(int i = 0; i < vecWave.size();i++){ + // addhanningWave.push_back(vecWave[i]*hanningWave[i]); + // } + + // //积分 + pCalculation->Integration(vecWave, IntegrationWave,resolution); + pCalculation->FFTSpec(IntegrationWave, fftWave); + + sampleRateReference = 1024; + } + /*for(int i = 0; i < fftWave.size();i++){ + fftWave[i] = fftWave[i]*2; + }*/ + printf("2---------------------------------------------->vecWave = %d,fftWave = %d\n",vecWave.size(),fftWave.size()); + + int flag = param.mPackageFlag; + flag = (flag + 1) * sampleRateReference; + int number = fftWave.size(); + printf("number---------------------------------------------->%d\n",number); + int start = param.mPackageFlag * sampleRateReference; + printf("param.mPackageFlag = %d\n",param.mPackageFlag); + printf("param.start = %d\n",start); + printf("param.flag = %d\n",flag); + if (number < sampleRateReference) { + flag = number; + start = 0; + } + char buf[32]; + for (int i = start; i < flag; i++) { + if ( i == start ) { + memset(buf, 0, 32); + sprintf(buf, "%.6f", fftWave[i]); + std::string waveTemp(buf); + strWaveData = waveTemp; + + } else { + memset(buf, 0, 32); + sprintf(buf, "%.6f", fftWave[i]); + std::string waveTemp(buf); + strWaveData = strWaveData + "," + waveTemp; + } + } + + int max = number / sampleRateReference; + 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["timestamp"] = string(localtimestamp); + jsBody["Data"] = strWaveData; + + + + + + print_info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@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_57(Param_57 ¶m) +{ + Json::Value jsonVal; + jsonVal.clear(); + Json::Value jsBody; + jsonVal[JSON_FIELD_CMD] = "57"; + jsonVal["success"] = true; + jsonVal["message"] = ""; + int zigbeepowerEnable = -1; + if(param.mMode == 1){ + zigbeepowerEnable = writeIntValue( "config", "zigbeepowerEnable",param.mZigbeePowerEnable,(char*)GlobalConfig::Config_G.c_str()); + }else if (param.mMode == 0) + { + zigbeepowerEnable = readIntValue( "config", "zigbeepowerEnable",(char*)GlobalConfig::Config_G.c_str()); + } + jsBody["zigbeepowerEnable"] = zigbeepowerEnable; + jsonVal["content"] = jsBody; + + return showValue.write(jsonVal); +} \ No newline at end of file diff --git a/jsonparse/SH_JsonCmd.hpp b/jsonparse/SH_JsonCmd.hpp new file mode 100644 index 0000000..2a7d5cc --- /dev/null +++ b/jsonparse/SH_JsonCmd.hpp @@ -0,0 +1,141 @@ +#ifndef _JSONCMD_H_ +#define _JSONCMD_H_ +#include +#include +#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" +#include "../datatransfer/SH_Datatrans.hpp" +#include "../wifi/wpa_client.h" + + +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); //系统配置信息 + std::string JsonCmd_50(Json::Value & recvBody); //download update file + std::string JsonCmd_51(Json::Value & recvBody); + std::string JsonCmd_52();//upload static data + std::string JsonCmd_53(Json::Value & recvBody); + 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_07(); //获取系统内存温度硬盘等信息 + std::string JsonCmd_Cgi_08(); //重启 + std::string JsonCmd_Cgi_09(Param_09 ¶m); //实时数据获取 + std::string JsonCmd_Cgi_10(Param_10 ¶m); // + std::string JsonCmd_Cgi_11(Param_11 ¶m); // + 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(Param_26 ¶m); + 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_40(Param_40 ¶m); // + std::string JsonCmd_Cgi_41(std::vector ¶m,int isServer = 0); // + std::string JsonCmd_Cgi_42(Param_42 ¶m); //从web端更新程序 + 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_50(); // + std::string JsonCmd_Cgi_51(Param_51 ¶m); // + std::string JsonCmd_Cgi_52(Param_52 ¶m); + std::string JsonCmd_Cgi_53(std::vector ¶m); + std::string JsonCmd_Cgi_54(Param_54 ¶m); + + std::string JsonCmd_Cgi_55(Param_55 ¶m); + std::string JsonCmd_Cgi_56(Param_56 ¶m); + std::string JsonCmd_Cgi_57(Param_57 ¶m); + 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/jsonparse/subdir.mk b/jsonparse/subdir.mk new file mode 100644 index 0000000..f3a537c --- /dev/null +++ b/jsonparse/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../jsonparse/SH_JsonCmd.cpp + +CPP_DEPS += \ +./jsonparse/SH_JsonCmd.d + +OBJS += \ +./jsonparse/SH_JsonCmd.o + + +# Each subdirectory must supply rules for building sources it contributes +jsonparse/%.o: ../jsonparse/%.cpp jsonparse/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-jsonparse + +clean-jsonparse: + -$(RM) ./jsonparse/SH_JsonCmd.d ./jsonparse/SH_JsonCmd.o + +.PHONY: clean-jsonparse + diff --git a/localserver/SH_LocalServer.cpp b/localserver/SH_LocalServer.cpp new file mode 100644 index 0000000..e971bfd --- /dev/null +++ b/localserver/SH_LocalServer.cpp @@ -0,0 +1,670 @@ +#include "SH_LocalServer.hpp" + +namespace { + PlatformInit *platform = PlatformInit::instance(); +} + +LocalServer::LocalServer() +{ + +} + +LocalServer::~LocalServer() +{ + print_info("~LocalServer is called!\n"); + LOG_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); + LOG_INFO("MQTT recv base64 %s\n",data_r.c_str()); + 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; + LOG_INFO("MQTT recv %s\n",pData.c_str()); + print_brown("pData : %s \n", pData.c_str()); + Json::Reader recvReader; + Json::Value recvValue; + Json::Value recvBody; + if (recvReader.parse(pData, recvValue)) { + int cmdType = atoi(recvValue["cmd"].asString().c_str()); + if(cmdType == 41){ + recvBody = recvValue["cmdBody"]; + }else{ + std::string cmdBody = recvValue["cmdBody"].asString(); + if (!recvReader.parse(cmdBody, recvBody)) { + print_error("recv body error"); + return; + } + } + + switch (cmdType) { + case 7:{ + JsonData jd; + std::string data = jd.JsonCmd_07(); + data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + }break; + 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"); + sleep(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 = atol(timestamp.c_str()); + SetTime(itimestamp); + mssleep(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 = to_string(recvBody["localServerPort"].asInt()); + param.mCommMode = to_string(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; + case 50:{ + JsonData jd; + std::string data = jd.JsonCmd_50(recvBody); + data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + }break; + case 41:{ + + JsonData jd; + Param_41 param; + std::vector param41; + for(int i = 0; i < recvBody.size();i++){ + param.mdataNodeNo = recvBody[i]["dataNodeNo"].asString(); + param.mfeatureInterVal = recvBody[i]["featureInterVal"].asInt(); + param.mwaveInterVal = recvBody[i]["waveInterVal"].asInt(); + param.msamplingRate = recvBody[i]["samplingRate"].asInt(); + param.mrange = recvBody[i]["range"].asInt(); + param.mAccSampleTime = recvBody[i]["ACCSampleTime"].asInt(); + param.mstartBrands = recvBody[i]["startBrands"].asString(); + param.mstopBrands = recvBody[i]["stopBrands"].asString(); + param.menvelopeBandPass = recvBody[i]["envelopeBandPass"].asString(); + param.mviff = recvBody[i]["viff"].asInt(); + param.mfaultFrequency = recvBody[i]["faultFrequency"].asString(); + param.ZigbeePower = recvBody[i]["ZigbeePower"].asInt(); + param.ZigbeeRetry = recvBody[i]["ZigbeeRetry"].asInt(); + param41.push_back(param); + } + std::string data = jd.JsonCmd_Cgi_41(param41,1); + char whereCon[64] = { 0 }; + sprintf(whereCon, " UpdateFlag <> 1 "); + string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + + } + break; + case 51:{ + JsonData jd; + std::string data = jd.JsonCmd_51(recvBody); + data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + }break; + case 52:{ +// JsonData jd; +// std::string data = jd.JsonCmd_52(recvBody); +// data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + }break; + case 53:{ + JsonData jd; + std::string data = jd.JsonCmd_53(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(); + param.mSetType = recvBody["setType"].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; + Param_09 param; + param.mPackageFlag = recvBody["package"].asInt(); + std::string data = jd.JsonCmd_Cgi_09(param); + return data; + } + break; + case 10:{ + JsonData jd; + Param_10 param; + param.strDataNode = recvBody["DataNode"].asString(); + param.strStatic = recvBody["Static"].asString(); + param.straxis = recvBody["Raxis"].asString(); + param.mPackageFlag = recvBody["package"].asInt(); + param.timeStart = recvBody["timeStart"].asString(); + param.timeEnd = recvBody["timeEnd"].asString(); + param.MeasurementID = recvBody["MeasurementID"].asString(); + std::string data = jd.JsonCmd_Cgi_10(param); + return data; + } + break; + case 11:{ + JsonData jd; + Param_11 param; + param.DataNodeNo = recvBody["DataNode"].asString(); + std::string data = jd.JsonCmd_Cgi_11(param); + 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 = recvBody["SystemSettings"]["CommMode"].asString(); + param.mUserName = recvBody["SystemSettings"]["UserName"].asString(); + param.mPassword = recvBody["SystemSettings"]["Password"].asString(); + param.mAPN = recvBody["SystemSettings"]["APN"].asString(); + } 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.mNet = recvBody["net"].asString(); + 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; + Param_26 param; + param.mPackageFlag = recvBody["package"].asInt(); + std::string data = jd.JsonCmd_Cgi_26(param); + // print_info("data = %s\n",data.c_str()); + return data; + } + break; + case 27:{ + Param_27 param; + param.mDataNodeNo = recvBody["dataNodeNo"].asString(); + param.mType = recvBody["type"].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.mPanID = recvBody["PanID"].asString(); + 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; + case 40:{ + JsonData jd; + Param_40 param; + param.mChannelId = recvBody["channelId"].asString(); + param.mPackageFlag = recvBody["package"].asInt(); + param.mDataNodeNo = recvBody["dataNodeNo"].asString(); + param.StartFrequency = recvBody["StartFrequency"].asInt(); + param.EndFrequency = recvBody["EndFrequency"].asInt(); + std::string data = jd.JsonCmd_Cgi_40(param); + return data; + } + break; + case 41:{ + JsonData jd; + Param_41 param; + std::vector param41; + for(int i = 0; i < recvBody.size();i++){ + param.mdataNodeNo = recvBody[i]["dataNodeNo"].asString(); + param.mfeatureInterVal = recvBody[i]["featureInterVal"].asInt(); + param.mwaveInterVal = recvBody[i]["waveInterVal"].asInt(); + param.msamplingRate = recvBody[i]["samplingRate"].asInt(); + param.mrange = recvBody[i]["range"].asInt(); + param.mAccSampleTime = recvBody[i]["ACCSampleTime"].asInt(); + param.mstartBrands = recvBody[i]["startBrands"].asString(); + param.mstopBrands = recvBody[i]["stopBrands"].asString(); + param.menvelopeBandPass = recvBody[i]["envelopeBandPass"].asString(); + param.mviff = recvBody[i]["viff"].asInt(); + param.mfaultFrequency = recvBody[i]["faultFrequency"].asString(); + param.mdataNodeName = recvBody[i]["dataNodeName"].asString(); + param.ZigbeePower = recvBody[i]["ZigbeePower"].asInt(); + param.ZigbeeRetry = recvBody[i]["ZigbeeRetry"].asInt(); + param.mMeasurementID = recvBody[i]["MeasurementID"].asString(); + param.nodeWaveSend = recvBody[i]["nodeWaveSend"].asString(); + param41.push_back(param); + } + std::string data = jd.JsonCmd_Cgi_41(param41); + char whereCon[64] = { 0 }; + sprintf(whereCon, " UpdateFlag <> 1 "); + string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + return data; + } + break; + case 42:{ + JsonData jd; + Param_42 param; + param.fileName = recvBody["fileName"].asString(); + std::string data = jd.JsonCmd_Cgi_42(param); + return data; + } + break; + case 50:{ + JsonData jd; + std::string data = jd.JsonCmd_Cgi_50(); + return data; + } + + break; + case 51:{ + JsonData jd; + Param_51 param; + std::string type = recvBody["type"].asString(); + if(0 == type.compare("SET")){ + param.mMode = 0; + param.strGateWayMAC = recvBody["gateWayNo"].asString(); + param.strGateWayLocation = recvBody["gateWayLocation"].asString(); + + }else{ + param.mMode = 1; + } + std::string data = jd.JsonCmd_Cgi_51(param); + return data; + } + break; + case 52:{ + Param_52 param; + param.mCmdSerial = recvValue["cmdSerial"].asString(); + std::string type = recvBody["type"].asString(); + if (0 == type.compare("SCAN")) { + param.mMode = 0; + } + if (0 == type.compare("SET")) { + param.mMode = 1; + param.mSsid = recvBody["ssid"].asString(); + param.mPassWord = recvBody["password"].asString(); + } + if (0 == type.compare("GET")) { + param.mMode = 2; + } + if (0 == type.compare("CLEAN")) { + param.mMode = 3; + } + JsonData jd; + std::string data = jd.JsonCmd_Cgi_52(param); + return data; + } + break; + case 53:{ + JsonData jd; + Param_53 param; + std::vector param53; + for(int i = 0; i < recvBody.size();i++){ + param.mdataNodeNo = recvBody[i]["dataNodeNo"].asString(); + param.mUpdateKey = recvBody[i]["updateKey"].asString(); + param.mUpdateValue = recvBody[i]["updateValue"].asString(); + param.mUpdateKey2 = recvBody[i]["updateKey2"].asString(); + param.mUpdateValue2 = recvBody[i]["updateValue2"].asString(); + param.mUpdateKey3 = recvBody[i]["updateKey3"].asString(); + param.mUpdateValue3 = recvBody[i]["updateValue3"].asString(); + param53.push_back(param); + } + std::string data = jd.JsonCmd_Cgi_53(param53); + char whereCon[64] = { 0 }; + sprintf(whereCon, "UpdateFlag <> 0 "); + string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + return data; + }break; + case 54:{ + JsonData jd; + Param_54 param; + param.mPackageFlag = recvBody["package"].asInt(); + std::string data = jd.JsonCmd_Cgi_54(param); + return data; + } + break; + case 55:{ + JsonData jd; + Param_55 param; + param.mChannelId = recvBody["channelId"].asString(); + param.mPackageFlag = recvBody["package"].asInt(); + param.mDataNodeNo = recvBody["dataNodeNo"].asString(); + std::string data = jd.JsonCmd_Cgi_55(param); + return data; + } + break; + case 56:{ + JsonData jd; + Param_56 param; + param.mChannelId = recvBody["channelId"].asString(); + param.mPackageFlag = recvBody["package"].asInt(); + param.mDataNodeNo = recvBody["dataNodeNo"].asString(); + std::string data = jd.JsonCmd_Cgi_56(param); + return data; + } + case 57:{ + JsonData jd; + Param_57 param; + param.mZigbeePowerEnable = recvBody["ZigbeePowerEnable"].asInt(); + std::string type = recvBody["type"].asString(); + if (0 == type.compare("SET")) { + param.mMode = 1; + } + if (0 == type.compare("GET")) { + param.mMode = 0; + } + std::string data = jd.JsonCmd_Cgi_57(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/localserver/subdir.mk b/localserver/subdir.mk new file mode 100644 index 0000000..5a3f411 --- /dev/null +++ b/localserver/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../localserver/SH_LocalServer.cpp + +CPP_DEPS += \ +./localserver/SH_LocalServer.d + +OBJS += \ +./localserver/SH_LocalServer.o + + +# Each subdirectory must supply rules for building sources it contributes +localserver/%.o: ../localserver/%.cpp localserver/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-localserver + +clean-localserver: + -$(RM) ./localserver/SH_LocalServer.d ./localserver/SH_LocalServer.o + +.PHONY: clean-localserver + diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..4292445 --- /dev/null +++ b/main.cpp @@ -0,0 +1,175 @@ +#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(); +} +extern std::vector g_VecWaveDataX; +extern std::vector g_VecWaveDataY; +extern std::vector g_VecWaveDataZ; +int main(int argc, char *argv[]) +{ + printf(" Firmware compile time:%s %s,version %s\n", __DATE__, __TIME__,GlobalConfig::Version.c_str()); + // 初始化日志记录,日志缓存区,记录数,未使用,后期,命令启动 + log_init(SOFTWARE_RUN_LOG, 1380, 1000 * 1024); + LOG_INFO("####CIDNSOFT start####\n"); + LOG_INFO(" Firmware compile time:%s %s,version %s\n", __DATE__, __TIME__,GlobalConfig::Version.c_str()); + // 查看版本信息 + if (CheckFileVersion(argc, argv)) { + return 0; + } + + g_VecWaveDataX.reserve(1000); + g_VecWaveDataY.reserve(1000); + g_VecWaveDataZ.reserve (1500); + // 设置线程属性之栈空间大小 + boost::thread::attributes attrs; + attrs.set_stack_size(1024*1024);//2M + + // 初始化平台配置文件 + platform->PlatFormInit(); + + sql_ctl->InintGateway(); + //sql_ctl->CalculateData(); + //sql_ctl->CalculateBattery(); + pUart->InitZigbee(); + // UDP,接收客户端发来的组播消息,用于外接 QT 专家系统,屏蔽之 + boost::thread searchT(SearchThread); + searchT.detach(); + + // 串口处理线程,用于与 ZigBee 模块通信,通过ZigBee无线通信技术与无线传感器通信 + boost::thread uartReadTh(UartStart); + uartReadTh.detach(); + + boost::thread uartTestReadTh(TestUart); + uartReadTh.detach(); + + boost::thread InitModuleReadTh(InitModule); + InitModuleReadTh.detach(); + //boost::thread uartWatchDogReadTh(WatchDog); + //uartWatchDogReadTh.detach(); + + // 休眠2秒,等待串口线程初始化完毕 + sleep(2); + + // 串口数据处理,读取传感器原始波形数据 + boost::thread uartWaveReadTh(UartStartWave); + uartWaveReadTh.detach(); + + +#ifdef G2UL_GATEWAY + //启动 RUN LED + boost::thread startRunLED(RunLED); + startRunLED.detach(); +#endif + +#ifdef NR5G_MODULE + print_info("NR5G_MODULE \n"); + //5G + boost::thread startCSQ(GetCSQ); + startCSQ.detach(); +#ifndef NR5G_MEIGE + boost::thread startDial(Dial5G); + startDial.detach(); +#endif +#endif + +#ifdef Q4G_MODULE + boost::thread startCSQ(GetCSQ); + startCSQ.detach(); + print_info("4G_MODULE \n"); + +#endif +#ifdef WIFI_MODULE + print_info("WiFi_MODULE \n"); +#endif + + // 通过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(); + + + sleep(5); + pUart->ZigbeeInit(); + sleep(1); + pUart->UpdateZigbeeInfoCtrl(); + + bool status = Ping( GlobalConfig::ServerIP.c_str(), 10000); + print_info("===========status ======== %d\n",status); + + /* char * szRes = sql_ctl->GetDataChar(T_SENSOR_INFO(TNAME), "dataNodeName", "dataNodeNo = '074cfd0000158d00'"); + printf("szRes = %s\n",szRes); + for(int i = 0; i < 64;i++){ + printf("temp = %02x ",szRes[i]); + }*/ + + //启动 mqtt客户端 + boost::thread startMqtt(StartMqttClient); + startMqtt.detach(); + + //启动 mqtt 心跳 + boost::thread startHeart(HeartRep); + startHeart.detach(); + + if (lzo_init() != LZO_E_OK) + { + printf("internal error - lzo_init() failed !!!\n"); + printf("(this usually indicates a compiler bug - try recompiling\nwithout optimizations, and enable '-DLZO_DEBUG' for diagnostics)\n"); + } + + int fd = OpenWatchDog(); + int count = 0; + while (GlobalConfig::QuitFlag_G) { +#ifdef G2UL_GATEWAY + gpio_set(GlobalConfig::GPIO_G.hardWatchDog,1); + usleep(20000); + gpio_set(GlobalConfig::GPIO_G.hardWatchDog,0); +#endif + WriteWatchDog(fd); + sleep(20); + if(GlobalConfig::threadStatus == 0){ + count ++; + }else if(GlobalConfig::threadStatus == 1){ + GlobalConfig::threadStatus = 0; + count = 0; + } + if(count >= 30){ + LOG_ERROR("===========threadStatus ========failed \n"); + break; + } + + } + return 0; +} + + diff --git a/minilzo-2.10/COPYING b/minilzo-2.10/COPYING new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/minilzo-2.10/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/minilzo-2.10/README.LZO b/minilzo-2.10/README.LZO new file mode 100644 index 0000000..7d9bea5 --- /dev/null +++ b/minilzo-2.10/README.LZO @@ -0,0 +1,123 @@ + + ============================================================================ + miniLZO -- mini subset of the LZO real-time data compression library + ============================================================================ + + Author : Markus Franz Xaver Johannes Oberhumer + + http://www.oberhumer.com/opensource/lzo/ + Version : 2.10 + Date : 01 Mar 2017 + + I've created miniLZO for projects where it is inconvenient to + include (or require) the full LZO source code just because you + want to add a little bit of data compression to your application. + + miniLZO implements the LZO1X-1 compressor and both the standard and + safe LZO1X decompressor. Apart from fast compression it also useful + for situations where you want to use pre-compressed data files (which + must have been compressed with LZO1X-999). + + miniLZO consists of one C source file and three header files: + minilzo.c + minilzo.h, lzoconf.h, lzodefs.h + + To use miniLZO just copy these files into your source directory, add + minilzo.c to your Makefile and #include minilzo.h from your program. + Note: you also must distribute this file ('README.LZO') with your project. + + minilzo.o compiles to about 6 KiB (using gcc or Visual C on an i386), and + the sources are about 30 KiB when packed with zip - so there's no more + excuse that your application doesn't support data compression :-) + + For more information, documentation, example programs and other support + files (like Makefiles and build scripts) please download the full LZO + package from + http://www.oberhumer.com/opensource/lzo/ + + Have fun, + Markus + + + P.S. minilzo.c is generated automatically from the LZO sources and + therefore functionality is completely identical + + + Appendix A: building miniLZO + ---------------------------- + miniLZO is written such a way that it should compile and run + out-of-the-box on most machines. + + If you are running on a very unusual architecture and lzo_init() fails then + you should first recompile with '-DLZO_DEBUG' to see what causes the failure. + The most probable case is something like 'sizeof(void *) != sizeof(size_t)'. + After identifying the problem you can compile by adding some defines + like '-DSIZEOF_VOID_P=8' to your Makefile. + + The best solution is (of course) using Autoconf - if your project uses + Autoconf anyway just add '-DMINILZO_HAVE_CONFIG_H' to your compiler + flags when compiling minilzo.c. See the LZO distribution for an example + how to set up configure.ac. + + + Appendix B: list of public functions available in miniLZO + --------------------------------------------------------- + Library initialization + lzo_init() + + Compression + lzo1x_1_compress() + + Decompression + lzo1x_decompress() + lzo1x_decompress_safe() + + Checksum functions + lzo_adler32() + + Version functions + lzo_version() + lzo_version_string() + lzo_version_date() + + Portable (but slow) string functions + lzo_memcmp() + lzo_memcpy() + lzo_memmove() + lzo_memset() + + + Appendix C: suggested macros for 'configure.ac' when using Autoconf + ------------------------------------------------------------------- + Checks for typedefs and structures + AC_CHECK_TYPE(ptrdiff_t,long) + AC_TYPE_SIZE_T + AC_CHECK_SIZEOF(short) + AC_CHECK_SIZEOF(int) + AC_CHECK_SIZEOF(long) + AC_CHECK_SIZEOF(long long) + AC_CHECK_SIZEOF(__int64) + AC_CHECK_SIZEOF(void *) + AC_CHECK_SIZEOF(size_t) + AC_CHECK_SIZEOF(ptrdiff_t) + + Checks for compiler characteristics + AC_C_CONST + + Checks for library functions + AC_CHECK_FUNCS(memcmp memcpy memmove memset) + + + Appendix D: Copyright + --------------------- + LZO and miniLZO are Copyright (C) 1996-2017 Markus Franz Xaver Oberhumer + All Rights Reserved. + + LZO and miniLZO are distributed under the terms of the GNU General + Public License (GPL). See the file COPYING. + + Special licenses for commercial and other applications which + are not willing to accept the GNU General Public License + are available by contacting the author. + + diff --git a/minilzo-2.10/lzoconf.h b/minilzo-2.10/lzoconf.h new file mode 100644 index 0000000..ee7a939 --- /dev/null +++ b/minilzo-2.10/lzoconf.h @@ -0,0 +1,453 @@ +/* lzoconf.h -- configuration of the LZO data compression library + + This file is part of the LZO real-time data compression library. + + Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer + All Rights Reserved. + + The LZO library is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of + the License, or (at your option) any later version. + + The LZO library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the LZO library; see the file COPYING. + If not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Markus F.X.J. Oberhumer + + http://www.oberhumer.com/opensource/lzo/ + */ + + +#ifndef __LZOCONF_H_INCLUDED +#define __LZOCONF_H_INCLUDED 1 + +#define LZO_VERSION 0x20a0 /* 2.10 */ +#define LZO_VERSION_STRING "2.10" +#define LZO_VERSION_DATE "Mar 01 2017" + +/* internal Autoconf configuration file - only used when building LZO */ +#if defined(LZO_HAVE_CONFIG_H) +# include +#endif +#include +#include + + +/*********************************************************************** +// LZO requires a conforming +************************************************************************/ + +#if !defined(CHAR_BIT) || (CHAR_BIT != 8) +# error "invalid CHAR_BIT" +#endif +#if !defined(UCHAR_MAX) || !defined(USHRT_MAX) || !defined(UINT_MAX) || !defined(ULONG_MAX) +# error "check your compiler installation" +#endif +#if (USHRT_MAX < 1) || (UINT_MAX < 1) || (ULONG_MAX < 1) +# error "your limits.h macros are broken" +#endif + +/* get OS and architecture defines */ +#ifndef __LZODEFS_H_INCLUDED +#include +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + +/*********************************************************************** +// some core defines +************************************************************************/ + +/* memory checkers */ +#if !defined(__LZO_CHECKER) +# if defined(__BOUNDS_CHECKING_ON) +# define __LZO_CHECKER 1 +# elif defined(__CHECKER__) +# define __LZO_CHECKER 1 +# elif defined(__INSURE__) +# define __LZO_CHECKER 1 +# elif defined(__PURIFY__) +# define __LZO_CHECKER 1 +# endif +#endif + + +/*********************************************************************** +// integral and pointer types +************************************************************************/ + +/* lzo_uint must match size_t */ +#if !defined(LZO_UINT_MAX) +# if (LZO_ABI_LLP64) +# if (LZO_OS_WIN64) + typedef unsigned __int64 lzo_uint; + typedef __int64 lzo_int; +# define LZO_TYPEOF_LZO_INT LZO_TYPEOF___INT64 +# else + typedef lzo_ullong_t lzo_uint; + typedef lzo_llong_t lzo_int; +# define LZO_TYPEOF_LZO_INT LZO_TYPEOF_LONG_LONG +# endif +# define LZO_SIZEOF_LZO_INT 8 +# define LZO_UINT_MAX 0xffffffffffffffffull +# define LZO_INT_MAX 9223372036854775807LL +# define LZO_INT_MIN (-1LL - LZO_INT_MAX) +# elif (LZO_ABI_IP32L64) /* MIPS R5900 */ + typedef unsigned int lzo_uint; + typedef int lzo_int; +# define LZO_SIZEOF_LZO_INT LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INT LZO_TYPEOF_INT +# define LZO_UINT_MAX UINT_MAX +# define LZO_INT_MAX INT_MAX +# define LZO_INT_MIN INT_MIN +# elif (ULONG_MAX >= LZO_0xffffffffL) + typedef unsigned long lzo_uint; + typedef long lzo_int; +# define LZO_SIZEOF_LZO_INT LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_INT LZO_TYPEOF_LONG +# define LZO_UINT_MAX ULONG_MAX +# define LZO_INT_MAX LONG_MAX +# define LZO_INT_MIN LONG_MIN +# else +# error "lzo_uint" +# endif +#endif + +/* The larger type of lzo_uint and lzo_uint32_t. */ +#if (LZO_SIZEOF_LZO_INT >= 4) +# define lzo_xint lzo_uint +#else +# define lzo_xint lzo_uint32_t +#endif + +typedef int lzo_bool; + +/* sanity checks */ +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int) == LZO_SIZEOF_LZO_INT) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint) == LZO_SIZEOF_LZO_INT) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_xint) >= sizeof(lzo_uint)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_xint) >= sizeof(lzo_uint32_t)) + +#ifndef __LZO_MMODEL +#define __LZO_MMODEL /*empty*/ +#endif + +/* no typedef here because of const-pointer issues */ +#define lzo_bytep unsigned char __LZO_MMODEL * +#define lzo_charp char __LZO_MMODEL * +#define lzo_voidp void __LZO_MMODEL * +#define lzo_shortp short __LZO_MMODEL * +#define lzo_ushortp unsigned short __LZO_MMODEL * +#define lzo_intp lzo_int __LZO_MMODEL * +#define lzo_uintp lzo_uint __LZO_MMODEL * +#define lzo_xintp lzo_xint __LZO_MMODEL * +#define lzo_voidpp lzo_voidp __LZO_MMODEL * +#define lzo_bytepp lzo_bytep __LZO_MMODEL * + +#define lzo_int8_tp lzo_int8_t __LZO_MMODEL * +#define lzo_uint8_tp lzo_uint8_t __LZO_MMODEL * +#define lzo_int16_tp lzo_int16_t __LZO_MMODEL * +#define lzo_uint16_tp lzo_uint16_t __LZO_MMODEL * +#define lzo_int32_tp lzo_int32_t __LZO_MMODEL * +#define lzo_uint32_tp lzo_uint32_t __LZO_MMODEL * +#if defined(lzo_int64_t) +#define lzo_int64_tp lzo_int64_t __LZO_MMODEL * +#define lzo_uint64_tp lzo_uint64_t __LZO_MMODEL * +#endif + +/* Older LZO versions used to support ancient systems and memory models + * such as 16-bit MSDOS with __huge pointers or Cray PVP, but these + * obsolete configurations are not supported any longer. + */ +#if defined(__LZO_MMODEL_HUGE) +#error "__LZO_MMODEL_HUGE memory model is unsupported" +#endif +#if (LZO_MM_PVP) +#error "LZO_MM_PVP memory model is unsupported" +#endif +#if (LZO_SIZEOF_INT < 4) +#error "LZO_SIZEOF_INT < 4 is unsupported" +#endif +#if (__LZO_UINTPTR_T_IS_POINTER) +#error "__LZO_UINTPTR_T_IS_POINTER is unsupported" +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(int) >= 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint) >= 4) +/* Strange configurations where sizeof(lzo_uint) != sizeof(size_t) should + * work but have not received much testing lately, so be strict here. + */ +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint) == sizeof(size_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint) == sizeof(ptrdiff_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint) == sizeof(lzo_uintptr_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(void *) == sizeof(lzo_uintptr_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(char *) == sizeof(lzo_uintptr_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long *) == sizeof(lzo_uintptr_t)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(void *) == sizeof(lzo_voidp)) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(char *) == sizeof(lzo_bytep)) + + +/*********************************************************************** +// function types +************************************************************************/ + +/* name mangling */ +#if !defined(__LZO_EXTERN_C) +# ifdef __cplusplus +# define __LZO_EXTERN_C extern "C" +# else +# define __LZO_EXTERN_C extern +# endif +#endif + +/* calling convention */ +#if !defined(__LZO_CDECL) +# define __LZO_CDECL __lzo_cdecl +#endif + +/* DLL export information */ +#if !defined(__LZO_EXPORT1) +# define __LZO_EXPORT1 /*empty*/ +#endif +#if !defined(__LZO_EXPORT2) +# define __LZO_EXPORT2 /*empty*/ +#endif + +/* __cdecl calling convention for public C and assembly functions */ +#if !defined(LZO_PUBLIC) +# define LZO_PUBLIC(r) __LZO_EXPORT1 r __LZO_EXPORT2 __LZO_CDECL +#endif +#if !defined(LZO_EXTERN) +# define LZO_EXTERN(r) __LZO_EXTERN_C LZO_PUBLIC(r) +#endif +#if !defined(LZO_PRIVATE) +# define LZO_PRIVATE(r) static r __LZO_CDECL +#endif + +/* function types */ +typedef int +(__LZO_CDECL *lzo_compress_t) ( const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem ); + +typedef int +(__LZO_CDECL *lzo_decompress_t) ( const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem ); + +typedef int +(__LZO_CDECL *lzo_optimize_t) ( lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem ); + +typedef int +(__LZO_CDECL *lzo_compress_dict_t)(const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem, + const lzo_bytep dict, lzo_uint dict_len ); + +typedef int +(__LZO_CDECL *lzo_decompress_dict_t)(const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem, + const lzo_bytep dict, lzo_uint dict_len ); + + +/* Callback interface. Currently only the progress indicator ("nprogress") + * is used, but this may change in a future release. */ + +struct lzo_callback_t; +typedef struct lzo_callback_t lzo_callback_t; +#define lzo_callback_p lzo_callback_t __LZO_MMODEL * + +/* malloc & free function types */ +typedef lzo_voidp (__LZO_CDECL *lzo_alloc_func_t) + (lzo_callback_p self, lzo_uint items, lzo_uint size); +typedef void (__LZO_CDECL *lzo_free_func_t) + (lzo_callback_p self, lzo_voidp ptr); + +/* a progress indicator callback function */ +typedef void (__LZO_CDECL *lzo_progress_func_t) + (lzo_callback_p, lzo_uint, lzo_uint, int); + +struct lzo_callback_t +{ + /* custom allocators (set to 0 to disable) */ + lzo_alloc_func_t nalloc; /* [not used right now] */ + lzo_free_func_t nfree; /* [not used right now] */ + + /* a progress indicator callback function (set to 0 to disable) */ + lzo_progress_func_t nprogress; + + /* INFO: the first parameter "self" of the nalloc/nfree/nprogress + * callbacks points back to this struct, so you are free to store + * some extra info in the following variables. */ + lzo_voidp user1; + lzo_xint user2; + lzo_xint user3; +}; + + +/*********************************************************************** +// error codes and prototypes +************************************************************************/ + +/* Error codes for the compression/decompression functions. Negative + * values are errors, positive values will be used for special but + * normal events. + */ +#define LZO_E_OK 0 +#define LZO_E_ERROR (-1) +#define LZO_E_OUT_OF_MEMORY (-2) /* [lzo_alloc_func_t failure] */ +#define LZO_E_NOT_COMPRESSIBLE (-3) /* [not used right now] */ +#define LZO_E_INPUT_OVERRUN (-4) +#define LZO_E_OUTPUT_OVERRUN (-5) +#define LZO_E_LOOKBEHIND_OVERRUN (-6) +#define LZO_E_EOF_NOT_FOUND (-7) +#define LZO_E_INPUT_NOT_CONSUMED (-8) +#define LZO_E_NOT_YET_IMPLEMENTED (-9) /* [not used right now] */ +#define LZO_E_INVALID_ARGUMENT (-10) +#define LZO_E_INVALID_ALIGNMENT (-11) /* pointer argument is not properly aligned */ +#define LZO_E_OUTPUT_NOT_CONSUMED (-12) +#define LZO_E_INTERNAL_ERROR (-99) + + +#ifndef lzo_sizeof_dict_t +# define lzo_sizeof_dict_t ((unsigned)sizeof(lzo_bytep)) +#endif + +/* lzo_init() should be the first function you call. + * Check the return code ! + * + * lzo_init() is a macro to allow checking that the library and the + * compiler's view of various types are consistent. + */ +#define lzo_init() __lzo_init_v2(LZO_VERSION,(int)sizeof(short),(int)sizeof(int),\ + (int)sizeof(long),(int)sizeof(lzo_uint32_t),(int)sizeof(lzo_uint),\ + (int)lzo_sizeof_dict_t,(int)sizeof(char *),(int)sizeof(lzo_voidp),\ + (int)sizeof(lzo_callback_t)) +LZO_EXTERN(int) __lzo_init_v2(unsigned,int,int,int,int,int,int,int,int,int); + +/* version functions (useful for shared libraries) */ +LZO_EXTERN(unsigned) lzo_version(void); +LZO_EXTERN(const char *) lzo_version_string(void); +LZO_EXTERN(const char *) lzo_version_date(void); +LZO_EXTERN(const lzo_charp) _lzo_version_string(void); +LZO_EXTERN(const lzo_charp) _lzo_version_date(void); + +/* string functions */ +LZO_EXTERN(int) + lzo_memcmp(const lzo_voidp a, const lzo_voidp b, lzo_uint len); +LZO_EXTERN(lzo_voidp) + lzo_memcpy(lzo_voidp dst, const lzo_voidp src, lzo_uint len); +LZO_EXTERN(lzo_voidp) + lzo_memmove(lzo_voidp dst, const lzo_voidp src, lzo_uint len); +LZO_EXTERN(lzo_voidp) + lzo_memset(lzo_voidp buf, int c, lzo_uint len); + +/* checksum functions */ +LZO_EXTERN(lzo_uint32_t) + lzo_adler32(lzo_uint32_t c, const lzo_bytep buf, lzo_uint len); +LZO_EXTERN(lzo_uint32_t) + lzo_crc32(lzo_uint32_t c, const lzo_bytep buf, lzo_uint len); +LZO_EXTERN(const lzo_uint32_tp) + lzo_get_crc32_table(void); + +/* misc. */ +LZO_EXTERN(int) _lzo_config_check(void); +typedef union { + lzo_voidp a00; lzo_bytep a01; lzo_uint a02; lzo_xint a03; lzo_uintptr_t a04; + void *a05; unsigned char *a06; unsigned long a07; size_t a08; ptrdiff_t a09; +#if defined(lzo_int64_t) + lzo_uint64_t a10; +#endif +} lzo_align_t; + +/* align a char pointer on a boundary that is a multiple of 'size' */ +LZO_EXTERN(unsigned) __lzo_align_gap(const lzo_voidp p, lzo_uint size); +#define LZO_PTR_ALIGN_UP(p,size) \ + ((p) + (lzo_uint) __lzo_align_gap((const lzo_voidp)(p),(lzo_uint)(size))) + + +/*********************************************************************** +// deprecated macros - only for backward compatibility +************************************************************************/ + +/* deprecated - use 'lzo_bytep' instead of 'lzo_byte *' */ +#define lzo_byte unsigned char +/* deprecated type names */ +#define lzo_int32 lzo_int32_t +#define lzo_uint32 lzo_uint32_t +#define lzo_int32p lzo_int32_t __LZO_MMODEL * +#define lzo_uint32p lzo_uint32_t __LZO_MMODEL * +#define LZO_INT32_MAX LZO_INT32_C(2147483647) +#define LZO_UINT32_MAX LZO_UINT32_C(4294967295) +#if defined(lzo_int64_t) +#define lzo_int64 lzo_int64_t +#define lzo_uint64 lzo_uint64_t +#define lzo_int64p lzo_int64_t __LZO_MMODEL * +#define lzo_uint64p lzo_uint64_t __LZO_MMODEL * +#define LZO_INT64_MAX LZO_INT64_C(9223372036854775807) +#define LZO_UINT64_MAX LZO_UINT64_C(18446744073709551615) +#endif +/* deprecated types */ +typedef union { lzo_bytep a; lzo_uint b; } __lzo_pu_u; +typedef union { lzo_bytep a; lzo_uint32_t b; } __lzo_pu32_u; +/* deprecated defines */ +#if !defined(LZO_SIZEOF_LZO_UINT) +# define LZO_SIZEOF_LZO_UINT LZO_SIZEOF_LZO_INT +#endif + +#if defined(LZO_CFG_COMPAT) + +#define __LZOCONF_H 1 + +#if defined(LZO_ARCH_I086) +# define __LZO_i386 1 +#elif defined(LZO_ARCH_I386) +# define __LZO_i386 1 +#endif + +#if defined(LZO_OS_DOS16) +# define __LZO_DOS 1 +# define __LZO_DOS16 1 +#elif defined(LZO_OS_DOS32) +# define __LZO_DOS 1 +#elif defined(LZO_OS_WIN16) +# define __LZO_WIN 1 +# define __LZO_WIN16 1 +#elif defined(LZO_OS_WIN32) +# define __LZO_WIN 1 +#endif + +#define __LZO_CMODEL /*empty*/ +#define __LZO_DMODEL /*empty*/ +#define __LZO_ENTRY __LZO_CDECL +#define LZO_EXTERN_CDECL LZO_EXTERN +#define LZO_ALIGN LZO_PTR_ALIGN_UP + +#define lzo_compress_asm_t lzo_compress_t +#define lzo_decompress_asm_t lzo_decompress_t + +#endif /* LZO_CFG_COMPAT */ + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* already included */ + + +/* vim:set ts=4 sw=4 et: */ diff --git a/minilzo-2.10/lzodefs.h b/minilzo-2.10/lzodefs.h new file mode 100644 index 0000000..1af2f09 --- /dev/null +++ b/minilzo-2.10/lzodefs.h @@ -0,0 +1,3268 @@ +/* lzodefs.h -- architecture, OS and compiler specific defines + + This file is part of the LZO real-time data compression library. + + Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer + All Rights Reserved. + + The LZO library is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of + the License, or (at your option) any later version. + + The LZO library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the LZO library; see the file COPYING. + If not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Markus F.X.J. Oberhumer + + http://www.oberhumer.com/opensource/lzo/ + */ + + +#ifndef __LZODEFS_H_INCLUDED +#define __LZODEFS_H_INCLUDED 1 + +#if defined(__CYGWIN32__) && !defined(__CYGWIN__) +# define __CYGWIN__ __CYGWIN32__ +#endif +#if 1 && defined(__INTERIX) && defined(__GNUC__) && !defined(_ALL_SOURCE) +# define _ALL_SOURCE 1 +#endif +#if defined(__mips__) && defined(__R5900__) +# if !defined(__LONG_MAX__) +# define __LONG_MAX__ 9223372036854775807L +# endif +#endif +#if 0 +#elif !defined(__LZO_LANG_OVERRIDE) +#if (defined(__clang__) || defined(__GNUC__)) && defined(__ASSEMBLER__) +# if (__ASSEMBLER__+0) <= 0 +# error "__ASSEMBLER__" +# else +# define LZO_LANG_ASSEMBLER 1 +# endif +#elif defined(__cplusplus) +# if (__cplusplus+0) <= 0 +# error "__cplusplus" +# elif (__cplusplus < 199711L) +# define LZO_LANG_CXX 1 +# elif defined(_MSC_VER) && defined(_MSVC_LANG) && (_MSVC_LANG+0 >= 201402L) && 1 +# define LZO_LANG_CXX _MSVC_LANG +# else +# define LZO_LANG_CXX __cplusplus +# endif +# define LZO_LANG_CPLUSPLUS LZO_LANG_CXX +#else +# if defined(__STDC_VERSION__) && (__STDC_VERSION__+0 >= 199409L) +# define LZO_LANG_C __STDC_VERSION__ +# else +# define LZO_LANG_C 1 +# endif +#endif +#endif +#if !defined(LZO_CFG_NO_DISABLE_WUNDEF) +#if defined(__ARMCC_VERSION) +# pragma diag_suppress 193 +#elif defined(__clang__) && defined(__clang_minor__) +# pragma clang diagnostic ignored "-Wundef" +#elif defined(__INTEL_COMPILER) +# pragma warning(disable: 193) +#elif defined(__KEIL__) && defined(__C166__) +# pragma warning disable = 322 +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && !defined(__PATHSCALE__) +# if ((__GNUC__-0) >= 5 || ((__GNUC__-0) == 4 && (__GNUC_MINOR__-0) >= 2)) +# pragma GCC diagnostic ignored "-Wundef" +# endif +#elif defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__MWERKS__) +# if ((_MSC_VER-0) >= 1300) +# pragma warning(disable: 4668) +# endif +#endif +#endif +#if 0 && defined(__POCC__) && defined(_WIN32) +# if (__POCC__ >= 400) +# pragma warn(disable: 2216) +# endif +#endif +#if 0 && defined(__WATCOMC__) +# if (__WATCOMC__ >= 1050) && (__WATCOMC__ < 1060) +# pragma warning 203 9 +# endif +#endif +#if defined(__BORLANDC__) && defined(__MSDOS__) && !defined(__FLAT__) +# pragma option -h +#endif +#if !(LZO_CFG_NO_DISABLE_WCRTNONSTDC) +#ifndef _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif +#ifndef _CRT_NONSTDC_NO_WARNINGS +#define _CRT_NONSTDC_NO_WARNINGS 1 +#endif +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS 1 +#endif +#endif +#if 0 +#define LZO_0xffffUL 0xfffful +#define LZO_0xffffffffUL 0xfffffffful +#else +#define LZO_0xffffUL 65535ul +#define LZO_0xffffffffUL 4294967295ul +#endif +#define LZO_0xffffL LZO_0xffffUL +#define LZO_0xffffffffL LZO_0xffffffffUL +#if (LZO_0xffffL == LZO_0xffffffffL) +# error "your preprocessor is broken 1" +#endif +#if (16ul * 16384ul != 262144ul) +# error "your preprocessor is broken 2" +#endif +#if 0 +#if (32767 >= 4294967295ul) +# error "your preprocessor is broken 3" +#endif +#if (65535u >= 4294967295ul) +# error "your preprocessor is broken 4" +#endif +#endif +#if defined(__COUNTER__) +# ifndef LZO_CFG_USE_COUNTER +# define LZO_CFG_USE_COUNTER 1 +# endif +#else +# undef LZO_CFG_USE_COUNTER +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(__ZTC__) && defined(__I86__) && !defined(__OS2__) +# if !defined(MSDOS) +# define MSDOS 1 +# endif +# if !defined(_MSDOS) +# define _MSDOS 1 +# endif +#elif 0 && defined(__VERSION) && defined(MB_LEN_MAX) +# if (__VERSION == 520) && (MB_LEN_MAX == 1) +# if !defined(__AZTEC_C__) +# define __AZTEC_C__ __VERSION +# endif +# if !defined(__DOS__) +# define __DOS__ 1 +# endif +# endif +#endif +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(_MSC_VER) && defined(M_I86HM) +# define ptrdiff_t long +# define _PTRDIFF_T_DEFINED 1 +#endif +#endif +#if (UINT_MAX == LZO_0xffffL) +# undef __LZO_RENAME_A +# undef __LZO_RENAME_B +# if defined(__AZTEC_C__) && defined(__DOS__) +# define __LZO_RENAME_A 1 +# elif defined(_MSC_VER) && defined(MSDOS) +# if (_MSC_VER < 600) +# define __LZO_RENAME_A 1 +# elif (_MSC_VER < 700) +# define __LZO_RENAME_B 1 +# endif +# elif defined(__TSC__) && defined(__OS2__) +# define __LZO_RENAME_A 1 +# elif defined(__MSDOS__) && defined(__TURBOC__) && (__TURBOC__ < 0x0410) +# define __LZO_RENAME_A 1 +# elif defined(__PACIFIC__) && defined(DOS) +# if !defined(__far) +# define __far far +# endif +# if !defined(__near) +# define __near near +# endif +# endif +# if defined(__LZO_RENAME_A) +# if !defined(__cdecl) +# define __cdecl cdecl +# endif +# if !defined(__far) +# define __far far +# endif +# if !defined(__huge) +# define __huge huge +# endif +# if !defined(__near) +# define __near near +# endif +# if !defined(__pascal) +# define __pascal pascal +# endif +# if !defined(__huge) +# define __huge huge +# endif +# elif defined(__LZO_RENAME_B) +# if !defined(__cdecl) +# define __cdecl _cdecl +# endif +# if !defined(__far) +# define __far _far +# endif +# if !defined(__huge) +# define __huge _huge +# endif +# if !defined(__near) +# define __near _near +# endif +# if !defined(__pascal) +# define __pascal _pascal +# endif +# elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) +# if !defined(__cdecl) +# define __cdecl cdecl +# endif +# if !defined(__pascal) +# define __pascal pascal +# endif +# endif +# undef __LZO_RENAME_A +# undef __LZO_RENAME_B +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(__AZTEC_C__) && defined(__DOS__) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +#elif defined(_MSC_VER) && defined(MSDOS) +# if (_MSC_VER < 600) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +# endif +# if (_MSC_VER < 700) +# define LZO_BROKEN_INTEGRAL_PROMOTION 1 +# define LZO_BROKEN_SIZEOF 1 +# endif +#elif defined(__PACIFIC__) && defined(DOS) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +#elif defined(__TURBOC__) && defined(__MSDOS__) +# if (__TURBOC__ < 0x0150) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +# define LZO_BROKEN_INTEGRAL_PROMOTION 1 +# endif +# if (__TURBOC__ < 0x0200) +# define LZO_BROKEN_SIZEOF 1 +# endif +# if (__TURBOC__ < 0x0400) && defined(__cplusplus) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# endif +#elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# define LZO_BROKEN_SIZEOF 1 +#endif +#endif +#if defined(__WATCOMC__) && (__WATCOMC__ < 900) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +#endif +#if defined(_CRAY) && defined(_CRAY1) +# define LZO_BROKEN_SIGNED_RIGHT_SHIFT 1 +#endif +#define LZO_PP_STRINGIZE(x) #x +#define LZO_PP_MACRO_EXPAND(x) LZO_PP_STRINGIZE(x) +#define LZO_PP_CONCAT0() /*empty*/ +#define LZO_PP_CONCAT1(a) a +#define LZO_PP_CONCAT2(a,b) a ## b +#define LZO_PP_CONCAT3(a,b,c) a ## b ## c +#define LZO_PP_CONCAT4(a,b,c,d) a ## b ## c ## d +#define LZO_PP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e +#define LZO_PP_CONCAT6(a,b,c,d,e,f) a ## b ## c ## d ## e ## f +#define LZO_PP_CONCAT7(a,b,c,d,e,f,g) a ## b ## c ## d ## e ## f ## g +#define LZO_PP_ECONCAT0() LZO_PP_CONCAT0() +#define LZO_PP_ECONCAT1(a) LZO_PP_CONCAT1(a) +#define LZO_PP_ECONCAT2(a,b) LZO_PP_CONCAT2(a,b) +#define LZO_PP_ECONCAT3(a,b,c) LZO_PP_CONCAT3(a,b,c) +#define LZO_PP_ECONCAT4(a,b,c,d) LZO_PP_CONCAT4(a,b,c,d) +#define LZO_PP_ECONCAT5(a,b,c,d,e) LZO_PP_CONCAT5(a,b,c,d,e) +#define LZO_PP_ECONCAT6(a,b,c,d,e,f) LZO_PP_CONCAT6(a,b,c,d,e,f) +#define LZO_PP_ECONCAT7(a,b,c,d,e,f,g) LZO_PP_CONCAT7(a,b,c,d,e,f,g) +#define LZO_PP_EMPTY /*empty*/ +#define LZO_PP_EMPTY0() /*empty*/ +#define LZO_PP_EMPTY1(a) /*empty*/ +#define LZO_PP_EMPTY2(a,b) /*empty*/ +#define LZO_PP_EMPTY3(a,b,c) /*empty*/ +#define LZO_PP_EMPTY4(a,b,c,d) /*empty*/ +#define LZO_PP_EMPTY5(a,b,c,d,e) /*empty*/ +#define LZO_PP_EMPTY6(a,b,c,d,e,f) /*empty*/ +#define LZO_PP_EMPTY7(a,b,c,d,e,f,g) /*empty*/ +#if 1 +#define LZO_CPP_STRINGIZE(x) #x +#define LZO_CPP_MACRO_EXPAND(x) LZO_CPP_STRINGIZE(x) +#define LZO_CPP_CONCAT2(a,b) a ## b +#define LZO_CPP_CONCAT3(a,b,c) a ## b ## c +#define LZO_CPP_CONCAT4(a,b,c,d) a ## b ## c ## d +#define LZO_CPP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e +#define LZO_CPP_CONCAT6(a,b,c,d,e,f) a ## b ## c ## d ## e ## f +#define LZO_CPP_CONCAT7(a,b,c,d,e,f,g) a ## b ## c ## d ## e ## f ## g +#define LZO_CPP_ECONCAT2(a,b) LZO_CPP_CONCAT2(a,b) +#define LZO_CPP_ECONCAT3(a,b,c) LZO_CPP_CONCAT3(a,b,c) +#define LZO_CPP_ECONCAT4(a,b,c,d) LZO_CPP_CONCAT4(a,b,c,d) +#define LZO_CPP_ECONCAT5(a,b,c,d,e) LZO_CPP_CONCAT5(a,b,c,d,e) +#define LZO_CPP_ECONCAT6(a,b,c,d,e,f) LZO_CPP_CONCAT6(a,b,c,d,e,f) +#define LZO_CPP_ECONCAT7(a,b,c,d,e,f,g) LZO_CPP_CONCAT7(a,b,c,d,e,f,g) +#endif +#define __LZO_MASK_GEN(o,b) (((((o) << ((b)-((b)!=0))) - (o)) << 1) + (o)*((b)!=0)) +#if 1 && defined(__cplusplus) +# if !defined(__STDC_CONSTANT_MACROS) +# define __STDC_CONSTANT_MACROS 1 +# endif +# if !defined(__STDC_LIMIT_MACROS) +# define __STDC_LIMIT_MACROS 1 +# endif +#endif +#if defined(__cplusplus) +# define LZO_EXTERN_C extern "C" +# define LZO_EXTERN_C_BEGIN extern "C" { +# define LZO_EXTERN_C_END } +#else +# define LZO_EXTERN_C extern +# define LZO_EXTERN_C_BEGIN /*empty*/ +# define LZO_EXTERN_C_END /*empty*/ +#endif +#if !defined(__LZO_OS_OVERRIDE) +#if (LZO_OS_FREESTANDING) +# define LZO_INFO_OS "freestanding" +#elif (LZO_OS_EMBEDDED) +# define LZO_INFO_OS "embedded" +#elif 1 && defined(__IAR_SYSTEMS_ICC__) +# define LZO_OS_EMBEDDED 1 +# define LZO_INFO_OS "embedded" +#elif defined(__CYGWIN__) && defined(__GNUC__) +# define LZO_OS_CYGWIN 1 +# define LZO_INFO_OS "cygwin" +#elif defined(__EMX__) && defined(__GNUC__) +# define LZO_OS_EMX 1 +# define LZO_INFO_OS "emx" +#elif defined(__BEOS__) +# define LZO_OS_BEOS 1 +# define LZO_INFO_OS "beos" +#elif defined(__Lynx__) +# define LZO_OS_LYNXOS 1 +# define LZO_INFO_OS "lynxos" +#elif defined(__OS400__) +# define LZO_OS_OS400 1 +# define LZO_INFO_OS "os400" +#elif defined(__QNX__) +# define LZO_OS_QNX 1 +# define LZO_INFO_OS "qnx" +#elif defined(__BORLANDC__) && defined(__DPMI32__) && (__BORLANDC__ >= 0x0460) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +#elif defined(__BORLANDC__) && defined(__DPMI16__) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +#elif defined(__ZTC__) && defined(DOS386) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +#elif defined(__OS2__) || defined(__OS2V2__) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_OS216 1 +# define LZO_INFO_OS "os216" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_OS2 1 +# define LZO_INFO_OS "os2" +# else +# error "check your limits.h header" +# endif +#elif defined(__WIN64__) || defined(_WIN64) || defined(WIN64) +# define LZO_OS_WIN64 1 +# define LZO_INFO_OS "win64" +#elif defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS_386__) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +#elif defined(__MWERKS__) && defined(__INTEL__) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +#elif defined(__WINDOWS__) || defined(_WINDOWS) || defined(_Windows) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_WIN16 1 +# define LZO_INFO_OS "win16" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +# else +# error "check your limits.h header" +# endif +#elif defined(__DOS__) || defined(__MSDOS__) || defined(_MSDOS) || defined(MSDOS) || (defined(__PACIFIC__) && defined(DOS)) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +# else +# error "check your limits.h header" +# endif +#elif defined(__WATCOMC__) +# if defined(__NT__) && (UINT_MAX == LZO_0xffffL) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +# elif defined(__NT__) && (__WATCOMC__ < 1100) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +# elif defined(__linux__) || defined(__LINUX__) +# define LZO_OS_POSIX 1 +# define LZO_INFO_OS "posix" +# else +# error "please specify a target using the -bt compiler option" +# endif +#elif defined(__palmos__) +# define LZO_OS_PALMOS 1 +# define LZO_INFO_OS "palmos" +#elif defined(__TOS__) || defined(__atarist__) +# define LZO_OS_TOS 1 +# define LZO_INFO_OS "tos" +#elif defined(macintosh) && !defined(__arm__) && !defined(__i386__) && !defined(__ppc__) && !defined(__x64_64__) +# define LZO_OS_MACCLASSIC 1 +# define LZO_INFO_OS "macclassic" +#elif defined(__VMS) +# define LZO_OS_VMS 1 +# define LZO_INFO_OS "vms" +#elif (defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__) +# define LZO_OS_CONSOLE 1 +# define LZO_OS_CONSOLE_PS2 1 +# define LZO_INFO_OS "console" +# define LZO_INFO_OS_CONSOLE "ps2" +#elif defined(__mips__) && defined(__psp__) +# define LZO_OS_CONSOLE 1 +# define LZO_OS_CONSOLE_PSP 1 +# define LZO_INFO_OS "console" +# define LZO_INFO_OS_CONSOLE "psp" +#else +# define LZO_OS_POSIX 1 +# define LZO_INFO_OS "posix" +#endif +#if (LZO_OS_POSIX) +# if defined(_AIX) || defined(__AIX__) || defined(__aix__) +# define LZO_OS_POSIX_AIX 1 +# define LZO_INFO_OS_POSIX "aix" +# elif defined(__FreeBSD__) +# define LZO_OS_POSIX_FREEBSD 1 +# define LZO_INFO_OS_POSIX "freebsd" +# elif defined(__hpux__) || defined(__hpux) +# define LZO_OS_POSIX_HPUX 1 +# define LZO_INFO_OS_POSIX "hpux" +# elif defined(__INTERIX) +# define LZO_OS_POSIX_INTERIX 1 +# define LZO_INFO_OS_POSIX "interix" +# elif defined(__IRIX__) || defined(__irix__) +# define LZO_OS_POSIX_IRIX 1 +# define LZO_INFO_OS_POSIX "irix" +# elif defined(__linux__) || defined(__linux) || defined(__LINUX__) +# define LZO_OS_POSIX_LINUX 1 +# define LZO_INFO_OS_POSIX "linux" +# elif defined(__APPLE__) && defined(__MACH__) +# if ((__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__-0) >= 20000) +# define LZO_OS_POSIX_DARWIN 1040 +# define LZO_INFO_OS_POSIX "darwin_iphone" +# elif ((__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__-0) >= 1040) +# define LZO_OS_POSIX_DARWIN __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ +# define LZO_INFO_OS_POSIX "darwin" +# else +# define LZO_OS_POSIX_DARWIN 1 +# define LZO_INFO_OS_POSIX "darwin" +# endif +# define LZO_OS_POSIX_MACOSX LZO_OS_POSIX_DARWIN +# elif defined(__minix__) || defined(__minix) +# define LZO_OS_POSIX_MINIX 1 +# define LZO_INFO_OS_POSIX "minix" +# elif defined(__NetBSD__) +# define LZO_OS_POSIX_NETBSD 1 +# define LZO_INFO_OS_POSIX "netbsd" +# elif defined(__OpenBSD__) +# define LZO_OS_POSIX_OPENBSD 1 +# define LZO_INFO_OS_POSIX "openbsd" +# elif defined(__osf__) +# define LZO_OS_POSIX_OSF 1 +# define LZO_INFO_OS_POSIX "osf" +# elif defined(__solaris__) || defined(__sun) +# if defined(__SVR4) || defined(__svr4__) +# define LZO_OS_POSIX_SOLARIS 1 +# define LZO_INFO_OS_POSIX "solaris" +# else +# define LZO_OS_POSIX_SUNOS 1 +# define LZO_INFO_OS_POSIX "sunos" +# endif +# elif defined(__ultrix__) || defined(__ultrix) +# define LZO_OS_POSIX_ULTRIX 1 +# define LZO_INFO_OS_POSIX "ultrix" +# elif defined(_UNICOS) +# define LZO_OS_POSIX_UNICOS 1 +# define LZO_INFO_OS_POSIX "unicos" +# else +# define LZO_OS_POSIX_UNKNOWN 1 +# define LZO_INFO_OS_POSIX "unknown" +# endif +#endif +#endif +#if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +# if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (UINT_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if defined(CIL) && defined(_GNUCC) && defined(__GNUC__) +# define LZO_CC_CILLY 1 +# define LZO_INFO_CC "Cilly" +# if defined(__CILLY__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__CILLY__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif 0 && defined(SDCC) && defined(__VERSION__) && !defined(__GNUC__) +# define LZO_CC_SDCC 1 +# define LZO_INFO_CC "sdcc" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(SDCC) +#elif defined(__PATHSCALE__) && defined(__PATHCC_PATCHLEVEL__) +# define LZO_CC_PATHSCALE (__PATHCC__ * 0x10000L + (__PATHCC_MINOR__-0) * 0x100 + (__PATHCC_PATCHLEVEL__-0)) +# define LZO_INFO_CC "Pathscale C" +# define LZO_INFO_CCVER __PATHSCALE__ +# if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_PATHSCALE_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__INTEL_COMPILER) && ((__INTEL_COMPILER-0) > 0) +# define LZO_CC_INTELC __INTEL_COMPILER +# define LZO_INFO_CC "Intel C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__INTEL_COMPILER) +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_INTELC_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_INTELC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__POCC__) && defined(_WIN32) +# define LZO_CC_PELLESC 1 +# define LZO_INFO_CC "Pelles C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__POCC__) +#elif defined(__ARMCC_VERSION) && defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# if defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_ARMCC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# else +# define LZO_CC_ARMCC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# endif +# define LZO_CC_ARMCC __ARMCC_VERSION +# define LZO_INFO_CC "ARM C Compiler" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(__clang__) && defined(__c2__) && defined(__c2_version__) && defined(_MSC_VER) +# define LZO_CC_CLANG (__clang_major__ * 0x10000L + (__clang_minor__-0) * 0x100 + (__clang_patchlevel__-0)) +# define LZO_CC_CLANG_C2 _MSC_VER +# define LZO_CC_CLANG_VENDOR_MICROSOFT 1 +# define LZO_INFO_CC "clang/c2" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__c2_version__) +#elif defined(__clang__) && defined(__llvm__) && defined(__VERSION__) +# if defined(__clang_major__) && defined(__clang_minor__) && defined(__clang_patchlevel__) +# define LZO_CC_CLANG (__clang_major__ * 0x10000L + (__clang_minor__-0) * 0x100 + (__clang_patchlevel__-0)) +# else +# define LZO_CC_CLANG 0x010000L +# endif +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_CLANG_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_CLANG_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +# if defined(__APPLE_CC__) +# define LZO_CC_CLANG_VENDOR_APPLE 1 +# define LZO_INFO_CC "clang/apple" +# else +# define LZO_CC_CLANG_VENDOR_LLVM 1 +# define LZO_INFO_CC "clang" +# endif +# if defined(__clang_version__) +# define LZO_INFO_CCVER __clang_version__ +# else +# define LZO_INFO_CCVER __VERSION__ +# endif +#elif defined(__llvm__) && defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# if defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_LLVM_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# else +# define LZO_CC_LLVM_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# endif +# define LZO_CC_LLVM LZO_CC_LLVM_GNUC +# define LZO_INFO_CC "llvm-gcc" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(__ACK__) && defined(_ACK) +# define LZO_CC_ACK 1 +# define LZO_INFO_CC "Amsterdam Compiler Kit C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__ARMCC_VERSION) && !defined(__GNUC__) +# define LZO_CC_ARMCC __ARMCC_VERSION +# define LZO_CC_ARMCC_ARMCC __ARMCC_VERSION +# define LZO_INFO_CC "ARM C Compiler" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__ARMCC_VERSION) +#elif defined(__AZTEC_C__) +# define LZO_CC_AZTECC 1 +# define LZO_INFO_CC "Aztec C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__AZTEC_C__) +#elif defined(__CODEGEARC__) +# define LZO_CC_CODEGEARC 1 +# define LZO_INFO_CC "CodeGear C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__CODEGEARC__) +#elif defined(__BORLANDC__) +# define LZO_CC_BORLANDC 1 +# define LZO_INFO_CC "Borland C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__BORLANDC__) +#elif defined(_CRAYC) && defined(_RELEASE) +# define LZO_CC_CRAYC 1 +# define LZO_INFO_CC "Cray C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_RELEASE) +#elif defined(__DMC__) && defined(__SC__) +# define LZO_CC_DMC 1 +# define LZO_INFO_CC "Digital Mars C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DMC__) +#elif defined(__DECC) +# define LZO_CC_DECC 1 +# define LZO_INFO_CC "DEC C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DECC) +#elif (defined(__ghs) || defined(__ghs__)) && defined(__GHS_VERSION_NUMBER) && ((__GHS_VERSION_NUMBER-0) > 0) +# define LZO_CC_GHS 1 +# define LZO_INFO_CC "Green Hills C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__GHS_VERSION_NUMBER) +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_GHS_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_GHS_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__HIGHC__) +# define LZO_CC_HIGHC 1 +# define LZO_INFO_CC "MetaWare High C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__HP_aCC) && ((__HP_aCC-0) > 0) +# define LZO_CC_HPACC __HP_aCC +# define LZO_INFO_CC "HP aCC" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__HP_aCC) +#elif defined(__IAR_SYSTEMS_ICC__) +# define LZO_CC_IARC 1 +# define LZO_INFO_CC "IAR C" +# if defined(__VER__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__VER__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__IBMC__) && ((__IBMC__-0) > 0) +# define LZO_CC_IBMC __IBMC__ +# define LZO_INFO_CC "IBM C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__IBMC__) +#elif defined(__IBMCPP__) && ((__IBMCPP__-0) > 0) +# define LZO_CC_IBMC __IBMCPP__ +# define LZO_INFO_CC "IBM C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__IBMCPP__) +#elif defined(__KEIL__) && defined(__C166__) +# define LZO_CC_KEILC 1 +# define LZO_INFO_CC "Keil C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__C166__) +#elif defined(__LCC__) && defined(_WIN32) && defined(__LCCOPTIMLEVEL) +# define LZO_CC_LCCWIN32 1 +# define LZO_INFO_CC "lcc-win32" +# define LZO_INFO_CCVER "unknown" +#elif defined(__LCC__) +# define LZO_CC_LCC 1 +# define LZO_INFO_CC "lcc" +# if defined(__LCC_VERSION__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__LCC_VERSION__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__MWERKS__) && ((__MWERKS__-0) > 0) +# define LZO_CC_MWERKS __MWERKS__ +# define LZO_INFO_CC "Metrowerks C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__MWERKS__) +#elif (defined(__NDPC__) || defined(__NDPX__)) && defined(__i386) +# define LZO_CC_NDPC 1 +# define LZO_INFO_CC "Microway NDP C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__PACIFIC__) +# define LZO_CC_PACIFICC 1 +# define LZO_INFO_CC "Pacific C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PACIFIC__) +#elif defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define LZO_CC_PGI (__PGIC__ * 0x10000L + (__PGIC_MINOR__-0) * 0x100 + (__PGIC_PATCHLEVEL__-0)) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PGIC__) "." LZO_PP_MACRO_EXPAND(__PGIC_MINOR__) "." LZO_PP_MACRO_EXPAND(__PGIC_PATCHLEVEL__) +# else +# define LZO_CC_PGI (__PGIC__ * 0x10000L + (__PGIC_MINOR__-0) * 0x100) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PGIC__) "." LZO_PP_MACRO_EXPAND(__PGIC_MINOR__) ".0" +# endif +# define LZO_INFO_CC "Portland Group PGI C" +#elif defined(__PGI) && (defined(__linux__) || defined(__WIN32__)) +# define LZO_CC_PGI 1 +# define LZO_INFO_CC "Portland Group PGI C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__PUREC__) && defined(__TOS__) +# define LZO_CC_PUREC 1 +# define LZO_INFO_CC "Pure C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PUREC__) +#elif defined(__SC__) && defined(__ZTC__) +# define LZO_CC_SYMANTECC 1 +# define LZO_INFO_CC "Symantec C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SC__) +#elif defined(__SUNPRO_C) +# define LZO_INFO_CC "SunPro C" +# if ((__SUNPRO_C-0) > 0) +# define LZO_CC_SUNPROC __SUNPRO_C +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_C) +# else +# define LZO_CC_SUNPROC 1 +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__SUNPRO_CC) +# define LZO_INFO_CC "SunPro C" +# if ((__SUNPRO_CC-0) > 0) +# define LZO_CC_SUNPROC __SUNPRO_CC +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_CC) +# else +# define LZO_CC_SUNPROC 1 +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__TINYC__) +# define LZO_CC_TINYC 1 +# define LZO_INFO_CC "Tiny C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TINYC__) +#elif defined(__TSC__) +# define LZO_CC_TOPSPEEDC 1 +# define LZO_INFO_CC "TopSpeed C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TSC__) +#elif defined(__WATCOMC__) +# define LZO_CC_WATCOMC 1 +# define LZO_INFO_CC "Watcom C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__WATCOMC__) +#elif defined(__TURBOC__) +# define LZO_CC_TURBOC 1 +# define LZO_INFO_CC "Turbo C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TURBOC__) +#elif defined(__ZTC__) +# define LZO_CC_ZORTECHC 1 +# define LZO_INFO_CC "Zortech C" +# if ((__ZTC__-0) == 0x310) +# define LZO_INFO_CCVER "0x310" +# else +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__ZTC__) +# endif +#elif defined(__GNUC__) && defined(__VERSION__) +# if defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# elif defined(__GNUC_MINOR__) +# define LZO_CC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# else +# define LZO_CC_GNUC (__GNUC__ * 0x10000L) +# endif +# define LZO_INFO_CC "gcc" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_MSC _MSC_VER +# define LZO_INFO_CC "Microsoft C" +# if defined(_MSC_FULL_VER) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) "." LZO_PP_MACRO_EXPAND(_MSC_FULL_VER) +# else +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) +# endif +#else +# define LZO_CC_UNKNOWN 1 +# define LZO_INFO_CC "unknown" +# define LZO_INFO_CCVER "unknown" +#endif +#if (LZO_CC_GNUC) && defined(__OPEN64__) +# if defined(__OPENCC__) && defined(__OPENCC_MINOR__) && defined(__OPENCC_PATCHLEVEL__) +# define LZO_CC_OPEN64 (__OPENCC__ * 0x10000L + (__OPENCC_MINOR__-0) * 0x100 + (__OPENCC_PATCHLEVEL__-0)) +# define LZO_CC_OPEN64_GNUC LZO_CC_GNUC +# endif +#endif +#if (LZO_CC_GNUC) && defined(__PCC__) +# if defined(__PCC__) && defined(__PCC_MINOR__) && defined(__PCC_MINORMINOR__) +# define LZO_CC_PCC (__PCC__ * 0x10000L + (__PCC_MINOR__-0) * 0x100 + (__PCC_MINORMINOR__-0)) +# define LZO_CC_PCC_GNUC LZO_CC_GNUC +# endif +#endif +#if 0 && (LZO_CC_MSC && (_MSC_VER >= 1200)) && !defined(_MSC_FULL_VER) +# error "LZO_CC_MSC: _MSC_FULL_VER is not defined" +#endif +#if !defined(__LZO_ARCH_OVERRIDE) && !(LZO_ARCH_GENERIC) && defined(_CRAY) +# if (UINT_MAX > LZO_0xffffffffL) && defined(_CRAY) +# if defined(_CRAYMPP) || defined(_CRAYT3D) || defined(_CRAYT3E) +# define LZO_ARCH_CRAY_MPP 1 +# elif defined(_CRAY1) +# define LZO_ARCH_CRAY_PVP 1 +# endif +# endif +#endif +#if !defined(__LZO_ARCH_OVERRIDE) +#if (LZO_ARCH_GENERIC) +# define LZO_INFO_ARCH "generic" +#elif (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +# define LZO_ARCH_I086 1 +# define LZO_INFO_ARCH "i086" +#elif defined(__aarch64__) || defined(_M_ARM64) +# define LZO_ARCH_ARM64 1 +# define LZO_INFO_ARCH "arm64" +#elif defined(__alpha__) || defined(__alpha) || defined(_M_ALPHA) +# define LZO_ARCH_ALPHA 1 +# define LZO_INFO_ARCH "alpha" +#elif (LZO_ARCH_CRAY_MPP) && (defined(_CRAYT3D) || defined(_CRAYT3E)) +# define LZO_ARCH_ALPHA 1 +# define LZO_INFO_ARCH "alpha" +#elif defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64) +# define LZO_ARCH_AMD64 1 +# define LZO_INFO_ARCH "amd64" +#elif defined(__arm__) || defined(_M_ARM) +# define LZO_ARCH_ARM 1 +# define LZO_INFO_ARCH "arm" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCARM__) +# define LZO_ARCH_ARM 1 +# define LZO_INFO_ARCH "arm" +#elif (UINT_MAX <= LZO_0xffffL) && defined(__AVR__) +# define LZO_ARCH_AVR 1 +# define LZO_INFO_ARCH "avr" +#elif defined(__avr32__) || defined(__AVR32__) +# define LZO_ARCH_AVR32 1 +# define LZO_INFO_ARCH "avr32" +#elif defined(__bfin__) +# define LZO_ARCH_BLACKFIN 1 +# define LZO_INFO_ARCH "blackfin" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C166__) +# define LZO_ARCH_C166 1 +# define LZO_INFO_ARCH "c166" +#elif defined(__cris__) +# define LZO_ARCH_CRIS 1 +# define LZO_INFO_ARCH "cris" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCEZ80__) +# define LZO_ARCH_EZ80 1 +# define LZO_INFO_ARCH "ez80" +#elif defined(__H8300__) || defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) +# define LZO_ARCH_H8300 1 +# define LZO_INFO_ARCH "h8300" +#elif defined(__hppa__) || defined(__hppa) +# define LZO_ARCH_HPPA 1 +# define LZO_INFO_ARCH "hppa" +#elif defined(__386__) || defined(__i386__) || defined(__i386) || defined(_M_IX86) || defined(_M_I386) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif (LZO_CC_ZORTECHC && defined(__I86__)) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif (LZO_OS_DOS32 && LZO_CC_HIGHC) && defined(_I386) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif defined(__ia64__) || defined(__ia64) || defined(_M_IA64) +# define LZO_ARCH_IA64 1 +# define LZO_INFO_ARCH "ia64" +#elif (UINT_MAX == LZO_0xffffL) && defined(__m32c__) +# define LZO_ARCH_M16C 1 +# define LZO_INFO_ARCH "m16c" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCM16C__) +# define LZO_ARCH_M16C 1 +# define LZO_INFO_ARCH "m16c" +#elif defined(__m32r__) +# define LZO_ARCH_M32R 1 +# define LZO_INFO_ARCH "m32r" +#elif (LZO_OS_TOS) || defined(__m68k__) || defined(__m68000__) || defined(__mc68000__) || defined(__mc68020__) || defined(_M_M68K) +# define LZO_ARCH_M68K 1 +# define LZO_INFO_ARCH "m68k" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C251__) +# define LZO_ARCH_MCS251 1 +# define LZO_INFO_ARCH "mcs251" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C51__) +# define LZO_ARCH_MCS51 1 +# define LZO_INFO_ARCH "mcs51" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC8051__) +# define LZO_ARCH_MCS51 1 +# define LZO_INFO_ARCH "mcs51" +#elif defined(__mips__) || defined(__mips) || defined(_MIPS_ARCH) || defined(_M_MRX000) +# define LZO_ARCH_MIPS 1 +# define LZO_INFO_ARCH "mips" +#elif (UINT_MAX == LZO_0xffffL) && defined(__MSP430__) +# define LZO_ARCH_MSP430 1 +# define LZO_INFO_ARCH "msp430" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC430__) +# define LZO_ARCH_MSP430 1 +# define LZO_INFO_ARCH "msp430" +#elif defined(__powerpc__) || defined(__powerpc) || defined(__ppc__) || defined(__PPC__) || defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PWR) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__powerpc64__) || defined(__powerpc64) || defined(__ppc64__) || defined(__PPC64__) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__powerpc64le__) || defined(__powerpc64le) || defined(__ppc64le__) || defined(__PPC64LE__) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__riscv) +# define LZO_ARCH_RISCV 1 +# define LZO_INFO_ARCH "riscv" +#elif defined(__s390__) || defined(__s390) || defined(__s390x__) || defined(__s390x) +# define LZO_ARCH_S390 1 +# define LZO_INFO_ARCH "s390" +#elif defined(__sh__) || defined(_M_SH) +# define LZO_ARCH_SH 1 +# define LZO_INFO_ARCH "sh" +#elif defined(__sparc__) || defined(__sparc) || defined(__sparcv8) +# define LZO_ARCH_SPARC 1 +# define LZO_INFO_ARCH "sparc" +#elif defined(__SPU__) +# define LZO_ARCH_SPU 1 +# define LZO_INFO_ARCH "spu" +#elif (UINT_MAX == LZO_0xffffL) && defined(__z80) +# define LZO_ARCH_Z80 1 +# define LZO_INFO_ARCH "z80" +#elif (LZO_ARCH_CRAY_PVP) +# if defined(_CRAYSV1) +# define LZO_ARCH_CRAY_SV1 1 +# define LZO_INFO_ARCH "cray_sv1" +# elif (_ADDR64) +# define LZO_ARCH_CRAY_T90 1 +# define LZO_INFO_ARCH "cray_t90" +# elif (_ADDR32) +# define LZO_ARCH_CRAY_YMP 1 +# define LZO_INFO_ARCH "cray_ymp" +# else +# define LZO_ARCH_CRAY_XMP 1 +# define LZO_INFO_ARCH "cray_xmp" +# endif +#else +# define LZO_ARCH_UNKNOWN 1 +# define LZO_INFO_ARCH "unknown" +#endif +#endif +#if !defined(LZO_ARCH_ARM_THUMB2) +#if (LZO_ARCH_ARM) +# if defined(__thumb__) || defined(__thumb) || defined(_M_THUMB) +# if defined(__thumb2__) +# define LZO_ARCH_ARM_THUMB2 1 +# elif 1 && defined(__TARGET_ARCH_THUMB) && ((__TARGET_ARCH_THUMB)+0 >= 4) +# define LZO_ARCH_ARM_THUMB2 1 +# elif 1 && defined(_MSC_VER) && defined(_M_THUMB) && ((_M_THUMB)+0 >= 7) +# define LZO_ARCH_ARM_THUMB2 1 +# endif +# endif +#endif +#endif +#if (LZO_ARCH_ARM_THUMB2) +# undef LZO_INFO_ARCH +# define LZO_INFO_ARCH "arm_thumb2" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_DOS32 || LZO_OS_OS2) +# error "FIXME - missing define for CPU architecture" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN32) +# error "FIXME - missing LZO_OS_WIN32 define for CPU architecture" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN64) +# error "FIXME - missing LZO_OS_WIN64 define for CPU architecture" +#endif +#if (LZO_OS_OS216 || LZO_OS_WIN16) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && defined(BLX286)) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && defined(DOSX286)) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && LZO_CC_BORLANDC && defined(__DPMI16__)) +# define LZO_ARCH_I086PM 1 +#endif +#if (LZO_ARCH_AMD64 && !LZO_ARCH_X64) +# define LZO_ARCH_X64 1 +#elif (!LZO_ARCH_AMD64 && LZO_ARCH_X64) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_AMD64 1 +#endif +#if (LZO_ARCH_ARM64 && !LZO_ARCH_AARCH64) +# define LZO_ARCH_AARCH64 1 +#elif (!LZO_ARCH_ARM64 && LZO_ARCH_AARCH64) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_ARM64 1 +#endif +#if (LZO_ARCH_I386 && !LZO_ARCH_X86) +# define LZO_ARCH_X86 1 +#elif (!LZO_ARCH_I386 && LZO_ARCH_X86) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_I386 1 +#endif +#if (LZO_ARCH_AMD64 && !LZO_ARCH_X64) || (!LZO_ARCH_AMD64 && LZO_ARCH_X64) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM64 && !LZO_ARCH_AARCH64) || (!LZO_ARCH_ARM64 && LZO_ARCH_AARCH64) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I386 && !LZO_ARCH_X86) || (!LZO_ARCH_I386 && LZO_ARCH_X86) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB1 && !LZO_ARCH_ARM) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB2 && !LZO_ARCH_ARM) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB1 && LZO_ARCH_ARM_THUMB2) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I086PM && !LZO_ARCH_I086) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I086) +# if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_ARCH_I386) +# if (UINT_MAX != LZO_0xffffL) && defined(__i386_int16__) +# error "unexpected configuration - check your compiler defines" +# endif +# if (UINT_MAX != LZO_0xffffffffL) && !defined(__i386_int16__) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_ARCH_AMD64 || LZO_ARCH_I386) +# if !defined(LZO_TARGET_FEATURE_SSE2) +# if defined(__SSE2__) +# define LZO_TARGET_FEATURE_SSE2 1 +# elif defined(_MSC_VER) && (defined(_M_IX86_FP) && ((_M_IX86_FP)+0 >= 2)) +# define LZO_TARGET_FEATURE_SSE2 1 +# elif (LZO_CC_INTELC_MSC || LZO_CC_MSC) && defined(_M_AMD64) +# define LZO_TARGET_FEATURE_SSE2 1 +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_SSSE3) +# if (LZO_TARGET_FEATURE_SSE2) +# if defined(__SSSE3__) +# define LZO_TARGET_FEATURE_SSSE3 1 +# elif defined(_MSC_VER) && defined(__AVX__) +# define LZO_TARGET_FEATURE_SSSE3 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_SSE4_2) +# if (LZO_TARGET_FEATURE_SSSE3) +# if defined(__SSE4_2__) +# define LZO_TARGET_FEATURE_SSE4_2 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_AVX) +# if (LZO_TARGET_FEATURE_SSSE3) +# if defined(__AVX__) +# define LZO_TARGET_FEATURE_AVX 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_AVX2) +# if (LZO_TARGET_FEATURE_AVX) +# if defined(__AVX2__) +# define LZO_TARGET_FEATURE_AVX2 1 +# endif +# endif +# endif +#endif +#if (LZO_TARGET_FEATURE_SSSE3 && !(LZO_TARGET_FEATURE_SSE2)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_SSE4_2 && !(LZO_TARGET_FEATURE_SSSE3)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_AVX && !(LZO_TARGET_FEATURE_SSSE3)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_AVX2 && !(LZO_TARGET_FEATURE_AVX)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM) +# if !defined(LZO_TARGET_FEATURE_NEON) +# if defined(__ARM_NEON) && ((__ARM_NEON)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# elif 1 && defined(__ARM_NEON__) && ((__ARM_NEON__)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# elif 1 && defined(__TARGET_FEATURE_NEON) && ((__TARGET_FEATURE_NEON)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# endif +# endif +#elif (LZO_ARCH_ARM64) +# if !defined(LZO_TARGET_FEATURE_NEON) +# if 1 +# define LZO_TARGET_FEATURE_NEON 1 +# endif +# endif +#endif +#if 0 +#elif !defined(__LZO_MM_OVERRIDE) +#if (LZO_ARCH_I086) +#if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +#endif +#if defined(__TINY__) || defined(M_I86TM) || defined(_M_I86TM) +# define LZO_MM_TINY 1 +#elif defined(__HUGE__) || defined(_HUGE_) || defined(M_I86HM) || defined(_M_I86HM) +# define LZO_MM_HUGE 1 +#elif defined(__SMALL__) || defined(M_I86SM) || defined(_M_I86SM) || defined(SMALL_MODEL) +# define LZO_MM_SMALL 1 +#elif defined(__MEDIUM__) || defined(M_I86MM) || defined(_M_I86MM) +# define LZO_MM_MEDIUM 1 +#elif defined(__COMPACT__) || defined(M_I86CM) || defined(_M_I86CM) +# define LZO_MM_COMPACT 1 +#elif defined(__LARGE__) || defined(M_I86LM) || defined(_M_I86LM) || defined(LARGE_MODEL) +# define LZO_MM_LARGE 1 +#elif (LZO_CC_AZTECC) +# if defined(_LARGE_CODE) && defined(_LARGE_DATA) +# define LZO_MM_LARGE 1 +# elif defined(_LARGE_CODE) +# define LZO_MM_MEDIUM 1 +# elif defined(_LARGE_DATA) +# define LZO_MM_COMPACT 1 +# else +# define LZO_MM_SMALL 1 +# endif +#elif (LZO_CC_ZORTECHC && defined(__VCM__)) +# define LZO_MM_LARGE 1 +#else +# error "unknown LZO_ARCH_I086 memory model" +#endif +#if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +#define LZO_HAVE_MM_HUGE_PTR 1 +#define LZO_HAVE_MM_HUGE_ARRAY 1 +#if (LZO_MM_TINY) +# undef LZO_HAVE_MM_HUGE_ARRAY +#endif +#if (LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_ZORTECHC) +# undef LZO_HAVE_MM_HUGE_PTR +# undef LZO_HAVE_MM_HUGE_ARRAY +#elif (LZO_CC_DMC || LZO_CC_SYMANTECC) +# undef LZO_HAVE_MM_HUGE_ARRAY +#elif (LZO_CC_MSC && defined(_QC)) +# undef LZO_HAVE_MM_HUGE_ARRAY +# if (_MSC_VER < 600) +# undef LZO_HAVE_MM_HUGE_PTR +# endif +#elif (LZO_CC_TURBOC && (__TURBOC__ < 0x0295)) +# undef LZO_HAVE_MM_HUGE_ARRAY +#endif +#if (LZO_ARCH_I086PM) && !(LZO_HAVE_MM_HUGE_PTR) +# if (LZO_OS_DOS16) +# error "unexpected configuration - check your compiler defines" +# elif (LZO_CC_ZORTECHC) +# else +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if defined(__cplusplus) +extern "C" { +#endif +#if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0200)) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_MSC || LZO_CC_TOPSPEEDC) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_TURBOC && (__TURBOC__ >= 0x0295)) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif ((LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_TURBOC) && LZO_OS_DOS16) +# define LZO_MM_AHSHIFT 12 +#elif (LZO_CC_WATCOMC) + extern unsigned char _HShift; +# define LZO_MM_AHSHIFT ((unsigned) _HShift) +#else +# error "FIXME - implement LZO_MM_AHSHIFT" +#endif +#if defined(__cplusplus) +} +#endif +#endif +#elif (LZO_ARCH_C166) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_C166 __MODEL__" +#elif ((__MODEL__) == 0) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 1) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_C166 __MODEL__" +#endif +#elif (LZO_ARCH_MCS251) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_MCS251 __MODEL__" +#elif ((__MODEL__) == 0) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_MCS251 __MODEL__" +#endif +#elif (LZO_ARCH_MCS51) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_MCS51 __MODEL__" +#elif ((__MODEL__) == 1) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_MCS51 __MODEL__" +#endif +#elif (LZO_ARCH_CRAY_PVP) +# define LZO_MM_PVP 1 +#else +# define LZO_MM_FLAT 1 +#endif +#if (LZO_MM_COMPACT) +# define LZO_INFO_MM "compact" +#elif (LZO_MM_FLAT) +# define LZO_INFO_MM "flat" +#elif (LZO_MM_HUGE) +# define LZO_INFO_MM "huge" +#elif (LZO_MM_LARGE) +# define LZO_INFO_MM "large" +#elif (LZO_MM_MEDIUM) +# define LZO_INFO_MM "medium" +#elif (LZO_MM_PVP) +# define LZO_INFO_MM "pvp" +#elif (LZO_MM_SMALL) +# define LZO_INFO_MM "small" +#elif (LZO_MM_TINY) +# define LZO_INFO_MM "tiny" +#else +# error "unknown memory model" +#endif +#endif +#if !defined(__lzo_gnuc_extension__) +#if (LZO_CC_GNUC >= 0x020800ul) +# define __lzo_gnuc_extension__ __extension__ +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_gnuc_extension__ __extension__ +#elif (LZO_CC_IBMC >= 600) +# define __lzo_gnuc_extension__ __extension__ +#endif +#endif +#if !defined(__lzo_gnuc_extension__) +# define __lzo_gnuc_extension__ /*empty*/ +#endif +#if !defined(lzo_has_builtin) +#if (LZO_CC_CLANG) && defined(__has_builtin) +# define lzo_has_builtin __has_builtin +#endif +#endif +#if !defined(lzo_has_builtin) +# define lzo_has_builtin(x) 0 +#endif +#if !defined(lzo_has_attribute) +#if (LZO_CC_CLANG) && defined(__has_attribute) +# define lzo_has_attribute __has_attribute +#endif +#endif +#if !defined(lzo_has_attribute) +# define lzo_has_attribute(x) 0 +#endif +#if !defined(lzo_has_declspec_attribute) +#if (LZO_CC_CLANG) && defined(__has_declspec_attribute) +# define lzo_has_declspec_attribute __has_declspec_attribute +#endif +#endif +#if !defined(lzo_has_declspec_attribute) +# define lzo_has_declspec_attribute(x) 0 +#endif +#if !defined(lzo_has_feature) +#if (LZO_CC_CLANG) && defined(__has_feature) +# define lzo_has_feature __has_feature +#endif +#endif +#if !defined(lzo_has_feature) +# define lzo_has_feature(x) 0 +#endif +#if !defined(lzo_has_extension) +#if (LZO_CC_CLANG) && defined(__has_extension) +# define lzo_has_extension __has_extension +#elif (LZO_CC_CLANG) && defined(__has_feature) +# define lzo_has_extension __has_feature +#endif +#endif +#if !defined(lzo_has_extension) +# define lzo_has_extension(x) 0 +#endif +#if !defined(LZO_CFG_USE_NEW_STYLE_CASTS) && defined(__cplusplus) && 0 +# if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +# elif (LZO_CC_INTELC && (__INTEL_COMPILER < 1200)) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +# else +# define LZO_CFG_USE_NEW_STYLE_CASTS 1 +# endif +#endif +#if !defined(LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +#endif +#if !defined(__cplusplus) +# if defined(LZO_CFG_USE_NEW_STYLE_CASTS) +# undef LZO_CFG_USE_NEW_STYLE_CASTS +# endif +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +#endif +#if !defined(LZO_REINTERPRET_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_REINTERPRET_CAST(t,e) (reinterpret_cast (e)) +# endif +#endif +#if !defined(LZO_REINTERPRET_CAST) +# define LZO_REINTERPRET_CAST(t,e) ((t) (e)) +#endif +#if !defined(LZO_STATIC_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_STATIC_CAST(t,e) (static_cast (e)) +# endif +#endif +#if !defined(LZO_STATIC_CAST) +# define LZO_STATIC_CAST(t,e) ((t) (e)) +#endif +#if !defined(LZO_STATIC_CAST2) +# define LZO_STATIC_CAST2(t1,t2,e) LZO_STATIC_CAST(t1, LZO_STATIC_CAST(t2, e)) +#endif +#if !defined(LZO_UNCONST_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNCONST_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNCONST_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNCONST_CAST(t,e) ((t) ((void *) ((lzo_uintptr_t) ((const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNCONST_CAST) +# define LZO_UNCONST_CAST(t,e) ((t) ((void *) ((const void *) (e)))) +#endif +#if !defined(LZO_UNCONST_VOLATILE_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNCONST_VOLATILE_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) ((volatile void *) ((lzo_uintptr_t) ((volatile const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNCONST_VOLATILE_CAST) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) ((volatile void *) ((volatile const void *) (e)))) +#endif +#if !defined(LZO_UNVOLATILE_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNVOLATILE_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNVOLATILE_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNVOLATILE_CAST(t,e) ((t) ((void *) ((lzo_uintptr_t) ((volatile void *) (e))))) +# endif +#endif +#if !defined(LZO_UNVOLATILE_CAST) +# define LZO_UNVOLATILE_CAST(t,e) ((t) ((void *) ((volatile void *) (e)))) +#endif +#if !defined(LZO_UNVOLATILE_CONST_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNVOLATILE_CONST_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) ((const void *) ((lzo_uintptr_t) ((volatile const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNVOLATILE_CONST_CAST) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) ((const void *) ((volatile const void *) (e)))) +#endif +#if !defined(LZO_PCAST) +# if (LZO_HAVE_MM_HUGE_PTR) +# define LZO_PCAST(t,e) ((t) (e)) +# endif +#endif +#if !defined(LZO_PCAST) +# define LZO_PCAST(t,e) LZO_STATIC_CAST(t, LZO_STATIC_CAST(void *, e)) +#endif +#if !defined(LZO_CCAST) +# if (LZO_HAVE_MM_HUGE_PTR) +# define LZO_CCAST(t,e) ((t) (e)) +# endif +#endif +#if !defined(LZO_CCAST) +# define LZO_CCAST(t,e) LZO_STATIC_CAST(t, LZO_STATIC_CAST(const void *, e)) +#endif +#if !defined(LZO_ICONV) +# define LZO_ICONV(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(LZO_ICAST) +# define LZO_ICAST(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(LZO_ITRUNC) +# define LZO_ITRUNC(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(__lzo_cte) +# if (LZO_CC_MSC || LZO_CC_WATCOMC) +# define __lzo_cte(e) ((void)0,(e)) +# elif 1 +# define __lzo_cte(e) ((void)0,(e)) +# endif +#endif +#if !defined(__lzo_cte) +# define __lzo_cte(e) (e) +#endif +#if !defined(LZO_BLOCK_BEGIN) +# define LZO_BLOCK_BEGIN do { +# define LZO_BLOCK_END } while __lzo_cte(0) +#endif +#if !defined(LZO_UNUSED) +# if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) +# define LZO_UNUSED(var) ((void) &var) +# elif (LZO_CC_BORLANDC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PELLESC || LZO_CC_TURBOC) +# define LZO_UNUSED(var) if (&var) ; else +# elif (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x030200ul)) +# define LZO_UNUSED(var) ((void) &var) +# elif (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNUSED(var) ((void) var) +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_UNUSED(var) if (&var) ; else +# elif (LZO_CC_KEILC) +# define LZO_UNUSED(var) {extern int lzo_unused__[1-2*!(sizeof(var)>0)]; (void)lzo_unused__;} +# elif (LZO_CC_PACIFICC) +# define LZO_UNUSED(var) ((void) sizeof(var)) +# elif (LZO_CC_WATCOMC) && defined(__cplusplus) +# define LZO_UNUSED(var) ((void) var) +# else +# define LZO_UNUSED(var) ((void) &var) +# endif +#endif +#if !defined(LZO_UNUSED_RESULT) +# define LZO_UNUSED_RESULT(var) LZO_UNUSED(var) +#endif +#if !defined(LZO_UNUSED_FUNC) +# if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) +# define LZO_UNUSED_FUNC(func) ((void) func) +# elif (LZO_CC_BORLANDC || LZO_CC_NDPC || LZO_CC_TURBOC) +# define LZO_UNUSED_FUNC(func) if (func) ; else +# elif (LZO_CC_CLANG || LZO_CC_LLVM) +# define LZO_UNUSED_FUNC(func) ((void) &func) +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_UNUSED_FUNC(func) if (func) ; else +# elif (LZO_CC_MSC) +# define LZO_UNUSED_FUNC(func) ((void) &func) +# elif (LZO_CC_KEILC || LZO_CC_PELLESC) +# define LZO_UNUSED_FUNC(func) {extern int lzo_unused__[1-2*!(sizeof((int)func)>0)]; (void)lzo_unused__;} +# else +# define LZO_UNUSED_FUNC(func) ((void) func) +# endif +#endif +#if !defined(LZO_UNUSED_LABEL) +# if (LZO_CC_CLANG >= 0x020800ul) +# define LZO_UNUSED_LABEL(l) (__lzo_gnuc_extension__ ((void) ((const void *) &&l))) +# elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_INTELC || LZO_CC_WATCOMC) +# define LZO_UNUSED_LABEL(l) if __lzo_cte(0) goto l +# else +# define LZO_UNUSED_LABEL(l) switch (0) case 1:goto l +# endif +#endif +#if !defined(LZO_DEFINE_UNINITIALIZED_VAR) +# if 0 +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var +# elif 0 && (LZO_CC_GNUC) +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = var +# else +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = init +# endif +#endif +#if !defined(__lzo_inline) +#if (LZO_CC_TURBOC && (__TURBOC__ <= 0x0295)) +#elif defined(__cplusplus) +# define __lzo_inline inline +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__-0 >= 199901L) +# define __lzo_inline inline +#elif (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0550)) +# define __lzo_inline __inline +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define __lzo_inline __inline__ +#elif (LZO_CC_DMC) +# define __lzo_inline __inline +#elif (LZO_CC_GHS) +# define __lzo_inline __inline__ +#elif (LZO_CC_IBMC >= 600) +# define __lzo_inline __inline__ +#elif (LZO_CC_INTELC) +# define __lzo_inline __inline +#elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x2405)) +# define __lzo_inline __inline +#elif (LZO_CC_MSC && (_MSC_VER >= 900)) +# define __lzo_inline __inline +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_inline __inline__ +#endif +#endif +#if defined(__lzo_inline) +# ifndef __lzo_HAVE_inline +# define __lzo_HAVE_inline 1 +# endif +#else +# define __lzo_inline /*empty*/ +#endif +#if !defined(__lzo_forceinline) +#if (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) +# define __lzo_forceinline __forceinline +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) +# define __lzo_forceinline __forceinline +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#endif +#endif +#if defined(__lzo_forceinline) +# ifndef __lzo_HAVE_forceinline +# define __lzo_HAVE_forceinline 1 +# endif +#else +# define __lzo_forceinline __lzo_inline +#endif +#if !defined(__lzo_noinline) +#if 1 && (LZO_ARCH_I386) && (LZO_CC_GNUC >= 0x040000ul) && (LZO_CC_GNUC < 0x040003ul) +# define __lzo_noinline __attribute__((__noinline__,__used__)) +#elif (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 600)) +# define __lzo_noinline __declspec(noinline) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_noinline __declspec(noinline) +#elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x3200) && (LZO_OS_WIN32 || LZO_OS_WIN64)) +# if defined(__cplusplus) +# else +# define __lzo_noinline __declspec(noinline) +# endif +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_noinline __attribute__((__noinline__)) +#endif +#endif +#if defined(__lzo_noinline) +# ifndef __lzo_HAVE_noinline +# define __lzo_HAVE_noinline 1 +# endif +#else +# define __lzo_noinline /*empty*/ +#endif +#if (__lzo_HAVE_forceinline || __lzo_HAVE_noinline) && !(__lzo_HAVE_inline) +# error "unexpected configuration - check your compiler defines" +#endif +#if !defined(__lzo_static_inline) +#if (LZO_CC_IBMC) +# define __lzo_static_inline __lzo_gnuc_extension__ static __lzo_inline +#endif +#endif +#if !defined(__lzo_static_inline) +# define __lzo_static_inline static __lzo_inline +#endif +#if !defined(__lzo_static_forceinline) +#if (LZO_CC_IBMC) +# define __lzo_static_forceinline __lzo_gnuc_extension__ static __lzo_forceinline +#endif +#endif +#if !defined(__lzo_static_forceinline) +# define __lzo_static_forceinline static __lzo_forceinline +#endif +#if !defined(__lzo_static_noinline) +#if (LZO_CC_IBMC) +# define __lzo_static_noinline __lzo_gnuc_extension__ static __lzo_noinline +#endif +#endif +#if !defined(__lzo_static_noinline) +# define __lzo_static_noinline static __lzo_noinline +#endif +#if !defined(__lzo_c99_extern_inline) +#if defined(__GNUC_GNU_INLINE__) +# define __lzo_c99_extern_inline __lzo_inline +#elif defined(__GNUC_STDC_INLINE__) +# define __lzo_c99_extern_inline extern __lzo_inline +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__-0 >= 199901L) +# define __lzo_c99_extern_inline extern __lzo_inline +#endif +#if !defined(__lzo_c99_extern_inline) && (__lzo_HAVE_inline) +# define __lzo_c99_extern_inline __lzo_inline +#endif +#endif +#if defined(__lzo_c99_extern_inline) +# ifndef __lzo_HAVE_c99_extern_inline +# define __lzo_HAVE_c99_extern_inline 1 +# endif +#else +# define __lzo_c99_extern_inline /*empty*/ +#endif +#if !defined(__lzo_may_alias) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_CLANG >= 0x020900ul) +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 1210)) && 0 +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_PGI >= 0x0d0a00ul) && 0 +# define __lzo_may_alias __attribute__((__may_alias__)) +#endif +#endif +#if defined(__lzo_may_alias) +# ifndef __lzo_HAVE_may_alias +# define __lzo_HAVE_may_alias 1 +# endif +#else +# define __lzo_may_alias /*empty*/ +#endif +#if !defined(__lzo_noreturn) +#if (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) +# define __lzo_noreturn __declspec(noreturn) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 600)) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) +# define __lzo_noreturn __declspec(noreturn) +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_noreturn __attribute__((__noreturn__)) +#endif +#endif +#if defined(__lzo_noreturn) +# ifndef __lzo_HAVE_noreturn +# define __lzo_HAVE_noreturn 1 +# endif +#else +# define __lzo_noreturn /*empty*/ +#endif +#if !defined(__lzo_nothrow) +#if (LZO_CC_GNUC >= 0x030300ul) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) && defined(__cplusplus) +# define __lzo_nothrow __declspec(nothrow) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 900)) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) && defined(__cplusplus) +# define __lzo_nothrow __declspec(nothrow) +#endif +#endif +#if defined(__lzo_nothrow) +# ifndef __lzo_HAVE_nothrow +# define __lzo_HAVE_nothrow 1 +# endif +#else +# define __lzo_nothrow /*empty*/ +#endif +#if !defined(__lzo_restrict) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_IBMC >= 800) && !defined(__cplusplus) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_IBMC >= 1210) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 600)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 600)) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_MSC && (_MSC_VER >= 1400)) +# define __lzo_restrict __restrict +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_restrict __restrict__ +#endif +#endif +#if defined(__lzo_restrict) +# ifndef __lzo_HAVE_restrict +# define __lzo_HAVE_restrict 1 +# endif +#else +# define __lzo_restrict /*empty*/ +#endif +#if !defined(__lzo_alignof) +#if (LZO_CC_ARMCC || LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_GHS) && !defined(__cplusplus) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_IBMC >= 600) +# define __lzo_alignof(e) (__lzo_gnuc_extension__ __alignof__(e)) +#elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 700)) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_alignof(e) __alignof(e) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_alignof(e) __alignof__(e) +#endif +#endif +#if defined(__lzo_alignof) +# ifndef __lzo_HAVE_alignof +# define __lzo_HAVE_alignof 1 +# endif +#endif +#if !defined(__lzo_struct_packed) +#if (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020700ul)) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_PCC && (LZO_CC_PCC < 0x010100ul)) +#elif (LZO_CC_SUNPROC && (LZO_CC_SUNPROC < 0x5110)) && !defined(__cplusplus) +#elif (LZO_CC_GNUC >= 0x030400ul) && !(LZO_CC_PCC_GNUC) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) +# define __lzo_struct_packed(s) struct s { +# define __lzo_struct_packed_end() } __attribute__((__gcc_struct__,__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__gcc_struct__,__packed__)); +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || (LZO_CC_PGI >= 0x0d0a00ul) || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_struct_packed(s) struct s { +# define __lzo_struct_packed_end() } __attribute__((__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_IBMC >= 700) +# define __lzo_struct_packed(s) __lzo_gnuc_extension__ struct s { +# define __lzo_struct_packed_end() } __attribute__((__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_struct_packed(s) __pragma(pack(push,1)) struct s { +# define __lzo_struct_packed_end() } __pragma(pack(pop)); +#elif (LZO_CC_WATCOMC && (__WATCOMC__ >= 900)) +# define __lzo_struct_packed(s) _Packed struct s { +# define __lzo_struct_packed_end() }; +#endif +#endif +#if defined(__lzo_struct_packed) && !defined(__lzo_struct_packed_ma) +# define __lzo_struct_packed_ma(s) __lzo_struct_packed(s) +#endif +#if defined(__lzo_struct_packed_end) && !defined(__lzo_struct_packed_ma_end) +# define __lzo_struct_packed_ma_end() __lzo_struct_packed_end() +#endif +#if !defined(__lzo_byte_struct) +#if defined(__lzo_struct_packed) +# define __lzo_byte_struct(s,n) __lzo_struct_packed(s) unsigned char a[n]; __lzo_struct_packed_end() +# define __lzo_byte_struct_ma(s,n) __lzo_struct_packed_ma(s) unsigned char a[n]; __lzo_struct_packed_ma_end() +#elif (LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_PGI || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_byte_struct(s,n) struct s { unsigned char a[n]; } __attribute__((__packed__)); +# define __lzo_byte_struct_ma(s,n) struct s { unsigned char a[n]; } __lzo_may_alias __attribute__((__packed__)); +#endif +#endif +#if defined(__lzo_byte_struct) && !defined(__lzo_byte_struct_ma) +# define __lzo_byte_struct_ma(s,n) __lzo_byte_struct(s,n) +#endif +#if !defined(__lzo_struct_align16) && (__lzo_HAVE_alignof) +#if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x030000ul)) +#elif (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_CILLY || LZO_CC_PCC) +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_struct_align16(s) struct __declspec(align(16)) s { +# define __lzo_struct_align16_end() }; +# define __lzo_struct_align32(s) struct __declspec(align(32)) s { +# define __lzo_struct_align32_end() }; +# define __lzo_struct_align64(s) struct __declspec(align(64)) s { +# define __lzo_struct_align64_end() }; +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || (LZO_CC_IBMC >= 700) || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_struct_align16(s) struct s { +# define __lzo_struct_align16_end() } __attribute__((__aligned__(16))); +# define __lzo_struct_align32(s) struct s { +# define __lzo_struct_align32_end() } __attribute__((__aligned__(32))); +# define __lzo_struct_align64(s) struct s { +# define __lzo_struct_align64_end() } __attribute__((__aligned__(64))); +#endif +#endif +#if !defined(__lzo_union_um) +#if (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020700ul)) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER < 810)) +#elif (LZO_CC_PCC && (LZO_CC_PCC < 0x010100ul)) +#elif (LZO_CC_SUNPROC && (LZO_CC_SUNPROC < 0x5110)) && !defined(__cplusplus) +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || (LZO_CC_PGI >= 0x0d0a00ul) || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_union_am(s) union s { +# define __lzo_union_am_end() } __lzo_may_alias; +# define __lzo_union_um(s) union s { +# define __lzo_union_um_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_IBMC >= 700) +# define __lzo_union_am(s) __lzo_gnuc_extension__ union s { +# define __lzo_union_am_end() } __lzo_may_alias; +# define __lzo_union_um(s) __lzo_gnuc_extension__ union s { +# define __lzo_union_um_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_union_um(s) __pragma(pack(push,1)) union s { +# define __lzo_union_um_end() } __pragma(pack(pop)); +#elif (LZO_CC_WATCOMC && (__WATCOMC__ >= 900)) +# define __lzo_union_um(s) _Packed union s { +# define __lzo_union_um_end() }; +#endif +#endif +#if !defined(__lzo_union_am) +# define __lzo_union_am(s) union s { +# define __lzo_union_am_end() }; +#endif +#if !defined(__lzo_constructor) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_constructor __attribute__((__constructor__,__used__)) +#elif (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_constructor __attribute__((__constructor__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_constructor __attribute__((__constructor__,__used__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_constructor __attribute__((__constructor__)) +#endif +#endif +#if defined(__lzo_constructor) +# ifndef __lzo_HAVE_constructor +# define __lzo_HAVE_constructor 1 +# endif +#endif +#if !defined(__lzo_destructor) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_destructor __attribute__((__destructor__,__used__)) +#elif (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_destructor __attribute__((__destructor__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_destructor __attribute__((__destructor__,__used__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_destructor __attribute__((__destructor__)) +#endif +#endif +#if defined(__lzo_destructor) +# ifndef __lzo_HAVE_destructor +# define __lzo_HAVE_destructor 1 +# endif +#endif +#if (__lzo_HAVE_destructor) && !(__lzo_HAVE_constructor) +# error "unexpected configuration - check your compiler defines" +#endif +#if !defined(__lzo_likely) && !defined(__lzo_unlikely) +#if (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_IBMC >= 1010) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800)) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_CLANG && LZO_CC_CLANG_C2) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#endif +#endif +#if defined(__lzo_likely) +# ifndef __lzo_HAVE_likely +# define __lzo_HAVE_likely 1 +# endif +#else +# define __lzo_likely(e) (e) +#endif +#if defined(__lzo_very_likely) +# ifndef __lzo_HAVE_very_likely +# define __lzo_HAVE_very_likely 1 +# endif +#else +# define __lzo_very_likely(e) __lzo_likely(e) +#endif +#if defined(__lzo_unlikely) +# ifndef __lzo_HAVE_unlikely +# define __lzo_HAVE_unlikely 1 +# endif +#else +# define __lzo_unlikely(e) (e) +#endif +#if defined(__lzo_very_unlikely) +# ifndef __lzo_HAVE_very_unlikely +# define __lzo_HAVE_very_unlikely 1 +# endif +#else +# define __lzo_very_unlikely(e) __lzo_unlikely(e) +#endif +#if !defined(__lzo_loop_forever) +# if (LZO_CC_IBMC) +# define __lzo_loop_forever() LZO_BLOCK_BEGIN for (;;) { ; } LZO_BLOCK_END +# else +# define __lzo_loop_forever() do { ; } while __lzo_cte(1) +# endif +#endif +#if !defined(__lzo_unreachable) +#if (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x020800ul)) && lzo_has_builtin(__builtin_unreachable) +# define __lzo_unreachable() __builtin_unreachable(); +#elif (LZO_CC_GNUC >= 0x040500ul) +# define __lzo_unreachable() __builtin_unreachable(); +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 1300)) && 1 +# define __lzo_unreachable() __builtin_unreachable(); +#endif +#endif +#if defined(__lzo_unreachable) +# ifndef __lzo_HAVE_unreachable +# define __lzo_HAVE_unreachable 1 +# endif +#else +# if 0 +# define __lzo_unreachable() ((void)0); +# else +# define __lzo_unreachable() __lzo_loop_forever(); +# endif +#endif +#if !defined(lzo_unused_funcs_impl) +# if 1 && (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || (LZO_CC_GNUC >= 0x020700ul) || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define lzo_unused_funcs_impl(r,f) static r __attribute__((__unused__)) f +# elif 1 && (LZO_CC_BORLANDC || LZO_CC_GNUC) +# define lzo_unused_funcs_impl(r,f) static r f +# else +# define lzo_unused_funcs_impl(r,f) __lzo_static_forceinline r f +# endif +#endif +#ifndef __LZO_CTA_NAME +#if (LZO_CFG_USE_COUNTER) +# define __LZO_CTA_NAME(a) LZO_PP_ECONCAT2(a,__COUNTER__) +#else +# define __LZO_CTA_NAME(a) LZO_PP_ECONCAT2(a,__LINE__) +#endif +#endif +#if !defined(LZO_COMPILE_TIME_ASSERT_HEADER) +# if (LZO_CC_AZTECC || LZO_CC_ZORTECHC) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_DMC || LZO_CC_SYMANTECC) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1u-2*!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020900ul)) && defined(__cplusplus) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN int __LZO_CTA_NAME(lzo_cta_f__)(int [1-2*!(e)]); LZO_EXTERN_C_END +# elif (LZO_CC_GNUC) && defined(__CHECKER__) && defined(__SPARSE_CHECKER__) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN enum {__LZO_CTA_NAME(lzo_cta_e__)=1/!!(e)} __attribute__((__unused__)); LZO_EXTERN_C_END +# else +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-2*!(e)]; LZO_EXTERN_C_END +# endif +#endif +#if !defined(LZO_COMPILE_TIME_ASSERT) +# if (LZO_CC_AZTECC) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-!(e)];} +# elif (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x030000ul)) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)] __attribute__((__unused__));} +# elif (LZO_CC_DMC || LZO_CC_PACIFICC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# elif (LZO_CC_GNUC) && defined(__CHECKER__) && defined(__SPARSE_CHECKER__) +# define LZO_COMPILE_TIME_ASSERT(e) {(void) (0/!!(e));} +# elif (LZO_CC_GNUC >= 0x040700ul) && (LZO_CFG_USE_COUNTER) && defined(__cplusplus) +# define LZO_COMPILE_TIME_ASSERT(e) {enum {__LZO_CTA_NAME(lzo_cta_e__)=1/!!(e)} __attribute__((__unused__));} +# elif (LZO_CC_GNUC >= 0x040700ul) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)] __attribute__((__unused__));} +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# else +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)];} +# endif +#endif +#if (LZO_LANG_ASSEMBLER) +# undef LZO_COMPILE_TIME_ASSERT_HEADER +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) /*empty*/ +#else +LZO_COMPILE_TIME_ASSERT_HEADER(1 == 1) +#if defined(__cplusplus) +extern "C" { LZO_COMPILE_TIME_ASSERT_HEADER(2 == 2) } +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(3 == 3) +#endif +#if (LZO_ARCH_I086 || LZO_ARCH_I386) && (LZO_OS_DOS16 || LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_OS216 || LZO_OS_WIN16 || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC) +# elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) +# define __lzo_cdecl __cdecl +# define __lzo_cdecl_atexit /*empty*/ +# define __lzo_cdecl_main __cdecl +# if (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) +# define __lzo_cdecl_qsort __pascal +# elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) +# define __lzo_cdecl_qsort _stdcall +# else +# define __lzo_cdecl_qsort __cdecl +# endif +# elif (LZO_CC_WATCOMC) +# define __lzo_cdecl __cdecl +# else +# define __lzo_cdecl __cdecl +# define __lzo_cdecl_atexit __cdecl +# define __lzo_cdecl_main __cdecl +# define __lzo_cdecl_qsort __cdecl +# endif +# if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC || LZO_CC_WATCOMC) +# elif (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) +# define __lzo_cdecl_sighandler __pascal +# elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) +# define __lzo_cdecl_sighandler _stdcall +# elif (LZO_CC_MSC && (_MSC_VER >= 1400)) && defined(_M_CEE_PURE) +# define __lzo_cdecl_sighandler __clrcall +# elif (LZO_CC_MSC && (_MSC_VER >= 600 && _MSC_VER < 700)) +# if defined(_DLL) +# define __lzo_cdecl_sighandler _far _cdecl _loadds +# elif defined(_MT) +# define __lzo_cdecl_sighandler _far _cdecl +# else +# define __lzo_cdecl_sighandler _cdecl +# endif +# else +# define __lzo_cdecl_sighandler __cdecl +# endif +#elif (LZO_ARCH_I386) && (LZO_CC_WATCOMC) +# define __lzo_cdecl __cdecl +#elif (LZO_ARCH_M68K && LZO_OS_TOS && (LZO_CC_PUREC || LZO_CC_TURBOC)) +# define __lzo_cdecl cdecl +#endif +#if !defined(__lzo_cdecl) +# define __lzo_cdecl /*empty*/ +#endif +#if !defined(__lzo_cdecl_atexit) +# define __lzo_cdecl_atexit /*empty*/ +#endif +#if !defined(__lzo_cdecl_main) +# define __lzo_cdecl_main /*empty*/ +#endif +#if !defined(__lzo_cdecl_qsort) +# define __lzo_cdecl_qsort /*empty*/ +#endif +#if !defined(__lzo_cdecl_sighandler) +# define __lzo_cdecl_sighandler /*empty*/ +#endif +#if !defined(__lzo_cdecl_va) +# define __lzo_cdecl_va __lzo_cdecl +#endif +#if !(LZO_CFG_NO_WINDOWS_H) +#if !defined(LZO_HAVE_WINDOWS_H) +#if (LZO_OS_CYGWIN || (LZO_OS_EMX && defined(__RSXNT__)) || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (LZO_CC_WATCOMC && (__WATCOMC__ < 1000)) +# elif ((LZO_OS_WIN32 && defined(__PW32__)) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x030000ul))) +# elif ((LZO_OS_CYGWIN || defined(__MINGW32__)) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x025f00ul))) +# else +# define LZO_HAVE_WINDOWS_H 1 +# endif +#endif +#endif +#endif +#define LZO_SIZEOF_CHAR 1 +#ifndef LZO_SIZEOF_SHORT +#if defined(SIZEOF_SHORT) +# define LZO_SIZEOF_SHORT (SIZEOF_SHORT) +#elif defined(__SIZEOF_SHORT__) +# define LZO_SIZEOF_SHORT (__SIZEOF_SHORT__) +#endif +#endif +#ifndef LZO_SIZEOF_INT +#if defined(SIZEOF_INT) +# define LZO_SIZEOF_INT (SIZEOF_INT) +#elif defined(__SIZEOF_INT__) +# define LZO_SIZEOF_INT (__SIZEOF_INT__) +#endif +#endif +#ifndef LZO_SIZEOF_LONG +#if defined(SIZEOF_LONG) +# define LZO_SIZEOF_LONG (SIZEOF_LONG) +#elif defined(__SIZEOF_LONG__) +# define LZO_SIZEOF_LONG (__SIZEOF_LONG__) +#endif +#endif +#ifndef LZO_SIZEOF_LONG_LONG +#if defined(SIZEOF_LONG_LONG) +# define LZO_SIZEOF_LONG_LONG (SIZEOF_LONG_LONG) +#elif defined(__SIZEOF_LONG_LONG__) +# define LZO_SIZEOF_LONG_LONG (__SIZEOF_LONG_LONG__) +#endif +#endif +#ifndef LZO_SIZEOF___INT16 +#if defined(SIZEOF___INT16) +# define LZO_SIZEOF___INT16 (SIZEOF___INT16) +#endif +#endif +#ifndef LZO_SIZEOF___INT32 +#if defined(SIZEOF___INT32) +# define LZO_SIZEOF___INT32 (SIZEOF___INT32) +#endif +#endif +#ifndef LZO_SIZEOF___INT64 +#if defined(SIZEOF___INT64) +# define LZO_SIZEOF___INT64 (SIZEOF___INT64) +#endif +#endif +#ifndef LZO_SIZEOF_VOID_P +#if defined(SIZEOF_VOID_P) +# define LZO_SIZEOF_VOID_P (SIZEOF_VOID_P) +#elif defined(__SIZEOF_POINTER__) +# define LZO_SIZEOF_VOID_P (__SIZEOF_POINTER__) +#endif +#endif +#ifndef LZO_SIZEOF_SIZE_T +#if defined(SIZEOF_SIZE_T) +# define LZO_SIZEOF_SIZE_T (SIZEOF_SIZE_T) +#elif defined(__SIZEOF_SIZE_T__) +# define LZO_SIZEOF_SIZE_T (__SIZEOF_SIZE_T__) +#endif +#endif +#ifndef LZO_SIZEOF_PTRDIFF_T +#if defined(SIZEOF_PTRDIFF_T) +# define LZO_SIZEOF_PTRDIFF_T (SIZEOF_PTRDIFF_T) +#elif defined(__SIZEOF_PTRDIFF_T__) +# define LZO_SIZEOF_PTRDIFF_T (__SIZEOF_PTRDIFF_T__) +#endif +#endif +#define __LZO_LSR(x,b) (((x)+0ul) >> (b)) +#if !defined(LZO_SIZEOF_SHORT) +# if (LZO_ARCH_CRAY_PVP) +# define LZO_SIZEOF_SHORT 8 +# elif (USHRT_MAX == LZO_0xffffL) +# define LZO_SIZEOF_SHORT 2 +# elif (__LZO_LSR(USHRT_MAX,7) == 1) +# define LZO_SIZEOF_SHORT 1 +# elif (__LZO_LSR(USHRT_MAX,15) == 1) +# define LZO_SIZEOF_SHORT 2 +# elif (__LZO_LSR(USHRT_MAX,31) == 1) +# define LZO_SIZEOF_SHORT 4 +# elif (__LZO_LSR(USHRT_MAX,63) == 1) +# define LZO_SIZEOF_SHORT 8 +# elif (__LZO_LSR(USHRT_MAX,127) == 1) +# define LZO_SIZEOF_SHORT 16 +# else +# error "LZO_SIZEOF_SHORT" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_SHORT == sizeof(short)) +#if !defined(LZO_SIZEOF_INT) +# if (LZO_ARCH_CRAY_PVP) +# define LZO_SIZEOF_INT 8 +# elif (UINT_MAX == LZO_0xffffL) +# define LZO_SIZEOF_INT 2 +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_SIZEOF_INT 4 +# elif (__LZO_LSR(UINT_MAX,7) == 1) +# define LZO_SIZEOF_INT 1 +# elif (__LZO_LSR(UINT_MAX,15) == 1) +# define LZO_SIZEOF_INT 2 +# elif (__LZO_LSR(UINT_MAX,31) == 1) +# define LZO_SIZEOF_INT 4 +# elif (__LZO_LSR(UINT_MAX,63) == 1) +# define LZO_SIZEOF_INT 8 +# elif (__LZO_LSR(UINT_MAX,127) == 1) +# define LZO_SIZEOF_INT 16 +# else +# error "LZO_SIZEOF_INT" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_INT == sizeof(int)) +#if !defined(LZO_SIZEOF_LONG) +# if (ULONG_MAX == LZO_0xffffffffL) +# define LZO_SIZEOF_LONG 4 +# elif (__LZO_LSR(ULONG_MAX,7) == 1) +# define LZO_SIZEOF_LONG 1 +# elif (__LZO_LSR(ULONG_MAX,15) == 1) +# define LZO_SIZEOF_LONG 2 +# elif (__LZO_LSR(ULONG_MAX,31) == 1) +# define LZO_SIZEOF_LONG 4 +# elif (__LZO_LSR(ULONG_MAX,39) == 1) +# define LZO_SIZEOF_LONG 5 +# elif (__LZO_LSR(ULONG_MAX,63) == 1) +# define LZO_SIZEOF_LONG 8 +# elif (__LZO_LSR(ULONG_MAX,127) == 1) +# define LZO_SIZEOF_LONG 16 +# else +# error "LZO_SIZEOF_LONG" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_LONG == sizeof(long)) +#if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) +#if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) +# if defined(__LONG_MAX__) && defined(__LONG_LONG_MAX__) +# if (LZO_CC_GNUC >= 0x030300ul) +# if ((__LONG_MAX__-0) == (__LONG_LONG_MAX__-0)) +# define LZO_SIZEOF_LONG_LONG LZO_SIZEOF_LONG +# elif (__LZO_LSR(__LONG_LONG_MAX__,30) == 1) +# define LZO_SIZEOF_LONG_LONG 4 +# endif +# endif +# endif +#endif +#endif +#if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) +#if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) +#if (LZO_ARCH_I086 && LZO_CC_DMC) +#elif (LZO_CC_CILLY) && defined(__GNUC__) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_SIZEOF_LONG_LONG 8 +#elif ((LZO_OS_WIN32 || LZO_OS_WIN64 || defined(_WIN32)) && LZO_CC_MSC && (_MSC_VER >= 1400)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_OS_WIN64 || defined(_WIN64)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_DMC)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_SYMANTECC && (__SC__ >= 0x700))) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_INTELC && defined(__linux__))) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_MWERKS || LZO_CC_PELLESC || LZO_CC_PGI || LZO_CC_SUNPROC)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_INTELC || LZO_CC_MSC)) +# define LZO_SIZEOF___INT64 8 +#elif ((LZO_OS_WIN32 || defined(_WIN32)) && (LZO_CC_MSC)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0520))) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_WATCOMC && (__WATCOMC__ >= 1100))) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_CC_GHS && defined(__LLONG_BIT) && ((__LLONG_BIT-0) == 64)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_WATCOMC && defined(_INTEGRAL_MAX_BITS) && ((_INTEGRAL_MAX_BITS-0) == 64)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_OS_OS400 || defined(__OS400__)) && defined(__LLP64_IFC__) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (defined(__vms) || defined(__VMS)) && ((__INITIAL_POINTER_SIZE-0) == 64) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_SDCC) && (LZO_SIZEOF_INT == 2) +#elif 1 && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) +# define LZO_SIZEOF_LONG_LONG 8 +#endif +#endif +#endif +#if defined(__cplusplus) && (LZO_CC_GNUC) +# if (LZO_CC_GNUC < 0x020800ul) +# undef LZO_SIZEOF_LONG_LONG +# endif +#endif +#if (LZO_CFG_NO_LONG_LONG) +# undef LZO_SIZEOF_LONG_LONG +#elif defined(__NO_LONG_LONG) +# undef LZO_SIZEOF_LONG_LONG +#elif defined(_NO_LONGLONG) +# undef LZO_SIZEOF_LONG_LONG +#endif +#if !defined(LZO_WORDSIZE) +#if (LZO_ARCH_ALPHA) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_AMD64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_ARM64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_AVR) +# define LZO_WORDSIZE 1 +#elif (LZO_ARCH_H8300) +# if defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) +# define LZO_WORDSIZE 4 +# else +# define LZO_WORDSIZE 2 +# endif +#elif (LZO_ARCH_I086) +# define LZO_WORDSIZE 2 +#elif (LZO_ARCH_IA64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_M16C) +# define LZO_WORDSIZE 2 +#elif (LZO_ARCH_SPU) +# define LZO_WORDSIZE 4 +#elif (LZO_ARCH_Z80) +# define LZO_WORDSIZE 1 +#elif (LZO_SIZEOF_LONG == 8) && ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) +# define LZO_WORDSIZE 8 +#elif (LZO_OS_OS400 || defined(__OS400__)) +# define LZO_WORDSIZE 8 +#elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) +# define LZO_WORDSIZE 8 +#endif +#endif +#if !defined(LZO_SIZEOF_VOID_P) +#if defined(__ILP32__) || defined(__ILP32) || defined(_ILP32) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(int) == 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 4) +# define LZO_SIZEOF_VOID_P 4 +#elif defined(__ILP64__) || defined(__ILP64) || defined(_ILP64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(int) == 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 8) +# define LZO_SIZEOF_VOID_P 8 +#elif defined(__LLP64__) || defined(__LLP64) || defined(_LLP64) || defined(_WIN64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 4) +# define LZO_SIZEOF_VOID_P 8 +#elif defined(__LP64__) || defined(__LP64) || defined(_LP64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 8) +# define LZO_SIZEOF_VOID_P 8 +#elif (LZO_ARCH_AVR) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_ARCH_C166 || LZO_ARCH_MCS51 || LZO_ARCH_MCS251 || LZO_ARCH_MSP430) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_ARCH_H8300) +# if defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) + LZO_COMPILE_TIME_ASSERT_HEADER(LZO_WORDSIZE == 4) +# if defined(__NORMAL_MODE__) +# define LZO_SIZEOF_VOID_P 2 +# else +# define LZO_SIZEOF_VOID_P 4 +# endif +# else + LZO_COMPILE_TIME_ASSERT_HEADER(LZO_WORDSIZE == 2) +# define LZO_SIZEOF_VOID_P 2 +# endif +# if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x040000ul)) && (LZO_SIZEOF_INT == 4) +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_INT +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_INT +# endif +#elif (LZO_ARCH_I086) +# if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM) +# define LZO_SIZEOF_VOID_P 2 +# elif (LZO_MM_COMPACT || LZO_MM_LARGE || LZO_MM_HUGE) +# define LZO_SIZEOF_VOID_P 4 +# else +# error "invalid LZO_ARCH_I086 memory model" +# endif +#elif (LZO_ARCH_M16C) +# if defined(__m32c_cpu__) || defined(__m32cm_cpu__) +# define LZO_SIZEOF_VOID_P 4 +# else +# define LZO_SIZEOF_VOID_P 2 +# endif +#elif (LZO_ARCH_SPU) +# define LZO_SIZEOF_VOID_P 4 +#elif (LZO_ARCH_Z80) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_SIZEOF_LONG == 8) && ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) +# define LZO_SIZEOF_VOID_P 4 +#elif (LZO_OS_OS400 || defined(__OS400__)) +# if defined(__LLP64_IFC__) +# define LZO_SIZEOF_VOID_P 8 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +# else +# define LZO_SIZEOF_VOID_P 16 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +# endif +#elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) +# define LZO_SIZEOF_VOID_P 8 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +#endif +#endif +#if !defined(LZO_SIZEOF_VOID_P) +# define LZO_SIZEOF_VOID_P LZO_SIZEOF_LONG +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_VOID_P == sizeof(void *)) +#if !defined(LZO_SIZEOF_SIZE_T) +#if (LZO_ARCH_I086 || LZO_ARCH_M16C) +# define LZO_SIZEOF_SIZE_T 2 +#endif +#endif +#if !defined(LZO_SIZEOF_SIZE_T) +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_VOID_P +#endif +#if defined(offsetof) +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_SIZE_T == sizeof(size_t)) +#endif +#if !defined(LZO_SIZEOF_PTRDIFF_T) +#if (LZO_ARCH_I086) +# if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM || LZO_MM_HUGE) +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_VOID_P +# elif (LZO_MM_COMPACT || LZO_MM_LARGE) +# if (LZO_CC_BORLANDC || LZO_CC_TURBOC) +# define LZO_SIZEOF_PTRDIFF_T 4 +# else +# define LZO_SIZEOF_PTRDIFF_T 2 +# endif +# else +# error "invalid LZO_ARCH_I086 memory model" +# endif +#endif +#endif +#if !defined(LZO_SIZEOF_PTRDIFF_T) +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_SIZE_T +#endif +#if defined(offsetof) +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_PTRDIFF_T == sizeof(ptrdiff_t)) +#endif +#if !defined(LZO_WORDSIZE) +# define LZO_WORDSIZE LZO_SIZEOF_VOID_P +#endif +#if (LZO_ABI_NEUTRAL_ENDIAN) +# undef LZO_ABI_BIG_ENDIAN +# undef LZO_ABI_LITTLE_ENDIAN +#elif !(LZO_ABI_BIG_ENDIAN) && !(LZO_ABI_LITTLE_ENDIAN) +#if (LZO_ARCH_ALPHA) && (LZO_ARCH_CRAY_MPP) +# define LZO_ABI_BIG_ENDIAN 1 +#elif (LZO_ARCH_IA64) && (LZO_OS_POSIX_LINUX || LZO_OS_WIN64) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif (LZO_ARCH_ALPHA || LZO_ARCH_AMD64 || LZO_ARCH_BLACKFIN || LZO_ARCH_CRIS || LZO_ARCH_I086 || LZO_ARCH_I386 || LZO_ARCH_MSP430 || LZO_ARCH_RISCV) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif (LZO_ARCH_AVR32 || LZO_ARCH_M68K || LZO_ARCH_S390 || LZO_ARCH_SPU) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && defined(__IAR_SYSTEMS_ICC__) && defined(__LITTLE_ENDIAN__) +# if (__LITTLE_ENDIAN__ == 1) +# define LZO_ABI_LITTLE_ENDIAN 1 +# else +# define LZO_ABI_BIG_ENDIAN 1 +# endif +#elif 1 && defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARM_BIG_ENDIAN) && ((__ARM_BIG_ENDIAN)+0) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARMEB__) && !defined(__ARMEL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARMEL__) && !defined(__ARMEB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(_MSC_VER) && defined(_WIN32) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM && LZO_CC_ARMCC_ARMCC) +# if defined(__BIG_ENDIAN) && defined(__LITTLE_ENDIAN) +# error "unexpected configuration - check your compiler defines" +# elif defined(__BIG_ENDIAN) +# define LZO_ABI_BIG_ENDIAN 1 +# else +# define LZO_ABI_LITTLE_ENDIAN 1 +# endif +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__ARM_BIG_ENDIAN) && ((__ARM_BIG_ENDIAN)+0) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__AARCH64EB__) && !defined(__AARCH64EL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__AARCH64EL__) && !defined(__AARCH64EB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(_MSC_VER) && defined(_WIN32) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEB__) && !defined(__MIPSEL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEL__) && !defined(__MIPSEB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#endif +#endif +#if (LZO_ABI_BIG_ENDIAN) && (LZO_ABI_LITTLE_ENDIAN) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ABI_BIG_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "be" +#elif (LZO_ABI_LITTLE_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "le" +#elif (LZO_ABI_NEUTRAL_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "neutral" +#endif +#if (LZO_SIZEOF_INT == 1 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) +# define LZO_ABI_I8LP16 1 +# define LZO_INFO_ABI_PM "i8lp16" +#elif (LZO_SIZEOF_INT == 2 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) +# define LZO_ABI_ILP16 1 +# define LZO_INFO_ABI_PM "ilp16" +#elif (LZO_SIZEOF_INT == 2 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_LP32 1 +# define LZO_INFO_ABI_PM "lp32" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_ILP32 1 +# define LZO_INFO_ABI_PM "ilp32" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 8 && LZO_SIZEOF_SIZE_T == 8) +# define LZO_ABI_LLP64 1 +# define LZO_INFO_ABI_PM "llp64" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) +# define LZO_ABI_LP64 1 +# define LZO_INFO_ABI_PM "lp64" +#elif (LZO_SIZEOF_INT == 8 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) +# define LZO_ABI_ILP64 1 +# define LZO_INFO_ABI_PM "ilp64" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_IP32L64 1 +# define LZO_INFO_ABI_PM "ip32l64" +#endif +#if (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_VOID_P == 4 && LZO_WORDSIZE == 8) +# define LZO_ABI_IP32W64 1 +# ifndef LZO_INFO_ABI_PM +# define LZO_INFO_ABI_PM "ip32w64" +# endif +#endif +#if 0 +#elif !defined(__LZO_LIBC_OVERRIDE) +#if (LZO_LIBC_NAKED) +# define LZO_INFO_LIBC "naked" +#elif (LZO_LIBC_FREESTANDING) +# define LZO_INFO_LIBC "freestanding" +#elif (LZO_LIBC_MOSTLY_FREESTANDING) +# define LZO_INFO_LIBC "mfreestanding" +#elif (LZO_LIBC_ISOC90) +# define LZO_INFO_LIBC "isoc90" +#elif (LZO_LIBC_ISOC99) +# define LZO_INFO_LIBC "isoc99" +#elif (LZO_CC_ARMCC_ARMCC) && defined(__ARMCLIB_VERSION) +# define LZO_LIBC_ISOC90 1 +# define LZO_INFO_LIBC "isoc90" +#elif defined(__dietlibc__) +# define LZO_LIBC_DIETLIBC 1 +# define LZO_INFO_LIBC "dietlibc" +#elif defined(_NEWLIB_VERSION) +# define LZO_LIBC_NEWLIB 1 +# define LZO_INFO_LIBC "newlib" +#elif defined(__UCLIBC__) && defined(__UCLIBC_MAJOR__) && defined(__UCLIBC_MINOR__) +# if defined(__UCLIBC_SUBLEVEL__) +# define LZO_LIBC_UCLIBC (__UCLIBC_MAJOR__ * 0x10000L + (__UCLIBC_MINOR__-0) * 0x100 + (__UCLIBC_SUBLEVEL__-0)) +# else +# define LZO_LIBC_UCLIBC 0x00090bL +# endif +# define LZO_INFO_LIBC "uc" "libc" +#elif defined(__GLIBC__) && defined(__GLIBC_MINOR__) +# define LZO_LIBC_GLIBC (__GLIBC__ * 0x10000L + (__GLIBC_MINOR__-0) * 0x100) +# define LZO_INFO_LIBC "glibc" +#elif (LZO_CC_MWERKS) && defined(__MSL__) +# define LZO_LIBC_MSL __MSL__ +# define LZO_INFO_LIBC "msl" +#elif 1 && defined(__IAR_SYSTEMS_ICC__) +# define LZO_LIBC_ISOC90 1 +# define LZO_INFO_LIBC "isoc90" +#else +# define LZO_LIBC_DEFAULT 1 +# define LZO_INFO_LIBC "default" +#endif +#endif +#if (LZO_ARCH_I386 && (LZO_OS_DOS32 || LZO_OS_WIN32) && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) +# define LZO_ASM_SYNTAX_MSC 1 +#elif (LZO_OS_WIN64 && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) +#elif (LZO_ARCH_I386 && LZO_CC_GNUC && (LZO_CC_GNUC == 0x011f00ul)) +#elif (LZO_ARCH_I386 && (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) +# define LZO_ASM_SYNTAX_GNUC 1 +#elif (LZO_ARCH_AMD64 && (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) +# define LZO_ASM_SYNTAX_GNUC 1 +#elif (LZO_CC_GNUC) +# define LZO_ASM_SYNTAX_GNUC 1 +#endif +#if (LZO_ASM_SYNTAX_GNUC) +#if (LZO_ARCH_I386 && LZO_CC_GNUC && (LZO_CC_GNUC < 0x020000ul)) +# define __LZO_ASM_CLOBBER "ax" +# define __LZO_ASM_CLOBBER_LIST_CC /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#elif (LZO_CC_INTELC && (__INTEL_COMPILER < 1000)) +# define __LZO_ASM_CLOBBER "memory" +# define __LZO_ASM_CLOBBER_LIST_CC /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY : "memory" +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#else +# define __LZO_ASM_CLOBBER "cc", "memory" +# define __LZO_ASM_CLOBBER_LIST_CC : "cc" +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY : "cc", "memory" +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#endif +#endif +#if (LZO_ARCH_ALPHA) +# define LZO_OPT_AVOID_UINT_INDEX 1 +#elif (LZO_ARCH_AMD64) +# define LZO_OPT_AVOID_INT_INDEX 1 +# define LZO_OPT_AVOID_UINT_INDEX 1 +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +#elif (LZO_ARCH_ARM) +# if defined(__ARM_FEATURE_UNALIGNED) +# if ((__ARM_FEATURE_UNALIGNED)+0) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +# elif 1 && (LZO_ARCH_ARM_THUMB2) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__ARM_ARCH) && ((__ARM_ARCH)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__TARGET_ARCH_ARM) && ((__TARGET_ARCH_ARM)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__TARGET_ARCH_ARM) && ((__TARGET_ARCH_ARM)+0 >= 6) && (defined(__TARGET_PROFILE_A) || defined(__TARGET_PROFILE_R)) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(_MSC_VER) && defined(_M_ARM) && ((_M_ARM)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +#elif (LZO_ARCH_ARM64) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +#elif (LZO_ARCH_CRIS) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +#elif (LZO_ARCH_I386) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +#elif (LZO_ARCH_IA64) +# define LZO_OPT_AVOID_INT_INDEX 1 +# define LZO_OPT_AVOID_UINT_INDEX 1 +# define LZO_OPT_PREFER_POSTINC 1 +#elif (LZO_ARCH_M68K) +# define LZO_OPT_PREFER_POSTINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +# if defined(__mc68020__) && !defined(__mcoldfire__) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +#elif (LZO_ARCH_MIPS) +# define LZO_OPT_AVOID_UINT_INDEX 1 +#elif (LZO_ARCH_POWERPC) +# define LZO_OPT_PREFER_PREINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +# if (LZO_ABI_BIG_ENDIAN) || (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +# endif +#elif (LZO_ARCH_RISCV) +# define LZO_OPT_AVOID_UINT_INDEX 1 +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +#elif (LZO_ARCH_S390) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +#elif (LZO_ARCH_SH) +# define LZO_OPT_PREFER_POSTINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +#endif +#ifndef LZO_CFG_NO_INLINE_ASM +#if (LZO_ABI_NEUTRAL_ENDIAN) || (LZO_ARCH_GENERIC) +# define LZO_CFG_NO_INLINE_ASM 1 +#elif (LZO_CC_LLVM) +# define LZO_CFG_NO_INLINE_ASM 1 +#endif +#endif +#if (LZO_CFG_NO_INLINE_ASM) +# undef LZO_ASM_SYNTAX_MSC +# undef LZO_ASM_SYNTAX_GNUC +# undef __LZO_ASM_CLOBBER +# undef __LZO_ASM_CLOBBER_LIST_CC +# undef __LZO_ASM_CLOBBER_LIST_CC_MEMORY +# undef __LZO_ASM_CLOBBER_LIST_EMPTY +#endif +#ifndef LZO_CFG_NO_UNALIGNED +#if (LZO_ABI_NEUTRAL_ENDIAN) || (LZO_ARCH_GENERIC) +# define LZO_CFG_NO_UNALIGNED 1 +#endif +#endif +#if (LZO_CFG_NO_UNALIGNED) +# undef LZO_OPT_UNALIGNED16 +# undef LZO_OPT_UNALIGNED32 +# undef LZO_OPT_UNALIGNED64 +#endif +#if defined(__LZO_INFOSTR_MM) +#elif (LZO_MM_FLAT) && (defined(__LZO_INFOSTR_PM) || defined(LZO_INFO_ABI_PM)) +# define __LZO_INFOSTR_MM "" +#elif defined(LZO_INFO_MM) +# define __LZO_INFOSTR_MM "." LZO_INFO_MM +#else +# define __LZO_INFOSTR_MM "" +#endif +#if defined(__LZO_INFOSTR_PM) +#elif defined(LZO_INFO_ABI_PM) +# define __LZO_INFOSTR_PM "." LZO_INFO_ABI_PM +#else +# define __LZO_INFOSTR_PM "" +#endif +#if defined(__LZO_INFOSTR_ENDIAN) +#elif defined(LZO_INFO_ABI_ENDIAN) +# define __LZO_INFOSTR_ENDIAN "." LZO_INFO_ABI_ENDIAN +#else +# define __LZO_INFOSTR_ENDIAN "" +#endif +#if defined(__LZO_INFOSTR_OSNAME) +#elif defined(LZO_INFO_OS_CONSOLE) +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_CONSOLE +#elif defined(LZO_INFO_OS_POSIX) +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_POSIX +#else +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS +#endif +#if defined(__LZO_INFOSTR_LIBC) +#elif defined(LZO_INFO_LIBC) +# define __LZO_INFOSTR_LIBC "." LZO_INFO_LIBC +#else +# define __LZO_INFOSTR_LIBC "" +#endif +#if defined(__LZO_INFOSTR_CCVER) +#elif defined(LZO_INFO_CCVER) +# define __LZO_INFOSTR_CCVER " " LZO_INFO_CCVER +#else +# define __LZO_INFOSTR_CCVER "" +#endif +#define LZO_INFO_STRING \ + LZO_INFO_ARCH __LZO_INFOSTR_MM __LZO_INFOSTR_PM __LZO_INFOSTR_ENDIAN \ + " " __LZO_INFOSTR_OSNAME __LZO_INFOSTR_LIBC " " LZO_INFO_CC __LZO_INFOSTR_CCVER +#if !(LZO_CFG_SKIP_LZO_TYPES) +#if (!(LZO_SIZEOF_SHORT+0 > 0 && LZO_SIZEOF_INT+0 > 0 && LZO_SIZEOF_LONG+0 > 0)) +# error "missing defines for sizes" +#endif +#if (!(LZO_SIZEOF_PTRDIFF_T+0 > 0 && LZO_SIZEOF_SIZE_T+0 > 0 && LZO_SIZEOF_VOID_P+0 > 0)) +# error "missing defines for sizes" +#endif +#define LZO_TYPEOF_CHAR 1u +#define LZO_TYPEOF_SHORT 2u +#define LZO_TYPEOF_INT 3u +#define LZO_TYPEOF_LONG 4u +#define LZO_TYPEOF_LONG_LONG 5u +#define LZO_TYPEOF___INT8 17u +#define LZO_TYPEOF___INT16 18u +#define LZO_TYPEOF___INT32 19u +#define LZO_TYPEOF___INT64 20u +#define LZO_TYPEOF___INT128 21u +#define LZO_TYPEOF___INT256 22u +#define LZO_TYPEOF___MODE_QI 33u +#define LZO_TYPEOF___MODE_HI 34u +#define LZO_TYPEOF___MODE_SI 35u +#define LZO_TYPEOF___MODE_DI 36u +#define LZO_TYPEOF___MODE_TI 37u +#define LZO_TYPEOF_CHAR_P 129u +#if !defined(lzo_llong_t) +#if (LZO_SIZEOF_LONG_LONG+0 > 0) +# if !(LZO_LANG_ASSEMBLER) + __lzo_gnuc_extension__ typedef long long lzo_llong_t__; + __lzo_gnuc_extension__ typedef unsigned long long lzo_ullong_t__; +# endif +# define lzo_llong_t lzo_llong_t__ +# define lzo_ullong_t lzo_ullong_t__ +#endif +#endif +#if !defined(lzo_int16e_t) +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) && (LZO_SIZEOF_SHORT != 2) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T +#endif +#if (LZO_SIZEOF_LONG == 2) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) +# define lzo_int16e_t long +# define lzo_uint16e_t unsigned long +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_INT == 2) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) +# define lzo_int16e_t int +# define lzo_uint16e_t unsigned int +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == 2) +# define lzo_int16e_t short int +# define lzo_uint16e_t unsigned short int +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_SHORT +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_HI) && (LZO_CC_CLANG || (LZO_CC_GNUC >= 0x025f00ul) || LZO_CC_LLVM) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int16e_hi_t__ __attribute__((__mode__(__HI__))); + typedef unsigned int lzo_uint16e_hi_t__ __attribute__((__mode__(__HI__))); +# endif +# define lzo_int16e_t lzo_int16e_hi_t__ +# define lzo_uint16e_t lzo_uint16e_hi_t__ +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF___MODE_HI +#elif (LZO_SIZEOF___INT16 == 2) +# define lzo_int16e_t __int16 +# define lzo_uint16e_t unsigned __int16 +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF___INT16 +#else +#endif +#endif +#if defined(lzo_int16e_t) +# define LZO_SIZEOF_LZO_INT16E_T 2 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16e_t) == 2) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16e_t) == LZO_SIZEOF_LZO_INT16E_T) +#endif +#if !defined(lzo_int32e_t) +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T == LZO_TYPEOF_INT) && (LZO_SIZEOF_INT != 4) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T +#endif +#if (LZO_SIZEOF_LONG == 4) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T == LZO_TYPEOF_INT) +# define lzo_int32e_t long int +# define lzo_uint32e_t unsigned long int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_INT == 4) +# define lzo_int32e_t int +# define lzo_uint32e_t unsigned int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == 4) +# define lzo_int32e_t short int +# define lzo_uint32e_t unsigned short int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_SHORT +#elif (LZO_SIZEOF_LONG_LONG == 4) +# define lzo_int32e_t lzo_llong_t +# define lzo_uint32e_t lzo_ullong_t +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_LONG_LONG +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_SI) && (LZO_CC_CLANG || (LZO_CC_GNUC >= 0x025f00ul) || LZO_CC_LLVM) && (__INT_MAX__+0 > 2147483647L) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int32e_si_t__ __attribute__((__mode__(__SI__))); + typedef unsigned int lzo_uint32e_si_t__ __attribute__((__mode__(__SI__))); +# endif +# define lzo_int32e_t lzo_int32e_si_t__ +# define lzo_uint32e_t lzo_uint32e_si_t__ +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___MODE_SI +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_SI) && (LZO_CC_GNUC >= 0x025f00ul) && defined(__AVR__) && (__LONG_MAX__+0 == 32767L) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int32e_si_t__ __attribute__((__mode__(__SI__))); + typedef unsigned int lzo_uint32e_si_t__ __attribute__((__mode__(__SI__))); +# endif +# define lzo_int32e_t lzo_int32e_si_t__ +# define lzo_uint32e_t lzo_uint32e_si_t__ +# define LZO_INT32_C(c) (c##LL) +# define LZO_UINT32_C(c) (c##ULL) +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___MODE_SI +#elif (LZO_SIZEOF___INT32 == 4) +# define lzo_int32e_t __int32 +# define lzo_uint32e_t unsigned __int32 +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___INT32 +#else +#endif +#endif +#if defined(lzo_int32e_t) +# define LZO_SIZEOF_LZO_INT32E_T 4 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32e_t) == 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32e_t) == LZO_SIZEOF_LZO_INT32E_T) +#endif +#if !defined(lzo_int64e_t) +#if (LZO_SIZEOF___INT64 == 8) +# if (LZO_CC_BORLANDC) && !defined(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T) +# define LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T LZO_TYPEOF___INT64 +# endif +#endif +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF_LONG_LONG) && (LZO_SIZEOF_LONG_LONG != 8) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T +#endif +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) && (LZO_SIZEOF___INT64 != 8) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T +#endif +#if (LZO_SIZEOF_INT == 8) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_int64e_t int +# define lzo_uint64e_t unsigned int +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_LONG == 8) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF_LONG_LONG) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) +# define lzo_int64e_t long int +# define lzo_uint64e_t unsigned long int +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_LONG_LONG == 8) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) +//# define lzo_int64e_t lzo_llong_t +# define lzo_uint64e_t lzo_ullong_t +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_LONG_LONG +# if (LZO_CC_BORLANDC) +# define LZO_INT64_C(c) ((c) + 0ll) +# define LZO_UINT64_C(c) ((c) + 0ull) +# elif 0 +# define LZO_INT64_C(c) (__lzo_gnuc_extension__ (c##LL)) +# define LZO_UINT64_C(c) (__lzo_gnuc_extension__ (c##ULL)) +# else +# define LZO_INT64_C(c) (c##LL) +# define LZO_UINT64_C(c) (c##ULL) +# endif +#elif (LZO_SIZEOF___INT64 == 8) +# define lzo_int64e_t __int64 +# define lzo_uint64e_t unsigned __int64 +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF___INT64 +# if (LZO_CC_BORLANDC) +# define LZO_INT64_C(c) ((c) + 0i64) +# define LZO_UINT64_C(c) ((c) + 0ui64) +# else +# define LZO_INT64_C(c) (c##i64) +# define LZO_UINT64_C(c) (c##ui64) +# endif +#else +#endif +#endif +#if defined(lzo_int64e_t) +# define LZO_SIZEOF_LZO_INT64E_T 8 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64e_t) == 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64e_t) == LZO_SIZEOF_LZO_INT64E_T) +#endif +#if !defined(lzo_int32l_t) +#if defined(lzo_int32e_t) +# define lzo_int32l_t lzo_int32e_t +# define lzo_uint32l_t lzo_uint32e_t +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_LZO_INT32E_T +# define LZO_TYPEOF_LZO_INT32L_T LZO_TYPEOF_LZO_INT32E_T +#elif (LZO_SIZEOF_INT >= 4) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_int32l_t int +# define lzo_uint32l_t unsigned int +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INT32L_T LZO_SIZEOF_INT +#elif (LZO_SIZEOF_LONG >= 4) +# define lzo_int32l_t long int +# define lzo_uint32l_t unsigned long int +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_INT32L_T LZO_SIZEOF_LONG +#else +# error "lzo_int32l_t" +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32l_t) >= 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32l_t) == LZO_SIZEOF_LZO_INT32L_T) +#endif +#if !defined(lzo_int64l_t) +#if defined(lzo_int64e_t) +# define lzo_int64l_t lzo_int64e_t +# define lzo_uint64l_t lzo_uint64e_t +# define LZO_SIZEOF_LZO_INT64L_T LZO_SIZEOF_LZO_INT64E_T +# define LZO_TYPEOF_LZO_INT64L_T LZO_TYPEOF_LZO_INT64E_T +#else +#endif +#endif +#if defined(lzo_int64l_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64l_t) >= 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64l_t) == LZO_SIZEOF_LZO_INT64L_T) +#endif +#if !defined(lzo_int32f_t) +#if (LZO_SIZEOF_SIZE_T >= 8) +# define lzo_int32f_t lzo_int64l_t +# define lzo_uint32f_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INT32F_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INT32F_T LZO_TYPEOF_LZO_INT64L_T +#else +# define lzo_int32f_t lzo_int32l_t +# define lzo_uint32f_t lzo_uint32l_t +# define LZO_SIZEOF_LZO_INT32F_T LZO_SIZEOF_LZO_INT32L_T +# define LZO_TYPEOF_LZO_INT32F_T LZO_TYPEOF_LZO_INT32L_T +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32f_t) >= 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32f_t) == LZO_SIZEOF_LZO_INT32F_T) +#endif +#if !defined(lzo_int64f_t) +#if defined(lzo_int64l_t) +# define lzo_int64f_t lzo_int64l_t +# define lzo_uint64f_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INT64F_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INT64F_T LZO_TYPEOF_LZO_INT64L_T +#else +#endif +#endif +#if defined(lzo_int64f_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64f_t) >= 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64f_t) == LZO_SIZEOF_LZO_INT64F_T) +#endif +#if !defined(lzo_intptr_t) +#if 1 && (LZO_OS_OS400 && (LZO_SIZEOF_VOID_P == 16)) +# define __LZO_INTPTR_T_IS_POINTER 1 +# if !(LZO_LANG_ASSEMBLER) + typedef char * lzo_intptr_t; + typedef char * lzo_uintptr_t; +# endif +# define lzo_intptr_t lzo_intptr_t +# define lzo_uintptr_t lzo_uintptr_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_VOID_P +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_CHAR_P +#elif (LZO_CC_MSC && (_MSC_VER >= 1300) && (LZO_SIZEOF_VOID_P == 4) && (LZO_SIZEOF_INT == 4)) +# if !(LZO_LANG_ASSEMBLER) + typedef __w64 int lzo_intptr_t; + typedef __w64 unsigned int lzo_uintptr_t; +# endif +# define lzo_intptr_t lzo_intptr_t +# define lzo_uintptr_t lzo_uintptr_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == LZO_SIZEOF_VOID_P) && (LZO_SIZEOF_INT > LZO_SIZEOF_VOID_P) +# define lzo_intptr_t short +# define lzo_uintptr_t unsigned short +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_SHORT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_SHORT +#elif (LZO_SIZEOF_INT >= LZO_SIZEOF_VOID_P) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_intptr_t int +# define lzo_uintptr_t unsigned int +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_LONG >= LZO_SIZEOF_VOID_P) +# define lzo_intptr_t long +# define lzo_uintptr_t unsigned long +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_LZO_INT64L_T >= LZO_SIZEOF_VOID_P) +# define lzo_intptr_t lzo_int64l_t +# define lzo_uintptr_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_LZO_INT64L_T +#else +# error "lzo_intptr_t" +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_intptr_t) >= sizeof(void *)) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_intptr_t) == sizeof(lzo_uintptr_t)) +#endif +#if !defined(lzo_word_t) +#if defined(LZO_WORDSIZE) && (LZO_WORDSIZE+0 > 0) +#if (LZO_WORDSIZE == LZO_SIZEOF_LZO_INTPTR_T) && !(__LZO_INTPTR_T_IS_POINTER) +# define lzo_word_t lzo_uintptr_t +# define lzo_sword_t lzo_intptr_t +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LZO_INTPTR_T +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_LZO_INTPTR_T +#elif (LZO_WORDSIZE == LZO_SIZEOF_LONG) +# define lzo_word_t unsigned long +# define lzo_sword_t long +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_LONG +#elif (LZO_WORDSIZE == LZO_SIZEOF_INT) +# define lzo_word_t unsigned int +# define lzo_sword_t int +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_INT +#elif (LZO_WORDSIZE == LZO_SIZEOF_SHORT) +# define lzo_word_t unsigned short +# define lzo_sword_t short +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_SHORT +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_SHORT +#elif (LZO_WORDSIZE == 1) +# define lzo_word_t unsigned char +# define lzo_sword_t signed char +# define LZO_SIZEOF_LZO_WORD_T 1 +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_CHAR +#elif (LZO_WORDSIZE == LZO_SIZEOF_LZO_INT64L_T) +# define lzo_word_t lzo_uint64l_t +# define lzo_sword_t lzo_int64l_t +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_WORD_T LZO_SIZEOF_LZO_INT64L_T +#elif (LZO_ARCH_SPU) && (LZO_CC_GNUC) +#if 0 +# if !(LZO_LANG_ASSEMBLER) + typedef unsigned lzo_word_t __attribute__((__mode__(__V16QI__))); + typedef int lzo_sword_t __attribute__((__mode__(__V16QI__))); +# endif +# define lzo_word_t lzo_word_t +# define lzo_sword_t lzo_sword_t +# define LZO_SIZEOF_LZO_WORD_T 16 +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF___MODE_V16QI +#endif +#else +# error "lzo_word_t" +#endif +#endif +#endif +#if 1 && defined(lzo_word_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_word_t) == LZO_WORDSIZE) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_sword_t) == LZO_WORDSIZE) +#endif +#if 1 +#define lzo_int8_t signed char +#define lzo_uint8_t unsigned char +#define LZO_SIZEOF_LZO_INT8_T 1 +#define LZO_TYPEOF_LZO_INT8_T LZO_TYPEOF_CHAR +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int8_t) == 1) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int8_t) == sizeof(lzo_uint8_t)) +#endif +#if defined(lzo_int16e_t) +#define lzo_int16_t lzo_int16e_t +#define lzo_uint16_t lzo_uint16e_t +#define LZO_SIZEOF_LZO_INT16_T LZO_SIZEOF_LZO_INT16E_T +#define LZO_TYPEOF_LZO_INT16_T LZO_TYPEOF_LZO_INT16E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16_t) == 2) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16_t) == sizeof(lzo_uint16_t)) +#endif +#if defined(lzo_int32e_t) +#define lzo_int32_t lzo_int32e_t +#define lzo_uint32_t lzo_uint32e_t +#define LZO_SIZEOF_LZO_INT32_T LZO_SIZEOF_LZO_INT32E_T +#define LZO_TYPEOF_LZO_INT32_T LZO_TYPEOF_LZO_INT32E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32_t) == 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32_t) == sizeof(lzo_uint32_t)) +#endif +#if defined(lzo_int64e_t) +#define lzo_int64_t lzo_int64e_t +#define lzo_uint64_t lzo_uint64e_t +#define LZO_SIZEOF_LZO_INT64_T LZO_SIZEOF_LZO_INT64E_T +#define LZO_TYPEOF_LZO_INT64_T LZO_TYPEOF_LZO_INT64E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64_t) == 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64_t) == sizeof(lzo_uint64_t)) +#endif +#if 1 +#define lzo_int_least32_t lzo_int32l_t +#define lzo_uint_least32_t lzo_uint32l_t +#define LZO_SIZEOF_LZO_INT_LEAST32_T LZO_SIZEOF_LZO_INT32L_T +#define LZO_TYPEOF_LZO_INT_LEAST32_T LZO_TYPEOF_LZO_INT32L_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least32_t) >= 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least32_t) == sizeof(lzo_uint_least32_t)) +#endif +#if defined(lzo_int64l_t) +#define lzo_int_least64_t lzo_int64l_t +#define lzo_uint_least64_t lzo_uint64l_t +#define LZO_SIZEOF_LZO_INT_LEAST64_T LZO_SIZEOF_LZO_INT64L_T +#define LZO_TYPEOF_LZO_INT_LEAST64_T LZO_TYPEOF_LZO_INT64L_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least64_t) >= 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least64_t) == sizeof(lzo_uint_least64_t)) +#endif +#if 1 +#define lzo_int_fast32_t lzo_int32f_t +#define lzo_uint_fast32_t lzo_uint32f_t +#define LZO_SIZEOF_LZO_INT_FAST32_T LZO_SIZEOF_LZO_INT32F_T +#define LZO_TYPEOF_LZO_INT_FAST32_T LZO_TYPEOF_LZO_INT32F_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast32_t) >= 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast32_t) == sizeof(lzo_uint_fast32_t)) +#endif +#if defined(lzo_int64f_t) +#define lzo_int_fast64_t lzo_int64f_t +#define lzo_uint_fast64_t lzo_uint64f_t +#define LZO_SIZEOF_LZO_INT_FAST64_T LZO_SIZEOF_LZO_INT64F_T +#define LZO_TYPEOF_LZO_INT_FAST64_T LZO_TYPEOF_LZO_INT64F_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast64_t) >= 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast64_t) == sizeof(lzo_uint_fast64_t)) +#endif +#if !defined(LZO_INT16_C) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 2) +# define LZO_INT16_C(c) ((c) + 0) +# define LZO_UINT16_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 2) +# define LZO_INT16_C(c) ((c) + 0L) +# define LZO_UINT16_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 2) +# define LZO_INT16_C(c) (c) +# define LZO_UINT16_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 2) +# define LZO_INT16_C(c) (c##L) +# define LZO_UINT16_C(c) (c##UL) +# else +# error "LZO_INT16_C" +# endif +#endif +#if !defined(LZO_INT32_C) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 4) +# define LZO_INT32_C(c) ((c) + 0) +# define LZO_UINT32_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 4) +# define LZO_INT32_C(c) ((c) + 0L) +# define LZO_UINT32_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 4) +# define LZO_INT32_C(c) (c) +# define LZO_UINT32_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 4) +# define LZO_INT32_C(c) (c##L) +# define LZO_UINT32_C(c) (c##UL) +# elif (LZO_SIZEOF_LONG_LONG >= 4) +# define LZO_INT32_C(c) (c##LL) +# define LZO_UINT32_C(c) (c##ULL) +# else +# error "LZO_INT32_C" +# endif +#endif +#if !defined(LZO_INT64_C) && defined(lzo_int64l_t) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 8) +# define LZO_INT64_C(c) ((c) + 0) +# define LZO_UINT64_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 8) +# define LZO_INT64_C(c) ((c) + 0L) +# define LZO_UINT64_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 8) +# define LZO_INT64_C(c) (c) +# define LZO_UINT64_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 8) +# define LZO_INT64_C(c) (c##L) +# define LZO_UINT64_C(c) (c##UL) +# else +# error "LZO_INT64_C" +# endif +#endif +#endif + +#endif /* already included */ + +/* vim:set ts=4 sw=4 et: */ diff --git a/minilzo-2.10/minilzo.c b/minilzo-2.10/minilzo.c new file mode 100644 index 0000000..8fd8664 --- /dev/null +++ b/minilzo-2.10/minilzo.c @@ -0,0 +1,6365 @@ +/* minilzo.c -- mini subset of the LZO real-time data compression library + + This file is part of the LZO real-time data compression library. + + Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer + All Rights Reserved. + + The LZO library is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of + the License, or (at your option) any later version. + + The LZO library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the LZO library; see the file COPYING. + If not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Markus F.X.J. Oberhumer + + http://www.oberhumer.com/opensource/lzo/ + */ + +/* + * NOTE: + * the full LZO package can be found at + * http://www.oberhumer.com/opensource/lzo/ + */ + +#define __LZO_IN_MINILZO 1 + +#if defined(LZO_CFG_FREESTANDING) +# undef MINILZO_HAVE_CONFIG_H +# define LZO_LIBC_FREESTANDING 1 +# define LZO_OS_FREESTANDING 1 +#endif + +#ifdef MINILZO_HAVE_CONFIG_H +# include +#endif +#include +#include +#if defined(MINILZO_CFG_USE_INTERNAL_LZODEFS) + +#ifndef __LZODEFS_H_INCLUDED +#define __LZODEFS_H_INCLUDED 1 + +#if defined(__CYGWIN32__) && !defined(__CYGWIN__) +# define __CYGWIN__ __CYGWIN32__ +#endif +#if 1 && defined(__INTERIX) && defined(__GNUC__) && !defined(_ALL_SOURCE) +# define _ALL_SOURCE 1 +#endif +#if defined(__mips__) && defined(__R5900__) +# if !defined(__LONG_MAX__) +# define __LONG_MAX__ 9223372036854775807L +# endif +#endif +#if 0 +#elif !defined(__LZO_LANG_OVERRIDE) +#if (defined(__clang__) || defined(__GNUC__)) && defined(__ASSEMBLER__) +# if (__ASSEMBLER__+0) <= 0 +# error "__ASSEMBLER__" +# else +# define LZO_LANG_ASSEMBLER 1 +# endif +#elif defined(__cplusplus) +# if (__cplusplus+0) <= 0 +# error "__cplusplus" +# elif (__cplusplus < 199711L) +# define LZO_LANG_CXX 1 +# elif defined(_MSC_VER) && defined(_MSVC_LANG) && (_MSVC_LANG+0 >= 201402L) && 1 +# define LZO_LANG_CXX _MSVC_LANG +# else +# define LZO_LANG_CXX __cplusplus +# endif +# define LZO_LANG_CPLUSPLUS LZO_LANG_CXX +#else +# if defined(__STDC_VERSION__) && (__STDC_VERSION__+0 >= 199409L) +# define LZO_LANG_C __STDC_VERSION__ +# else +# define LZO_LANG_C 1 +# endif +#endif +#endif +#if !defined(LZO_CFG_NO_DISABLE_WUNDEF) +#if defined(__ARMCC_VERSION) +# pragma diag_suppress 193 +#elif defined(__clang__) && defined(__clang_minor__) +# pragma clang diagnostic ignored "-Wundef" +#elif defined(__INTEL_COMPILER) +# pragma warning(disable: 193) +#elif defined(__KEIL__) && defined(__C166__) +# pragma warning disable = 322 +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && !defined(__PATHSCALE__) +# if ((__GNUC__-0) >= 5 || ((__GNUC__-0) == 4 && (__GNUC_MINOR__-0) >= 2)) +# pragma GCC diagnostic ignored "-Wundef" +# endif +#elif defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__MWERKS__) +# if ((_MSC_VER-0) >= 1300) +# pragma warning(disable: 4668) +# endif +#endif +#endif +#if 0 && defined(__POCC__) && defined(_WIN32) +# if (__POCC__ >= 400) +# pragma warn(disable: 2216) +# endif +#endif +#if 0 && defined(__WATCOMC__) +# if (__WATCOMC__ >= 1050) && (__WATCOMC__ < 1060) +# pragma warning 203 9 +# endif +#endif +#if defined(__BORLANDC__) && defined(__MSDOS__) && !defined(__FLAT__) +# pragma option -h +#endif +#if !(LZO_CFG_NO_DISABLE_WCRTNONSTDC) +#ifndef _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif +#ifndef _CRT_NONSTDC_NO_WARNINGS +#define _CRT_NONSTDC_NO_WARNINGS 1 +#endif +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS 1 +#endif +#endif +#if 0 +#define LZO_0xffffUL 0xfffful +#define LZO_0xffffffffUL 0xfffffffful +#else +#define LZO_0xffffUL 65535ul +#define LZO_0xffffffffUL 4294967295ul +#endif +#define LZO_0xffffL LZO_0xffffUL +#define LZO_0xffffffffL LZO_0xffffffffUL +#if (LZO_0xffffL == LZO_0xffffffffL) +# error "your preprocessor is broken 1" +#endif +#if (16ul * 16384ul != 262144ul) +# error "your preprocessor is broken 2" +#endif +#if 0 +#if (32767 >= 4294967295ul) +# error "your preprocessor is broken 3" +#endif +#if (65535u >= 4294967295ul) +# error "your preprocessor is broken 4" +#endif +#endif +#if defined(__COUNTER__) +# ifndef LZO_CFG_USE_COUNTER +# define LZO_CFG_USE_COUNTER 1 +# endif +#else +# undef LZO_CFG_USE_COUNTER +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(__ZTC__) && defined(__I86__) && !defined(__OS2__) +# if !defined(MSDOS) +# define MSDOS 1 +# endif +# if !defined(_MSDOS) +# define _MSDOS 1 +# endif +#elif 0 && defined(__VERSION) && defined(MB_LEN_MAX) +# if (__VERSION == 520) && (MB_LEN_MAX == 1) +# if !defined(__AZTEC_C__) +# define __AZTEC_C__ __VERSION +# endif +# if !defined(__DOS__) +# define __DOS__ 1 +# endif +# endif +#endif +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(_MSC_VER) && defined(M_I86HM) +# define ptrdiff_t long +# define _PTRDIFF_T_DEFINED 1 +#endif +#endif +#if (UINT_MAX == LZO_0xffffL) +# undef __LZO_RENAME_A +# undef __LZO_RENAME_B +# if defined(__AZTEC_C__) && defined(__DOS__) +# define __LZO_RENAME_A 1 +# elif defined(_MSC_VER) && defined(MSDOS) +# if (_MSC_VER < 600) +# define __LZO_RENAME_A 1 +# elif (_MSC_VER < 700) +# define __LZO_RENAME_B 1 +# endif +# elif defined(__TSC__) && defined(__OS2__) +# define __LZO_RENAME_A 1 +# elif defined(__MSDOS__) && defined(__TURBOC__) && (__TURBOC__ < 0x0410) +# define __LZO_RENAME_A 1 +# elif defined(__PACIFIC__) && defined(DOS) +# if !defined(__far) +# define __far far +# endif +# if !defined(__near) +# define __near near +# endif +# endif +# if defined(__LZO_RENAME_A) +# if !defined(__cdecl) +# define __cdecl cdecl +# endif +# if !defined(__far) +# define __far far +# endif +# if !defined(__huge) +# define __huge huge +# endif +# if !defined(__near) +# define __near near +# endif +# if !defined(__pascal) +# define __pascal pascal +# endif +# if !defined(__huge) +# define __huge huge +# endif +# elif defined(__LZO_RENAME_B) +# if !defined(__cdecl) +# define __cdecl _cdecl +# endif +# if !defined(__far) +# define __far _far +# endif +# if !defined(__huge) +# define __huge _huge +# endif +# if !defined(__near) +# define __near _near +# endif +# if !defined(__pascal) +# define __pascal _pascal +# endif +# elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) +# if !defined(__cdecl) +# define __cdecl cdecl +# endif +# if !defined(__pascal) +# define __pascal pascal +# endif +# endif +# undef __LZO_RENAME_A +# undef __LZO_RENAME_B +#endif +#if (UINT_MAX == LZO_0xffffL) +#if defined(__AZTEC_C__) && defined(__DOS__) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +#elif defined(_MSC_VER) && defined(MSDOS) +# if (_MSC_VER < 600) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +# endif +# if (_MSC_VER < 700) +# define LZO_BROKEN_INTEGRAL_PROMOTION 1 +# define LZO_BROKEN_SIZEOF 1 +# endif +#elif defined(__PACIFIC__) && defined(DOS) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +#elif defined(__TURBOC__) && defined(__MSDOS__) +# if (__TURBOC__ < 0x0150) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +# define LZO_BROKEN_INTEGRAL_PROMOTION 1 +# endif +# if (__TURBOC__ < 0x0200) +# define LZO_BROKEN_SIZEOF 1 +# endif +# if (__TURBOC__ < 0x0400) && defined(__cplusplus) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# endif +#elif (defined(__PUREC__) || defined(__TURBOC__)) && defined(__TOS__) +# define LZO_BROKEN_CDECL_ALT_SYNTAX 1 +# define LZO_BROKEN_SIZEOF 1 +#endif +#endif +#if defined(__WATCOMC__) && (__WATCOMC__ < 900) +# define LZO_BROKEN_INTEGRAL_CONSTANTS 1 +#endif +#if defined(_CRAY) && defined(_CRAY1) +# define LZO_BROKEN_SIGNED_RIGHT_SHIFT 1 +#endif +#define LZO_PP_STRINGIZE(x) #x +#define LZO_PP_MACRO_EXPAND(x) LZO_PP_STRINGIZE(x) +#define LZO_PP_CONCAT0() /*empty*/ +#define LZO_PP_CONCAT1(a) a +#define LZO_PP_CONCAT2(a,b) a ## b +#define LZO_PP_CONCAT3(a,b,c) a ## b ## c +#define LZO_PP_CONCAT4(a,b,c,d) a ## b ## c ## d +#define LZO_PP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e +#define LZO_PP_CONCAT6(a,b,c,d,e,f) a ## b ## c ## d ## e ## f +#define LZO_PP_CONCAT7(a,b,c,d,e,f,g) a ## b ## c ## d ## e ## f ## g +#define LZO_PP_ECONCAT0() LZO_PP_CONCAT0() +#define LZO_PP_ECONCAT1(a) LZO_PP_CONCAT1(a) +#define LZO_PP_ECONCAT2(a,b) LZO_PP_CONCAT2(a,b) +#define LZO_PP_ECONCAT3(a,b,c) LZO_PP_CONCAT3(a,b,c) +#define LZO_PP_ECONCAT4(a,b,c,d) LZO_PP_CONCAT4(a,b,c,d) +#define LZO_PP_ECONCAT5(a,b,c,d,e) LZO_PP_CONCAT5(a,b,c,d,e) +#define LZO_PP_ECONCAT6(a,b,c,d,e,f) LZO_PP_CONCAT6(a,b,c,d,e,f) +#define LZO_PP_ECONCAT7(a,b,c,d,e,f,g) LZO_PP_CONCAT7(a,b,c,d,e,f,g) +#define LZO_PP_EMPTY /*empty*/ +#define LZO_PP_EMPTY0() /*empty*/ +#define LZO_PP_EMPTY1(a) /*empty*/ +#define LZO_PP_EMPTY2(a,b) /*empty*/ +#define LZO_PP_EMPTY3(a,b,c) /*empty*/ +#define LZO_PP_EMPTY4(a,b,c,d) /*empty*/ +#define LZO_PP_EMPTY5(a,b,c,d,e) /*empty*/ +#define LZO_PP_EMPTY6(a,b,c,d,e,f) /*empty*/ +#define LZO_PP_EMPTY7(a,b,c,d,e,f,g) /*empty*/ +#if 1 +#define LZO_CPP_STRINGIZE(x) #x +#define LZO_CPP_MACRO_EXPAND(x) LZO_CPP_STRINGIZE(x) +#define LZO_CPP_CONCAT2(a,b) a ## b +#define LZO_CPP_CONCAT3(a,b,c) a ## b ## c +#define LZO_CPP_CONCAT4(a,b,c,d) a ## b ## c ## d +#define LZO_CPP_CONCAT5(a,b,c,d,e) a ## b ## c ## d ## e +#define LZO_CPP_CONCAT6(a,b,c,d,e,f) a ## b ## c ## d ## e ## f +#define LZO_CPP_CONCAT7(a,b,c,d,e,f,g) a ## b ## c ## d ## e ## f ## g +#define LZO_CPP_ECONCAT2(a,b) LZO_CPP_CONCAT2(a,b) +#define LZO_CPP_ECONCAT3(a,b,c) LZO_CPP_CONCAT3(a,b,c) +#define LZO_CPP_ECONCAT4(a,b,c,d) LZO_CPP_CONCAT4(a,b,c,d) +#define LZO_CPP_ECONCAT5(a,b,c,d,e) LZO_CPP_CONCAT5(a,b,c,d,e) +#define LZO_CPP_ECONCAT6(a,b,c,d,e,f) LZO_CPP_CONCAT6(a,b,c,d,e,f) +#define LZO_CPP_ECONCAT7(a,b,c,d,e,f,g) LZO_CPP_CONCAT7(a,b,c,d,e,f,g) +#endif +#define __LZO_MASK_GEN(o,b) (((((o) << ((b)-((b)!=0))) - (o)) << 1) + (o)*((b)!=0)) +#if 1 && defined(__cplusplus) +# if !defined(__STDC_CONSTANT_MACROS) +# define __STDC_CONSTANT_MACROS 1 +# endif +# if !defined(__STDC_LIMIT_MACROS) +# define __STDC_LIMIT_MACROS 1 +# endif +#endif +#if defined(__cplusplus) +# define LZO_EXTERN_C extern "C" +# define LZO_EXTERN_C_BEGIN extern "C" { +# define LZO_EXTERN_C_END } +#else +# define LZO_EXTERN_C extern +# define LZO_EXTERN_C_BEGIN /*empty*/ +# define LZO_EXTERN_C_END /*empty*/ +#endif +#if !defined(__LZO_OS_OVERRIDE) +#if (LZO_OS_FREESTANDING) +# define LZO_INFO_OS "freestanding" +#elif (LZO_OS_EMBEDDED) +# define LZO_INFO_OS "embedded" +#elif 1 && defined(__IAR_SYSTEMS_ICC__) +# define LZO_OS_EMBEDDED 1 +# define LZO_INFO_OS "embedded" +#elif defined(__CYGWIN__) && defined(__GNUC__) +# define LZO_OS_CYGWIN 1 +# define LZO_INFO_OS "cygwin" +#elif defined(__EMX__) && defined(__GNUC__) +# define LZO_OS_EMX 1 +# define LZO_INFO_OS "emx" +#elif defined(__BEOS__) +# define LZO_OS_BEOS 1 +# define LZO_INFO_OS "beos" +#elif defined(__Lynx__) +# define LZO_OS_LYNXOS 1 +# define LZO_INFO_OS "lynxos" +#elif defined(__OS400__) +# define LZO_OS_OS400 1 +# define LZO_INFO_OS "os400" +#elif defined(__QNX__) +# define LZO_OS_QNX 1 +# define LZO_INFO_OS "qnx" +#elif defined(__BORLANDC__) && defined(__DPMI32__) && (__BORLANDC__ >= 0x0460) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +#elif defined(__BORLANDC__) && defined(__DPMI16__) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +#elif defined(__ZTC__) && defined(DOS386) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +#elif defined(__OS2__) || defined(__OS2V2__) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_OS216 1 +# define LZO_INFO_OS "os216" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_OS2 1 +# define LZO_INFO_OS "os2" +# else +# error "check your limits.h header" +# endif +#elif defined(__WIN64__) || defined(_WIN64) || defined(WIN64) +# define LZO_OS_WIN64 1 +# define LZO_INFO_OS "win64" +#elif defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS_386__) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +#elif defined(__MWERKS__) && defined(__INTEL__) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +#elif defined(__WINDOWS__) || defined(_WINDOWS) || defined(_Windows) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_WIN16 1 +# define LZO_INFO_OS "win16" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +# else +# error "check your limits.h header" +# endif +#elif defined(__DOS__) || defined(__MSDOS__) || defined(_MSDOS) || defined(MSDOS) || (defined(__PACIFIC__) && defined(DOS)) +# if (UINT_MAX == LZO_0xffffL) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_OS_DOS32 1 +# define LZO_INFO_OS "dos32" +# else +# error "check your limits.h header" +# endif +#elif defined(__WATCOMC__) +# if defined(__NT__) && (UINT_MAX == LZO_0xffffL) +# define LZO_OS_DOS16 1 +# define LZO_INFO_OS "dos16" +# elif defined(__NT__) && (__WATCOMC__ < 1100) +# define LZO_OS_WIN32 1 +# define LZO_INFO_OS "win32" +# elif defined(__linux__) || defined(__LINUX__) +# define LZO_OS_POSIX 1 +# define LZO_INFO_OS "posix" +# else +# error "please specify a target using the -bt compiler option" +# endif +#elif defined(__palmos__) +# define LZO_OS_PALMOS 1 +# define LZO_INFO_OS "palmos" +#elif defined(__TOS__) || defined(__atarist__) +# define LZO_OS_TOS 1 +# define LZO_INFO_OS "tos" +#elif defined(macintosh) && !defined(__arm__) && !defined(__i386__) && !defined(__ppc__) && !defined(__x64_64__) +# define LZO_OS_MACCLASSIC 1 +# define LZO_INFO_OS "macclassic" +#elif defined(__VMS) +# define LZO_OS_VMS 1 +# define LZO_INFO_OS "vms" +#elif (defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__) +# define LZO_OS_CONSOLE 1 +# define LZO_OS_CONSOLE_PS2 1 +# define LZO_INFO_OS "console" +# define LZO_INFO_OS_CONSOLE "ps2" +#elif defined(__mips__) && defined(__psp__) +# define LZO_OS_CONSOLE 1 +# define LZO_OS_CONSOLE_PSP 1 +# define LZO_INFO_OS "console" +# define LZO_INFO_OS_CONSOLE "psp" +#else +# define LZO_OS_POSIX 1 +# define LZO_INFO_OS "posix" +#endif +#if (LZO_OS_POSIX) +# if defined(_AIX) || defined(__AIX__) || defined(__aix__) +# define LZO_OS_POSIX_AIX 1 +# define LZO_INFO_OS_POSIX "aix" +# elif defined(__FreeBSD__) +# define LZO_OS_POSIX_FREEBSD 1 +# define LZO_INFO_OS_POSIX "freebsd" +# elif defined(__hpux__) || defined(__hpux) +# define LZO_OS_POSIX_HPUX 1 +# define LZO_INFO_OS_POSIX "hpux" +# elif defined(__INTERIX) +# define LZO_OS_POSIX_INTERIX 1 +# define LZO_INFO_OS_POSIX "interix" +# elif defined(__IRIX__) || defined(__irix__) +# define LZO_OS_POSIX_IRIX 1 +# define LZO_INFO_OS_POSIX "irix" +# elif defined(__linux__) || defined(__linux) || defined(__LINUX__) +# define LZO_OS_POSIX_LINUX 1 +# define LZO_INFO_OS_POSIX "linux" +# elif defined(__APPLE__) && defined(__MACH__) +# if ((__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__-0) >= 20000) +# define LZO_OS_POSIX_DARWIN 1040 +# define LZO_INFO_OS_POSIX "darwin_iphone" +# elif ((__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__-0) >= 1040) +# define LZO_OS_POSIX_DARWIN __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ +# define LZO_INFO_OS_POSIX "darwin" +# else +# define LZO_OS_POSIX_DARWIN 1 +# define LZO_INFO_OS_POSIX "darwin" +# endif +# define LZO_OS_POSIX_MACOSX LZO_OS_POSIX_DARWIN +# elif defined(__minix__) || defined(__minix) +# define LZO_OS_POSIX_MINIX 1 +# define LZO_INFO_OS_POSIX "minix" +# elif defined(__NetBSD__) +# define LZO_OS_POSIX_NETBSD 1 +# define LZO_INFO_OS_POSIX "netbsd" +# elif defined(__OpenBSD__) +# define LZO_OS_POSIX_OPENBSD 1 +# define LZO_INFO_OS_POSIX "openbsd" +# elif defined(__osf__) +# define LZO_OS_POSIX_OSF 1 +# define LZO_INFO_OS_POSIX "osf" +# elif defined(__solaris__) || defined(__sun) +# if defined(__SVR4) || defined(__svr4__) +# define LZO_OS_POSIX_SOLARIS 1 +# define LZO_INFO_OS_POSIX "solaris" +# else +# define LZO_OS_POSIX_SUNOS 1 +# define LZO_INFO_OS_POSIX "sunos" +# endif +# elif defined(__ultrix__) || defined(__ultrix) +# define LZO_OS_POSIX_ULTRIX 1 +# define LZO_INFO_OS_POSIX "ultrix" +# elif defined(_UNICOS) +# define LZO_OS_POSIX_UNICOS 1 +# define LZO_INFO_OS_POSIX "unicos" +# else +# define LZO_OS_POSIX_UNKNOWN 1 +# define LZO_INFO_OS_POSIX "unknown" +# endif +#endif +#endif +#if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +# if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (UINT_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if defined(CIL) && defined(_GNUCC) && defined(__GNUC__) +# define LZO_CC_CILLY 1 +# define LZO_INFO_CC "Cilly" +# if defined(__CILLY__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__CILLY__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif 0 && defined(SDCC) && defined(__VERSION__) && !defined(__GNUC__) +# define LZO_CC_SDCC 1 +# define LZO_INFO_CC "sdcc" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(SDCC) +#elif defined(__PATHSCALE__) && defined(__PATHCC_PATCHLEVEL__) +# define LZO_CC_PATHSCALE (__PATHCC__ * 0x10000L + (__PATHCC_MINOR__-0) * 0x100 + (__PATHCC_PATCHLEVEL__-0)) +# define LZO_INFO_CC "Pathscale C" +# define LZO_INFO_CCVER __PATHSCALE__ +# if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_PATHSCALE_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__INTEL_COMPILER) && ((__INTEL_COMPILER-0) > 0) +# define LZO_CC_INTELC __INTEL_COMPILER +# define LZO_INFO_CC "Intel C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__INTEL_COMPILER) +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_INTELC_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_INTELC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__POCC__) && defined(_WIN32) +# define LZO_CC_PELLESC 1 +# define LZO_INFO_CC "Pelles C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__POCC__) +#elif defined(__ARMCC_VERSION) && defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# if defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_ARMCC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# else +# define LZO_CC_ARMCC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# endif +# define LZO_CC_ARMCC __ARMCC_VERSION +# define LZO_INFO_CC "ARM C Compiler" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(__clang__) && defined(__c2__) && defined(__c2_version__) && defined(_MSC_VER) +# define LZO_CC_CLANG (__clang_major__ * 0x10000L + (__clang_minor__-0) * 0x100 + (__clang_patchlevel__-0)) +# define LZO_CC_CLANG_C2 _MSC_VER +# define LZO_CC_CLANG_VENDOR_MICROSOFT 1 +# define LZO_INFO_CC "clang/c2" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__c2_version__) +#elif defined(__clang__) && defined(__llvm__) && defined(__VERSION__) +# if defined(__clang_major__) && defined(__clang_minor__) && defined(__clang_patchlevel__) +# define LZO_CC_CLANG (__clang_major__ * 0x10000L + (__clang_minor__-0) * 0x100 + (__clang_patchlevel__-0)) +# else +# define LZO_CC_CLANG 0x010000L +# endif +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_CLANG_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_CLANG_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +# if defined(__APPLE_CC__) +# define LZO_CC_CLANG_VENDOR_APPLE 1 +# define LZO_INFO_CC "clang/apple" +# else +# define LZO_CC_CLANG_VENDOR_LLVM 1 +# define LZO_INFO_CC "clang" +# endif +# if defined(__clang_version__) +# define LZO_INFO_CCVER __clang_version__ +# else +# define LZO_INFO_CCVER __VERSION__ +# endif +#elif defined(__llvm__) && defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# if defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_LLVM_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# else +# define LZO_CC_LLVM_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# endif +# define LZO_CC_LLVM LZO_CC_LLVM_GNUC +# define LZO_INFO_CC "llvm-gcc" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(__ACK__) && defined(_ACK) +# define LZO_CC_ACK 1 +# define LZO_INFO_CC "Amsterdam Compiler Kit C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__ARMCC_VERSION) && !defined(__GNUC__) +# define LZO_CC_ARMCC __ARMCC_VERSION +# define LZO_CC_ARMCC_ARMCC __ARMCC_VERSION +# define LZO_INFO_CC "ARM C Compiler" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__ARMCC_VERSION) +#elif defined(__AZTEC_C__) +# define LZO_CC_AZTECC 1 +# define LZO_INFO_CC "Aztec C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__AZTEC_C__) +#elif defined(__CODEGEARC__) +# define LZO_CC_CODEGEARC 1 +# define LZO_INFO_CC "CodeGear C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__CODEGEARC__) +#elif defined(__BORLANDC__) +# define LZO_CC_BORLANDC 1 +# define LZO_INFO_CC "Borland C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__BORLANDC__) +#elif defined(_CRAYC) && defined(_RELEASE) +# define LZO_CC_CRAYC 1 +# define LZO_INFO_CC "Cray C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_RELEASE) +#elif defined(__DMC__) && defined(__SC__) +# define LZO_CC_DMC 1 +# define LZO_INFO_CC "Digital Mars C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DMC__) +#elif defined(__DECC) +# define LZO_CC_DECC 1 +# define LZO_INFO_CC "DEC C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__DECC) +#elif (defined(__ghs) || defined(__ghs__)) && defined(__GHS_VERSION_NUMBER) && ((__GHS_VERSION_NUMBER-0) > 0) +# define LZO_CC_GHS 1 +# define LZO_INFO_CC "Green Hills C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__GHS_VERSION_NUMBER) +# if defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_GHS_MSC _MSC_VER +# elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__VERSION__) +# define LZO_CC_GHS_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# endif +#elif defined(__HIGHC__) +# define LZO_CC_HIGHC 1 +# define LZO_INFO_CC "MetaWare High C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__HP_aCC) && ((__HP_aCC-0) > 0) +# define LZO_CC_HPACC __HP_aCC +# define LZO_INFO_CC "HP aCC" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__HP_aCC) +#elif defined(__IAR_SYSTEMS_ICC__) +# define LZO_CC_IARC 1 +# define LZO_INFO_CC "IAR C" +# if defined(__VER__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__VER__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__IBMC__) && ((__IBMC__-0) > 0) +# define LZO_CC_IBMC __IBMC__ +# define LZO_INFO_CC "IBM C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__IBMC__) +#elif defined(__IBMCPP__) && ((__IBMCPP__-0) > 0) +# define LZO_CC_IBMC __IBMCPP__ +# define LZO_INFO_CC "IBM C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__IBMCPP__) +#elif defined(__KEIL__) && defined(__C166__) +# define LZO_CC_KEILC 1 +# define LZO_INFO_CC "Keil C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__C166__) +#elif defined(__LCC__) && defined(_WIN32) && defined(__LCCOPTIMLEVEL) +# define LZO_CC_LCCWIN32 1 +# define LZO_INFO_CC "lcc-win32" +# define LZO_INFO_CCVER "unknown" +#elif defined(__LCC__) +# define LZO_CC_LCC 1 +# define LZO_INFO_CC "lcc" +# if defined(__LCC_VERSION__) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__LCC_VERSION__) +# else +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__MWERKS__) && ((__MWERKS__-0) > 0) +# define LZO_CC_MWERKS __MWERKS__ +# define LZO_INFO_CC "Metrowerks C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__MWERKS__) +#elif (defined(__NDPC__) || defined(__NDPX__)) && defined(__i386) +# define LZO_CC_NDPC 1 +# define LZO_INFO_CC "Microway NDP C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__PACIFIC__) +# define LZO_CC_PACIFICC 1 +# define LZO_INFO_CC "Pacific C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PACIFIC__) +#elif defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define LZO_CC_PGI (__PGIC__ * 0x10000L + (__PGIC_MINOR__-0) * 0x100 + (__PGIC_PATCHLEVEL__-0)) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PGIC__) "." LZO_PP_MACRO_EXPAND(__PGIC_MINOR__) "." LZO_PP_MACRO_EXPAND(__PGIC_PATCHLEVEL__) +# else +# define LZO_CC_PGI (__PGIC__ * 0x10000L + (__PGIC_MINOR__-0) * 0x100) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PGIC__) "." LZO_PP_MACRO_EXPAND(__PGIC_MINOR__) ".0" +# endif +# define LZO_INFO_CC "Portland Group PGI C" +#elif defined(__PGI) && (defined(__linux__) || defined(__WIN32__)) +# define LZO_CC_PGI 1 +# define LZO_INFO_CC "Portland Group PGI C" +# define LZO_INFO_CCVER "unknown" +#elif defined(__PUREC__) && defined(__TOS__) +# define LZO_CC_PUREC 1 +# define LZO_INFO_CC "Pure C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__PUREC__) +#elif defined(__SC__) && defined(__ZTC__) +# define LZO_CC_SYMANTECC 1 +# define LZO_INFO_CC "Symantec C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SC__) +#elif defined(__SUNPRO_C) +# define LZO_INFO_CC "SunPro C" +# if ((__SUNPRO_C-0) > 0) +# define LZO_CC_SUNPROC __SUNPRO_C +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_C) +# else +# define LZO_CC_SUNPROC 1 +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__SUNPRO_CC) +# define LZO_INFO_CC "SunPro C" +# if ((__SUNPRO_CC-0) > 0) +# define LZO_CC_SUNPROC __SUNPRO_CC +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__SUNPRO_CC) +# else +# define LZO_CC_SUNPROC 1 +# define LZO_INFO_CCVER "unknown" +# endif +#elif defined(__TINYC__) +# define LZO_CC_TINYC 1 +# define LZO_INFO_CC "Tiny C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TINYC__) +#elif defined(__TSC__) +# define LZO_CC_TOPSPEEDC 1 +# define LZO_INFO_CC "TopSpeed C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TSC__) +#elif defined(__WATCOMC__) +# define LZO_CC_WATCOMC 1 +# define LZO_INFO_CC "Watcom C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__WATCOMC__) +#elif defined(__TURBOC__) +# define LZO_CC_TURBOC 1 +# define LZO_INFO_CC "Turbo C" +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__TURBOC__) +#elif defined(__ZTC__) +# define LZO_CC_ZORTECHC 1 +# define LZO_INFO_CC "Zortech C" +# if ((__ZTC__-0) == 0x310) +# define LZO_INFO_CCVER "0x310" +# else +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(__ZTC__) +# endif +#elif defined(__GNUC__) && defined(__VERSION__) +# if defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) +# define LZO_CC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100 + (__GNUC_PATCHLEVEL__-0)) +# elif defined(__GNUC_MINOR__) +# define LZO_CC_GNUC (__GNUC__ * 0x10000L + (__GNUC_MINOR__-0) * 0x100) +# else +# define LZO_CC_GNUC (__GNUC__ * 0x10000L) +# endif +# define LZO_INFO_CC "gcc" +# define LZO_INFO_CCVER __VERSION__ +#elif defined(_MSC_VER) && ((_MSC_VER-0) > 0) +# define LZO_CC_MSC _MSC_VER +# define LZO_INFO_CC "Microsoft C" +# if defined(_MSC_FULL_VER) +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) "." LZO_PP_MACRO_EXPAND(_MSC_FULL_VER) +# else +# define LZO_INFO_CCVER LZO_PP_MACRO_EXPAND(_MSC_VER) +# endif +#else +# define LZO_CC_UNKNOWN 1 +# define LZO_INFO_CC "unknown" +# define LZO_INFO_CCVER "unknown" +#endif +#if (LZO_CC_GNUC) && defined(__OPEN64__) +# if defined(__OPENCC__) && defined(__OPENCC_MINOR__) && defined(__OPENCC_PATCHLEVEL__) +# define LZO_CC_OPEN64 (__OPENCC__ * 0x10000L + (__OPENCC_MINOR__-0) * 0x100 + (__OPENCC_PATCHLEVEL__-0)) +# define LZO_CC_OPEN64_GNUC LZO_CC_GNUC +# endif +#endif +#if (LZO_CC_GNUC) && defined(__PCC__) +# if defined(__PCC__) && defined(__PCC_MINOR__) && defined(__PCC_MINORMINOR__) +# define LZO_CC_PCC (__PCC__ * 0x10000L + (__PCC_MINOR__-0) * 0x100 + (__PCC_MINORMINOR__-0)) +# define LZO_CC_PCC_GNUC LZO_CC_GNUC +# endif +#endif +#if 0 && (LZO_CC_MSC && (_MSC_VER >= 1200)) && !defined(_MSC_FULL_VER) +# error "LZO_CC_MSC: _MSC_FULL_VER is not defined" +#endif +#if !defined(__LZO_ARCH_OVERRIDE) && !(LZO_ARCH_GENERIC) && defined(_CRAY) +# if (UINT_MAX > LZO_0xffffffffL) && defined(_CRAY) +# if defined(_CRAYMPP) || defined(_CRAYT3D) || defined(_CRAYT3E) +# define LZO_ARCH_CRAY_MPP 1 +# elif defined(_CRAY1) +# define LZO_ARCH_CRAY_PVP 1 +# endif +# endif +#endif +#if !defined(__LZO_ARCH_OVERRIDE) +#if (LZO_ARCH_GENERIC) +# define LZO_INFO_ARCH "generic" +#elif (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +# define LZO_ARCH_I086 1 +# define LZO_INFO_ARCH "i086" +#elif defined(__aarch64__) || defined(_M_ARM64) +# define LZO_ARCH_ARM64 1 +# define LZO_INFO_ARCH "arm64" +#elif defined(__alpha__) || defined(__alpha) || defined(_M_ALPHA) +# define LZO_ARCH_ALPHA 1 +# define LZO_INFO_ARCH "alpha" +#elif (LZO_ARCH_CRAY_MPP) && (defined(_CRAYT3D) || defined(_CRAYT3E)) +# define LZO_ARCH_ALPHA 1 +# define LZO_INFO_ARCH "alpha" +#elif defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64) +# define LZO_ARCH_AMD64 1 +# define LZO_INFO_ARCH "amd64" +#elif defined(__arm__) || defined(_M_ARM) +# define LZO_ARCH_ARM 1 +# define LZO_INFO_ARCH "arm" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCARM__) +# define LZO_ARCH_ARM 1 +# define LZO_INFO_ARCH "arm" +#elif (UINT_MAX <= LZO_0xffffL) && defined(__AVR__) +# define LZO_ARCH_AVR 1 +# define LZO_INFO_ARCH "avr" +#elif defined(__avr32__) || defined(__AVR32__) +# define LZO_ARCH_AVR32 1 +# define LZO_INFO_ARCH "avr32" +#elif defined(__bfin__) +# define LZO_ARCH_BLACKFIN 1 +# define LZO_INFO_ARCH "blackfin" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C166__) +# define LZO_ARCH_C166 1 +# define LZO_INFO_ARCH "c166" +#elif defined(__cris__) +# define LZO_ARCH_CRIS 1 +# define LZO_INFO_ARCH "cris" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCEZ80__) +# define LZO_ARCH_EZ80 1 +# define LZO_INFO_ARCH "ez80" +#elif defined(__H8300__) || defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) +# define LZO_ARCH_H8300 1 +# define LZO_INFO_ARCH "h8300" +#elif defined(__hppa__) || defined(__hppa) +# define LZO_ARCH_HPPA 1 +# define LZO_INFO_ARCH "hppa" +#elif defined(__386__) || defined(__i386__) || defined(__i386) || defined(_M_IX86) || defined(_M_I386) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif (LZO_CC_ZORTECHC && defined(__I86__)) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif (LZO_OS_DOS32 && LZO_CC_HIGHC) && defined(_I386) +# define LZO_ARCH_I386 1 +# define LZO_ARCH_IA32 1 +# define LZO_INFO_ARCH "i386" +#elif defined(__ia64__) || defined(__ia64) || defined(_M_IA64) +# define LZO_ARCH_IA64 1 +# define LZO_INFO_ARCH "ia64" +#elif (UINT_MAX == LZO_0xffffL) && defined(__m32c__) +# define LZO_ARCH_M16C 1 +# define LZO_INFO_ARCH "m16c" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICCM16C__) +# define LZO_ARCH_M16C 1 +# define LZO_INFO_ARCH "m16c" +#elif defined(__m32r__) +# define LZO_ARCH_M32R 1 +# define LZO_INFO_ARCH "m32r" +#elif (LZO_OS_TOS) || defined(__m68k__) || defined(__m68000__) || defined(__mc68000__) || defined(__mc68020__) || defined(_M_M68K) +# define LZO_ARCH_M68K 1 +# define LZO_INFO_ARCH "m68k" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C251__) +# define LZO_ARCH_MCS251 1 +# define LZO_INFO_ARCH "mcs251" +#elif (UINT_MAX == LZO_0xffffL) && defined(__C51__) +# define LZO_ARCH_MCS51 1 +# define LZO_INFO_ARCH "mcs51" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC8051__) +# define LZO_ARCH_MCS51 1 +# define LZO_INFO_ARCH "mcs51" +#elif defined(__mips__) || defined(__mips) || defined(_MIPS_ARCH) || defined(_M_MRX000) +# define LZO_ARCH_MIPS 1 +# define LZO_INFO_ARCH "mips" +#elif (UINT_MAX == LZO_0xffffL) && defined(__MSP430__) +# define LZO_ARCH_MSP430 1 +# define LZO_INFO_ARCH "msp430" +#elif defined(__IAR_SYSTEMS_ICC__) && defined(__ICC430__) +# define LZO_ARCH_MSP430 1 +# define LZO_INFO_ARCH "msp430" +#elif defined(__powerpc__) || defined(__powerpc) || defined(__ppc__) || defined(__PPC__) || defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PWR) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__powerpc64__) || defined(__powerpc64) || defined(__ppc64__) || defined(__PPC64__) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__powerpc64le__) || defined(__powerpc64le) || defined(__ppc64le__) || defined(__PPC64LE__) +# define LZO_ARCH_POWERPC 1 +# define LZO_INFO_ARCH "powerpc" +#elif defined(__riscv) +# define LZO_ARCH_RISCV 1 +# define LZO_INFO_ARCH "riscv" +#elif defined(__s390__) || defined(__s390) || defined(__s390x__) || defined(__s390x) +# define LZO_ARCH_S390 1 +# define LZO_INFO_ARCH "s390" +#elif defined(__sh__) || defined(_M_SH) +# define LZO_ARCH_SH 1 +# define LZO_INFO_ARCH "sh" +#elif defined(__sparc__) || defined(__sparc) || defined(__sparcv8) +# define LZO_ARCH_SPARC 1 +# define LZO_INFO_ARCH "sparc" +#elif defined(__SPU__) +# define LZO_ARCH_SPU 1 +# define LZO_INFO_ARCH "spu" +#elif (UINT_MAX == LZO_0xffffL) && defined(__z80) +# define LZO_ARCH_Z80 1 +# define LZO_INFO_ARCH "z80" +#elif (LZO_ARCH_CRAY_PVP) +# if defined(_CRAYSV1) +# define LZO_ARCH_CRAY_SV1 1 +# define LZO_INFO_ARCH "cray_sv1" +# elif (_ADDR64) +# define LZO_ARCH_CRAY_T90 1 +# define LZO_INFO_ARCH "cray_t90" +# elif (_ADDR32) +# define LZO_ARCH_CRAY_YMP 1 +# define LZO_INFO_ARCH "cray_ymp" +# else +# define LZO_ARCH_CRAY_XMP 1 +# define LZO_INFO_ARCH "cray_xmp" +# endif +#else +# define LZO_ARCH_UNKNOWN 1 +# define LZO_INFO_ARCH "unknown" +#endif +#endif +#if !defined(LZO_ARCH_ARM_THUMB2) +#if (LZO_ARCH_ARM) +# if defined(__thumb__) || defined(__thumb) || defined(_M_THUMB) +# if defined(__thumb2__) +# define LZO_ARCH_ARM_THUMB2 1 +# elif 1 && defined(__TARGET_ARCH_THUMB) && ((__TARGET_ARCH_THUMB)+0 >= 4) +# define LZO_ARCH_ARM_THUMB2 1 +# elif 1 && defined(_MSC_VER) && defined(_M_THUMB) && ((_M_THUMB)+0 >= 7) +# define LZO_ARCH_ARM_THUMB2 1 +# endif +# endif +#endif +#endif +#if (LZO_ARCH_ARM_THUMB2) +# undef LZO_INFO_ARCH +# define LZO_INFO_ARCH "arm_thumb2" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_DOS32 || LZO_OS_OS2) +# error "FIXME - missing define for CPU architecture" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN32) +# error "FIXME - missing LZO_OS_WIN32 define for CPU architecture" +#endif +#if 1 && (LZO_ARCH_UNKNOWN) && (LZO_OS_WIN64) +# error "FIXME - missing LZO_OS_WIN64 define for CPU architecture" +#endif +#if (LZO_OS_OS216 || LZO_OS_WIN16) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && defined(BLX286)) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && defined(DOSX286)) +# define LZO_ARCH_I086PM 1 +#elif 1 && (LZO_OS_DOS16 && LZO_CC_BORLANDC && defined(__DPMI16__)) +# define LZO_ARCH_I086PM 1 +#endif +#if (LZO_ARCH_AMD64 && !LZO_ARCH_X64) +# define LZO_ARCH_X64 1 +#elif (!LZO_ARCH_AMD64 && LZO_ARCH_X64) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_AMD64 1 +#endif +#if (LZO_ARCH_ARM64 && !LZO_ARCH_AARCH64) +# define LZO_ARCH_AARCH64 1 +#elif (!LZO_ARCH_ARM64 && LZO_ARCH_AARCH64) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_ARM64 1 +#endif +#if (LZO_ARCH_I386 && !LZO_ARCH_X86) +# define LZO_ARCH_X86 1 +#elif (!LZO_ARCH_I386 && LZO_ARCH_X86) && defined(__LZO_ARCH_OVERRIDE) +# define LZO_ARCH_I386 1 +#endif +#if (LZO_ARCH_AMD64 && !LZO_ARCH_X64) || (!LZO_ARCH_AMD64 && LZO_ARCH_X64) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM64 && !LZO_ARCH_AARCH64) || (!LZO_ARCH_ARM64 && LZO_ARCH_AARCH64) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I386 && !LZO_ARCH_X86) || (!LZO_ARCH_I386 && LZO_ARCH_X86) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB1 && !LZO_ARCH_ARM) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB2 && !LZO_ARCH_ARM) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM_THUMB1 && LZO_ARCH_ARM_THUMB2) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I086PM && !LZO_ARCH_I086) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_I086) +# if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_ARCH_I386) +# if (UINT_MAX != LZO_0xffffL) && defined(__i386_int16__) +# error "unexpected configuration - check your compiler defines" +# endif +# if (UINT_MAX != LZO_0xffffffffL) && !defined(__i386_int16__) +# error "unexpected configuration - check your compiler defines" +# endif +# if (ULONG_MAX != LZO_0xffffffffL) +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if (LZO_ARCH_AMD64 || LZO_ARCH_I386) +# if !defined(LZO_TARGET_FEATURE_SSE2) +# if defined(__SSE2__) +# define LZO_TARGET_FEATURE_SSE2 1 +# elif defined(_MSC_VER) && (defined(_M_IX86_FP) && ((_M_IX86_FP)+0 >= 2)) +# define LZO_TARGET_FEATURE_SSE2 1 +# elif (LZO_CC_INTELC_MSC || LZO_CC_MSC) && defined(_M_AMD64) +# define LZO_TARGET_FEATURE_SSE2 1 +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_SSSE3) +# if (LZO_TARGET_FEATURE_SSE2) +# if defined(__SSSE3__) +# define LZO_TARGET_FEATURE_SSSE3 1 +# elif defined(_MSC_VER) && defined(__AVX__) +# define LZO_TARGET_FEATURE_SSSE3 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_SSE4_2) +# if (LZO_TARGET_FEATURE_SSSE3) +# if defined(__SSE4_2__) +# define LZO_TARGET_FEATURE_SSE4_2 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_AVX) +# if (LZO_TARGET_FEATURE_SSSE3) +# if defined(__AVX__) +# define LZO_TARGET_FEATURE_AVX 1 +# endif +# endif +# endif +# if !defined(LZO_TARGET_FEATURE_AVX2) +# if (LZO_TARGET_FEATURE_AVX) +# if defined(__AVX2__) +# define LZO_TARGET_FEATURE_AVX2 1 +# endif +# endif +# endif +#endif +#if (LZO_TARGET_FEATURE_SSSE3 && !(LZO_TARGET_FEATURE_SSE2)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_SSE4_2 && !(LZO_TARGET_FEATURE_SSSE3)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_AVX && !(LZO_TARGET_FEATURE_SSSE3)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_TARGET_FEATURE_AVX2 && !(LZO_TARGET_FEATURE_AVX)) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ARCH_ARM) +# if !defined(LZO_TARGET_FEATURE_NEON) +# if defined(__ARM_NEON) && ((__ARM_NEON)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# elif 1 && defined(__ARM_NEON__) && ((__ARM_NEON__)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# elif 1 && defined(__TARGET_FEATURE_NEON) && ((__TARGET_FEATURE_NEON)+0) +# define LZO_TARGET_FEATURE_NEON 1 +# endif +# endif +#elif (LZO_ARCH_ARM64) +# if !defined(LZO_TARGET_FEATURE_NEON) +# if 1 +# define LZO_TARGET_FEATURE_NEON 1 +# endif +# endif +#endif +#if 0 +#elif !defined(__LZO_MM_OVERRIDE) +#if (LZO_ARCH_I086) +#if (UINT_MAX != LZO_0xffffL) +# error "unexpected configuration - check your compiler defines" +#endif +#if defined(__TINY__) || defined(M_I86TM) || defined(_M_I86TM) +# define LZO_MM_TINY 1 +#elif defined(__HUGE__) || defined(_HUGE_) || defined(M_I86HM) || defined(_M_I86HM) +# define LZO_MM_HUGE 1 +#elif defined(__SMALL__) || defined(M_I86SM) || defined(_M_I86SM) || defined(SMALL_MODEL) +# define LZO_MM_SMALL 1 +#elif defined(__MEDIUM__) || defined(M_I86MM) || defined(_M_I86MM) +# define LZO_MM_MEDIUM 1 +#elif defined(__COMPACT__) || defined(M_I86CM) || defined(_M_I86CM) +# define LZO_MM_COMPACT 1 +#elif defined(__LARGE__) || defined(M_I86LM) || defined(_M_I86LM) || defined(LARGE_MODEL) +# define LZO_MM_LARGE 1 +#elif (LZO_CC_AZTECC) +# if defined(_LARGE_CODE) && defined(_LARGE_DATA) +# define LZO_MM_LARGE 1 +# elif defined(_LARGE_CODE) +# define LZO_MM_MEDIUM 1 +# elif defined(_LARGE_DATA) +# define LZO_MM_COMPACT 1 +# else +# define LZO_MM_SMALL 1 +# endif +#elif (LZO_CC_ZORTECHC && defined(__VCM__)) +# define LZO_MM_LARGE 1 +#else +# error "unknown LZO_ARCH_I086 memory model" +#endif +#if (LZO_OS_DOS16 || LZO_OS_OS216 || LZO_OS_WIN16) +#define LZO_HAVE_MM_HUGE_PTR 1 +#define LZO_HAVE_MM_HUGE_ARRAY 1 +#if (LZO_MM_TINY) +# undef LZO_HAVE_MM_HUGE_ARRAY +#endif +#if (LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_ZORTECHC) +# undef LZO_HAVE_MM_HUGE_PTR +# undef LZO_HAVE_MM_HUGE_ARRAY +#elif (LZO_CC_DMC || LZO_CC_SYMANTECC) +# undef LZO_HAVE_MM_HUGE_ARRAY +#elif (LZO_CC_MSC && defined(_QC)) +# undef LZO_HAVE_MM_HUGE_ARRAY +# if (_MSC_VER < 600) +# undef LZO_HAVE_MM_HUGE_PTR +# endif +#elif (LZO_CC_TURBOC && (__TURBOC__ < 0x0295)) +# undef LZO_HAVE_MM_HUGE_ARRAY +#endif +#if (LZO_ARCH_I086PM) && !(LZO_HAVE_MM_HUGE_PTR) +# if (LZO_OS_DOS16) +# error "unexpected configuration - check your compiler defines" +# elif (LZO_CC_ZORTECHC) +# else +# error "unexpected configuration - check your compiler defines" +# endif +#endif +#if defined(__cplusplus) +extern "C" { +#endif +#if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0200)) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_MSC || LZO_CC_TOPSPEEDC) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif (LZO_CC_TURBOC && (__TURBOC__ >= 0x0295)) + extern void __near __cdecl _AHSHIFT(void); +# define LZO_MM_AHSHIFT ((unsigned) _AHSHIFT) +#elif ((LZO_CC_AZTECC || LZO_CC_PACIFICC || LZO_CC_TURBOC) && LZO_OS_DOS16) +# define LZO_MM_AHSHIFT 12 +#elif (LZO_CC_WATCOMC) + extern unsigned char _HShift; +# define LZO_MM_AHSHIFT ((unsigned) _HShift) +#else +# error "FIXME - implement LZO_MM_AHSHIFT" +#endif +#if defined(__cplusplus) +} +#endif +#endif +#elif (LZO_ARCH_C166) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_C166 __MODEL__" +#elif ((__MODEL__) == 0) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 1) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_C166 __MODEL__" +#endif +#elif (LZO_ARCH_MCS251) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_MCS251 __MODEL__" +#elif ((__MODEL__) == 0) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_MCS251 __MODEL__" +#endif +#elif (LZO_ARCH_MCS51) +#if !defined(__MODEL__) +# error "FIXME - LZO_ARCH_MCS51 __MODEL__" +#elif ((__MODEL__) == 1) +# define LZO_MM_SMALL 1 +#elif ((__MODEL__) == 2) +# define LZO_MM_LARGE 1 +#elif ((__MODEL__) == 3) +# define LZO_MM_TINY 1 +#elif ((__MODEL__) == 4) +# define LZO_MM_XTINY 1 +#elif ((__MODEL__) == 5) +# define LZO_MM_XSMALL 1 +#else +# error "FIXME - LZO_ARCH_MCS51 __MODEL__" +#endif +#elif (LZO_ARCH_CRAY_PVP) +# define LZO_MM_PVP 1 +#else +# define LZO_MM_FLAT 1 +#endif +#if (LZO_MM_COMPACT) +# define LZO_INFO_MM "compact" +#elif (LZO_MM_FLAT) +# define LZO_INFO_MM "flat" +#elif (LZO_MM_HUGE) +# define LZO_INFO_MM "huge" +#elif (LZO_MM_LARGE) +# define LZO_INFO_MM "large" +#elif (LZO_MM_MEDIUM) +# define LZO_INFO_MM "medium" +#elif (LZO_MM_PVP) +# define LZO_INFO_MM "pvp" +#elif (LZO_MM_SMALL) +# define LZO_INFO_MM "small" +#elif (LZO_MM_TINY) +# define LZO_INFO_MM "tiny" +#else +# error "unknown memory model" +#endif +#endif +#if !defined(__lzo_gnuc_extension__) +#if (LZO_CC_GNUC >= 0x020800ul) +# define __lzo_gnuc_extension__ __extension__ +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_gnuc_extension__ __extension__ +#elif (LZO_CC_IBMC >= 600) +# define __lzo_gnuc_extension__ __extension__ +#endif +#endif +#if !defined(__lzo_gnuc_extension__) +# define __lzo_gnuc_extension__ /*empty*/ +#endif +#if !defined(lzo_has_builtin) +#if (LZO_CC_CLANG) && defined(__has_builtin) +# define lzo_has_builtin __has_builtin +#endif +#endif +#if !defined(lzo_has_builtin) +# define lzo_has_builtin(x) 0 +#endif +#if !defined(lzo_has_attribute) +#if (LZO_CC_CLANG) && defined(__has_attribute) +# define lzo_has_attribute __has_attribute +#endif +#endif +#if !defined(lzo_has_attribute) +# define lzo_has_attribute(x) 0 +#endif +#if !defined(lzo_has_declspec_attribute) +#if (LZO_CC_CLANG) && defined(__has_declspec_attribute) +# define lzo_has_declspec_attribute __has_declspec_attribute +#endif +#endif +#if !defined(lzo_has_declspec_attribute) +# define lzo_has_declspec_attribute(x) 0 +#endif +#if !defined(lzo_has_feature) +#if (LZO_CC_CLANG) && defined(__has_feature) +# define lzo_has_feature __has_feature +#endif +#endif +#if !defined(lzo_has_feature) +# define lzo_has_feature(x) 0 +#endif +#if !defined(lzo_has_extension) +#if (LZO_CC_CLANG) && defined(__has_extension) +# define lzo_has_extension __has_extension +#elif (LZO_CC_CLANG) && defined(__has_feature) +# define lzo_has_extension __has_feature +#endif +#endif +#if !defined(lzo_has_extension) +# define lzo_has_extension(x) 0 +#endif +#if !defined(LZO_CFG_USE_NEW_STYLE_CASTS) && defined(__cplusplus) && 0 +# if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +# elif (LZO_CC_INTELC && (__INTEL_COMPILER < 1200)) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +# else +# define LZO_CFG_USE_NEW_STYLE_CASTS 1 +# endif +#endif +#if !defined(LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +#endif +#if !defined(__cplusplus) +# if defined(LZO_CFG_USE_NEW_STYLE_CASTS) +# undef LZO_CFG_USE_NEW_STYLE_CASTS +# endif +# define LZO_CFG_USE_NEW_STYLE_CASTS 0 +#endif +#if !defined(LZO_REINTERPRET_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_REINTERPRET_CAST(t,e) (reinterpret_cast (e)) +# endif +#endif +#if !defined(LZO_REINTERPRET_CAST) +# define LZO_REINTERPRET_CAST(t,e) ((t) (e)) +#endif +#if !defined(LZO_STATIC_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_STATIC_CAST(t,e) (static_cast (e)) +# endif +#endif +#if !defined(LZO_STATIC_CAST) +# define LZO_STATIC_CAST(t,e) ((t) (e)) +#endif +#if !defined(LZO_STATIC_CAST2) +# define LZO_STATIC_CAST2(t1,t2,e) LZO_STATIC_CAST(t1, LZO_STATIC_CAST(t2, e)) +#endif +#if !defined(LZO_UNCONST_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNCONST_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNCONST_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNCONST_CAST(t,e) ((t) ((void *) ((lzo_uintptr_t) ((const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNCONST_CAST) +# define LZO_UNCONST_CAST(t,e) ((t) ((void *) ((const void *) (e)))) +#endif +#if !defined(LZO_UNCONST_VOLATILE_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNCONST_VOLATILE_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) ((volatile void *) ((lzo_uintptr_t) ((volatile const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNCONST_VOLATILE_CAST) +# define LZO_UNCONST_VOLATILE_CAST(t,e) ((t) ((volatile void *) ((volatile const void *) (e)))) +#endif +#if !defined(LZO_UNVOLATILE_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNVOLATILE_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNVOLATILE_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNVOLATILE_CAST(t,e) ((t) ((void *) ((lzo_uintptr_t) ((volatile void *) (e))))) +# endif +#endif +#if !defined(LZO_UNVOLATILE_CAST) +# define LZO_UNVOLATILE_CAST(t,e) ((t) ((void *) ((volatile void *) (e)))) +#endif +#if !defined(LZO_UNVOLATILE_CONST_CAST) +# if (LZO_CFG_USE_NEW_STYLE_CASTS) +# define LZO_UNVOLATILE_CONST_CAST(t,e) (const_cast (e)) +# elif (LZO_HAVE_MM_HUGE_PTR) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) (e)) +# elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) ((const void *) ((lzo_uintptr_t) ((volatile const void *) (e))))) +# endif +#endif +#if !defined(LZO_UNVOLATILE_CONST_CAST) +# define LZO_UNVOLATILE_CONST_CAST(t,e) ((t) ((const void *) ((volatile const void *) (e)))) +#endif +#if !defined(LZO_PCAST) +# if (LZO_HAVE_MM_HUGE_PTR) +# define LZO_PCAST(t,e) ((t) (e)) +# endif +#endif +#if !defined(LZO_PCAST) +# define LZO_PCAST(t,e) LZO_STATIC_CAST(t, LZO_STATIC_CAST(void *, e)) +#endif +#if !defined(LZO_CCAST) +# if (LZO_HAVE_MM_HUGE_PTR) +# define LZO_CCAST(t,e) ((t) (e)) +# endif +#endif +#if !defined(LZO_CCAST) +# define LZO_CCAST(t,e) LZO_STATIC_CAST(t, LZO_STATIC_CAST(const void *, e)) +#endif +#if !defined(LZO_ICONV) +# define LZO_ICONV(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(LZO_ICAST) +# define LZO_ICAST(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(LZO_ITRUNC) +# define LZO_ITRUNC(t,e) LZO_STATIC_CAST(t, e) +#endif +#if !defined(__lzo_cte) +# if (LZO_CC_MSC || LZO_CC_WATCOMC) +# define __lzo_cte(e) ((void)0,(e)) +# elif 1 +# define __lzo_cte(e) ((void)0,(e)) +# endif +#endif +#if !defined(__lzo_cte) +# define __lzo_cte(e) (e) +#endif +#if !defined(LZO_BLOCK_BEGIN) +# define LZO_BLOCK_BEGIN do { +# define LZO_BLOCK_END } while __lzo_cte(0) +#endif +#if !defined(LZO_UNUSED) +# if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) +# define LZO_UNUSED(var) ((void) &var) +# elif (LZO_CC_BORLANDC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PELLESC || LZO_CC_TURBOC) +# define LZO_UNUSED(var) if (&var) ; else +# elif (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x030200ul)) +# define LZO_UNUSED(var) ((void) &var) +# elif (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_UNUSED(var) ((void) var) +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_UNUSED(var) if (&var) ; else +# elif (LZO_CC_KEILC) +# define LZO_UNUSED(var) {extern int lzo_unused__[1-2*!(sizeof(var)>0)]; (void)lzo_unused__;} +# elif (LZO_CC_PACIFICC) +# define LZO_UNUSED(var) ((void) sizeof(var)) +# elif (LZO_CC_WATCOMC) && defined(__cplusplus) +# define LZO_UNUSED(var) ((void) var) +# else +# define LZO_UNUSED(var) ((void) &var) +# endif +#endif +#if !defined(LZO_UNUSED_RESULT) +# define LZO_UNUSED_RESULT(var) LZO_UNUSED(var) +#endif +#if !defined(LZO_UNUSED_FUNC) +# if (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0600)) +# define LZO_UNUSED_FUNC(func) ((void) func) +# elif (LZO_CC_BORLANDC || LZO_CC_NDPC || LZO_CC_TURBOC) +# define LZO_UNUSED_FUNC(func) if (func) ; else +# elif (LZO_CC_CLANG || LZO_CC_LLVM) +# define LZO_UNUSED_FUNC(func) ((void) &func) +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_UNUSED_FUNC(func) if (func) ; else +# elif (LZO_CC_MSC) +# define LZO_UNUSED_FUNC(func) ((void) &func) +# elif (LZO_CC_KEILC || LZO_CC_PELLESC) +# define LZO_UNUSED_FUNC(func) {extern int lzo_unused__[1-2*!(sizeof((int)func)>0)]; (void)lzo_unused__;} +# else +# define LZO_UNUSED_FUNC(func) ((void) func) +# endif +#endif +#if !defined(LZO_UNUSED_LABEL) +# if (LZO_CC_CLANG >= 0x020800ul) +# define LZO_UNUSED_LABEL(l) (__lzo_gnuc_extension__ ((void) ((const void *) &&l))) +# elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_INTELC || LZO_CC_WATCOMC) +# define LZO_UNUSED_LABEL(l) if __lzo_cte(0) goto l +# else +# define LZO_UNUSED_LABEL(l) switch (0) case 1:goto l +# endif +#endif +#if !defined(LZO_DEFINE_UNINITIALIZED_VAR) +# if 0 +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var +# elif 0 && (LZO_CC_GNUC) +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = var +# else +# define LZO_DEFINE_UNINITIALIZED_VAR(type,var,init) type var = init +# endif +#endif +#if !defined(__lzo_inline) +#if (LZO_CC_TURBOC && (__TURBOC__ <= 0x0295)) +#elif defined(__cplusplus) +# define __lzo_inline inline +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__-0 >= 199901L) +# define __lzo_inline inline +#elif (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0550)) +# define __lzo_inline __inline +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define __lzo_inline __inline__ +#elif (LZO_CC_DMC) +# define __lzo_inline __inline +#elif (LZO_CC_GHS) +# define __lzo_inline __inline__ +#elif (LZO_CC_IBMC >= 600) +# define __lzo_inline __inline__ +#elif (LZO_CC_INTELC) +# define __lzo_inline __inline +#elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x2405)) +# define __lzo_inline __inline +#elif (LZO_CC_MSC && (_MSC_VER >= 900)) +# define __lzo_inline __inline +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_inline __inline__ +#endif +#endif +#if defined(__lzo_inline) +# ifndef __lzo_HAVE_inline +# define __lzo_HAVE_inline 1 +# endif +#else +# define __lzo_inline /*empty*/ +#endif +#if !defined(__lzo_forceinline) +#if (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) +# define __lzo_forceinline __forceinline +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) +# define __lzo_forceinline __forceinline +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_forceinline __inline__ __attribute__((__always_inline__)) +#endif +#endif +#if defined(__lzo_forceinline) +# ifndef __lzo_HAVE_forceinline +# define __lzo_HAVE_forceinline 1 +# endif +#else +# define __lzo_forceinline __lzo_inline +#endif +#if !defined(__lzo_noinline) +#if 1 && (LZO_ARCH_I386) && (LZO_CC_GNUC >= 0x040000ul) && (LZO_CC_GNUC < 0x040003ul) +# define __lzo_noinline __attribute__((__noinline__,__used__)) +#elif (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 600)) +# define __lzo_noinline __declspec(noinline) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_noinline __declspec(noinline) +#elif (LZO_CC_MWERKS && (__MWERKS__ >= 0x3200) && (LZO_OS_WIN32 || LZO_OS_WIN64)) +# if defined(__cplusplus) +# else +# define __lzo_noinline __declspec(noinline) +# endif +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_noinline __attribute__((__noinline__)) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_noinline __attribute__((__noinline__)) +#endif +#endif +#if defined(__lzo_noinline) +# ifndef __lzo_HAVE_noinline +# define __lzo_HAVE_noinline 1 +# endif +#else +# define __lzo_noinline /*empty*/ +#endif +#if (__lzo_HAVE_forceinline || __lzo_HAVE_noinline) && !(__lzo_HAVE_inline) +# error "unexpected configuration - check your compiler defines" +#endif +#if !defined(__lzo_static_inline) +#if (LZO_CC_IBMC) +# define __lzo_static_inline __lzo_gnuc_extension__ static __lzo_inline +#endif +#endif +#if !defined(__lzo_static_inline) +# define __lzo_static_inline static __lzo_inline +#endif +#if !defined(__lzo_static_forceinline) +#if (LZO_CC_IBMC) +# define __lzo_static_forceinline __lzo_gnuc_extension__ static __lzo_forceinline +#endif +#endif +#if !defined(__lzo_static_forceinline) +# define __lzo_static_forceinline static __lzo_forceinline +#endif +#if !defined(__lzo_static_noinline) +#if (LZO_CC_IBMC) +# define __lzo_static_noinline __lzo_gnuc_extension__ static __lzo_noinline +#endif +#endif +#if !defined(__lzo_static_noinline) +# define __lzo_static_noinline static __lzo_noinline +#endif +#if !defined(__lzo_c99_extern_inline) +#if defined(__GNUC_GNU_INLINE__) +# define __lzo_c99_extern_inline __lzo_inline +#elif defined(__GNUC_STDC_INLINE__) +# define __lzo_c99_extern_inline extern __lzo_inline +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__-0 >= 199901L) +# define __lzo_c99_extern_inline extern __lzo_inline +#endif +#if !defined(__lzo_c99_extern_inline) && (__lzo_HAVE_inline) +# define __lzo_c99_extern_inline __lzo_inline +#endif +#endif +#if defined(__lzo_c99_extern_inline) +# ifndef __lzo_HAVE_c99_extern_inline +# define __lzo_HAVE_c99_extern_inline 1 +# endif +#else +# define __lzo_c99_extern_inline /*empty*/ +#endif +#if !defined(__lzo_may_alias) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_CLANG >= 0x020900ul) +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 1210)) && 0 +# define __lzo_may_alias __attribute__((__may_alias__)) +#elif (LZO_CC_PGI >= 0x0d0a00ul) && 0 +# define __lzo_may_alias __attribute__((__may_alias__)) +#endif +#endif +#if defined(__lzo_may_alias) +# ifndef __lzo_HAVE_may_alias +# define __lzo_HAVE_may_alias 1 +# endif +#else +# define __lzo_may_alias /*empty*/ +#endif +#if !defined(__lzo_noreturn) +#if (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_IBMC >= 700) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) +# define __lzo_noreturn __declspec(noreturn) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 600)) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_noreturn __attribute__((__noreturn__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) +# define __lzo_noreturn __declspec(noreturn) +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_noreturn __attribute__((__noreturn__)) +#endif +#endif +#if defined(__lzo_noreturn) +# ifndef __lzo_HAVE_noreturn +# define __lzo_HAVE_noreturn 1 +# endif +#else +# define __lzo_noreturn /*empty*/ +#endif +#if !defined(__lzo_nothrow) +#if (LZO_CC_GNUC >= 0x030300ul) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 450)) && defined(__cplusplus) +# define __lzo_nothrow __declspec(nothrow) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 900)) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_nothrow __attribute__((__nothrow__)) +#elif (LZO_CC_MSC && (_MSC_VER >= 1200)) && defined(__cplusplus) +# define __lzo_nothrow __declspec(nothrow) +#endif +#endif +#if defined(__lzo_nothrow) +# ifndef __lzo_HAVE_nothrow +# define __lzo_HAVE_nothrow 1 +# endif +#else +# define __lzo_nothrow /*empty*/ +#endif +#if !defined(__lzo_restrict) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_IBMC >= 800) && !defined(__cplusplus) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_IBMC >= 1210) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 600)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 600)) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM) +# define __lzo_restrict __restrict__ +#elif (LZO_CC_MSC && (_MSC_VER >= 1400)) +# define __lzo_restrict __restrict +#elif (LZO_CC_PGI >= 0x0d0a00ul) +# define __lzo_restrict __restrict__ +#endif +#endif +#if defined(__lzo_restrict) +# ifndef __lzo_HAVE_restrict +# define __lzo_HAVE_restrict 1 +# endif +#else +# define __lzo_restrict /*empty*/ +#endif +#if !defined(__lzo_alignof) +#if (LZO_CC_ARMCC || LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_GHS) && !defined(__cplusplus) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_IBMC >= 600) +# define __lzo_alignof(e) (__lzo_gnuc_extension__ __alignof__(e)) +#elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 700)) +# define __lzo_alignof(e) __alignof__(e) +#elif (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_alignof(e) __alignof(e) +#elif (LZO_CC_SUNPROC >= 0x5100) +# define __lzo_alignof(e) __alignof__(e) +#endif +#endif +#if defined(__lzo_alignof) +# ifndef __lzo_HAVE_alignof +# define __lzo_HAVE_alignof 1 +# endif +#endif +#if !defined(__lzo_struct_packed) +#if (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020700ul)) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_PCC && (LZO_CC_PCC < 0x010100ul)) +#elif (LZO_CC_SUNPROC && (LZO_CC_SUNPROC < 0x5110)) && !defined(__cplusplus) +#elif (LZO_CC_GNUC >= 0x030400ul) && !(LZO_CC_PCC_GNUC) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) +# define __lzo_struct_packed(s) struct s { +# define __lzo_struct_packed_end() } __attribute__((__gcc_struct__,__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__gcc_struct__,__packed__)); +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || (LZO_CC_PGI >= 0x0d0a00ul) || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_struct_packed(s) struct s { +# define __lzo_struct_packed_end() } __attribute__((__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_IBMC >= 700) +# define __lzo_struct_packed(s) __lzo_gnuc_extension__ struct s { +# define __lzo_struct_packed_end() } __attribute__((__packed__)); +# define __lzo_struct_packed_ma_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_struct_packed(s) __pragma(pack(push,1)) struct s { +# define __lzo_struct_packed_end() } __pragma(pack(pop)); +#elif (LZO_CC_WATCOMC && (__WATCOMC__ >= 900)) +# define __lzo_struct_packed(s) _Packed struct s { +# define __lzo_struct_packed_end() }; +#endif +#endif +#if defined(__lzo_struct_packed) && !defined(__lzo_struct_packed_ma) +# define __lzo_struct_packed_ma(s) __lzo_struct_packed(s) +#endif +#if defined(__lzo_struct_packed_end) && !defined(__lzo_struct_packed_ma_end) +# define __lzo_struct_packed_ma_end() __lzo_struct_packed_end() +#endif +#if !defined(__lzo_byte_struct) +#if defined(__lzo_struct_packed) +# define __lzo_byte_struct(s,n) __lzo_struct_packed(s) unsigned char a[n]; __lzo_struct_packed_end() +# define __lzo_byte_struct_ma(s,n) __lzo_struct_packed_ma(s) unsigned char a[n]; __lzo_struct_packed_ma_end() +#elif (LZO_CC_CILLY || LZO_CC_CLANG || LZO_CC_PGI || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_byte_struct(s,n) struct s { unsigned char a[n]; } __attribute__((__packed__)); +# define __lzo_byte_struct_ma(s,n) struct s { unsigned char a[n]; } __lzo_may_alias __attribute__((__packed__)); +#endif +#endif +#if defined(__lzo_byte_struct) && !defined(__lzo_byte_struct_ma) +# define __lzo_byte_struct_ma(s,n) __lzo_byte_struct(s,n) +#endif +#if !defined(__lzo_struct_align16) && (__lzo_HAVE_alignof) +#if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x030000ul)) +#elif (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_CILLY || LZO_CC_PCC) +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_struct_align16(s) struct __declspec(align(16)) s { +# define __lzo_struct_align16_end() }; +# define __lzo_struct_align32(s) struct __declspec(align(32)) s { +# define __lzo_struct_align32_end() }; +# define __lzo_struct_align64(s) struct __declspec(align(64)) s { +# define __lzo_struct_align64_end() }; +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || (LZO_CC_IBMC >= 700) || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_struct_align16(s) struct s { +# define __lzo_struct_align16_end() } __attribute__((__aligned__(16))); +# define __lzo_struct_align32(s) struct s { +# define __lzo_struct_align32_end() } __attribute__((__aligned__(32))); +# define __lzo_struct_align64(s) struct s { +# define __lzo_struct_align64_end() } __attribute__((__aligned__(64))); +#endif +#endif +#if !defined(__lzo_union_um) +#if (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020700ul)) +#elif (LZO_CC_GNUC && (LZO_CC_GNUC < 0x020800ul)) && defined(__cplusplus) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER < 810)) +#elif (LZO_CC_PCC && (LZO_CC_PCC < 0x010100ul)) +#elif (LZO_CC_SUNPROC && (LZO_CC_SUNPROC < 0x5110)) && !defined(__cplusplus) +#elif (LZO_CC_ARMCC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || (LZO_CC_PGI >= 0x0d0a00ul) || (LZO_CC_SUNPROC >= 0x5100)) +# define __lzo_union_am(s) union s { +# define __lzo_union_am_end() } __lzo_may_alias; +# define __lzo_union_um(s) union s { +# define __lzo_union_um_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_IBMC >= 700) +# define __lzo_union_am(s) __lzo_gnuc_extension__ union s { +# define __lzo_union_am_end() } __lzo_may_alias; +# define __lzo_union_um(s) __lzo_gnuc_extension__ union s { +# define __lzo_union_um_end() } __lzo_may_alias __attribute__((__packed__)); +#elif (LZO_CC_INTELC_MSC) || (LZO_CC_MSC && (_MSC_VER >= 1300)) +# define __lzo_union_um(s) __pragma(pack(push,1)) union s { +# define __lzo_union_um_end() } __pragma(pack(pop)); +#elif (LZO_CC_WATCOMC && (__WATCOMC__ >= 900)) +# define __lzo_union_um(s) _Packed union s { +# define __lzo_union_um_end() }; +#endif +#endif +#if !defined(__lzo_union_am) +# define __lzo_union_am(s) union s { +# define __lzo_union_am_end() }; +#endif +#if !defined(__lzo_constructor) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_constructor __attribute__((__constructor__,__used__)) +#elif (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_constructor __attribute__((__constructor__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_constructor __attribute__((__constructor__,__used__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_constructor __attribute__((__constructor__)) +#endif +#endif +#if defined(__lzo_constructor) +# ifndef __lzo_HAVE_constructor +# define __lzo_HAVE_constructor 1 +# endif +#endif +#if !defined(__lzo_destructor) +#if (LZO_CC_GNUC >= 0x030400ul) +# define __lzo_destructor __attribute__((__destructor__,__used__)) +#elif (LZO_CC_GNUC >= 0x020700ul) +# define __lzo_destructor __attribute__((__destructor__)) +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 800)) +# define __lzo_destructor __attribute__((__destructor__,__used__)) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_destructor __attribute__((__destructor__)) +#endif +#endif +#if defined(__lzo_destructor) +# ifndef __lzo_HAVE_destructor +# define __lzo_HAVE_destructor 1 +# endif +#endif +#if (__lzo_HAVE_destructor) && !(__lzo_HAVE_constructor) +# error "unexpected configuration - check your compiler defines" +#endif +#if !defined(__lzo_likely) && !defined(__lzo_unlikely) +#if (LZO_CC_GNUC >= 0x030200ul) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_IBMC >= 1010) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_INTELC && (__INTEL_COMPILER >= 800)) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#elif (LZO_CC_CLANG && LZO_CC_CLANG_C2) +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define __lzo_likely(e) (__builtin_expect(!!(e),1)) +# define __lzo_unlikely(e) (__builtin_expect(!!(e),0)) +#endif +#endif +#if defined(__lzo_likely) +# ifndef __lzo_HAVE_likely +# define __lzo_HAVE_likely 1 +# endif +#else +# define __lzo_likely(e) (e) +#endif +#if defined(__lzo_very_likely) +# ifndef __lzo_HAVE_very_likely +# define __lzo_HAVE_very_likely 1 +# endif +#else +# define __lzo_very_likely(e) __lzo_likely(e) +#endif +#if defined(__lzo_unlikely) +# ifndef __lzo_HAVE_unlikely +# define __lzo_HAVE_unlikely 1 +# endif +#else +# define __lzo_unlikely(e) (e) +#endif +#if defined(__lzo_very_unlikely) +# ifndef __lzo_HAVE_very_unlikely +# define __lzo_HAVE_very_unlikely 1 +# endif +#else +# define __lzo_very_unlikely(e) __lzo_unlikely(e) +#endif +#if !defined(__lzo_loop_forever) +# if (LZO_CC_IBMC) +# define __lzo_loop_forever() LZO_BLOCK_BEGIN for (;;) { ; } LZO_BLOCK_END +# else +# define __lzo_loop_forever() do { ; } while __lzo_cte(1) +# endif +#endif +#if !defined(__lzo_unreachable) +#if (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x020800ul)) && lzo_has_builtin(__builtin_unreachable) +# define __lzo_unreachable() __builtin_unreachable(); +#elif (LZO_CC_GNUC >= 0x040500ul) +# define __lzo_unreachable() __builtin_unreachable(); +#elif (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 1300)) && 1 +# define __lzo_unreachable() __builtin_unreachable(); +#endif +#endif +#if defined(__lzo_unreachable) +# ifndef __lzo_HAVE_unreachable +# define __lzo_HAVE_unreachable 1 +# endif +#else +# if 0 +# define __lzo_unreachable() ((void)0); +# else +# define __lzo_unreachable() __lzo_loop_forever(); +# endif +#endif +#if !defined(lzo_unused_funcs_impl) +# if 1 && (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || (LZO_CC_GNUC >= 0x020700ul) || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +# define lzo_unused_funcs_impl(r,f) static r __attribute__((__unused__)) f +# elif 1 && (LZO_CC_BORLANDC || LZO_CC_GNUC) +# define lzo_unused_funcs_impl(r,f) static r f +# else +# define lzo_unused_funcs_impl(r,f) __lzo_static_forceinline r f +# endif +#endif +#ifndef __LZO_CTA_NAME +#if (LZO_CFG_USE_COUNTER) +# define __LZO_CTA_NAME(a) LZO_PP_ECONCAT2(a,__COUNTER__) +#else +# define __LZO_CTA_NAME(a) LZO_PP_ECONCAT2(a,__LINE__) +#endif +#endif +#if !defined(LZO_COMPILE_TIME_ASSERT_HEADER) +# if (LZO_CC_AZTECC || LZO_CC_ZORTECHC) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_DMC || LZO_CC_SYMANTECC) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1u-2*!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-!(e)]; LZO_EXTERN_C_END +# elif (LZO_CC_CLANG && (LZO_CC_CLANG < 0x020900ul)) && defined(__cplusplus) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN int __LZO_CTA_NAME(lzo_cta_f__)(int [1-2*!(e)]); LZO_EXTERN_C_END +# elif (LZO_CC_GNUC) && defined(__CHECKER__) && defined(__SPARSE_CHECKER__) +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN enum {__LZO_CTA_NAME(lzo_cta_e__)=1/!!(e)} __attribute__((__unused__)); LZO_EXTERN_C_END +# else +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) LZO_EXTERN_C_BEGIN extern int __LZO_CTA_NAME(lzo_cta__)[1-2*!(e)]; LZO_EXTERN_C_END +# endif +#endif +#if !defined(LZO_COMPILE_TIME_ASSERT) +# if (LZO_CC_AZTECC) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-!(e)];} +# elif (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x030000ul)) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)] __attribute__((__unused__));} +# elif (LZO_CC_DMC || LZO_CC_PACIFICC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# elif (LZO_CC_GNUC) && defined(__CHECKER__) && defined(__SPARSE_CHECKER__) +# define LZO_COMPILE_TIME_ASSERT(e) {(void) (0/!!(e));} +# elif (LZO_CC_GNUC >= 0x040700ul) && (LZO_CFG_USE_COUNTER) && defined(__cplusplus) +# define LZO_COMPILE_TIME_ASSERT(e) {enum {__LZO_CTA_NAME(lzo_cta_e__)=1/!!(e)} __attribute__((__unused__));} +# elif (LZO_CC_GNUC >= 0x040700ul) +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)] __attribute__((__unused__));} +# elif (LZO_CC_MSC && (_MSC_VER < 900)) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# elif (LZO_CC_TURBOC && (__TURBOC__ == 0x0295)) +# define LZO_COMPILE_TIME_ASSERT(e) switch(0) case 1:case !(e):break; +# else +# define LZO_COMPILE_TIME_ASSERT(e) {typedef int __LZO_CTA_NAME(lzo_cta_t__)[1-2*!(e)];} +# endif +#endif +#if (LZO_LANG_ASSEMBLER) +# undef LZO_COMPILE_TIME_ASSERT_HEADER +# define LZO_COMPILE_TIME_ASSERT_HEADER(e) /*empty*/ +#else +LZO_COMPILE_TIME_ASSERT_HEADER(1 == 1) +#if defined(__cplusplus) +extern "C" { LZO_COMPILE_TIME_ASSERT_HEADER(2 == 2) } +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(3 == 3) +#endif +#if (LZO_ARCH_I086 || LZO_ARCH_I386) && (LZO_OS_DOS16 || LZO_OS_DOS32 || LZO_OS_OS2 || LZO_OS_OS216 || LZO_OS_WIN16 || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC) +# elif (LZO_CC_DMC || LZO_CC_SYMANTECC || LZO_CC_ZORTECHC) +# define __lzo_cdecl __cdecl +# define __lzo_cdecl_atexit /*empty*/ +# define __lzo_cdecl_main __cdecl +# if (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) +# define __lzo_cdecl_qsort __pascal +# elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) +# define __lzo_cdecl_qsort _stdcall +# else +# define __lzo_cdecl_qsort __cdecl +# endif +# elif (LZO_CC_WATCOMC) +# define __lzo_cdecl __cdecl +# else +# define __lzo_cdecl __cdecl +# define __lzo_cdecl_atexit __cdecl +# define __lzo_cdecl_main __cdecl +# define __lzo_cdecl_qsort __cdecl +# endif +# if (LZO_CC_GNUC || LZO_CC_HIGHC || LZO_CC_NDPC || LZO_CC_PACIFICC || LZO_CC_WATCOMC) +# elif (LZO_OS_OS2 && (LZO_CC_DMC || LZO_CC_SYMANTECC)) +# define __lzo_cdecl_sighandler __pascal +# elif (LZO_OS_OS2 && (LZO_CC_ZORTECHC)) +# define __lzo_cdecl_sighandler _stdcall +# elif (LZO_CC_MSC && (_MSC_VER >= 1400)) && defined(_M_CEE_PURE) +# define __lzo_cdecl_sighandler __clrcall +# elif (LZO_CC_MSC && (_MSC_VER >= 600 && _MSC_VER < 700)) +# if defined(_DLL) +# define __lzo_cdecl_sighandler _far _cdecl _loadds +# elif defined(_MT) +# define __lzo_cdecl_sighandler _far _cdecl +# else +# define __lzo_cdecl_sighandler _cdecl +# endif +# else +# define __lzo_cdecl_sighandler __cdecl +# endif +#elif (LZO_ARCH_I386) && (LZO_CC_WATCOMC) +# define __lzo_cdecl __cdecl +#elif (LZO_ARCH_M68K && LZO_OS_TOS && (LZO_CC_PUREC || LZO_CC_TURBOC)) +# define __lzo_cdecl cdecl +#endif +#if !defined(__lzo_cdecl) +# define __lzo_cdecl /*empty*/ +#endif +#if !defined(__lzo_cdecl_atexit) +# define __lzo_cdecl_atexit /*empty*/ +#endif +#if !defined(__lzo_cdecl_main) +# define __lzo_cdecl_main /*empty*/ +#endif +#if !defined(__lzo_cdecl_qsort) +# define __lzo_cdecl_qsort /*empty*/ +#endif +#if !defined(__lzo_cdecl_sighandler) +# define __lzo_cdecl_sighandler /*empty*/ +#endif +#if !defined(__lzo_cdecl_va) +# define __lzo_cdecl_va __lzo_cdecl +#endif +#if !(LZO_CFG_NO_WINDOWS_H) +#if !defined(LZO_HAVE_WINDOWS_H) +#if (LZO_OS_CYGWIN || (LZO_OS_EMX && defined(__RSXNT__)) || LZO_OS_WIN32 || LZO_OS_WIN64) +# if (LZO_CC_WATCOMC && (__WATCOMC__ < 1000)) +# elif ((LZO_OS_WIN32 && defined(__PW32__)) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x030000ul))) +# elif ((LZO_OS_CYGWIN || defined(__MINGW32__)) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x025f00ul))) +# else +# define LZO_HAVE_WINDOWS_H 1 +# endif +#endif +#endif +#endif +#define LZO_SIZEOF_CHAR 1 +#ifndef LZO_SIZEOF_SHORT +#if defined(SIZEOF_SHORT) +# define LZO_SIZEOF_SHORT (SIZEOF_SHORT) +#elif defined(__SIZEOF_SHORT__) +# define LZO_SIZEOF_SHORT (__SIZEOF_SHORT__) +#endif +#endif +#ifndef LZO_SIZEOF_INT +#if defined(SIZEOF_INT) +# define LZO_SIZEOF_INT (SIZEOF_INT) +#elif defined(__SIZEOF_INT__) +# define LZO_SIZEOF_INT (__SIZEOF_INT__) +#endif +#endif +#ifndef LZO_SIZEOF_LONG +#if defined(SIZEOF_LONG) +# define LZO_SIZEOF_LONG (SIZEOF_LONG) +#elif defined(__SIZEOF_LONG__) +# define LZO_SIZEOF_LONG (__SIZEOF_LONG__) +#endif +#endif +#ifndef LZO_SIZEOF_LONG_LONG +#if defined(SIZEOF_LONG_LONG) +# define LZO_SIZEOF_LONG_LONG (SIZEOF_LONG_LONG) +#elif defined(__SIZEOF_LONG_LONG__) +# define LZO_SIZEOF_LONG_LONG (__SIZEOF_LONG_LONG__) +#endif +#endif +#ifndef LZO_SIZEOF___INT16 +#if defined(SIZEOF___INT16) +# define LZO_SIZEOF___INT16 (SIZEOF___INT16) +#endif +#endif +#ifndef LZO_SIZEOF___INT32 +#if defined(SIZEOF___INT32) +# define LZO_SIZEOF___INT32 (SIZEOF___INT32) +#endif +#endif +#ifndef LZO_SIZEOF___INT64 +#if defined(SIZEOF___INT64) +# define LZO_SIZEOF___INT64 (SIZEOF___INT64) +#endif +#endif +#ifndef LZO_SIZEOF_VOID_P +#if defined(SIZEOF_VOID_P) +# define LZO_SIZEOF_VOID_P (SIZEOF_VOID_P) +#elif defined(__SIZEOF_POINTER__) +# define LZO_SIZEOF_VOID_P (__SIZEOF_POINTER__) +#endif +#endif +#ifndef LZO_SIZEOF_SIZE_T +#if defined(SIZEOF_SIZE_T) +# define LZO_SIZEOF_SIZE_T (SIZEOF_SIZE_T) +#elif defined(__SIZEOF_SIZE_T__) +# define LZO_SIZEOF_SIZE_T (__SIZEOF_SIZE_T__) +#endif +#endif +#ifndef LZO_SIZEOF_PTRDIFF_T +#if defined(SIZEOF_PTRDIFF_T) +# define LZO_SIZEOF_PTRDIFF_T (SIZEOF_PTRDIFF_T) +#elif defined(__SIZEOF_PTRDIFF_T__) +# define LZO_SIZEOF_PTRDIFF_T (__SIZEOF_PTRDIFF_T__) +#endif +#endif +#define __LZO_LSR(x,b) (((x)+0ul) >> (b)) +#if !defined(LZO_SIZEOF_SHORT) +# if (LZO_ARCH_CRAY_PVP) +# define LZO_SIZEOF_SHORT 8 +# elif (USHRT_MAX == LZO_0xffffL) +# define LZO_SIZEOF_SHORT 2 +# elif (__LZO_LSR(USHRT_MAX,7) == 1) +# define LZO_SIZEOF_SHORT 1 +# elif (__LZO_LSR(USHRT_MAX,15) == 1) +# define LZO_SIZEOF_SHORT 2 +# elif (__LZO_LSR(USHRT_MAX,31) == 1) +# define LZO_SIZEOF_SHORT 4 +# elif (__LZO_LSR(USHRT_MAX,63) == 1) +# define LZO_SIZEOF_SHORT 8 +# elif (__LZO_LSR(USHRT_MAX,127) == 1) +# define LZO_SIZEOF_SHORT 16 +# else +# error "LZO_SIZEOF_SHORT" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_SHORT == sizeof(short)) +#if !defined(LZO_SIZEOF_INT) +# if (LZO_ARCH_CRAY_PVP) +# define LZO_SIZEOF_INT 8 +# elif (UINT_MAX == LZO_0xffffL) +# define LZO_SIZEOF_INT 2 +# elif (UINT_MAX == LZO_0xffffffffL) +# define LZO_SIZEOF_INT 4 +# elif (__LZO_LSR(UINT_MAX,7) == 1) +# define LZO_SIZEOF_INT 1 +# elif (__LZO_LSR(UINT_MAX,15) == 1) +# define LZO_SIZEOF_INT 2 +# elif (__LZO_LSR(UINT_MAX,31) == 1) +# define LZO_SIZEOF_INT 4 +# elif (__LZO_LSR(UINT_MAX,63) == 1) +# define LZO_SIZEOF_INT 8 +# elif (__LZO_LSR(UINT_MAX,127) == 1) +# define LZO_SIZEOF_INT 16 +# else +# error "LZO_SIZEOF_INT" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_INT == sizeof(int)) +#if !defined(LZO_SIZEOF_LONG) +# if (ULONG_MAX == LZO_0xffffffffL) +# define LZO_SIZEOF_LONG 4 +# elif (__LZO_LSR(ULONG_MAX,7) == 1) +# define LZO_SIZEOF_LONG 1 +# elif (__LZO_LSR(ULONG_MAX,15) == 1) +# define LZO_SIZEOF_LONG 2 +# elif (__LZO_LSR(ULONG_MAX,31) == 1) +# define LZO_SIZEOF_LONG 4 +# elif (__LZO_LSR(ULONG_MAX,39) == 1) +# define LZO_SIZEOF_LONG 5 +# elif (__LZO_LSR(ULONG_MAX,63) == 1) +# define LZO_SIZEOF_LONG 8 +# elif (__LZO_LSR(ULONG_MAX,127) == 1) +# define LZO_SIZEOF_LONG 16 +# else +# error "LZO_SIZEOF_LONG" +# endif +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_LONG == sizeof(long)) +#if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) +#if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) +# if defined(__LONG_MAX__) && defined(__LONG_LONG_MAX__) +# if (LZO_CC_GNUC >= 0x030300ul) +# if ((__LONG_MAX__-0) == (__LONG_LONG_MAX__-0)) +# define LZO_SIZEOF_LONG_LONG LZO_SIZEOF_LONG +# elif (__LZO_LSR(__LONG_LONG_MAX__,30) == 1) +# define LZO_SIZEOF_LONG_LONG 4 +# endif +# endif +# endif +#endif +#endif +#if !defined(LZO_SIZEOF_LONG_LONG) && !defined(LZO_SIZEOF___INT64) +#if (LZO_SIZEOF_LONG > 0 && LZO_SIZEOF_LONG < 8) +#if (LZO_ARCH_I086 && LZO_CC_DMC) +#elif (LZO_CC_CILLY) && defined(__GNUC__) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE) +# define LZO_SIZEOF_LONG_LONG 8 +#elif ((LZO_OS_WIN32 || LZO_OS_WIN64 || defined(_WIN32)) && LZO_CC_MSC && (_MSC_VER >= 1400)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_OS_WIN64 || defined(_WIN64)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_DMC)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_SYMANTECC && (__SC__ >= 0x700))) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_INTELC && defined(__linux__))) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_MWERKS || LZO_CC_PELLESC || LZO_CC_PGI || LZO_CC_SUNPROC)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_ARCH_I386 && (LZO_CC_INTELC || LZO_CC_MSC)) +# define LZO_SIZEOF___INT64 8 +#elif ((LZO_OS_WIN32 || defined(_WIN32)) && (LZO_CC_MSC)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_BORLANDC && (__BORLANDC__ >= 0x0520))) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_ARCH_I386 && (LZO_CC_WATCOMC && (__WATCOMC__ >= 1100))) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_CC_GHS && defined(__LLONG_BIT) && ((__LLONG_BIT-0) == 64)) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_WATCOMC && defined(_INTEGRAL_MAX_BITS) && ((_INTEGRAL_MAX_BITS-0) == 64)) +# define LZO_SIZEOF___INT64 8 +#elif (LZO_OS_OS400 || defined(__OS400__)) && defined(__LLP64_IFC__) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (defined(__vms) || defined(__VMS)) && ((__INITIAL_POINTER_SIZE-0) == 64) +# define LZO_SIZEOF_LONG_LONG 8 +#elif (LZO_CC_SDCC) && (LZO_SIZEOF_INT == 2) +#elif 1 && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) +# define LZO_SIZEOF_LONG_LONG 8 +#endif +#endif +#endif +#if defined(__cplusplus) && (LZO_CC_GNUC) +# if (LZO_CC_GNUC < 0x020800ul) +# undef LZO_SIZEOF_LONG_LONG +# endif +#endif +#if (LZO_CFG_NO_LONG_LONG) +# undef LZO_SIZEOF_LONG_LONG +#elif defined(__NO_LONG_LONG) +# undef LZO_SIZEOF_LONG_LONG +#elif defined(_NO_LONGLONG) +# undef LZO_SIZEOF_LONG_LONG +#endif +#if !defined(LZO_WORDSIZE) +#if (LZO_ARCH_ALPHA) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_AMD64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_ARM64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_AVR) +# define LZO_WORDSIZE 1 +#elif (LZO_ARCH_H8300) +# if defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) +# define LZO_WORDSIZE 4 +# else +# define LZO_WORDSIZE 2 +# endif +#elif (LZO_ARCH_I086) +# define LZO_WORDSIZE 2 +#elif (LZO_ARCH_IA64) +# define LZO_WORDSIZE 8 +#elif (LZO_ARCH_M16C) +# define LZO_WORDSIZE 2 +#elif (LZO_ARCH_SPU) +# define LZO_WORDSIZE 4 +#elif (LZO_ARCH_Z80) +# define LZO_WORDSIZE 1 +#elif (LZO_SIZEOF_LONG == 8) && ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) +# define LZO_WORDSIZE 8 +#elif (LZO_OS_OS400 || defined(__OS400__)) +# define LZO_WORDSIZE 8 +#elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) +# define LZO_WORDSIZE 8 +#endif +#endif +#if !defined(LZO_SIZEOF_VOID_P) +#if defined(__ILP32__) || defined(__ILP32) || defined(_ILP32) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(int) == 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 4) +# define LZO_SIZEOF_VOID_P 4 +#elif defined(__ILP64__) || defined(__ILP64) || defined(_ILP64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(int) == 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 8) +# define LZO_SIZEOF_VOID_P 8 +#elif defined(__LLP64__) || defined(__LLP64) || defined(_LLP64) || defined(_WIN64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 4) +# define LZO_SIZEOF_VOID_P 8 +#elif defined(__LP64__) || defined(__LP64) || defined(_LP64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(long) == 8) +# define LZO_SIZEOF_VOID_P 8 +#elif (LZO_ARCH_AVR) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_ARCH_C166 || LZO_ARCH_MCS51 || LZO_ARCH_MCS251 || LZO_ARCH_MSP430) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_ARCH_H8300) +# if defined(__H8300H__) || defined(__H8300S__) || defined(__H8300SX__) + LZO_COMPILE_TIME_ASSERT_HEADER(LZO_WORDSIZE == 4) +# if defined(__NORMAL_MODE__) +# define LZO_SIZEOF_VOID_P 2 +# else +# define LZO_SIZEOF_VOID_P 4 +# endif +# else + LZO_COMPILE_TIME_ASSERT_HEADER(LZO_WORDSIZE == 2) +# define LZO_SIZEOF_VOID_P 2 +# endif +# if (LZO_CC_GNUC && (LZO_CC_GNUC < 0x040000ul)) && (LZO_SIZEOF_INT == 4) +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_INT +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_INT +# endif +#elif (LZO_ARCH_I086) +# if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM) +# define LZO_SIZEOF_VOID_P 2 +# elif (LZO_MM_COMPACT || LZO_MM_LARGE || LZO_MM_HUGE) +# define LZO_SIZEOF_VOID_P 4 +# else +# error "invalid LZO_ARCH_I086 memory model" +# endif +#elif (LZO_ARCH_M16C) +# if defined(__m32c_cpu__) || defined(__m32cm_cpu__) +# define LZO_SIZEOF_VOID_P 4 +# else +# define LZO_SIZEOF_VOID_P 2 +# endif +#elif (LZO_ARCH_SPU) +# define LZO_SIZEOF_VOID_P 4 +#elif (LZO_ARCH_Z80) +# define LZO_SIZEOF_VOID_P 2 +#elif (LZO_SIZEOF_LONG == 8) && ((defined(__mips__) && defined(__R5900__)) || defined(__MIPS_PSX2__)) +# define LZO_SIZEOF_VOID_P 4 +#elif (LZO_OS_OS400 || defined(__OS400__)) +# if defined(__LLP64_IFC__) +# define LZO_SIZEOF_VOID_P 8 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +# else +# define LZO_SIZEOF_VOID_P 16 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +# endif +#elif (defined(__vms) || defined(__VMS)) && (__INITIAL_POINTER_SIZE+0 == 64) +# define LZO_SIZEOF_VOID_P 8 +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_LONG +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_LONG +#endif +#endif +#if !defined(LZO_SIZEOF_VOID_P) +# define LZO_SIZEOF_VOID_P LZO_SIZEOF_LONG +#endif +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_VOID_P == sizeof(void *)) +#if !defined(LZO_SIZEOF_SIZE_T) +#if (LZO_ARCH_I086 || LZO_ARCH_M16C) +# define LZO_SIZEOF_SIZE_T 2 +#endif +#endif +#if !defined(LZO_SIZEOF_SIZE_T) +# define LZO_SIZEOF_SIZE_T LZO_SIZEOF_VOID_P +#endif +#if defined(offsetof) +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_SIZE_T == sizeof(size_t)) +#endif +#if !defined(LZO_SIZEOF_PTRDIFF_T) +#if (LZO_ARCH_I086) +# if (LZO_MM_TINY || LZO_MM_SMALL || LZO_MM_MEDIUM || LZO_MM_HUGE) +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_VOID_P +# elif (LZO_MM_COMPACT || LZO_MM_LARGE) +# if (LZO_CC_BORLANDC || LZO_CC_TURBOC) +# define LZO_SIZEOF_PTRDIFF_T 4 +# else +# define LZO_SIZEOF_PTRDIFF_T 2 +# endif +# else +# error "invalid LZO_ARCH_I086 memory model" +# endif +#endif +#endif +#if !defined(LZO_SIZEOF_PTRDIFF_T) +# define LZO_SIZEOF_PTRDIFF_T LZO_SIZEOF_SIZE_T +#endif +#if defined(offsetof) +LZO_COMPILE_TIME_ASSERT_HEADER(LZO_SIZEOF_PTRDIFF_T == sizeof(ptrdiff_t)) +#endif +#if !defined(LZO_WORDSIZE) +# define LZO_WORDSIZE LZO_SIZEOF_VOID_P +#endif +#if (LZO_ABI_NEUTRAL_ENDIAN) +# undef LZO_ABI_BIG_ENDIAN +# undef LZO_ABI_LITTLE_ENDIAN +#elif !(LZO_ABI_BIG_ENDIAN) && !(LZO_ABI_LITTLE_ENDIAN) +#if (LZO_ARCH_ALPHA) && (LZO_ARCH_CRAY_MPP) +# define LZO_ABI_BIG_ENDIAN 1 +#elif (LZO_ARCH_IA64) && (LZO_OS_POSIX_LINUX || LZO_OS_WIN64) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif (LZO_ARCH_ALPHA || LZO_ARCH_AMD64 || LZO_ARCH_BLACKFIN || LZO_ARCH_CRIS || LZO_ARCH_I086 || LZO_ARCH_I386 || LZO_ARCH_MSP430 || LZO_ARCH_RISCV) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif (LZO_ARCH_AVR32 || LZO_ARCH_M68K || LZO_ARCH_S390 || LZO_ARCH_SPU) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && defined(__IAR_SYSTEMS_ICC__) && defined(__LITTLE_ENDIAN__) +# if (__LITTLE_ENDIAN__ == 1) +# define LZO_ABI_LITTLE_ENDIAN 1 +# else +# define LZO_ABI_BIG_ENDIAN 1 +# endif +#elif 1 && defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARM_BIG_ENDIAN) && ((__ARM_BIG_ENDIAN)+0) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARMEB__) && !defined(__ARMEL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(__ARMEL__) && !defined(__ARMEB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM) && defined(_MSC_VER) && defined(_WIN32) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM && LZO_CC_ARMCC_ARMCC) +# if defined(__BIG_ENDIAN) && defined(__LITTLE_ENDIAN) +# error "unexpected configuration - check your compiler defines" +# elif defined(__BIG_ENDIAN) +# define LZO_ABI_BIG_ENDIAN 1 +# else +# define LZO_ABI_LITTLE_ENDIAN 1 +# endif +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__ARM_BIG_ENDIAN) && ((__ARM_BIG_ENDIAN)+0) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__AARCH64EB__) && !defined(__AARCH64EL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(__AARCH64EL__) && !defined(__AARCH64EB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_ARM64) && defined(_MSC_VER) && defined(_WIN32) +# define LZO_ABI_LITTLE_ENDIAN 1 +#elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEB__) && !defined(__MIPSEL__) +# define LZO_ABI_BIG_ENDIAN 1 +#elif 1 && (LZO_ARCH_MIPS) && defined(__MIPSEL__) && !defined(__MIPSEB__) +# define LZO_ABI_LITTLE_ENDIAN 1 +#endif +#endif +#if (LZO_ABI_BIG_ENDIAN) && (LZO_ABI_LITTLE_ENDIAN) +# error "unexpected configuration - check your compiler defines" +#endif +#if (LZO_ABI_BIG_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "be" +#elif (LZO_ABI_LITTLE_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "le" +#elif (LZO_ABI_NEUTRAL_ENDIAN) +# define LZO_INFO_ABI_ENDIAN "neutral" +#endif +#if (LZO_SIZEOF_INT == 1 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) +# define LZO_ABI_I8LP16 1 +# define LZO_INFO_ABI_PM "i8lp16" +#elif (LZO_SIZEOF_INT == 2 && LZO_SIZEOF_LONG == 2 && LZO_SIZEOF_VOID_P == 2) +# define LZO_ABI_ILP16 1 +# define LZO_INFO_ABI_PM "ilp16" +#elif (LZO_SIZEOF_INT == 2 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_LP32 1 +# define LZO_INFO_ABI_PM "lp32" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_ILP32 1 +# define LZO_INFO_ABI_PM "ilp32" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 4 && LZO_SIZEOF_VOID_P == 8 && LZO_SIZEOF_SIZE_T == 8) +# define LZO_ABI_LLP64 1 +# define LZO_INFO_ABI_PM "llp64" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) +# define LZO_ABI_LP64 1 +# define LZO_INFO_ABI_PM "lp64" +#elif (LZO_SIZEOF_INT == 8 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 8) +# define LZO_ABI_ILP64 1 +# define LZO_INFO_ABI_PM "ilp64" +#elif (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_LONG == 8 && LZO_SIZEOF_VOID_P == 4) +# define LZO_ABI_IP32L64 1 +# define LZO_INFO_ABI_PM "ip32l64" +#endif +#if (LZO_SIZEOF_INT == 4 && LZO_SIZEOF_VOID_P == 4 && LZO_WORDSIZE == 8) +# define LZO_ABI_IP32W64 1 +# ifndef LZO_INFO_ABI_PM +# define LZO_INFO_ABI_PM "ip32w64" +# endif +#endif +#if 0 +#elif !defined(__LZO_LIBC_OVERRIDE) +#if (LZO_LIBC_NAKED) +# define LZO_INFO_LIBC "naked" +#elif (LZO_LIBC_FREESTANDING) +# define LZO_INFO_LIBC "freestanding" +#elif (LZO_LIBC_MOSTLY_FREESTANDING) +# define LZO_INFO_LIBC "mfreestanding" +#elif (LZO_LIBC_ISOC90) +# define LZO_INFO_LIBC "isoc90" +#elif (LZO_LIBC_ISOC99) +# define LZO_INFO_LIBC "isoc99" +#elif (LZO_CC_ARMCC_ARMCC) && defined(__ARMCLIB_VERSION) +# define LZO_LIBC_ISOC90 1 +# define LZO_INFO_LIBC "isoc90" +#elif defined(__dietlibc__) +# define LZO_LIBC_DIETLIBC 1 +# define LZO_INFO_LIBC "dietlibc" +#elif defined(_NEWLIB_VERSION) +# define LZO_LIBC_NEWLIB 1 +# define LZO_INFO_LIBC "newlib" +#elif defined(__UCLIBC__) && defined(__UCLIBC_MAJOR__) && defined(__UCLIBC_MINOR__) +# if defined(__UCLIBC_SUBLEVEL__) +# define LZO_LIBC_UCLIBC (__UCLIBC_MAJOR__ * 0x10000L + (__UCLIBC_MINOR__-0) * 0x100 + (__UCLIBC_SUBLEVEL__-0)) +# else +# define LZO_LIBC_UCLIBC 0x00090bL +# endif +# define LZO_INFO_LIBC "uc" "libc" +#elif defined(__GLIBC__) && defined(__GLIBC_MINOR__) +# define LZO_LIBC_GLIBC (__GLIBC__ * 0x10000L + (__GLIBC_MINOR__-0) * 0x100) +# define LZO_INFO_LIBC "glibc" +#elif (LZO_CC_MWERKS) && defined(__MSL__) +# define LZO_LIBC_MSL __MSL__ +# define LZO_INFO_LIBC "msl" +#elif 1 && defined(__IAR_SYSTEMS_ICC__) +# define LZO_LIBC_ISOC90 1 +# define LZO_INFO_LIBC "isoc90" +#else +# define LZO_LIBC_DEFAULT 1 +# define LZO_INFO_LIBC "default" +#endif +#endif +#if (LZO_ARCH_I386 && (LZO_OS_DOS32 || LZO_OS_WIN32) && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) +# define LZO_ASM_SYNTAX_MSC 1 +#elif (LZO_OS_WIN64 && (LZO_CC_DMC || LZO_CC_INTELC || LZO_CC_MSC || LZO_CC_PELLESC)) +#elif (LZO_ARCH_I386 && LZO_CC_GNUC && (LZO_CC_GNUC == 0x011f00ul)) +#elif (LZO_ARCH_I386 && (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) +# define LZO_ASM_SYNTAX_GNUC 1 +#elif (LZO_ARCH_AMD64 && (LZO_CC_CLANG || LZO_CC_GNUC || LZO_CC_INTELC || LZO_CC_PATHSCALE)) +# define LZO_ASM_SYNTAX_GNUC 1 +#elif (LZO_CC_GNUC) +# define LZO_ASM_SYNTAX_GNUC 1 +#endif +#if (LZO_ASM_SYNTAX_GNUC) +#if (LZO_ARCH_I386 && LZO_CC_GNUC && (LZO_CC_GNUC < 0x020000ul)) +# define __LZO_ASM_CLOBBER "ax" +# define __LZO_ASM_CLOBBER_LIST_CC /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#elif (LZO_CC_INTELC && (__INTEL_COMPILER < 1000)) +# define __LZO_ASM_CLOBBER "memory" +# define __LZO_ASM_CLOBBER_LIST_CC /*empty*/ +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY : "memory" +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#else +# define __LZO_ASM_CLOBBER "cc", "memory" +# define __LZO_ASM_CLOBBER_LIST_CC : "cc" +# define __LZO_ASM_CLOBBER_LIST_CC_MEMORY : "cc", "memory" +# define __LZO_ASM_CLOBBER_LIST_EMPTY /*empty*/ +#endif +#endif +#if (LZO_ARCH_ALPHA) +# define LZO_OPT_AVOID_UINT_INDEX 1 +#elif (LZO_ARCH_AMD64) +# define LZO_OPT_AVOID_INT_INDEX 1 +# define LZO_OPT_AVOID_UINT_INDEX 1 +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +#elif (LZO_ARCH_ARM) +# if defined(__ARM_FEATURE_UNALIGNED) +# if ((__ARM_FEATURE_UNALIGNED)+0) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +# elif 1 && (LZO_ARCH_ARM_THUMB2) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__ARM_ARCH) && ((__ARM_ARCH)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__TARGET_ARCH_ARM) && ((__TARGET_ARCH_ARM)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(__TARGET_ARCH_ARM) && ((__TARGET_ARCH_ARM)+0 >= 6) && (defined(__TARGET_PROFILE_A) || defined(__TARGET_PROFILE_R)) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# elif 1 && defined(_MSC_VER) && defined(_M_ARM) && ((_M_ARM)+0 >= 7) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +#elif (LZO_ARCH_ARM64) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +#elif (LZO_ARCH_CRIS) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +#elif (LZO_ARCH_I386) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +#elif (LZO_ARCH_IA64) +# define LZO_OPT_AVOID_INT_INDEX 1 +# define LZO_OPT_AVOID_UINT_INDEX 1 +# define LZO_OPT_PREFER_POSTINC 1 +#elif (LZO_ARCH_M68K) +# define LZO_OPT_PREFER_POSTINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +# if defined(__mc68020__) && !defined(__mcoldfire__) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# endif +#elif (LZO_ARCH_MIPS) +# define LZO_OPT_AVOID_UINT_INDEX 1 +#elif (LZO_ARCH_POWERPC) +# define LZO_OPT_PREFER_PREINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +# if (LZO_ABI_BIG_ENDIAN) || (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +# endif +#elif (LZO_ARCH_RISCV) +# define LZO_OPT_AVOID_UINT_INDEX 1 +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +#elif (LZO_ARCH_S390) +# ifndef LZO_OPT_UNALIGNED16 +# define LZO_OPT_UNALIGNED16 1 +# endif +# ifndef LZO_OPT_UNALIGNED32 +# define LZO_OPT_UNALIGNED32 1 +# endif +# if (LZO_WORDSIZE == 8) +# ifndef LZO_OPT_UNALIGNED64 +# define LZO_OPT_UNALIGNED64 1 +# endif +# endif +#elif (LZO_ARCH_SH) +# define LZO_OPT_PREFER_POSTINC 1 +# define LZO_OPT_PREFER_PREDEC 1 +#endif +#ifndef LZO_CFG_NO_INLINE_ASM +#if (LZO_ABI_NEUTRAL_ENDIAN) || (LZO_ARCH_GENERIC) +# define LZO_CFG_NO_INLINE_ASM 1 +#elif (LZO_CC_LLVM) +# define LZO_CFG_NO_INLINE_ASM 1 +#endif +#endif +#if (LZO_CFG_NO_INLINE_ASM) +# undef LZO_ASM_SYNTAX_MSC +# undef LZO_ASM_SYNTAX_GNUC +# undef __LZO_ASM_CLOBBER +# undef __LZO_ASM_CLOBBER_LIST_CC +# undef __LZO_ASM_CLOBBER_LIST_CC_MEMORY +# undef __LZO_ASM_CLOBBER_LIST_EMPTY +#endif +#ifndef LZO_CFG_NO_UNALIGNED +#if (LZO_ABI_NEUTRAL_ENDIAN) || (LZO_ARCH_GENERIC) +# define LZO_CFG_NO_UNALIGNED 1 +#endif +#endif +#if (LZO_CFG_NO_UNALIGNED) +# undef LZO_OPT_UNALIGNED16 +# undef LZO_OPT_UNALIGNED32 +# undef LZO_OPT_UNALIGNED64 +#endif +#if defined(__LZO_INFOSTR_MM) +#elif (LZO_MM_FLAT) && (defined(__LZO_INFOSTR_PM) || defined(LZO_INFO_ABI_PM)) +# define __LZO_INFOSTR_MM "" +#elif defined(LZO_INFO_MM) +# define __LZO_INFOSTR_MM "." LZO_INFO_MM +#else +# define __LZO_INFOSTR_MM "" +#endif +#if defined(__LZO_INFOSTR_PM) +#elif defined(LZO_INFO_ABI_PM) +# define __LZO_INFOSTR_PM "." LZO_INFO_ABI_PM +#else +# define __LZO_INFOSTR_PM "" +#endif +#if defined(__LZO_INFOSTR_ENDIAN) +#elif defined(LZO_INFO_ABI_ENDIAN) +# define __LZO_INFOSTR_ENDIAN "." LZO_INFO_ABI_ENDIAN +#else +# define __LZO_INFOSTR_ENDIAN "" +#endif +#if defined(__LZO_INFOSTR_OSNAME) +#elif defined(LZO_INFO_OS_CONSOLE) +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_CONSOLE +#elif defined(LZO_INFO_OS_POSIX) +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS "." LZO_INFO_OS_POSIX +#else +# define __LZO_INFOSTR_OSNAME LZO_INFO_OS +#endif +#if defined(__LZO_INFOSTR_LIBC) +#elif defined(LZO_INFO_LIBC) +# define __LZO_INFOSTR_LIBC "." LZO_INFO_LIBC +#else +# define __LZO_INFOSTR_LIBC "" +#endif +#if defined(__LZO_INFOSTR_CCVER) +#elif defined(LZO_INFO_CCVER) +# define __LZO_INFOSTR_CCVER " " LZO_INFO_CCVER +#else +# define __LZO_INFOSTR_CCVER "" +#endif +#define LZO_INFO_STRING \ + LZO_INFO_ARCH __LZO_INFOSTR_MM __LZO_INFOSTR_PM __LZO_INFOSTR_ENDIAN \ + " " __LZO_INFOSTR_OSNAME __LZO_INFOSTR_LIBC " " LZO_INFO_CC __LZO_INFOSTR_CCVER +#if !(LZO_CFG_SKIP_LZO_TYPES) +#if (!(LZO_SIZEOF_SHORT+0 > 0 && LZO_SIZEOF_INT+0 > 0 && LZO_SIZEOF_LONG+0 > 0)) +# error "missing defines for sizes" +#endif +#if (!(LZO_SIZEOF_PTRDIFF_T+0 > 0 && LZO_SIZEOF_SIZE_T+0 > 0 && LZO_SIZEOF_VOID_P+0 > 0)) +# error "missing defines for sizes" +#endif +#define LZO_TYPEOF_CHAR 1u +#define LZO_TYPEOF_SHORT 2u +#define LZO_TYPEOF_INT 3u +#define LZO_TYPEOF_LONG 4u +#define LZO_TYPEOF_LONG_LONG 5u +#define LZO_TYPEOF___INT8 17u +#define LZO_TYPEOF___INT16 18u +#define LZO_TYPEOF___INT32 19u +#define LZO_TYPEOF___INT64 20u +#define LZO_TYPEOF___INT128 21u +#define LZO_TYPEOF___INT256 22u +#define LZO_TYPEOF___MODE_QI 33u +#define LZO_TYPEOF___MODE_HI 34u +#define LZO_TYPEOF___MODE_SI 35u +#define LZO_TYPEOF___MODE_DI 36u +#define LZO_TYPEOF___MODE_TI 37u +#define LZO_TYPEOF_CHAR_P 129u +#if !defined(lzo_llong_t) +#if (LZO_SIZEOF_LONG_LONG+0 > 0) +# if !(LZO_LANG_ASSEMBLER) + __lzo_gnuc_extension__ typedef long long lzo_llong_t__; + __lzo_gnuc_extension__ typedef unsigned long long lzo_ullong_t__; +# endif +# define lzo_llong_t lzo_llong_t__ +# define lzo_ullong_t lzo_ullong_t__ +#endif +#endif +#if !defined(lzo_int16e_t) +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) && (LZO_SIZEOF_SHORT != 2) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T +#endif +#if (LZO_SIZEOF_LONG == 2) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) +# define lzo_int16e_t long +# define lzo_uint16e_t unsigned long +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_INT == 2) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT16E_T == LZO_TYPEOF_SHORT) +# define lzo_int16e_t int +# define lzo_uint16e_t unsigned int +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == 2) +# define lzo_int16e_t short int +# define lzo_uint16e_t unsigned short int +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF_SHORT +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_HI) && (LZO_CC_CLANG || (LZO_CC_GNUC >= 0x025f00ul) || LZO_CC_LLVM) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int16e_hi_t__ __attribute__((__mode__(__HI__))); + typedef unsigned int lzo_uint16e_hi_t__ __attribute__((__mode__(__HI__))); +# endif +# define lzo_int16e_t lzo_int16e_hi_t__ +# define lzo_uint16e_t lzo_uint16e_hi_t__ +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF___MODE_HI +#elif (LZO_SIZEOF___INT16 == 2) +# define lzo_int16e_t __int16 +# define lzo_uint16e_t unsigned __int16 +# define LZO_TYPEOF_LZO_INT16E_T LZO_TYPEOF___INT16 +#else +#endif +#endif +#if defined(lzo_int16e_t) +# define LZO_SIZEOF_LZO_INT16E_T 2 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16e_t) == 2) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16e_t) == LZO_SIZEOF_LZO_INT16E_T) +#endif +#if !defined(lzo_int32e_t) +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T == LZO_TYPEOF_INT) && (LZO_SIZEOF_INT != 4) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T +#endif +#if (LZO_SIZEOF_LONG == 4) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT32E_T == LZO_TYPEOF_INT) +# define lzo_int32e_t long int +# define lzo_uint32e_t unsigned long int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_INT == 4) +# define lzo_int32e_t int +# define lzo_uint32e_t unsigned int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == 4) +# define lzo_int32e_t short int +# define lzo_uint32e_t unsigned short int +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_SHORT +#elif (LZO_SIZEOF_LONG_LONG == 4) +# define lzo_int32e_t lzo_llong_t +# define lzo_uint32e_t lzo_ullong_t +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF_LONG_LONG +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_SI) && (LZO_CC_CLANG || (LZO_CC_GNUC >= 0x025f00ul) || LZO_CC_LLVM) && (__INT_MAX__+0 > 2147483647L) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int32e_si_t__ __attribute__((__mode__(__SI__))); + typedef unsigned int lzo_uint32e_si_t__ __attribute__((__mode__(__SI__))); +# endif +# define lzo_int32e_t lzo_int32e_si_t__ +# define lzo_uint32e_t lzo_uint32e_si_t__ +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___MODE_SI +#elif 1 && !(LZO_CFG_TYPE_NO_MODE_SI) && (LZO_CC_GNUC >= 0x025f00ul) && defined(__AVR__) && (__LONG_MAX__+0 == 32767L) +# if !(LZO_LANG_ASSEMBLER) + typedef int lzo_int32e_si_t__ __attribute__((__mode__(__SI__))); + typedef unsigned int lzo_uint32e_si_t__ __attribute__((__mode__(__SI__))); +# endif +# define lzo_int32e_t lzo_int32e_si_t__ +# define lzo_uint32e_t lzo_uint32e_si_t__ +# define LZO_INT32_C(c) (c##LL) +# define LZO_UINT32_C(c) (c##ULL) +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___MODE_SI +#elif (LZO_SIZEOF___INT32 == 4) +# define lzo_int32e_t __int32 +# define lzo_uint32e_t unsigned __int32 +# define LZO_TYPEOF_LZO_INT32E_T LZO_TYPEOF___INT32 +#else +#endif +#endif +#if defined(lzo_int32e_t) +# define LZO_SIZEOF_LZO_INT32E_T 4 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32e_t) == 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32e_t) == LZO_SIZEOF_LZO_INT32E_T) +#endif +#if !defined(lzo_int64e_t) +#if (LZO_SIZEOF___INT64 == 8) +# if (LZO_CC_BORLANDC) && !defined(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T) +# define LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T LZO_TYPEOF___INT64 +# endif +#endif +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF_LONG_LONG) && (LZO_SIZEOF_LONG_LONG != 8) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T +#endif +#if (LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) && (LZO_SIZEOF___INT64 != 8) +# undef LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T +#endif +#if (LZO_SIZEOF_INT == 8) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_int64e_t int +# define lzo_uint64e_t unsigned int +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_LONG == 8) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF_LONG_LONG) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) +# define lzo_int64e_t long int +# define lzo_uint64e_t unsigned long int +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_LONG_LONG == 8) && !(LZO_CFG_PREFER_TYPEOF_ACC_INT64E_T == LZO_TYPEOF___INT64) +# define lzo_int64e_t lzo_llong_t +# define lzo_uint64e_t lzo_ullong_t +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF_LONG_LONG +# if (LZO_CC_BORLANDC) +# define LZO_INT64_C(c) ((c) + 0ll) +# define LZO_UINT64_C(c) ((c) + 0ull) +# elif 0 +# define LZO_INT64_C(c) (__lzo_gnuc_extension__ (c##LL)) +# define LZO_UINT64_C(c) (__lzo_gnuc_extension__ (c##ULL)) +# else +# define LZO_INT64_C(c) (c##LL) +# define LZO_UINT64_C(c) (c##ULL) +# endif +#elif (LZO_SIZEOF___INT64 == 8) +# define lzo_int64e_t __int64 +# define lzo_uint64e_t unsigned __int64 +# define LZO_TYPEOF_LZO_INT64E_T LZO_TYPEOF___INT64 +# if (LZO_CC_BORLANDC) +# define LZO_INT64_C(c) ((c) + 0i64) +# define LZO_UINT64_C(c) ((c) + 0ui64) +# else +# define LZO_INT64_C(c) (c##i64) +# define LZO_UINT64_C(c) (c##ui64) +# endif +#else +#endif +#endif +#if defined(lzo_int64e_t) +# define LZO_SIZEOF_LZO_INT64E_T 8 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64e_t) == 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64e_t) == LZO_SIZEOF_LZO_INT64E_T) +#endif +#if !defined(lzo_int32l_t) +#if defined(lzo_int32e_t) +# define lzo_int32l_t lzo_int32e_t +# define lzo_uint32l_t lzo_uint32e_t +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_LZO_INT32E_T +# define LZO_TYPEOF_LZO_INT32L_T LZO_TYPEOF_LZO_INT32E_T +#elif (LZO_SIZEOF_INT >= 4) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_int32l_t int +# define lzo_uint32l_t unsigned int +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INT32L_T LZO_SIZEOF_INT +#elif (LZO_SIZEOF_LONG >= 4) +# define lzo_int32l_t long int +# define lzo_uint32l_t unsigned long int +# define LZO_SIZEOF_LZO_INT32L_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_INT32L_T LZO_SIZEOF_LONG +#else +# error "lzo_int32l_t" +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32l_t) >= 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32l_t) == LZO_SIZEOF_LZO_INT32L_T) +#endif +#if !defined(lzo_int64l_t) +#if defined(lzo_int64e_t) +# define lzo_int64l_t lzo_int64e_t +# define lzo_uint64l_t lzo_uint64e_t +# define LZO_SIZEOF_LZO_INT64L_T LZO_SIZEOF_LZO_INT64E_T +# define LZO_TYPEOF_LZO_INT64L_T LZO_TYPEOF_LZO_INT64E_T +#else +#endif +#endif +#if defined(lzo_int64l_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64l_t) >= 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64l_t) == LZO_SIZEOF_LZO_INT64L_T) +#endif +#if !defined(lzo_int32f_t) +#if (LZO_SIZEOF_SIZE_T >= 8) +# define lzo_int32f_t lzo_int64l_t +# define lzo_uint32f_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INT32F_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INT32F_T LZO_TYPEOF_LZO_INT64L_T +#else +# define lzo_int32f_t lzo_int32l_t +# define lzo_uint32f_t lzo_uint32l_t +# define LZO_SIZEOF_LZO_INT32F_T LZO_SIZEOF_LZO_INT32L_T +# define LZO_TYPEOF_LZO_INT32F_T LZO_TYPEOF_LZO_INT32L_T +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32f_t) >= 4) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32f_t) == LZO_SIZEOF_LZO_INT32F_T) +#endif +#if !defined(lzo_int64f_t) +#if defined(lzo_int64l_t) +# define lzo_int64f_t lzo_int64l_t +# define lzo_uint64f_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INT64F_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INT64F_T LZO_TYPEOF_LZO_INT64L_T +#else +#endif +#endif +#if defined(lzo_int64f_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64f_t) >= 8) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64f_t) == LZO_SIZEOF_LZO_INT64F_T) +#endif +#if !defined(lzo_intptr_t) +#if 1 && (LZO_OS_OS400 && (LZO_SIZEOF_VOID_P == 16)) +# define __LZO_INTPTR_T_IS_POINTER 1 +# if !(LZO_LANG_ASSEMBLER) + typedef char * lzo_intptr_t; + typedef char * lzo_uintptr_t; +# endif +# define lzo_intptr_t lzo_intptr_t +# define lzo_uintptr_t lzo_uintptr_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_VOID_P +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_CHAR_P +#elif (LZO_CC_MSC && (_MSC_VER >= 1300) && (LZO_SIZEOF_VOID_P == 4) && (LZO_SIZEOF_INT == 4)) +# if !(LZO_LANG_ASSEMBLER) + typedef __w64 int lzo_intptr_t; + typedef __w64 unsigned int lzo_uintptr_t; +# endif +# define lzo_intptr_t lzo_intptr_t +# define lzo_uintptr_t lzo_uintptr_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_SHORT == LZO_SIZEOF_VOID_P) && (LZO_SIZEOF_INT > LZO_SIZEOF_VOID_P) +# define lzo_intptr_t short +# define lzo_uintptr_t unsigned short +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_SHORT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_SHORT +#elif (LZO_SIZEOF_INT >= LZO_SIZEOF_VOID_P) && (LZO_SIZEOF_INT < LZO_SIZEOF_LONG) +# define lzo_intptr_t int +# define lzo_uintptr_t unsigned int +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_INT +#elif (LZO_SIZEOF_LONG >= LZO_SIZEOF_VOID_P) +# define lzo_intptr_t long +# define lzo_uintptr_t unsigned long +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_LONG +#elif (LZO_SIZEOF_LZO_INT64L_T >= LZO_SIZEOF_VOID_P) +# define lzo_intptr_t lzo_int64l_t +# define lzo_uintptr_t lzo_uint64l_t +# define LZO_SIZEOF_LZO_INTPTR_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_INTPTR_T LZO_TYPEOF_LZO_INT64L_T +#else +# error "lzo_intptr_t" +#endif +#endif +#if 1 + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_intptr_t) >= sizeof(void *)) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_intptr_t) == sizeof(lzo_uintptr_t)) +#endif +#if !defined(lzo_word_t) +#if defined(LZO_WORDSIZE) && (LZO_WORDSIZE+0 > 0) +#if (LZO_WORDSIZE == LZO_SIZEOF_LZO_INTPTR_T) && !(__LZO_INTPTR_T_IS_POINTER) +# define lzo_word_t lzo_uintptr_t +# define lzo_sword_t lzo_intptr_t +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LZO_INTPTR_T +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_LZO_INTPTR_T +#elif (LZO_WORDSIZE == LZO_SIZEOF_LONG) +# define lzo_word_t unsigned long +# define lzo_sword_t long +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LONG +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_LONG +#elif (LZO_WORDSIZE == LZO_SIZEOF_INT) +# define lzo_word_t unsigned int +# define lzo_sword_t int +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_INT +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_INT +#elif (LZO_WORDSIZE == LZO_SIZEOF_SHORT) +# define lzo_word_t unsigned short +# define lzo_sword_t short +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_SHORT +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_SHORT +#elif (LZO_WORDSIZE == 1) +# define lzo_word_t unsigned char +# define lzo_sword_t signed char +# define LZO_SIZEOF_LZO_WORD_T 1 +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF_CHAR +#elif (LZO_WORDSIZE == LZO_SIZEOF_LZO_INT64L_T) +# define lzo_word_t lzo_uint64l_t +# define lzo_sword_t lzo_int64l_t +# define LZO_SIZEOF_LZO_WORD_T LZO_SIZEOF_LZO_INT64L_T +# define LZO_TYPEOF_LZO_WORD_T LZO_SIZEOF_LZO_INT64L_T +#elif (LZO_ARCH_SPU) && (LZO_CC_GNUC) +#if 0 +# if !(LZO_LANG_ASSEMBLER) + typedef unsigned lzo_word_t __attribute__((__mode__(__V16QI__))); + typedef int lzo_sword_t __attribute__((__mode__(__V16QI__))); +# endif +# define lzo_word_t lzo_word_t +# define lzo_sword_t lzo_sword_t +# define LZO_SIZEOF_LZO_WORD_T 16 +# define LZO_TYPEOF_LZO_WORD_T LZO_TYPEOF___MODE_V16QI +#endif +#else +# error "lzo_word_t" +#endif +#endif +#endif +#if 1 && defined(lzo_word_t) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_word_t) == LZO_WORDSIZE) + LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_sword_t) == LZO_WORDSIZE) +#endif +#if 1 +#define lzo_int8_t signed char +#define lzo_uint8_t unsigned char +#define LZO_SIZEOF_LZO_INT8_T 1 +#define LZO_TYPEOF_LZO_INT8_T LZO_TYPEOF_CHAR +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int8_t) == 1) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int8_t) == sizeof(lzo_uint8_t)) +#endif +#if defined(lzo_int16e_t) +#define lzo_int16_t lzo_int16e_t +#define lzo_uint16_t lzo_uint16e_t +#define LZO_SIZEOF_LZO_INT16_T LZO_SIZEOF_LZO_INT16E_T +#define LZO_TYPEOF_LZO_INT16_T LZO_TYPEOF_LZO_INT16E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16_t) == 2) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16_t) == sizeof(lzo_uint16_t)) +#endif +#if defined(lzo_int32e_t) +#define lzo_int32_t lzo_int32e_t +#define lzo_uint32_t lzo_uint32e_t +#define LZO_SIZEOF_LZO_INT32_T LZO_SIZEOF_LZO_INT32E_T +#define LZO_TYPEOF_LZO_INT32_T LZO_TYPEOF_LZO_INT32E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32_t) == 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32_t) == sizeof(lzo_uint32_t)) +#endif +#if defined(lzo_int64e_t) +#define lzo_int64_t lzo_int64e_t +#define lzo_uint64_t lzo_uint64e_t +#define LZO_SIZEOF_LZO_INT64_T LZO_SIZEOF_LZO_INT64E_T +#define LZO_TYPEOF_LZO_INT64_T LZO_TYPEOF_LZO_INT64E_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64_t) == 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64_t) == sizeof(lzo_uint64_t)) +#endif +#if 1 +#define lzo_int_least32_t lzo_int32l_t +#define lzo_uint_least32_t lzo_uint32l_t +#define LZO_SIZEOF_LZO_INT_LEAST32_T LZO_SIZEOF_LZO_INT32L_T +#define LZO_TYPEOF_LZO_INT_LEAST32_T LZO_TYPEOF_LZO_INT32L_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least32_t) >= 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least32_t) == sizeof(lzo_uint_least32_t)) +#endif +#if defined(lzo_int64l_t) +#define lzo_int_least64_t lzo_int64l_t +#define lzo_uint_least64_t lzo_uint64l_t +#define LZO_SIZEOF_LZO_INT_LEAST64_T LZO_SIZEOF_LZO_INT64L_T +#define LZO_TYPEOF_LZO_INT_LEAST64_T LZO_TYPEOF_LZO_INT64L_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least64_t) >= 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_least64_t) == sizeof(lzo_uint_least64_t)) +#endif +#if 1 +#define lzo_int_fast32_t lzo_int32f_t +#define lzo_uint_fast32_t lzo_uint32f_t +#define LZO_SIZEOF_LZO_INT_FAST32_T LZO_SIZEOF_LZO_INT32F_T +#define LZO_TYPEOF_LZO_INT_FAST32_T LZO_TYPEOF_LZO_INT32F_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast32_t) >= 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast32_t) == sizeof(lzo_uint_fast32_t)) +#endif +#if defined(lzo_int64f_t) +#define lzo_int_fast64_t lzo_int64f_t +#define lzo_uint_fast64_t lzo_uint64f_t +#define LZO_SIZEOF_LZO_INT_FAST64_T LZO_SIZEOF_LZO_INT64F_T +#define LZO_TYPEOF_LZO_INT_FAST64_T LZO_TYPEOF_LZO_INT64F_T +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast64_t) >= 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int_fast64_t) == sizeof(lzo_uint_fast64_t)) +#endif +#if !defined(LZO_INT16_C) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 2) +# define LZO_INT16_C(c) ((c) + 0) +# define LZO_UINT16_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 2) +# define LZO_INT16_C(c) ((c) + 0L) +# define LZO_UINT16_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 2) +# define LZO_INT16_C(c) (c) +# define LZO_UINT16_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 2) +# define LZO_INT16_C(c) (c##L) +# define LZO_UINT16_C(c) (c##UL) +# else +# error "LZO_INT16_C" +# endif +#endif +#if !defined(LZO_INT32_C) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 4) +# define LZO_INT32_C(c) ((c) + 0) +# define LZO_UINT32_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 4) +# define LZO_INT32_C(c) ((c) + 0L) +# define LZO_UINT32_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 4) +# define LZO_INT32_C(c) (c) +# define LZO_UINT32_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 4) +# define LZO_INT32_C(c) (c##L) +# define LZO_UINT32_C(c) (c##UL) +# elif (LZO_SIZEOF_LONG_LONG >= 4) +# define LZO_INT32_C(c) (c##LL) +# define LZO_UINT32_C(c) (c##ULL) +# else +# error "LZO_INT32_C" +# endif +#endif +#if !defined(LZO_INT64_C) && defined(lzo_int64l_t) +# if (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_INT >= 8) +# define LZO_INT64_C(c) ((c) + 0) +# define LZO_UINT64_C(c) ((c) + 0U) +# elif (LZO_BROKEN_INTEGRAL_CONSTANTS) && (LZO_SIZEOF_LONG >= 8) +# define LZO_INT64_C(c) ((c) + 0L) +# define LZO_UINT64_C(c) ((c) + 0UL) +# elif (LZO_SIZEOF_INT >= 8) +# define LZO_INT64_C(c) (c) +# define LZO_UINT64_C(c) (c##U) +# elif (LZO_SIZEOF_LONG >= 8) +# define LZO_INT64_C(c) (c##L) +# define LZO_UINT64_C(c) (c##UL) +# else +# error "LZO_INT64_C" +# endif +#endif +#endif + +#endif + +#endif + +#undef LZO_HAVE_CONFIG_H +#include "minilzo.h" + +#if !defined(MINILZO_VERSION) || (MINILZO_VERSION != 0x20a0) +# error "version mismatch in miniLZO source files" +#endif + +#ifdef MINILZO_HAVE_CONFIG_H +# define LZO_HAVE_CONFIG_H 1 +#endif + +#ifndef __LZO_CONF_H +#define __LZO_CONF_H 1 + +#if !defined(__LZO_IN_MINILZO) +#if defined(LZO_CFG_FREESTANDING) && (LZO_CFG_FREESTANDING) +# define LZO_LIBC_FREESTANDING 1 +# define LZO_OS_FREESTANDING 1 +#endif +#if defined(LZO_CFG_EXTRA_CONFIG_HEADER) +# include LZO_CFG_EXTRA_CONFIG_HEADER +#endif +#if defined(__LZOCONF_H) || defined(__LZOCONF_H_INCLUDED) +# error "include this file first" +#endif +#if defined(LZO_CFG_BUILD_DLL) && (LZO_CFG_BUILD_DLL+0) && !defined(__LZO_EXPORT1) && !defined(__LZO_EXPORT2) && 0 +#ifndef __LZODEFS_H_INCLUDED +#if defined(LZO_HAVE_CONFIG_H) +# include +#endif +#include +#include +#include +#endif +#endif +#include +#if defined(LZO_CFG_EXTRA_CONFIG_HEADER2) +# include LZO_CFG_EXTRA_CONFIG_HEADER2 +#endif +#endif + +#if !defined(__LZOCONF_H_INCLUDED) || (LZO_VERSION+0 != 0x20a0) +# error "version mismatch" +#endif + +#if (LZO_CC_MSC && (_MSC_VER >= 1000 && _MSC_VER < 1100)) +# pragma warning(disable: 4702) +#endif +#if (LZO_CC_MSC && (_MSC_VER >= 1000)) +# pragma warning(disable: 4127 4701) +# pragma warning(disable: 4514 4710 4711) +#endif +#if (LZO_CC_MSC && (_MSC_VER >= 1300)) +# pragma warning(disable: 4820) +#endif +#if (LZO_CC_MSC && (_MSC_VER >= 1800)) +# pragma warning(disable: 4746) +#endif +#if (LZO_CC_INTELC && (__INTEL_COMPILER >= 900)) +# pragma warning(disable: 1684) +#endif + +#if (LZO_CC_SUNPROC) +#if !defined(__cplusplus) +# pragma error_messages(off,E_END_OF_LOOP_CODE_NOT_REACHED) +# pragma error_messages(off,E_LOOP_NOT_ENTERED_AT_TOP) +# pragma error_messages(off,E_STATEMENT_NOT_REACHED) +#endif +#endif + +#if !defined(__LZO_NOEXPORT1) +# define __LZO_NOEXPORT1 /*empty*/ +#endif +#if !defined(__LZO_NOEXPORT2) +# define __LZO_NOEXPORT2 /*empty*/ +#endif + +#if 1 +# define LZO_PUBLIC_DECL(r) LZO_EXTERN(r) +#endif +#if 1 +# define LZO_PUBLIC_IMPL(r) LZO_PUBLIC(r) +#endif +#if !defined(LZO_LOCAL_DECL) +# define LZO_LOCAL_DECL(r) __LZO_EXTERN_C LZO_LOCAL_IMPL(r) +#endif +#if !defined(LZO_LOCAL_IMPL) +# define LZO_LOCAL_IMPL(r) __LZO_NOEXPORT1 r __LZO_NOEXPORT2 __LZO_CDECL +#endif +#if 1 +# define LZO_STATIC_DECL(r) LZO_PRIVATE(r) +#endif +#if 1 +# define LZO_STATIC_IMPL(r) LZO_PRIVATE(r) +#endif + +#if defined(__LZO_IN_MINILZO) || (LZO_CFG_FREESTANDING) +#elif 1 +# include +#else +# define LZO_WANT_ACC_INCD_H 1 +#endif +#if defined(LZO_HAVE_CONFIG_H) +# define LZO_CFG_NO_CONFIG_HEADER 1 +#endif + +#if 1 && !defined(LZO_CFG_FREESTANDING) +#if 1 && !defined(HAVE_STRING_H) +#define HAVE_STRING_H 1 +#endif +#if 1 && !defined(HAVE_MEMCMP) +#define HAVE_MEMCMP 1 +#endif +#if 1 && !defined(HAVE_MEMCPY) +#define HAVE_MEMCPY 1 +#endif +#if 1 && !defined(HAVE_MEMMOVE) +#define HAVE_MEMMOVE 1 +#endif +#if 1 && !defined(HAVE_MEMSET) +#define HAVE_MEMSET 1 +#endif +#endif + +#if 1 && defined(HAVE_STRING_H) +#include +#endif + +#if 1 || defined(lzo_int8_t) || defined(lzo_uint8_t) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int8_t) == 1) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint8_t) == 1) +#endif +#if 1 || defined(lzo_int16_t) || defined(lzo_uint16_t) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int16_t) == 2) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint16_t) == 2) +#endif +#if 1 || defined(lzo_int32_t) || defined(lzo_uint32_t) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int32_t) == 4) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint32_t) == 4) +#endif +#if defined(lzo_int64_t) || defined(lzo_uint64_t) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_int64_t) == 8) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(lzo_uint64_t) == 8) +#endif + +#if (LZO_CFG_FREESTANDING) +# undef HAVE_MEMCMP +# undef HAVE_MEMCPY +# undef HAVE_MEMMOVE +# undef HAVE_MEMSET +#endif + +#if !(HAVE_MEMCMP) +# undef memcmp +# define memcmp(a,b,c) lzo_memcmp(a,b,c) +#else +# undef lzo_memcmp +# define lzo_memcmp(a,b,c) memcmp(a,b,c) +#endif +#if !(HAVE_MEMCPY) +# undef memcpy +# define memcpy(a,b,c) lzo_memcpy(a,b,c) +#else +# undef lzo_memcpy +# define lzo_memcpy(a,b,c) memcpy(a,b,c) +#endif +#if !(HAVE_MEMMOVE) +# undef memmove +# define memmove(a,b,c) lzo_memmove(a,b,c) +#else +# undef lzo_memmove +# define lzo_memmove(a,b,c) memmove(a,b,c) +#endif +#if !(HAVE_MEMSET) +# undef memset +# define memset(a,b,c) lzo_memset(a,b,c) +#else +# undef lzo_memset +# define lzo_memset(a,b,c) memset(a,b,c) +#endif + +#undef NDEBUG +#if (LZO_CFG_FREESTANDING) +# undef LZO_DEBUG +# define NDEBUG 1 +# undef assert +# define assert(e) ((void)0) +#else +# if !defined(LZO_DEBUG) +# define NDEBUG 1 +# endif +# include +#endif + +#if 0 && defined(__BOUNDS_CHECKING_ON) +# include +#else +# define BOUNDS_CHECKING_OFF_DURING(stmt) stmt +# define BOUNDS_CHECKING_OFF_IN_EXPR(expr) (expr) +#endif + +#if (LZO_CFG_PGO) +# undef __lzo_likely +# undef __lzo_unlikely +# define __lzo_likely(e) (e) +# define __lzo_unlikely(e) (e) +#endif + +#undef _ +#undef __ +#undef ___ +#undef ____ +#undef _p0 +#undef _p1 +#undef _p2 +#undef _p3 +#undef _p4 +#undef _s0 +#undef _s1 +#undef _s2 +#undef _s3 +#undef _s4 +#undef _ww + +#if 1 +# define LZO_BYTE(x) ((unsigned char) (x)) +#else +# define LZO_BYTE(x) ((unsigned char) ((x) & 0xff)) +#endif + +#define LZO_MAX(a,b) ((a) >= (b) ? (a) : (b)) +#define LZO_MIN(a,b) ((a) <= (b) ? (a) : (b)) +#define LZO_MAX3(a,b,c) ((a) >= (b) ? LZO_MAX(a,c) : LZO_MAX(b,c)) +#define LZO_MIN3(a,b,c) ((a) <= (b) ? LZO_MIN(a,c) : LZO_MIN(b,c)) + +#define lzo_sizeof(type) ((lzo_uint) (sizeof(type))) + +#define LZO_HIGH(array) ((lzo_uint) (sizeof(array)/sizeof(*(array)))) + +#define LZO_SIZE(bits) (1u << (bits)) +#define LZO_MASK(bits) (LZO_SIZE(bits) - 1) + +#define LZO_USIZE(bits) ((lzo_uint) 1 << (bits)) +#define LZO_UMASK(bits) (LZO_USIZE(bits) - 1) + +#if !defined(DMUL) +#if 0 + +# define DMUL(a,b) ((lzo_xint) ((lzo_uint32_t)(a) * (lzo_uint32_t)(b))) +#else +# define DMUL(a,b) ((lzo_xint) ((a) * (b))) +#endif +#endif + +#ifndef __LZO_FUNC_H +#define __LZO_FUNC_H 1 + +#if !defined(LZO_BITOPS_USE_ASM_BITSCAN) && !defined(LZO_BITOPS_USE_GNUC_BITSCAN) && !defined(LZO_BITOPS_USE_MSC_BITSCAN) +#if 1 && (LZO_ARCH_AMD64) && (LZO_CC_GNUC && (LZO_CC_GNUC < 0x040000ul)) && (LZO_ASM_SYNTAX_GNUC) +#define LZO_BITOPS_USE_ASM_BITSCAN 1 +#elif (LZO_CC_CLANG || (LZO_CC_GNUC >= 0x030400ul) || (LZO_CC_INTELC_GNUC && (__INTEL_COMPILER >= 1000)) || (LZO_CC_LLVM && (!defined(__llvm_tools_version__) || (__llvm_tools_version__+0 >= 0x010500ul)))) +#define LZO_BITOPS_USE_GNUC_BITSCAN 1 +#elif (LZO_OS_WIN32 || LZO_OS_WIN64) && ((LZO_CC_INTELC_MSC && (__INTEL_COMPILER >= 1010)) || (LZO_CC_MSC && (_MSC_VER >= 1400))) +#define LZO_BITOPS_USE_MSC_BITSCAN 1 +#if (LZO_CC_MSC) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) +#include +#endif +#if (LZO_CC_MSC) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) +#pragma intrinsic(_BitScanReverse) +#pragma intrinsic(_BitScanForward) +#endif +#if (LZO_CC_MSC) && (LZO_ARCH_AMD64) +#pragma intrinsic(_BitScanReverse64) +#pragma intrinsic(_BitScanForward64) +#endif +#endif +#endif + +__lzo_static_forceinline unsigned lzo_bitops_ctlz32_func(lzo_uint32_t v) +{ +#if (LZO_BITOPS_USE_MSC_BITSCAN) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) + unsigned long r; (void) _BitScanReverse(&r, v); return (unsigned) r ^ 31; +#define lzo_bitops_ctlz32(v) lzo_bitops_ctlz32_func(v) +#elif (LZO_BITOPS_USE_ASM_BITSCAN) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) && (LZO_ASM_SYNTAX_GNUC) + lzo_uint32_t r; + __asm__("bsr %1,%0" : "=r" (r) : "rm" (v) __LZO_ASM_CLOBBER_LIST_CC); + return (unsigned) r ^ 31; +#define lzo_bitops_ctlz32(v) lzo_bitops_ctlz32_func(v) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_INT == 4) + unsigned r; r = (unsigned) __builtin_clz(v); return r; +#define lzo_bitops_ctlz32(v) ((unsigned) __builtin_clz(v)) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_LONG == 8) && (LZO_WORDSIZE >= 8) + unsigned r; r = (unsigned) __builtin_clzl(v); return r ^ 32; +#define lzo_bitops_ctlz32(v) (((unsigned) __builtin_clzl(v)) ^ 32) +#else + LZO_UNUSED(v); return 0; +#endif +} + +#if defined(lzo_uint64_t) +__lzo_static_forceinline unsigned lzo_bitops_ctlz64_func(lzo_uint64_t v) +{ +#if (LZO_BITOPS_USE_MSC_BITSCAN) && (LZO_ARCH_AMD64) + unsigned long r; (void) _BitScanReverse64(&r, v); return (unsigned) r ^ 63; +#define lzo_bitops_ctlz64(v) lzo_bitops_ctlz64_func(v) +#elif (LZO_BITOPS_USE_ASM_BITSCAN) && (LZO_ARCH_AMD64) && (LZO_ASM_SYNTAX_GNUC) + lzo_uint64_t r; + __asm__("bsr %1,%0" : "=r" (r) : "rm" (v) __LZO_ASM_CLOBBER_LIST_CC); + return (unsigned) r ^ 63; +#define lzo_bitops_ctlz64(v) lzo_bitops_ctlz64_func(v) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_LONG == 8) && (LZO_WORDSIZE >= 8) + unsigned r; r = (unsigned) __builtin_clzl(v); return r; +#define lzo_bitops_ctlz64(v) ((unsigned) __builtin_clzl(v)) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_LONG_LONG == 8) && (LZO_WORDSIZE >= 8) + unsigned r; r = (unsigned) __builtin_clzll(v); return r; +#define lzo_bitops_ctlz64(v) ((unsigned) __builtin_clzll(v)) +#else + LZO_UNUSED(v); return 0; +#endif +} +#endif + +__lzo_static_forceinline unsigned lzo_bitops_cttz32_func(lzo_uint32_t v) +{ +#if (LZO_BITOPS_USE_MSC_BITSCAN) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) + unsigned long r; (void) _BitScanForward(&r, v); return (unsigned) r; +#define lzo_bitops_cttz32(v) lzo_bitops_cttz32_func(v) +#elif (LZO_BITOPS_USE_ASM_BITSCAN) && (LZO_ARCH_AMD64 || LZO_ARCH_I386) && (LZO_ASM_SYNTAX_GNUC) + lzo_uint32_t r; + __asm__("bsf %1,%0" : "=r" (r) : "rm" (v) __LZO_ASM_CLOBBER_LIST_CC); + return (unsigned) r; +#define lzo_bitops_cttz32(v) lzo_bitops_cttz32_func(v) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_INT >= 4) + unsigned r; r = (unsigned) __builtin_ctz(v); return r; +#define lzo_bitops_cttz32(v) ((unsigned) __builtin_ctz(v)) +#else + LZO_UNUSED(v); return 0; +#endif +} + +#if defined(lzo_uint64_t) +__lzo_static_forceinline unsigned lzo_bitops_cttz64_func(lzo_uint64_t v) +{ +#if (LZO_BITOPS_USE_MSC_BITSCAN) && (LZO_ARCH_AMD64) + unsigned long r; (void) _BitScanForward64(&r, v); return (unsigned) r; +#define lzo_bitops_cttz64(v) lzo_bitops_cttz64_func(v) +#elif (LZO_BITOPS_USE_ASM_BITSCAN) && (LZO_ARCH_AMD64) && (LZO_ASM_SYNTAX_GNUC) + lzo_uint64_t r; + __asm__("bsf %1,%0" : "=r" (r) : "rm" (v) __LZO_ASM_CLOBBER_LIST_CC); + return (unsigned) r; +#define lzo_bitops_cttz64(v) lzo_bitops_cttz64_func(v) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_LONG >= 8) && (LZO_WORDSIZE >= 8) + unsigned r; r = (unsigned) __builtin_ctzl(v); return r; +#define lzo_bitops_cttz64(v) ((unsigned) __builtin_ctzl(v)) +#elif (LZO_BITOPS_USE_GNUC_BITSCAN) && (LZO_SIZEOF_LONG_LONG >= 8) && (LZO_WORDSIZE >= 8) + unsigned r; r = (unsigned) __builtin_ctzll(v); return r; +#define lzo_bitops_cttz64(v) ((unsigned) __builtin_ctzll(v)) +#else + LZO_UNUSED(v); return 0; +#endif +} +#endif + +lzo_unused_funcs_impl(void, lzo_bitops_unused_funcs)(void) +{ + LZO_UNUSED_FUNC(lzo_bitops_unused_funcs); + LZO_UNUSED_FUNC(lzo_bitops_ctlz32_func); + LZO_UNUSED_FUNC(lzo_bitops_cttz32_func); +#if defined(lzo_uint64_t) + LZO_UNUSED_FUNC(lzo_bitops_ctlz64_func); + LZO_UNUSED_FUNC(lzo_bitops_cttz64_func); +#endif +} + +#if defined(__lzo_alignof) && !(LZO_CFG_NO_UNALIGNED) +#if !defined(lzo_memops_tcheck__) && 0 +#define lzo_memops_tcheck__(t,a,b) ((void)0, sizeof(t) == (a) && __lzo_alignof(t) == (b)) +#endif +#endif +#ifndef lzo_memops_TU0p +#define lzo_memops_TU0p void __LZO_MMODEL * +#endif +#ifndef lzo_memops_TU1p +#define lzo_memops_TU1p unsigned char __LZO_MMODEL * +#endif +#ifndef lzo_memops_TU2p +#if (LZO_OPT_UNALIGNED16) +typedef lzo_uint16_t __lzo_may_alias lzo_memops_TU2; +#define lzo_memops_TU2p volatile lzo_memops_TU2 * +#elif defined(__lzo_byte_struct) +__lzo_byte_struct(lzo_memops_TU2_struct,2) +typedef struct lzo_memops_TU2_struct lzo_memops_TU2; +#else +struct lzo_memops_TU2_struct { unsigned char a[2]; } __lzo_may_alias; +typedef struct lzo_memops_TU2_struct lzo_memops_TU2; +#endif +#ifndef lzo_memops_TU2p +#define lzo_memops_TU2p lzo_memops_TU2 * +#endif +#endif +#ifndef lzo_memops_TU4p +#if (LZO_OPT_UNALIGNED32) +typedef lzo_uint32_t __lzo_may_alias lzo_memops_TU4; +#define lzo_memops_TU4p volatile lzo_memops_TU4 __LZO_MMODEL * +#elif defined(__lzo_byte_struct) +__lzo_byte_struct(lzo_memops_TU4_struct,4) +typedef struct lzo_memops_TU4_struct lzo_memops_TU4; +#else +struct lzo_memops_TU4_struct { unsigned char a[4]; } __lzo_may_alias; +typedef struct lzo_memops_TU4_struct lzo_memops_TU4; +#endif +#ifndef lzo_memops_TU4p +#define lzo_memops_TU4p lzo_memops_TU4 __LZO_MMODEL * +#endif +#endif +#ifndef lzo_memops_TU8p +#if (LZO_OPT_UNALIGNED64) +typedef lzo_uint64_t __lzo_may_alias lzo_memops_TU8; +#define lzo_memops_TU8p volatile lzo_memops_TU8 __LZO_MMODEL * +#elif defined(__lzo_byte_struct) +__lzo_byte_struct(lzo_memops_TU8_struct,8) +typedef struct lzo_memops_TU8_struct lzo_memops_TU8; +#else +struct lzo_memops_TU8_struct { unsigned char a[8]; } __lzo_may_alias; +typedef struct lzo_memops_TU8_struct lzo_memops_TU8; +#endif +#ifndef lzo_memops_TU8p +#define lzo_memops_TU8p lzo_memops_TU8 __LZO_MMODEL * +#endif +#endif +#ifndef lzo_memops_set_TU1p +#define lzo_memops_set_TU1p volatile lzo_memops_TU1p +#endif +#ifndef lzo_memops_move_TU1p +#define lzo_memops_move_TU1p lzo_memops_TU1p +#endif +#define LZO_MEMOPS_SET1(dd,cc) \ + LZO_BLOCK_BEGIN \ + lzo_memops_set_TU1p d__1 = (lzo_memops_set_TU1p) (lzo_memops_TU0p) (dd); \ + d__1[0] = LZO_BYTE(cc); \ + LZO_BLOCK_END +#define LZO_MEMOPS_SET2(dd,cc) \ + LZO_BLOCK_BEGIN \ + lzo_memops_set_TU1p d__2 = (lzo_memops_set_TU1p) (lzo_memops_TU0p) (dd); \ + d__2[0] = LZO_BYTE(cc); d__2[1] = LZO_BYTE(cc); \ + LZO_BLOCK_END +#define LZO_MEMOPS_SET3(dd,cc) \ + LZO_BLOCK_BEGIN \ + lzo_memops_set_TU1p d__3 = (lzo_memops_set_TU1p) (lzo_memops_TU0p) (dd); \ + d__3[0] = LZO_BYTE(cc); d__3[1] = LZO_BYTE(cc); d__3[2] = LZO_BYTE(cc); \ + LZO_BLOCK_END +#define LZO_MEMOPS_SET4(dd,cc) \ + LZO_BLOCK_BEGIN \ + lzo_memops_set_TU1p d__4 = (lzo_memops_set_TU1p) (lzo_memops_TU0p) (dd); \ + d__4[0] = LZO_BYTE(cc); d__4[1] = LZO_BYTE(cc); d__4[2] = LZO_BYTE(cc); d__4[3] = LZO_BYTE(cc); \ + LZO_BLOCK_END +#define LZO_MEMOPS_MOVE1(dd,ss) \ + LZO_BLOCK_BEGIN \ + lzo_memops_move_TU1p d__1 = (lzo_memops_move_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_move_TU1p s__1 = (const lzo_memops_move_TU1p) (const lzo_memops_TU0p) (ss); \ + d__1[0] = s__1[0]; \ + LZO_BLOCK_END +#define LZO_MEMOPS_MOVE2(dd,ss) \ + LZO_BLOCK_BEGIN \ + lzo_memops_move_TU1p d__2 = (lzo_memops_move_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_move_TU1p s__2 = (const lzo_memops_move_TU1p) (const lzo_memops_TU0p) (ss); \ + d__2[0] = s__2[0]; d__2[1] = s__2[1]; \ + LZO_BLOCK_END +#define LZO_MEMOPS_MOVE3(dd,ss) \ + LZO_BLOCK_BEGIN \ + lzo_memops_move_TU1p d__3 = (lzo_memops_move_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_move_TU1p s__3 = (const lzo_memops_move_TU1p) (const lzo_memops_TU0p) (ss); \ + d__3[0] = s__3[0]; d__3[1] = s__3[1]; d__3[2] = s__3[2]; \ + LZO_BLOCK_END +#define LZO_MEMOPS_MOVE4(dd,ss) \ + LZO_BLOCK_BEGIN \ + lzo_memops_move_TU1p d__4 = (lzo_memops_move_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_move_TU1p s__4 = (const lzo_memops_move_TU1p) (const lzo_memops_TU0p) (ss); \ + d__4[0] = s__4[0]; d__4[1] = s__4[1]; d__4[2] = s__4[2]; d__4[3] = s__4[3]; \ + LZO_BLOCK_END +#define LZO_MEMOPS_MOVE8(dd,ss) \ + LZO_BLOCK_BEGIN \ + lzo_memops_move_TU1p d__8 = (lzo_memops_move_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_move_TU1p s__8 = (const lzo_memops_move_TU1p) (const lzo_memops_TU0p) (ss); \ + d__8[0] = s__8[0]; d__8[1] = s__8[1]; d__8[2] = s__8[2]; d__8[3] = s__8[3]; \ + d__8[4] = s__8[4]; d__8[5] = s__8[5]; d__8[6] = s__8[6]; d__8[7] = s__8[7]; \ + LZO_BLOCK_END +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU1p)0)==1) +#define LZO_MEMOPS_COPY1(dd,ss) LZO_MEMOPS_MOVE1(dd,ss) +#if (LZO_OPT_UNALIGNED16) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU2p)0)==2) +#define LZO_MEMOPS_COPY2(dd,ss) \ + * (lzo_memops_TU2p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU2p) (const lzo_memops_TU0p) (ss) +#elif defined(lzo_memops_tcheck__) +#define LZO_MEMOPS_COPY2(dd,ss) \ + LZO_BLOCK_BEGIN if (lzo_memops_tcheck__(lzo_memops_TU2,2,1)) { \ + * (lzo_memops_TU2p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU2p) (const lzo_memops_TU0p) (ss); \ + } else { LZO_MEMOPS_MOVE2(dd,ss); } LZO_BLOCK_END +#else +#define LZO_MEMOPS_COPY2(dd,ss) LZO_MEMOPS_MOVE2(dd,ss) +#endif +#if (LZO_OPT_UNALIGNED32) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU4p)0)==4) +#define LZO_MEMOPS_COPY4(dd,ss) \ + * (lzo_memops_TU4p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU4p) (const lzo_memops_TU0p) (ss) +#elif defined(lzo_memops_tcheck__) +#define LZO_MEMOPS_COPY4(dd,ss) \ + LZO_BLOCK_BEGIN if (lzo_memops_tcheck__(lzo_memops_TU4,4,1)) { \ + * (lzo_memops_TU4p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU4p) (const lzo_memops_TU0p) (ss); \ + } else { LZO_MEMOPS_MOVE4(dd,ss); } LZO_BLOCK_END +#else +#define LZO_MEMOPS_COPY4(dd,ss) LZO_MEMOPS_MOVE4(dd,ss) +#endif +#if (LZO_WORDSIZE != 8) +#define LZO_MEMOPS_COPY8(dd,ss) \ + LZO_BLOCK_BEGIN LZO_MEMOPS_COPY4(dd,ss); LZO_MEMOPS_COPY4((lzo_memops_TU1p)(lzo_memops_TU0p)(dd)+4,(const lzo_memops_TU1p)(const lzo_memops_TU0p)(ss)+4); LZO_BLOCK_END +#else +#if (LZO_OPT_UNALIGNED64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU8p)0)==8) +#define LZO_MEMOPS_COPY8(dd,ss) \ + * (lzo_memops_TU8p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU8p) (const lzo_memops_TU0p) (ss) +#elif (LZO_OPT_UNALIGNED32) +#define LZO_MEMOPS_COPY8(dd,ss) \ + LZO_BLOCK_BEGIN LZO_MEMOPS_COPY4(dd,ss); LZO_MEMOPS_COPY4((lzo_memops_TU1p)(lzo_memops_TU0p)(dd)+4,(const lzo_memops_TU1p)(const lzo_memops_TU0p)(ss)+4); LZO_BLOCK_END +#elif defined(lzo_memops_tcheck__) +#define LZO_MEMOPS_COPY8(dd,ss) \ + LZO_BLOCK_BEGIN if (lzo_memops_tcheck__(lzo_memops_TU8,8,1)) { \ + * (lzo_memops_TU8p) (lzo_memops_TU0p) (dd) = * (const lzo_memops_TU8p) (const lzo_memops_TU0p) (ss); \ + } else { LZO_MEMOPS_MOVE8(dd,ss); } LZO_BLOCK_END +#else +#define LZO_MEMOPS_COPY8(dd,ss) LZO_MEMOPS_MOVE8(dd,ss) +#endif +#endif +#define LZO_MEMOPS_COPYN(dd,ss,nn) \ + LZO_BLOCK_BEGIN \ + lzo_memops_TU1p d__n = (lzo_memops_TU1p) (lzo_memops_TU0p) (dd); \ + const lzo_memops_TU1p s__n = (const lzo_memops_TU1p) (const lzo_memops_TU0p) (ss); \ + lzo_uint n__n = (nn); \ + while ((void)0, n__n >= 8) { LZO_MEMOPS_COPY8(d__n, s__n); d__n += 8; s__n += 8; n__n -= 8; } \ + if ((void)0, n__n >= 4) { LZO_MEMOPS_COPY4(d__n, s__n); d__n += 4; s__n += 4; n__n -= 4; } \ + if ((void)0, n__n > 0) do { *d__n++ = *s__n++; } while (--n__n > 0); \ + LZO_BLOCK_END + +__lzo_static_forceinline lzo_uint16_t lzo_memops_get_le16(const lzo_voidp ss) +{ + lzo_uint16_t v; +#if (LZO_ABI_LITTLE_ENDIAN) + LZO_MEMOPS_COPY2(&v, ss); +#elif (LZO_OPT_UNALIGNED16 && LZO_ARCH_POWERPC && LZO_ABI_BIG_ENDIAN) && (LZO_ASM_SYNTAX_GNUC) + const lzo_memops_TU2p s = (const lzo_memops_TU2p) ss; + unsigned long vv; + __asm__("lhbrx %0,0,%1" : "=r" (vv) : "r" (s), "m" (*s)); + v = (lzo_uint16_t) vv; +#else + const lzo_memops_TU1p s = (const lzo_memops_TU1p) ss; + v = (lzo_uint16_t) (((lzo_uint16_t)s[0]) | ((lzo_uint16_t)s[1] << 8)); +#endif + return v; +} +#if (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) +#define LZO_MEMOPS_GET_LE16(ss) (* (const lzo_memops_TU2p) (const lzo_memops_TU0p) (ss)) +#else +#define LZO_MEMOPS_GET_LE16(ss) lzo_memops_get_le16(ss) +#endif + +__lzo_static_forceinline lzo_uint32_t lzo_memops_get_le32(const lzo_voidp ss) +{ + lzo_uint32_t v; +#if (LZO_ABI_LITTLE_ENDIAN) + LZO_MEMOPS_COPY4(&v, ss); +#elif (LZO_OPT_UNALIGNED32 && LZO_ARCH_POWERPC && LZO_ABI_BIG_ENDIAN) && (LZO_ASM_SYNTAX_GNUC) + const lzo_memops_TU4p s = (const lzo_memops_TU4p) ss; + unsigned long vv; + __asm__("lwbrx %0,0,%1" : "=r" (vv) : "r" (s), "m" (*s)); + v = (lzo_uint32_t) vv; +#else + const lzo_memops_TU1p s = (const lzo_memops_TU1p) ss; + v = (lzo_uint32_t) (((lzo_uint32_t)s[0]) | ((lzo_uint32_t)s[1] << 8) | ((lzo_uint32_t)s[2] << 16) | ((lzo_uint32_t)s[3] << 24)); +#endif + return v; +} +#if (LZO_OPT_UNALIGNED32) && (LZO_ABI_LITTLE_ENDIAN) +#define LZO_MEMOPS_GET_LE32(ss) (* (const lzo_memops_TU4p) (const lzo_memops_TU0p) (ss)) +#else +#define LZO_MEMOPS_GET_LE32(ss) lzo_memops_get_le32(ss) +#endif + +#if (LZO_OPT_UNALIGNED64) && (LZO_ABI_LITTLE_ENDIAN) +#define LZO_MEMOPS_GET_LE64(ss) (* (const lzo_memops_TU8p) (const lzo_memops_TU0p) (ss)) +#endif + +__lzo_static_forceinline lzo_uint16_t lzo_memops_get_ne16(const lzo_voidp ss) +{ + lzo_uint16_t v; + LZO_MEMOPS_COPY2(&v, ss); + return v; +} +#if (LZO_OPT_UNALIGNED16) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU2p)0)==2) +#define LZO_MEMOPS_GET_NE16(ss) (* (const lzo_memops_TU2p) (const lzo_memops_TU0p) (ss)) +#else +#define LZO_MEMOPS_GET_NE16(ss) lzo_memops_get_ne16(ss) +#endif + +__lzo_static_forceinline lzo_uint32_t lzo_memops_get_ne32(const lzo_voidp ss) +{ + lzo_uint32_t v; + LZO_MEMOPS_COPY4(&v, ss); + return v; +} +#if (LZO_OPT_UNALIGNED32) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU4p)0)==4) +#define LZO_MEMOPS_GET_NE32(ss) (* (const lzo_memops_TU4p) (const lzo_memops_TU0p) (ss)) +#else +#define LZO_MEMOPS_GET_NE32(ss) lzo_memops_get_ne32(ss) +#endif + +#if (LZO_OPT_UNALIGNED64) +LZO_COMPILE_TIME_ASSERT_HEADER(sizeof(*(lzo_memops_TU8p)0)==8) +#define LZO_MEMOPS_GET_NE64(ss) (* (const lzo_memops_TU8p) (const lzo_memops_TU0p) (ss)) +#endif + +__lzo_static_forceinline void lzo_memops_put_le16(lzo_voidp dd, lzo_uint16_t vv) +{ +#if (LZO_ABI_LITTLE_ENDIAN) + LZO_MEMOPS_COPY2(dd, &vv); +#elif (LZO_OPT_UNALIGNED16 && LZO_ARCH_POWERPC && LZO_ABI_BIG_ENDIAN) && (LZO_ASM_SYNTAX_GNUC) + lzo_memops_TU2p d = (lzo_memops_TU2p) dd; + unsigned long v = vv; + __asm__("sthbrx %2,0,%1" : "=m" (*d) : "r" (d), "r" (v)); +#else + lzo_memops_TU1p d = (lzo_memops_TU1p) dd; + d[0] = LZO_BYTE((vv ) & 0xff); + d[1] = LZO_BYTE((vv >> 8) & 0xff); +#endif +} +#if (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) +#define LZO_MEMOPS_PUT_LE16(dd,vv) (* (lzo_memops_TU2p) (lzo_memops_TU0p) (dd) = (vv)) +#else +#define LZO_MEMOPS_PUT_LE16(dd,vv) lzo_memops_put_le16(dd,vv) +#endif + +__lzo_static_forceinline void lzo_memops_put_le32(lzo_voidp dd, lzo_uint32_t vv) +{ +#if (LZO_ABI_LITTLE_ENDIAN) + LZO_MEMOPS_COPY4(dd, &vv); +#elif (LZO_OPT_UNALIGNED32 && LZO_ARCH_POWERPC && LZO_ABI_BIG_ENDIAN) && (LZO_ASM_SYNTAX_GNUC) + lzo_memops_TU4p d = (lzo_memops_TU4p) dd; + unsigned long v = vv; + __asm__("stwbrx %2,0,%1" : "=m" (*d) : "r" (d), "r" (v)); +#else + lzo_memops_TU1p d = (lzo_memops_TU1p) dd; + d[0] = LZO_BYTE((vv ) & 0xff); + d[1] = LZO_BYTE((vv >> 8) & 0xff); + d[2] = LZO_BYTE((vv >> 16) & 0xff); + d[3] = LZO_BYTE((vv >> 24) & 0xff); +#endif +} +#if (LZO_OPT_UNALIGNED32) && (LZO_ABI_LITTLE_ENDIAN) +#define LZO_MEMOPS_PUT_LE32(dd,vv) (* (lzo_memops_TU4p) (lzo_memops_TU0p) (dd) = (vv)) +#else +#define LZO_MEMOPS_PUT_LE32(dd,vv) lzo_memops_put_le32(dd,vv) +#endif + +__lzo_static_forceinline void lzo_memops_put_ne16(lzo_voidp dd, lzo_uint16_t vv) +{ + LZO_MEMOPS_COPY2(dd, &vv); +} +#if (LZO_OPT_UNALIGNED16) +#define LZO_MEMOPS_PUT_NE16(dd,vv) (* (lzo_memops_TU2p) (lzo_memops_TU0p) (dd) = (vv)) +#else +#define LZO_MEMOPS_PUT_NE16(dd,vv) lzo_memops_put_ne16(dd,vv) +#endif + +__lzo_static_forceinline void lzo_memops_put_ne32(lzo_voidp dd, lzo_uint32_t vv) +{ + LZO_MEMOPS_COPY4(dd, &vv); +} +#if (LZO_OPT_UNALIGNED32) +#define LZO_MEMOPS_PUT_NE32(dd,vv) (* (lzo_memops_TU4p) (lzo_memops_TU0p) (dd) = (vv)) +#else +#define LZO_MEMOPS_PUT_NE32(dd,vv) lzo_memops_put_ne32(dd,vv) +#endif + +lzo_unused_funcs_impl(void, lzo_memops_unused_funcs)(void) +{ + LZO_UNUSED_FUNC(lzo_memops_unused_funcs); + LZO_UNUSED_FUNC(lzo_memops_get_le16); + LZO_UNUSED_FUNC(lzo_memops_get_le32); + LZO_UNUSED_FUNC(lzo_memops_get_ne16); + LZO_UNUSED_FUNC(lzo_memops_get_ne32); + LZO_UNUSED_FUNC(lzo_memops_put_le16); + LZO_UNUSED_FUNC(lzo_memops_put_le32); + LZO_UNUSED_FUNC(lzo_memops_put_ne16); + LZO_UNUSED_FUNC(lzo_memops_put_ne32); +} + +#endif + +#ifndef UA_SET1 +#define UA_SET1 LZO_MEMOPS_SET1 +#endif +#ifndef UA_SET2 +#define UA_SET2 LZO_MEMOPS_SET2 +#endif +#ifndef UA_SET3 +#define UA_SET3 LZO_MEMOPS_SET3 +#endif +#ifndef UA_SET4 +#define UA_SET4 LZO_MEMOPS_SET4 +#endif +#ifndef UA_MOVE1 +#define UA_MOVE1 LZO_MEMOPS_MOVE1 +#endif +#ifndef UA_MOVE2 +#define UA_MOVE2 LZO_MEMOPS_MOVE2 +#endif +#ifndef UA_MOVE3 +#define UA_MOVE3 LZO_MEMOPS_MOVE3 +#endif +#ifndef UA_MOVE4 +#define UA_MOVE4 LZO_MEMOPS_MOVE4 +#endif +#ifndef UA_MOVE8 +#define UA_MOVE8 LZO_MEMOPS_MOVE8 +#endif +#ifndef UA_COPY1 +#define UA_COPY1 LZO_MEMOPS_COPY1 +#endif +#ifndef UA_COPY2 +#define UA_COPY2 LZO_MEMOPS_COPY2 +#endif +#ifndef UA_COPY3 +#define UA_COPY3 LZO_MEMOPS_COPY3 +#endif +#ifndef UA_COPY4 +#define UA_COPY4 LZO_MEMOPS_COPY4 +#endif +#ifndef UA_COPY8 +#define UA_COPY8 LZO_MEMOPS_COPY8 +#endif +#ifndef UA_COPYN +#define UA_COPYN LZO_MEMOPS_COPYN +#endif +#ifndef UA_COPYN_X +#define UA_COPYN_X LZO_MEMOPS_COPYN +#endif +#ifndef UA_GET_LE16 +#define UA_GET_LE16 LZO_MEMOPS_GET_LE16 +#endif +#ifndef UA_GET_LE32 +#define UA_GET_LE32 LZO_MEMOPS_GET_LE32 +#endif +#ifdef LZO_MEMOPS_GET_LE64 +#ifndef UA_GET_LE64 +#define UA_GET_LE64 LZO_MEMOPS_GET_LE64 +#endif +#endif +#ifndef UA_GET_NE16 +#define UA_GET_NE16 LZO_MEMOPS_GET_NE16 +#endif +#ifndef UA_GET_NE32 +#define UA_GET_NE32 LZO_MEMOPS_GET_NE32 +#endif +#ifdef LZO_MEMOPS_GET_NE64 +#ifndef UA_GET_NE64 +#define UA_GET_NE64 LZO_MEMOPS_GET_NE64 +#endif +#endif +#ifndef UA_PUT_LE16 +#define UA_PUT_LE16 LZO_MEMOPS_PUT_LE16 +#endif +#ifndef UA_PUT_LE32 +#define UA_PUT_LE32 LZO_MEMOPS_PUT_LE32 +#endif +#ifndef UA_PUT_NE16 +#define UA_PUT_NE16 LZO_MEMOPS_PUT_NE16 +#endif +#ifndef UA_PUT_NE32 +#define UA_PUT_NE32 LZO_MEMOPS_PUT_NE32 +#endif + +#define MEMCPY8_DS(dest,src,len) \ + lzo_memcpy(dest,src,len); dest += len; src += len + +#define BZERO8_PTR(s,l,n) \ + lzo_memset((lzo_voidp)(s),0,(lzo_uint)(l)*(n)) + +#define MEMCPY_DS(dest,src,len) \ + do *dest++ = *src++; while (--len > 0) + +LZO_EXTERN(const lzo_bytep) lzo_copyright(void); + +#ifndef __LZO_PTR_H +#define __LZO_PTR_H 1 + +#ifdef __cplusplus +extern "C" { +#endif + +#if (LZO_ARCH_I086) +#error "LZO_ARCH_I086 is unsupported" +#elif (LZO_MM_PVP) +#error "LZO_MM_PVP is unsupported" +#else +#define PTR(a) ((lzo_uintptr_t) (a)) +#define PTR_LINEAR(a) PTR(a) +#define PTR_ALIGNED_4(a) ((PTR_LINEAR(a) & 3) == 0) +#define PTR_ALIGNED_8(a) ((PTR_LINEAR(a) & 7) == 0) +#define PTR_ALIGNED2_4(a,b) (((PTR_LINEAR(a) | PTR_LINEAR(b)) & 3) == 0) +#define PTR_ALIGNED2_8(a,b) (((PTR_LINEAR(a) | PTR_LINEAR(b)) & 7) == 0) +#endif + +#define PTR_LT(a,b) (PTR(a) < PTR(b)) +#define PTR_GE(a,b) (PTR(a) >= PTR(b)) +#define PTR_DIFF(a,b) (PTR(a) - PTR(b)) +#define pd(a,b) ((lzo_uint) ((a)-(b))) + +LZO_EXTERN(lzo_uintptr_t) +__lzo_ptr_linear(const lzo_voidp ptr); + +typedef union +{ + char a_char; + unsigned char a_uchar; + short a_short; + unsigned short a_ushort; + int a_int; + unsigned int a_uint; + long a_long; + unsigned long a_ulong; + lzo_int a_lzo_int; + lzo_uint a_lzo_uint; + lzo_xint a_lzo_xint; + lzo_int16_t a_lzo_int16_t; + lzo_uint16_t a_lzo_uint16_t; + lzo_int32_t a_lzo_int32_t; + lzo_uint32_t a_lzo_uint32_t; +#if defined(lzo_uint64_t) + lzo_int64_t a_lzo_int64_t; + lzo_uint64_t a_lzo_uint64_t; +#endif + size_t a_size_t; + ptrdiff_t a_ptrdiff_t; + lzo_uintptr_t a_lzo_uintptr_t; + void * a_void_p; + char * a_char_p; + unsigned char * a_uchar_p; + const void * a_c_void_p; + const char * a_c_char_p; + const unsigned char * a_c_uchar_p; + lzo_voidp a_lzo_voidp; + lzo_bytep a_lzo_bytep; + const lzo_voidp a_c_lzo_voidp; + const lzo_bytep a_c_lzo_bytep; +} +lzo_full_align_t; + +#ifdef __cplusplus +} +#endif + +#endif + +#ifndef LZO_DETERMINISTIC +#define LZO_DETERMINISTIC 1 +#endif + +#ifndef LZO_DICT_USE_PTR +#define LZO_DICT_USE_PTR 1 +#endif + +#if (LZO_DICT_USE_PTR) +# define lzo_dict_t const lzo_bytep +# define lzo_dict_p lzo_dict_t * +#else +# define lzo_dict_t lzo_uint +# define lzo_dict_p lzo_dict_t * +#endif + +#endif + +#if !defined(MINILZO_CFG_SKIP_LZO_PTR) + +LZO_PUBLIC(lzo_uintptr_t) +__lzo_ptr_linear(const lzo_voidp ptr) +{ + lzo_uintptr_t p; + +#if (LZO_ARCH_I086) +#error "LZO_ARCH_I086 is unsupported" +#elif (LZO_MM_PVP) +#error "LZO_MM_PVP is unsupported" +#else + p = (lzo_uintptr_t) PTR_LINEAR(ptr); +#endif + + return p; +} + +LZO_PUBLIC(unsigned) +__lzo_align_gap(const lzo_voidp ptr, lzo_uint size) +{ +#if (__LZO_UINTPTR_T_IS_POINTER) +#error "__LZO_UINTPTR_T_IS_POINTER is unsupported" +#else + lzo_uintptr_t p, n; + if (size < 2) return 0; + p = __lzo_ptr_linear(ptr); +#if 0 + n = (((p + size - 1) / size) * size) - p; +#else + if ((size & (size - 1)) != 0) + return 0; + n = size; n = ((p + n - 1) & ~(n - 1)) - p; +#endif +#endif + assert((long)n >= 0); + assert(n <= size); + return (unsigned)n; +} + +#endif +#if !defined(MINILZO_CFG_SKIP_LZO_UTIL) + +/* If you use the LZO library in a product, I would appreciate that you + * keep this copyright string in the executable of your product. + */ + +static const char lzo_copyright_[] = +#if !defined(__LZO_IN_MINLZO) + LZO_VERSION_STRING; +#else + "\r\n\n" + "LZO data compression library.\n" + "$Copyright: LZO Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer\n" + "\n" + "http://www.oberhumer.com $\n\n" + "$Id: LZO version: v" LZO_VERSION_STRING ", " LZO_VERSION_DATE " $\n" + "$Info: " LZO_INFO_STRING " $\n"; +#endif +static const char lzo_version_string_[] = LZO_VERSION_STRING; +static const char lzo_version_date_[] = LZO_VERSION_DATE; + +LZO_PUBLIC(const lzo_bytep) +lzo_copyright(void) +{ + return (const lzo_bytep) lzo_copyright_; +} + +LZO_PUBLIC(unsigned) +lzo_version(void) +{ + return LZO_VERSION; +} + +LZO_PUBLIC(const char *) +lzo_version_string(void) +{ + return lzo_version_string_; +} + +LZO_PUBLIC(const char *) +lzo_version_date(void) +{ + return lzo_version_date_; +} + +LZO_PUBLIC(const lzo_charp) +_lzo_version_string(void) +{ + return lzo_version_string_; +} + +LZO_PUBLIC(const lzo_charp) +_lzo_version_date(void) +{ + return lzo_version_date_; +} + +#define LZO_BASE 65521u +#define LZO_NMAX 5552 + +#define LZO_DO1(buf,i) s1 += buf[i]; s2 += s1 +#define LZO_DO2(buf,i) LZO_DO1(buf,i); LZO_DO1(buf,i+1) +#define LZO_DO4(buf,i) LZO_DO2(buf,i); LZO_DO2(buf,i+2) +#define LZO_DO8(buf,i) LZO_DO4(buf,i); LZO_DO4(buf,i+4) +#define LZO_DO16(buf,i) LZO_DO8(buf,i); LZO_DO8(buf,i+8) + +LZO_PUBLIC(lzo_uint32_t) +lzo_adler32(lzo_uint32_t adler, const lzo_bytep buf, lzo_uint len) +{ + lzo_uint32_t s1 = adler & 0xffff; + lzo_uint32_t s2 = (adler >> 16) & 0xffff; + unsigned k; + + if (buf == NULL) + return 1; + + while (len > 0) + { + k = len < LZO_NMAX ? (unsigned) len : LZO_NMAX; + len -= k; + if (k >= 16) do + { + LZO_DO16(buf,0); + buf += 16; + k -= 16; + } while (k >= 16); + if (k != 0) do + { + s1 += *buf++; + s2 += s1; + } while (--k > 0); + s1 %= LZO_BASE; + s2 %= LZO_BASE; + } + return (s2 << 16) | s1; +} + +#undef LZO_DO1 +#undef LZO_DO2 +#undef LZO_DO4 +#undef LZO_DO8 +#undef LZO_DO16 + +#endif +#if !defined(MINILZO_CFG_SKIP_LZO_STRING) +#undef lzo_memcmp +#undef lzo_memcpy +#undef lzo_memmove +#undef lzo_memset +#if !defined(__LZO_MMODEL_HUGE) +# undef LZO_HAVE_MM_HUGE_PTR +#endif +#define lzo_hsize_t lzo_uint +#define lzo_hvoid_p lzo_voidp +#define lzo_hbyte_p lzo_bytep +#define LZOLIB_PUBLIC(r,f) LZO_PUBLIC(r) f +#define lzo_hmemcmp lzo_memcmp +#define lzo_hmemcpy lzo_memcpy +#define lzo_hmemmove lzo_memmove +#define lzo_hmemset lzo_memset +#define __LZOLIB_HMEMCPY_CH_INCLUDED 1 +#if !defined(LZOLIB_PUBLIC) +# define LZOLIB_PUBLIC(r,f) r __LZOLIB_FUNCNAME(f) +#endif +LZOLIB_PUBLIC(int, lzo_hmemcmp) (const lzo_hvoid_p s1, const lzo_hvoid_p s2, lzo_hsize_t len) +{ +#if (LZO_HAVE_MM_HUGE_PTR) || !(HAVE_MEMCMP) + const lzo_hbyte_p p1 = LZO_STATIC_CAST(const lzo_hbyte_p, s1); + const lzo_hbyte_p p2 = LZO_STATIC_CAST(const lzo_hbyte_p, s2); + if __lzo_likely(len > 0) do + { + int d = *p1 - *p2; + if (d != 0) + return d; + p1++; p2++; + } while __lzo_likely(--len > 0); + return 0; +#else + return memcmp(s1, s2, len); +#endif +} +LZOLIB_PUBLIC(lzo_hvoid_p, lzo_hmemcpy) (lzo_hvoid_p dest, const lzo_hvoid_p src, lzo_hsize_t len) +{ +#if (LZO_HAVE_MM_HUGE_PTR) || !(HAVE_MEMCPY) + lzo_hbyte_p p1 = LZO_STATIC_CAST(lzo_hbyte_p, dest); + const lzo_hbyte_p p2 = LZO_STATIC_CAST(const lzo_hbyte_p, src); + if (!(len > 0) || p1 == p2) + return dest; + do + *p1++ = *p2++; + while __lzo_likely(--len > 0); + return dest; +#else + return memcpy(dest, src, len); +#endif +} +LZOLIB_PUBLIC(lzo_hvoid_p, lzo_hmemmove) (lzo_hvoid_p dest, const lzo_hvoid_p src, lzo_hsize_t len) +{ +#if (LZO_HAVE_MM_HUGE_PTR) || !(HAVE_MEMMOVE) + lzo_hbyte_p p1 = LZO_STATIC_CAST(lzo_hbyte_p, dest); + const lzo_hbyte_p p2 = LZO_STATIC_CAST(const lzo_hbyte_p, src); + if (!(len > 0) || p1 == p2) + return dest; + if (p1 < p2) + { + do + *p1++ = *p2++; + while __lzo_likely(--len > 0); + } + else + { + p1 += len; + p2 += len; + do + *--p1 = *--p2; + while __lzo_likely(--len > 0); + } + return dest; +#else + return memmove(dest, src, len); +#endif +} +LZOLIB_PUBLIC(lzo_hvoid_p, lzo_hmemset) (lzo_hvoid_p s, int cc, lzo_hsize_t len) +{ +#if (LZO_HAVE_MM_HUGE_PTR) || !(HAVE_MEMSET) + lzo_hbyte_p p = LZO_STATIC_CAST(lzo_hbyte_p, s); + unsigned char c = LZO_ITRUNC(unsigned char, cc); + if __lzo_likely(len > 0) do + *p++ = c; + while __lzo_likely(--len > 0); + return s; +#else + return memset(s, cc, len); +#endif +} +#undef LZOLIB_PUBLIC +#endif +#if !defined(MINILZO_CFG_SKIP_LZO_INIT) + +#if !defined(__LZO_IN_MINILZO) + +#define LZO_WANT_ACC_CHK_CH 1 +#undef LZOCHK_ASSERT + + LZOCHK_ASSERT((LZO_UINT32_C(1) << (int)(8*sizeof(LZO_UINT32_C(1))-1)) > 0) + LZOCHK_ASSERT_IS_SIGNED_T(lzo_int) + LZOCHK_ASSERT_IS_UNSIGNED_T(lzo_uint) +#if !(__LZO_UINTPTR_T_IS_POINTER) + LZOCHK_ASSERT_IS_UNSIGNED_T(lzo_uintptr_t) +#endif + LZOCHK_ASSERT(sizeof(lzo_uintptr_t) >= sizeof(lzo_voidp)) + LZOCHK_ASSERT_IS_UNSIGNED_T(lzo_xint) + +#endif +#undef LZOCHK_ASSERT + +union lzo_config_check_union { + lzo_uint a[2]; + unsigned char b[2*LZO_MAX(8,sizeof(lzo_uint))]; +#if defined(lzo_uint64_t) + lzo_uint64_t c[2]; +#endif +}; + +#if 0 +#define u2p(ptr,off) ((lzo_voidp) (((lzo_bytep)(lzo_voidp)(ptr)) + (off))) +#else +static __lzo_noinline lzo_voidp u2p(lzo_voidp ptr, lzo_uint off) +{ + return (lzo_voidp) ((lzo_bytep) ptr + off); +} +#endif + +LZO_PUBLIC(int) +_lzo_config_check(void) +{ +#if (LZO_CC_CLANG && (LZO_CC_CLANG >= 0x030100ul && LZO_CC_CLANG < 0x030300ul)) +# if 0 + volatile +# endif +#endif + union lzo_config_check_union u; + lzo_voidp p; + unsigned r = 1; + + u.a[0] = u.a[1] = 0; + p = u2p(&u, 0); + r &= ((* (lzo_bytep) p) == 0); +#if !(LZO_CFG_NO_CONFIG_CHECK) +#if (LZO_ABI_BIG_ENDIAN) + u.a[0] = u.a[1] = 0; u.b[sizeof(lzo_uint) - 1] = 128; + p = u2p(&u, 0); + r &= ((* (lzo_uintp) p) == 128); +#endif +#if (LZO_ABI_LITTLE_ENDIAN) + u.a[0] = u.a[1] = 0; u.b[0] = 128; + p = u2p(&u, 0); + r &= ((* (lzo_uintp) p) == 128); +#endif + u.a[0] = u.a[1] = 0; + u.b[0] = 1; u.b[3] = 2; + p = u2p(&u, 1); + r &= UA_GET_NE16(p) == 0; + r &= UA_GET_LE16(p) == 0; + u.b[1] = 128; + r &= UA_GET_LE16(p) == 128; + u.b[2] = 129; + r &= UA_GET_LE16(p) == LZO_UINT16_C(0x8180); +#if (LZO_ABI_BIG_ENDIAN) + r &= UA_GET_NE16(p) == LZO_UINT16_C(0x8081); +#endif +#if (LZO_ABI_LITTLE_ENDIAN) + r &= UA_GET_NE16(p) == LZO_UINT16_C(0x8180); +#endif + u.a[0] = u.a[1] = 0; + u.b[0] = 3; u.b[5] = 4; + p = u2p(&u, 1); + r &= UA_GET_NE32(p) == 0; + r &= UA_GET_LE32(p) == 0; + u.b[1] = 128; + r &= UA_GET_LE32(p) == 128; + u.b[2] = 129; u.b[3] = 130; u.b[4] = 131; + r &= UA_GET_LE32(p) == LZO_UINT32_C(0x83828180); +#if (LZO_ABI_BIG_ENDIAN) + r &= UA_GET_NE32(p) == LZO_UINT32_C(0x80818283); +#endif +#if (LZO_ABI_LITTLE_ENDIAN) + r &= UA_GET_NE32(p) == LZO_UINT32_C(0x83828180); +#endif +#if defined(UA_GET_NE64) + u.c[0] = u.c[1] = 0; + u.b[0] = 5; u.b[9] = 6; + p = u2p(&u, 1); + u.c[0] = u.c[1] = 0; + r &= UA_GET_NE64(p) == 0; +#if defined(UA_GET_LE64) + r &= UA_GET_LE64(p) == 0; + u.b[1] = 128; + r &= UA_GET_LE64(p) == 128; +#endif +#endif +#if defined(lzo_bitops_ctlz32) + { unsigned i = 0; lzo_uint32_t v; + for (v = 1; v != 0 && r == 1; v <<= 1, i++) { + r &= lzo_bitops_ctlz32(v) == 31 - i; + r &= lzo_bitops_ctlz32_func(v) == 31 - i; + }} +#endif +#if defined(lzo_bitops_ctlz64) + { unsigned i = 0; lzo_uint64_t v; + for (v = 1; v != 0 && r == 1; v <<= 1, i++) { + r &= lzo_bitops_ctlz64(v) == 63 - i; + r &= lzo_bitops_ctlz64_func(v) == 63 - i; + }} +#endif +#if defined(lzo_bitops_cttz32) + { unsigned i = 0; lzo_uint32_t v; + for (v = 1; v != 0 && r == 1; v <<= 1, i++) { + r &= lzo_bitops_cttz32(v) == i; + r &= lzo_bitops_cttz32_func(v) == i; + }} +#endif +#if defined(lzo_bitops_cttz64) + { unsigned i = 0; lzo_uint64_t v; + for (v = 1; v != 0 && r == 1; v <<= 1, i++) { + r &= lzo_bitops_cttz64(v) == i; + r &= lzo_bitops_cttz64_func(v) == i; + }} +#endif +#endif + LZO_UNUSED_FUNC(lzo_bitops_unused_funcs); + + return r == 1 ? LZO_E_OK : LZO_E_ERROR; +} + +LZO_PUBLIC(int) +__lzo_init_v2(unsigned v, int s1, int s2, int s3, int s4, int s5, + int s6, int s7, int s8, int s9) +{ + int r; + +#if defined(__LZO_IN_MINILZO) +#elif (LZO_CC_MSC && ((_MSC_VER) < 700)) +#else +#define LZO_WANT_ACC_CHK_CH 1 +#undef LZOCHK_ASSERT +#define LZOCHK_ASSERT(expr) LZO_COMPILE_TIME_ASSERT(expr) +#endif +#undef LZOCHK_ASSERT + + if (v == 0) + return LZO_E_ERROR; + + r = (s1 == -1 || s1 == (int) sizeof(short)) && + (s2 == -1 || s2 == (int) sizeof(int)) && + (s3 == -1 || s3 == (int) sizeof(long)) && + (s4 == -1 || s4 == (int) sizeof(lzo_uint32_t)) && + (s5 == -1 || s5 == (int) sizeof(lzo_uint)) && + (s6 == -1 || s6 == (int) lzo_sizeof_dict_t) && + (s7 == -1 || s7 == (int) sizeof(char *)) && + (s8 == -1 || s8 == (int) sizeof(lzo_voidp)) && + (s9 == -1 || s9 == (int) sizeof(lzo_callback_t)); + if (!r) + return LZO_E_ERROR; + + r = _lzo_config_check(); + if (r != LZO_E_OK) + return r; + + return r; +} + +#if !defined(__LZO_IN_MINILZO) + +#if (LZO_OS_WIN16 && LZO_CC_WATCOMC) && defined(__SW_BD) + +#if 0 +BOOL FAR PASCAL LibMain ( HANDLE hInstance, WORD wDataSegment, + WORD wHeapSize, LPSTR lpszCmdLine ) +#else +int __far __pascal LibMain ( int a, short b, short c, long d ) +#endif +{ + LZO_UNUSED(a); LZO_UNUSED(b); LZO_UNUSED(c); LZO_UNUSED(d); + return 1; +} + +#endif + +#endif + +#endif + +#define LZO1X 1 +#define LZO_EOF_CODE 1 +#define M2_MAX_OFFSET 0x0800 + +#if !defined(MINILZO_CFG_SKIP_LZO1X_1_COMPRESS) + +#if 1 && defined(UA_GET_LE32) +#undef LZO_DICT_USE_PTR +#define LZO_DICT_USE_PTR 0 +#undef lzo_dict_t +#define lzo_dict_t lzo_uint16_t +#endif + +#define LZO_NEED_DICT_H 1 +#ifndef D_BITS +#define D_BITS 14 +#endif +#define D_INDEX1(d,p) d = DM(DMUL(0x21,DX3(p,5,5,6)) >> 5) +#define D_INDEX2(d,p) d = (d & (D_MASK & 0x7ff)) ^ (D_HIGH | 0x1f) +#if 1 +#define DINDEX(dv,p) DM(((DMUL(0x1824429d,dv)) >> (32-D_BITS))) +#else +#define DINDEX(dv,p) DM((dv) + ((dv) >> (32-D_BITS))) +#endif + +#ifndef __LZO_CONFIG1X_H +#define __LZO_CONFIG1X_H 1 + +#if !defined(LZO1X) && !defined(LZO1Y) && !defined(LZO1Z) +# define LZO1X 1 +#endif + +#if !defined(__LZO_IN_MINILZO) +#include +#endif + +#ifndef LZO_EOF_CODE +#define LZO_EOF_CODE 1 +#endif +#undef LZO_DETERMINISTIC + +#define M1_MAX_OFFSET 0x0400 +#ifndef M2_MAX_OFFSET +#define M2_MAX_OFFSET 0x0800 +#endif +#define M3_MAX_OFFSET 0x4000 +#define M4_MAX_OFFSET 0xbfff + +#define MX_MAX_OFFSET (M1_MAX_OFFSET + M2_MAX_OFFSET) + +#define M1_MIN_LEN 2 +#define M1_MAX_LEN 2 +#define M2_MIN_LEN 3 +#ifndef M2_MAX_LEN +#define M2_MAX_LEN 8 +#endif +#define M3_MIN_LEN 3 +#define M3_MAX_LEN 33 +#define M4_MIN_LEN 3 +#define M4_MAX_LEN 9 + +#define M1_MARKER 0 +#define M2_MARKER 64 +#define M3_MARKER 32 +#define M4_MARKER 16 + +#ifndef MIN_LOOKAHEAD +#define MIN_LOOKAHEAD (M2_MAX_LEN + 1) +#endif + +#if defined(LZO_NEED_DICT_H) + +#ifndef LZO_HASH +#define LZO_HASH LZO_HASH_LZO_INCREMENTAL_B +#endif +#define DL_MIN_LEN M2_MIN_LEN + +#ifndef __LZO_DICT_H +#define __LZO_DICT_H 1 + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(D_BITS) && defined(DBITS) +# define D_BITS DBITS +#endif +#if !defined(D_BITS) +# error "D_BITS is not defined" +#endif +#if (D_BITS < 16) +# define D_SIZE LZO_SIZE(D_BITS) +# define D_MASK LZO_MASK(D_BITS) +#else +# define D_SIZE LZO_USIZE(D_BITS) +# define D_MASK LZO_UMASK(D_BITS) +#endif +#define D_HIGH ((D_MASK >> 1) + 1) + +#if !defined(DD_BITS) +# define DD_BITS 0 +#endif +#define DD_SIZE LZO_SIZE(DD_BITS) +#define DD_MASK LZO_MASK(DD_BITS) + +#if !defined(DL_BITS) +# define DL_BITS (D_BITS - DD_BITS) +#endif +#if (DL_BITS < 16) +# define DL_SIZE LZO_SIZE(DL_BITS) +# define DL_MASK LZO_MASK(DL_BITS) +#else +# define DL_SIZE LZO_USIZE(DL_BITS) +# define DL_MASK LZO_UMASK(DL_BITS) +#endif + +#if (D_BITS != DL_BITS + DD_BITS) +# error "D_BITS does not match" +#endif +#if (D_BITS < 6 || D_BITS > 18) +# error "invalid D_BITS" +#endif +#if (DL_BITS < 6 || DL_BITS > 20) +# error "invalid DL_BITS" +#endif +#if (DD_BITS < 0 || DD_BITS > 6) +# error "invalid DD_BITS" +#endif + +#if !defined(DL_MIN_LEN) +# define DL_MIN_LEN 3 +#endif +#if !defined(DL_SHIFT) +# define DL_SHIFT ((DL_BITS + (DL_MIN_LEN - 1)) / DL_MIN_LEN) +#endif + +#define LZO_HASH_GZIP 1 +#define LZO_HASH_GZIP_INCREMENTAL 2 +#define LZO_HASH_LZO_INCREMENTAL_A 3 +#define LZO_HASH_LZO_INCREMENTAL_B 4 + +#if !defined(LZO_HASH) +# error "choose a hashing strategy" +#endif + +#undef DM +#undef DX + +#if (DL_MIN_LEN == 3) +# define _DV2_A(p,shift1,shift2) \ + (((( (lzo_xint)((p)[0]) << shift1) ^ (p)[1]) << shift2) ^ (p)[2]) +# define _DV2_B(p,shift1,shift2) \ + (((( (lzo_xint)((p)[2]) << shift1) ^ (p)[1]) << shift2) ^ (p)[0]) +# define _DV3_B(p,shift1,shift2,shift3) \ + ((_DV2_B((p)+1,shift1,shift2) << (shift3)) ^ (p)[0]) +#elif (DL_MIN_LEN == 2) +# define _DV2_A(p,shift1,shift2) \ + (( (lzo_xint)(p[0]) << shift1) ^ p[1]) +# define _DV2_B(p,shift1,shift2) \ + (( (lzo_xint)(p[1]) << shift1) ^ p[2]) +#else +# error "invalid DL_MIN_LEN" +#endif +#define _DV_A(p,shift) _DV2_A(p,shift,shift) +#define _DV_B(p,shift) _DV2_B(p,shift,shift) +#define DA2(p,s1,s2) \ + (((((lzo_xint)((p)[2]) << (s2)) + (p)[1]) << (s1)) + (p)[0]) +#define DS2(p,s1,s2) \ + (((((lzo_xint)((p)[2]) << (s2)) - (p)[1]) << (s1)) - (p)[0]) +#define DX2(p,s1,s2) \ + (((((lzo_xint)((p)[2]) << (s2)) ^ (p)[1]) << (s1)) ^ (p)[0]) +#define DA3(p,s1,s2,s3) ((DA2((p)+1,s2,s3) << (s1)) + (p)[0]) +#define DS3(p,s1,s2,s3) ((DS2((p)+1,s2,s3) << (s1)) - (p)[0]) +#define DX3(p,s1,s2,s3) ((DX2((p)+1,s2,s3) << (s1)) ^ (p)[0]) +#define DMS(v,s) ((lzo_uint) (((v) & (D_MASK >> (s))) << (s))) +#define DM(v) DMS(v,0) + +#if (LZO_HASH == LZO_HASH_GZIP) +# define _DINDEX(dv,p) (_DV_A((p),DL_SHIFT)) + +#elif (LZO_HASH == LZO_HASH_GZIP_INCREMENTAL) +# define __LZO_HASH_INCREMENTAL 1 +# define DVAL_FIRST(dv,p) dv = _DV_A((p),DL_SHIFT) +# define DVAL_NEXT(dv,p) dv = (((dv) << DL_SHIFT) ^ p[2]) +# define _DINDEX(dv,p) (dv) +# define DVAL_LOOKAHEAD DL_MIN_LEN + +#elif (LZO_HASH == LZO_HASH_LZO_INCREMENTAL_A) +# define __LZO_HASH_INCREMENTAL 1 +# define DVAL_FIRST(dv,p) dv = _DV_A((p),5) +# define DVAL_NEXT(dv,p) \ + dv ^= (lzo_xint)(p[-1]) << (2*5); dv = (((dv) << 5) ^ p[2]) +# define _DINDEX(dv,p) ((DMUL(0x9f5f,dv)) >> 5) +# define DVAL_LOOKAHEAD DL_MIN_LEN + +#elif (LZO_HASH == LZO_HASH_LZO_INCREMENTAL_B) +# define __LZO_HASH_INCREMENTAL 1 +# define DVAL_FIRST(dv,p) dv = _DV_B((p),5) +# define DVAL_NEXT(dv,p) \ + dv ^= p[-1]; dv = (((dv) >> 5) ^ ((lzo_xint)(p[2]) << (2*5))) +# define _DINDEX(dv,p) ((DMUL(0x9f5f,dv)) >> 5) +# define DVAL_LOOKAHEAD DL_MIN_LEN + +#else +# error "choose a hashing strategy" +#endif + +#ifndef DINDEX +#define DINDEX(dv,p) ((lzo_uint)((_DINDEX(dv,p)) & DL_MASK) << DD_BITS) +#endif +#if !defined(DINDEX1) && defined(D_INDEX1) +#define DINDEX1 D_INDEX1 +#endif +#if !defined(DINDEX2) && defined(D_INDEX2) +#define DINDEX2 D_INDEX2 +#endif + +#if !defined(__LZO_HASH_INCREMENTAL) +# define DVAL_FIRST(dv,p) ((void) 0) +# define DVAL_NEXT(dv,p) ((void) 0) +# define DVAL_LOOKAHEAD 0 +#endif + +#if !defined(DVAL_ASSERT) +#if defined(__LZO_HASH_INCREMENTAL) && !defined(NDEBUG) +#if 1 && (LZO_CC_ARMCC_GNUC || LZO_CC_CLANG || (LZO_CC_GNUC >= 0x020700ul) || LZO_CC_INTELC_GNUC || LZO_CC_LLVM || LZO_CC_PATHSCALE || LZO_CC_PGI) +static void __attribute__((__unused__)) +#else +static void +#endif +DVAL_ASSERT(lzo_xint dv, const lzo_bytep p) +{ + lzo_xint df; + DVAL_FIRST(df,(p)); + assert(DINDEX(dv,p) == DINDEX(df,p)); +} +#else +# define DVAL_ASSERT(dv,p) ((void) 0) +#endif +#endif + +#if (LZO_DICT_USE_PTR) +# define DENTRY(p,in) (p) +# define GINDEX(m_pos,m_off,dict,dindex,in) m_pos = dict[dindex] +#else +# define DENTRY(p,in) ((lzo_dict_t) pd(p, in)) +# define GINDEX(m_pos,m_off,dict,dindex,in) m_off = dict[dindex] +#endif + +#if (DD_BITS == 0) + +# define UPDATE_D(dict,drun,dv,p,in) dict[ DINDEX(dv,p) ] = DENTRY(p,in) +# define UPDATE_I(dict,drun,index,p,in) dict[index] = DENTRY(p,in) +# define UPDATE_P(ptr,drun,p,in) (ptr)[0] = DENTRY(p,in) + +#else + +# define UPDATE_D(dict,drun,dv,p,in) \ + dict[ DINDEX(dv,p) + drun++ ] = DENTRY(p,in); drun &= DD_MASK +# define UPDATE_I(dict,drun,index,p,in) \ + dict[ (index) + drun++ ] = DENTRY(p,in); drun &= DD_MASK +# define UPDATE_P(ptr,drun,p,in) \ + (ptr) [ drun++ ] = DENTRY(p,in); drun &= DD_MASK + +#endif + +#if (LZO_DICT_USE_PTR) + +#define LZO_CHECK_MPOS_DET(m_pos,m_off,in,ip,max_offset) \ + (m_pos == NULL || (m_off = pd(ip, m_pos)) > max_offset) + +#define LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,max_offset) \ + (BOUNDS_CHECKING_OFF_IN_EXPR(( \ + m_pos = ip - (lzo_uint) PTR_DIFF(ip,m_pos), \ + PTR_LT(m_pos,in) || \ + (m_off = (lzo_uint) PTR_DIFF(ip,m_pos)) == 0 || \ + m_off > max_offset ))) + +#else + +#define LZO_CHECK_MPOS_DET(m_pos,m_off,in,ip,max_offset) \ + (m_off == 0 || \ + ((m_off = pd(ip, in) - m_off) > max_offset) || \ + (m_pos = (ip) - (m_off), 0) ) + +#define LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,max_offset) \ + (pd(ip, in) <= m_off || \ + ((m_off = pd(ip, in) - m_off) > max_offset) || \ + (m_pos = (ip) - (m_off), 0) ) + +#endif + +#if (LZO_DETERMINISTIC) +# define LZO_CHECK_MPOS LZO_CHECK_MPOS_DET +#else +# define LZO_CHECK_MPOS LZO_CHECK_MPOS_NON_DET +#endif + +#ifdef __cplusplus +} +#endif + +#endif + +#endif + +#endif + +#define LZO_DETERMINISTIC !(LZO_DICT_USE_PTR) + +#ifndef DO_COMPRESS +#define DO_COMPRESS lzo1x_1_compress +#endif + +#if 1 && defined(DO_COMPRESS) && !defined(do_compress) +# define do_compress LZO_PP_ECONCAT2(DO_COMPRESS,_core) +#endif + +static __lzo_noinline lzo_uint +do_compress ( const lzo_bytep in , lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_uint ti, lzo_voidp wrkmem) +{ + const lzo_bytep ip; + lzo_bytep op; + const lzo_bytep const in_end = in + in_len; + const lzo_bytep const ip_end = in + in_len - 20; + const lzo_bytep ii; + lzo_dict_p const dict = (lzo_dict_p) wrkmem; + + op = out; + ip = in; + ii = ip; + + ip += ti < 4 ? 4 - ti : 0; + for (;;) + { + const lzo_bytep m_pos; +#if !(LZO_DETERMINISTIC) + LZO_DEFINE_UNINITIALIZED_VAR(lzo_uint, m_off, 0); + lzo_uint m_len; + lzo_uint dindex; +next: + if __lzo_unlikely(ip >= ip_end) + break; + DINDEX1(dindex,ip); + GINDEX(m_pos,m_off,dict,dindex,in); + if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET)) + goto literal; +#if 1 + if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3]) + goto try_match; + DINDEX2(dindex,ip); +#endif + GINDEX(m_pos,m_off,dict,dindex,in); + if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET)) + goto literal; + if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3]) + goto try_match; + goto literal; + +try_match: +#if (LZO_OPT_UNALIGNED32) + if (UA_GET_NE32(m_pos) != UA_GET_NE32(ip)) +#else + if (m_pos[0] != ip[0] || m_pos[1] != ip[1] || m_pos[2] != ip[2] || m_pos[3] != ip[3]) +#endif + { +literal: + UPDATE_I(dict,0,dindex,ip,in); + ip += 1 + ((ip - ii) >> 5); + continue; + } + UPDATE_I(dict,0,dindex,ip,in); +#else + lzo_uint m_off; + lzo_uint m_len; + { + lzo_uint32_t dv; + lzo_uint dindex; +literal: + ip += 1 + ((ip - ii) >> 5); +next: + if __lzo_unlikely(ip >= ip_end) + break; + dv = UA_GET_LE32(ip); + dindex = DINDEX(dv,ip); + GINDEX(m_off,m_pos,in+dict,dindex,in); + UPDATE_I(dict,0,dindex,ip,in); + if __lzo_unlikely(dv != UA_GET_LE32(m_pos)) + goto literal; + } +#endif + + ii -= ti; ti = 0; + { + lzo_uint t = pd(ip,ii); + if (t != 0) + { + if (t <= 3) + { + op[-2] = LZO_BYTE(op[-2] | t); +#if (LZO_OPT_UNALIGNED32) + UA_COPY4(op, ii); + op += t; +#else + { do *op++ = *ii++; while (--t > 0); } +#endif + } +#if (LZO_OPT_UNALIGNED32) || (LZO_OPT_UNALIGNED64) + else if (t <= 16) + { + *op++ = LZO_BYTE(t - 3); + UA_COPY8(op, ii); + UA_COPY8(op+8, ii+8); + op += t; + } +#endif + else + { + if (t <= 18) + *op++ = LZO_BYTE(t - 3); + else + { + lzo_uint tt = t - 18; + *op++ = 0; + while __lzo_unlikely(tt > 255) + { + tt -= 255; + UA_SET1(op, 0); + op++; + } + assert(tt > 0); + *op++ = LZO_BYTE(tt); + } +#if (LZO_OPT_UNALIGNED32) || (LZO_OPT_UNALIGNED64) + do { + UA_COPY8(op, ii); + UA_COPY8(op+8, ii+8); + op += 16; ii += 16; t -= 16; + } while (t >= 16); if (t > 0) +#endif + { do *op++ = *ii++; while (--t > 0); } + } + } + } + m_len = 4; + { +#if (LZO_OPT_UNALIGNED64) + lzo_uint64_t v; + v = UA_GET_NE64(ip + m_len) ^ UA_GET_NE64(m_pos + m_len); + if __lzo_unlikely(v == 0) { + do { + m_len += 8; + v = UA_GET_NE64(ip + m_len) ^ UA_GET_NE64(m_pos + m_len); + if __lzo_unlikely(ip + m_len >= ip_end) + goto m_len_done; + } while (v == 0); + } +#if (LZO_ABI_BIG_ENDIAN) && defined(lzo_bitops_ctlz64) + m_len += lzo_bitops_ctlz64(v) / CHAR_BIT; +#elif (LZO_ABI_BIG_ENDIAN) + if ((v >> (64 - CHAR_BIT)) == 0) do { + v <<= CHAR_BIT; + m_len += 1; + } while ((v >> (64 - CHAR_BIT)) == 0); +#elif (LZO_ABI_LITTLE_ENDIAN) && defined(lzo_bitops_cttz64) + m_len += lzo_bitops_cttz64(v) / CHAR_BIT; +#elif (LZO_ABI_LITTLE_ENDIAN) + if ((v & UCHAR_MAX) == 0) do { + v >>= CHAR_BIT; + m_len += 1; + } while ((v & UCHAR_MAX) == 0); +#else + if (ip[m_len] == m_pos[m_len]) do { + m_len += 1; + } while (ip[m_len] == m_pos[m_len]); +#endif +#elif (LZO_OPT_UNALIGNED32) + lzo_uint32_t v; + v = UA_GET_NE32(ip + m_len) ^ UA_GET_NE32(m_pos + m_len); + if __lzo_unlikely(v == 0) { + do { + m_len += 4; + v = UA_GET_NE32(ip + m_len) ^ UA_GET_NE32(m_pos + m_len); + if (v != 0) + break; + m_len += 4; + v = UA_GET_NE32(ip + m_len) ^ UA_GET_NE32(m_pos + m_len); + if __lzo_unlikely(ip + m_len >= ip_end) + goto m_len_done; + } while (v == 0); + } +#if (LZO_ABI_BIG_ENDIAN) && defined(lzo_bitops_ctlz32) + m_len += lzo_bitops_ctlz32(v) / CHAR_BIT; +#elif (LZO_ABI_BIG_ENDIAN) + if ((v >> (32 - CHAR_BIT)) == 0) do { + v <<= CHAR_BIT; + m_len += 1; + } while ((v >> (32 - CHAR_BIT)) == 0); +#elif (LZO_ABI_LITTLE_ENDIAN) && defined(lzo_bitops_cttz32) + m_len += lzo_bitops_cttz32(v) / CHAR_BIT; +#elif (LZO_ABI_LITTLE_ENDIAN) + if ((v & UCHAR_MAX) == 0) do { + v >>= CHAR_BIT; + m_len += 1; + } while ((v & UCHAR_MAX) == 0); +#else + if (ip[m_len] == m_pos[m_len]) do { + m_len += 1; + } while (ip[m_len] == m_pos[m_len]); +#endif +#else + if __lzo_unlikely(ip[m_len] == m_pos[m_len]) { + do { + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if (ip[m_len] != m_pos[m_len]) + break; + m_len += 1; + if __lzo_unlikely(ip + m_len >= ip_end) + goto m_len_done; + } while (ip[m_len] == m_pos[m_len]); + } +#endif + } +m_len_done: + m_off = pd(ip,m_pos); + ip += m_len; + ii = ip; + if (m_len <= M2_MAX_LEN && m_off <= M2_MAX_OFFSET) + { + m_off -= 1; +#if defined(LZO1X) + *op++ = LZO_BYTE(((m_len - 1) << 5) | ((m_off & 7) << 2)); + *op++ = LZO_BYTE(m_off >> 3); +#elif defined(LZO1Y) + *op++ = LZO_BYTE(((m_len + 1) << 4) | ((m_off & 3) << 2)); + *op++ = LZO_BYTE(m_off >> 2); +#endif + } + else if (m_off <= M3_MAX_OFFSET) + { + m_off -= 1; + if (m_len <= M3_MAX_LEN) + *op++ = LZO_BYTE(M3_MARKER | (m_len - 2)); + else + { + m_len -= M3_MAX_LEN; + *op++ = M3_MARKER | 0; + while __lzo_unlikely(m_len > 255) + { + m_len -= 255; + UA_SET1(op, 0); + op++; + } + *op++ = LZO_BYTE(m_len); + } + *op++ = LZO_BYTE(m_off << 2); + *op++ = LZO_BYTE(m_off >> 6); + } + else + { + m_off -= 0x4000; + if (m_len <= M4_MAX_LEN) + *op++ = LZO_BYTE(M4_MARKER | ((m_off >> 11) & 8) | (m_len - 2)); + else + { + m_len -= M4_MAX_LEN; + *op++ = LZO_BYTE(M4_MARKER | ((m_off >> 11) & 8)); + while __lzo_unlikely(m_len > 255) + { + m_len -= 255; + UA_SET1(op, 0); + op++; + } + *op++ = LZO_BYTE(m_len); + } + *op++ = LZO_BYTE(m_off << 2); + *op++ = LZO_BYTE(m_off >> 6); + } + goto next; + } + + *out_len = pd(op, out); + return pd(in_end,ii-ti); +} + +LZO_PUBLIC(int) +DO_COMPRESS ( const lzo_bytep in , lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_voidp wrkmem ) +{ + const lzo_bytep ip = in; + lzo_bytep op = out; + lzo_uint l = in_len; + lzo_uint t = 0; + + while (l > 20) + { + lzo_uint ll = l; + lzo_uintptr_t ll_end; +#if 0 || (LZO_DETERMINISTIC) + ll = LZO_MIN(ll, 49152); +#endif + ll_end = (lzo_uintptr_t)ip + ll; + if ((ll_end + ((t + ll) >> 5)) <= ll_end || (const lzo_bytep)(ll_end + ((t + ll) >> 5)) <= ip + ll) + break; +#if (LZO_DETERMINISTIC) + lzo_memset(wrkmem, 0, ((lzo_uint)1 << D_BITS) * sizeof(lzo_dict_t)); +#endif + t = do_compress(ip,ll,op,out_len,t,wrkmem); + ip += ll; + op += *out_len; + l -= ll; + } + t += l; + + if (t > 0) + { + const lzo_bytep ii = in + in_len - t; + + if (op == out && t <= 238) + *op++ = LZO_BYTE(17 + t); + else if (t <= 3) + op[-2] = LZO_BYTE(op[-2] | t); + else if (t <= 18) + *op++ = LZO_BYTE(t - 3); + else + { + lzo_uint tt = t - 18; + + *op++ = 0; + while (tt > 255) + { + tt -= 255; + UA_SET1(op, 0); + op++; + } + assert(tt > 0); + *op++ = LZO_BYTE(tt); + } + UA_COPYN(op, ii, t); + op += t; + } + + *op++ = M4_MARKER | 1; + *op++ = 0; + *op++ = 0; + + *out_len = pd(op, out); + return LZO_E_OK; +} + +#endif + +#undef do_compress +#undef DO_COMPRESS +#undef LZO_HASH + +#undef LZO_TEST_OVERRUN +#undef DO_DECOMPRESS +#define DO_DECOMPRESS lzo1x_decompress + +#if !defined(MINILZO_CFG_SKIP_LZO1X_DECOMPRESS) + +#if defined(LZO_TEST_OVERRUN) +# if !defined(LZO_TEST_OVERRUN_INPUT) +# define LZO_TEST_OVERRUN_INPUT 2 +# endif +# if !defined(LZO_TEST_OVERRUN_OUTPUT) +# define LZO_TEST_OVERRUN_OUTPUT 2 +# endif +# if !defined(LZO_TEST_OVERRUN_LOOKBEHIND) +# define LZO_TEST_OVERRUN_LOOKBEHIND 1 +# endif +#endif + +#undef TEST_IP +#undef TEST_OP +#undef TEST_IP_AND_TEST_OP +#undef TEST_LB +#undef TEST_LBO +#undef NEED_IP +#undef NEED_OP +#undef TEST_IV +#undef TEST_OV +#undef HAVE_TEST_IP +#undef HAVE_TEST_OP +#undef HAVE_NEED_IP +#undef HAVE_NEED_OP +#undef HAVE_ANY_IP +#undef HAVE_ANY_OP + +#if defined(LZO_TEST_OVERRUN_INPUT) +# if (LZO_TEST_OVERRUN_INPUT >= 1) +# define TEST_IP (ip < ip_end) +# endif +# if (LZO_TEST_OVERRUN_INPUT >= 2) +# define NEED_IP(x) \ + if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun +# define TEST_IV(x) if ((x) > (lzo_uint)0 - (511)) goto input_overrun +# endif +#endif + +#if defined(LZO_TEST_OVERRUN_OUTPUT) +# if (LZO_TEST_OVERRUN_OUTPUT >= 1) +# define TEST_OP (op <= op_end) +# endif +# if (LZO_TEST_OVERRUN_OUTPUT >= 2) +# undef TEST_OP +# define NEED_OP(x) \ + if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun +# define TEST_OV(x) if ((x) > (lzo_uint)0 - (511)) goto output_overrun +# endif +#endif + +#if defined(LZO_TEST_OVERRUN_LOOKBEHIND) +# define TEST_LB(m_pos) if (PTR_LT(m_pos,out) || PTR_GE(m_pos,op)) goto lookbehind_overrun +# define TEST_LBO(m_pos,o) if (PTR_LT(m_pos,out) || PTR_GE(m_pos,op-(o))) goto lookbehind_overrun +#else +# define TEST_LB(m_pos) ((void) 0) +# define TEST_LBO(m_pos,o) ((void) 0) +#endif + +#if !defined(LZO_EOF_CODE) && !defined(TEST_IP) +# define TEST_IP (ip < ip_end) +#endif + +#if defined(TEST_IP) +# define HAVE_TEST_IP 1 +#else +# define TEST_IP 1 +#endif +#if defined(TEST_OP) +# define HAVE_TEST_OP 1 +#else +# define TEST_OP 1 +#endif + +#if defined(HAVE_TEST_IP) && defined(HAVE_TEST_OP) +# define TEST_IP_AND_TEST_OP (TEST_IP && TEST_OP) +#elif defined(HAVE_TEST_IP) +# define TEST_IP_AND_TEST_OP TEST_IP +#elif defined(HAVE_TEST_OP) +# define TEST_IP_AND_TEST_OP TEST_OP +#else +# define TEST_IP_AND_TEST_OP 1 +#endif + +#if defined(NEED_IP) +# define HAVE_NEED_IP 1 +#else +# define NEED_IP(x) ((void) 0) +# define TEST_IV(x) ((void) 0) +#endif +#if defined(NEED_OP) +# define HAVE_NEED_OP 1 +#else +# define NEED_OP(x) ((void) 0) +# define TEST_OV(x) ((void) 0) +#endif + +#if defined(HAVE_TEST_IP) || defined(HAVE_NEED_IP) +# define HAVE_ANY_IP 1 +#endif +#if defined(HAVE_TEST_OP) || defined(HAVE_NEED_OP) +# define HAVE_ANY_OP 1 +#endif + +#if defined(DO_DECOMPRESS) +LZO_PUBLIC(int) +DO_DECOMPRESS ( const lzo_bytep in , lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_voidp wrkmem ) +#endif +{ + lzo_bytep op; + const lzo_bytep ip; + lzo_uint t; +#if defined(COPY_DICT) + lzo_uint m_off; + const lzo_bytep dict_end; +#else + const lzo_bytep m_pos; +#endif + + const lzo_bytep const ip_end = in + in_len; +#if defined(HAVE_ANY_OP) + lzo_bytep const op_end = out + *out_len; +#endif +#if defined(LZO1Z) + lzo_uint last_m_off = 0; +#endif + + LZO_UNUSED(wrkmem); + +#if defined(COPY_DICT) + if (dict) + { + if (dict_len > M4_MAX_OFFSET) + { + dict += dict_len - M4_MAX_OFFSET; + dict_len = M4_MAX_OFFSET; + } + dict_end = dict + dict_len; + } + else + { + dict_len = 0; + dict_end = NULL; + } +#endif + + *out_len = 0; + + op = out; + ip = in; + + NEED_IP(1); + if (*ip > 17) + { + t = *ip++ - 17; + if (t < 4) + goto match_next; + assert(t > 0); NEED_OP(t); NEED_IP(t+3); + do *op++ = *ip++; while (--t > 0); + goto first_literal_run; + } + + for (;;) + { + NEED_IP(3); + t = *ip++; + if (t >= 16) + goto match; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_IV(t); + NEED_IP(1); + } + t += 15 + *ip++; + } + assert(t > 0); NEED_OP(t+3); NEED_IP(t+6); +#if (LZO_OPT_UNALIGNED64) && (LZO_OPT_UNALIGNED32) + t += 3; + if (t >= 8) do + { + UA_COPY8(op,ip); + op += 8; ip += 8; t -= 8; + } while (t >= 8); + if (t >= 4) + { + UA_COPY4(op,ip); + op += 4; ip += 4; t -= 4; + } + if (t > 0) + { + *op++ = *ip++; + if (t > 1) { *op++ = *ip++; if (t > 2) { *op++ = *ip++; } } + } +#elif (LZO_OPT_UNALIGNED32) || (LZO_ALIGNED_OK_4) +#if !(LZO_OPT_UNALIGNED32) + if (PTR_ALIGNED2_4(op,ip)) + { +#endif + UA_COPY4(op,ip); + op += 4; ip += 4; + if (--t > 0) + { + if (t >= 4) + { + do { + UA_COPY4(op,ip); + op += 4; ip += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *ip++; while (--t > 0); + } + else + do *op++ = *ip++; while (--t > 0); + } +#if !(LZO_OPT_UNALIGNED32) + } + else +#endif +#endif +#if !(LZO_OPT_UNALIGNED32) + { + *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; + do *op++ = *ip++; while (--t > 0); + } +#endif + +first_literal_run: + + t = *ip++; + if (t >= 16) + goto match; +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; +#else + m_off = (1 + M2_MAX_OFFSET) + (t >> 2) + (*ip++ << 2); +#endif + NEED_OP(3); + t = 3; COPY_DICT(t,m_off) +#else +#if defined(LZO1Z) + t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; +#else + m_pos = op - (1 + M2_MAX_OFFSET); + m_pos -= t >> 2; + m_pos -= *ip++ << 2; +#endif + TEST_LB(m_pos); NEED_OP(3); + *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; +#endif + goto match_done; + + for (;;) { +match: + if (t >= 64) + { +#if defined(COPY_DICT) +#if defined(LZO1X) + m_off = 1 + ((t >> 2) & 7) + (*ip++ << 3); + t = (t >> 5) - 1; +#elif defined(LZO1Y) + m_off = 1 + ((t >> 2) & 3) + (*ip++ << 2); + t = (t >> 4) - 3; +#elif defined(LZO1Z) + m_off = t & 0x1f; + if (m_off >= 0x1c) + m_off = last_m_off; + else + { + m_off = 1 + (m_off << 6) + (*ip++ >> 2); + last_m_off = m_off; + } + t = (t >> 5) - 1; +#endif +#else +#if defined(LZO1X) + m_pos = op - 1; + m_pos -= (t >> 2) & 7; + m_pos -= *ip++ << 3; + t = (t >> 5) - 1; +#elif defined(LZO1Y) + m_pos = op - 1; + m_pos -= (t >> 2) & 3; + m_pos -= *ip++ << 2; + t = (t >> 4) - 3; +#elif defined(LZO1Z) + { + lzo_uint off = t & 0x1f; + m_pos = op; + if (off >= 0x1c) + { + assert(last_m_off > 0); + m_pos -= last_m_off; + } + else + { + off = 1 + (off << 6) + (*ip++ >> 2); + m_pos -= off; + last_m_off = off; + } + } + t = (t >> 5) - 1; +#endif + TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); + goto copy_match; +#endif + } + else if (t >= 32) + { + t &= 31; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_OV(t); + NEED_IP(1); + } + t += 31 + *ip++; + NEED_IP(2); + } +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = 1 + (ip[0] << 6) + (ip[1] >> 2); + last_m_off = m_off; +#else + m_off = 1 + (ip[0] >> 2) + (ip[1] << 6); +#endif +#else +#if defined(LZO1Z) + { + lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2); + m_pos = op - off; + last_m_off = off; + } +#elif (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) + m_pos = op - 1; + m_pos -= UA_GET_LE16(ip) >> 2; +#else + m_pos = op - 1; + m_pos -= (ip[0] >> 2) + (ip[1] << 6); +#endif +#endif + ip += 2; + } + else if (t >= 16) + { +#if defined(COPY_DICT) + m_off = (t & 8) << 11; +#else + m_pos = op; + m_pos -= (t & 8) << 11; +#endif + t &= 7; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_OV(t); + NEED_IP(1); + } + t += 7 + *ip++; + NEED_IP(2); + } +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off += (ip[0] << 6) + (ip[1] >> 2); +#else + m_off += (ip[0] >> 2) + (ip[1] << 6); +#endif + ip += 2; + if (m_off == 0) + goto eof_found; + m_off += 0x4000; +#if defined(LZO1Z) + last_m_off = m_off; +#endif +#else +#if defined(LZO1Z) + m_pos -= (ip[0] << 6) + (ip[1] >> 2); +#elif (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) + m_pos -= UA_GET_LE16(ip) >> 2; +#else + m_pos -= (ip[0] >> 2) + (ip[1] << 6); +#endif + ip += 2; + if (m_pos == op) + goto eof_found; + m_pos -= 0x4000; +#if defined(LZO1Z) + last_m_off = pd((const lzo_bytep)op, m_pos); +#endif +#endif + } + else + { +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = 1 + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; +#else + m_off = 1 + (t >> 2) + (*ip++ << 2); +#endif + NEED_OP(2); + t = 2; COPY_DICT(t,m_off) +#else +#if defined(LZO1Z) + t = 1 + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; +#else + m_pos = op - 1; + m_pos -= t >> 2; + m_pos -= *ip++ << 2; +#endif + TEST_LB(m_pos); NEED_OP(2); + *op++ = *m_pos++; *op++ = *m_pos; +#endif + goto match_done; + } + +#if defined(COPY_DICT) + + NEED_OP(t+3-1); + t += 3-1; COPY_DICT(t,m_off) + +#else + + TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); +#if (LZO_OPT_UNALIGNED64) && (LZO_OPT_UNALIGNED32) + if (op - m_pos >= 8) + { + t += (3 - 1); + if (t >= 8) do + { + UA_COPY8(op,m_pos); + op += 8; m_pos += 8; t -= 8; + } while (t >= 8); + if (t >= 4) + { + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4; + } + if (t > 0) + { + *op++ = m_pos[0]; + if (t > 1) { *op++ = m_pos[1]; if (t > 2) { *op++ = m_pos[2]; } } + } + } + else +#elif (LZO_OPT_UNALIGNED32) || (LZO_ALIGNED_OK_4) +#if !(LZO_OPT_UNALIGNED32) + if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos)) + { + assert((op - m_pos) >= 4); +#else + if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4) + { +#endif + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4 - (3 - 1); + do { + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *m_pos++; while (--t > 0); + } + else +#endif + { +copy_match: + *op++ = *m_pos++; *op++ = *m_pos++; + do *op++ = *m_pos++; while (--t > 0); + } + +#endif + +match_done: +#if defined(LZO1Z) + t = ip[-1] & 3; +#else + t = ip[-2] & 3; +#endif + if (t == 0) + break; + +match_next: + assert(t > 0); assert(t < 4); NEED_OP(t); NEED_IP(t+3); +#if 0 + do *op++ = *ip++; while (--t > 0); +#else + *op++ = *ip++; + if (t > 1) { *op++ = *ip++; if (t > 2) { *op++ = *ip++; } } +#endif + t = *ip++; + } + } + +eof_found: + *out_len = pd(op, out); + return (ip == ip_end ? LZO_E_OK : + (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); + +#if defined(HAVE_NEED_IP) +input_overrun: + *out_len = pd(op, out); + return LZO_E_INPUT_OVERRUN; +#endif + +#if defined(HAVE_NEED_OP) +output_overrun: + *out_len = pd(op, out); + return LZO_E_OUTPUT_OVERRUN; +#endif + +#if defined(LZO_TEST_OVERRUN_LOOKBEHIND) +lookbehind_overrun: + *out_len = pd(op, out); + return LZO_E_LOOKBEHIND_OVERRUN; +#endif +} + +#endif + +#define LZO_TEST_OVERRUN 1 +#undef DO_DECOMPRESS +#define DO_DECOMPRESS lzo1x_decompress_safe + +#if !defined(MINILZO_CFG_SKIP_LZO1X_DECOMPRESS_SAFE) + +#if defined(LZO_TEST_OVERRUN) +# if !defined(LZO_TEST_OVERRUN_INPUT) +# define LZO_TEST_OVERRUN_INPUT 2 +# endif +# if !defined(LZO_TEST_OVERRUN_OUTPUT) +# define LZO_TEST_OVERRUN_OUTPUT 2 +# endif +# if !defined(LZO_TEST_OVERRUN_LOOKBEHIND) +# define LZO_TEST_OVERRUN_LOOKBEHIND 1 +# endif +#endif + +#undef TEST_IP +#undef TEST_OP +#undef TEST_IP_AND_TEST_OP +#undef TEST_LB +#undef TEST_LBO +#undef NEED_IP +#undef NEED_OP +#undef TEST_IV +#undef TEST_OV +#undef HAVE_TEST_IP +#undef HAVE_TEST_OP +#undef HAVE_NEED_IP +#undef HAVE_NEED_OP +#undef HAVE_ANY_IP +#undef HAVE_ANY_OP + +#if defined(LZO_TEST_OVERRUN_INPUT) +# if (LZO_TEST_OVERRUN_INPUT >= 1) +# define TEST_IP (ip < ip_end) +# endif +# if (LZO_TEST_OVERRUN_INPUT >= 2) +# define NEED_IP(x) \ + if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun +# define TEST_IV(x) if ((x) > (lzo_uint)0 - (511)) goto input_overrun +# endif +#endif + +#if defined(LZO_TEST_OVERRUN_OUTPUT) +# if (LZO_TEST_OVERRUN_OUTPUT >= 1) +# define TEST_OP (op <= op_end) +# endif +# if (LZO_TEST_OVERRUN_OUTPUT >= 2) +# undef TEST_OP +# define NEED_OP(x) \ + if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun +# define TEST_OV(x) if ((x) > (lzo_uint)0 - (511)) goto output_overrun +# endif +#endif + +#if defined(LZO_TEST_OVERRUN_LOOKBEHIND) +# define TEST_LB(m_pos) if (PTR_LT(m_pos,out) || PTR_GE(m_pos,op)) goto lookbehind_overrun +# define TEST_LBO(m_pos,o) if (PTR_LT(m_pos,out) || PTR_GE(m_pos,op-(o))) goto lookbehind_overrun +#else +# define TEST_LB(m_pos) ((void) 0) +# define TEST_LBO(m_pos,o) ((void) 0) +#endif + +#if !defined(LZO_EOF_CODE) && !defined(TEST_IP) +# define TEST_IP (ip < ip_end) +#endif + +#if defined(TEST_IP) +# define HAVE_TEST_IP 1 +#else +# define TEST_IP 1 +#endif +#if defined(TEST_OP) +# define HAVE_TEST_OP 1 +#else +# define TEST_OP 1 +#endif + +#if defined(HAVE_TEST_IP) && defined(HAVE_TEST_OP) +# define TEST_IP_AND_TEST_OP (TEST_IP && TEST_OP) +#elif defined(HAVE_TEST_IP) +# define TEST_IP_AND_TEST_OP TEST_IP +#elif defined(HAVE_TEST_OP) +# define TEST_IP_AND_TEST_OP TEST_OP +#else +# define TEST_IP_AND_TEST_OP 1 +#endif + +#if defined(NEED_IP) +# define HAVE_NEED_IP 1 +#else +# define NEED_IP(x) ((void) 0) +# define TEST_IV(x) ((void) 0) +#endif +#if defined(NEED_OP) +# define HAVE_NEED_OP 1 +#else +# define NEED_OP(x) ((void) 0) +# define TEST_OV(x) ((void) 0) +#endif + +#if defined(HAVE_TEST_IP) || defined(HAVE_NEED_IP) +# define HAVE_ANY_IP 1 +#endif +#if defined(HAVE_TEST_OP) || defined(HAVE_NEED_OP) +# define HAVE_ANY_OP 1 +#endif + +#if defined(DO_DECOMPRESS) +LZO_PUBLIC(int) +DO_DECOMPRESS ( const lzo_bytep in , lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_voidp wrkmem ) +#endif +{ + lzo_bytep op; + const lzo_bytep ip; + lzo_uint t; +#if defined(COPY_DICT) + lzo_uint m_off; + const lzo_bytep dict_end; +#else + const lzo_bytep m_pos; +#endif + + const lzo_bytep const ip_end = in + in_len; +#if defined(HAVE_ANY_OP) + lzo_bytep const op_end = out + *out_len; +#endif +#if defined(LZO1Z) + lzo_uint last_m_off = 0; +#endif + + LZO_UNUSED(wrkmem); + +#if defined(COPY_DICT) + if (dict) + { + if (dict_len > M4_MAX_OFFSET) + { + dict += dict_len - M4_MAX_OFFSET; + dict_len = M4_MAX_OFFSET; + } + dict_end = dict + dict_len; + } + else + { + dict_len = 0; + dict_end = NULL; + } +#endif + + *out_len = 0; + + op = out; + ip = in; + + NEED_IP(1); + if (*ip > 17) + { + t = *ip++ - 17; + if (t < 4) + goto match_next; + assert(t > 0); NEED_OP(t); NEED_IP(t+3); + do *op++ = *ip++; while (--t > 0); + goto first_literal_run; + } + + for (;;) + { + NEED_IP(3); + t = *ip++; + if (t >= 16) + goto match; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_IV(t); + NEED_IP(1); + } + t += 15 + *ip++; + } + assert(t > 0); NEED_OP(t+3); NEED_IP(t+6); +#if (LZO_OPT_UNALIGNED64) && (LZO_OPT_UNALIGNED32) + t += 3; + if (t >= 8) do + { + UA_COPY8(op,ip); + op += 8; ip += 8; t -= 8; + } while (t >= 8); + if (t >= 4) + { + UA_COPY4(op,ip); + op += 4; ip += 4; t -= 4; + } + if (t > 0) + { + *op++ = *ip++; + if (t > 1) { *op++ = *ip++; if (t > 2) { *op++ = *ip++; } } + } +#elif (LZO_OPT_UNALIGNED32) || (LZO_ALIGNED_OK_4) +#if !(LZO_OPT_UNALIGNED32) + if (PTR_ALIGNED2_4(op,ip)) + { +#endif + UA_COPY4(op,ip); + op += 4; ip += 4; + if (--t > 0) + { + if (t >= 4) + { + do { + UA_COPY4(op,ip); + op += 4; ip += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *ip++; while (--t > 0); + } + else + do *op++ = *ip++; while (--t > 0); + } +#if !(LZO_OPT_UNALIGNED32) + } + else +#endif +#endif +#if !(LZO_OPT_UNALIGNED32) + { + *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; + do *op++ = *ip++; while (--t > 0); + } +#endif + +first_literal_run: + + t = *ip++; + if (t >= 16) + goto match; +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; +#else + m_off = (1 + M2_MAX_OFFSET) + (t >> 2) + (*ip++ << 2); +#endif + NEED_OP(3); + t = 3; COPY_DICT(t,m_off) +#else +#if defined(LZO1Z) + t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; +#else + m_pos = op - (1 + M2_MAX_OFFSET); + m_pos -= t >> 2; + m_pos -= *ip++ << 2; +#endif + TEST_LB(m_pos); NEED_OP(3); + *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; +#endif + goto match_done; + + for (;;) { +match: + if (t >= 64) + { +#if defined(COPY_DICT) +#if defined(LZO1X) + m_off = 1 + ((t >> 2) & 7) + (*ip++ << 3); + t = (t >> 5) - 1; +#elif defined(LZO1Y) + m_off = 1 + ((t >> 2) & 3) + (*ip++ << 2); + t = (t >> 4) - 3; +#elif defined(LZO1Z) + m_off = t & 0x1f; + if (m_off >= 0x1c) + m_off = last_m_off; + else + { + m_off = 1 + (m_off << 6) + (*ip++ >> 2); + last_m_off = m_off; + } + t = (t >> 5) - 1; +#endif +#else +#if defined(LZO1X) + m_pos = op - 1; + m_pos -= (t >> 2) & 7; + m_pos -= *ip++ << 3; + t = (t >> 5) - 1; +#elif defined(LZO1Y) + m_pos = op - 1; + m_pos -= (t >> 2) & 3; + m_pos -= *ip++ << 2; + t = (t >> 4) - 3; +#elif defined(LZO1Z) + { + lzo_uint off = t & 0x1f; + m_pos = op; + if (off >= 0x1c) + { + assert(last_m_off > 0); + m_pos -= last_m_off; + } + else + { + off = 1 + (off << 6) + (*ip++ >> 2); + m_pos -= off; + last_m_off = off; + } + } + t = (t >> 5) - 1; +#endif + TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); + goto copy_match; +#endif + } + else if (t >= 32) + { + t &= 31; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_OV(t); + NEED_IP(1); + } + t += 31 + *ip++; + NEED_IP(2); + } +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = 1 + (ip[0] << 6) + (ip[1] >> 2); + last_m_off = m_off; +#else + m_off = 1 + (ip[0] >> 2) + (ip[1] << 6); +#endif +#else +#if defined(LZO1Z) + { + lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2); + m_pos = op - off; + last_m_off = off; + } +#elif (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) + m_pos = op - 1; + m_pos -= UA_GET_LE16(ip) >> 2; +#else + m_pos = op - 1; + m_pos -= (ip[0] >> 2) + (ip[1] << 6); +#endif +#endif + ip += 2; + } + else if (t >= 16) + { +#if defined(COPY_DICT) + m_off = (t & 8) << 11; +#else + m_pos = op; + m_pos -= (t & 8) << 11; +#endif + t &= 7; + if (t == 0) + { + while (*ip == 0) + { + t += 255; + ip++; + TEST_OV(t); + NEED_IP(1); + } + t += 7 + *ip++; + NEED_IP(2); + } +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off += (ip[0] << 6) + (ip[1] >> 2); +#else + m_off += (ip[0] >> 2) + (ip[1] << 6); +#endif + ip += 2; + if (m_off == 0) + goto eof_found; + m_off += 0x4000; +#if defined(LZO1Z) + last_m_off = m_off; +#endif +#else +#if defined(LZO1Z) + m_pos -= (ip[0] << 6) + (ip[1] >> 2); +#elif (LZO_OPT_UNALIGNED16) && (LZO_ABI_LITTLE_ENDIAN) + m_pos -= UA_GET_LE16(ip) >> 2; +#else + m_pos -= (ip[0] >> 2) + (ip[1] << 6); +#endif + ip += 2; + if (m_pos == op) + goto eof_found; + m_pos -= 0x4000; +#if defined(LZO1Z) + last_m_off = pd((const lzo_bytep)op, m_pos); +#endif +#endif + } + else + { +#if defined(COPY_DICT) +#if defined(LZO1Z) + m_off = 1 + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; +#else + m_off = 1 + (t >> 2) + (*ip++ << 2); +#endif + NEED_OP(2); + t = 2; COPY_DICT(t,m_off) +#else +#if defined(LZO1Z) + t = 1 + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; +#else + m_pos = op - 1; + m_pos -= t >> 2; + m_pos -= *ip++ << 2; +#endif + TEST_LB(m_pos); NEED_OP(2); + *op++ = *m_pos++; *op++ = *m_pos; +#endif + goto match_done; + } + +#if defined(COPY_DICT) + + NEED_OP(t+3-1); + t += 3-1; COPY_DICT(t,m_off) + +#else + + TEST_LB(m_pos); assert(t > 0); NEED_OP(t+3-1); +#if (LZO_OPT_UNALIGNED64) && (LZO_OPT_UNALIGNED32) + if (op - m_pos >= 8) + { + t += (3 - 1); + if (t >= 8) do + { + UA_COPY8(op,m_pos); + op += 8; m_pos += 8; t -= 8; + } while (t >= 8); + if (t >= 4) + { + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4; + } + if (t > 0) + { + *op++ = m_pos[0]; + if (t > 1) { *op++ = m_pos[1]; if (t > 2) { *op++ = m_pos[2]; } } + } + } + else +#elif (LZO_OPT_UNALIGNED32) || (LZO_ALIGNED_OK_4) +#if !(LZO_OPT_UNALIGNED32) + if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos)) + { + assert((op - m_pos) >= 4); +#else + if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4) + { +#endif + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4 - (3 - 1); + do { + UA_COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *m_pos++; while (--t > 0); + } + else +#endif + { +copy_match: + *op++ = *m_pos++; *op++ = *m_pos++; + do *op++ = *m_pos++; while (--t > 0); + } + +#endif + +match_done: +#if defined(LZO1Z) + t = ip[-1] & 3; +#else + t = ip[-2] & 3; +#endif + if (t == 0) + break; + +match_next: + assert(t > 0); assert(t < 4); NEED_OP(t); NEED_IP(t+3); +#if 0 + do *op++ = *ip++; while (--t > 0); +#else + *op++ = *ip++; + if (t > 1) { *op++ = *ip++; if (t > 2) { *op++ = *ip++; } } +#endif + t = *ip++; + } + } + +eof_found: + *out_len = pd(op, out); + return (ip == ip_end ? LZO_E_OK : + (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); + +#if defined(HAVE_NEED_IP) +input_overrun: + *out_len = pd(op, out); + return LZO_E_INPUT_OVERRUN; +#endif + +#if defined(HAVE_NEED_OP) +output_overrun: + *out_len = pd(op, out); + return LZO_E_OUTPUT_OVERRUN; +#endif + +#if defined(LZO_TEST_OVERRUN_LOOKBEHIND) +lookbehind_overrun: + *out_len = pd(op, out); + return LZO_E_LOOKBEHIND_OVERRUN; +#endif +} + +#endif + +/***** End of minilzo.c *****/ diff --git a/minilzo-2.10/minilzo.h b/minilzo-2.10/minilzo.h new file mode 100644 index 0000000..c1c2297 --- /dev/null +++ b/minilzo-2.10/minilzo.h @@ -0,0 +1,106 @@ +/* minilzo.h -- mini subset of the LZO real-time data compression library + + This file is part of the LZO real-time data compression library. + + Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer + All Rights Reserved. + + The LZO library is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of + the License, or (at your option) any later version. + + The LZO library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the LZO library; see the file COPYING. + If not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Markus F.X.J. Oberhumer + + http://www.oberhumer.com/opensource/lzo/ + */ + +/* + * NOTE: + * the full LZO package can be found at + * http://www.oberhumer.com/opensource/lzo/ + */ + + +#ifndef __MINILZO_H_INCLUDED +#define __MINILZO_H_INCLUDED 1 + +#define MINILZO_VERSION 0x20a0 /* 2.10 */ + +#if defined(__LZOCONF_H_INCLUDED) +# error "you cannot use both LZO and miniLZO" +#endif + +/* internal Autoconf configuration file - only used when building miniLZO */ +#ifdef MINILZO_HAVE_CONFIG_H +# include +#endif +#include +#include + +#ifndef __LZODEFS_H_INCLUDED +#include "lzodefs.h" +#endif +#undef LZO_HAVE_CONFIG_H +#include "lzoconf.h" + +#if !defined(LZO_VERSION) || (LZO_VERSION != MINILZO_VERSION) +# error "version mismatch in header files" +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + +/*********************************************************************** +// +************************************************************************/ + +/* Memory required for the wrkmem parameter. + * When the required size is 0, you can also pass a NULL pointer. + */ + +#define LZO1X_MEM_COMPRESS LZO1X_1_MEM_COMPRESS +#define LZO1X_1_MEM_COMPRESS ((lzo_uint32_t) (16384L * lzo_sizeof_dict_t)) +#define LZO1X_MEM_DECOMPRESS (0) + + +/* compression */ +LZO_EXTERN(int) +lzo1x_1_compress ( const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem ); + +/* decompression */ +LZO_EXTERN(int) +lzo1x_decompress ( const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem /* NOT USED */ ); + +/* safe decompression with overrun testing */ +LZO_EXTERN(int) +lzo1x_decompress_safe ( const lzo_bytep src, lzo_uint src_len, + lzo_bytep dst, lzo_uintp dst_len, + lzo_voidp wrkmem /* NOT USED */ ); + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* already included */ + + +/* vim:set ts=4 sw=4 et: */ diff --git a/mqttclient/SH_MqttClient.cpp b/mqttclient/SH_MqttClient.cpp new file mode 100644 index 0000000..3a24cc4 --- /dev/null +++ b/mqttclient/SH_MqttClient.cpp @@ -0,0 +1,375 @@ +#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 || \ + strTopic.find("configureInfo") != 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); + //char *base64_data = new char[pData.length() * 2]; + //memset(base64_data, 0, pData.length() *2); + //Secure::instance()->Base64Decode(base64_aes, (unsigned char*)base64_data); + //std::string pData = std::string(base64_data); + if(base64_aes != NULL) + delete[] base64_aes; + // free(out); + } else { + iRet = mosquitto_publish(mosq, &mid_sent, topic, strlen(str), str, ud.topic_qos, false); + } + + } + if(iRet != 0) + { + disconnect(); + } + 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 reconnect() +{ + return mosquitto_reconnect(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) { + print_info("please call the register_collback function first.\n"); + return -1; + } + + int qos = readIntValue( "config", "qos",(char*)GlobalConfig::Config_G.c_str()); + 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; +#ifdef WIFI_MODULE + mqttsdata.qos = 0; +#else + mqttsdata.qos = qos; +#endif + print_info("mqttsdata.qos = %d\n",mqttsdata.qos); + // std::string username = "root"; + // std::string password = "xom!*283#@XHG"; + + std::string username = ReadStrByOpt(SERVERCONFIG, "Server", "UserName"); + std::string password = ReadStrByOpt(SERVERCONFIG, "Server", "Password"); + if(username == "" || password == ""){ + username = "chaos"; + password = "HSD272*#xkd"; + } + + char userName[100]; + sprintf(userName, "%s", username.c_str()); + + char passWord[100]; + sprintf(passWord, "%s", password.c_str()); + print_info("userName = %s , passWord = %s\n",userName,passWord); + ud.username = userName; + ud.password = passWord; + + ud.gwid = mqttsdata.gwid; + ud.dataUrl = mqttsdata.dataUrl; + ud.fsUrl = mqttsdata.fsUrl; + will_qos = mqttsdata.qos; + ud.topic_qos = will_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"); + print_info("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); + print_info("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/%s-%s", GlobalConfig::ZigbeeInfo_G.PanID.c_str(), hostname); + if (strlen(id) > MOSQ_MQTT_ID_MAX_LENGTH){ + /* Enforce maximum client id length of 23 characters */ + id[MOSQ_MQTT_ID_MAX_LENGTH] = '\0'; + } + } + print_info("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); + } + print_info("host = %s port = %d rc = %d\n",host,port,rc); + if (rc){ + if (!ud.quiet){ + if (rc == MOSQ_ERR_ERRNO){ + //strerror_r(errno, err, 1024); + //fprintf(stderr, "Error_: %s\n", err); + //print_info("%s",stderr); + } + else{ + fprintf(stderr, "Unable to connect (%d).\n", rc); + print_info("%s",stderr); + } + } + goto mosq_free; + } + rc = mosquitto_loop_forever(mosq, -1, 1); + if (rc) + { + fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc)); + print_info("%s",stderr); + } +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..d080fc9 --- /dev/null +++ b/mqttclient/SH_MqttClient.h @@ -0,0 +1,71 @@ +#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 reconnect(); +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..5633b40 --- /dev/null +++ b/mqttclient/mosquitto.h @@ -0,0 +1,3271 @@ +/* +Copyright (c) 2010-2020 Roger Light + +All rights reserved. This program and the accompanying materials +are made available under the terms of the Eclipse Public License 2.0 +and Eclipse Distribution License v1.0 which accompany this distribution. + +The Eclipse Public License is available at + https://www.eclipse.org/legal/epl-2.0/ +and the Eclipse Distribution License is available at + http://www.eclipse.org/org/documents/edl-v10.php. + +SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause + +Contributors: + Roger Light - initial implementation and documentation. +*/ + +#ifndef MOSQUITTO_H +#define MOSQUITTO_H + +/* + * File: mosquitto.h + * + * This header contains functions and definitions for use with libmosquitto, the Mosquitto client library. + * + * The definitions are also used in Mosquitto broker plugins, and some functions are available to plugins. + */ +#ifdef __cplusplus +extern "C" { +#endif + + +#ifdef WIN32 +# ifdef mosquitto_EXPORTS +# define libmosq_EXPORT __declspec(dllexport) +# else +# ifndef LIBMOSQUITTO_STATIC +# ifdef libmosquitto_EXPORTS +# define libmosq_EXPORT __declspec(dllexport) +# else +# define libmosq_EXPORT __declspec(dllimport) +# endif +# else +# define libmosq_EXPORT +# endif +# endif +#else +# define libmosq_EXPORT +#endif + +#if defined(_MSC_VER) && _MSC_VER < 1900 && !defined(bool) +# ifndef __cplusplus +# define bool char +# define true 1 +# define false 0 +# endif +#else +# ifndef __cplusplus +# include +# endif +#endif + +#include +#include + +#define LIBMOSQUITTO_MAJOR 2 +#define LIBMOSQUITTO_MINOR 0 +#define LIBMOSQUITTO_REVISION 18 +/* 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 0 +#define MOSQ_LOG_INFO (1<<0) +#define MOSQ_LOG_NOTICE (1<<1) +#define MOSQ_LOG_WARNING (1<<2) +#define MOSQ_LOG_ERR (1<<3) +#define MOSQ_LOG_DEBUG (1<<4) +#define MOSQ_LOG_SUBSCRIBE (1<<5) +#define MOSQ_LOG_UNSUBSCRIBE (1<<6) +#define MOSQ_LOG_WEBSOCKETS (1<<7) +#define MOSQ_LOG_INTERNAL 0x80000000U +#define MOSQ_LOG_ALL 0xFFFFFFFFU + +/* Enum: mosq_err_t + * Integer values returned from many libmosquitto functions. */ +enum mosq_err_t { + MOSQ_ERR_AUTH_CONTINUE = -4, + MOSQ_ERR_NO_SUBSCRIBERS = -3, + MOSQ_ERR_SUB_EXISTS = -2, + 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, + MOSQ_ERR_PLUGIN_DEFER = 17, + MOSQ_ERR_MALFORMED_UTF8 = 18, + MOSQ_ERR_KEEPALIVE = 19, + MOSQ_ERR_LOOKUP = 20, + MOSQ_ERR_MALFORMED_PACKET = 21, + MOSQ_ERR_DUPLICATE_PROPERTY = 22, + MOSQ_ERR_TLS_HANDSHAKE = 23, + MOSQ_ERR_QOS_NOT_SUPPORTED = 24, + MOSQ_ERR_OVERSIZE_PACKET = 25, + MOSQ_ERR_OCSP = 26, + MOSQ_ERR_TIMEOUT = 27, + MOSQ_ERR_RETAIN_NOT_SUPPORTED = 28, + MOSQ_ERR_TOPIC_ALIAS_INVALID = 29, + MOSQ_ERR_ADMINISTRATIVE_ACTION = 30, + MOSQ_ERR_ALREADY_EXISTS = 31, +}; + +/* Enum: mosq_opt_t + * + * Client options. + * + * See , , and . + */ +enum mosq_opt_t { + MOSQ_OPT_PROTOCOL_VERSION = 1, + MOSQ_OPT_SSL_CTX = 2, + MOSQ_OPT_SSL_CTX_WITH_DEFAULTS = 3, + MOSQ_OPT_RECEIVE_MAXIMUM = 4, + MOSQ_OPT_SEND_MAXIMUM = 5, + MOSQ_OPT_TLS_KEYFORM = 6, + MOSQ_OPT_TLS_ENGINE = 7, + MOSQ_OPT_TLS_ENGINE_KPASS_SHA1 = 8, + MOSQ_OPT_TLS_OCSP_REQUIRED = 9, + MOSQ_OPT_TLS_ALPN = 10, + MOSQ_OPT_TCP_NODELAY = 11, + MOSQ_OPT_BIND_ADDRESS = 12, + MOSQ_OPT_TLS_USE_OS_CERTS = 13, +}; + + +/* 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 +#define MQTT_PROTOCOL_V5 5 + +/* Struct: mosquitto_message + * + * Contains details of a PUBLISH message. + * + * int mid - the message/packet ID of the PUBLISH message, assuming this is a + * QoS 1 or 2 message. Will be set to 0 for QoS 0 messages. + * + * char *topic - the topic the message was delivered on. + * + * void *payload - the message payload. This will be payloadlen bytes long, and + * may be NULL if a zero length payload was sent. + * + * int payloadlen - the length of the payload, in bytes. + * + * int qos - the quality of service of the message, 0, 1, or 2. + * + * bool retain - set to true for stale retained messages. + */ +struct mosquitto_message{ + int mid; + char *topic; + void *payload; + int payloadlen; + int qos; + bool retain; +}; + +struct mosquitto; +typedef struct mqtt5__property mosquitto_property; + +/* + * Topic: Threads + * libmosquitto provides thread safe operation, with the exception of + * which is not thread safe. + * + * If the library has been compiled without thread support it is *not* + * guaranteed to be 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() + ***************************************************/ + + +/* ====================================================================== + * + * Section: Library version, init, and cleanup + * + * ====================================================================== */ +/* + * 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 - on success. + * MOSQ_ERR_UNKNOWN - on Windows, if sockets couldn't be initialized. + * + * 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); + + +/* ====================================================================== + * + * Section: Client creation, destruction, and reinitialisation + * + * ====================================================================== */ +/* + * 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. + * MOSQ_ERR_MALFORMED_UTF8 - if the client id is not valid UTF-8. + * + * See Also: + * , + */ +libmosq_EXPORT int mosquitto_reinitialise(struct mosquitto *mosq, const char *id, bool clean_session, void *obj); + + +/* ====================================================================== + * + * Section: Will + * + * ====================================================================== */ +/* + * 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 . + * + * It is valid to use this function for clients using all MQTT protocol versions. + * If you need to set MQTT v5 Will properties, use instead. + * + * 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. + * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8. + */ +libmosq_EXPORT int mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain); + +/* + * Function: mosquitto_will_set_v5 + * + * Configure will information for a mosquitto instance, with attached + * properties. By default, clients do not have a will. This must be called + * before calling . + * + * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument + * will be applied to the Will. For MQTT v3.1.1 and below, the `properties` + * argument will be ignored. + * + * Set your client to use MQTT v5 immediately after it is created: + * + * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); + * + * 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. + * properties - list of MQTT 5 properties. Can be NULL. On success only, the + * property list becomes the property of libmosquitto once this + * function is called and will be freed by the library. The + * property list must be freed by the application on error. + * + * 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. + * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8. + * MOSQ_ERR_NOT_SUPPORTED - if properties is not NULL and the client is not + * using MQTT v5 + * MOSQ_ERR_PROTOCOL - if a property is invalid for use with wills. + * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. + */ +libmosq_EXPORT int mosquitto_will_set_v5(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties); + +/* + * 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); + + +/* ====================================================================== + * + * Section: Username and password + * + * ====================================================================== */ +/* + * Function: mosquitto_username_pw_set + * + * Configure username and password for a mosquitto instance. By default, no + * username or password will be sent. For v3.1 and v3.1.1 clients, if username + * is NULL, the password argument is ignored. + * + * 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); + + +/* ====================================================================== + * + * Section: Connecting, reconnecting, disconnecting + * + * ====================================================================== */ +/* + * Function: mosquitto_connect + * + * Connect to an MQTT broker. + * + * It is valid to use this function for clients using all MQTT protocol versions. + * If you need to set MQTT v5 CONNECT properties, use + * instead. + * + * 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 client should send a PING + * message to the broker 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, which could be any of: + * * mosq == NULL + * * host == NULL + * * port < 0 + * * keepalive < 5 + * 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 client should send a PING + * message to the broker 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. If you do not want to bind to a specific interface, + * set this to NULL. + * + * 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_bind_v5 + * + * Connect to an MQTT broker. This extends the functionality of + * by adding the bind_address parameter and MQTT v5 + * properties. Use this function if you need to restrict network communication + * over a particular interface. + * + * Use e.g. and similar to create a list of + * properties, then attach them to this publish. Properties need freeing with + * . + * + * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument + * will be applied to the CONNECT message. For MQTT v3.1.1 and below, the + * `properties` argument will be ignored. + * + * Set your client to use MQTT v5 immediately after it is created: + * + * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); + * + * 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 client should send a PING + * message to the broker 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. If you do not want to bind to a specific interface, + * set this to NULL. + * properties - the MQTT 5 properties for the connect (not for the Will). + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid, which could be any of: + * * mosq == NULL + * * host == NULL + * * port < 0 + * * keepalive < 5 + * 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. + * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. + * MOSQ_ERR_PROTOCOL - if any property is invalid for use with CONNECT. + * + * See Also: + * , , + */ +libmosq_EXPORT int mosquitto_connect_bind_v5(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address, const mosquitto_property *properties); + +/* + * 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 client should send a PING + * message to the broker 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 client should send a PING + * message to the broker 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. If you do not want to bind to a specific interface, + * set this to NULL. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid, which could be any of: + * * mosq == NULL + * * host == NULL + * * port < 0 + * * keepalive < 5 + * 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. + * + * If you set `host` to `example.com`, then this call will attempt to retrieve + * the DNS SRV record for `_secure-mqtt._tcp.example.com` or + * `_mqtt._tcp.example.com` to discover which actual host to connect to. + * + * DNS SRV support is not usually compiled in to libmosquitto, use of this call + * is not recommended. + * + * Parameters: + * mosq - a valid mosquitto instance. + * host - the hostname to search for an SRV record. + * keepalive - the number of seconds after which the client should send a PING + * message to the broker 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. If you do not want to bind to a specific interface, + * set this to NULL. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success. + * MOSQ_ERR_INVAL - if the input parameters were invalid, which could be any of: + * * mosq == NULL + * * host == NULL + * * port < 0 + * * keepalive < 5 + * 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. + * 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. + * 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. + * + * It is valid to use this function for clients using all MQTT protocol versions. + * If you need to set MQTT v5 DISCONNECT properties, use + * instead. + * + * 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_disconnect_v5 + * + * Disconnect from the broker, with attached MQTT properties. + * + * Use e.g. and similar to create a list of + * properties, then attach them to this publish. Properties need freeing with + * . + * + * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument + * will be applied to the DISCONNECT message. For MQTT v3.1.1 and below, the + * `properties` argument will be ignored. + * + * Set your client to use MQTT v5 immediately after it is created: + * + * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); + * + * Parameters: + * mosq - a valid mosquitto instance. + * reason_code - the disconnect reason code. + * properties - a valid mosquitto_property list, or NULL. + * + * 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. + * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. + * MOSQ_ERR_PROTOCOL - if any property is invalid for use with DISCONNECT. + */ +libmosq_EXPORT int mosquitto_disconnect_v5(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties); + + +/* ====================================================================== + * + * Section: Publishing, subscribing, unsubscribing + * + * ====================================================================== */ +/* + * Function: mosquitto_publish + * + * Publish a message on a given topic. + * + * It is valid to use this function for clients using all MQTT protocol versions. + * If you need to set MQTT v5 PUBLISH properties, use + * instead. + * + * 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. + * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 + * MOSQ_ERR_QOS_NOT_SUPPORTED - if the QoS is greater than that supported by + * the broker. + * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than + * supported by the broker. + * + * 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_publish_v5 + * + * Publish a message on a given topic, with attached MQTT properties. + * + * Use e.g. and similar to create a list of + * properties, then attach them to this publish. Properties need freeing with + * . + * + * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument + * will be applied to the PUBLISH message. For MQTT v3.1.1 and below, the + * `properties` argument will be ignored. + * + * Set your client to use MQTT v5 immediately after it is created: + * + * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); + * + * 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. + * properties - a valid mosquitto_property list, or NULL. + * + * 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. + * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 + * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. + * MOSQ_ERR_PROTOCOL - if any property is invalid for use with PUBLISH. + * MOSQ_ERR_QOS_NOT_SUPPORTED - if the QoS is greater than that supported by + * the broker. + * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than + * supported by the broker. + */ +libmosq_EXPORT int mosquitto_publish_v5( + struct mosquitto *mosq, + int *mid, + const char *topic, + int payloadlen, + const void *payload, + int qos, + bool retain, + const mosquitto_property *properties); + + +/* + * Function: mosquitto_subscribe + * + * Subscribe to a topic. + * + * It is valid to use this function for clients using all MQTT protocol versions. + * If you need to set MQTT v5 SUBSCRIBE properties, use + * instead. + * + * 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. + * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 + * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than + * supported by the broker. + */ +libmosq_EXPORT int mosquitto_subscribe(struct mosquitto *mosq, int *mid, const char *sub, int qos); + +/* + * Function: mosquitto_subscribe_v5 + * + * Subscribe to a topic, with attached MQTT properties. + * + * Use e.g. and similar to create a list of + * properties, then attach them to this publish. Properties need freeing with + * . + * + * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument + * will be applied to the PUBLISH message. For MQTT v3.1.1 and below, the + * `properties` argument will be ignored. + * + * Set your client to use MQTT v5 immediately after it is created: + * + * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); + * + * 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. + * options - options to apply to this subscription, OR'd together. Set to 0 to + * use the default options, otherwise choose from list of + * properties - a valid mosquitto_property list, or NULL. + * + * 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_MALFORMED_UTF8 - if the topic is not valid UTF-8 + * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. + * MOSQ_ERR_PROTOCOL - if any property is invalid for use with SUBSCRIBE. + * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than + * supported by the broker. + */ +libmosq_EXPORT int mosquitto_subscribe_v5(struct mosquitto *mosq, int *mid, const char *sub, int qos, int options, const mosquitto_property *properties); + +/* + * Function: mosquitto_subscribe_multiple + * + * Subscribe to multiple topics. + * + * 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_count - the count of subscriptions to be made + * sub - array of sub_count pointers, each pointing to a subscription string. + * The "char *const *const" datatype ensures that neither the array of + * pointers nor the strings that they point to are mutable. If you aren't + * familiar with this, just think of it as a safer "char **", + * equivalent to "const char *" for a simple string pointer. + * qos - the requested Quality of Service for each subscription. + * options - options to apply to this subscription, OR'd together. This + * argument is not used for MQTT v3 susbcriptions. Set to 0 to use + * the default options, otherwise choose from list of + * properties - a valid mosquitto_property list, or NULL. Only used with MQTT + * v5 clients. + * + * 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_MALFORMED_UTF8 - if a topic is not valid UTF-8 + * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than + * supported by the broker. + */ +libmosq_EXPORT int mosquitto_subscribe_multiple(struct mosquitto *mosq, int *mid, int sub_count, char *const *const sub, int qos, int options, const mosquitto_property *properties); + +/* + * 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. + * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 + * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than + * supported by the broker. + */ +libmosq_EXPORT int mosquitto_unsubscribe(struct mosquitto *mosq, int *mid, const char *sub); + +/* + * Function: mosquitto_unsubscribe_v5 + * + * Unsubscribe from a topic, with attached MQTT properties. + * + * It is valid to use this function for clients using all MQTT protocol versions. + * If you need to set MQTT v5 UNSUBSCRIBE properties, use + * instead. + * + * Use e.g. and similar to create a list of + * properties, then attach them to this publish. Properties need freeing with + * . + * + * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument + * will be applied to the PUBLISH message. For MQTT v3.1.1 and below, the + * `properties` argument will be ignored. + * + * Set your client to use MQTT v5 immediately after it is created: + * + * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); + * + * 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. + * properties - a valid mosquitto_property list, or NULL. Only used with MQTT + * v5 clients. + * + * 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_MALFORMED_UTF8 - if the topic is not valid UTF-8 + * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. + * MOSQ_ERR_PROTOCOL - if any property is invalid for use with UNSUBSCRIBE. + * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than + * supported by the broker. + */ +libmosq_EXPORT int mosquitto_unsubscribe_v5(struct mosquitto *mosq, int *mid, const char *sub, const mosquitto_property *properties); + +/* + * Function: mosquitto_unsubscribe_multiple + * + * Unsubscribe from multiple topics. + * + * 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_count - the count of unsubscriptions to be made + * sub - array of sub_count pointers, each pointing to an unsubscription string. + * The "char *const *const" datatype ensures that neither the array of + * pointers nor the strings that they point to are mutable. If you aren't + * familiar with this, just think of it as a safer "char **", + * equivalent to "const char *" for a simple string pointer. + * properties - a valid mosquitto_property list, or NULL. Only used with MQTT + * v5 clients. + * + * 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_MALFORMED_UTF8 - if a topic is not valid UTF-8 + * MOSQ_ERR_OVERSIZE_PACKET - if the resulting packet would be larger than + * supported by the broker. + */ +libmosq_EXPORT int mosquitto_unsubscribe_multiple(struct mosquitto *mosq, int *mid, int sub_count, char *const *const sub, const mosquitto_property *properties); + + +/* ====================================================================== + * + * Section: Struct mosquitto_message helper functions + * + * ====================================================================== */ +/* + * 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_message_free_contents + * + * Free a mosquitto_message struct contents, leaving the struct unaffected. + * + * Parameters: + * message - pointer to a mosquitto_message struct to free its contents. + * + * See Also: + * , + */ +libmosq_EXPORT void mosquitto_message_free_contents(struct mosquitto_message *message); + + +/* ====================================================================== + * + * Section: Network loop (managed by libmosquitto) + * + * The internal network loop must be called at a regular interval. The two + * recommended approaches are to use either or + * . is a blocking call and is + * suitable for the situation where you only want to handle incoming messages + * in callbacks. is a non-blocking call, it creates a + * separate thread to run the loop for you. Use this function when you have + * other tasks you need to run at the same time as the MQTT client, e.g. + * reading data from a sensor. + * + * ====================================================================== */ + +/* + * 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_loop + * + * The main network loop for the client. This must be called frequently + * to keep communications between the client and broker working. This is + * carried out by and , which + * are the recommended ways of handling the network loop. You may also use this + * function if you wish. It must not be called inside a callback. + * + * 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. + * + * 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); + +/* ====================================================================== + * + * Section: Network loop (for use in other event loops) + * + * ====================================================================== */ +/* + * 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, around once per second + * is sufficient. + * + * 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); + + +/* ====================================================================== + * + * Section: Network loop (helper functions) + * + * ====================================================================== */ +/* + * 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_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); + + +/* ====================================================================== + * + * Section: Client options + * + * ====================================================================== */ +/* + * Function: mosquitto_opts_set + * + * Used to set options for the client. + * + * This function is deprecated, the replacement , + * and functions should + * be used instead. + * + * 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. + * + * MOSQ_OPT_SSL_CTX - Pass an openssl SSL_CTX to be used when creating + * TLS connections rather than libmosquitto creating its own. + * This must be called before connecting to have any effect. + * If you use this option, the onus is on you to ensure that + * you are using secure settings. + * Setting to NULL means that libmosquitto will use its own SSL_CTX + * if TLS is to be used. + * This option is only available for openssl 1.1.0 and higher. + * + * MOSQ_OPT_SSL_CTX_WITH_DEFAULTS - Value must be an int set to 1 or 0. + * If set to 1, then the user specified SSL_CTX passed in using + * MOSQ_OPT_SSL_CTX will have the default options applied to it. + * This means that you only need to change the values that are + * relevant to you. If you use this option then you must configure + * the TLS options as normal, i.e. you should use + * to configure the cafile/capath as a minimum. + * This option is only available for openssl 1.1.0 and higher. + */ +libmosq_EXPORT int mosquitto_opts_set(struct mosquitto *mosq, enum mosq_opt_t option, void *value); + +/* + * Function: mosquitto_int_option + * + * Used to set integer options for the client. + * + * Parameters: + * mosq - a valid mosquitto instance. + * option - the option to set. + * value - the option specific value. + * + * Options: + * MOSQ_OPT_TCP_NODELAY - Set to 1 to disable Nagle's algorithm on client + * sockets. This has the effect of reducing latency of individual + * messages at the potential cost of increasing the number of + * packets being sent. + * Defaults to 0, which means Nagle remains enabled. + * + * MOSQ_OPT_PROTOCOL_VERSION - Value must be set to either MQTT_PROTOCOL_V31, + * MQTT_PROTOCOL_V311, or MQTT_PROTOCOL_V5. Must be set before the + * client connects. Defaults to MQTT_PROTOCOL_V311. + * + * MOSQ_OPT_RECEIVE_MAXIMUM - Value can be set between 1 and 65535 inclusive, + * and represents the maximum number of incoming QoS 1 and QoS 2 + * messages that this client wants to process at once. Defaults to + * 20. This option is not valid for MQTT v3.1 or v3.1.1 clients. + * Note that if the MQTT_PROP_RECEIVE_MAXIMUM property is in the + * proplist passed to mosquitto_connect_v5(), then that property + * will override this option. Using this option is the recommended + * method however. + * + * MOSQ_OPT_SEND_MAXIMUM - Value can be set between 1 and 65535 inclusive, + * and represents the maximum number of outgoing QoS 1 and QoS 2 + * messages that this client will attempt to have "in flight" at + * once. Defaults to 20. + * This option is not valid for MQTT v3.1 or v3.1.1 clients. + * Note that if the broker being connected to sends a + * MQTT_PROP_RECEIVE_MAXIMUM property that has a lower value than + * this option, then the broker provided value will be used. + * + * MOSQ_OPT_SSL_CTX_WITH_DEFAULTS - If value is set to a non zero value, + * then the user specified SSL_CTX passed in using MOSQ_OPT_SSL_CTX + * will have the default options applied to it. This means that + * you only need to change the values that are relevant to you. + * If you use this option then you must configure the TLS options + * as normal, i.e. you should use to + * configure the cafile/capath as a minimum. + * This option is only available for openssl 1.1.0 and higher. + * + * MOSQ_OPT_TLS_OCSP_REQUIRED - Set whether OCSP checking on TLS + * connections is required. Set to 1 to enable checking, + * or 0 (the default) for no checking. + * + * MOSQ_OPT_TLS_USE_OS_CERTS - Set to 1 to instruct the client to load and + * trust OS provided CA certificates for use with TLS connections. + * Set to 0 (the default) to only use manually specified CA certs. + */ +libmosq_EXPORT int mosquitto_int_option(struct mosquitto *mosq, enum mosq_opt_t option, int value); + + +/* + * Function: mosquitto_string_option + * + * Used to set const char* options for the client. + * + * Parameters: + * mosq - a valid mosquitto instance. + * option - the option to set. + * value - the option specific value. + * + * Options: + * MOSQ_OPT_TLS_ENGINE - Configure the client for TLS Engine support. + * Pass a TLS Engine ID to be used when creating TLS + * connections. Must be set before . + * Must be a valid engine, and note that the string will not be used + * until a connection attempt is made so this function will return + * success even if an invalid engine string is passed. + * + * MOSQ_OPT_TLS_KEYFORM - Configure the client to treat the keyfile + * differently depending on its type. Must be set + * before . + * Set as either "pem" or "engine", to determine from where the + * private key for a TLS connection will be obtained. Defaults to + * "pem", a normal private key file. + * + * MOSQ_OPT_TLS_KPASS_SHA1 - Where the TLS Engine requires the use of + * a password to be accessed, this option allows a hex encoded + * SHA1 hash of the private key password to be passed to the + * engine directly. Must be set before . + * + * MOSQ_OPT_TLS_ALPN - If the broker being connected to has multiple + * services available on a single TLS port, such as both MQTT + * and WebSockets, use this option to configure the ALPN + * option for the connection. + * + * MOSQ_OPT_BIND_ADDRESS - Set the hostname or ip address of the local network + * interface to bind to when connecting. + */ +libmosq_EXPORT int mosquitto_string_option(struct mosquitto *mosq, enum mosq_opt_t option, const char *value); + + +/* + * Function: mosquitto_void_option + * + * Used to set void* options for the client. + * + * Parameters: + * mosq - a valid mosquitto instance. + * option - the option to set. + * value - the option specific value. + * + * Options: + * MOSQ_OPT_SSL_CTX - Pass an openssl SSL_CTX to be used when creating TLS + * connections rather than libmosquitto creating its own. This must + * be called before connecting to have any effect. If you use this + * option, the onus is on you to ensure that you are using secure + * settings. + * Setting to NULL means that libmosquitto will use its own SSL_CTX + * if TLS is to be used. + * This option is only available for openssl 1.1.0 and higher. + */ +libmosq_EXPORT int mosquitto_void_option(struct mosquitto *mosq, enum mosq_opt_t option, void *value); + +/* + * 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 + * + * This function is deprected. Use the function with the + * MOSQ_OPT_SEND_MAXIMUM option instead. + * + * 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 + * + * This function now has no effect. + */ +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); + +/* Function: mosquitto_userdata + * + * Retrieve the "userdata" variable for a mosquitto client. + * + * Parameters: + * mosq - a valid mosquitto instance. + * + * Returns: + * A pointer to the userdata member variable. + */ +libmosq_EXPORT void *mosquitto_userdata(struct mosquitto *mosq); + + +/* ====================================================================== + * + * Section: TLS support + * + * ====================================================================== */ +/* + * 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. The mosquitto userdata member variable can be + * retrieved using . + * + * 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_ssl_get + * + * Retrieve a pointer to the SSL structure used for TLS connections in this + * client. This can be used in e.g. the connect callback to carry out + * additional verification steps. + * + * Parameters: + * mosq - a valid mosquitto instance + * + * Returns: + * A valid pointer to an openssl SSL structure - if the client is using TLS. + * NULL - if the client is not using TLS, or TLS support is not compiled in. + */ +libmosq_EXPORT void *mosquitto_ssl_get(struct mosquitto *mosq); + + +/* ====================================================================== + * + * Section: Callbacks + * + * ====================================================================== */ +/* + * Function: mosquitto_connect_callback_set + * + * Set the connect callback. This is called when the library receives 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. The values are defined by + * the MQTT protocol version in use. + * For MQTT v5.0, look at section 3.2.2.2 Connect Reason code: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html + * For MQTT v3.1.1, look at section 3.2.2.3 Connect Return code: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html + */ +libmosq_EXPORT void mosquitto_connect_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int)); + +/* + * Function: mosquitto_connect_with_flags_callback_set + * + * Set the connect callback. This is called when the library receives 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. The values are defined by + * the MQTT protocol version in use. + * For MQTT v5.0, look at section 3.2.2.2 Connect Reason code: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html + * For MQTT v3.1.1, look at section 3.2.2.3 Connect Return code: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html + * flags - the connect flags. + */ +libmosq_EXPORT void mosquitto_connect_with_flags_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int, int)); + +/* + * Function: mosquitto_connect_v5_callback_set + * + * Set the connect callback. This is called when the library receives a CONNACK + * message in response to a connection. + * + * It is valid to set this callback for all MQTT protocol versions. If it is + * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` + * argument will always be NULL. + * + * 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. The values are defined by + * the MQTT protocol version in use. + * For MQTT v5.0, look at section 3.2.2.2 Connect Reason code: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html + * For MQTT v3.1.1, look at section 3.2.2.3 Connect Return code: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html + * flags - the connect flags. + * props - list of MQTT 5 properties, or NULL + * + */ +libmosq_EXPORT void mosquitto_connect_v5_callback_set(struct mosquitto *mosq, void (*on_connect)(struct mosquitto *, void *, int, int, const mosquitto_property *props)); + +/* + * 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_disconnect_v5_callback_set + * + * Set the disconnect callback. This is called when the broker has received the + * DISCONNECT command and has disconnected the client. + * + * It is valid to set this callback for all MQTT protocol versions. If it is + * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` + * argument will always be NULL. + * + * 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. + * props - list of MQTT 5 properties, or NULL + */ +libmosq_EXPORT void mosquitto_disconnect_v5_callback_set(struct mosquitto *mosq, void (*on_disconnect)(struct mosquitto *, void *, int, const mosquitto_property *props)); + +/* + * Function: mosquitto_publish_callback_set + * + * Set the publish callback. This is called when a message initiated with + * has been sent to the broker. "Sent" means different + * things depending on the QoS of the message: + * + * QoS 0: The PUBLISH was passed to the local operating system for delivery, + * there is no guarantee that it was delivered to the remote broker. + * QoS 1: The PUBLISH was sent to the remote broker and the corresponding + * PUBACK was received by the library. + * QoS 2: The PUBLISH was sent to the remote broker and the corresponding + * PUBCOMP was received by the library. + * + * 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_publish_v5_callback_set + * + * Set the publish callback. This is called when a message initiated with + * has been sent to the broker. This callback will be + * called both if the message is sent successfully, or if the broker responded + * with an error, which will be reflected in the reason_code parameter. + * "Sent" means different things depending on the QoS of the message: + * + * QoS 0: The PUBLISH was passed to the local operating system for delivery, + * there is no guarantee that it was delivered to the remote broker. + * QoS 1: The PUBLISH was sent to the remote broker and the corresponding + * PUBACK was received by the library. + * QoS 2: The PUBLISH was sent to the remote broker and the corresponding + * PUBCOMP was received by the library. + * + * + * It is valid to set this callback for all MQTT protocol versions. If it is + * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` + * argument will always be NULL. + * + * 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. + * reason_code - the MQTT 5 reason code + * props - list of MQTT 5 properties, or NULL + */ +libmosq_EXPORT void mosquitto_publish_v5_callback_set(struct mosquitto *mosq, void (*on_publish)(struct mosquitto *, void *, int, int, const mosquitto_property *props)); + +/* + * Function: mosquitto_message_callback_set + * + * Set the message callback. This is called when a message is received from the + * broker and the required QoS flow has completed. + * + * 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_message_v5_callback_set + * + * Set the message callback. This is called when a message is received from the + * broker and the required QoS flow has completed. + * + * It is valid to set this callback for all MQTT protocol versions. If it is + * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` + * argument will always be NULL. + * + * 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. + * props - list of MQTT 5 properties, or NULL + * + * See Also: + * + */ +libmosq_EXPORT void mosquitto_message_v5_callback_set(struct mosquitto *mosq, void (*on_message)(struct mosquitto *, void *, const struct mosquitto_message *, const mosquitto_property *props)); + +/* + * Function: mosquitto_subscribe_callback_set + * + * Set the subscribe callback. This is called when the library receives a + * SUBACK message in response to a SUBSCRIBE. + * + * 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_subscribe_v5_callback_set + * + * Set the subscribe callback. This is called when the library receives a + * SUBACK message in response to a SUBSCRIBE. + * + * It is valid to set this callback for all MQTT protocol versions. If it is + * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` + * argument will always be NULL. + * + * 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. + * props - list of MQTT 5 properties, or NULL + */ +libmosq_EXPORT void mosquitto_subscribe_v5_callback_set(struct mosquitto *mosq, void (*on_subscribe)(struct mosquitto *, void *, int, int, const int *, const mosquitto_property *props)); + +/* + * Function: mosquitto_unsubscribe_callback_set + * + * Set the unsubscribe callback. This is called when the library receives a + * UNSUBACK message in response to an UNSUBSCRIBE. + * + * 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_unsubscribe_v5_callback_set + * + * Set the unsubscribe callback. This is called when the library receives a + * UNSUBACK message in response to an UNSUBSCRIBE. + * + * It is valid to set this callback for all MQTT protocol versions. If it is + * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` + * argument will always be NULL. + * + * 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. + * props - list of MQTT 5 properties, or NULL + */ +libmosq_EXPORT void mosquitto_unsubscribe_v5_callback_set(struct mosquitto *mosq, void (*on_unsubscribe)(struct mosquitto *, void *, int, const mosquitto_property *props)); + +/* + * 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 *)); + + +/* ============================================================================= + * + * 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_reason_string + * + * Call to obtain a const string description of an MQTT reason code. + * + * Parameters: + * reason_code - an MQTT reason code. + * + * Returns: + * A constant string describing the reason. + */ +libmosq_EXPORT const char *mosquitto_reason_string(int reason_code); + +/* Function: mosquitto_string_to_command + * + * Take a string input representing an MQTT command and convert it to the + * libmosquitto integer representation. + * + * Parameters: + * str - the string to parse. + * cmd - pointer to an int, for the result. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - on an invalid input. + * + * Example: + * (start code) + * mosquitto_string_to_command("CONNECT", &cmd); + * // cmd == CMD_CONNECT + * (end) + */ +libmosq_EXPORT int mosquitto_string_to_command(const char *str, int *cmd); + +/* + * 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. + * MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8 + * + * 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_topic_matches_sub2 + * + * 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. + * sublen - length in bytes of sub string + * topic - topic to check. + * topiclen - length in bytes of topic string + * 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_sub2(const char *sub, size_t sublen, const char *topic, size_t topiclen, 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. + * MOSQ_ERR_MALFORMED_UTF8 - if topic is not valid UTF-8 + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_pub_topic_check(const char *topic); + +/* + * Function: mosquitto_pub_topic_check2 + * + * 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 + * topiclen - length of the topic in bytes + * + * Returns: + * MOSQ_ERR_SUCCESS - for a valid topic + * MOSQ_ERR_INVAL - if the topic contains a + or a #, or if it is too long. + * MOSQ_ERR_MALFORMED_UTF8 - if topic is not valid UTF-8 + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_pub_topic_check2(const char *topic, size_t topiclen); + +/* + * 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. + * MOSQ_ERR_MALFORMED_UTF8 - if topic is not valid UTF-8 + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_sub_topic_check(const char *topic); + +/* + * Function: mosquitto_sub_topic_check2 + * + * 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 + * topiclen - the length in bytes of the topic + * + * 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. + * MOSQ_ERR_MALFORMED_UTF8 - if topic is not valid UTF-8 + * + * See Also: + * + */ +libmosq_EXPORT int mosquitto_sub_topic_check2(const char *topic, size_t topiclen); + + +/* + * Function: mosquitto_validate_utf8 + * + * Helper function to validate whether a UTF-8 string is valid, according to + * the UTF-8 spec and the MQTT additions. + * + * Parameters: + * str - a string to check + * len - the length of the string in bytes + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if str is NULL or len<0 or len>65536 + * MOSQ_ERR_MALFORMED_UTF8 - if str is not valid UTF-8 + */ +libmosq_EXPORT int mosquitto_validate_utf8(const char *str, int len); + + +/* ============================================================================= + * + * Section: One line client helper functions + * + * ============================================================================= + */ + +struct libmosquitto_will { + char *topic; + void *payload; + int payloadlen; + int qos; + bool retain; +}; + +struct libmosquitto_auth { + char *username; + char *password; +}; + +struct libmosquitto_tls { + char *cafile; + char *capath; + char *certfile; + char *keyfile; + char *ciphers; + char *tls_version; + int (*pw_callback)(char *buf, int size, int rwflag, void *userdata); + int cert_reqs; +}; + +/* + * Function: mosquitto_subscribe_simple + * + * Helper function to make subscribing to a topic and retrieving some messages + * very straightforward. + * + * This connects to a broker, subscribes to a topic, waits for msg_count + * messages to be received, then returns after disconnecting cleanly. + * + * Parameters: + * messages - pointer to a "struct mosquitto_message *". The received + * messages will be returned here. On error, this will be set to + * NULL. + * msg_count - the number of messages to retrieve. + * want_retained - if set to true, stale retained messages will be treated as + * normal messages with regards to msg_count. If set to + * false, they will be ignored. + * topic - the subscription topic to use (wildcards are allowed). + * qos - the qos to use for the subscription. + * host - the broker to connect to. + * port - the network port the broker is listening on. + * client_id - the client id to use, or NULL if a random client id should be + * generated. + * keepalive - the MQTT keepalive value. + * clean_session - the MQTT clean session flag. + * username - the username string, or NULL for no username authentication. + * password - the password string, or NULL for an empty password. + * will - a libmosquitto_will struct containing will information, or NULL for + * no will. + * tls - a libmosquitto_tls struct containing TLS related parameters, or NULL + * for no use of TLS. + * + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * Greater than 0 - on error. + */ +libmosq_EXPORT int mosquitto_subscribe_simple( + struct mosquitto_message **messages, + int msg_count, + bool want_retained, + const char *topic, + int qos, + const char *host, + int port, + const char *client_id, + int keepalive, + bool clean_session, + const char *username, + const char *password, + const struct libmosquitto_will *will, + const struct libmosquitto_tls *tls); + + +/* + * Function: mosquitto_subscribe_callback + * + * Helper function to make subscribing to a topic and processing some messages + * very straightforward. + * + * This connects to a broker, subscribes to a topic, then passes received + * messages to a user provided callback. If the callback returns a 1, it then + * disconnects cleanly and returns. + * + * Parameters: + * callback - a callback function in the following form: + * int callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) + * Note that this is the same as the normal on_message callback, + * except that it returns an int. + * userdata - user provided pointer that will be passed to the callback. + * topic - the subscription topic to use (wildcards are allowed). + * qos - the qos to use for the subscription. + * host - the broker to connect to. + * port - the network port the broker is listening on. + * client_id - the client id to use, or NULL if a random client id should be + * generated. + * keepalive - the MQTT keepalive value. + * clean_session - the MQTT clean session flag. + * username - the username string, or NULL for no username authentication. + * password - the password string, or NULL for an empty password. + * will - a libmosquitto_will struct containing will information, or NULL for + * no will. + * tls - a libmosquitto_tls struct containing TLS related parameters, or NULL + * for no use of TLS. + * + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * Greater than 0 - on error. + */ +libmosq_EXPORT int mosquitto_subscribe_callback( + int (*callback)(struct mosquitto *, void *, const struct mosquitto_message *), + void *userdata, + const char *topic, + int qos, + const char *host, + int port, + const char *client_id, + int keepalive, + bool clean_session, + const char *username, + const char *password, + const struct libmosquitto_will *will, + const struct libmosquitto_tls *tls); + + +/* ============================================================================= + * + * Section: Properties + * + * ============================================================================= + */ + + +/* + * Function: mosquitto_property_add_byte + * + * Add a new byte property to a property list. + * + * If *proplist == NULL, a new list will be created, otherwise the new property + * will be appended to the list. + * + * Parameters: + * proplist - pointer to mosquitto_property pointer, the list of properties + * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) + * value - integer value for the new property + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if identifier is invalid, or if proplist is NULL + * MOSQ_ERR_NOMEM - on out of memory + * + * Example: + * > mosquitto_property *proplist = NULL; + * > mosquitto_property_add_byte(&proplist, MQTT_PROP_PAYLOAD_FORMAT_IDENTIFIER, 1); + */ +libmosq_EXPORT int mosquitto_property_add_byte(mosquitto_property **proplist, int identifier, uint8_t value); + +/* + * Function: mosquitto_property_add_int16 + * + * Add a new int16 property to a property list. + * + * If *proplist == NULL, a new list will be created, otherwise the new property + * will be appended to the list. + * + * Parameters: + * proplist - pointer to mosquitto_property pointer, the list of properties + * identifier - property identifier (e.g. MQTT_PROP_RECEIVE_MAXIMUM) + * value - integer value for the new property + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if identifier is invalid, or if proplist is NULL + * MOSQ_ERR_NOMEM - on out of memory + * + * Example: + * > mosquitto_property *proplist = NULL; + * > mosquitto_property_add_int16(&proplist, MQTT_PROP_RECEIVE_MAXIMUM, 1000); + */ +libmosq_EXPORT int mosquitto_property_add_int16(mosquitto_property **proplist, int identifier, uint16_t value); + +/* + * Function: mosquitto_property_add_int32 + * + * Add a new int32 property to a property list. + * + * If *proplist == NULL, a new list will be created, otherwise the new property + * will be appended to the list. + * + * Parameters: + * proplist - pointer to mosquitto_property pointer, the list of properties + * identifier - property identifier (e.g. MQTT_PROP_MESSAGE_EXPIRY_INTERVAL) + * value - integer value for the new property + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if identifier is invalid, or if proplist is NULL + * MOSQ_ERR_NOMEM - on out of memory + * + * Example: + * > mosquitto_property *proplist = NULL; + * > mosquitto_property_add_int32(&proplist, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, 86400); + */ +libmosq_EXPORT int mosquitto_property_add_int32(mosquitto_property **proplist, int identifier, uint32_t value); + +/* + * Function: mosquitto_property_add_varint + * + * Add a new varint property to a property list. + * + * If *proplist == NULL, a new list will be created, otherwise the new property + * will be appended to the list. + * + * Parameters: + * proplist - pointer to mosquitto_property pointer, the list of properties + * identifier - property identifier (e.g. MQTT_PROP_SUBSCRIPTION_IDENTIFIER) + * value - integer value for the new property + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if identifier is invalid, or if proplist is NULL + * MOSQ_ERR_NOMEM - on out of memory + * + * Example: + * > mosquitto_property *proplist = NULL; + * > mosquitto_property_add_varint(&proplist, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 1); + */ +libmosq_EXPORT int mosquitto_property_add_varint(mosquitto_property **proplist, int identifier, uint32_t value); + +/* + * Function: mosquitto_property_add_binary + * + * Add a new binary property to a property list. + * + * If *proplist == NULL, a new list will be created, otherwise the new property + * will be appended to the list. + * + * Parameters: + * proplist - pointer to mosquitto_property pointer, the list of properties + * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) + * value - pointer to the property data + * len - length of property data in bytes + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if identifier is invalid, or if proplist is NULL + * MOSQ_ERR_NOMEM - on out of memory + * + * Example: + * > mosquitto_property *proplist = NULL; + * > mosquitto_property_add_binary(&proplist, MQTT_PROP_AUTHENTICATION_DATA, auth_data, auth_data_len); + */ +libmosq_EXPORT int mosquitto_property_add_binary(mosquitto_property **proplist, int identifier, const void *value, uint16_t len); + +/* + * Function: mosquitto_property_add_string + * + * Add a new string property to a property list. + * + * If *proplist == NULL, a new list will be created, otherwise the new property + * will be appended to the list. + * + * Parameters: + * proplist - pointer to mosquitto_property pointer, the list of properties + * identifier - property identifier (e.g. MQTT_PROP_CONTENT_TYPE) + * value - string value for the new property, must be UTF-8 and zero terminated + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if identifier is invalid, if value is NULL, or if proplist is NULL + * MOSQ_ERR_NOMEM - on out of memory + * MOSQ_ERR_MALFORMED_UTF8 - value is not valid UTF-8. + * + * Example: + * > mosquitto_property *proplist = NULL; + * > mosquitto_property_add_string(&proplist, MQTT_PROP_CONTENT_TYPE, "application/json"); + */ +libmosq_EXPORT int mosquitto_property_add_string(mosquitto_property **proplist, int identifier, const char *value); + +/* + * Function: mosquitto_property_add_string_pair + * + * Add a new string pair property to a property list. + * + * If *proplist == NULL, a new list will be created, otherwise the new property + * will be appended to the list. + * + * Parameters: + * proplist - pointer to mosquitto_property pointer, the list of properties + * identifier - property identifier (e.g. MQTT_PROP_USER_PROPERTY) + * name - string name for the new property, must be UTF-8 and zero terminated + * value - string value for the new property, must be UTF-8 and zero terminated + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if identifier is invalid, if name or value is NULL, or if proplist is NULL + * MOSQ_ERR_NOMEM - on out of memory + * MOSQ_ERR_MALFORMED_UTF8 - if name or value are not valid UTF-8. + * + * Example: + * > mosquitto_property *proplist = NULL; + * > mosquitto_property_add_string_pair(&proplist, MQTT_PROP_USER_PROPERTY, "client", "mosquitto_pub"); + */ +libmosq_EXPORT int mosquitto_property_add_string_pair(mosquitto_property **proplist, int identifier, const char *name, const char *value); + + +/* + * Function: mosquitto_property_identifier + * + * Return the property identifier for a single property. + * + * Parameters: + * property - pointer to a valid mosquitto_property pointer. + * + * Returns: + * A valid property identifier on success + * 0 - on error + */ +libmosq_EXPORT int mosquitto_property_identifier(const mosquitto_property *property); + + +/* + * Function: mosquitto_property_next + * + * Return the next property in a property list. Use to iterate over a property + * list, e.g.: + * + * (start code) + * for(prop = proplist; prop != NULL; prop = mosquitto_property_next(prop)){ + * if(mosquitto_property_identifier(prop) == MQTT_PROP_CONTENT_TYPE){ + * ... + * } + * } + * (end) + * + * Parameters: + * proplist - pointer to mosquitto_property pointer, the list of properties + * + * Returns: + * Pointer to the next item in the list + * NULL, if proplist is NULL, or if there are no more items in the list. + */ +libmosq_EXPORT const mosquitto_property *mosquitto_property_next(const mosquitto_property *proplist); + + +/* + * Function: mosquitto_property_read_byte + * + * Attempt to read a byte property matching an identifier, from a property list + * or single property. This function can search for multiple entries of the + * same identifier by using the returned value and skip_first. Note however + * that it is forbidden for most properties to be duplicated. + * + * If the property is not found, *value will not be modified, so it is safe to + * pass a variable with a default value to be potentially overwritten: + * + * (start code) + * uint16_t keepalive = 60; // default value + * // Get value from property list, or keep default if not found. + * mosquitto_property_read_int16(proplist, MQTT_PROP_SERVER_KEEP_ALIVE, &keepalive, false); + * (end) + * + * Parameters: + * proplist - mosquitto_property pointer, the list of properties or single property + * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) + * value - pointer to store the value, or NULL if the value is not required. + * skip_first - boolean that indicates whether the first item in the list + * should be ignored or not. Should usually be set to false. + * + * Returns: + * A valid property pointer if the property is found + * NULL, if the property is not found, or proplist is NULL. + * + * Example: + * (start code) + * // proplist is obtained from a callback + * mosquitto_property *prop; + * prop = mosquitto_property_read_byte(proplist, identifier, &value, false); + * while(prop){ + * printf("value: %s\n", value); + * prop = mosquitto_property_read_byte(prop, identifier, &value); + * } + * (end) + */ +libmosq_EXPORT const mosquitto_property *mosquitto_property_read_byte( + const mosquitto_property *proplist, + int identifier, + uint8_t *value, + bool skip_first); + +/* + * Function: mosquitto_property_read_int16 + * + * Read an int16 property value from a property. + * + * Parameters: + * property - property to read + * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) + * value - pointer to store the value, or NULL if the value is not required. + * skip_first - boolean that indicates whether the first item in the list + * should be ignored or not. Should usually be set to false. + * + * Returns: + * A valid property pointer if the property is found + * NULL, if the property is not found, or proplist is NULL. + * + * Example: + * See + */ +libmosq_EXPORT const mosquitto_property *mosquitto_property_read_int16( + const mosquitto_property *proplist, + int identifier, + uint16_t *value, + bool skip_first); + +/* + * Function: mosquitto_property_read_int32 + * + * Read an int32 property value from a property. + * + * Parameters: + * property - pointer to mosquitto_property pointer, the list of properties + * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) + * value - pointer to store the value, or NULL if the value is not required. + * skip_first - boolean that indicates whether the first item in the list + * should be ignored or not. Should usually be set to false. + * + * Returns: + * A valid property pointer if the property is found + * NULL, if the property is not found, or proplist is NULL. + * + * Example: + * See + */ +libmosq_EXPORT const mosquitto_property *mosquitto_property_read_int32( + const mosquitto_property *proplist, + int identifier, + uint32_t *value, + bool skip_first); + +/* + * Function: mosquitto_property_read_varint + * + * Read a varint property value from a property. + * + * Parameters: + * property - property to read + * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) + * value - pointer to store the value, or NULL if the value is not required. + * skip_first - boolean that indicates whether the first item in the list + * should be ignored or not. Should usually be set to false. + * + * Returns: + * A valid property pointer if the property is found + * NULL, if the property is not found, or proplist is NULL. + * + * Example: + * See + */ +libmosq_EXPORT const mosquitto_property *mosquitto_property_read_varint( + const mosquitto_property *proplist, + int identifier, + uint32_t *value, + bool skip_first); + +/* + * Function: mosquitto_property_read_binary + * + * Read a binary property value from a property. + * + * On success, value must be free()'d by the application. + * + * Parameters: + * property - property to read + * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) + * value - pointer to store the value, or NULL if the value is not required. + * skip_first - boolean that indicates whether the first item in the list + * should be ignored or not. Should usually be set to false. + * + * Returns: + * A valid property pointer if the property is found + * NULL, if the property is not found, or proplist is NULL, or if an out of memory condition occurred. + * + * Example: + * See + */ +libmosq_EXPORT const mosquitto_property *mosquitto_property_read_binary( + const mosquitto_property *proplist, + int identifier, + void **value, + uint16_t *len, + bool skip_first); + +/* + * Function: mosquitto_property_read_string + * + * Read a string property value from a property. + * + * On success, value must be free()'d by the application. + * + * Parameters: + * property - property to read + * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) + * value - pointer to char*, for the property data to be stored in, or NULL if + * the value is not required. + * skip_first - boolean that indicates whether the first item in the list + * should be ignored or not. Should usually be set to false. + * + * Returns: + * A valid property pointer if the property is found + * NULL, if the property is not found, or proplist is NULL, or if an out of memory condition occurred. + * + * Example: + * See + */ +libmosq_EXPORT const mosquitto_property *mosquitto_property_read_string( + const mosquitto_property *proplist, + int identifier, + char **value, + bool skip_first); + +/* + * Function: mosquitto_property_read_string_pair + * + * Read a string pair property value pair from a property. + * + * On success, name and value must be free()'d by the application. + * + * Parameters: + * property - property to read + * identifier - property identifier (e.g. MQTT_PROP_PAYLOAD_FORMAT_INDICATOR) + * name - pointer to char* for the name property data to be stored in, or NULL + * if the name is not required. + * value - pointer to char*, for the property data to be stored in, or NULL if + * the value is not required. + * skip_first - boolean that indicates whether the first item in the list + * should be ignored or not. Should usually be set to false. + * + * Returns: + * A valid property pointer if the property is found + * NULL, if the property is not found, or proplist is NULL, or if an out of memory condition occurred. + * + * Example: + * See + */ +libmosq_EXPORT const mosquitto_property *mosquitto_property_read_string_pair( + const mosquitto_property *proplist, + int identifier, + char **name, + char **value, + bool skip_first); + +/* + * Function: mosquitto_property_free_all + * + * Free all properties from a list of properties. Frees the list and sets *properties to NULL. + * + * Parameters: + * properties - list of properties to free + * + * Example: + * > mosquitto_properties *properties = NULL; + * > // Add properties + * > mosquitto_property_free_all(&properties); + */ +libmosq_EXPORT void mosquitto_property_free_all(mosquitto_property **properties); + +/* + * Function: mosquitto_property_copy_all + * + * Parameters: + * dest - pointer for new property list + * src - property list + * + * Returns: + * MOSQ_ERR_SUCCESS - on successful copy + * MOSQ_ERR_INVAL - if dest is NULL + * MOSQ_ERR_NOMEM - on out of memory (dest will be set to NULL) + */ +libmosq_EXPORT int mosquitto_property_copy_all(mosquitto_property **dest, const mosquitto_property *src); + +/* + * Function: mosquitto_property_check_command + * + * Check whether a property identifier is valid for the given command. + * + * Parameters: + * command - MQTT command (e.g. CMD_CONNECT) + * identifier - MQTT property (e.g. MQTT_PROP_USER_PROPERTY) + * + * Returns: + * MOSQ_ERR_SUCCESS - if the identifier is valid for command + * MOSQ_ERR_PROTOCOL - if the identifier is not valid for use with command. + */ +libmosq_EXPORT int mosquitto_property_check_command(int command, int identifier); + + +/* + * Function: mosquitto_property_check_all + * + * Check whether a list of properties are valid for a particular command, + * whether there are duplicates, and whether the values are valid where + * possible. + * + * Note that this function is used internally in the library whenever + * properties are passed to it, so in basic use this is not needed, but should + * be helpful to check property lists *before* the point of using them. + * + * Parameters: + * command - MQTT command (e.g. CMD_CONNECT) + * properties - list of MQTT properties to check. + * + * Returns: + * MOSQ_ERR_SUCCESS - if all properties are valid + * MOSQ_ERR_DUPLICATE_PROPERTY - if a property is duplicated where it is forbidden. + * MOSQ_ERR_PROTOCOL - if any property is invalid + */ +libmosq_EXPORT int mosquitto_property_check_all(int command, const mosquitto_property *properties); + +/* + * Function: mosquitto_property_identifier_to_string + * + * Return the property name as a string for a property identifier. + * The property name is as defined in the MQTT specification, with - as a + * separator, for example: payload-format-indicator. + * + * Parameters: + * identifier - valid MQTT property identifier integer + * + * Returns: + * A const string to the property name on success + * NULL on failure + */ +libmosq_EXPORT const char *mosquitto_property_identifier_to_string(int identifier); + + +/* Function: mosquitto_string_to_property_info + * + * Parse a property name string and convert to a property identifier and data type. + * The property name is as defined in the MQTT specification, with - as a + * separator, for example: payload-format-indicator. + * + * Parameters: + * propname - the string to parse + * identifier - pointer to an int to receive the property identifier + * type - pointer to an int to receive the property type + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if the string does not match a property + * + * Example: + * (start code) + * mosquitto_string_to_property_info("response-topic", &id, &type); + * // id == MQTT_PROP_RESPONSE_TOPIC + * // type == MQTT_PROP_TYPE_STRING + * (end) + */ +libmosq_EXPORT int mosquitto_string_to_property_info(const char *propname, int *identifier, int *type); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/mqttclient/mosquitto_broker.h b/mqttclient/mosquitto_broker.h new file mode 100644 index 0000000..9a6ba1e --- /dev/null +++ b/mqttclient/mosquitto_broker.h @@ -0,0 +1,561 @@ +/* +Copyright (c) 2009-2020 Roger Light + +All rights reserved. This program and the accompanying materials +are made available under the terms of the Eclipse Public License 2.0 +and Eclipse Distribution License v1.0 which accompany this distribution. + +The Eclipse Public License is available at + https://www.eclipse.org/legal/epl-2.0/ +and the Eclipse Distribution License is available at + http://www.eclipse.org/org/documents/edl-v10.php. + +SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause + +Contributors: + Roger Light - initial implementation and documentation. +*/ + +/* + * File: mosquitto_broker.h + * + * This header contains functions for use by plugins. + */ +#ifndef MOSQUITTO_BROKER_H +#define MOSQUITTO_BROKER_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(WIN32) && defined(mosquitto_EXPORTS) +# define mosq_EXPORT __declspec(dllexport) +#else +# define mosq_EXPORT +#endif + +#include +#include +#include +#include + +struct mosquitto; +typedef struct mqtt5__property mosquitto_property; + +enum mosquitto_protocol { + mp_mqtt, + mp_mqttsn, + mp_websockets +}; + +/* ========================================================================= + * + * Section: Register callbacks. + * + * ========================================================================= */ + +/* Callback events */ +enum mosquitto_plugin_event { + MOSQ_EVT_RELOAD = 1, + MOSQ_EVT_ACL_CHECK = 2, + MOSQ_EVT_BASIC_AUTH = 3, + MOSQ_EVT_EXT_AUTH_START = 4, + MOSQ_EVT_EXT_AUTH_CONTINUE = 5, + MOSQ_EVT_CONTROL = 6, + MOSQ_EVT_MESSAGE = 7, + MOSQ_EVT_PSK_KEY = 8, + MOSQ_EVT_TICK = 9, + MOSQ_EVT_DISCONNECT = 10, +}; + +/* Data for the MOSQ_EVT_RELOAD event */ +struct mosquitto_evt_reload { + void *future; + struct mosquitto_opt *options; + int option_count; + void *future2[4]; +}; + +/* Data for the MOSQ_EVT_ACL_CHECK event */ +struct mosquitto_evt_acl_check { + void *future; + struct mosquitto *client; + const char *topic; + const void *payload; + mosquitto_property *properties; + int access; + uint32_t payloadlen; + uint8_t qos; + bool retain; + void *future2[4]; +}; + +/* Data for the MOSQ_EVT_BASIC_AUTH event */ +struct mosquitto_evt_basic_auth { + void *future; + struct mosquitto *client; + char *username; + char *password; + void *future2[4]; +}; + +/* Data for the MOSQ_EVT_PSK_KEY event */ +struct mosquitto_evt_psk_key { + void *future; + struct mosquitto *client; + const char *hint; + const char *identity; + char *key; + int max_key_len; + void *future2[4]; +}; + +/* Data for the MOSQ_EVT_EXTENDED_AUTH event */ +struct mosquitto_evt_extended_auth { + void *future; + struct mosquitto *client; + const void *data_in; + void *data_out; + uint16_t data_in_len; + uint16_t data_out_len; + const char *auth_method; + void *future2[3]; +}; + +/* Data for the MOSQ_EVT_CONTROL event */ +struct mosquitto_evt_control { + void *future; + struct mosquitto *client; + const char *topic; + const void *payload; + const mosquitto_property *properties; + char *reason_string; + uint32_t payloadlen; + uint8_t qos; + uint8_t reason_code; + bool retain; + void *future2[4]; +}; + +/* Data for the MOSQ_EVT_MESSAGE event */ +struct mosquitto_evt_message { + void *future; + struct mosquitto *client; + char *topic; + void *payload; + mosquitto_property *properties; + char *reason_string; + uint32_t payloadlen; + uint8_t qos; + uint8_t reason_code; + bool retain; + void *future2[4]; +}; + + +/* Data for the MOSQ_EVT_TICK event */ +struct mosquitto_evt_tick { + void *future; + long now_ns; + long next_ns; + time_t now_s; + time_t next_s; + void *future2[4]; +}; + +/* Data for the MOSQ_EVT_DISCONNECT event */ +struct mosquitto_evt_disconnect { + void *future; + struct mosquitto *client; + int reason; + void *future2[4]; +}; + + +/* Callback definition */ +typedef int (*MOSQ_FUNC_generic_callback)(int, void *, void *); + +typedef struct mosquitto_plugin_id_t mosquitto_plugin_id_t; + +/* + * Function: mosquitto_callback_register + * + * Register a callback for an event. + * + * Parameters: + * identifier - the plugin identifier, as provided by . + * event - the event to register a callback for. Can be one of: + * * MOSQ_EVT_RELOAD + * * MOSQ_EVT_ACL_CHECK + * * MOSQ_EVT_BASIC_AUTH + * * MOSQ_EVT_EXT_AUTH_START + * * MOSQ_EVT_EXT_AUTH_CONTINUE + * * MOSQ_EVT_CONTROL + * * MOSQ_EVT_MESSAGE + * * MOSQ_EVT_PSK_KEY + * * MOSQ_EVT_TICK + * * MOSQ_EVT_DISCONNECT + * cb_func - the callback function + * event_data - event specific data + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if cb_func is NULL + * MOSQ_ERR_NOMEM - on out of memory + * MOSQ_ERR_ALREADY_EXISTS - if cb_func has already been registered for this event + * MOSQ_ERR_NOT_SUPPORTED - if the event is not supported + */ +mosq_EXPORT int mosquitto_callback_register( + mosquitto_plugin_id_t *identifier, + int event, + MOSQ_FUNC_generic_callback cb_func, + const void *event_data, + void *userdata); + +/* + * Function: mosquitto_callback_unregister + * + * Unregister a previously registered callback function. + * + * Parameters: + * identifier - the plugin identifier, as provided by . + * event - the event to register a callback for. Can be one of: + * * MOSQ_EVT_RELOAD + * * MOSQ_EVT_ACL_CHECK + * * MOSQ_EVT_BASIC_AUTH + * * MOSQ_EVT_EXT_AUTH_START + * * MOSQ_EVT_EXT_AUTH_CONTINUE + * * MOSQ_EVT_CONTROL + * * MOSQ_EVT_MESSAGE + * * MOSQ_EVT_PSK_KEY + * * MOSQ_EVT_TICK + * * MOSQ_EVT_DISCONNECT + * cb_func - the callback function + * event_data - event specific data + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if cb_func is NULL + * MOSQ_ERR_NOT_FOUND - if cb_func was not registered for this event + * MOSQ_ERR_NOT_SUPPORTED - if the event is not supported + */ +mosq_EXPORT int mosquitto_callback_unregister( + mosquitto_plugin_id_t *identifier, + int event, + MOSQ_FUNC_generic_callback cb_func, + const void *event_data); + + +/* ========================================================================= + * + * Section: Memory allocation. + * + * Use these functions when allocating or freeing memory to have your memory + * included in the memory tracking on the broker. + * + * ========================================================================= */ + +/* + * Function: mosquitto_calloc + */ +mosq_EXPORT void *mosquitto_calloc(size_t nmemb, size_t size); + +/* + * Function: mosquitto_free + */ +mosq_EXPORT void mosquitto_free(void *mem); + +/* + * Function: mosquitto_malloc + */ +mosq_EXPORT void *mosquitto_malloc(size_t size); + +/* + * Function: mosquitto_realloc + */ +mosq_EXPORT void *mosquitto_realloc(void *ptr, size_t size); + +/* + * Function: mosquitto_strdup + */ +mosq_EXPORT char *mosquitto_strdup(const char *s); + +/* ========================================================================= + * + * Section: Utility Functions + * + * Use these functions from within your plugin. + * + * ========================================================================= */ + + +/* + * Function: mosquitto_log_printf + * + * Write a log message using the broker configured logging. + * + * Parameters: + * level - Log message priority. Can currently be one of: + * + * * MOSQ_LOG_INFO + * * MOSQ_LOG_NOTICE + * * MOSQ_LOG_WARNING + * * MOSQ_LOG_ERR + * * MOSQ_LOG_DEBUG + * * MOSQ_LOG_SUBSCRIBE (not recommended for use by plugins) + * * MOSQ_LOG_UNSUBSCRIBE (not recommended for use by plugins) + * + * These values are defined in mosquitto.h. + * + * fmt, ... - printf style format and arguments. + */ +mosq_EXPORT void mosquitto_log_printf(int level, const char *fmt, ...); + + +/* ========================================================================= + * + * Client Functions + * + * Use these functions to access client information. + * + * ========================================================================= */ + +/* + * Function: mosquitto_client_address + * + * Retrieve the IP address of the client as a string. + */ +mosq_EXPORT const char *mosquitto_client_address(const struct mosquitto *client); + + +/* + * Function: mosquitto_client_clean_session + * + * Retrieve the clean session flag value for a client. + */ +mosq_EXPORT bool mosquitto_client_clean_session(const struct mosquitto *client); + + +/* + * Function: mosquitto_client_id + * + * Retrieve the client id associated with a client. + */ +mosq_EXPORT const char *mosquitto_client_id(const struct mosquitto *client); + + +/* + * Function: mosquitto_client_keepalive + * + * Retrieve the keepalive value for a client. + */ +mosq_EXPORT int mosquitto_client_keepalive(const struct mosquitto *client); + + +/* + * Function: mosquitto_client_certificate + * + * If TLS support is enabled, return the certificate provided by a client as an + * X509 pointer from openssl. If the client did not provide a certificate, then + * NULL will be returned. This function will only ever return a non-NULL value + * if the `require_certificate` option is set to true. + * + * When you have finished with the x509 pointer, it must be freed using + * X509_free(). + * + * If TLS is not supported, this function will always return NULL. + */ +mosq_EXPORT void *mosquitto_client_certificate(const struct mosquitto *client); + + +/* + * Function: mosquitto_client_protocol + * + * Retrieve the protocol with which the client has connected. Can be one of: + * + * mp_mqtt (MQTT over TCP) + * mp_mqttsn (MQTT-SN) + * mp_websockets (MQTT over Websockets) + */ +mosq_EXPORT int mosquitto_client_protocol(const struct mosquitto *client); + + +/* + * Function: mosquitto_client_protocol_version + * + * Retrieve the MQTT protocol version with which the client has connected. Can be one of: + * + * Returns: + * 3 - for MQTT v3 / v3.1 + * 4 - for MQTT v3.1.1 + * 5 - for MQTT v5 + */ +mosq_EXPORT int mosquitto_client_protocol_version(const struct mosquitto *client); + + +/* + * Function: mosquitto_client_sub_count + * + * Retrieve the number of subscriptions that have been made by a client. + */ +mosq_EXPORT int mosquitto_client_sub_count(const struct mosquitto *client); + + +/* + * Function: mosquitto_client_username + * + * Retrieve the username associated with a client. + */ +mosq_EXPORT const char *mosquitto_client_username(const struct mosquitto *client); + + +/* Function: mosquitto_set_username + * + * Set the username for a client. + * + * This removes and replaces the current username for a client and hence + * updates its access. + * + * username can be NULL, in which case the client will become anonymous, but + * must not be zero length. + * + * In the case of error, the client will be left with its original username. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if client is NULL, or if username is zero length + * MOSQ_ERR_NOMEM - on out of memory + */ +mosq_EXPORT int mosquitto_set_username(struct mosquitto *client, const char *username); + + +/* ========================================================================= + * + * Section: Client control + * + * ========================================================================= */ + +/* Function: mosquitto_kick_client_by_clientid + * + * Forcefully disconnect a client from the broker. + * + * If clientid != NULL, then the client with the matching client id is + * disconnected from the broker. + * If clientid == NULL, then all clients are disconnected from the broker. + * + * If with_will == true, then if the client has a Last Will and Testament + * defined then this will be sent. If false, the LWT will not be sent. + */ +mosq_EXPORT int mosquitto_kick_client_by_clientid(const char *clientid, bool with_will); + +/* Function: mosquitto_kick_client_by_username + * + * Forcefully disconnect a client from the broker. + * + * If username != NULL, then all clients with a matching username are kicked + * from the broker. + * If username == NULL, then all clients that do not have a username are + * kicked. + * + * If with_will == true, then if the client has a Last Will and Testament + * defined then this will be sent. If false, the LWT will not be sent. + */ +mosq_EXPORT int mosquitto_kick_client_by_username(const char *username, bool with_will); + + +/* ========================================================================= + * + * Section: Publishing functions + * + * ========================================================================= */ + +/* Function: mosquitto_broker_publish + * + * Publish a message from within a plugin. + * + * This function allows a plugin to publish a message. Messages published in + * this way are treated as coming from the broker and so will not be passed to + * `mosquitto_auth_acl_check(, MOSQ_ACL_WRITE, , )` for checking. Read access + * will be enforced as normal for individual clients when they are due to + * receive the message. + * + * It can be used to send messages to all clients that have a matching + * subscription, or to a single client whether or not it has a matching + * subscription. + * + * Parameters: + * clientid - optional string. If set to NULL, the message is delivered to all + * clients. If non-NULL, the message is delivered only to the + * client with the corresponding client id. If the client id + * specified is not connected, the message will be dropped. + * topic - message topic + * payloadlen - payload length in bytes. Can be 0 for an empty payload. + * payload - payload bytes. If payloadlen > 0 this must not be NULL. Must + * be allocated on the heap. Will be freed by mosquitto after use if the + * function returns success. + * qos - message QoS to use. + * retain - should retain be set on the message. This does not apply if + * clientid is non-NULL. + * properties - MQTT v5 properties to attach to the message. If the function + * returns success, then properties is owned by the broker and + * will be freed at a later point. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if topic is NULL, if payloadlen < 0, if payloadlen > 0 + * and payload is NULL, if qos is not 0, 1, or 2. + * MOSQ_ERR_NOMEM - on out of memory + */ +mosq_EXPORT int mosquitto_broker_publish( + const char *clientid, + const char *topic, + int payloadlen, + void *payload, + int qos, + bool retain, + mosquitto_property *properties); + + +/* Function: mosquitto_broker_publish_copy + * + * Publish a message from within a plugin. + * + * This function is identical to mosquitto_broker_publish, except that a copy + * of `payload` is taken. + * + * Parameters: + * clientid - optional string. If set to NULL, the message is delivered to all + * clients. If non-NULL, the message is delivered only to the + * client with the corresponding client id. If the client id + * specified is not connected, the message will be dropped. + * topic - message topic + * payloadlen - payload length in bytes. Can be 0 for an empty payload. + * payload - payload bytes. If payloadlen > 0 this must not be NULL. + * Memory remains the property of the calling function. + * qos - message QoS to use. + * retain - should retain be set on the message. This does not apply if + * clientid is non-NULL. + * properties - MQTT v5 properties to attach to the message. If the function + * returns success, then properties is owned by the broker and + * will be freed at a later point. + * + * Returns: + * MOSQ_ERR_SUCCESS - on success + * MOSQ_ERR_INVAL - if topic is NULL, if payloadlen < 0, if payloadlen > 0 + * and payload is NULL, if qos is not 0, 1, or 2. + * MOSQ_ERR_NOMEM - on out of memory + */ +mosq_EXPORT int mosquitto_broker_publish_copy( + const char *clientid, + const char *topic, + int payloadlen, + const void *payload, + int qos, + bool retain, + mosquitto_property *properties); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/mqttclient/mosquitto_plugin.h b/mqttclient/mosquitto_plugin.h new file mode 100644 index 0000000..5b5974d --- /dev/null +++ b/mqttclient/mosquitto_plugin.h @@ -0,0 +1,420 @@ +/* +Copyright (c) 2012-2020 Roger Light + +All rights reserved. This program and the accompanying materials +are made available under the terms of the Eclipse Public License 2.0 +and Eclipse Distribution License v1.0 which accompany this distribution. + +The Eclipse Public License is available at + https://www.eclipse.org/legal/epl-2.0/ +and the Eclipse Distribution License is available at + http://www.eclipse.org/org/documents/edl-v10.php. + +SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause + +Contributors: + Roger Light - initial implementation and documentation. +*/ + +#ifndef MOSQUITTO_PLUGIN_H +#define MOSQUITTO_PLUGIN_H + +/* + * File: mosquitto_plugin.h + * + * This header contains function declarations for use when writing a Mosquitto plugin. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* The generic plugin interface starts at version 5 */ +#define MOSQ_PLUGIN_VERSION 5 + +/* The old auth only interface stopped at version 4 */ +#define MOSQ_AUTH_PLUGIN_VERSION 4 + +#define MOSQ_ACL_NONE 0x00 +#define MOSQ_ACL_READ 0x01 +#define MOSQ_ACL_WRITE 0x02 +#define MOSQ_ACL_SUBSCRIBE 0x04 +#define MOSQ_ACL_UNSUBSCRIBE 0x08 + +#include +#include + +#include + +struct mosquitto; + +struct mosquitto_opt { + char *key; + char *value; +}; + +struct mosquitto_auth_opt { + char *key; + char *value; +}; + +struct mosquitto_acl_msg { + const char *topic; + const void *payload; + long payloadlen; + int qos; + bool retain; +}; + +#ifdef WIN32 +# define mosq_plugin_EXPORT __declspec(dllexport) +#else +# define mosq_plugin_EXPORT +#endif + +/* + * To create an authentication plugin you must include this file then implement + * the functions listed in the "Plugin Functions" section below. The resulting + * code should then be compiled as a shared library. Using gcc this can be + * achieved as follows: + * + * gcc -I -fPIC -shared plugin.c -o plugin.so + * + * On Mac OS X: + * + * gcc -I -fPIC -shared plugin.c -undefined dynamic_lookup -o plugin.so + * + * Authentication plugins can implement one or both of authentication and + * access control. If your plugin does not wish to handle either of + * authentication or access control it should return MOSQ_ERR_PLUGIN_DEFER. In + * this case, the next plugin will handle it. If all plugins return + * MOSQ_ERR_PLUGIN_DEFER, the request will be denied. + * + * For each check, the following flow happens: + * + * * The default password file and/or acl file checks are made. If either one + * of these is not defined, then they are considered to be deferred. If either + * one accepts the check, no further checks are made. If an error occurs, the + * check is denied + * * The first plugin does the check, if it returns anything other than + * MOSQ_ERR_PLUGIN_DEFER, then the check returns immediately. If the plugin + * returns MOSQ_ERR_PLUGIN_DEFER then the next plugin runs its check. + * * If the final plugin returns MOSQ_ERR_PLUGIN_DEFER, then access will be + * denied. + */ + +/* ========================================================================= + * + * Helper Functions + * + * ========================================================================= */ + +/* There are functions that are available for plugin developers to use in + * mosquitto_broker.h, including logging and accessor functions. + */ + + +/* ========================================================================= + * + * Section: Plugin Functions v5 + * + * This is the plugin version 5 interface, which covers authentication, access + * control, the $CONTROL topic space handling, and message inspection and + * modification. + * + * This interface is available from v2.0 onwards. + * + * There are just three functions to implement in your plugin. You should + * register callbacks to handle different events in your + * mosquitto_plugin_init() function. See mosquitto_broker.h for the events and + * callback registering functions. + * + * ========================================================================= */ + +/* + * Function: mosquitto_plugin_version + * + * The broker will attempt to call this function immediately after loading the + * plugin to check it is a supported plugin version. Your code must simply + * return the plugin interface version you support, i.e. 5. + * + * The supported_versions array tells you which plugin versions the broker supports. + * + * If the broker does not support the version that you require, return -1 to + * indicate failure. + */ +mosq_plugin_EXPORT int mosquitto_plugin_version(int supported_version_count, const int *supported_versions); + +/* + * Function: mosquitto_plugin_init + * + * Called after the plugin has been loaded and + * has been called. This will only ever be called once and can be used to + * initialise the plugin. + * + * Parameters: + * + * identifier - This is a pointer to an opaque structure which you must + * save and use when registering/unregistering callbacks. + * user_data - The pointer set here will be passed to the other plugin + * functions. Use to hold connection information for example. + * opts - Pointer to an array of struct mosquitto_opt, which + * provides the plugin options defined in the configuration file. + * opt_count - The number of elements in the opts array. + * + * Return value: + * Return 0 on success + * Return >0 on failure. + */ +mosq_plugin_EXPORT int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **userdata, struct mosquitto_opt *options, int option_count); + + +/* + * Function: mosquitto_plugin_cleanup + * + * Called when the broker is shutting down. This will only ever be called once + * per plugin. + * + * Parameters: + * + * user_data - The pointer provided in . + * opts - Pointer to an array of struct mosquitto_opt, which + * provides the plugin options defined in the configuration file. + * opt_count - The number of elements in the opts array. + * + * Return value: + * Return 0 on success + * Return >0 on failure. + */ +mosq_plugin_EXPORT int mosquitto_plugin_cleanup(void *userdata, struct mosquitto_opt *options, int option_count); + + + +/* ========================================================================= + * + * Section: Plugin Functions v4 + * + * This is the plugin version 4 interface, which is exclusively for + * authentication and access control, and which is still supported for existing + * plugins. If you are developing a new plugin, please use the v5 interface. + * + * You must implement these functions in your plugin. + * + * ========================================================================= */ + +/* + * Function: mosquitto_auth_plugin_version + * + * The broker will call this function immediately after loading the plugin to + * check it is a supported plugin version. Your code must simply return + * the version of the plugin interface you support, i.e. 4. + */ +mosq_plugin_EXPORT int mosquitto_auth_plugin_version(void); + + +/* + * Function: mosquitto_auth_plugin_init + * + * Called after the plugin has been loaded and + * has been called. This will only ever be called once and can be used to + * initialise the plugin. + * + * Parameters: + * + * user_data - The pointer set here will be passed to the other plugin + * functions. Use to hold connection information for example. + * opts - Pointer to an array of struct mosquitto_opt, which + * provides the plugin options defined in the configuration file. + * opt_count - The number of elements in the opts array. + * + * Return value: + * Return 0 on success + * Return >0 on failure. + */ +mosq_plugin_EXPORT int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *opts, int opt_count); + + +/* + * Function: mosquitto_auth_plugin_cleanup + * + * Called when the broker is shutting down. This will only ever be called once + * per plugin. + * Note that will be called directly before + * this function. + * + * Parameters: + * + * user_data - The pointer provided in . + * opts - Pointer to an array of struct mosquitto_opt, which + * provides the plugin options defined in the configuration file. + * opt_count - The number of elements in the opts array. + * + * Return value: + * Return 0 on success + * Return >0 on failure. + */ +mosq_plugin_EXPORT int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count); + + +/* + * Function: mosquitto_auth_security_init + * + * This function is called in two scenarios: + * + * 1. When the broker starts up. + * 2. If the broker is requested to reload its configuration whilst running. In + * this case, will be called first, then + * this function will be called. In this situation, the reload parameter + * will be true. + * + * Parameters: + * + * user_data - The pointer provided in . + * opts - Pointer to an array of struct mosquitto_opt, which + * provides the plugin options defined in the configuration file. + * opt_count - The number of elements in the opts array. + * reload - If set to false, this is the first time the function has + * been called. If true, the broker has received a signal + * asking to reload its configuration. + * + * Return value: + * Return 0 on success + * Return >0 on failure. + */ +mosq_plugin_EXPORT int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *opts, int opt_count, bool reload); + + +/* + * Function: mosquitto_auth_security_cleanup + * + * This function is called in two scenarios: + * + * 1. When the broker is shutting down. + * 2. If the broker is requested to reload its configuration whilst running. In + * this case, this function will be called, followed by + * . In this situation, the reload parameter + * will be true. + * + * Parameters: + * + * user_data - The pointer provided in . + * opts - Pointer to an array of struct mosquitto_opt, which + * provides the plugin options defined in the configuration file. + * opt_count - The number of elements in the opts array. + * reload - If set to false, this is the first time the function has + * been called. If true, the broker has received a signal + * asking to reload its configuration. + * + * Return value: + * Return 0 on success + * Return >0 on failure. + */ +mosq_plugin_EXPORT int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count, bool reload); + + +/* + * Function: mosquitto_auth_acl_check + * + * Called by the broker when topic access must be checked. access will be one + * of: + * MOSQ_ACL_SUBSCRIBE when a client is asking to subscribe to a topic string. + * This differs from MOSQ_ACL_READ in that it allows you to + * deny access to topic strings rather than by pattern. For + * example, you may use MOSQ_ACL_SUBSCRIBE to deny + * subscriptions to '#', but allow all topics in + * MOSQ_ACL_READ. This allows clients to subscribe to any + * topic they want, but not discover what topics are in use + * on the server. + * MOSQ_ACL_READ when a message is about to be sent to a client (i.e. whether + * it can read that topic or not). + * MOSQ_ACL_WRITE when a message has been received from a client (i.e. whether + * it can write to that topic or not). + * + * Return: + * MOSQ_ERR_SUCCESS if access was granted. + * MOSQ_ERR_ACL_DENIED if access was not granted. + * MOSQ_ERR_UNKNOWN for an application specific error. + * MOSQ_ERR_PLUGIN_DEFER if your plugin does not wish to handle this check. + */ +mosq_plugin_EXPORT int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg); + + +/* + * Function: mosquitto_auth_unpwd_check + * + * This function is OPTIONAL. Only include this function in your plugin if you + * are making basic username/password checks. + * + * Called by the broker when a username/password must be checked. + * + * Return: + * MOSQ_ERR_SUCCESS if the user is authenticated. + * MOSQ_ERR_AUTH if authentication failed. + * MOSQ_ERR_UNKNOWN for an application specific error. + * MOSQ_ERR_PLUGIN_DEFER if your plugin does not wish to handle this check. + */ +mosq_plugin_EXPORT int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password); + + +/* + * Function: mosquitto_psk_key_get + * + * This function is OPTIONAL. Only include this function in your plugin if you + * are making TLS-PSK checks. + * + * Called by the broker when a client connects to a listener using TLS/PSK. + * This is used to retrieve the pre-shared-key associated with a client + * identity. + * + * Examine hint and identity to determine the required PSK (which must be a + * hexadecimal string with no leading "0x") and copy this string into key. + * + * Parameters: + * user_data - the pointer provided in . + * hint - the psk_hint for the listener the client is connecting to. + * identity - the identity string provided by the client + * key - a string where the hex PSK should be copied + * max_key_len - the size of key + * + * Return value: + * Return 0 on success. + * Return >0 on failure. + * Return MOSQ_ERR_PLUGIN_DEFER if your plugin does not wish to handle this check. + */ +mosq_plugin_EXPORT int mosquitto_auth_psk_key_get(void *user_data, struct mosquitto *client, const char *hint, const char *identity, char *key, int max_key_len); + +/* + * Function: mosquitto_auth_start + * + * This function is OPTIONAL. Only include this function in your plugin if you + * are making extended authentication checks. + * + * Parameters: + * user_data - the pointer provided in . + * method - the authentication method + * reauth - this is set to false if this is the first authentication attempt + * on a connection, set to true if the client is attempting to + * reauthenticate. + * data_in - pointer to authentication data, or NULL + * data_in_len - length of data_in, in bytes + * data_out - if your plugin wishes to send authentication data back to the + * client, allocate some memory using malloc or friends and set + * data_out. The broker will free the memory after use. + * data_out_len - Set the length of data_out in bytes. + * + * Return value: + * Return MOSQ_ERR_SUCCESS if authentication was successful. + * Return MOSQ_ERR_AUTH_CONTINUE if the authentication is a multi step process and can continue. + * Return MOSQ_ERR_AUTH if authentication was valid but did not succeed. + * Return any other relevant positive integer MOSQ_ERR_* to produce an error. + */ +mosq_plugin_EXPORT int mosquitto_auth_start(void *user_data, struct mosquitto *client, const char *method, bool reauth, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len); + +mosq_plugin_EXPORT int mosquitto_auth_continue(void *user_data, struct mosquitto *client, const char *method, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/mqttclient/mqtt_protocol.h b/mqttclient/mqtt_protocol.h new file mode 100644 index 0000000..15c4c3e --- /dev/null +++ b/mqttclient/mqtt_protocol.h @@ -0,0 +1,282 @@ +/* +Copyright (c) 2009-2020 Roger Light + +All rights reserved. This program and the accompanying materials +are made available under the terms of the Eclipse Public License 2.0 +and Eclipse Distribution License v1.0 which accompany this distribution. + +The Eclipse Public License is available at + https://www.eclipse.org/legal/epl-2.0/ +and the Eclipse Distribution License is available at + http://www.eclipse.org/org/documents/edl-v10.php. + +SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause + +Contributors: + Roger Light - initial implementation and documentation. +*/ + +#ifndef MQTT_PROTOCOL_H +#define MQTT_PROTOCOL_H + +/* + * File: mqtt_protocol.h + * + * This header contains definitions of MQTT values as defined in the specifications. + */ +#define PROTOCOL_NAME_v31 "MQIsdp" +#define PROTOCOL_VERSION_v31 3 + +#define PROTOCOL_NAME "MQTT" + +#define PROTOCOL_VERSION_v311 4 +#define PROTOCOL_VERSION_v5 5 + + +/* Message types */ +#define CMD_CONNECT 0x10U +#define CMD_CONNACK 0x20U +#define CMD_PUBLISH 0x30U +#define CMD_PUBACK 0x40U +#define CMD_PUBREC 0x50U +#define CMD_PUBREL 0x60U +#define CMD_PUBCOMP 0x70U +#define CMD_SUBSCRIBE 0x80U +#define CMD_SUBACK 0x90U +#define CMD_UNSUBSCRIBE 0xA0U +#define CMD_UNSUBACK 0xB0U +#define CMD_PINGREQ 0xC0U +#define CMD_PINGRESP 0xD0U +#define CMD_DISCONNECT 0xE0U +#define CMD_AUTH 0xF0U + +/* Mosquitto only: for distinguishing CONNECT and WILL properties */ +#define CMD_WILL 0x100 + +/* Enum: mqtt311_connack_codes + * + * The CONNACK results for MQTT v3.1.1, and v3.1. + * + * Values: + * CONNACK_ACCEPTED - 0 + * CONNACK_REFUSED_PROTOCOL_VERSION - 1 + * CONNACK_REFUSED_IDENTIFIER_REJECTED - 2 + * CONNACK_REFUSED_SERVER_UNAVAILABLE - 3 + * CONNACK_REFUSED_BAD_USERNAME_PASSWORD - 4 + * CONNACK_REFUSED_NOT_AUTHORIZED - 5 + */ +enum mqtt311_connack_codes { + CONNACK_ACCEPTED = 0, + CONNACK_REFUSED_PROTOCOL_VERSION = 1, + CONNACK_REFUSED_IDENTIFIER_REJECTED = 2, + CONNACK_REFUSED_SERVER_UNAVAILABLE = 3, + CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4, + CONNACK_REFUSED_NOT_AUTHORIZED = 5, +}; + +/* Enum: mqtt5_return_codes + * The reason codes returned in various MQTT commands. + * + * Values: + * MQTT_RC_SUCCESS - 0 + * MQTT_RC_NORMAL_DISCONNECTION - 0 + * MQTT_RC_GRANTED_QOS0 - 0 + * MQTT_RC_GRANTED_QOS1 - 1 + * MQTT_RC_GRANTED_QOS2 - 2 + * MQTT_RC_DISCONNECT_WITH_WILL_MSG - 4 + * MQTT_RC_NO_MATCHING_SUBSCRIBERS - 16 + * MQTT_RC_NO_SUBSCRIPTION_EXISTED - 17 + * MQTT_RC_CONTINUE_AUTHENTICATION - 24 + * MQTT_RC_REAUTHENTICATE - 25 + * MQTT_RC_UNSPECIFIED - 128 + * MQTT_RC_MALFORMED_PACKET - 129 + * MQTT_RC_PROTOCOL_ERROR - 130 + * MQTT_RC_IMPLEMENTATION_SPECIFIC - 131 + * MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION - 132 + * MQTT_RC_CLIENTID_NOT_VALID - 133 + * MQTT_RC_BAD_USERNAME_OR_PASSWORD - 134 + * MQTT_RC_NOT_AUTHORIZED - 135 + * MQTT_RC_SERVER_UNAVAILABLE - 136 + * MQTT_RC_SERVER_BUSY - 137 + * MQTT_RC_BANNED - 138 + * MQTT_RC_SERVER_SHUTTING_DOWN - 139 + * MQTT_RC_BAD_AUTHENTICATION_METHOD - 140 + * MQTT_RC_KEEP_ALIVE_TIMEOUT - 141 + * MQTT_RC_SESSION_TAKEN_OVER - 142 + * MQTT_RC_TOPIC_FILTER_INVALID - 143 + * MQTT_RC_TOPIC_NAME_INVALID - 144 + * MQTT_RC_PACKET_ID_IN_USE - 145 + * MQTT_RC_PACKET_ID_NOT_FOUND - 146 + * MQTT_RC_RECEIVE_MAXIMUM_EXCEEDED - 147 + * MQTT_RC_TOPIC_ALIAS_INVALID - 148 + * MQTT_RC_PACKET_TOO_LARGE - 149 + * MQTT_RC_MESSAGE_RATE_TOO_HIGH - 150 + * MQTT_RC_QUOTA_EXCEEDED - 151 + * MQTT_RC_ADMINISTRATIVE_ACTION - 152 + * MQTT_RC_PAYLOAD_FORMAT_INVALID - 153 + * MQTT_RC_RETAIN_NOT_SUPPORTED - 154 + * MQTT_RC_QOS_NOT_SUPPORTED - 155 + * MQTT_RC_USE_ANOTHER_SERVER - 156 + * MQTT_RC_SERVER_MOVED - 157 + * MQTT_RC_SHARED_SUBS_NOT_SUPPORTED - 158 + * MQTT_RC_CONNECTION_RATE_EXCEEDED - 159 + * MQTT_RC_MAXIMUM_CONNECT_TIME - 160 + * MQTT_RC_SUBSCRIPTION_IDS_NOT_SUPPORTED - 161 + * MQTT_RC_WILDCARD_SUBS_NOT_SUPPORTED - 162 + */ +enum mqtt5_return_codes { + MQTT_RC_SUCCESS = 0, /* CONNACK, PUBACK, PUBREC, PUBREL, PUBCOMP, UNSUBACK, AUTH */ + MQTT_RC_NORMAL_DISCONNECTION = 0, /* DISCONNECT */ + MQTT_RC_GRANTED_QOS0 = 0, /* SUBACK */ + MQTT_RC_GRANTED_QOS1 = 1, /* SUBACK */ + MQTT_RC_GRANTED_QOS2 = 2, /* SUBACK */ + MQTT_RC_DISCONNECT_WITH_WILL_MSG = 4, /* DISCONNECT */ + MQTT_RC_NO_MATCHING_SUBSCRIBERS = 16, /* PUBACK, PUBREC */ + MQTT_RC_NO_SUBSCRIPTION_EXISTED = 17, /* UNSUBACK */ + MQTT_RC_CONTINUE_AUTHENTICATION = 24, /* AUTH */ + MQTT_RC_REAUTHENTICATE = 25, /* AUTH */ + + MQTT_RC_UNSPECIFIED = 128, /* CONNACK, PUBACK, PUBREC, SUBACK, UNSUBACK, DISCONNECT */ + MQTT_RC_MALFORMED_PACKET = 129, /* CONNACK, DISCONNECT */ + MQTT_RC_PROTOCOL_ERROR = 130, /* DISCONNECT */ + MQTT_RC_IMPLEMENTATION_SPECIFIC = 131, /* CONNACK, PUBACK, PUBREC, SUBACK, UNSUBACK, DISCONNECT */ + MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION = 132, /* CONNACK */ + MQTT_RC_CLIENTID_NOT_VALID = 133, /* CONNACK */ + MQTT_RC_BAD_USERNAME_OR_PASSWORD = 134, /* CONNACK */ + MQTT_RC_NOT_AUTHORIZED = 135, /* CONNACK, PUBACK, PUBREC, SUBACK, UNSUBACK, DISCONNECT */ + MQTT_RC_SERVER_UNAVAILABLE = 136, /* CONNACK */ + MQTT_RC_SERVER_BUSY = 137, /* CONNACK, DISCONNECT */ + MQTT_RC_BANNED = 138, /* CONNACK */ + MQTT_RC_SERVER_SHUTTING_DOWN = 139, /* DISCONNECT */ + MQTT_RC_BAD_AUTHENTICATION_METHOD = 140, /* CONNACK */ + MQTT_RC_KEEP_ALIVE_TIMEOUT = 141, /* DISCONNECT */ + MQTT_RC_SESSION_TAKEN_OVER = 142, /* DISCONNECT */ + MQTT_RC_TOPIC_FILTER_INVALID = 143, /* SUBACK, UNSUBACK, DISCONNECT */ + MQTT_RC_TOPIC_NAME_INVALID = 144, /* CONNACK, PUBACK, PUBREC, DISCONNECT */ + MQTT_RC_PACKET_ID_IN_USE = 145, /* PUBACK, SUBACK, UNSUBACK */ + MQTT_RC_PACKET_ID_NOT_FOUND = 146, /* PUBREL, PUBCOMP */ + MQTT_RC_RECEIVE_MAXIMUM_EXCEEDED = 147, /* DISCONNECT */ + MQTT_RC_TOPIC_ALIAS_INVALID = 148, /* DISCONNECT */ + MQTT_RC_PACKET_TOO_LARGE = 149, /* CONNACK, PUBACK, PUBREC, DISCONNECT */ + MQTT_RC_MESSAGE_RATE_TOO_HIGH = 150, /* DISCONNECT */ + MQTT_RC_QUOTA_EXCEEDED = 151, /* PUBACK, PUBREC, SUBACK, DISCONNECT */ + MQTT_RC_ADMINISTRATIVE_ACTION = 152, /* DISCONNECT */ + MQTT_RC_PAYLOAD_FORMAT_INVALID = 153, /* CONNACK, DISCONNECT */ + MQTT_RC_RETAIN_NOT_SUPPORTED = 154, /* CONNACK, DISCONNECT */ + MQTT_RC_QOS_NOT_SUPPORTED = 155, /* CONNACK, DISCONNECT */ + MQTT_RC_USE_ANOTHER_SERVER = 156, /* CONNACK, DISCONNECT */ + MQTT_RC_SERVER_MOVED = 157, /* CONNACK, DISCONNECT */ + MQTT_RC_SHARED_SUBS_NOT_SUPPORTED = 158, /* SUBACK, DISCONNECT */ + MQTT_RC_CONNECTION_RATE_EXCEEDED = 159, /* CONNACK, DISCONNECT */ + MQTT_RC_MAXIMUM_CONNECT_TIME = 160, /* DISCONNECT */ + MQTT_RC_SUBSCRIPTION_IDS_NOT_SUPPORTED = 161, /* SUBACK, DISCONNECT */ + MQTT_RC_WILDCARD_SUBS_NOT_SUPPORTED = 162, /* SUBACK, DISCONNECT */ +}; + +/* Enum: mqtt5_property + * Options for use with MQTTv5 properties. + * Options: + * + * MQTT_PROP_PAYLOAD_FORMAT_INDICATOR - property option. + * MQTT_PROP_MESSAGE_EXPIRY_INTERVAL - property option. + * MQTT_PROP_CONTENT_TYPE - property option. + * MQTT_PROP_RESPONSE_TOPIC - property option. + * MQTT_PROP_CORRELATION_DATA - property option. + * MQTT_PROP_SUBSCRIPTION_IDENTIFIER - property option. + * MQTT_PROP_SESSION_EXPIRY_INTERVAL - property option. + * MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER - property option. + * MQTT_PROP_SERVER_KEEP_ALIVE - property option. + * MQTT_PROP_AUTHENTICATION_METHOD - property option. + * MQTT_PROP_AUTHENTICATION_DATA - property option. + * MQTT_PROP_REQUEST_PROBLEM_INFORMATION - property option. + * MQTT_PROP_WILL_DELAY_INTERVAL - property option. + * MQTT_PROP_REQUEST_RESPONSE_INFORMATION - property option. + * MQTT_PROP_RESPONSE_INFORMATION - property option. + * MQTT_PROP_SERVER_REFERENCE - property option. + * MQTT_PROP_REASON_STRING - property option. + * MQTT_PROP_RECEIVE_MAXIMUM - property option. + * MQTT_PROP_TOPIC_ALIAS_MAXIMUM - property option. + * MQTT_PROP_TOPIC_ALIAS - property option. + * MQTT_PROP_MAXIMUM_QOS - property option. + * MQTT_PROP_RETAIN_AVAILABLE - property option. + * MQTT_PROP_USER_PROPERTY - property option. + * MQTT_PROP_MAXIMUM_PACKET_SIZE - property option. + * MQTT_PROP_WILDCARD_SUB_AVAILABLE - property option. + * MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE - property option. + * MQTT_PROP_SHARED_SUB_AVAILABLE - property option. + */ +enum mqtt5_property { + MQTT_PROP_PAYLOAD_FORMAT_INDICATOR = 1, /* Byte : PUBLISH, Will Properties */ + MQTT_PROP_MESSAGE_EXPIRY_INTERVAL = 2, /* 4 byte int : PUBLISH, Will Properties */ + MQTT_PROP_CONTENT_TYPE = 3, /* UTF-8 string : PUBLISH, Will Properties */ + MQTT_PROP_RESPONSE_TOPIC = 8, /* UTF-8 string : PUBLISH, Will Properties */ + MQTT_PROP_CORRELATION_DATA = 9, /* Binary Data : PUBLISH, Will Properties */ + MQTT_PROP_SUBSCRIPTION_IDENTIFIER = 11, /* Variable byte int : PUBLISH, SUBSCRIBE */ + MQTT_PROP_SESSION_EXPIRY_INTERVAL = 17, /* 4 byte int : CONNECT, CONNACK, DISCONNECT */ + MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER = 18, /* UTF-8 string : CONNACK */ + MQTT_PROP_SERVER_KEEP_ALIVE = 19, /* 2 byte int : CONNACK */ + MQTT_PROP_AUTHENTICATION_METHOD = 21, /* UTF-8 string : CONNECT, CONNACK, AUTH */ + MQTT_PROP_AUTHENTICATION_DATA = 22, /* Binary Data : CONNECT, CONNACK, AUTH */ + MQTT_PROP_REQUEST_PROBLEM_INFORMATION = 23, /* Byte : CONNECT */ + MQTT_PROP_WILL_DELAY_INTERVAL = 24, /* 4 byte int : Will properties */ + MQTT_PROP_REQUEST_RESPONSE_INFORMATION = 25,/* Byte : CONNECT */ + MQTT_PROP_RESPONSE_INFORMATION = 26, /* UTF-8 string : CONNACK */ + MQTT_PROP_SERVER_REFERENCE = 28, /* UTF-8 string : CONNACK, DISCONNECT */ + MQTT_PROP_REASON_STRING = 31, /* UTF-8 string : All except Will properties */ + MQTT_PROP_RECEIVE_MAXIMUM = 33, /* 2 byte int : CONNECT, CONNACK */ + MQTT_PROP_TOPIC_ALIAS_MAXIMUM = 34, /* 2 byte int : CONNECT, CONNACK */ + MQTT_PROP_TOPIC_ALIAS = 35, /* 2 byte int : PUBLISH */ + MQTT_PROP_MAXIMUM_QOS = 36, /* Byte : CONNACK */ + MQTT_PROP_RETAIN_AVAILABLE = 37, /* Byte : CONNACK */ + MQTT_PROP_USER_PROPERTY = 38, /* UTF-8 string pair : All */ + MQTT_PROP_MAXIMUM_PACKET_SIZE = 39, /* 4 byte int : CONNECT, CONNACK */ + MQTT_PROP_WILDCARD_SUB_AVAILABLE = 40, /* Byte : CONNACK */ + MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE = 41, /* Byte : CONNACK */ + MQTT_PROP_SHARED_SUB_AVAILABLE = 42, /* Byte : CONNACK */ +}; + +enum mqtt5_property_type { + MQTT_PROP_TYPE_BYTE = 1, + MQTT_PROP_TYPE_INT16 = 2, + MQTT_PROP_TYPE_INT32 = 3, + MQTT_PROP_TYPE_VARINT = 4, + MQTT_PROP_TYPE_BINARY = 5, + MQTT_PROP_TYPE_STRING = 6, + MQTT_PROP_TYPE_STRING_PAIR = 7 +}; + +/* Enum: mqtt5_sub_options + * Options for use with MQTTv5 subscriptions. + * + * MQTT_SUB_OPT_NO_LOCAL - with this option set, if this client publishes to + * a topic to which it is subscribed, the broker will not publish the + * message back to the client. + * + * MQTT_SUB_OPT_RETAIN_AS_PUBLISHED - with this option set, messages + * published for this subscription will keep the retain flag as was set by + * the publishing client. The default behaviour without this option set has + * the retain flag indicating whether a message is fresh/stale. + * + * MQTT_SUB_OPT_SEND_RETAIN_ALWAYS - with this option set, pre-existing + * retained messages are sent as soon as the subscription is made, even + * if the subscription already exists. This is the default behaviour, so + * it is not necessary to set this option. + * + * MQTT_SUB_OPT_SEND_RETAIN_NEW - with this option set, pre-existing retained + * messages for this subscription will be sent when the subscription is made, + * but only if the subscription does not already exist. + * + * MQTT_SUB_OPT_SEND_RETAIN_NEVER - with this option set, pre-existing + * retained messages will never be sent for this subscription. + */ +enum mqtt5_sub_options { + MQTT_SUB_OPT_NO_LOCAL = 0x04, + MQTT_SUB_OPT_RETAIN_AS_PUBLISHED = 0x08, + MQTT_SUB_OPT_SEND_RETAIN_ALWAYS = 0x00, + MQTT_SUB_OPT_SEND_RETAIN_NEW = 0x10, + MQTT_SUB_OPT_SEND_RETAIN_NEVER = 0x20, +}; + +#define MQTT_MAX_PAYLOAD 268435455U + +#endif diff --git a/mqttclient/subdir.mk b/mqttclient/subdir.mk new file mode 100644 index 0000000..21e083d --- /dev/null +++ b/mqttclient/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../mqttclient/SH_MqttClient.cpp + +CPP_DEPS += \ +./mqttclient/SH_MqttClient.d + +OBJS += \ +./mqttclient/SH_MqttClient.o + + +# Each subdirectory must supply rules for building sources it contributes +mqttclient/%.o: ../mqttclient/%.cpp mqttclient/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-mqttclient + +clean-mqttclient: + -$(RM) ./mqttclient/SH_MqttClient.d ./mqttclient/SH_MqttClient.o + +.PHONY: clean-mqttclient + diff --git a/platform/SH_PlatformInit.cpp b/platform/SH_PlatformInit.cpp new file mode 100644 index 0000000..d80e1d6 --- /dev/null +++ b/platform/SH_PlatformInit.cpp @@ -0,0 +1,376 @@ +#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; +int GlobalConfig::net0Status = 1; + + +std::string GlobalConfig::Version = "3.2.5"; +std::string GlobalConfig::MacAddr_G = ""; +std::string GlobalConfig::MacAddr_G2 = ""; +std::string GlobalConfig::IpAddr_G = ""; +std::string GlobalConfig::ServerIP = ""; +std::string GlobalConfig::NetStatus = ""; +std::string GlobalConfig::NetType = ""; +std::string GlobalConfig::NR5GTemp = ""; +int GlobalConfig::serverStatus = 0; +int GlobalConfig::NetSignal = 0; +int GlobalConfig::ServerPort = 0; +int GlobalConfig::threadStatus = 1; +int GlobalConfig::day = 0; + +extern map g_mapCompress; + +TopicList GlobalConfig::Topic_G; +ZigbeeInfo GlobalConfig::ZigbeeInfo_G; +ZIGBEE GlobalConfig::Zigbee_G; +GPIOInfo GlobalConfig::GPIO_G; +std::string GlobalConfig::DbName_G = "/opt/configenv/cidn.db"; //数据库名称 +std::string GlobalConfig::Config_G = "/opt/configenv/config.ini"; +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("eth0"); + GlobalConfig::MacAddr_G2 = GetLocalMac("eth1"); + transform(GlobalConfig::MacAddr_G.begin(), GlobalConfig::MacAddr_G.end(), GlobalConfig::MacAddr_G.begin(), ::toupper); + transform(GlobalConfig::MacAddr_G2.begin(), GlobalConfig::MacAddr_G2.end(), GlobalConfig::MacAddr_G2.begin(), ::toupper); + GlobalConfig::IpAddr_G = IpAddrInit(); + print_info("GlobalConfig::IpAddr_G : %s\n", GlobalConfig::IpAddr_G.c_str()); + this->ConfigFileCheck(); + print_info("ConfigFileCheck\n"); + this->TopicInit(); + print_info("TopicInit\n"); + this->ServerIpInit(); + print_info("TopicInit\n"); + this->Sqlite3Init(); + this->GPIOInit(); + + print_info("ServerIP : %s \n", GlobalConfig::ServerIP.c_str()); + std::string strMac = sql_ctl->GetData("t_gateway_info","gatewayMAC",NULL); + if(strMac == "60294D208517"){ + char szUpdateSql[100]={0x00}; + sprintf(szUpdateSql,"gatewayMAC = '%s'",GlobalConfig::MacAddr_G.c_str()); + sql_ctl->UpdateTableData("t_gateway_info",szUpdateSql,NULL); + } + else if(strMac != GlobalConfig::MacAddr_G ){ + LOG_ERROR("MAC error strMac1 = %s,MacAddr_G1 = %s\n",strMac.c_str(),GlobalConfig::MacAddr_G.c_str()); + strMac.insert(2,":"); + strMac.insert(5,":"); + strMac.insert(8,":"); + strMac.insert(11,":"); + strMac.insert(14,":"); + ModifyMac((char*)strMac.c_str()); + //system("reboot"); + } +#ifdef G2UL_GATEWAY + std::string strMac2 = sql_ctl->GetData("t_gateway_info","MAC2",NULL); + if(strMac2 == "60294D208518"){ + char szUpdateSql[100]={0x00}; + sprintf(szUpdateSql,"MAC2 = '%s'",GlobalConfig::MacAddr_G2.c_str()); + sql_ctl->UpdateTableData("t_gateway_info",szUpdateSql,NULL); + } + else if(strMac2 != GlobalConfig::MacAddr_G2 ){ + LOG_ERROR("MAC error strMac2 = %s,MacAddr_G2 = %s\n",strMac2.c_str(),GlobalConfig::MacAddr_G2.c_str()); + strMac2.insert(2,":"); + strMac2.insert(5,":"); + strMac2.insert(8,":"); + strMac2.insert(11,":"); + strMac2.insert(14,":"); + ModifyMac((char*)strMac2.c_str()); + //system("reboot"); + } +#endif + + // sleep(10); + } catch(...){ + print_error("PlatFormInit exception happend.\n"); + std::string errorinfo = "系统初始化异常"; + } + vec_t vecResult = sql_ctl->GetDataMultiLineOfOneColumn(T_SENSOR_INFO(TNAME)," zigbeeShortAddr ",NULL); + for (size_t i = 0; i < vecResult.size(); i++) + { + compressWaveChannel tempchannel; + g_mapCompress.insert(std::make_pair(vecResult[0],tempchannel)); + } + +} + +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/configureInfo/" + 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.mPubTiming = "equipment/cmd/" + 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 = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str()); + } + +} + +void PlatformInit::Sqlite3Init() +{ + sql_ctl->OpenDB(GlobalConfig::DbName_G.c_str()); + char szValue[10] = {0x00}; + int nType = readIntValue( "Update", "type",(char*)GlobalConfig::Config_G.c_str()); + if(nType== 1){ + sql_ctl->SqliteInitDel(GlobalConfig::DbName_G.c_str()); + writeIntValue("Update", "type",0,(char*)GlobalConfig::Config_G.c_str()); + } + print_info("szValue = %d\n",nType); + sql_ctl->SqliteInit(GlobalConfig::DbName_G.c_str()); + print_info("Sqlite3Init \n"); +} + +void PlatformInit::GPIOInit() +{ +#ifdef G2UL_GATEWAY + GlobalConfig::GPIO_G.zigAckrep = 507; + GlobalConfig::GPIO_G.zigAckreset = 499; + GlobalConfig::GPIO_G.zigReset = 496; + GlobalConfig::GPIO_G.commPower = 363; + GlobalConfig::GPIO_G.vol3_8 = 498; + GlobalConfig::GPIO_G.commRest = 466; + GlobalConfig::GPIO_G.wifiPower = 488; + GlobalConfig::GPIO_G.wifiReset = 474; + GlobalConfig::GPIO_G.hardWatchDog = 497; + GlobalConfig::GPIO_G.zigDef = 408; + GlobalConfig::GPIO_G.runLed = 409; + GlobalConfig::GPIO_G.errorLed = 410; + GlobalConfig::GPIO_G.netResetNet0 = 489; +#else if IMX6UL_GATEWAY + GlobalConfig::GPIO_G.zigAckrep = 119; + GlobalConfig::GPIO_G.zigAckreset = 120; + GlobalConfig::GPIO_G.zigReset = 116; + GlobalConfig::GPIO_G.wifiReset = 8; + GlobalConfig::GPIO_G.commRest = 8; + GlobalConfig::GPIO_G.power = 9; + GlobalConfig::GPIO_G.errorLed = 130; +#endif +} +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(std::string eth) +{ + //eth0 初始化 + int flag = 0; + std::string networkPortStatus = ReadStrByOpt(NETWORKCONFIG, eth, "networkPortStatus"); + std::string subnetMask = ReadStrByOpt(NETWORKCONFIG, eth, "subnetMask"); + std::string gateway = ReadStrByOpt(NETWORKCONFIG, eth, "gateway"); + std::string dataWatchIpAddress = ReadStrByOpt(NETWORKCONFIG, eth, "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 = ""; +#ifdef IMX6UL_GATEWAY + 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"); +#endif +#ifdef G2UL_GATEWAY + if(eth == "eth0"){ + system("sed -i '5c DHCP=ipv4' /etc/systemd/network/static/10-eth0-static.network"); + system("sed -i '6c ' /etc/systemd/network/static/10-eth0-static.network"); + system("sed -i '7c ' /etc/systemd/network/static/10-eth0-static.network"); + }else if(eth == "eth1"){ + system("sed -i '5c DHCP=ipv4' /etc/systemd/network/dynamic/20-eth1-dynamic.network"); + system("sed -i '6c ' /etc/systemd/network/dynamic/20-eth1-dynamic.network"); + system("sed -i '7c ' /etc/systemd/network/dynamic/20-eth1-dynamic.network"); + } +#endif + flag = 0; + } + if(0 == networkPortStatus.compare("STATIC")) + { + std::string cmd = ""; + print_red("static config\n"); +#ifdef IMX6UL_GATEWAY + 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(); +#endif +#ifdef G2UL_GATEWAY + if(eth == "eth0"){ + cmd = "sed -i '5c Address=" + dataWatchIpAddress + "' /etc/systemd/network/static/10-eth0-static.network"; + system(cmd.c_str()); + cmd = "sed -i '6c Netmask=" + subnetMask + "' /etc/systemd/network/static/10-eth0-static.network"; + system(cmd.c_str()); + cmd = "sed -i '7c Gateway=" + gateway + "' /etc/systemd/network/static/10-eth0-static.network"; + system(cmd.c_str()); + }else if(eth == "eth1"){ + cmd = "sed -i '5c Address=" + dataWatchIpAddress + "' /etc/systemd/network/dynamic/20-eth1-dynamic.network"; + system(cmd.c_str()); + cmd = "sed -i '6c Netmask=" + subnetMask + "' /etc/systemd/network/dynamic/20-eth1-dynamic.network"; + system(cmd.c_str()); + cmd = "sed -i '7c Gateway=" + gateway + "' /etc/systemd/network/dynamic/20-eth1-dynamic.network"; + system(cmd.c_str()); + } +#endif + flag = 1; + } +#ifdef IMX6UL_GATEWAY + + + system("reboot"); + +#endif +#ifdef G2UL_GATEWAY + system("systemctl restart systemd-networkd.service"); +#endif +} + diff --git a/platform/SH_PlatformInit.hpp b/platform/SH_PlatformInit.hpp new file mode 100644 index 0000000..0734532 --- /dev/null +++ b/platform/SH_PlatformInit.hpp @@ -0,0 +1,68 @@ +#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(std::string eth); + + void GPIOInit(); +private: + + /** + * @brief mqtt主题初始化 + * @return void + */ + void TopicInit(); + +}; + +#endif diff --git a/platform/subdir.mk b/platform/subdir.mk new file mode 100644 index 0000000..c946d0d --- /dev/null +++ b/platform/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../platform/SH_PlatformInit.cpp + +CPP_DEPS += \ +./platform/SH_PlatformInit.d + +OBJS += \ +./platform/SH_PlatformInit.o + + +# Each subdirectory must supply rules for building sources it contributes +platform/%.o: ../platform/%.cpp platform/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-platform + +clean-platform: + -$(RM) ./platform/SH_PlatformInit.d ./platform/SH_PlatformInit.o + +.PHONY: clean-platform + diff --git a/searchdev/SH_SearchDev.cpp b/searchdev/SH_SearchDev.cpp new file mode 100644 index 0000000..ea4e66d --- /dev/null +++ b/searchdev/SH_SearchDev.cpp @@ -0,0 +1,149 @@ +#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["dataWatchNo"] = GlobalConfig::MacAddr_G.c_str(); + jsData["localServerIpAddress"] = GlobalConfig::IpAddr_G; + jsData["status"] = "ACK"; + jsData["DeviceType"] = "WirelessGateWay"; + 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; + } + }else{ + print_error("parse error\n"); + } + 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/searchdev/subdir.mk b/searchdev/subdir.mk new file mode 100644 index 0000000..600efaa --- /dev/null +++ b/searchdev/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../searchdev/SH_SearchDev.cpp + +CPP_DEPS += \ +./searchdev/SH_SearchDev.d + +OBJS += \ +./searchdev/SH_SearchDev.o + + +# Each subdirectory must supply rules for building sources it contributes +searchdev/%.o: ../searchdev/%.cpp searchdev/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-searchdev + +clean-searchdev: + -$(RM) ./searchdev/SH_SearchDev.d ./searchdev/SH_SearchDev.o + +.PHONY: clean-searchdev + 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/secure/subdir.mk b/secure/subdir.mk new file mode 100644 index 0000000..0773eb9 --- /dev/null +++ b/secure/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../secure/SH_Secure.cpp + +CPP_DEPS += \ +./secure/SH_Secure.d + +OBJS += \ +./secure/SH_Secure.o + + +# Each subdirectory must supply rules for building sources it contributes +secure/%.o: ../secure/%.cpp secure/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-secure + +clean-secure: + -$(RM) ./secure/SH_Secure.d ./secure/SH_Secure.o + +.PHONY: clean-secure + diff --git a/serial/serial.c b/serial/serial.c new file mode 100644 index 0000000..3f9102c --- /dev/null +++ b/serial/serial.c @@ -0,0 +1,503 @@ +/* + * A library for Linux serial communication + * + * Author: JoStudio, 2016 + * + * Version: 0.5 + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "serial.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef CMSPAR +#define CMSPAR 010000000000 +#endif + + + +/* + * convert baud_rate to speed_t + */ +static speed_t get_speed(unsigned int baud_rate) +{ + switch (baud_rate) { + case 0: + return B0; + case 50: + return B50; + case 75: + return B75; + case 110: + return B110; + case 150: + return B150; + case 200: + return B200; + case 300: + return B300; + case 600: + return B600; + case 1200: + return B1200; + case 1800: + return B1800; + case 2400: + return B2400; + case 4800: + return B4800; + case 9600: + return B9600; + case 19200: + return B19200; + case 38400: + return B38400; + case 57600: + return B57600; + case 115200: + return B115200; + case 230400: + return B230400; + case 460800: + return B460800; + case 500000: + return B500000; + case 576000: + return B576000; + case 921600: + return B921600; + case 1000000: + return B1000000; + case 1152000: + return B1152000; + case 1500000: + return B1500000; + case 2000000: + return B2000000; + case 2500000: + return B2500000; + case 3000000: + return B3000000; + case 3500000: + return B3500000; + case 4000000: + return B4000000; + default: + //unsupported baud rate + return 0; + } +} + + +/** + * set baud rate of serial port + * + * @param file_descriptor file descriptor of serial device + * @param baud_rate baud rate + * + * @return 1 if success + * return negative error code if fail + */ +int serial_set_baud_rate(int file_descriptor, int baud_rate) { +/* struct termios termio; + speed_t speed; + int fd = file_descriptor; + + if ( fd < 0 ) { + return SERIAL_INVALID_FILE; + } + + memset(&termio, 0, sizeof(termio)); + + //get old attribute + if (tcgetattr(fd, &termio)) { + return SERIAL_INVALID_RESOURCE; + } + + //calculate baud rate + speed = get_speed(baud_rate); + if (speed == 0) { + return SERIAL_ERROR_BAUDRATE; + } + cfsetispeed(&termio, speed); + cfsetospeed(&termio, speed); + + // set baud rate + if (tcsetattr(fd, TCSAFLUSH, &termio) < 0) { + return SERIAL_ERROR_BAUDRATE; + }*/ + int iFd = file_descriptor; + int len,ret; + struct termios opt; + tcgetattr(iFd, &opt); + cfsetispeed(&opt, B115200); + cfsetospeed(&opt, B115200); + if (tcgetattr(iFd, &opt)<0) { + return -1; + } + opt.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); + opt.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); + opt.c_oflag &= ~(OPOST); + opt.c_cflag &= ~(CSIZE | PARENB | CBAUD); + opt.c_cflag |= (CS8 | B115200); + opt.c_cc[VMIN] = 255; + opt.c_cc[VTIME] = 5; + if (tcsetattr(iFd, TCSANOW, &opt)<0) { + return -1; + } + tcflush(iFd,TCIOFLUSH); + + return 1; +} + + +/** + * set serial attributes + * + * @param file_descriptor file descriptor of serial device + * @param flow_ctrl + * @param data_bits how many bits per data, could be 7, 8, 5 + * @param parity which parity method, could be PARITY_NONE, PARITY_ODD, PARITY_EVEN + * @param stop_bits how many stop bits + * + * @return 1 if success. + * return negative error code if fail. + */ +int serial_set_attr(int file_descriptor, int data_bits, char parity, int stop_bits, int flow_ctrl) +{ + struct termios termio; + int fd = file_descriptor; + + if ( fd < 0 ) { + return SERIAL_INVALID_FILE; + } + + memset(&termio, 0, sizeof(termio)); + + if (tcgetattr(fd, &termio)) { + return SERIAL_INVALID_RESOURCE; + } + + //set flow control + switch(flow_ctrl) { + case FLOW_CONTROL_NONE : + termio.c_cflag &= ~CRTSCTS; + break; + case FLOW_CONTROL_HARDWARE : + termio.c_cflag |= CRTSCTS; + break; + case FLOW_CONTROL_SOFTWARE : + termio.c_cflag |= IXON | IXOFF | IXANY; + break; + } + + //set data bit + termio.c_cflag &= ~CSIZE; + switch (data_bits) { + case 8: + termio.c_cflag |= CS8; + break; + case 7: + termio.c_cflag |= CS7; + break; + case 6: + termio.c_cflag |= CS6; + break; + case 5: + termio.c_cflag |= CS5; + break; + default: + termio.c_cflag |= CS8; + break; + } + + //set stop bits + switch (stop_bits) { + case 1: + termio.c_cflag &= ~CSTOPB; + break; + case 2: + termio.c_cflag |= CSTOPB; + break; + default: + break; + } + + //set parity bit + switch (parity) { + case PARITY_NONE: + termio.c_cflag &= ~(PARENB | PARODD); + break; + case PARITY_EVEN: + termio.c_cflag |= PARENB; + termio.c_cflag &= ~PARODD; + break; + case PARITY_ODD: + termio.c_cflag |= PARENB | PARODD; + break; + case PARITY_MARK: + termio.c_cflag |= PARENB | CMSPAR | PARODD; + break; + case PARITY_SPACE: + termio.c_cflag |= PARENB | CMSPAR; + termio.c_cflag &= ~PARODD; + break; + } + + if (tcsetattr(fd, TCSAFLUSH, &termio) < 0) { + return SERIAL_ERROR_SETTING; + } + + return 1; +} + + +/** + * open serial port + * + * @param device_filename device file name, such as "/dev/ttyS0" + * @param baund_rate could be 57600, 38400, 19200, 9600, 4800, 2400, 1200, 300 + * + * @return file descriptor which could be used in read() or write() + * return -1 if failed, and errno is set + */ +int serial_open_file(char *device_filename, int baud_rate) { + int fd; + struct termios termio; + + if ((fd = open(device_filename, O_RDWR | O_NOCTTY )) == -1) { + return -1; + } + + memset(&termio, 0, sizeof(termio)); + + // setup the tty and the selected baud rate + // get current modes + if (tcgetattr(fd, &termio)) { + close(fd); + return -1; + } + + // setup initial mode: 8 bit data, No parity, 1 stop bit, no echo, no flow control + cfmakeraw(&termio); + if (tcsetattr(fd, TCSAFLUSH, &termio) < 0) { + close(fd); + return -1; + } + + if (serial_set_baud_rate(fd, baud_rate) != 1) { + close(fd); + return -1; + } + + return fd; +} + +/** + * open serial port + * + * @param file_descriptor file descriptor of serial device + * @param timeout timeout in second + * + * @return 1 if success + * return negative error code if fail + */ +int serial_set_timeout(int file_descriptor, int timeout) +{ + int fd = file_descriptor; + struct termios termio; + + if (fd < 0) { + return SERIAL_INVALID_FILE; + } + + + // get current attributes + if (tcgetattr(fd, &termio)) { + return SERIAL_INVALID_RESOURCE; + } + + //set read timeout + if (timeout > 0) { + timeout = timeout / 100; + if (timeout == 0) + timeout = 1; + } + termio.c_lflag &= ~ICANON; /* Set non-canonical mode */ + termio.c_cc[VTIME] = timeout; /* Set timeout in tenth seconds */ + if (tcsetattr(fd, TCSANOW, &termio) < 0) { + return SERIAL_ERROR_SETTING; + } + + return 1; +} + + +/** + * open serial port + * + * @param port number of port, could be 0, 1 ... , the device file is /dev/ttyS0, /dev/ttyS1 respectively + * @param baund_rate could be 57600, 38400, 19200, 9600, 4800, 2400, 1200, 300 + * + * @return file descriptor which could be used in read() or write() + * return -1 if failed, and errno is set + */ +int serial_open(char* port, int baud_rate) { + char buf[128]; + + snprintf(buf, sizeof(buf), "/dev/ttyS%d", port); + return serial_open_file(port, baud_rate); +} + + +/** + * close serial port + * + * @param file_descriptor file descriptor of serial port device file + * + * @return 0 if success. + * return -1 if failed, and errno is set. + */ +int serial_close(int file_descriptor) { + return close(file_descriptor); +} + + +/** + * The function waits until all queued output to the terminal filedes has been transmitted. + * + * tcdrain() is called. + + * @param file_descriptor file descriptor of serial port device file + * + * @return 0 if success. + * return -1 if fail, and errno is set. + */ +int serial_flush(int file_descriptor) +{ + return tcdrain(file_descriptor); +} + +/** + * whether data is available + * + * @param file_descriptor file descriptor of serial port device file + * @param timeout_millisec timeout in millisecond + * + * @return 1 if data is available + * return 0 if data is not available + */ +int serial_data_available(int file_descriptor, unsigned int timeout_millisec) +{ + int fd = file_descriptor; + struct timeval timeout; + fd_set readfds; + + if (fd < 0) { + return SERIAL_INVALID_FILE; + } + + if (timeout_millisec == 0) { + // no waiting + timeout.tv_sec = 0; + timeout.tv_usec = 0; + } else { + timeout.tv_sec = timeout_millisec / 1000; + timeout.tv_usec = (timeout_millisec % 1000) * 1000; + } + + FD_ZERO(&readfds); + FD_SET(fd, &readfds); + + if (select(fd + 1, &readfds, NULL, NULL, &timeout) > 0) { + return 1; // data is ready + } else { + return 0; // no data + } +} + + +/** + * send data + * + * @param file_descriptor file descriptor of serial port device file + * @param buffer buffer of data to send + * @param data_len data length + * + * @return positive integer of bytes sent if success. + * return -1 if failed. + */ +int serial_send(int file_descriptor, char *buffer, size_t data_len) +{ + ssize_t len = 0; + len = write(file_descriptor, buffer, data_len); + if ( len == data_len ) { + return len; + } else { + tcflush(file_descriptor, TCOFLUSH); + return -1; + } + +} + +/** + * receive data + * + * @param file_descriptor file descriptor of serial port device file + * @param buffer buffer to receive data + * @param data_len max data length + * + * @return positive integer of bytes received if success. + * return -1 if failed. + */ +int serial_receive(int file_descriptor, char *buffer,size_t data_len) +{ + int len,fs_sel; + fd_set fs_read; + struct timeval time; + int fd = file_descriptor; + + FD_ZERO(&fs_read); + FD_SET(fd, &fs_read); + + time.tv_sec = 10; + time.tv_usec = 0; + + //use select() to achieve multiple channel communication + fs_sel = select(fd + 1, &fs_read, NULL, NULL, &time); + if ( fs_sel ) { + len = read(fd, buffer, data_len); + return len; + } else { + return -1; + } +} + + diff --git a/serial/serial.h b/serial/serial.h new file mode 100644 index 0000000..5e1eb3b --- /dev/null +++ b/serial/serial.h @@ -0,0 +1,193 @@ +/* + * A library for Linux serial communication + * + * Author: JoStudio, 2016 + * + * Version: 0.5 + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef __SERIAL_H__ +#define __SERIAL_H__ + + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* serial error code */ +#define SERIAL_ERROR_OPEN -1 +#define SERIAL_ERROR_READ -2 +#define SERIAL_ERROR_WRITE -3 +#define SERIAL_ERROR_BAUDRATE -4 +#define SERIAL_ERROR_SETTING -5 +#define SERIAL_INVALID_RESOURCE -6 +#define SERIAL_INVALID_FILE -7 + + +/* flow control */ +#define FLOW_CONTROL_NONE 0 +#define FLOW_CONTROL_HARDWARE 1 +#define FLOW_CONTROL_SOFTWARE 2 + +/* parity */ +#define PARITY_NONE 'N' +#define PARITY_EVEN 'E' +#define PARITY_ODD 'O' +#define PARITY_SPACE 'S' +#define PARITY_MARK 'M' + + +/** + * open serial port + * + * @param port number of port, could be 0, 1 ... , the device file is /etc/ttyS0, /etc/ttyS1 respectively + * @param baund_rate could be 57600, 38400, 19200, 9600, 4800, 2400, 1200, 300 + * + * @return file descriptor which could be used in read() or write() + * return -1 if failed, and errno is set + */ +int serial_open(char* port, int baud_rate); + + +/** + * close serial port + * + * @param file_descriptor file descriptor of serial port device file + * + * @return 0 if success. + * return -1 if failed, and errno is set. + */ +int serial_close(int file_descriptor); + +/** + * open serial port + * + * @param device_filename device file name, such as "/etc/ttyS0" + * @param baund_rate could be 57600, 38400, 19200, 9600, 4800, 2400, 1200, 300 + * + * @return file descriptor which could be used in read() or write() + * return -1 if failed, and errno is set + */ +int serial_open_file(char *device_filename, int baud_rate); + + +/** + * set serial attributes + * + * @param file_descriptor file descriptor of serial device + * @param flow_ctrl + * @param data_bits how many bits per data, could be 7, 8, 5 + * @param parity which parity method, could be PARITY_NONE, PARITY_ODD, PARITY_EVEN + * @param stop_bits how many stop bits + * + * @return 1 if success. + * return negative error code if fail. + */ +int serial_set_attr(int file_descriptor, int data_bits, char parity, int stop_bits, int flow_ctrl); + + +/** + * open serial port + * + * @param file_descriptor file descriptor of serial device + * @param timeout timeout in second + * + * @return 1 if success + * return negative error code if fail + */ +int serial_set_timeout(int file_descriptor, int timeout); + + +/** + * set baud rate of serial port + * + * @param file_descriptor file descriptor of serial device + * @param baud_rate baud rate + * + * @return 1 if success + * return negative error code if fail + */ +int serial_set_baud_rate(int file_descriptor, int baud_rate) ; + + + + +/** + * The function waits until all queued output to the terminal filedes has been transmitted. + * + * tcdrain() is called. + + * @param file_descriptor file descriptor of serial port device file + * + * @return 0 if success. + * return -1 if fail, and errno is set. + */ +int serial_flush(int file_descriptor); + +/** + * whether data is available + * + * @param file_descriptor file descriptor of serial port device file + * @param timeout_millisec timeout in millisecond + * + * @return 1 if data is available + * return 0 if data is not available + */ +int serial_data_available(int file_descriptor, unsigned int timeout_millisec); + + +/** + * send data + * + * @param file_descriptor file descriptor of serial port device file + * @param buffer buffer of data to send + * @param data_len data length + * + * @return positive integer of bytes sent if success. + * return -1 if failed. + */ +int serial_send(int file_descriptor, char *buffer, size_t data_len); + + + +/** + * receive data + * + * @param file_descriptor file descriptor of serial port device file + * @param buffer buffer to receive data + * @param data_len max data length + * + * @return positive integer of bytes received if success. + * return -1 if failed. + */ +int serial_receive(int file_descriptor, char *buffer,size_t data_len); + + + +#ifdef __cplusplus +} +#endif + + +#endif /* __SERIAL_H__ */ diff --git a/serial/subdir.mk b/serial/subdir.mk new file mode 100644 index 0000000..af81255 --- /dev/null +++ b/serial/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +C_SRCS += \ +../serial/serial.c + +C_DEPS += \ +./serial/serial.d + +OBJS += \ +./serial/serial.o + + +# Each subdirectory must supply rules for building sources it contributes +serial/%.o: ../serial/%.c serial/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross GCC Compiler' + arm-linux-gnueabihf-gcc -O0 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-serial + +clean-serial: + -$(RM) ./serial/serial.d ./serial/serial.o + +.PHONY: clean-serial + diff --git a/threadfunc/SH_ThreadFunc.cpp b/threadfunc/SH_ThreadFunc.cpp new file mode 100644 index 0000000..019ca0d --- /dev/null +++ b/threadfunc/SH_ThreadFunc.cpp @@ -0,0 +1,1031 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "SH_ThreadFunc.hpp" +#include "../API_log/SH_log.h" +#include "../uart/SH_Uart.hpp" +#include "../common/SH_CommonFunc.hpp" +#include "../dial5G/Dial.h" +#include "../wifi/wpa_client.h" +#include + +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 + +Dial dial; + +void CheckThread() +{ + print_info("ENTER CHECK THREAD \n"); + std::string runinfo = "ENTER CHECK THREAD "; + LOG_INFO(runinfo.c_str()); + int heart_count = 0; + + int time_check = 0; + int reset_flag = 0; + int online_check = 0; + int HardStatus = 0; + int logClean = 0; + int Battery = 0; + int UpdateZigbee = 0; + int commSignal = 0; + int loose_check = 0; + int mqttresend = 0; + int rebootsystem = 0; + int ModifyAddr = 0; + int wifi_reconnect_count = 0; + int checkNet0 = 0; + int connectCount = 0; + + while (GlobalConfig::QuitFlag_G) { + GlobalConfig::threadStatus = 1; + sleep(1); + 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->modify_LocalAddr(0x8888); + GlobalConfig::Zigbee_G.MyAddr = 0x8888; + // 延时1秒 + sleep(1); + // 重新读回 GlobalConfig::ZigbeeInfo_G.PanID + pUart->UpdateZigbeeInfoCtrl(); + pUart->bUpdateconfig = false; + pUart->bUpdate = false; + pUart->bSendTimeStamp = false; + // 延时1秒 + sleep(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"); + } + } + continue; + } + if (10 == heart_count) { + if (GlobalConfig::LinkCount > 30) { + LOG_ERROR("MQTT connect failed\n"); +#ifdef IMX6UL_GATEWAY + char connect[10]={0x00}; + readStringValue("config", "connect",connect,(char*)GlobalConfig::Config_G.c_str()); + if(atoi(connect)){ + LOG_ERROR("MQTT connect failed,reboot\n"); + exit(0); + } +#endif + } + std::string ipTemp = IpAddrInit(); + GlobalConfig::IpAddr_G = ipTemp; + if ( 0 != ipTemp.compare(GlobalConfig::IpAddr_G)) { + //exit(0); + } + heart_count = 0; + } +#ifdef G2UL_GATEWAY + if(checkNet0 == 5){ + checkNet0 = 0; + int iStatus = get_netlink_status("eth0"); + if(iStatus == 1 && GlobalConfig::net0Status == 0){ + system("ifconfig eth0:1 192.168.188.188 netmask 255.255.255.0"); + } + GlobalConfig::net0Status = iStatus; + } +#endif + if (7200 == time_check) {//2h + char buf[256] = {0}; + char buf2[256] = {0}; + sprintf(buf, "{\"dataNodeGatewayNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}", + GlobalConfig::MacAddr_G.c_str()); + sprintf(buf2, "{\"dataWatchNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}", + GlobalConfig::MacAddr_G.c_str()); + std::string str = std::string(buf); + std::string str2 = std::string(buf2); + time_check = 0; + int iRet = data_publish(str.c_str(), GlobalConfig::Topic_G.mPubTiming.c_str()); + iRet = data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + iRet = data_publish(str2.c_str(), GlobalConfig::Topic_G.mPubTiming.c_str()); + iRet = data_publish(str2.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + if(iRet != 0 ) + { + LOG_ERROR("MQTT connect failed ,time check\n"); +#ifdef IMX6UL_GATEWAY + char connect[10]={0x00}; + readStringValue("config", "connect",connect,(char*)GlobalConfig::Config_G.c_str()); + if(atoi(connect)){ + LOG_ERROR("MQTT connect failed,time check ,reboot\n"); + exit(0); + } +#endif +#ifdef NR5G_MODULE +#ifdef IMX6UL_GATEWAY + dial.closePort(); + gpio_set(GlobalConfig::GPIO_G.commRest,0); + LOG_DEBUG("GPIO 8 start\n"); + sleep(2); + gpio_set(GlobalConfig::GPIO_G.commRest,1); + LOG_DEBUG("GPIO 8 End\n"); + sleep(20); + dial.openPort("/dev/ttyUSB2"); + dial.setState(); +#endif +#ifdef G2UL_GATEWAY + dial.closePort(); + gpio_set(GlobalConfig::GPIO_G.commPower,0); + LOG_DEBUG("commPower start\n"); + sleep(2); + gpio_set(GlobalConfig::GPIO_G.commPower,1); + LOG_DEBUG("commPower End\n"); + sleep(20); + connectCount ++; + if(connectCount > 10){ + LOG_ERROR("5G reset error ,reboot!\n"); + system("reboot"); + } +#ifndef NR5G_MEIGE + dial.openPort("/dev/ttyUSB2"); + dial.setState(); +#else + char szquectel[100]={0x00}; + std::string strAPN = ReadStrByOpt(SERVERCONFIG, "Server", "APN"); + sprintf(szquectel,"/opt/quectel-CM/Meig-CM -s %s &",strAPN.c_str()); + system(szquectel); +#endif +#endif +#endif +#ifdef WIFI_MODULE + LOG_ERROR("WiFi reset!\n"); +#ifdef IMX6UL_GATEWAY + gpio_set(GlobalConfig::GPIO_G.wifiReset,0); + sleep(5); + gpio_set(GlobalConfig::GPIO_G.wifiReset,1); + sleep(5); + wifi::WPAClient wpa; + wpa.ReconnectWiFi(); + system("/etc/init.d/wpa_restart"); + system("udhcpc -i wlan2 &"); +#endif +#ifdef G2UL_GATEWAY + system("/etc/init.d/wpa_restart"); + sleep(5); + string strip = GetGwIp_("wlan0"); + print_info("strip = %s\n",strip.c_str()); + if (strip.compare("0.0.0.0") != 0) { + + }else{ + gpio_set(GlobalConfig::GPIO_G.wifiReset,1); + sleep(5); + gpio_set(GlobalConfig::GPIO_G.wifiReset,0); + sleep(30); + wifi::WPAClient wpa; + wpa.ReconnectWiFi(); + system("/etc/init.d/wpa_restart"); + sleep(5); + system("udhcpc -b -i wlan0 &"); + } +#endif +#endif + }else{ + connectCount = 0; + } + } + if(HardStatus == 3600){//one hour 3600 + JsonData jd; + std::string data = jd.JsonCmd_07(); + data_publish(data.c_str(), GlobalConfig::Topic_G.mPubStatus.c_str()); + HardStatus = 0; + int hour = 0; + struct tm *tm_info = get_current_date(); + hour = tm_info->tm_hour; + print_info("hour = %d\n",hour); + int statistics = readIntValue( "config", "statistics",(char*)GlobalConfig::Config_G.c_str()); + if(statistics == 0 && hour > 13 ){ + writeIntValue("config", "statistics",1,(char*)GlobalConfig::Config_G.c_str()); + sql_ctl->CalculateData(); + }else if(statistics == 1 && hour < 13){ + writeIntValue("config", "statistics",0,(char*)GlobalConfig::Config_G.c_str()); + } + + } + if(mqttresend == 7200){ + mqttresend = 0; + LOG_INFO("mqttresend check\n"); + Json::Value jsHeart; + Json::FastWriter fw; + jsHeart["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsHeart["status"] = "online_V" + GlobalConfig::Version; + jsHeart["IP"] = GlobalConfig::IpAddr_G; + std::string strJson = fw.write(jsHeart); + int iRet = data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubHeart.c_str()); + if(iRet == 0){ + sql_ctl->QueryofflineData(); + } + + } + + if (600 == online_check) { + online_check = 0; + int Count = sql_ctl->GetTableRows(T_SENSOR_INFO(TNAME), NULL); + if(Count > 0){ + JsonData jd; + jd.DataNodeStatusCheck(); + Param_29 param; + std::string cmd29 = jd.JsonCmd_29(param); + int iRet = data_publish(cmd29.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + char selectCon[128] = { 0 }; + sprintf(selectCon, " sendMsg <> '' ORDER BY timeStamp DESC LIMIT 0,1"); + sleep(1); + std::string strTime = sql_ctl->GetData(T_DATASTATIC_INFO(TNAME), "timeStamp", selectCon); + long lTime = atol(nowTimetamp.c_str())-atol(strTime.c_str()); + LOG_INFO("online check = %d\n",lTime); + if(lTime > 1800){ + LOG_ERROR("nowTimetamp = %s,lastTime = %s,lTime = %d\n",nowTimetamp.c_str(),strTime.c_str(),lTime); + } + } + } + if(7200 == Battery){ + Battery = 0; + LOG_INFO("Battery\n"); + sql_ctl->CalculateBattery(); + } + + if(3500 == loose_check){ + LOG_INFO("loosecheck\n"); + loose_check = 0; + sql_ctl->CalculateDip(); + } + if(ModifyAddr == 3600) { + LOG_INFO("ModifyAddr check\n"); + ModifyAddr = 0; + if(pUart->bModifyAddr){ + LOG_ERROR("ModifyAddr failed \n"); + exit(0); + } + } + + if(18000 == commSignal){ //5h + Json::Value jsBody,jsonVal; + Json::FastWriter showValue; + if(GlobalConfig::NetStatus == "\"NOCONN\"" || GlobalConfig::NetStatus == "\"CONNECT\""){ + if(GlobalConfig::NetSignal == 0){ + jsBody["communicationSignal"] = "未知"; + } + else if(GlobalConfig::NetSignal > -80){ + jsBody["commSignal"] = "优"; + }else if(GlobalConfig::NetSignal > -90 && GlobalConfig::NetSignal < -80){ + jsBody["commSignal"] = "良"; + }else if(GlobalConfig::NetSignal > -105 && GlobalConfig::NetSignal < -90){ + jsBody["commSignal"] = "一般"; + }else if(GlobalConfig::NetSignal < -105){ + jsBody["commSignal"] = "弱"; + }else if(GlobalConfig::NetSignal < -115){ + jsBody["commSignal"] = "不稳定"; + } + + }else if(GlobalConfig::NetStatus == "\"SEARCH\""){ + jsBody["commSignal"] = "搜索网络"; + }else if(GlobalConfig::NetStatus == "\"LIMSRV\""){ + jsBody["commSignal"] = "未插卡"; + }else{ + jsBody["commSignal"] = "未知"; + } + + jsonVal["cmd"] = "53"; + std::string dataBody = showValue.write(jsBody); + jsonVal["cmdBody"] = dataBody; + data_publish(showValue.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + } + if(21600 == logClean){ + logClean = 0; + DIR *dp; //创建一个指向root路径下每个文件的指针 + struct dirent *dirp; + string root="/opt/log/"; + if((dp = opendir(root.c_str()))==NULL) + cout << "can't open"<< root << endl; + while((dirp = readdir(dp)) != NULL){ + + if((!strcmp(dirp->d_name,".")||(!strcmp(dirp->d_name,"..")))) + continue; + struct timeval curTime; + gettimeofday(&curTime, NULL); + char buffer[80] = {0}; + char fileMonth[11] = {0}; + char todayMonth[11]={0}; + char fileDay[11] = {0}; + char todayDay[11]={0}; + struct tm nowTime; + localtime_r(&curTime.tv_sec, &nowTime);//把得到的值存入临时分配的内存中,线程安全 + strftime(buffer, sizeof(buffer), "%Y-%m-%d", &nowTime); + memcpy(fileDay,dirp->d_name+8,2); + memcpy(todayDay,buffer+8,2); + memcpy(fileMonth,dirp->d_name+5,2); + memcpy(todayMonth,buffer+5,2); + string filename = root + string(dirp->d_name); + if(atoi(fileMonth) == atoi(todayMonth) ? abs(atoi(todayDay) - atoi(fileDay)) > 15: abs(abs(30-(atoi(fileDay)) + atoi(todayDay))) > 15){ + LOG_INFO("filename = %s\n",filename.c_str()); + remove(filename.c_str()); + } + + } + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + char whereCon[1024] = {0}; +#ifdef G2UL_GATEWAY + sprintf(whereCon," timestamp < '%ld' ",atol(localtimestamp) - 2592000 * 2); //删除2个月前的数据 +#endif +#ifdef IMX6UL_GATEWAY + sprintf(whereCon," timestamp < '%ld' ",atol(localtimestamp) - 2592000); //删除1个月前的数据 +#endif + sql_ctl->DeleteTableData(" t_battery_history ",whereCon); + /*staticData = 0; + Json::Value jsHeart; + Json::FastWriter fw; + jsHeart["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsHeart["status"] = "online"; + std::string strJson = fw.write(jsHeart); + int iRet = data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubHeart.c_str()); + if(iRet == 0){ + JsonData jd; + std::string data = jd.JsonCmd_52(); + } + double freeDisk = GetHardDiskFree(); + if(freeDisk < 90){ + char whereCon[512] = {0x00}; + time_t timestamp; + long timeStamp = time(×tamp) ;//秒级时间戳 + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon,"sendMsg = '0' and timeStamp < '%s'",timeStamp-1); //1 week + sql_ctl->DeleteTableData(T_DATA_INFO(TNAME),whereCon,0); + sql_ctl->DeleteTableData(T_DATASTATIC_INFO(TNAME),whereCon,0); + }*/ + + } +#ifdef WIFI_MODULE + if (wifi_reconnect_count == 600) { // 每 10分钟,重连WiFi网络 + wifi_reconnect_count = 0; + wifi::WPAClient wpa; + std::string netssid = wpa.GetNetSsid(); + std::string currentssid = ""; + if (0 == netssid.compare("")) { + netssid = wpa.GetNetSsid(); + } + + if (netssid.length() > 0) { + currentssid = wpa.GetCurrentSSID(); + if (currentssid.length() > 0) { + char buf[64] = {0}; + std::string rssiSend = ""; +#ifdef G2UL_GATEWAY + rssiSend = "/usr/sbin/wpa_cli signal_poll|grep RSSI | cut -f 2 -d '='"; +#endif + +#ifdef IMX6UL_GATEWAY + rssiSend = "/opt/Cidn/wpa_cli signal_poll|grep RSSI | cut -f 2 -d '='"; +#endif + system_custom(rssiSend.c_str(), buf); + std::string Rssi = std::string(buf); + + memset(buf, 0, 64); + sprintf(buf, "wifi:true Rssi:%s", Rssi.c_str()); + print_info("%s\n", buf); + LOG_INFO("%s\n",buf); + + } else { + std::string runinfo = "wifi:false\n"; + print_info("%s\n", runinfo.c_str()); + } + } + if (wpa.ReconnectWiFi()) { + print_info("wifi reconnect ok\n"); + } + } +#endif + + if ( reset_flag > 7200) { + reset_flag = 0; + //exit(0); + } + Battery ++; + reset_flag++; + time_check++; + heart_count++; + online_check++; + HardStatus ++; + logClean ++ ; + loose_check ++; + ModifyAddr ++; + mqttresend ++; +#ifdef G2UL_GATEWAY + checkNet0 ++; +#endif +#ifdef WIFI_MODULE + wifi_reconnect_count ++; +#endif + + } +} + +void StartCgiServer() +{ + print_info("start deal cgi\n"); + TcpCgi *tcpCgi = TcpCgi::instance(); + while (1) { + tcpCgi->startCgiServer(); + sleep(10); + } +} +void RunLED() +{ + while(1){ + gpio_set(GlobalConfig::GPIO_G.runLed,1); + sleep(1); + gpio_set(GlobalConfig::GPIO_G.runLed,0); + sleep(1); + } +} + +void HeartRep() +{ + int count = 0; + while(1) { + Json::Value jsHeart; + Json::FastWriter fw; + jsHeart["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + jsHeart["status"] = "online_V" + GlobalConfig::Version; + jsHeart["IP"] = GlobalConfig::IpAddr_G; + std::string strJson = fw.write(jsHeart); + int iRet = data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubHeart.c_str()); + print_info("heart = %s,iRet = %d\n",strJson.c_str(),iRet); + if(iRet != 0){ + //count ++; + gpio_set(GlobalConfig::GPIO_G.errorLed,1); + sleep(1); + gpio_set(GlobalConfig::GPIO_G.errorLed,0); + sleep(1); + gpio_set(GlobalConfig::GPIO_G.errorLed,1); + sleep(1); + gpio_set(GlobalConfig::GPIO_G.errorLed,0); + sleep(1); + gpio_set(GlobalConfig::GPIO_G.errorLed,1); + sleep(1); + GlobalConfig::serverStatus = 1; + }else{ + GlobalConfig::serverStatus = 0; + count = 0; + gpio_set(GlobalConfig::GPIO_G.errorLed,0); + } + //gpio_set(GlobalConfig::GPIO_G.errorLed,0); +// if(count > 0){ +// bool status = Ping( GlobalConfig::ServerIP.c_str(), 10000); +// if(status != 0) +// //LOG_INFO("===========net status ========failed heart count %d\n",count); +// if(status != 0 && count > 30){ +// LOG_ERROR("heart send failed,heart count %d\n",count); +// count = 0; +// sleep(20); +// gpio_set(GlobalConfig::GPIO_G.power,1); +// } +// } +// if(count > 1000){ +// gpio_set(GlobalConfig::GPIO_G.power,1); +// count = 0; +// } +// write_data(fd,"AT+QENG=\"servingcell\"\r\n",27); +// //sleep(1); +// char buff[1024]={0x00}; +// int ret = read_data(fd, buff, 1024, 10); +// print_info("ret = %d,buff = %s\n",ret,buff); +// const char *str2 = "+QENG: "; +// char csq[128] = {0}; +// char *pdata = strstr((char*)buff, str2); +// if(pdata){ +// strncpy(csq, pdata+7, sizeof(csq)); +// } +// else { +// } +// +// //printf("SIM-CSQ: %s\n", csq); +// GlobalConfig::NetStatus = GetOneContent(csq,1,","); +// string signal = GetOneContent(csq,13,","); +// GlobalConfig::NetSignal = atoi(signal.c_str()); +// print_info("NetStatus = %s,NetSignal = %d\n",GlobalConfig::NetStatus.c_str(),GlobalConfig::NetSignal); + + //GlobalConfig::NetSignal = getcsq(); + /*if(GlobalConfig::NetSignal <= -105 ){ + gpio_set(130,1); + }else if(GlobalConfig::NetSignal > -105 ){ + gpio_set(130,0); + }else{ + gpio_set(130,1); + }*/ + sleep(10); + //socketHeart(strJson.c_str()); + } +} + +void GetCSQ() +{ +#ifdef NR5G_MODULE + //5G + int iRet = -1; +open5G: + iRet = dial.openPort("/dev/ttyUSB2"); + if (iRet < 0){ + sleep(5); + goto open5G; + } +#ifdef NR5G_MEIGE + dial.closePort(); + char szquectel[100]={0x00}; + std::string strAPN = ReadStrByOpt(SERVERCONFIG, "Server", "APN"); + sprintf(szquectel,"/opt/quectel-CM/Meig-CM -s %s &",strAPN.c_str()); + system(szquectel); +#else + dial.recvData(); +#endif +#endif +#ifdef Q4G_MODULE + //4G + int fd = -1; +open4G: + fd = config_uart("/dev/ttyUSB2",115200); + if (fd < 0){ + sleep(5); + goto open4G; + } + char szbuffer[200]={0x00}; + int offSize = 0; + int timeoutflag = 0; + write_data(fd,"AT+QENG=\"servingcell\"\r\n",27); + while(1){ + char buff[1024]={0x00}; + int ret = read_data(fd, buff, 1024, 10); + if(ret <= 0){ + timeoutflag ++; + if(timeoutflag > 5){ + print_info("timeoutflag = %d\n",timeoutflag); + timeoutflag = 0; + const char *str2 = "+QENG: "; + char csq[128] = {0}; + char *pdata = strstr((char*)szbuffer, str2); + if(pdata){ + strncpy(csq, pdata+7, sizeof(csq)); + + //printf("SIM-CSQ: %s\n", csq); + GlobalConfig::NetStatus = GetOneContent(csq,1,","); + string signal = GetOneContent(csq,13,","); + GlobalConfig::NetSignal = atoi(signal.c_str()); + GlobalConfig::NetType = GetOneContent(csq,2,","); + print_info("NetStatus = %s,NetSignal = %d\n",GlobalConfig::NetStatus.c_str(),GlobalConfig::NetSignal); + + } + memset(szbuffer,0x00,sizeof(szbuffer)); + offSize = 0; + write_data(fd,"AT+QENG=\"servingcell\"\r\n",27); + } + usleep(10000); + }else if(ret > 0){ + print_info("ret = %d,buff = %s\n",ret,buff); + memcpy(szbuffer + offSize,buff,ret); + offSize = offSize + ret; + print_info("szbuffer = %s\n",szbuffer); + continue; + } + sleep(10); + } +#endif +} +void Dial5G() +{ + sleep(2); +dial5G: + if(dial.m_fd > 0){ + dial.dial5G(); + }else{ + sleep(5); + goto dial5G; + } +} +void UartStart() +{ + // onReceiveUart cb = (onReceiveUart)&ProtoConvert::HandleFromUart; + // pUart->setCallBack(cb); + print_info("zigAckrep = %d,zigAckreset = %d,zigReset = %d,errorLed = %d,power = %d",\ + GlobalConfig::GPIO_G.zigAckrep,GlobalConfig::GPIO_G.zigAckreset,GlobalConfig::GPIO_G.zigReset,GlobalConfig::GPIO_G.errorLed,\ + GlobalConfig::GPIO_G.power); + InitGpio(GlobalConfig::GPIO_G.zigAckrep,0);//ACK + InitGpio(GlobalConfig::GPIO_G.zigAckreset,1);//ACK reset + InitGpio(GlobalConfig::GPIO_G.zigReset,1);//Zigbee reset + gpio_set(GlobalConfig::GPIO_G.zigAckreset,1); + gpio_set(GlobalConfig::GPIO_G.zigReset,1); + print_info("GPIO Init1\n"); + +#ifdef IMX6UL_GATEWAY + InitGpio(GlobalConfig::GPIO_G.errorLed,1);//指示灯 + gpio_set(GlobalConfig::GPIO_G.errorLed,0); + InitGpio(GlobalConfig::GPIO_G.power,1);//power reset + gpio_set(GlobalConfig::GPIO_G.power,0); +#endif +#ifdef G2UL_GATEWAY + InitGpio(GlobalConfig::GPIO_G.runLed,1); + InitGpio(GlobalConfig::GPIO_G.errorLed,1); + gpio_set(GlobalConfig::GPIO_G.runLed,1); + gpio_set(GlobalConfig::GPIO_G.errorLed,0); + InitGpio(GlobalConfig::GPIO_G.netResetNet0,1); + gpio_set(GlobalConfig::GPIO_G.netResetNet0,0); +#endif + GlobalConfig::Zigbee_G.Serial_Rate = 0x07; + GlobalConfig::Zigbee_G.Serial_DataB = 0x08; + GlobalConfig::Zigbee_G.Serial_StopB = 0x01; + pUart->InitUart(B115200); + char buffer[1100]={0x00}; + + sleep(1); + pUart->UartRecv(pUart->fd,1,buffer); + sleep(1); + +} +void InitModule() +{ +#ifdef NR5G_MODULE +#ifdef G2UL_GATEWAY + + InitGpio(GlobalConfig::GPIO_G.commPower,1);//4G,5G模组供电, + gpio_set(GlobalConfig::GPIO_G.commPower,1); + InitGpio(GlobalConfig::GPIO_G.vol3_8,1);//5G 高电平3.8V,低电平3.3V + gpio_set(GlobalConfig::GPIO_G.vol3_8,1); + + InitGpio(GlobalConfig::GPIO_G.commRest,1); + gpio_set(GlobalConfig::GPIO_G.commRest,0);//高电平复位 +#endif +#ifdef IMX6UL_GATEWAY + InitGpio(GlobalConfig::GPIO_G.commRest,1); + gpio_set(GlobalConfig::GPIO_G.commRest,1);// +#endif +#endif +#ifdef Q4G_MODULE +#ifdef G2UL_GATEWAY + InitGpio(GlobalConfig::GPIO_G.commPower,1);//4G,5G模组供电, + gpio_set(GlobalConfig::GPIO_G.commPower,1); + InitGpio(GlobalConfig::GPIO_G.commRest,1); + gpio_set(GlobalConfig::GPIO_G.commRest,0);//高电平复位 + sleep(10); + char szquectel[100]={0x00}; + std::string strAPN = ReadStrByOpt(SERVERCONFIG, "Server", "APN"); + sprintf(szquectel,"/opt/quectel-CM/quectel-CM -s %s &",strAPN.c_str()); + system(szquectel); +#endif +#endif +#ifdef WIFI_MODULE + print_info("Init WiFi!\n"); + +#ifdef IMX6UL_GATEWAY + InitGpio(GlobalConfig::GPIO_G.wifiReset,1);//WiFi模组复位,0复位,1取消复位 + gpio_set(GlobalConfig::GPIO_G.wifiReset,1); + sleep(10); + wifi::WPAClient wpa; + wpa.ReconnectWiFi(); + system("/etc/init.d/wpa_restart"); + system("udhcpc -i wlan2 &"); +#endif +#ifdef G2UL_GATEWAY + InitGpio(GlobalConfig::GPIO_G.wifiReset,1);//WiFi模组复位,1复位,0取消复位 + gpio_set(GlobalConfig::GPIO_G.wifiReset,0); + InitGpio(GlobalConfig::GPIO_G.wifiPower,1);//WiFi模组上电 + gpio_set(GlobalConfig::GPIO_G.wifiPower,1); + sleep(10); + wifi::WPAClient wpa; + wpa.ReconnectWiFi(); + system("/usr/sbin/wpa_supplicant -Dnl80211 -iwlan0 -c/etc/wpa_supplicant.conf &"); + system("udhcpc -b -i wlan0 &"); +#endif +#endif +} +void TestUart() +{ + pUart->InitTestUart(B115200); + pUart->ReadTestUart(); +} +void UartStartWave() +{ + pUart->DealWaveThread(); +} + +void StartUdpSys() +{ + UdpSys *udpsys = UdpSys::instance(); + udpsys->StartConnectSysUdp(); +} +void WatchDog() +{ + int fd = OpenWatchDog(); + while(1){ + WriteWatchDog(fd); + sleep(50); + } + close(fd); +} +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; + + std::string strCmd15 = fw.write(jsData); + + 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()); + 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 MQTT connection lost:%d\n", ret); + print_debug("The MQTT 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; + +#ifdef WIFI_MODULE + char buf[128] = {0}; + std::string wpa_state = ""; +#ifdef G2UL_GATEWAY + wpa_state = "/usr/sbin/wpa_cli status|grep wpa_state | cut -f 2 -d '='"; +#endif + +#ifdef IMX6UL_GATEWAY + wpa_state = "/opt/Cidn/wpa_cli status|grep wpa_state | cut -f 2 -d '='"; +#endif + system_custom(wpa_state.c_str(), buf); + std::string state = std::string(buf); + std::string RSSI_cmd = ""; +#ifdef G2UL_GATEWAY + RSSI_cmd = "/usr/sbin/wpa_cli signal_poll|grep RSSI | cut -f 2 -d '='"; +#endif +#ifdef IMX6UL_GATEWAY + RSSI_cmd = "/opt/Cidn/wpa_cli signal_poll|grep RSSI | cut -f 2 -d '='"; +#endif + system_custom(RSSI_cmd.c_str(), buf); + std::string RSSI = std::string(buf); + + int iRet = reconnect(); + memset(buf, 0, sizeof(buf)); + sprintf(buf, "wifi RSSI:%s,state:%s,MQTT reconnect :%d\n", RSSI.c_str(),state.c_str(),iRet); + //LOG_WARN(" %s\n",buf); + int status = Ping( GlobalConfig::ServerIP.c_str(), 10000);; + //LOG_WARN(" netStatus %d\n",status); + print_info("%s\n", buf); + +#else + // int iRet = reconnect(); + // print_info("reconnect = %d\n",iRet); +#endif + +} + +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); + } + sleep(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")) { + print_info("%s\n",runinfo.c_str()); + boost::asio::io_service io_service; + SearchDev *searchDevObj = new SearchDev(io_service); + searchDevObj->MultiCastRecv(); + io_service.run(); + delete searchDevObj; + } + sleep(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..8f35074 --- /dev/null +++ b/threadfunc/SH_ThreadFunc.hpp @@ -0,0 +1,37 @@ +#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 TestUart(); +extern void WatchDog(); +extern void UartStartWave(); +extern void StartUdpSys(); //组播通信 +extern void GetCSQ(); +extern void Dial5G(); +extern void InitModule(); +extern void RunLED(); diff --git a/threadfunc/subdir.mk b/threadfunc/subdir.mk new file mode 100644 index 0000000..c9610c6 --- /dev/null +++ b/threadfunc/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../threadfunc/SH_ThreadFunc.cpp + +CPP_DEPS += \ +./threadfunc/SH_ThreadFunc.d + +OBJS += \ +./threadfunc/SH_ThreadFunc.o + + +# Each subdirectory must supply rules for building sources it contributes +threadfunc/%.o: ../threadfunc/%.cpp threadfunc/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-threadfunc + +clean-threadfunc: + -$(RM) ./threadfunc/SH_ThreadFunc.d ./threadfunc/SH_ThreadFunc.o + +.PHONY: clean-threadfunc + diff --git a/uart/SH_Uart.cpp b/uart/SH_Uart.cpp new file mode 100644 index 0000000..f667e0c --- /dev/null +++ b/uart/SH_Uart.cpp @@ -0,0 +1,4501 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../uart/SH_Uart.hpp" +#include "../serial/serial.h" + + +namespace{ + Uart *pUart = Uart::instance(); + Calculation *pCalculation = Calculation::instance(); +} +char g_UartRecvBuf[GENERAL_BUF_SIZE]; +int offSize = 0; +pTestRecvCallBack pTestRecv ; +std::vector g_VecWaveDataX; +std::vector g_VecWaveDataY; +std::vector g_VecWaveDataZ; +map g_mapCompress; +// 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; + +int Uart::UartRecv(int fd, char srcshow,char* buffer) +{ + char buff[BUF_LENGTH]; + int ret = 0; + int maxSize = 0; + int offSize = 0; + int timeoutflag = 0; + char head[] = {0xAA,0x55,0xAA}; + char szbuffer[BUF_LENGTH]={0x00}; + while(1) + { + + if((unsigned short)GlobalConfig::Zigbee_G.MyAddr == 0x9999){ + + memset(buff, 0, sizeof(buff)); + ret = read_data(fd, buff, BUF_LENGTH, 10); + if (ret <= 0 ){ + if(!bUpdate && !bUpdateconfig && GlobalConfig::EnterZigBeeWaveTransmittingCnt_G > 15){ + timeoutflag ++; + if(timeoutflag > 300){ + LOG_DEBUG("===============0x9999 timeout= %d offSize = %d===============\n",timeoutflag,offSize); + print_info("0x9999 timeout %d===============Size = %d\n",timeoutflag,offSize); + FindRecvPackage(offSize, mUartRecvTmpBuf,head); + GlobalConfig::Zigbee_G.MyAddr = 0x8888; + timeoutflag = 0; + offSize = 0; + maxSize = 0; + tcflush(fd,TCIFLUSH); + bModifyAddr = true; + modify_LocalAddr(0x8888); + bSendTimeStamp = false; + mssleep(10000); + m_waveTrans = true; + memset(mUartRecvTmpBuf,0,BUF_LENGTH); + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + + LOG_DEBUG("wave end\n"); + } + mssleep(10000); + }else if(bUpdatePre || (bUpdateconfig && GlobalConfig::EnterZigBeeWaveTransmittingCnt_G > 15)){ + timeoutflag ++; + if(timeoutflag > 300){ + print_info("bUpdateconfig %d===============\n",timeoutflag); + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + timeoutflag = 0; + offSize = 0; + maxSize = 0; + bUpdate = false; + bUpdatePre = false; + bUpdateconfig = false; + bModifyAddr = true; + bSendTimeStamp = false; + modify_LocalAddr(0x8888); + mssleep(10000); + GlobalConfig::Zigbee_G.MyAddr = 0x8888; + } + mssleep(10000); + } + } + else if(ret > 0){ + maxSize += ret; +// print_debug("0x9999===str_recv===,ret = %d offSize = %d,bUpdatePre = %d,bUpdateconfig = %d\n",ret,maxSize,bUpdatePre,bUpdateconfig); +// for(int i = 0; i < ret;i++){ +// printf("[%02x]", buff[i]&0xff); +// } + //print_debug("maxSize = %d\n",maxSize); + //print_debug("\n"); + timeoutflag = 0; + + if((bUpdatePre || bUpdateconfig)) + { + for(int i = 0; i < ret;i++){ + printf("%02x ", buff[i]&0xff); + } + //print_debug("maxSize111 = %d\n",maxSize); + // string strTime = GetLocalTimeWithMs(); + // LOG_INFO("str_recv strTime1 = %s\n",strTime.c_str()); + FindRecvPackage(ret,buff,head); + // ReadHandle(buff,ret); + // strTime = GetLocalTimeWithMs(); + // LOG_INFO("str_recv strTime2 = %s\n",strTime.c_str()); + }else{ + m_TimeStamp = 0; + memcpy(mUartRecvTmpBuf + offSize,buff,ret); + offSize = offSize + ret; + if(offSize > BUF_LENGTH * 15){ + LOG_INFO("maxSize = %d\n",offSize); + memset(mUartRecvTmpBuf,0,BUF_LENGTH); + timeoutflag = 0; + offSize = 0; + maxSize = 0; + tcflush(fd,TCIOFLUSH); + bModifyAddr = true; + modify_LocalAddr(0x8888); + GlobalConfig::Zigbee_G.MyAddr = 0x8888; + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + } + //print_debug("offSize = %d\n",offSize); + } + } + + }else if((unsigned short)GlobalConfig::Zigbee_G.MyAddr == 0x8888){ +#ifdef IMX6UL_GATEWAY + memset(buff, 0, sizeof(buff)); + ret = read_data(fd, buff, BUF_LENGTH, 50); + if (ret <= 0){ + continue; + } + if (srcshow) { + print_info("0x8888 ===str_recv===,ret = %d\n",ret); + for(int i = 0; i < ret;i++){ + print_debug("[%02x]", buff[i]&0xff); + } + printf("\n"); + FindRecvPackage(ret, buff,head); + + } +#else if G2UL_GATEWAY + memset(buff, 0x00, sizeof(buff)); + ret = read_data(fd, buff, BUF_LENGTH, 50); + if (ret <= 0 ){ + timeoutflag ++; + if(timeoutflag > 5){ + + FindRecvPackage(offSize, szbuffer,(char*)head); + memset(szbuffer,0x00,sizeof(szbuffer)); + timeoutflag = 0; + offSize = 0; + maxSize = 0; + mssleep(10000); + } + }else if(ret > 0){ + maxSize += ret; + print_debug("0x8888==str_recv===,ret = %d offSize = %d\n",ret,maxSize); + for(int i = 0; i < ret;i++){ + print_debug("%02x ", buff[i]&0xff); + } + print_debug("\n"); + timeoutflag = 0; + m_TimeStamp = 0; + memcpy(szbuffer + offSize,buff,ret); + offSize = offSize + ret; + } +#endif + } + //mssleep(50); + } +} + +Uart::Uart():mUart(mIoSev),mStrand(mIoSev) +{ + mRdLength = 0; + m_TimeStamp = 0; + mlastSize = 0; + fd = 0; + waittime = 0; + mPackgeIndex = -1; + bUpdate = false; + m_strDestShortAddr = ""; + memset(mUartRecvBuf,0,BUF_LENGTH); + memset(mUartRecvTmpBuf,0,BUF_LENGTH); + bTest = false; + TestFd = 0; + DataNodeUpdateFile = ""; + strTimetamp = ""; + bZigbeeSinal = false; + bModifyAddr = false; + bUpdatePre = false; + bSendTimeStamp = false; + m_waveCountX = 0; + m_waveCountY = 0; + m_waveCountZ = 0; + VecWaveDataX.reserve(300000); + VecWaveDataY.reserve(300000); + VecWaveDataZ.reserve (500000); +} +Uart::~Uart() +{ + close(fd); + close(TestFd); + if (mUart.is_open()) + mUart.close(); +} + +void Uart::openSwitch() +{ + char buffer[100]={0x00}; + int len; + int fdSwitch = config_uart("/dev/ttymxc1",B38400); + char strSend[8]={0x01,0x06,0x00,0x00,0x00,0x00,0x89,0xCA}; + len = write_data(fdSwitch,(char*)strSend,8); + sleep(1); + len = read_data(fdSwitch,(char*)buffer,100,10); + for ( int i = 0; i < len; i++) + print_debug("%02X ",buffer[i]&0xFF); + char strSend2[8]={0x01,0x06,0x00,0x00,0x00,0x01,0x48,0x0A}; + len = write_data(fdSwitch,(char*)strSend2,8); + sleep(1); + len = read_data(fdSwitch,(char*)buffer,100,10); + for ( int i = 0; i < len; i++) + print_debug("%02X ",buffer[i]&0xFF); + close(fdSwitch); +} +void Uart::InitUart(speed_t speed) +{ + +#ifdef G2UL_GATEWAY + fd = config_uart("/dev/ttySC2",speed); +#endif +#ifdef IMX6UL_GATEWAY + fd = config_uart("/dev/ttymxc4",speed); +#endif + print_info("InitUart fd = %d\n",fd); + if(fd < 0){ + printf("config_uart error\n"); + } + +} +void Uart::Close() +{ + close(fd); + fd = 0; +} +void Uart::InitZigbee() +{ + + InitUart(B115200); + UpdateZigbeeInfoCtrl(); + sleep(2); + int iRet = ReadFromUart(); + if(iRet <= 0) + { + Close(); + sleep(2); + print_info("Speed error\n"); + InitUart(B57600); + UpdateZigbeeInfoCtrl(); + sleep(2); + ReadFromUart(); + print_info("modify speed\n"); + WriteSpeed2Zigbee(); + ReadFromUart(); + } + Close(); + sleep(1); +} +void TestRecv(int status) +{ + char szStatus[10]={0x00}; + sprintf(szStatus,"%d",status); + write_data(pUart->TestFd,(char*)szStatus,strlen(szStatus)); +} +void Regist(pTestRecvCallBack pTestRecv1){ + pTestRecv = pTestRecv1; +} +void Uart::InitTestUart(speed_t speed) +{ + print_info("InitTestUart\n"); + TestFd = config_uart("/dev/ttymxc2",speed);//Test + if(TestFd < 0){ + printf("Test config_uart error\n"); + } + Regist(TestRecv); +} + +void Uart::ReadTestUart() +{ + char buff[BUF_LENGTH] = {0x00}; + print_info("ReadTestUart\n"); + while(1){ + int ret = read_data(TestFd, buff, BUF_LENGTH, 10); + if(ret > 0){ + print_info("buff = %s\n",buff); + if(!strcmp(buff,"0")){ + + char buf[256] = {0}; + sprintf(buf, "{\"dataNodeGatewayNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}", + GlobalConfig::MacAddr_G.c_str()); + std::string str = std::string(buf); + int iRet = data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + if(iRet < 0){ + pTestRecv(1); + }else{ + pTestRecv(0); + } + iRet = ZigbeeTest(); + }else if(!strcmp(buff,"1")){ + string IP = GetGwIp_("eth0"); + write_data(TestFd,(char*)IP.c_str(),IP.size()); + IP = GetGwIp_("eth1"); + write_data(TestFd,(char*)"|",1); + write_data(TestFd,(char*)IP.c_str(),IP.size()); + write_data(TestFd,(char*)"|",1); + }else{ + ModifyMac(buff); + pTestRecv(0); + } + } + mssleep(20000); + } +} + +int Uart::ZigbeeTest() +{ + char buff[BUF_LENGTH] = {0x00}; + modify_Localchannel(22); + mssleep(100000); + + modify_LocalPanID(2222); + + mssleep(100000); + modify_LocalAddr(6666); + + mssleep(100000); + return 0; +} + +void Uart::WriteToUart(const char *strSend,int pLen) +{ +//#ifdef ZIGBEE_TEST + if(!bUpdate){ + print_debug("Write To Uart Start:\n"); + for(int i=0; i 0){ + ReadHandle(buffer,len); + }*/ +} + +void Uart::Run() +{ + mIoSev.run(); +} + +void Uart::Stop() +{ + if (mUart.is_open()) + mUart.close(); + mIoSev.stop(); +} +int Uart::FindRecvPackage(int bytesRead, char* mUartRecvBuf,char* head) +{ + string strTime = GetLocalTimeWithMs(); + char head1[] = {0xAB,0xBC,0xCD}; + char head2[] = {0xDE,0xDF,0xEF}; + + //LOG_INFO("m_VecWaveData= %d\n",m_VecWaveData.size()); + int lastSize = 0; + char UartRecvBuf[BUF_LENGTH*15]={0x00}; + char RecvBuf[200] = {0x00}; + if(mlastSize > 0){ + print_info("mlastSize = %d\n",mlastSize); + memcpy(UartRecvBuf,mUartRecvTmpBuf,mlastSize); + for(int i = 0; i < mlastSize;i++){ + print_info("%02x ",UartRecvBuf[i]); + } + print_info("\n "); + memset(mUartRecvTmpBuf,0x00,sizeof(mUartRecvTmpBuf)); + } + memcpy(UartRecvBuf + mlastSize,mUartRecvBuf,bytesRead); + // for(int i = 0 ; i < bytesRead;i++){ + // if(!(i % 100)) + // printf("\n"); + // printf("%02x ",mUartRecvBuf[i]); + // } + bytesRead = bytesRead + mlastSize; + for(int i = 0; i < bytesRead;i++){ + if(UartRecvBuf[i] == head[0]){ + char buf[6]={0x00}; + char ShortAddr[8]={0x00}; + sprintf(&buf[0], "%02X", UartRecvBuf[i]&0xFF); + sprintf(&buf[2], "%02X", UartRecvBuf[i+1]&0xFF); + sprintf(&buf[4], "%02X", UartRecvBuf[i+2]&0xFF); + sprintf(ShortAddr, "%02x%02x", UartRecvBuf[i+3]&0xFF, UartRecvBuf[i+4]&0xFF); + std::string strShortAddr(ShortAddr); + std::string strHeadFlag(buf); + if ( 0 == strHeadFlag.compare("AA55AA")) { + char buf[8]={0x00}; + sprintf(buf, "%02d", UartRecvBuf[i+5]&0xFF); + int command = atoi(buf); + //print_info("command = %d\n",command); + //print_info("index = %d\n",UartRecvBuf[i+6]&0xFF); + //print_info("mPackgeIndex1 = %d\n",mPackgeIndex); + if((mPackgeIndex == -1 || (unsigned int)UartRecvBuf[i+6] == 0) && (!bUpdatePre && !bUpdateconfig)){ + //print_info("mPackgeIndex2 = %d\n",mPackgeIndex); + mPackgeIndex = UartRecvBuf[i+6]&0xFF; + }else if((unsigned int)mPackgeIndex == (unsigned int)UartRecvBuf[i+6] && + mPackgeIndex != -1 && (!bUpdatePre && !bUpdateconfig) && command != 2){ + LOG_ERROR("mPackgeIndex same index1:%d,index2:%02d ShortAddr :%s \n",\ + mPackgeIndex,UartRecvBuf[i+6]&0xff,strShortAddr.c_str()); + continue; + + }else if((unsigned int)mPackgeIndex + 1 != (unsigned int)UartRecvBuf[i+6] && + mPackgeIndex != -1 && (!bUpdatePre && !bUpdateconfig) && command != 2){ + m_TimeStamp = 0; + //print_info("mPackgeIndex3 = %d\n",mPackgeIndex); + LOG_ERROR("mPackgeIndex error index1:%d,index2:%02d ShortAddr :%s \n",\ + mPackgeIndex,UartRecvBuf[i+6]&0xff,strShortAddr.c_str()); + mPackgeIndex = -1; + print_error("mPackgeIndex error ShortAddr :%s \n",strShortAddr.c_str()); + + char tmp[10]={0x00}; + char tmp2[10]={0x00}; + for(int j = 0; j < 100;j++){ + sprintf(tmp,"%02x ",UartRecvBuf[i + j] & 0xff); + strcat(tmp2,tmp); + } + LOG_ERROR("error str = %s\n",tmp2); + GlobalConfig::Zigbee_G.MyAddr = 0x8888; + tcflush(fd,TCIOFLUSH); + sleep(1); + modify_LocalAddr(0x8888); + sleep(1); + bModifyAddr = true; + bSendTimeStamp = false; + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + //std::vector().swap(m_VecWaveData); + break; + } + + if(command == 32){ + LOG_INFO("bUpdatepackge command = %d ShortAddr :%s\n",command,strShortAddr.c_str()); + memcpy(RecvBuf,(char*)&UartRecvBuf[i],12); + //for(int j = i; j < i+12;j++){ + // print_info("%02X ",UartRecvBuf[j]&0xFF); + //} + + if(!CheckCrc(RecvBuf,11)){ + LOG_INFO("CheckCrc error command 20 \n"); + mPackgeIndex = -1; + GlobalConfig::Zigbee_G.MyAddr = 0x8888; + tcflush(fd,TCIOFLUSH); + sleep(1); + modify_LocalAddr(0x8888); + sleep(1); + bModifyAddr = true; + bSendTimeStamp = false; + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + break; + } + bUpdate = true; + m_TimeStamp = 0; + DealRecvData(RecvBuf); + break; + }else if(!bUpdatePre && !bUpdateconfig && (command == 3 || command == 4 || command == 5)){ + if(!CheckCrc(&UartRecvBuf[i],99)){ + m_TimeStamp = 0; + mPackgeIndex = -1; + LOG_INFO("CheckCrc error ShortAddr :%s command = %d\n",strShortAddr.c_str(),command); + print_error("CheckCrc error ShortAddr :%s \n",strShortAddr.c_str()); + char tmp[10]={0x00}; + char tmp2[10]={0x00}; + for(int j = 0; j < 100;j++){ + sprintf(tmp,"%02x ",UartRecvBuf[i + j] & 0xff); + strcat(tmp2,tmp); + } + LOG_ERROR("error str = %s\n",tmp2); + print_info("\n"); + GlobalConfig::Zigbee_G.MyAddr = 0x8888; + tcflush(fd,TCIOFLUSH); + sleep(1); + modify_LocalAddr(0x8888); + bModifyAddr = true; + sleep(1); + bSendTimeStamp = false; + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + m_waveCountX = 0; + m_waveCountY = 0; + m_waveCountZ = 0; + g_VecWaveDataX.clear(); + g_VecWaveDataY.clear(); + g_VecWaveDataZ.clear(); + //std::vector().swap(m_VecWaveData); + break; + } + mlastSize = 0; + lastSize = bytesRead - i; + //print_info("laseSize = %d , i = %d\n",lastSize,i); + if(lastSize < 100 && lastSize > 0){ + memcpy(mUartRecvTmpBuf,(char*)&UartRecvBuf[bytesRead-lastSize],lastSize); + mlastSize = lastSize; + break; + } + memcpy(RecvBuf,(char*)&UartRecvBuf[i],100); + DealDataNodeWave(RecvBuf,command); + }else if(!bUpdate && !bUpdateconfig && (command == 1 || command == 2 || command == 6 || command == 7)){ + char RecvBuf[100] = {0x00}; + memcpy(RecvBuf,&UartRecvBuf[i],100); + if(!CheckCrc(RecvBuf,99)){ + LOG_INFO("CheckCrc error ShortAddr :%s command = %d \n",strShortAddr.c_str(),command); + break; + } + DealRecvData(RecvBuf); + + }else if(bUpdate && !bUpdateconfig && (command == 1 || command == 2 || command == 6 || command == 7)){ + + print_info("m_strDestShortAddr = %s,strShortAddr = %s,waittime = %d\n",\ + m_strDestShortAddr.c_str(),strShortAddr.c_str(),waittime); + //if(waittime >= 2 || m_strDestShortAddr == strShortAddr) + { + char RecvBuf[100] = {0x00}; + memcpy(RecvBuf,&UartRecvBuf[i],100); + DealRecvData(RecvBuf); + LOG_INFO("Online = %s,command = %d\n",strShortAddr.c_str(),command); + waittime = 0; + bUpdate = false; + bUpdatePre = false; + m_strDestShortAddr = ""; + GlobalConfig::Zigbee_G.MyAddr = 0x8888; + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + //break; + }/*else if(m_strDestShortAddr != strShortAddr){ + mssleep(100000); + waittime ++; + }*/ + + }else if(command == 34 && bUpdateconfig){ + LOG_INFO("bUpdateconfig command = %d ShortAddr :%s\n",command,strShortAddr.c_str()); + memset(RecvBuf,0x00,sizeof(RecvBuf)); + print_info("bUpdateconfig ShortAddr :%s\n",strShortAddr.c_str()); + //memcpy(RecvBuf,(char*)&UartRecvBuf[i],100); + /*for(int j = i; j < i+100;j++){ + print_info("%02X ",UartRecvBuf[j]&0xFF); + }*/ + m_TimeStamp = 0; + //if(!CheckCrc((char*)&UartRecvBuf[i],99)) + { + char whereCon[1024] = {0}; + char updateSql[1024] = { 0 }; + char buf[20]={0x00}; + sprintf(buf, "%02x%02x", UartRecvBuf[i+3]&0xFF, UartRecvBuf[i+4]&0xFF);//Zigbee 本地地址 2 byte + sprintf(updateSql, "UpdateFlag = UpdateFlag + 1"); + sprintf(whereCon, "zigbeeShortAddr='%s'", buf); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + //string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + //data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + GlobalConfig::Zigbee_G.MyAddr = 0x8888; + bUpdateconfig = false; + mPackgeIndex = -1; + tcflush(fd,TCIOFLUSH); + sleep(1); + modify_LocalAddr(0x8888); + bModifyAddr = true; + bSendTimeStamp = false; + sleep(1); + + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + break; + } + break; + }else if(command == 35){ + //LOG_INFO("command = %d ShortAddr :%s,Timetamp=%s\n",command,strShortAddr.c_str(),strTimetamp.c_str()); + // for(int j = i; j < i+100;j++){ + // printf("%02X ",UartRecvBuf[j]&0xFF); + // } + char signalNode[10]={0x00}; + sprintf(signalNode,"%02d",UartRecvBuf[i+14]&0xFF); + if(!strcmp(signalNode,"00") || !strcmp(signalNode,"0")){ + char errorInfo[100]={0x00}; + sprintf(errorInfo,"未检测到信号!%s",signalNode); + LOG_ERROR(errorInfo); + }else{ + char whereCon[1024] = {0}; + char updateSql[1024] = { 0 }; + char tableName[100]={0x00}; + sprintf(whereCon, "zigbeeShortAddr='%s'", strShortAddr.c_str()); + vec_t vecDataNodeNo = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME), " dataNodeNo,RSSI ", whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(updateSql, "zigbeeSignalNode = '%02d' ",UartRecvBuf[i+14]&0xFF);//zigbeeRSSIType = 0 传感器获取网关信号强度 + sprintf(whereCon, "dataNodeNo='%s' and timeStamp = '%s'", (char*)vecDataNodeNo[0].c_str(),strTimetamp.c_str()); + sprintf(tableName,"t_dataStatic_%s",(char*)vecDataNodeNo[0].c_str()); + sql_ctl->UpdateTableData(tableName, updateSql, whereCon); + + vector vParamRSSI; + boost::split( vParamRSSI, vecDataNodeNo[1], boost::is_any_of( "," ), boost::token_compress_on ); + if(vParamRSSI.size() > 0){ + sprintf(updateSql, "RSSI = '%s,%02d' ",vParamRSSI[0].c_str(),UartRecvBuf[i+14]&0xFF); + //LOG_INFO(updateSql); + sprintf(whereCon, "dataNodeNo='%s'", (char*)vecDataNodeNo[0].c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + } + } + + } + mPackgeIndex = (unsigned int)UartRecvBuf[i+6]; + + } + else{ + continue; + } + }else if(UartRecvBuf[i] == head1[0]){ + char buf[6]={0x00}; + sprintf(&buf[0], "%02X", UartRecvBuf[i]&0xFF); + sprintf(&buf[2], "%02X", UartRecvBuf[i+1]&0xFF); + sprintf(&buf[4], "%02X", UartRecvBuf[i+2]&0xFF); + std::string strHeadFlag(buf); + if ( 0 == strHeadFlag.compare("ABBCCD")) { + char buf[8]={0x00}; + sprintf(buf, "%02d", UartRecvBuf[i+3]&0xFF); + int command = atoi(buf); + print_info("command = %d\n",command); + if(command == 209){ + UpdateZigbeeInfo(&UartRecvBuf[i]); + }else if(command == 220){//DC + bModifyAddr = false; + LOG_INFO("zigbeeShortAddr = %s , ret = %02d\n",m_strDestShortAddr.c_str(),UartRecvBuf[i+6]&0xFF); + if(UartRecvBuf[i+6]&0xFF != 00){ + modify_LocalAddr(0x8888); + } + } + } + }else if(UartRecvBuf[i] == head2[0]){ + char buf[6]={0x00}; + sprintf(&buf[0], "%02X", UartRecvBuf[i]&0xFF); + sprintf(&buf[2], "%02X", UartRecvBuf[i+1]&0xFF); + sprintf(&buf[4], "%02X", UartRecvBuf[i+2]&0xFF); + std::string strHeadFlag(buf); + if ( 0 == strHeadFlag.compare("DEDFEF")) { + char buf[8]={0x00}; + sprintf(buf, "%02d", UartRecvBuf[i+3]&0xFF); + int command = atoi(buf); + print_info("command = %d\n",command); + char tmp[16] = {0x00}; + if(command == 209){//D1 + pTestRecv(command); + }else if(command == 219){//DB + pTestRecv(command); + }else if(command == 220){//DC + bModifyAddr = false; + print_info("%02x,%02x,%02x,%02x,%02x \n",UartRecvBuf[i],UartRecvBuf[i+1],UartRecvBuf[i+2],UartRecvBuf[i+3],UartRecvBuf[i+4]); + LOG_INFO("zigbeeShortAddr = %s , ret = %02d\n",m_strDestShortAddr.c_str(),UartRecvBuf[i+4]&0xFF); + + //pTestRecv(command); + }else if(command == 218){//DA + //LOG_INFO("command = %d,zigbeeShortAddr = %s , signal = %02d,strTimetamp = %s\n",command,m_strDestShortAddr.c_str(),UartRecvBuf[i+6]&0xFF,strTimetamp.c_str()); + char whereCon[1024] = {0}; + char updateSql[1024] = { 0 }; + char tableName[100]={0x00}; + bZigbeeSinal = false; + sprintf(whereCon, "zigbeeShortAddr='%s'", m_strDestShortAddr.c_str()); + vec_t vecDataNodeNo = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME), " dataNodeNo,LooseValue,RSSI ", whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(updateSql, "zigbeeSignal = '%02d' ",UartRecvBuf[i+6]&0xFF);//zigbeeRSSIType = 1 网关获取传感器信号强度 + sprintf(whereCon, "dataNodeNo='%s' and timeStamp = '%s'", (char*)vecDataNodeNo[0].c_str(),strTimetamp.c_str()); + sprintf(tableName,"t_dataStatic_%s",(char*)vecDataNodeNo[0].c_str()); + sql_ctl->UpdateTableData(tableName, updateSql, whereCon); + Json::Value jsBody,jsonVal; + Json::FastWriter showValue; + char looseValue[10]={0x00}; + readStringValue("config", "loose",looseValue,(char*)GlobalConfig::Config_G.c_str()); + if(atof(looseValue) < atof(vecDataNodeNo[1].c_str())){ + jsBody["looseStatus"] = "1"; + }else{ + jsBody["looseStatus"] = "0"; + } + vector vParamRSSI; + boost::split( vParamRSSI, vecDataNodeNo[2], boost::is_any_of( "," ), boost::token_compress_on ); + if(vParamRSSI.size() == 1){ + sprintf(updateSql, "RSSI = '%02d,%s' ",UartRecvBuf[i+6]&0xFF,vParamRSSI[0].c_str()); + //LOG_INFO(updateSql); + + }else if(vParamRSSI.size() == 2){ + sprintf(updateSql, "RSSI = '%02d,%s' ",UartRecvBuf[i+6]&0xFF,vParamRSSI[1].c_str()); + //LOG_INFO(updateSql); + } + sprintf(whereCon, "dataNodeNo='%s'", (char*)vecDataNodeNo[0].c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + + jsonVal["cmd"] = "52"; + jsBody["timeStamp"] = strTimetamp; + jsBody["dataNodeNo"] = vecDataNodeNo[0]; + jsBody["zigbeeSignal"] = UartRecvBuf[i+6]&0xFF; + std::string dataBody = showValue.write(jsBody); + jsonVal["cmdBody"] = dataBody; + data_publish(showValue.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + } + } + } + + } + strTime = GetLocalTimeWithMs(); +// LOG_INFO("findRecvPackage strTime2 = %s\n",strTime.c_str()); +} +void Uart::ReadHandle(char* pUartRecvBuf,size_t bytesRead) +{ +/*try{ + if (ec) { + mRdLength = 0; + ReadFromUart(); + return ; + } + else*/ + { //长度检测 + char UartRecvBuf[BUF_LENGTH]={0x00}; + memcpy(UartRecvBuf,pUartRecvBuf,bytesRead); + print_info("recv uart len in ZigBee short address %4x : %d\n recv uart data:", + (unsigned short)GlobalConfig::Zigbee_G.MyAddr, bytesRead); + // for ( int i = 0; i < bytesRead; i++) +// print_debug("%02X ",mUartRecvBuf[i]&0xFF); + + int iPackageSize = bytesRead / 100; + if (0 == iPackageSize) { + iPackageSize = 1; + } + int Count = bytesRead; + /*每次看到这块代码时总感觉不妥,因为bytesRead是100的整数倍时对结果不影响;如果不是,则会造成数据丢失(例如1024时,iPackageSize的值 + 为10,这样就丢失了24字节的数据)。况且一个传感器与无线网关通信数据量对 无线网关的处理影响不大,但是如果是多个传感器都在和无线网关 + 通信,数据量处理不好就会产生很大的影响。我的逻辑:利用while循环,条件是判断bytesRead是否大于0,如果条件满足,再取数据包的前3字节, + 判断命令码是ABBCCD还是AA55AA,如果是ABBCCD就处理74字节数据,如果是AA55AA就处理100自己数据,此时存放数据的buf减去处理的大小数据, + 然后进入下一次while循环。*/ + + if((unsigned short)GlobalConfig::Zigbee_G.MyAddr == (unsigned short)0x9999){ + + }else{ + for (int j = 0; j < iPackageSize; j++) { + char buf[6]; + char mUartRecvPackage[100] = {0}; + char ShortAddr[8]; + + // 多包分包,解包, + if (Count < 100) { + memcpy(mUartRecvPackage, &UartRecvBuf[j * 100], Count); + } else { + memcpy(mUartRecvPackage, &UartRecvBuf[j * 100], 100); + Count = Count - 100; + } + + sprintf(&buf[0], "%02X", mUartRecvPackage[0]&0xFF); + sprintf(&buf[2], "%02X", mUartRecvPackage[1]&0xFF); + sprintf(&buf[4], "%02X", mUartRecvPackage[2]&0xFF); + sprintf(ShortAddr, "%02x%02x", mUartRecvPackage[3]&0xFF, mUartRecvPackage[4]&0xFF); + if(bUpdate){//waitting for the upated node 4s + std::string strShortAddr(ShortAddr); + print_info("m_strDestShortAddr = %s,strShortAddr = %s,waittime = %d\n",m_strDestShortAddr.c_str(),strShortAddr.c_str(),waittime); + if(waittime >= 40 || m_strDestShortAddr == strShortAddr){ + LOG_INFO("Online = %s\n",strShortAddr.c_str()); + waittime = 0; + bUpdate = false; + m_strDestShortAddr = ""; + }else if(m_strDestShortAddr != strShortAddr){ + mssleep(100000); + waittime ++; + return ; + } + } + std::string strHeadFlag(buf); + print_info("data package head command type:%s\n", strHeadFlag.c_str()); + + if ( 0 == strHeadFlag.compare("ABBCCD") && (0xD1 == (mUartRecvPackage[3]&0xFF))) { + UpdateZigbeeInfo(mUartRecvPackage); + } + + if ( 0 == strHeadFlag.compare("DEDFEF") ) { + LOG_INFO("ReadHandle flag = %s\n",strHeadFlag.c_str()); + } + + if ( 0 == strHeadFlag.compare("AA55AA") ) { + DealRecvData(mUartRecvPackage); + } + }} + + } +/* //读串口循环 + ReadFromUart(); +} catch(...) { + print_error("PlatFormInit exception happend.\n"); + // LOG_ERROR("%s,%d\n", __FUNCTION__, __LINE__); +}*/ +} + +void Uart::setCallBack(onReceiveUart _callback) +{ + m_callback = _callback; +} + +void Uart::DataAnalysis_R(DevDataOfGwid &pData) +{ + mLocalTime = boost::posix_time::microsec_clock::local_time(); + m_callback(pData); + mLocalTime = boost::posix_time::microsec_clock::local_time(); +} + +void Uart::WriteHandle(const char *strSend,const boost::system::error_code &ec,size_t bytesWrite) +{ + if (ec) { + print_error("Fail To Write Uart! ]\n"); + // LOG_ERROR("Fail To Write Uart! ]\n"); + } else { + // print_info("[ To Uart ][ Bytes:%d ]\n",bytesWrite); + } +} + + +void Uart::ThreadInit() +{ + // SignalInit(); +} + +void Uart::DataAnalysis_W(DevData &pData,bool pFlag) +{ + this->WriteToUart(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); + sleep(1);*/ +// ReadFromUart(); + char command[5]={0x00}; + unsigned char command1[100]={0x00}; + command[0] = 0xab; + command[1] = 0xbc; + command[2] = 0xcd; + command[3] = 0xd1; + command[4] = 0xaa; + WriteToUart(command,5); + LOG_INFO("UpdateZigbeeInfoCtrl \n"); + /*for ( int i = 0; i < 20; i++) + print_info("%02X ",command[i]); + print_info("\n");*/ + /*int ret = write_data(fd, (char*)command, 5); + if (ret < 0) { + perror("write"); + return ; + } + // sleep(1); + + /*ret = read_data(fd, (char *)command1, 100, 10); + printf("ret = %d\n",ret); + if (ret <= 4) { + printf("info get error!\n"); + return ; + } + UpdateZigbeeInfo((char*)command1);*/ +} + +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 = atoi(buff); + + memset(buff, 0, 8); + sprintf(buff, "%02d", pData[37]&0xFF); + GlobalConfig::ZigbeeInfo_G.Channel = atoi(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); + + memset(buff, 0, 8); + sprintf(buff, "%d", pData[62]); + GlobalConfig::ZigbeeInfo_G.RetryNum = std::string(buff); + + memset(buff, 0, 8); + sprintf(buff, "%d", pData[63]); + GlobalConfig::ZigbeeInfo_G.TranTimeout = std::string(buff); + + LOG_INFO("local zigbee module info Mode : %d Chan : %d PanID : %s MyAddr : %s DstAddr : %s,RetryNum:%s,TranTimeout:%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(),GlobalConfig::ZigbeeInfo_G.RetryNum.c_str(),GlobalConfig::ZigbeeInfo_G.TranTimeout.c_str()); +// if(GlobalConfig::ZigbeeInfo_G.MyAddr != "8888"){ +// modify_LocalAddr(0x8888); +// +// LOG_INFO("zigbee Update \n"); +// GlobalConfig::ZigbeeInfo_G.MyAddr = "8888"; +// } + LOG_INFO("PanID = %s,MacAddr_G= %s\n",GlobalConfig::ZigbeeInfo_G.PanID.c_str(),GlobalConfig::MacAddr_G.c_str()); +// if(GlobalConfig::ZigbeeInfo_G.PanID != GlobalConfig::MacAddr_G.substr(8)){ +// string strPanId = GlobalConfig::MacAddr_G.substr(8); +// long lShortAddr = strtol(strPanId.c_str(), NULL, 16); +// unsigned short panid = lShortAddr & 0xffff; +// //modify_LocalPanID(panid); +// WritePanId2Zigbee(panid); +// mssleep(100000); +// LOG_ERROR("PanID error"); +// } + + + std::string strchan = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "channel"); + LOG_INFO("Channel = %d,strchan = %s\n",GlobalConfig::ZigbeeInfo_G.Channel,strchan.c_str()); +// if(GlobalConfig::ZigbeeInfo_G.Channel != atoi(strchan.c_str())){ +// unsigned short Chan = (unsigned short)strtol(strchan.c_str(), NULL, 10); +// if(Chan > 10 && Chan < 27) +// { +// //modify_Localchannel(Chan); +// WriteChanl2Zigbee(Chan); +// mssleep(100000); +// } +// LOG_ERROR("channel error"); +// } + + std::string strType = ReadStrByOpt(SYSTEMINFOFILE, "ZigbeeType", "type"); + print_info("TranTimeout = %02x,strType = %s \n",GlobalConfig::Zigbee_G.TranTimeout,strType.c_str()); + if(strType == "aw21"){ + unsigned short TranTimeout = 0x0A; + WriteTranTimeout2Zigbee(TranTimeout); + } + if( strType == "zm5161"){ + unsigned short TranTimeout = 0x03; + WriteTranTimeout2Zigbee(TranTimeout); + } +// 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 int2bytes(int i, unsigned char* bytes, int size) { + // byte[] bytes = new byte[4]; + memset(bytes,0,sizeof(unsigned char) * size); + bytes[0] = (unsigned char) (0xff & i); + bytes[1] = (unsigned char) ((0xff00 & i) >> 8); + bytes[2] = (unsigned char) ((0xff0000 & i) >> 16); + bytes[3] = (unsigned char) ((0xff000000 & i) >> 24); +} +bool Uart::ReadUpdatePackge(unsigned char* pDestShortAddr) +{ + //compare hardversion in update list + std::vector strHWversion; + std::string strFileName = "",strSoftVersion = ""; + std::vector vecDataNodeUpdate; + vecDataNodeUpdate = ReadStrUpdate("/opt/DataNode/config.json"); + char gethardVersion_sql[32] = { 0 }; + char selectsql[1024]={ 0 }; + sprintf(gethardVersion_sql, "zigbeeShortAddr='%02x%02x'", pDestShortAddr[0],pDestShortAddr[1]); + sprintf(selectsql,"%s,%s",T_SENSOR_INFO(HARDVERSION),T_SENSOR_INFO(SOFTVERSION)); + vec_t vecResult = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME), selectsql, gethardVersion_sql); + if(vecResult.size() < 1){ + return false; + } + print_info("hardversion %s,softversion %s\n",vecResult[0].c_str(),vecResult[1].c_str()); + int thisindex = -1; + int flag = -1; + for(int j = 0; j < vecDataNodeUpdate.size();j++){ + for(int i = 0; i < vecDataNodeUpdate[j].hwVersion.size();i++){ + if(vecResult[0] == vecDataNodeUpdate[j].hwVersion[i]){ + if(vecResult[1] == vecDataNodeUpdate[j].strSoftVersion){ + flag = 0; + break; + }else{ + thisindex = i; + strFileName = vecDataNodeUpdate[j].strUpdataFileName; + break; + } + } + } + if(thisindex >= 0 || flag == 0) + break; + } + + if(thisindex < 0) + return false; + +// if(!strncmp(vecResult[0].c_str(),"3",1)){ +// WriteTranTimeout2Zigbee(0x03); +// }else if(!strncmp(vecResult[0].c_str(),"4",1)){ +// WriteTranTimeout2Zigbee(0x0A); +// } + + print_info("thisindex = %d\n",thisindex); + + FILE * pFile=NULL; + int thisSize = 0; + DataNodeUpdateFile = "/opt/DataNode/" + strFileName; + print_info("strFileName = %s\n",DataNodeUpdateFile.c_str()); + pFile = fopen (DataNodeUpdateFile.c_str(),"rb"); + if (pFile==NULL){ + return false; + } + else + { + while (fgetc(pFile) != EOF) { + ++thisSize; + } + fclose (pFile); + } + +// WriteShortAddr_DistAddr2Zigbee(localAddr,pDestShortAddr);//永久参数配置 +/* char tmpbuf[8] = {0x00}; + * unsigned short localAddr = 0x9999; + sprintf(tmpbuf,"%02x%02x",pDestShortAddr[0],pDestShortAddr[1]); + m_strDestShortAddr = std::string(tmpbuf); + modify_distaddr_info(localAddr,"",pDestShortAddr);//临时参数配置 + GlobalConfig::Zigbee_G.MyAddr = 0x9999;*/ + + unsigned char Data[12]={0x00}; + unsigned char size[4]={0x00}; + print_info("thisSize = %d\n",thisSize); + //帧头[3byte] 节点地址[2byte] 数据类型[1byte] 序号[1byte] 升级包大小[4byte] CRC校验[1byte] + Data[0]=0xAA; + Data[1]=0x55; + Data[2]=0xAA; + Data[3]=pDestShortAddr[0]; + Data[4]=pDestShortAddr[1]; + Data[5]=0x20; + Data[6]=0x00; + int2bytes(thisSize,size,4); + Data[7]=size[3]; + Data[8]=size[2]; + Data[9]=size[1]; + Data[10]=size[0]; + unsigned char tmp = 0x00; + for(int i = 0 ; i < 11;i++){ + tmp +=Data[i]; + } + Data[11]=tmp; + sleep(1); + WriteToUart((const char*)Data,12); + int iRet = CheckZigbeeACK(); + if(iRet == 0){ + LOG_DEBUG("Packge ACK send success,shortAddr = %02x%02x\n",pDestShortAddr[0],pDestShortAddr[1]); + }else{ + LOG_ERROR("Packge ACK send failed,shortAddr = %02x%02x\n",pDestShortAddr[0],pDestShortAddr[1]); + } + string strTime = GetLocalTimeWithMs(); + LOG_INFO("ReadUpdatePackge strTime = %s\n",strTime.c_str()); + return true; +} +void Uart::UpdateWirelessNode(unsigned short shortAdd) +{ + string strTime = GetLocalTimeWithMs(); + LOG_INFO("UpdateWirelessNode start = %s UpdateWirelessNode id = %02x %02x\n",strTime.c_str(),UINT16_HIGH(shortAdd),UINT16_LOW(shortAdd)); + /*std::string strFileName = "",strSoftVersion = ""; + std::vector vecDataNodeUpdate; + vecDataNodeUpdate = ReadStrUpdate("/opt/DataNode/config.json"); + + char gethardVersion_sql[32] = { 0 }; + sprintf(gethardVersion_sql, "zigbeeShortAddr='%02x%02x'", UINT16_HIGH(shortAdd),UINT16_LOW(shortAdd)); + std::string SoftVersion = sql_ctl->GetData(T_SENSOR_INFO(TNAME), "softVersion", gethardVersion_sql); + + print_info("SoftVersion = %s\n",SoftVersion.c_str()); + LOG_INFO(" NOW SoftVersion = %s\n",SoftVersion.c_str());*/ + ////// + ////// + //strFileName = "/opt/DataNode/" + strFileName; + FILE * pFile=NULL; + int thisSize = 0; + char *buffer=NULL; + int resendCount = 0; + pFile = fopen (DataNodeUpdateFile.c_str(),"rb"); + if (pFile==NULL) perror ("Error opening file"); + else + { + while (fgetc(pFile) != EOF) { + ++thisSize; + } + rewind(pFile); + buffer = (char*)malloc(thisSize);// + fread (buffer, sizeof (char), thisSize, pFile); + fclose (pFile); + + int Count = thisSize / 92; + int lastSize = thisSize % 92; + unsigned char UpdateData[100]={0x00}; + //帧头[3byte] 节点地址[2byte] 数据类型[1byte] 序号[1byte] 数据包[92byte] CRC校验[1byte] + print_info("Start Update!!! file Size = %d\n",thisSize); + unsigned char tmp = 0x00; + gpio_set(GlobalConfig::GPIO_G.zigAckreset,0); + //boost::this_thread::sleep(boost::posix_time::milliseconds(1)); + mssleep(1000); + gpio_set(GlobalConfig::GPIO_G.zigAckreset,1); + for(int j = 0; j < Count;j++){ + int time ,value; + UpdateData[0]=0xAA; + UpdateData[1]=0x55; + UpdateData[2]=0xAA; + UpdateData[3]=UINT16_HIGH(shortAdd); + UpdateData[4]=UINT16_LOW(shortAdd); + UpdateData[5]=0x21; + UpdateData[6]=0xff & j; + memcpy(&UpdateData[7],buffer+92*j,92); + tmp = 0x00; + for(int k = 0; k < 99;k++){ + tmp +=UpdateData[k]; + } + UpdateData[99] = tmp; +// RESEND: + WriteToUart((const char*)UpdateData,100); + if(gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 48) + gpio_set(GlobalConfig::GPIO_G.zigAckreset,1); + time = 0; + do{ + value = gpio_read(GlobalConfig::GPIO_G.zigAckrep); + if(value == 49) + break; + mssleep(10000); + time += 1; + }while(time < 150); + if(time >= 150){ + resendCount++; + if(resendCount < 5){ + LOG_INFO(" RESEND gpio_read failed shortAdd %x %x,error index %d\n",UINT16_HIGH(shortAdd),UINT16_LOW(shortAdd),j); + }else{ + LOG_INFO("gpio_read failed shortAdd %x %x,error index %d\n",UINT16_HIGH(shortAdd),UINT16_LOW(shortAdd),j); + print_red("gpio_read failed \n"); + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + bUpdate = false; + goto endUpdate; + } + } + gpio_set(GlobalConfig::GPIO_G.zigAckreset,0); + mssleep(2000); +// if(gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 48) +// gpio_set(GlobalConfig::GPIO_G.zigAckreset,1); + memset(UpdateData,0x00,sizeof(UpdateData)); + //boost::this_thread::sleep(boost::posix_time::milliseconds(5)); + mssleep(5000); + } + if(gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 48) + gpio_set(GlobalConfig::GPIO_G.zigAckreset,1); + // printf("Count =%d,lastSize = %d\n",Count,lastSize); + if(lastSize > 0){ + UpdateData[0]=0xAA; + UpdateData[1]=0x55; + UpdateData[2]=0xAA; + UpdateData[3]=UINT16_HIGH(shortAdd); + UpdateData[4]=UINT16_LOW(shortAdd); + UpdateData[5]=0x21; + UpdateData[6]=0xff & Count; + memcpy(&UpdateData[7],buffer+92*Count,lastSize); + tmp = 0x00; + for(int k = 0; k < 99;k++){ + tmp +=UpdateData[k]; + } + UpdateData[99] = tmp; + WriteToUart((const char*)UpdateData,100); + boost::this_thread::sleep(boost::posix_time::milliseconds(10)); +// if(gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 49){ +// gpio_set(GlobalConfig::GPIO_G.zigAckreset,0); +// boost::this_thread::sleep(boost::posix_time::milliseconds(1)); +// if(gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 48)gpio_set(GlobalConfig::GPIO_G.zigAckreset,1); +// } + int time = 0; + do{ + int value = gpio_read(GlobalConfig::GPIO_G.zigAckrep); + if(value == 49){ + gpio_set(GlobalConfig::GPIO_G.zigAckreset,0); + mssleep(10000); + if(gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 48) + gpio_set(GlobalConfig::GPIO_G.zigAckreset,1); + break; + } + mssleep(10000); + time += 1; + }while(time < 150); + if(time >= 150){ + LOG_INFO("gpio_read failed shortAdd %x %x\n",UINT16_HIGH(shortAdd),UINT16_LOW(shortAdd)); + print_info("gpio_read failed \n"); + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + bUpdate = false; + goto endUpdate; + } + memset(UpdateData,0x00,sizeof(UpdateData)); + } + print_info("Update END!!! file Size = %d\n",thisSize); + } + endUpdate: + resendCount = 0; + free(buffer); + tcflush(fd,TCIFLUSH); + boost::this_thread::sleep(boost::posix_time::seconds(1)); + bUpdate = false; + bSendTimeStamp = false; + modify_LocalAddr(0x8888); + bModifyAddr = true; + boost::this_thread::sleep(boost::posix_time::milliseconds(100)); + GlobalConfig::Zigbee_G.MyAddr = 0x8888; + DataNodeUpdateFile = ""; + // std::vector().swap(m_VecWaveData); + // WriteShortAddr2Zigbee(shortAddr); + // UpdateZigbeeInfoCtrl(); + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + LOG_INFO("UpdateWirelessNode end"); +} + + +int Uart::UpdateConfig(unsigned char* pDestShortAddr) +{ + char whereCon[64] = { 0 }; + char selCon[100]={0x00}; + sprintf(whereCon, "zigbeeShortAddr='%02x%02x'", pDestShortAddr[0],pDestShortAddr[1]); + //std::string strUpdate = sql_ctl->GetData(T_SENSOR_INFO(TNAME), "UpdateFlag", whereCon); + vec_t vecResultNode = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME), "*", whereCon); + if(vecResultNode.size() <= 0) + return -1; + if(vecResultNode[41] == "0") + { +// if(!strncmp(vecResult[1].c_str(),"3",1)){//zm5161 +// WriteTranTimeout2Zigbee(0x03); +// }else if(!strncmp(vecResult[1].c_str(),"4",1)){//aw21 +// WriteTranTimeout2Zigbee(0x0A); +// } + print_info("UpdateConfig\n"); + LOG_INFO("UpdateConfig\n"); + bUpdateconfig = true; + unsigned short localAddr = 0x9999; + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + // WriteShortAddr_DistAddr2Zigbee(localAddr,pDestShortAddr);//永久参数配置 + char tmpbuf[8] = {0x00}; + sprintf(tmpbuf,"%02x%02x",pDestShortAddr[0],pDestShortAddr[1]); + m_strDestShortAddr = std::string(tmpbuf); + //modify_distaddr_info(localAddr,"",pDestShortAddr);//临时参数配置 + GlobalConfig::Zigbee_G.MyAddr = 0x9999; + boost::this_thread::sleep(boost::posix_time::milliseconds(500)); + vec_t vecResult; + sprintf(selCon,"featureInterVal,waveInterVal,range,samplingRate,ACCSampleTime,startBrands,stopBrands,\ + envelopeBandPass,faultFrequency,timeStamp,viff,ZigbeePower,ZigbeeRetry,MeasurementID,NodeWaveSend"); + vecResult = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME),selCon,whereCon); + print_info("vecResult size = %d\n",vecResult.size()); + if(vecResult.size() < 1){ + return -1; + } + unsigned char UpdateData[100]={0x00}; + //帧头[3byte] 节点地址[2byte] 数据类型[1byte] 序号[1byte] 数据包[92byte] CRC校验[1byte] + UpdateData[0]=0xAA; + UpdateData[1]=0x55; + UpdateData[2]=0xAA; + UpdateData[3]=pDestShortAddr[0]; + UpdateData[4]=pDestShortAddr[1]; + UpdateData[5]=0x22; + UpdateData[6]=0x00; + UpdateData[7]=0x01; + UpdateData[8]=UINT16_LOW(atoi(vecResult[0].c_str())); + UpdateData[9]=UINT16_HIGH(atoi(vecResult[1].c_str())); + UpdateData[10]=UINT16_LOW(atoi(vecResult[1].c_str())); + int y = 0; + if(vecResultNode[17] == "01"){ + if(vecResult[3]=="3200"){ + y = 0; + }else if(vecResult[3]=="6400"){ + y = 1; + }else if(vecResult[3]=="12800"){ + y = 2; + }else if(vecResult[3]=="25600"){ + y = 3; + } + }else if(vecResultNode[17] == "02"){ + if(vecResult[3]=="8000"){ + y = 0; + }else if(vecResult[3]=="16000"){ + y = 1; + }else if(vecResult[3]=="24000"){ + y = 2; + }else if(vecResult[3]=="32000"){ + y = 3; + }else if(vecResult[3]=="48000"){ + y = 4; + }else if(vecResult[3]=="96000"){ + y = 5; + }else if(vecResult[3]=="192000"){ + y = 6; + } + } + UpdateData[18] = atoi(vecResult[11].c_str()) & 0xFF;; + UpdateData[19] = atoi(vecResult[12].c_str()) & 0xFF;; + int x = atoi(vecResult[2].c_str()); + UpdateData[21] = BUILD_UINT2(x,y); + UpdateData[22] = atoi(vecResult[4].c_str()) & 0xFF; + print_info("vecResult size = %s==%s==%s==%s=%s\n",vecResult[5].c_str(),vecResult[6].c_str(),vecResult[7].c_str(),vecResult[8].c_str(),vecResult[14].c_str()); + vector vStart,vStop,vEnvelopeBandPass,vfaultFrequency,vNodeWaveSend; + boost::split( vStart, vecResult[5], boost::is_any_of( "," ), boost::token_compress_on ); + boost::split( vStop, vecResult[6], boost::is_any_of( "," ), boost::token_compress_on ); + boost::split( vEnvelopeBandPass, vecResult[7], boost::is_any_of( "," ), boost::token_compress_on ); + boost::split( vfaultFrequency, vecResult[8], boost::is_any_of( "," ), boost::token_compress_on ); + if(vecResult[14] != "") + boost::split( vNodeWaveSend, vecResult[14], boost::is_any_of( "," ), boost::token_compress_on ); + + UpdateData[23] = UINT16_HIGH(atoi(vStart[0].c_str())); + UpdateData[24] = UINT16_LOW(atoi(vStart[0].c_str())); + UpdateData[25] = UINT16_HIGH(atoi(vStop[0].c_str())); + UpdateData[26] = UINT16_LOW(atoi(vStop[0].c_str())); + + UpdateData[27] = UINT16_HIGH(atoi(vStart[1].c_str())); + UpdateData[28] = UINT16_LOW(atoi(vStart[1].c_str())); + UpdateData[29] = UINT16_HIGH(atoi(vStop[1].c_str())); + UpdateData[30] = UINT16_LOW(atoi(vStop[1].c_str())); + + UpdateData[31] = UINT16_HIGH(atoi(vStart[2].c_str())); + UpdateData[32] = UINT16_LOW(atoi(vStart[2].c_str())); + UpdateData[33] = UINT16_HIGH(atoi(vStop[2].c_str())); + UpdateData[34] = UINT16_LOW(atoi(vStop[2].c_str())); + + UpdateData[35] = UINT16_HIGH(atoi(vStart[3].c_str())); + UpdateData[36] = UINT16_LOW(atoi(vStart[3].c_str())); + UpdateData[37] = UINT16_HIGH(atoi(vStop[3].c_str())); + UpdateData[38] = UINT16_LOW(atoi(vStop[3].c_str())); + + UpdateData[39] = UINT16_HIGH(atoi(vStart[4].c_str())); + UpdateData[40] = UINT16_LOW(atoi(vStart[4].c_str())); + UpdateData[41] = UINT16_HIGH(atoi(vStop[4].c_str())); + UpdateData[42] = UINT16_LOW(atoi(vStop[4].c_str())); + + UpdateData[43] = UINT16_HIGH(atoi(vEnvelopeBandPass[0].c_str())); + UpdateData[44] = UINT16_LOW(atoi(vEnvelopeBandPass[0].c_str())); + UpdateData[45] = UINT16_HIGH(atoi(vEnvelopeBandPass[1].c_str())); + UpdateData[46] = UINT16_LOW(atoi(vEnvelopeBandPass[1].c_str())); + + UpdateData[47] = UINT16_HIGH(atoi(vfaultFrequency[0].c_str())); + UpdateData[48] = UINT16_LOW(atoi(vfaultFrequency[0].c_str())); + UpdateData[49] = UINT16_HIGH(atoi(vfaultFrequency[1].c_str())); + UpdateData[50] = UINT16_LOW(atoi(vfaultFrequency[1].c_str())); + + UpdateData[51] = UINT16_HIGH(atoi(vfaultFrequency[2].c_str())); + UpdateData[52] = UINT16_LOW(atoi(vfaultFrequency[2].c_str())); + UpdateData[53] = UINT16_HIGH(atoi(vfaultFrequency[3].c_str())); + UpdateData[54] = UINT16_LOW(atoi(vfaultFrequency[3].c_str())); + + UpdateData[55] = UINT32_HIGH_1(atoi(vecResult[9].c_str())); + UpdateData[56] = UINT32_HIGH_2(atoi(vecResult[9].c_str())); + UpdateData[57] = UINT32_LOW_1(atoi(vecResult[9].c_str())); + UpdateData[58] = UINT32_LOW_2(atoi(vecResult[9].c_str())); + + UpdateData[59] = (atoi(vecResult[10].c_str())) & 0xFF; + + size_t bytesSize = strlen(vecResult[13].c_str()) / 2; + unsigned char* bytes = (unsigned char*)malloc(bytesSize); + + if (hexStringToBytes(vecResult[13].c_str(), bytes, bytesSize) != 0) { + free(bytes); + }else{ + UpdateData[60] = bytes[0]; + UpdateData[61] = bytes[1]; + UpdateData[62] = bytes[2]; + UpdateData[63] = bytes[3]; + UpdateData[64] = bytes[4]; + UpdateData[65] = bytes[5]; + UpdateData[66] = bytes[6]; + UpdateData[67] = bytes[7]; + } + unsigned char byte = 0; + if(vNodeWaveSend.size() > 0){ + if (vNodeWaveSend[0] == "0") + { + Binary_Bit(&byte,0,0); + } + if (vNodeWaveSend[0] == "1") + { + Binary_Bit(&byte,0,1); + } + if (vNodeWaveSend[1] == "0") + { + Binary_Bit(&byte,1,0); + } + if (vNodeWaveSend[1] == "1") + { + Binary_Bit(&byte,1,1); + } + if (vNodeWaveSend[2] == "0") + { + Binary_Bit(&byte,2,0); + } + if (vNodeWaveSend[2] == "1") + { + Binary_Bit(&byte,2,1); + } + } + UpdateData[68] = byte; + free(bytes); + unsigned char tmp1 = 0x00; + for(int k = 0; k < 99;k++){ + tmp1 +=UpdateData[k]; + } + UpdateData[99] = tmp1; + tcflush(fd,TCIFLUSH); + WriteToUart((const char*)UpdateData,100); + int iRet = CheckZigbeeACK(); + if(iRet == 0){ + LOG_DEBUG("updataconfig ACK send success,shortAddr = %02x%02x\n",pDestShortAddr[0],pDestShortAddr[1]); + }else{ + LOG_ERROR("updataconfig ACK send failed,shortAddr = %02x%02x\n",pDestShortAddr[0],pDestShortAddr[1]); + } + return 0; + }else if(vecResultNode[41] == "-1"){ + + bUpdateconfig = true; + unsigned short localAddr = 0x9999; + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + string strName = sql_ctl->GetData(T_SENSOR_INFO(TNAME)," dataNodeName ",whereCon); + + unsigned char UpdateData[100]={0x00}; + //帧头[3byte] 节点地址[2byte] 数据类型[1byte] 序号[1byte] 数据包[92byte] CRC校验[1byte] + UpdateData[0]=0xAA; + UpdateData[1]=0x55; + UpdateData[2]=0xAA; + UpdateData[3]=pDestShortAddr[0]; + UpdateData[4]=pDestShortAddr[1]; + UpdateData[5]=0x22; + UpdateData[6]=0x00; + UpdateData[7]=0x02; + char hex[200]={0X00}; + stringToHex(strName.c_str(),hex); + size_t bytesSize = strlen(hex) / 2; + unsigned char* bytes = (unsigned char*)malloc(bytesSize); + + if (hexStringToBytes(hex, bytes, bytesSize) != 0) { + free(bytes); + }else{ + for (size_t i = 0; i < bytesSize; i++) + { + UpdateData[8 + i] = bytes[i]; + } + free(bytes); + unsigned char tmp1 = 0x00; + for(int k = 0; k < 99;k++){ + tmp1 += UpdateData[k]; + } + UpdateData[99] = tmp1; + tcflush(fd,TCIFLUSH); + WriteToUart((const char*)UpdateData,100); + int iRet = CheckZigbeeACK(); + if(iRet == 0){ + LOG_DEBUG("updataname ACK send success,shortAddr = %02x%02x\n",pDestShortAddr[0],pDestShortAddr[1]); + }else{ + LOG_ERROR("updataname ACK send failed,shortAddr = %02x%02x\n",pDestShortAddr[0],pDestShortAddr[1]); + } + return 0; + + } + + + + }else{ + return -1; + } + +} +int Uart::UpdateWirelessNodeTime(unsigned char* pDestShortAddr,int modifyaddr/*,int nodewaveindex,int nodetime,int nodeindex*/) +{ + if(modifyaddr) + modify_DistAddr(pDestShortAddr); + mssleep(10000); + //print_info("nodewaveindex = %d,nodetime = %d,nodeindex = %d\n",nodewaveindex,nodetime,nodeindex); + char localtimestamp[32]={0x00}; + int millisecond = 0; + + string rtcTime = GetRTC(localtimestamp,millisecond); + LOG_INFO("ShortAddr = %02x%02x,rtcTime = %s,localtimestamp = %s,millisecond = %d,bSendTimeStamp = %d \n",pDestShortAddr[0],pDestShortAddr[1],rtcTime.c_str(),localtimestamp,millisecond,bSendTimeStamp); + // struct timeval tv; + // gettimeofday(&tv, NULL); + // int millisecond = tv.tv_usec / 1000; + + // sprintf(localtimestamp, "%ld", tv.tv_sec); + + unsigned char UpdateData[100]={0x00}; + UpdateData[0]=0xAA; + UpdateData[1]=0x55; + UpdateData[2]=0xAA; + UpdateData[3]=pDestShortAddr[0]; + UpdateData[4]=pDestShortAddr[1]; + UpdateData[5]=0x23; + UpdateData[6]=0x00; + UpdateData[7]=0x00; + UpdateData[8]=UINT32_LOW_2(atol(localtimestamp)); + UpdateData[9]=UINT32_LOW_1(atol(localtimestamp)); + UpdateData[10]=UINT32_HIGH_2(atol(localtimestamp)); + UpdateData[11]=UINT32_HIGH_1(atol(localtimestamp)); + UpdateData[12]=UINT16_LOW(millisecond); + UpdateData[13]=UINT16_HIGH(millisecond); + //UpdateData[13]=UINT16_HIGH(nodetime); + //UpdateData[14]=UINT16_LOW(nodetime); + //UpdateData[15]=UINT16_LOW(nodewaveindex); + //UpdateData[16]=UINT16_LOW(nodeindex); + unsigned char tmp = 0x00; + for(int k = 0; k < 99;k++){ + tmp += UpdateData[k]; + } + UpdateData[99] = tmp; + WriteToUart((const char*)UpdateData,100); + int iRet = CheckZigbeeACK(); + if(iRet == 0){ + LOG_DEBUG("NodeTime ACK send success,shortAddr = %02x%02x\n",pDestShortAddr[0],pDestShortAddr[1]); + }else{ + LOG_ERROR("NodeTime ACK send failed,shortAddr = %02x%02x\n",pDestShortAddr[0],pDestShortAddr[1]); + } + return iRet; +} +void Uart::DealRecvData(const char *pData) +{ + char buf[8]; + char shortAdd[8]={0x00}; + sprintf(buf, "%02d", pData[5]&0xFF); + sprintf(shortAdd, "%02x%02x", pData[3]&0xFF,pData[4]&0xFF); + unsigned short ushortAdd = BUILD_UINT16(pData[3]&0xFF,pData[4]&0xFF); + int flag = atoi(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:{//0x01:设备信息 + DealDataNodeInfo(pData); + } + break; + case 2:{//0x02:特征值 + DealDataNodeFeature(pData, 0); + } + break; +/* case 3:{//0x03:长波形X轴 + DealDataNodeWave(pData); + } + break; + case 4:{//0x04:长波形Y轴 + DealDataNodeWave(pData); + } + break; + case 5:{//0x05:长波形Z轴 + DealDataNodeWave(pData); + } + break;*/ + case 6:{//0x06:特征值+长波形 + //LOG_INFO("DealDataNodeFeature 06"); + DealDataNodeFeature(pData, 1); + } + break; + case 32:{//升级 + + UpdateWirelessNode(ushortAdd); + } + break; + case 7:{ + DealDataNodeName(pData); + } + break; + default: + break; + } +} + +void Uart::DealDataNodeName(const char* pData) +{ + bSendTimeStamp = false; + print_info("DealDataNodeName \n"); + string strTime = GetLocalTimeWithMs(); + //LOG_INFO("DealDataNodeName Time = %s\n",strTime.c_str()); + char szShortAdd[8]={0x00}; + char shortAdd[8]={0x00}; + char NodeName[64]={0x00}; + sprintf(szShortAdd, "%02x%02x", pData[3]&0xFF,pData[4]&0xFF); + memcpy(NodeName,&pData[7],64); + memcpy(shortAdd,&pData[3],2); + char whereCon[64] = { 0 }; + char uplCon[200]={0x00}; + int iRet = -1; + char nodeWaveSend[10]={0x00}; + + UpdateWirelessNodeTime((unsigned char*)shortAdd,1); + + for(int i = 0; i < 64;i++){ + sprintf(&NodeName[i * 2], "%02X", pData[7 + i]&0xFF); + } + char MeasurementID[100]={0x00}; + sprintf(MeasurementID, "%02x%02x%02x%02x%02x%02x%02x%02x", pData[71], pData[72], pData[73], pData[74], + pData[75], pData[76], pData[77],pData[78]); + sprintf(nodeWaveSend,"%d,%d,%d",GET_BIT(pData[79], 0 ),GET_BIT(pData[79], 1 ),GET_BIT(pData[79], 2 )); + char gbkNodeName[128]={0x00}; + sprintf(whereCon, "zigbeeShortAddr='%s'", szShortAdd); + print_info("whereCon = %s\n",whereCon); + array_t vecRes = sql_ctl->GetDataMultiLine(T_SENSOR_INFO(TNAME)," dataNodeNo, MeasurementID,hardVersion,softVersion",whereCon); + if(vecRes.size() > 1){ + for(int i = 0; i < vecRes.size();i++){ + if(vecRes[i][1] != ""){ + char whereCon1[64] = { 0 }; + sprintf(whereCon1, " dataNodeNo='%s' ", vecRes[i][0].c_str()); + sql_ctl->DeleteTableData(T_SENSOR_INFO(TNAME), whereCon1); + sql_ctl->DeleteTableData(T_DATA_INFO(TNAME), whereCon1); + sql_ctl->DeleteTableData(T_DATASTATIC_INFO(TNAME), whereCon1); + sql_ctl->DeleteTableData(T_DATANODE_TIME(TNAME), whereCon1); + char szTableName[50]={0x00}; + sprintf(szTableName,"DROP TABLE t_data_%s",vecRes[i][0].c_str()); + sql_ctl->CreateTable(szTableName, 0); + memset(szTableName,0x00,sizeof(szTableName)); + sprintf(szTableName,"DROP TABLE t_dataStatic_%s",vecRes[i][0].c_str()); + sql_ctl->CreateTable(szTableName, 0); + } + } + } + string hardVersion = vecRes[0][2]; + string softVersion = vecRes[0][3]; + if((hardVersion == "3.0" && compareVersions(softVersion,"3.6") == -1) || + (hardVersion == "4.0" && compareVersions(softVersion,"4.6") == -1)){ + memcpy(MeasurementID , vecRes[0][0].c_str(),sizeof(MeasurementID)); + } + std::string strNodeName(NodeName); + print_info("strNodeName = %s\n",strNodeName.c_str()); + solve(gbkNodeName,NodeName); + print_info("gbkNodeName = %s\n",gbkNodeName); + string utfNodeName = GBKToUTF8(gbkNodeName); + print_info("NodeName = %s\n",NodeName); + print_info("whereCon = %s\n",whereCon); + sprintf(uplCon,"dataNodeName = '%s' , MeasurementID = '%s',NodeWaveSend = '%s'",gbkNodeName,MeasurementID,nodeWaveSend); + iRet = sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME),uplCon,whereCon,0); + string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + iRet = data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + +} + +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];//设备状态标志 1 byte + DataNodeInfo dataNodeInfo; + dataNodeInfo.EquipSta = GET_BIT(chTemp, 2 ); + dataNodeInfo.TemTopFlag = GET_BIT(chTemp, 3 ); + dataNodeInfo.TemBotFlag = GET_BIT(chTemp , 4); + dataNodeInfo.ZigbeeFlag = GET_BIT(chTemp , 5); + dataNodeInfo.AccFlag = GET_BIT(chTemp ,6); + dataNodeInfo.InitFlag = GET_BIT(chTemp ,7); + + 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);//Zigbee MAC 8 byte + + chTemp = pRecvData->Data[9];//硬件版本 1 byte + memset(buf, 0, 32); + sprintf(buf, "%.1f", 0.1*chTemp); + dataNodeInfo.HardVersion = std::string(buf); + + chTemp = pRecvData->Data[10];//软件版本 1 byte + 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, "%d", BUILD_UINT32(pRecvData->Data[11], pRecvData->Data[12], pRecvData->Data[13], pRecvData->Data[14])); + dataNodeInfo.BpNo = std::string(buf);//生产批号 4 byte + + memset(buf, 0, 32); + sprintf(buf, "%d", BUILD_UINT32(pRecvData->Data[15], pRecvData->Data[16], pRecvData->Data[17], pRecvData->Data[18])); + dataNodeInfo.SerialNo = std::string(buf);//生产序列号 4 byte + + memset(buf, 0, 32); + sprintf(buf, "%d", BUILD_UINT32(pRecvData->Data[19], pRecvData->Data[20], pRecvData->Data[21], pRecvData->Data[22])); + dataNodeInfo.FirstPowerTime = std::string(buf);//首次上电日期 4 byte + + //23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38=>序号13 无线信号强度 + + memset(buf, 0, 32); + sprintf(buf, "%d", BUILD_UINT32(pRecvData->Data[23], pRecvData->Data[24], pRecvData->Data[25], pRecvData->Data[26])); + dataNodeInfo.WakeupTime = atoi(buf);//唤醒次数 4 byte + printf("WakeupTime = %d\n",dataNodeInfo.WakeupTime); + memset(buf, 0, 32); + sprintf(buf, "%d", BUILD_UINT32(pRecvData->Data[27], pRecvData->Data[28], pRecvData->Data[29], pRecvData->Data[30])); + dataNodeInfo.StaticTime = atoi(buf);//特征值发送次数 4 byte + printf("StaticTime = %d\n",dataNodeInfo.StaticTime); + memset(buf, 0, 32); +// sprintf(buf, "%d", BUILD_UINT32(pRecvData->Data[31], pRecvData->Data[32], pRecvData->Data[33], pRecvData->Data[34])); + + dataNodeInfo.WaveTime = BUILD_UINT32(pRecvData->Data[31], pRecvData->Data[32], pRecvData->Data[33], pRecvData->Data[34]);//原始波形发送次数 4 byte + + memset(buf, 0, 32); +// sprintf(buf, "%02x%02x", pRecvData->Data[35], pRecvData->Data[36]); + dataNodeInfo.BateryV = BUILD_UINT16(pRecvData->Data[35],pRecvData->Data[36]);//电池电压 2 byte + + memset(buf, 0, 32); + sprintf(buf, "%02x", pRecvData->Data[37]); + dataNodeInfo.ProductNo = std::string(buf);//产品型号 1 byte + + // 获取 RSSI + chTemp = pRecvData->Data[38]; + memset(buf, 0, 32); + sprintf(buf, "%d", chTemp); + dataNodeInfo.RSSI = atoi(buf); //无线信号强度 1 byte + + chTemp = pRecvData->Data[39]; + memset(buf, 0, 32); + sprintf(buf, "%02x", chTemp); + dataNodeInfo.ConfigFlag = ((0 == std::string(buf).compare("aa")) ? 1 : 0); //配置标志 1 byte + + chTemp = pRecvData->Data[40]; + memset(buf, 0, 32); + sprintf(buf, "%d", chTemp); + dataNodeInfo.FeatureInterVal = atoi(buf); //唤醒周期 1 byte + memset(buf, 0, 32); + // yxq + sprintf(buf, "%u%u", pRecvData->Data[41],pRecvData->Data[42]); + dataNodeInfo.WaveInterVal = atoi(buf);//原始波形发送周期 2 byte + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[43], pRecvData->Data[44]); //Zigbee PID 2 byte + dataNodeInfo.ZigbeePanId = std::string(buf); + + chTemp = pRecvData->Data[45]; + memset(buf, 0, 32); + sprintf(buf, "%d", chTemp); + dataNodeInfo.ZigbeeChannel = atoi(buf);//Zigbee 信道 1 byte + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[46], pRecvData->Data[47]);//Zigbee 本地地址 2 byte + + dataNodeInfo.ZigbeeShortAddr = std::string(buf); + unsigned char shortAddr[2] = {0x00}; + memcpy(shortAddr,(unsigned char*)&pRecvData->Data[46],2); + modify_DistAddr(shortAddr);//修改目标地址 + string strTime = GetLocalTimeWithMs(); + //LOG_INFO("DealDataNodeInfo modify_DistAddr Time = %s\n",strTime.c_str()); + + //LOG_INFO("ZigbeeShortAddr = %s,SoftVersion = %s\n",dataNodeInfo.ZigbeeShortAddr.c_str(),dataNodeInfo.SoftVersion.c_str()); + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[48], pRecvData->Data[49]);//Zigbee 目标地址 2 byte + dataNodeInfo.ZigbeeDesAddr = std::string(buf); + //print_info("ZigbeeDesAddr = %s\n",buf); + //50 51 52=》序号23 zigbee重试间隔 + + memset(buf, 0, 32); + sprintf(buf, "%02x", pRecvData->Data[50]);//Zigbee 发射功率 1 byte + dataNodeInfo.ZigbeePower = atoi(buf); + //print_info("ZigbeePower = %s\n",buf); + + memset(buf, 0, 32); + sprintf(buf, "%d", BUILD_UINT16(00,pRecvData->Data[51]));//Zigbee 重试次数 1 byte + dataNodeInfo.ZigbeeRetry = atoi(buf); + //print_info("ZigbeeRetry = %s\n",buf); + + memset(buf, 0, 32); + sprintf(buf, "%d", BUILD_UINT16(00,pRecvData->Data[52]));//Zigbee 重试间隔 1 byte + dataNodeInfo.ZigbeeRetryGap = atoi(buf); + //print_info("ZigbeeRetryGap = %s\n",buf); + + + if(dataNodeInfo.ProductNo == "01"){ + chTemp = pRecvData->Data[53]; + unsigned char range = (chTemp >> 2) & 0x3; + dataNodeInfo.Range = range; + int SamplingRate = (chTemp & 0x3); + print_info("SamplingRate = %d\n",SamplingRate); + if(SamplingRate == 0){ + dataNodeInfo.SamplingRate = 3200; + }else if(SamplingRate == 1){ + dataNodeInfo.SamplingRate = 6400; + }else if(SamplingRate == 2){ + dataNodeInfo.SamplingRate = 12800; + }else if(SamplingRate == 3){ + dataNodeInfo.SamplingRate = 25600; + } + }else if(dataNodeInfo.ProductNo == "02"){ + chTemp = pRecvData->Data[53]; + unsigned char range = (chTemp >> 3) & 0x7; + dataNodeInfo.Range = range; + int SamplingRate = (chTemp & 0x7); + print_info("SamplingRate = %d\n",SamplingRate); + if(SamplingRate == 0){ + dataNodeInfo.SamplingRate = 8000; + }else if(SamplingRate == 1){ + dataNodeInfo.SamplingRate = 16000; + }else if(SamplingRate == 2){ + dataNodeInfo.SamplingRate = 24000; + }else if(SamplingRate == 3){ + dataNodeInfo.SamplingRate = 32000; + }else if(SamplingRate == 4){ + dataNodeInfo.SamplingRate = 48000; + }else if(SamplingRate == 5){ + dataNodeInfo.SamplingRate = 96000; + }else if(SamplingRate == 6){ + dataNodeInfo.SamplingRate = 192000; + } + } + // 54=》序号25 ACC采样时间 + memset(buf, 0, 32); + sprintf(buf, "%u", pRecvData->Data[54]);//ACC 采样时间 1 byte + dataNodeInfo.ACCSampleTime = atoi(buf); + + 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 = to_string(iTemp); + } else { + dataNodeInfo.StartBrands += ("," + to_string(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 = to_string(iTemp); + } else { + dataNodeInfo.StopBrands += ("," + to_string(iTemp)); + } + } + + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[75], pRecvData->Data[76]); + iTemp = (int)strtol(buf, NULL, 16); + dataNodeInfo.EnvelopeBandPass = to_string(iTemp); + + + memset(buf, 0, 32); + sprintf(buf, "%02x%02x", pRecvData->Data[77], pRecvData->Data[78]); + iTemp = (int)strtol(buf, NULL, 16); + dataNodeInfo.EnvelopeBandPass += ("," + to_string(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 = to_string(iTemp); + } else { + dataNodeInfo.FaultFrequency += ("," + to_string(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 = to_string(lTimeStamp); + + chTemp = pRecvData->Data[91]; + memset(buf, 0, 32); + sprintf(buf, "%d", chTemp); + dataNodeInfo.VIntegralFilterFrequency = atoi(buf); + + char whereCon[64] = {0}; + sprintf(whereCon, "dataNodeNo='%s'", dataNodeInfo.ZigbeeLongAddr.c_str()); + if (sql_ctl->GetTableRows(T_SENSOR_INFO(TNAME), whereCon) > 0) { + + char updateSql[1024] = { 0 }; + sprintf(updateSql, " initFlag = '%d',accFlag = '%d',zigbeeFlag = '%d',temTopFlag = '%d',temBotFlag = '%d',equipSta = '%d',\ + hardVersion = '%s',softVersion = '%s',bpNo = '%s',serialNo = '%s',firstPowerTime = '%s',WakeupTime = '%d',\ + StaticTime = '%d',WaveTime = '%d',BateryV = '%d',ProductNo = '%s',configFlag = '%d',startBrands = '%s',\ + stopBrands = '%s',featureInterVal = '%u',waveInterVal = '%d',samplingRate = '%d',scope = '%s',range = '%d',envelopeBandPass = '%s',faultFrequency = '%s',\ + zigbeePanId = '%s',zigbeeChannel = '%d',zigbeeShortAddr = '%s',zigbeeLongAddr = '%s',zigbeeDesAddr = '%s',\ + ZigbeePower = '%d',ZigbeeRetry = '%d',ZigbeeRetryGap = '%d',ACCSampleTime = '%d',status = '%s',timeStamp = '%s',viff = '%d',RSSI = '0,%d',UpdateFlag = 1", + 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.WakeupTime,\ + dataNodeInfo.StaticTime,dataNodeInfo.WaveTime,dataNodeInfo.BateryV,dataNodeInfo.ProductNo.c_str(),dataNodeInfo.ConfigFlag, dataNodeInfo.StartBrands.c_str(), \ + dataNodeInfo.StopBrands.c_str(), dataNodeInfo.FeatureInterVal, dataNodeInfo.WaveInterVal, dataNodeInfo.SamplingRate,"",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(), \ + dataNodeInfo.ZigbeePower,dataNodeInfo.ZigbeeRetry,dataNodeInfo.ZigbeeRetryGap,dataNodeInfo.ACCSampleTime,"1", dataNodeInfo.ConfigDate.c_str(),dataNodeInfo.VIntegralFilterFrequency,dataNodeInfo.RSSI); + sprintf(whereCon,"dataNodeNo = '%s'",dataNodeInfo.ZigbeeLongAddr.c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + }else{ + char insertSql[1024] = { 0 }; + sprintf(insertSql, " '%s','%s','%d','%d','%d','%d','%d','%d',\ + '%s','%s','%s','%s','%s','%d',\ + '%d','%d','%d','%s','%d','%s',\ + '%s','%u','%d','%d','%s','%d', '%s', '%s',\ + '%s','%d','%s','%s','%s',\ + '%d','%d','%d','%d','%s','%s', '%d', '0,%d','1','0,0','','',''", + 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.WakeupTime,\ + dataNodeInfo.StaticTime,dataNodeInfo.WaveTime,dataNodeInfo.BateryV,dataNodeInfo.ProductNo.c_str(),dataNodeInfo.ConfigFlag, dataNodeInfo.StartBrands.c_str(), \ + dataNodeInfo.StopBrands.c_str(), dataNodeInfo.FeatureInterVal, dataNodeInfo.WaveInterVal, dataNodeInfo.SamplingRate,"",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(), \ + dataNodeInfo.ZigbeePower,dataNodeInfo.ZigbeeRetry,dataNodeInfo.ZigbeeRetryGap,dataNodeInfo.ACCSampleTime,"1", dataNodeInfo.ConfigDate.c_str(),dataNodeInfo.VIntegralFilterFrequency,dataNodeInfo.RSSI); + sql_ctl->InsertData(T_SENSOR_INFO(TNAME), insertSql); + } + char szTableName[50]={0x00}; + sprintf(szTableName,"t_data_%s",dataNodeInfo.ZigbeeLongAddr.c_str()); + sql_ctl->Createtable(szTableName); + memset(szTableName,0x00,sizeof(szTableName)); + sprintf(szTableName,"t_dataStatic_%s",dataNodeInfo.ZigbeeLongAddr.c_str()); + sql_ctl->CreatedataStatictable(szTableName); + 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 strCmd26 = showValue.write(jsonVal); + //传感器发来的数据包中的表示设备信息的数据转化为json格式后,通过调用data_publish将数据传给mqttclient : Topic:wireless/cmd/60294D203717 + data_publish(strCmd26.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); + + if (g_mapCompress.find(dataNodeInfo.ZigbeeShortAddr) == g_mapCompress.end()){ + + compressWaveChannel tempchannel; + g_mapCompress.insert(std::make_pair(dataNodeInfo.ZigbeeShortAddr,tempchannel)); + print_info("new Node,size = %d\n",g_mapCompress.size()); + } + LOG_INFO("DealDataNodeInfo %s \n",dataNodeInfo.ZigbeeShortAddr.c_str()); +} + +void Uart::RecordBattery(string & strLongAddr,DataRecvStatic& dataStatic,string& nowTimetamp) +{ + char insertSql[1024] = { 0 }; + sprintf(insertSql, "'%s','%d','%f','%f','%f','%d','','','%s'", + strLongAddr.c_str(), dataStatic.Dip, dataStatic.TemBot,dataStatic.nodeWorkTime,dataStatic.nodeSendTime, dataStatic.Voltage,nowTimetamp.c_str()); + sql_ctl->InsertData(T_BATTERY_INFO(TNAME), insertSql); +} +void Uart::DealDataNodeFeature(const char *pData, int flag) +{ + print_info("recv feature\n"); + RecvData * pRecvData = (RecvData *)pData; + char whereCon[1024] = {0}; + char updateSql[1024] = { 0 }; + char buf[20] = {0x00}; + int nodeResend = 0,timing = 0; + sprintf(buf, "%02x%02x", pRecvData->ShortAddr[0], pRecvData->ShortAddr[1]); + if (flag == 1) + { + LOG_INFO("DealDataNodeFeature %02x%02x, %d\n",pRecvData->ShortAddr[0], pRecvData->ShortAddr[1],flag); + } + + + if (bSendTimeStamp)//波形处理中 + return; + std::string strShortAddr = std::string(buf); + print_info("zigbeeShortAddr='%s'\n", strShortAddr.c_str()); + 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); + vec_t vecResult = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME)," softVersion,dataNodeNo,MeasurementID ",getLongAddr_sql); + + if (vecResult.size() < 1) { + LOG_ERROR("device info not found %02x%02x\n",pRecvData->ShortAddr[0], pRecvData->ShortAddr[1]); + print_error("device info not found\n"); + return; + } + print_info("--------->the remote sensor short addr:%s strLongAddr=%s,softVersion = %s\n",buf,vecResult[1].c_str(),vecResult[0].c_str()); + + std::string strLongAddr = vecResult[1]; + std::string strMeasurementID = vecResult[2]; + if (1 == flag) { + + tcflush(fd,TCIOFLUSH); + + if (!bSendTimeStamp) + { + bSendTimeStamp = true; + modify_distaddr_info(0x9999,"",pRecvData->ShortAddr);//临时参数配置 + mssleep(10000); + + LOG_DEBUG("Zigbee Signal !\n"); + int Times = 0; + mssleep(20000); + while(Times < 3 ){ + getZigbeeSignal(pRecvData->ShortAddr); + Times ++ ; + mssleep(20000); + } + mssleep(10000); + timing = UpdateWirelessNodeTime((unsigned char*)pRecvData->ShortAddr,0); + }else + { + return; + } + + //modify_distaddr_info(0x9999,"",pRecvData->ShortAddr);//临时参数配置 + + GlobalConfig::ZigbeeInfo_G.MyAddr = "9999"; + GlobalConfig::Zigbee_G.MyAddr = 0x9999; + string strTime = GetLocalTimeWithMs(); + + m_strDestShortAddr = std::string(buf); + + bool isUpdate = ReadUpdatePackge(pRecvData->ShortAddr); + bUpdatePre = isUpdate; + if(!isUpdate){ + int iRet = UpdateConfig(pRecvData->ShortAddr); + } + if(isUpdate || bUpdateconfig){ + + }else{ + LOG_DEBUG("DealDataNodeFeature %02x%02x,localaddr %02x%02x \n",pRecvData->ShortAddr[0], pRecvData->ShortAddr[1],\ + UINT16_HIGH(GlobalConfig::Zigbee_G.MyAddr),UINT16_LOW(GlobalConfig::Zigbee_G.MyAddr)); + // 进入传输原始数据状态,启动计数 60秒 + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + } + unsigned char compressChannel = pRecvData->Data[34]; + compressWaveChannel tempchannel; + tempchannel.compressChannelX = GET_BIT(compressChannel ,0); + tempchannel.compressChannelY = GET_BIT(compressChannel ,2); + tempchannel.compressChannelZ = GET_BIT(compressChannel ,4); + tempchannel.CountX = BUILD_UINT16(pRecvData->Data[55],pRecvData->Data[54]); + tempchannel.CountY = BUILD_UINT16(pRecvData->Data[57],pRecvData->Data[56]); + tempchannel.CountZ = BUILD_UINT16(pRecvData->Data[59],pRecvData->Data[58]); + g_mapCompress[strShortAddr] = tempchannel; + + print_info("count X = %d,Y = %d,Z = %d\n",tempchannel.CountX,tempchannel.CountY,tempchannel.CountZ); + print_info("compress X = %d,Y = %d,Z = %d \n",tempchannel.compressChannelX,tempchannel.compressChannelY,tempchannel.compressChannelZ); + }else{ + memset(whereCon,0x00,sizeof(whereCon)); + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(whereCon, "zigbeeShortAddr='%s'", strShortAddr.c_str()); + sprintf(updateSql, " StaticTime = StaticTime + 1"); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + //string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + //data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + } + + if (vecResult[0] == "3.0" || vecResult[0] == "4.0"){ + return; + } + long staticIndex = BUILD_UINT32(pRecvData->Data[29], pRecvData->Data[28],pRecvData->Data[27], pRecvData->Data[26]); + + print_info("staticIndex = %d\n",staticIndex); + + + //LOG_INFO("staticIndex = %d\n",staticIndex); + + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + strTimetamp = nowTimetamp; + + int iTemp = 0; + unsigned char highbit = 0; + unsigned int lowbit = 0; + float n = 0; + + DataRecvStatic dataStatic; + memset(buf, 0, sizeof(buf)); + sprintf(buf, "%02x%02x", pRecvData->Data[5], pRecvData->Data[4]); + print_blue("!!!!!!!!!!!!!!!!!!!!!!%s\n",buf); + iTemp = (int)strtol(buf, NULL, 16); + dataStatic.Dip = iTemp; + + int fTemp = 0; + memset(buf, 0, sizeof(buf)); + sprintf(buf, "%02x%02x", pRecvData->Data[1], pRecvData->Data[0]); + print_blue("@@@@@@@@@@@@@@@@@%s\n",buf); + iTemp = (int)strtol(buf, NULL, 16); + if (iTemp < 0x8000) { + fTemp = iTemp ; + } else { + fTemp = (((~iTemp)&0xffff) + 1)* (-1); + } + dataStatic.TemBot = fTemp * 0.0625;//设备温度 + + fTemp = 0; + memset(buf, 0, sizeof(buf)); + sprintf(buf, "%02x%02x", pRecvData->Data[3], pRecvData->Data[2]); + iTemp = (int)strtol(buf, NULL, 16); + if (iTemp < 0x8000) { + fTemp = iTemp ; + } else { + fTemp = (((~iTemp)&0xffff) + 1) * (-1); + } + dataStatic.TemTop = fTemp * 0.0625;//环境温度 + + memset(buf, 0, sizeof(buf)); + sprintf(buf, "%02x%02x", pRecvData->Data[7], pRecvData->Data[6]); + iTemp = (int)strtol(buf, NULL, 16); + dataStatic.Voltage = iTemp; + + memset(buf, 0, sizeof(buf)); + 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; + } + dataStatic.nodeWorkTime = lowbit * n; + + print_info("workTime = %f\n",dataStatic.nodeWorkTime); + + memset(buf, 0, sizeof(buf)); + 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; + } + dataStatic.nodeSendTime = lowbit * n; + print_info("SendTime = %f\n",dataStatic.nodeSendTime ); + dataStatic.nodeWorkTime = dataStatic.nodeWorkTime - dataStatic.nodeSendTime; + + RecordBattery(strLongAddr,dataStatic,nowTimetamp); + + char szTableName[50]={0x00},szTableNameStatic[50]={0x00},szTableNameData[50]={0x00}; + sprintf(szTableName,"t_dataStatic_%s",strLongAddr.c_str()); + memcpy(szTableNameStatic,szTableName,sizeof(szTableNameStatic)); + memset(whereCon,0x00,sizeof(whereCon)); + + sprintf(whereCon,"StaticIndex = %d",staticIndex); + int count = sql_ctl->GetTableRows(szTableNameStatic, whereCon);//避免重复数据 + sprintf(szTableNameData,"t_data_%s",strLongAddr.c_str()); + + int count2 = sql_ctl->GetTableRows(szTableNameData, whereCon); + if(count > 0 || count2 > 0){ + char logInfo[20]={0x00}; + sprintf(logInfo,"ShortAddr = %s,staticIndex = %d,staticData = %d, data = %d",strShortAddr.c_str(),staticIndex,count,count2); + LOG_DEBUG(logInfo); + return; + } + memset(whereCon,0x00,sizeof(whereCon)); + ///////////////////////////////////////////////////////////// for V2.0.3 upgrade to V3.0 + std::string strTmp = ""; + char sztmp[100]={0x00}; + strTmp = "name = '" + string(szTableNameStatic)+ "' and sql LIKE '%nodeResend%' "; + + int row = sql_ctl->GetTableRows(" sqlite_master ",strTmp.c_str()); + print_info("row1 = %d\n",row); + if(row == 0){ + memset(sztmp,0x00,sizeof(sztmp)); + sprintf(sztmp,"ALTER TABLE %s ADD COLUMN 'nodeResend'",szTableNameStatic); + sql_ctl->CreateTable(sztmp); + } + // strTmp = "name = '" + string(szTableNameStatic)+ "' and sql LIKE '%zigbeeRSSIType%' "; + // row = sql_ctl->GetTableRows(" sqlite_master ",strTmp.c_str()); + // print_info("row2 = %d\n",row); + // if(row == 0){ + // memset(sztmp,0x00,sizeof(sztmp)); + // sprintf(sztmp,"ALTER TABLE %s ADD COLUMN 'zigbeeRSSIType'",szTableNameStatic); + // sql_ctl->CreateTable(sztmp); + // } + strTmp = "name = '" + string(szTableNameData)+ "' and sql LIKE '%nodeResend%' "; + row = sql_ctl->GetTableRows(" sqlite_master ",strTmp.c_str()); + print_info("row2 = %d\n",row); + if(row == 0){ + memset(sztmp,0x00,sizeof(sztmp)); + sprintf(sztmp,"ALTER TABLE %s ADD COLUMN 'nodeResend'",szTableNameData); + sql_ctl->CreateTable(sztmp); + } + + ////////////////////////////////////////////////////////////更换电池判断 + sprintf(whereCon," dataNodeNo = '%s' and StaticIndex > 0 order by StaticIndex desc LIMIT 0 , 1 ",strLongAddr.c_str()); + std::string strStaticIndex = sql_ctl->GetData(szTableNameStatic, "StaticIndex", whereCon); + if(atol(strStaticIndex.c_str()) - staticIndex > 100){ + sql_ctl->Deletetable(szTableNameStatic); + sql_ctl->Deletetable(szTableNameData); + LOG_INFO("staticIndexNOW = %d,strStaticIndexLast = %s\n",staticIndex,strStaticIndex.c_str()); + } + print_info("NowstaticIndex = %d,RecordStaticIndex = %d",staticIndex,atol(strStaticIndex.c_str())); + if(staticIndex != atol(strStaticIndex.c_str() + 1) && + strStaticIndex != "" && + staticIndex < atol(strStaticIndex.c_str())) + { + sprintf(whereCon,"StaticIndex = %d order by StaticIndex desc LIMIT 0 , 1",atol(strStaticIndex.c_str())); + vec_t vecResult = sql_ctl->GetDataSingleLine(szTableNameStatic, "timeStamp,StaticIndex", whereCon); + if(vecResult.size() > 0){ + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon,"dataNodeNo = '%s'",strLongAddr.c_str()); + string staticInterval = sql_ctl->GetData(T_SENSOR_INFO(TNAME), "featureInterval", whereCon); + long nNowTimetamp = atol(vecResult[0].c_str()) - (atol(staticInterval.c_str()) * \ + (atol(vecResult[1].c_str()) - staticIndex)) * 60; + char tmp[10]={0x00}; + sprintf(tmp,"%ld",nNowTimetamp); + nowTimetamp = string(tmp); + nodeResend = 1; + } + } + print_info("nowTimetamp = %s",nowTimetamp.c_str()); + // save dataStatic of 7 days + char selectCon[128] = { 0 }; + sprintf(selectCon, "channelID='%s' ORDER BY timeStamp ASC LIMIT 0,1",(strMeasurementID + "-S").c_str()); + std::string strTime = sql_ctl->GetData(szTableName, "timeStamp", selectCon); + sprintf(whereCon,"channelID='%s' ",(strMeasurementID + "-S").c_str()); + int Count = sql_ctl->GetTableRows(szTableName, whereCon); + if(Count == -1){ + sql_ctl->CreatedataStatictable(szTableName); + } + print_info("strLongAddr = %s,strTime = %s\n",strLongAddr.c_str(),strTime.c_str()); + long lTime = atol(nowTimetamp.c_str())-atol(strTime.c_str()); + print_info("lTime = %d,OneWeek = %d\n",lTime,OneWeek); + + print_info("dataStatic.TemTop : %f dataStatic.TemBot : %f dataStatic.Dip :%d dataStatic.Voltage : %d\n", dataStatic.TemTop\ + , dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage); + + sprintf(updateSql, "temTop='%f',temBot='%f',dip='%d',voltage='%d',timeStamp='%s',StaticIndex = %d, nodeResend = %d,zigbeeSignal = '',zigbeeSignalNode = '',statisticType = '%d',timing = '%d' ",\ + dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, nowTimetamp.c_str(),staticIndex,nodeResend,flag,timing); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-S").c_str()); + if ( /*0 == sql_ctl->GetTableRows(T_DATASTATIC_INFO(TNAME), whereCon)*/ (Count * 3 < SAVE_COUNT && lTime < OneWeek ) || strTime.size() == 0 ) { + print_info("insert static data to sql\n"); + char insertSql[1024] = { 0 }; + sprintf(insertSql, "'%s','%s','%f','%f','%d','%d','',%d,'%s','1',%d,'','%d','%d'", + strLongAddr.c_str(), (strMeasurementID + "-S").c_str(), dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, staticIndex,nowTimetamp.c_str(),nodeResend,flag,timing); + sql_ctl->InsertData(szTableName, insertSql); + + if(0 == sql_ctl->GetTableRows(T_DATASTATIC_INFO(TNAME), whereCon)){ // First Connect + char insertSql[1024] = { 0 }; + sprintf(insertSql, "'%s','%s','%f','%f','%d','%d','',%d,'%s','1',%d", + strLongAddr.c_str(), (strMeasurementID + "-S").c_str(), dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, staticIndex,nowTimetamp.c_str(),nodeResend); + sql_ctl->InsertData(T_DATASTATIC_INFO(TNAME), insertSql); + sql_ctl->CalculateBattery(); + } + else{ + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(updateSql, "temTop='%f',temBot='%f',dip='%d',voltage='%d',timeStamp='%s',StaticIndex = %d ",\ + dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, nowTimetamp.c_str(),staticIndex); + sql_ctl->UpdateTableData(T_DATASTATIC_INFO(TNAME), updateSql, whereCon); + } + } else { + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "channelID='%s' and timeStamp = '%s'", (strMeasurementID + "-S").c_str(),strTime.c_str()); + print_info("update static data to sql\n"); + sql_ctl->UpdateTableData(szTableName, updateSql, whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-S").c_str()); + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(updateSql, "temTop='%f',temBot='%f',dip='%d',voltage='%d',timeStamp='%s',StaticIndex = %d ",\ + dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, nowTimetamp.c_str(),staticIndex); + sql_ctl->UpdateTableData(T_DATASTATIC_INFO(TNAME), updateSql, whereCon); + } + memset(szTableName,0x00,sizeof(szTableName)); + sprintf(szTableName,"t_data_%s",strLongAddr.c_str()); + if(Count == -1){ + sql_ctl->Createtable(szTableName); + } + DataRecvDym dataDymX; + memset(buf, 0, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); +// 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; + + dataDymX.EnvelopEnergy = 0; + + memset(buf, 0, sizeof(buf)); +// 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; + + dataDymX.Phase1 = 0; + + memset(buf, 0, sizeof(buf)); +// 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 = 0; + + memset(buf, 0, sizeof(buf)); + + 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 = 0; + + memset(buf, 0, sizeof(buf)); + 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 = 0; + + memset(whereCon, 0, 1024); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-X").c_str()); + memset(updateSql, 0, 1024); + 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',StaticIndex = %d,nodeResend = %d ",\ + 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(),staticIndex,nodeResend); + if ( /*0 == sql_ctl->GetTableRows(T_DATA_INFO(TNAME), whereCon)*/(Count * 3 < SAVE_COUNT && lTime < OneWeek ) || strTime.size() == 0) {//1 week + char insertSql[1024] = { 0 }; + memset(insertSql,0x00,sizeof(insertSql)); + sprintf(insertSql, "'%s','%s','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f',%d,'%s','1',%d", + strLongAddr.c_str(), (strMeasurementID + "-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, staticIndex,nowTimetamp.c_str(),nodeResend); + sql_ctl->InsertData(szTableName, insertSql); + + if(0 == sql_ctl->GetTableRows(T_DATA_INFO(TNAME), whereCon)) + sql_ctl->InsertData(T_DATA_INFO(TNAME), insertSql); + else + sql_ctl->UpdateTableData(T_DATA_INFO(TNAME), updateSql, whereCon); + } else { + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "channelID='%s' and timeStamp = '%s'", (strMeasurementID + "-X").c_str(),strTime.c_str()); +// sprintf(whereCon, "channelID='%s' and sendMsg = '1' ", (strLongAddr + "-X").c_str()); + sql_ctl->UpdateTableData(szTableName, updateSql, whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-X").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(), (strMeasurementID + "-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"] = strMeasurementID; + valNodeFeature["ChannelId"] = strMeasurementID + "-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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); +// 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; + + dataDymY.EnvelopEnergy = 0; + + memset(buf, 0, sizeof(buf)); +// 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 = 0; + + memset(buf, 0, sizeof(buf)); +// 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 = 0; + + memset(buf, 0, sizeof(buf)); +// 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 = 0; + + memset(buf, 0, sizeof(buf)); +// 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 = 0; + + memset(whereCon, 0, 1024); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-Y").c_str()); + memset(updateSql, 0, 1024); + 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',StaticIndex = %d,nodeResend = %d ",\ + 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(),staticIndex,nodeResend); + if ( /*0 == sql_ctl->GetTableRows(T_DATA_INFO(TNAME), whereCon)*/ (Count * 3 < SAVE_COUNT && lTime < OneWeek ) || strTime.size() == 0) { + char insertSql[1024] = { 0 }; + memset(insertSql,0x00,sizeof(insertSql)); + sprintf(insertSql, "'%s','%s','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f',%d,'%s','1',%d", + strLongAddr.c_str(), (strMeasurementID + "-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,staticIndex, nowTimetamp.c_str(),nodeResend); + sql_ctl->InsertData(szTableName, insertSql); + + if(0 == sql_ctl->GetTableRows(T_DATA_INFO(TNAME), whereCon)) + sql_ctl->InsertData(T_DATA_INFO(TNAME), insertSql); + else + sql_ctl->UpdateTableData(T_DATA_INFO(TNAME), updateSql, whereCon); + } else { + + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "channelID='%s' and timeStamp = '%s'", (strMeasurementID + "-Y").c_str(),strTime.c_str()); +// sprintf(whereCon, "channelID='%s' and sendMsg = '1' ", (strLongAddr + "-Y").c_str()); + sql_ctl->UpdateTableData(szTableName, updateSql, whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-Y").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(), (strMeasurementID + "-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"] = strMeasurementID; + valNodeFeature["ChannelId"] = strMeasurementID + "-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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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, sizeof(buf)); + 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; + + 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, 1024); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-Z").c_str()); + memset(updateSql, 0, 1024); + + 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',StaticIndex = %d,nodeResend = %d ",\ + 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(),staticIndex,nodeResend); + if ( /*0 == sql_ctl->GetTableRows(T_DATA_INFO(TNAME), whereCon)*/ Count *3 < SAVE_COUNT && (lTime < OneWeek || strTime.size() == 0)) { + char insertSql[1024] = { 0 }; + memset(insertSql,0x00,sizeof(insertSql)); + sprintf(insertSql, "'%s','%s','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f',%d,'%s','1',%d", + strLongAddr.c_str(), (strMeasurementID + "-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, staticIndex,nowTimetamp.c_str(),nodeResend); + sql_ctl->InsertData(szTableName, insertSql); + + if(0 == sql_ctl->GetTableRows(T_DATA_INFO(TNAME), whereCon)) + sql_ctl->InsertData(T_DATA_INFO(TNAME), insertSql); + else + sql_ctl->UpdateTableData(T_DATA_INFO(TNAME), updateSql, whereCon); + } else { + + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "channelID='%s' and timeStamp = '%s'", (strMeasurementID + "-Z").c_str(),strTime.c_str()); +// sprintf(whereCon, "channelID='%s' and sendMsg = '1'", (strLongAddr + "-Z").c_str()); + sql_ctl->UpdateTableData(szTableName, updateSql, whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-Z").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(), (strMeasurementID + "-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()); + + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "dataNodeNo='%s'", strLongAddr.c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), "status='1'", whereCon); + //string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + //data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + //无线传感器Z信息 + valNodeFeature["dataNodeNo"] = strMeasurementID; + valNodeFeature["ChannelId"] = strMeasurementID + "-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); + + memset(whereCon, 0, 1024); + sprintf(whereCon, "dataNodeNo='%s'", strLongAddr.c_str()); + + string strBattery = sql_ctl->GetData(T_SENSOR_INFO(TNAME),"batteryPower",whereCon); + vector vBattery; + vBattery.push_back("0"); + vBattery.push_back("0"); + if(strBattery.length() > 0){ + + boost::split( vBattery, strBattery, boost::is_any_of( "," ), boost::token_compress_on ); + } + + //无线传感器信息 + Json::Value root; + Json::Value valdatastatic; + valdatastatic["TemperatureTop"] = dataStatic.TemTop; + valdatastatic["TemperatureBot"] = dataStatic.TemBot; + valdatastatic["WorkTime"] = dataStatic.nodeWorkTime; + valdatastatic["SendTime"] = dataStatic.nodeSendTime; + valdatastatic["Dip"] = dataStatic.Dip; + valdatastatic["Voltage"] = dataStatic.Voltage; + valdatastatic["ChannelType"] = "STATUS"; + valdatastatic["ChannelId"] = strMeasurementID + "-S"; + valdatastatic["TimeStamp"] = nowTimetamp; + valdatastatic["bateryProportion"] = atof(vBattery[1].c_str())/atof(vBattery[0].c_str()); + valdatastatic["batteryRemainDay"] = atof(vBattery[1].c_str()); + valdatastatic["dataNodeNo"] = strMeasurementID; + valNodeData.append(valdatastatic); + + root["data"] = valNodeData; + root["TimeStamp"] = nowTimetamp; + root["dataNodeNo"] = strMeasurementID; + root["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + Json::FastWriter featureValue; + std::string strstatisticData = featureValue.write(root); + //传感器发来的数据包中的表示设备信息的数据转化为json格式后,通过调用data_publish将数据传给mqttclient : Topic:wireless/cmd/60294D203717 + int iRet = data_publish(strstatisticData.c_str(), GlobalConfig::Topic_G.mPubData.c_str()); + print_info("dataNodeNo = '%s' and TimeStamp = '%s',MQTT ret = %d\n",strLongAddr.c_str(),nowTimetamp.c_str(),iRet); + if(iRet != 0){ + char updateSql[1024] = { 0 }; + memset(whereCon, 0, 64); + sprintf(whereCon, "dataNodeNo = '%s' and TimeStamp = '%s'", strLongAddr.c_str(),nowTimetamp.c_str()); + memcpy(updateSql, "sendMsg='0'",sizeof(updateSql)); + sql_ctl->UpdateTableData(szTableNameStatic, updateSql, whereCon); + sql_ctl->UpdateTableData(szTableNameData, updateSql, whereCon); + } + //综上代码,把静态数据,x y z轴的特征值存放到sql数据库中(如果数据原来不存在,则插入新数据;如果存在,则更新数据) + + print_info("Dip : %d TemBot : %f TemBot : %f Voltage : %d\n", dataStatic.Dip, dataStatic.TemBot, dataStatic.TemTop, dataStatic.Voltage); + + memset(selectCon,0x00,sizeof(selectCon)); + sprintf(selectCon, "zigbeeSignal <> '' ORDER BY timeStamp desc LIMIT 0,1"); + strTime = sql_ctl->GetData(szTableNameStatic, "timeStamp", selectCon); + + if (flag == 1) + { + LOG_INFO("DealDataNodeFeature end %02x%02x\n",pRecvData->ShortAddr[0], pRecvData->ShortAddr[1]); + } + +} + +void Uart::DealDataNodeWave(const char *pData,int comand) +{ + //print_info("recv wave\n"); + RecvData * pRecvData = (RecvData *)pData; + if (m_waveTrans) + { + if (comand == 3) + { + VecWaveDataX.push_back(*pRecvData); + }else if(comand == 4){ + VecWaveDataY.push_back(*pRecvData); + }else if(comand == 5){ + VecWaveDataZ.push_back(*pRecvData); + } + }else{ + if (comand == 3) + { + g_VecWaveDataX[m_waveCountX] = *pRecvData; + m_waveCountX++; + }else if(comand == 4){ + g_VecWaveDataY[m_waveCountY] = *pRecvData; + m_waveCountY++; + }else if(comand == 5){ + g_VecWaveDataZ[m_waveCountZ] = *pRecvData; + m_waveCountZ++; + } + } + //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) { +// sleep(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; +// offSize = 0; +// GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; +// GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; +// // 准备重新恢复到 8888 PanID,正常接收特征数据 +// mPackgeIndex = -1; +// //WriteLocalAddr(0x8888); +// //GlobalConfig::Zigbee_G.MyAddr = 0x8888; + +// // WriteShortAddr2Zigbee(0x8888); +// // UpdateZigbeeInfoCtrl(); + +// } else { +// print_info("NO! The time difference is less than 3,nowTimeStamp : %ld m_TimeStamp : %ld\n", nowTimeStamp, m_TimeStamp); +// } + DealWave(); + sleep(1); + } + +} +std::vector Uart::DealData(int iChannel,float coe,int sampleRate,int ACCSampleTime,string strProduct) +{ + + int waveCount = 0 ; + unsigned char data[1024*100]={0x00}; + unsigned char outdata[1024*100]={0x00}; + unsigned char dealdata[1024*100]={0x00}; + long unsigned int new_len = 0,deallen = 0; + int compress = 0,count = 0; + long iTemp = 0; + char buf[8] = {0x00}; + std::vector vecData; + print_info("data1 = %02x\n",g_VecWaveDataX[0].Data[0]); + print_info("data2 = %02x\n",g_VecWaveDataY[0].Data[0]); + print_info("data3 = %02x\n",g_VecWaveDataZ[0].Data[0]); + size_t j = 0; + std::string strShortAddr = ""; + if (iChannel == 3) + { + if (VecWaveDataX.size() > 0 ) + { + g_VecWaveDataX.assign(VecWaveDataX.begin(), VecWaveDataX.end()); + waveCount = VecWaveDataX.size(); + } + waveCount = m_waveCountX; + for (; j < waveCount; j++) + { + RecvData recvData = g_VecWaveDataX[j]; + memcpy(data + j * 92 ,recvData.Data,92); + } + memset(buf,0x00,sizeof(buf)); + sprintf(buf, "%02x%02x", g_VecWaveDataX[0].ShortAddr[0], g_VecWaveDataX[0].ShortAddr[1]); + strShortAddr = std::string(buf); + compress = g_mapCompress[strShortAddr].compressChannelX; + count = g_mapCompress[strShortAddr].CountX; + } + if (iChannel == 4) + { + if (VecWaveDataY.size() > 0 ) + { + g_VecWaveDataY.assign(VecWaveDataY.begin(), VecWaveDataY.end()); + waveCount = VecWaveDataY.size(); + } + waveCount = m_waveCountY; + for (; j < waveCount; j++) + { + RecvData recvData = g_VecWaveDataY[j]; + memcpy(data + j * 92 ,recvData.Data,92); + } + memset(buf,0x00,sizeof(buf)); + sprintf(buf, "%02x%02x", g_VecWaveDataY[0].ShortAddr[0], g_VecWaveDataY[0].ShortAddr[1]); + strShortAddr = std::string(buf); + compress = g_mapCompress[strShortAddr].compressChannelY; + count = g_mapCompress[strShortAddr].CountY; + } + if (iChannel == 5) + { + if (VecWaveDataZ.size() > 0 ) + { + g_VecWaveDataZ.assign(VecWaveDataZ.begin(), VecWaveDataZ.end()); + waveCount = VecWaveDataZ.size(); + } + waveCount = m_waveCountZ; + for (; j < waveCount; j++) + { + RecvData recvData = g_VecWaveDataZ[j]; + memcpy(data + j * 92 ,recvData.Data,92); + } + memset(buf,0x00,sizeof(buf)); + sprintf(buf, "%02x%02x", g_VecWaveDataZ[0].ShortAddr[0], g_VecWaveDataZ[0].ShortAddr[1]); + strShortAddr = std::string(buf); + compress = g_mapCompress[strShortAddr].compressChannelZ; + count = g_mapCompress[strShortAddr].CountZ; + } + if(j * 92 < count) + return vecData; + print_info("len = %d,data = %02x,iChannel = %d,compress = %d,count = %d\n",j,data[0],iChannel,compress,count); + if(compress){ + print_info("iChannel = %d,compress = %d\n",iChannel,compress); + int r = lzo1x_decompress(data,count,outdata,&new_len,NULL); + print_info("lzo1x_decompress end\n"); + if (r == LZO_E_OK ){ + printf("decompressed %lu bytes back into %lu bytes\n", + (unsigned long) j * 92, (unsigned long) new_len); + LOG_INFO("iChannel = %d ,ShortAddr = %s decompressed %lu bytes back into %lu bytes\n",iChannel,strShortAddr.c_str(), + (unsigned long) j * 92, (unsigned long) new_len); + } + else + { + /* this should NEVER happen */ + printf("internal error - decompression failed: %d\n", r); + LOG_ERROR("internal error - decompression failed: %d,channel = %d,ShortAddr = %s\n", r,iChannel,strShortAddr.c_str()); + return vecData; + } + memcpy(dealdata,outdata,new_len); + deallen = new_len; + }else{ + memcpy(dealdata,data,j * 92); + deallen = j * 92; + } + print_info("len = %d,dealdata = %02x\n",deallen,dealdata[0]); + for (int i = 0; i < deallen; i++) { + float fTemp = 0.0; + memset(buf, 0, 8); + sprintf(buf, "%02x%02x", dealdata[2*i+1],dealdata[i*2]); + iTemp = strtol(buf, NULL, 16); + if (iTemp < 0x8000) { + fTemp = iTemp * coe * 9.8; //convert to m/s2 + } else { + fTemp = (((~iTemp)&0xffff) + 1) * - coe * 9.8; //convert to m/s2 + } + vecData.push_back(fTemp); + if(strProduct == "01"){ + //print_blue("vecData.size() = %d,sampleRate * ACCSampleTime = %d,iChannel = %d\n",vecData.size(),sampleRate * ACCSampleTime,iChannel); + if(vecData.size() == sampleRate * ACCSampleTime && iChannel == 3 ){//过滤数据包结尾空数据 + print_blue("%d vecData.size() == %d,sampleRate * ACCSampleTime = %d\n",iChannel,vecData.size(),sampleRate * ACCSampleTime); + break; + } + if(vecData.size() == sampleRate * ACCSampleTime && iChannel == 4 ){//过滤数据包结尾空数据 + print_blue("%d vecData.size() == %d,sampleRate * ACCSampleTime = %d\n",iChannel,vecData.size(),sampleRate * ACCSampleTime); + break; + } + if(vecData.size() == sampleRate * ACCSampleTime && iChannel == 5 ){//过滤数据包结尾空数据 + print_blue("%d vecData.size() == %d,sampleRate * ACCSampleTime = %d\n",iChannel,vecData.size(),sampleRate * ACCSampleTime); + + break; + } + }else if(strProduct == "02"){ + if(vecData.size() == 8192 && iChannel == 3 ){//过滤数据包结尾空数据 + break; + } + if(vecData.size() == 8192 && iChannel == 4 ){//过滤数据包结尾空数据 + break; + } + if(vecData.size() == sampleRate * ACCSampleTime && iChannel == 5 ){//过滤数据包结尾空数据 + break; + } + } + } + return vecData; +} +void Uart::DealWave() +{ + //LOG_DEBUG("begin deal Wave data !\n"); + //print_blue("wave data size is(m_VecWaveData.size) : %d\n",m_VecWaveData.size()); + std::string strShortAddr = ""; + std::string strShortAddrTemp; + std::string strLongAddr = ""; + std::string strMeasurementID= ""; + std::string strFileName = ""; + std::string strProduct = ""; + int iChannel = 0; + int iChannelTemp = 0; + + std::vector vecData; + + RecvData recvTemp; + if (m_waveTrans) { //对每个传感器的每个通道进行遍历然后处理数据,例如:传感器1x轴的数据处理完后,再去处理y轴的。传感器1的所有数据处理完后,再处理传感器2的 + char getLongAddr_sql[32] = { 0 }; + sprintf(getLongAddr_sql, "zigbeeShortAddr='%s'", m_strDestShortAddr.c_str()); + vec_t res = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME)," * ",getLongAddr_sql); + strLongAddr = res[0]; + strMeasurementID = res[44]; + if ( 0 == strLongAddr.length() ) { + sleep(1); + return; + } + std::string ran = ""; + int n = 0; + int range = 0; + float coe = 0; + int sampleRate = 0,ACCSampleTime = 0; + char getrange[32] = {0}; + std::string str = "range"; + sprintf(getrange, "zigbeeShortAddr='%s'", strShortAddr.c_str()); + //ran = sql_ctl->GetData(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(RANGE), getrange); + ran = res[25]; + sampleRate = atoi(res[23].c_str()); + ACCSampleTime = atoi(res[36].c_str()); + strProduct = res[17]; + memset(getrange, 0, 32); + sprintf(getrange, "%s", ran.c_str()); + n = (int)strtol(getrange, NULL, 32); + if (m_waveCountX > 0 || VecWaveDataX.size() > 0) + { + print_info("m_waveCountX = %d,VecWaveData = %d\n",m_waveCountX,VecWaveDataX.size()); + coe = Calcoe(n,3,strProduct,range); + vecData = DealData(3,coe,sampleRate,ACCSampleTime,strProduct); + WriteDatFile(sampleRate, strMeasurementID, 3,vecData); + m_waveCountX = 0; + g_VecWaveDataX.clear(); + VecWaveDataX.clear(); + } + if (m_waveCountY > 0 || VecWaveDataY.size() > 0) + { + print_info("m_waveCountX = %d,VecWaveData = %d\n",m_waveCountY,VecWaveDataY.size()); + coe = Calcoe(n,4,strProduct,range); + vecData = DealData(4,coe,sampleRate,ACCSampleTime,strProduct); + WriteDatFile(sampleRate, strMeasurementID, 4,vecData); + m_waveCountY = 0; + g_VecWaveDataY.clear(); + VecWaveDataY.clear(); + } + if (m_waveCountZ > 0 || VecWaveDataZ.size() > 0) + { + print_info("m_waveCountZ = %d,VecWaveDataZ = %d\n",m_waveCountZ,VecWaveDataZ.size()); + coe = Calcoe(n,5,strProduct,range); + vecData = DealData(5,coe,sampleRate,ACCSampleTime,strProduct); + WriteDatFile(sampleRate, strMeasurementID, 5,vecData); + m_waveCountZ = 0; + g_VecWaveDataZ.clear(); + VecWaveDataZ.clear(); + + } + char whereCon[1024] = {0x00}; + char updateSql[1024] = {0x00}; + sprintf(whereCon, "dataNodeNo='%s'", strLongAddr.c_str()); + sprintf(updateSql, "WaveTime = WaveTime + 1"); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + m_waveTrans = false; + } + + + + + //string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + //data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + // memset(buf, 0, 8); + // sprintf(buf, "%02x%02x", recvTemp.ShortAddr[0], recvTemp.ShortAddr[1]); + // std::string strShortAddr = std::string(buf); + +} +float Uart::Calcoe(int ran,int iChannel,string& product,int range) +{ + float coe = 0.0; + if(product== "01"){ + switch (ran) + { + 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; + } + }else if(product == "02"){ + if(iChannel == 3 || iChannel == 4){ + coe = 0.00048828125; + } + if(iChannel == 5){ + /*if(res[8] == "0.1"){ + coe = 0.0034521484375;//0.03265968810083316; + }else*/ + { + coe = 0.00172607421875; + } + } + } + return coe; +} +void Uart::WriteDatFile(int sampleRate,string& strMeasurementID,int iChannel,std::vector& vecData) +{ + if(vecData.size() <= 0) + return; + std::string strFileName = ""; + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + std::string strChannelID = ""; + switch (iChannel) + { + case 3:{ + strFileName = "/opt/data/" + strMeasurementID + "-X.dat"; + strChannelID = strMeasurementID + "-X"; + } + break; + case 4:{ + strFileName = "/opt/data/" + strMeasurementID + "-Y.dat"; + strChannelID = strMeasurementID + "-Y"; + } + break; + case 5:{ + strFileName = "/opt/data/" + strMeasurementID + "-Z.dat"; + strChannelID = strMeasurementID + "-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"); + fwrite(localtimestamp,sizeof(localtimestamp),1,fp); + print_info("fopen FIle vecData.size : %d\n", vecData.size()); + float mean = pCalculation->mean(vecData); + float frTemp; + char buf[33]={0x00}; + std::string strWaveData = ""; + for (int i = 0; i < vecData.size(); i++) { + frTemp = vecData[i] - mean; + fwrite(&frTemp,sizeof(float),1,fp); + memset(buf,0x00,sizeof(buf)); + sprintf(buf, "%.2f", frTemp); + std::string waveTemp(buf); + if(i == 0) + strWaveData = waveTemp; + else + strWaveData = strWaveData + "," + waveTemp; + + if (i % 100 == 0) + { + mssleep(5000); + } + } + + fclose(fp); + // + Json::Value valWaveData; + int length = vecData.size(); + valWaveData["number"] = sampleRate; + valWaveData["channelId"] = strChannelID; + valWaveData["dataNodeNo"] = strMeasurementID; + valWaveData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; + valWaveData["SensorEngineeringUnit"] = ""; + valWaveData["timeStamp"] = nowTimetamp; + valWaveData["waveData"] = strWaveData; + valWaveData["mean"] = mean; + Json::FastWriter WaveValue; + std::string WaveData = WaveValue.write(valWaveData); + + char selectCon[128] = { 0 }; + sprintf(selectCon, "channelID='%s' ORDER BY timeStamp ASC LIMIT 0,1",strChannelID.c_str()); + std::string strTime = sql_ctl->GetData("t_data_waveSend", "timeStamp", selectCon); + long lTime = atol(nowTimetamp.c_str())-atol(strTime.c_str()); + int Count = sql_ctl->GetTableRows("t_data_waveSend", NULL); + std::string strFileName_Record = strFileName + "_" + nowTimetamp; + if ((Count * 3 < SAVE_COUNT && lTime < OneWeek ) || strTime.size() == 0 ) { + char insertSql[128]={0x00}; + sprintf(insertSql,"'%s','%s','%s',1,0",strChannelID.c_str(),strFileName_Record.c_str(),nowTimetamp.c_str()); + sql_ctl->InsertData("t_data_waveSend", insertSql); + }else{ + char updateSql[128] = { 0 },whereCon[128] = {0}; + sprintf(updateSql, "waveName='%s',timeStamp='%s'",strFileName_Record.c_str(),nowTimetamp.c_str()); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "channelID='%s' and timeStamp = '%s'", strChannelID.c_str(),strTime.c_str()); + print_info("update static data to sql\n"); + sql_ctl->UpdateTableData("t_data_waveSend", updateSql, whereCon); + } + //传感器发来的数据包中的表示设备信息的数据转化为json格式后,通过调用data_publish将数据传给mqttclient : Topic:wireless/cmd/60294D203717 + + int iRet = data_publish(WaveData.c_str(), GlobalConfig::Topic_G.mPubWaveData.c_str()); + if(iRet != 0){ + char whereCon[1024] = {0x00}; + char updateSql[1024] = {0x00}; + char tmpWhere[128]={0x00}; + sprintf(tmpWhere,"channelID = '%s' and sendMsg = 0 ",strChannelID.c_str()); + int count = sql_ctl->GetTableRows("t_data_waveSend", tmpWhere); + LOG_ERROR("save channlID %s dat count = %d\n",strChannelID.c_str(),count); + if(count <= 12) + { + sprintf(whereCon, "channelID='%s' and timeStamp = '%s' ", strChannelID.c_str(),nowTimetamp.c_str()); + sprintf(updateSql, "SendMsg = 0 "); + sql_ctl->UpdateTableData("t_data_waveSend", updateSql, whereCon); + LOG_ERROR("send failed,filename %s,iRet = %d\n",strFileName.c_str(),iRet); + string strFileName_failed = strFileName + "_" + nowTimetamp; + char tmpCmd[128]={0x00}; + sprintf(tmpCmd,"cp %s %s",strFileName.c_str(),strFileName_failed.c_str()); + system(tmpCmd); + }else { + memset(tmpWhere,0x00,sizeof(tmpWhere)); + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(tmpWhere, " sendMsg = 0 and channelID='%s' ORDER BY timeStamp ASC LIMIT 0,1",strChannelID.c_str()); + vec_t vecRet = sql_ctl->GetDataSingleLine("t_data_waveSend","*",tmpWhere); + memset(tmpWhere,0x00,sizeof(tmpWhere)); + sprintf(tmpWhere, " sendMsg = 0 and timeStamp = '%s' and channelID = '%s' ",vecRet[2].c_str(),vecRet[0].c_str()); + sprintf(updateSql, "sendMsg = 3 "); + int iRet = sql_ctl->UpdateTableData("t_data_waveSend", updateSql, tmpWhere); + memset(tmpWhere,0x00,sizeof(tmpWhere)); + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(whereCon, "channelID='%s' and timeStamp = '%s' ", strChannelID.c_str(),nowTimetamp.c_str()); + sprintf(updateSql, "sendMsg = 0"); + int iRet2 = sql_ctl->UpdateTableData("t_data_waveSend", updateSql, whereCon); + + string strFileName_failed = strFileName + "_" + nowTimetamp; + char tmpCmd[128]={0x00}; + sprintf(tmpCmd,"cp %s %s",strFileName.c_str(),strFileName_failed.c_str()); + system(tmpCmd); + LOG_ERROR("cp dat file %s \n",tmpCmd); + + memset(tmpWhere,0x00,sizeof(tmpWhere)); + sprintf(tmpWhere," channelID = '%s' and sendMsg = 0 ",strChannelID.c_str()); + int count = sql_ctl->GetTableRows("t_data_waveSend", tmpWhere); + + memset(tmpCmd,0x00,sizeof(tmpCmd)); + sprintf(tmpCmd,"rm %s ",vecRet[1].c_str()); + system(tmpCmd); + LOG_ERROR("rm dat file %s \n",tmpCmd); + + } + + }else{ + LOG_DEBUG("send data , filename %s,size = %d\n", strFileName.c_str(),vecData.size()); + } +#ifdef G2UL_GATEWAY//存储6条波形数据 + char whereCon[1024] = {0x00}; + char updateSql[1024] = {0x00}; + char tmpWhere[128]={0x00}; + sprintf(tmpWhere,"channelID = '%s' and save = 1 ",strChannelID.c_str()); + int count = sql_ctl->GetTableRows("t_data_waveSend", tmpWhere); + LOG_INFO("save channlID %s dat count = %d\n",strChannelID.c_str(),count); + if(count <= 5) + { + sprintf(whereCon, "channelID='%s' and timeStamp = '%s' ", strChannelID.c_str(),nowTimetamp.c_str()); + sprintf(updateSql, "save = 1 "); + sql_ctl->UpdateTableData("t_data_waveSend", updateSql, whereCon); + string strFileName_save = strFileName + "_" + nowTimetamp + "_save"; + char tmpCmd[128]={0x00}; + sprintf(tmpCmd,"cp %s %s",strFileName.c_str(),strFileName_save.c_str()); + system(tmpCmd); + }else { + memset(tmpWhere,0x00,sizeof(tmpWhere)); + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(tmpWhere, " save = 1 and channelID='%s' ORDER BY timeStamp ASC LIMIT 0,1",strChannelID.c_str()); + vec_t vecRet = sql_ctl->GetDataSingleLine("t_data_waveSend","*",tmpWhere); + memset(tmpWhere,0x00,sizeof(tmpWhere)); + sprintf(tmpWhere, " save = 1 and timeStamp = '%s' and channelID = '%s' ",vecRet[2].c_str(),vecRet[0].c_str()); + sprintf(updateSql, "save = 0 "); + int iRet = sql_ctl->UpdateTableData("t_data_waveSend", updateSql, tmpWhere); + memset(tmpWhere,0x00,sizeof(tmpWhere)); + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(whereCon, "channelID='%s' and timeStamp = '%s' ", strChannelID.c_str(),nowTimetamp.c_str()); + sprintf(updateSql, "save = 1"); + int iRet2 = sql_ctl->UpdateTableData("t_data_waveSend", updateSql, whereCon); + + string strFileName_save = strFileName + "_" + nowTimetamp + "_save"; + char tmpCmd[128]={0x00}; + sprintf(tmpCmd,"cp %s %s",strFileName.c_str(),strFileName_save.c_str()); + system(tmpCmd); + + memset(tmpWhere,0x00,sizeof(tmpWhere)); + sprintf(tmpWhere," channelID = '%s' and save = 1 ",strChannelID.c_str()); + int count = sql_ctl->GetTableRows("t_data_waveSend", tmpWhere); + + memset(tmpCmd,0x00,sizeof(tmpCmd)); + sprintf(tmpCmd,"rm %s ",(vecRet[1]+"_save").c_str()); + system(tmpCmd); + LOG_INFO("rm dat file %s \n",tmpCmd); + } + +#endif + print_info("write data to filename %s\n", strFileName.c_str()); + std::vector().swap(vecData); + sleep(1); + +} +void Uart::DealNodeSendTime(unsigned char* shortaddr) +{ + + /*char updateSql[1024]={0x00},whereCon[1024]={0x00},insertSql[1024]={0x00}; + memset(whereCon,0x00,sizeof(whereCon)); + memset(insertSql,0x00,sizeof(insertSql)); + sprintf(whereCon,"dataNodeNo = '%s'",dataNodeInfo.ZigbeeLongAddr.c_str()); + int nodegroup = 0; + int staticStartTime = 0; + int nodeindex = 0; + int statictime = 0; + int nodewaveindex = 1; + if(0 == sql_ctl->GetTableRows(T_DATANODE_TIME(TNAME), whereCon)){ + + sprintf(whereCon,"staticcycle = '%d' and wavecycle = '%d' order by nodeindex desc LIMIT 0 , 1",dataNodeInfo.FeatureInterVal,dataNodeInfo.WaveInterVal); + vec_t vecResult = sql_ctl->GetDataSingleLine(T_DATANODE_TIME(TNAME),"*",whereCon); + if(vecResult.size() == 0){ + string strResult = sql_ctl->GetData(T_DATANODE_TIME(TNAME),"nodegroup"," nodegroup > 0 order by nodegroup desc LIMIT 0 , 1"); + if(atoi(strResult.c_str()) > 0){ + print_info("strResult = %s\n",strResult.c_str()); + nodegroup = atoi(strResult.c_str()) + 1; + }else{ + nodegroup = 1; + } + staticStartTime = 0; + }else{ + nodegroup = atoi(vecResult[4].c_str()); + nodewaveindex = atoi(vecResult[6].c_str()) + 1; + statictime = atoi(vecResult[7].c_str()) + atoi(vecResult[2].c_str()); + if(statictime > atoi(vecResult[3].c_str())){ + staticStartTime = ceil(atof(vecResult[2].c_str()) / 2 ); + statictime = staticStartTime; + nodewaveindex = 1; + }else{ + staticStartTime = atoi(vecResult[8].c_str()); + } + } + std::string strnodeinex = sql_ctl->GetData(T_DATANODE_TIME(TNAME), "nodeindex", "nodeindex > 0 order by nodeindex desc LIMIT 0 , 1"); + LOG_INFO("DealNodeSendTime strnodeinex = %s\n",strnodeinex.c_str()); + nodeindex = atoi(strnodeinex.c_str())+1; + sprintf(insertSql,"'%s','%s','%d','%d',%d,%d,%d,%d,%d",dataNodeInfo.ZigbeeLongAddr.c_str(),dataNodeInfo.ZigbeeShortAddr.c_str(),\ + dataNodeInfo.FeatureInterVal,dataNodeInfo.WaveInterVal,nodegroup,nodeindex,nodewaveindex,statictime,staticStartTime); + sql_ctl->InsertData(T_DATANODE_TIME(TNAME), insertSql); + LOG_INFO("DealNodeSendTime InsertData = %s\n",insertSql); + UpdateWirelessNodeTime(shortaddr,nodewaveindex,staticStartTime,nodeindex);//更新时间戳 + }else{ + sprintf(whereCon,"staticcycle = '%d' and wavecycle = '%d' order by nodeindex desc LIMIT 0 , 1", + dataNodeInfo.FeatureInterVal,dataNodeInfo.WaveInterVal); + + vec_t vecResult = sql_ctl->GetDataSingleLine(T_DATANODE_TIME(TNAME),"*",whereCon); + if(vecResult.size() == 0){ + string strResult = sql_ctl->GetData(T_DATANODE_TIME(TNAME),"nodegroup"," nodegroup > 0 order by nodeindex desc LIMIT 0 , 1"); + if(atoi(strResult.c_str()) > 0){ + nodegroup = atoi(strResult.c_str()) + 1; + }else{ + nodegroup = 1; + } + staticStartTime = 0; + statictime = 0; + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon,"dataNodeNo = '%s'",dataNodeInfo.ZigbeeLongAddr.c_str()); + sprintf(updateSql," staticcycle = '%d',wavecycle = '%d',nodegroup = %d,nodewaveindex = %d,statictime = %d, staticstarttime = %d",dataNodeInfo.FeatureInterVal,dataNodeInfo.WaveInterVal,\ + nodegroup,nodewaveindex,statictime,staticStartTime); + sql_ctl->UpdateTableData(T_DATANODE_TIME(TNAME), updateSql, whereCon); + LOG_INFO("DealNodeSendTime updateSql = %s\n",updateSql); + LOG_DEBUG("DealNodeSendTime1"); + UpdateWirelessNodeTime(shortaddr,nodewaveindex,staticStartTime,nodeindex);//更新时间戳 + }else{ + print_info("=======Send Time======\n"); + LOG_DEBUG("DealNodeSendTime2"); + UpdateWirelessNodeTime(shortaddr,atoi(vecResult[6].c_str()),atoi(vecResult[8].c_str()),atoi(vecResult[5].c_str()));//更新时间戳 + } + } + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon,"dataNodeNo = '%s' and staticcycle <> '%d' and wavecycle <> '%d'",dataNodeInfo.ZigbeeLongAddr.c_str(),\ + dataNodeInfo.FeatureInterVal,dataNodeInfo.WaveInterVal); + sql_ctl->DeleteTableData(T_DATANODE_TIME(TNAME),whereCon);*/ + + +} +bool Uart::CheckCrc(char* pCheckBuff,int No) +{ + unsigned char tmp = 0x00; + for(int i = 0 ; i < No;i++){ + tmp += (unsigned char)pCheckBuff[i]; +// printf("%02x ",pCheckBuff[i]); + } + + if((unsigned char)pCheckBuff[No] != (unsigned char)tmp) + return false; + return true; + +} +void Uart::modify_distaddr_info(unsigned short id, char * zigbee,unsigned char* distAddr) +{ + char command[6] = {0x00}; + command[0] = 0xDE; + command[1] = 0xDF; + command[2] = 0xEF; + command[3] = 0xDC; + command[4] = ((char *)&id)[1]; + command[5] = ((char *)&id)[0]; + WriteToUart(command, 6); + + mssleep(10000); + memset(command,0x00,sizeof(command)); + command[0] = 0xDE; + command[1] = 0xDF; + command[2] = 0xEF; + command[3] = 0xD2; + command[4] = distAddr[0]; + command[5] = distAddr[1]; + WriteToUart(command, 6); + + +} +void Uart::getZigbeeSignal(unsigned char* distAddr) +{ + mssleep(10000); + char command[6] = {0x00}; + command[0] = 0xDE; + command[1] = 0xDF; + command[2] = 0xEF; + command[3] = 0xDA; + command[4] = distAddr[0]; + command[5] = distAddr[1]; + WriteToUart(command, 6); +} +void Uart::modify_DistAddr(unsigned char* distAddr) +{ + char command[6] = {0x00}; + memset(command,0x00,sizeof(command)); + command[0] = 0xDE; + command[1] = 0xDF; + command[2] = 0xEF; + command[3] = 0xD2; + command[4] = distAddr[0]; + command[5] = distAddr[1]; + WriteToUart(command, 6); +} +void Uart::modify_LocalAddr(unsigned short id) +{ + char command[6] = {0x00}; + + + command[0] = 0xDE; + command[1] = 0xDF; + command[2] = 0xEF; + command[3] = 0xDC; + command[4] = ((char *)&id)[1]; + command[5] = ((char *)&id)[0]; + WriteToUart(command, 6); +// ReadFromUart(); + +} +void Uart::modify_Localchannel(unsigned char pad) +{ + char command[6] = {0x00}; + command[0] = 0xDE; + command[1] = 0xDF; + command[2] = 0xEF; + command[3] = 0xD1; + command[4] = pad & 0xff; + WriteToUart(command, 5); +// ReadFromUart(); + +} +void Uart::modify_LocalPanID(unsigned short padID) +{ + char command[6] = {0x00}; + command[0] = 0xDE; + command[1] = 0xDF; + command[2] = 0xEF; + command[3] = 0xDB; + command[4] = ((char *)&padID)[1]; + command[5] = ((char *)&padID)[0]; + WriteToUart(command, 6); +// ReadFromUart(); + +} +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)[0]; + command[5] = ((char *)&id)[1]; + 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] = 0xaa; + WriteToUart(command, i+1); + sleep(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); + + gpio_set(GlobalConfig::GPIO_G.zigReset,0); + mssleep(10000); + gpio_set(GlobalConfig::GPIO_G.zigReset,1); +} + +void Uart::WritePanId2Zigbee(unsigned short pad) +{ + print_info("WritePanId2Zigbee : %d\n", pad); + unsigned short pad1 = pad,tmp; + tmp = GlobalConfig::Zigbee_G.MyAddr; + print_info("MyAddr : %d\n", GlobalConfig::Zigbee_G.MyAddr); + swap((char *)&pad1); + //swap((char *)&tmp); + GlobalConfig::Zigbee_G.PanID = pad1; + modify_info(tmp, (char *)&GlobalConfig::Zigbee_G); + + gpio_set(GlobalConfig::GPIO_G.zigReset,0); + mssleep(10000); + gpio_set(GlobalConfig::GPIO_G.zigReset,1); +} +void Uart::WriteSpeed2Zigbee() +{ + GlobalConfig::Zigbee_G.Serial_Rate = 0x07; + GlobalConfig::Zigbee_G.Serial_DataB = 0x08; + GlobalConfig::Zigbee_G.Serial_StopB = 0x01; + unsigned short tmp; + tmp = GlobalConfig::Zigbee_G.MyAddr; + modify_info(tmp, (char *)&GlobalConfig::Zigbee_G); + gpio_set(GlobalConfig::GPIO_G.zigReset,0); + mssleep(10000); + gpio_set(GlobalConfig::GPIO_G.zigReset,1); +} +/*void Uart::WriteLocalAddr(unsigned short id) +{ + gpio_set(116,0); + mssleep(10000); + gpio_set(116,1); + sleep(1); + char command[8]={0x00}; + command[0] = 0xab; + command[1] = 0xbc; + command[2] = 0xcd; + command[3] = 0xdc; + command[4] = ((char *)&id)[1]; + command[5] = ((char *)&id)[0]; + command[6] = 0x00; + command[7] = 0xaa; + WriteToUart(command, 8); + mssleep(600000); + gpio_set(116,0); + mssleep(10000); + gpio_set(116,1); +}*/ +void Uart::WriteTranTimeout2Zigbee(unsigned char Time) +{ + print_info("WriteTranTimeout2Zigbee : %d\n", Time); + + unsigned short tmp = GlobalConfig::Zigbee_G.MyAddr; + //print_info("MyAddr : %d\n", GlobalConfig::Zigbee_G.MyAddr); + GlobalConfig::Zigbee_G.PowerLevel = 0x03; + GlobalConfig::Zigbee_G.RetryNum = 0x64; + GlobalConfig::Zigbee_G.TranTimeout = Time; + modify_info(tmp, (char *)&GlobalConfig::Zigbee_G); + + gpio_set(GlobalConfig::GPIO_G.zigReset,0); + mssleep(10000); + gpio_set(GlobalConfig::GPIO_G.zigReset,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); + + gpio_set(GlobalConfig::GPIO_G.zigReset,0); + mssleep(10000); + gpio_set(GlobalConfig::GPIO_G.zigReset,1); + sleep(1); +} + +void Uart::WriteShortAddr_DistAddr2Zigbee(unsigned short pad,unsigned char* pDestShortAddr) +{ + print_info("WriteShortAddr2Zigbee : %4x\n", (unsigned short)pad); + unsigned short pad1 = pad,tmp; + tmp = GlobalConfig::Zigbee_G.MyAddr; + swap((char *)&pad1); + swap((char *)&tmp); + char tmpDest[8]={0x00}; + sprintf(tmpDest,"%02x%02x",pDestShortAddr[0],pDestShortAddr[1]); + memcpy(&GlobalConfig::Zigbee_G.DstAddr,pDestShortAddr,2); + GlobalConfig::Zigbee_G.MyAddr = pad1; +// GlobalConfig::Zigbee_G.DstAddr = (short)atoi((char*)tmpDest); + print_info("DstAddr = %x\n",GlobalConfig::Zigbee_G.DstAddr); + GlobalConfig::ZigbeeInfo_G.MyAddr = "9999"; + modify_info(tmp, (char *)& GlobalConfig::Zigbee_G); + + gpio_set(GlobalConfig::GPIO_G.zigReset,0); + mssleep(10000); + gpio_set(GlobalConfig::GPIO_G.zigReset,1); +} +int Uart::CheckZigbeeACK() +{ + if(gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 48) + gpio_set(GlobalConfig::GPIO_G.zigAckreset,1); + int time = 0,value = 0,iRet = -1; + do{ + value = gpio_read(GlobalConfig::GPIO_G.zigAckrep); + if(value == 49) + { + iRet = 0; + break; + } + mssleep(10000); + }while(time < 150); + return iRet; +} +void Uart::ZigbeeInit() +{ + std::string strPanId = sql_ctl->GetData("t_gateway_info","zigbeePanID",NULL); + + { + unsigned short shortAddr = 0x8888; + //GlobalConfig::Zigbee_G.MyAddr = shortAddr; + //WriteLocalAddr(shortAddr); + WriteShortAddr2Zigbee(shortAddr); + mssleep(100000); + // 更新GlobalConfig::ZigbeeInfo_G.MyAddr,用于外部显示 + + } + + //std::string strPanId = GlobalConfig::MacAddr_G.substr(8); + print_info("strPanId : %s\n", strPanId.c_str()); + print_info("MacAddr_G : %s\n", GlobalConfig::MacAddr_G.c_str()); + // 新增管理ZigBee代码 + std::string strchan = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "channel"); + + unsigned short Chan = (unsigned short)strtol(strchan.c_str(), NULL, 10); + print_info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%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) + { + WriteChanl2Zigbee(Chan); + //modify_Localchannel(Chan); + mssleep(100000); + } + } + print_info("PanID1 = %s,strPanId = %s\n",GlobalConfig::ZigbeeInfo_G.PanID.c_str(),strPanId.c_str()); + //if (0 != GlobalConfig::ZigbeeInfo_G.PanID.compare(strPanId.c_str())) + { + long lShortAddr = strtol(strPanId.c_str(), NULL, 16); + unsigned short panid = lShortAddr & 0xffff; + //modify_LocalPanID(panid); + + WritePanId2Zigbee(panid); + mssleep(100000); + } + + //if (0 != GlobalConfig::ZigbeeInfo_G.MyAddr.compare("8888")) + + 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..3928563 --- /dev/null +++ b/uart/SH_Uart.hpp @@ -0,0 +1,130 @@ +#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" +#include "../calculation/Calculation.hpp" + + + +//using namespace boost::asio; +//using std::string; +//using boost::system::error_code; +typedef unsigned int UINT; + +typedef void (*pTestRecvCallBack)(int Status); + +class Uart : public MySingleton +{ +private : + boost::posix_time::ptime mLocalTime; + boost::asio::io_service mIoSev; + boost::asio::serial_port mUart; + int mRdLength; + int mlastSize; + int mPackgeIndex; + string strTimetamp; + + //DataNodeInfo dataNodeInfo; + std::string m_strDestShortAddr; + + int waittime; + enum{BUF_LENGTH = 40960}; + unsigned char mUartRecvBuf[BUF_LENGTH]; + char mUartRecvTmpBuf[BUF_LENGTH*15]; + boost::mutex mLock; + boost::asio::io_service::strand mStrand; + +public : + Uart(); + ~Uart(); + void InitZigbee(); + void InitUart(speed_t speed); + void Close(); + void InitTestUart(speed_t speed); + void ReadTestUart(); + int fd,TestFd; + bool bUpdate; + bool bUpdatePre; + bool bUpdateconfig; + bool bTest; + bool bZigbeeSinal; + bool bModifyAddr; + bool bSendTimeStamp; + std::string DataNodeUpdateFile; + void WriteToUart(const char *strSend,int pLen); + int 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 DealDataNodeName(const char *pData); + void DealDataNodeFeature(const char *pData, int flag); + void DealDataNodeWave(const char *pData,int comand); + void DealWaveThread(); + void DealWave(); + std::vector DealData(int ichannel,float coe,int sampleRate,int ACCSampleTime,string strProduct); + float Calcoe(int ran,int iChannel,string& product,int range); + void WriteDatFile(int sampleRate,string& strMeasurementID,int iChannel,std::vector& vecData); + void DealNodeSendTime(unsigned char* shortaddr); + void ZigbeeInit(); + int ZigbeeTest(); + void RecordBattery(string & strLongAddr,DataRecvStatic& dataStatic,string& nowTimetamp); + + void modify_info(unsigned short id, char * zigbee); + void modify_distaddr_info(unsigned short id, char * zigbee,unsigned char* distAddr); + void modify_LocalAddr(unsigned short id); + void modify_DistAddr(unsigned char* distAddr); + void modify_Localchannel(unsigned char pad); + void modify_LocalPanID(unsigned short padID); + void getZigbeeSignal(unsigned char* distAddr); + void zigbee_reset(unsigned short pad, unsigned short type); + void WriteChanl2Zigbee(unsigned char pad); + void WritePanId2Zigbee(unsigned short pad); + void WriteSpeed2Zigbee(); + //void WriteLocalAddr(unsigned short id); + void WriteTranTimeout2Zigbee(unsigned char Time); + void WriteShortAddr2Zigbee(unsigned short pad); + void WriteShortAddr_DistAddr2Zigbee(unsigned short pad,unsigned char* pDestShortAddr); + void UpdateWirelessNode(unsigned short shortAdd); + int UpdateWirelessNodeTime(unsigned char* pDestShortAddr,int modifyaddr/*,int nodewaveindex,int nodetime,int nodeindex*/); + int UpdateConfig(unsigned char* pDestShortAddr); + bool ReadUpdatePackge(unsigned char* shortAddr); + bool CheckCrc(char* pCheckBuff,int No); + int FindRecvPackage(int bytesRead, char* mUartRecvBuf,char* head); + virtual void DataAnalysis_R(DevDataOfGwid &pData); + virtual void DataAnalysis_W(DevData &pData,bool pFlag); + virtual void ThreadInit(); + int UartRecv(int fd, char srcshow,char* buffer); + void openSwitch(); + int CheckZigbeeACK(); +private : + void ReadHandle(char* pUartRecvBuf,size_t bytesRead); + void WriteHandle(const char *strSend,const boost::system::error_code &ec,size_t bytesWrite); + onReceiveUart m_callback; + + boost::mutex mtx; // 互斥锁 + unsigned long m_TimeStamp; + bool m_waveTrans; + int m_waveCountX; + int m_waveCountY; + int m_waveCountZ; + std::vector VecWaveDataX; + std::vector VecWaveDataY; + std::vector VecWaveDataZ; + +}; + + +#endif diff --git a/uart/subdir.mk b/uart/subdir.mk new file mode 100644 index 0000000..8198ce4 --- /dev/null +++ b/uart/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../uart/SH_Uart.cpp + +CPP_DEPS += \ +./uart/SH_Uart.d + +OBJS += \ +./uart/SH_Uart.o + + +# Each subdirectory must supply rules for building sources it contributes +uart/%.o: ../uart/%.cpp uart/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-uart + +clean-uart: + -$(RM) ./uart/SH_Uart.d ./uart/SH_Uart.o + +.PHONY: clean-uart + diff --git a/udpqt/SH_UdpQt.cpp b/udpqt/SH_UdpQt.cpp new file mode 100644 index 0000000..9a61974 --- /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", to_string(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(); +} 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/udpqt/subdir.mk b/udpqt/subdir.mk new file mode 100644 index 0000000..123fe57 --- /dev/null +++ b/udpqt/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../udpqt/SH_UdpQt.cpp + +CPP_DEPS += \ +./udpqt/SH_UdpQt.d + +OBJS += \ +./udpqt/SH_UdpQt.o + + +# Each subdirectory must supply rules for building sources it contributes +udpqt/%.o: ../udpqt/%.cpp udpqt/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-udpqt + +clean-udpqt: + -$(RM) ./udpqt/SH_UdpQt.d ./udpqt/SH_UdpQt.o + +.PHONY: clean-udpqt + 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 diff --git a/utility/subdir.mk b/utility/subdir.mk new file mode 100644 index 0000000..3d0f720 --- /dev/null +++ b/utility/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../utility/RuleCheck.cpp + +CPP_DEPS += \ +./utility/RuleCheck.d + +OBJS += \ +./utility/RuleCheck.o + + +# Each subdirectory must supply rules for building sources it contributes +utility/%.o: ../utility/%.cpp utility/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-utility + +clean-utility: + -$(RM) ./utility/RuleCheck.d ./utility/RuleCheck.o + +.PHONY: clean-utility + diff --git a/wifi/subdir.mk b/wifi/subdir.mk new file mode 100644 index 0000000..b2c1285 --- /dev/null +++ b/wifi/subdir.mk @@ -0,0 +1,31 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../wifi/wpa_client.cpp + +CPP_DEPS += \ +./wifi/wpa_client.d + +OBJS += \ +./wifi/wpa_client.o + + +# Each subdirectory must supply rules for building sources it contributes +wifi/%.o: ../wifi/%.cpp wifi/subdir.mk + @echo 'Building file: $<' + @echo 'Invoking: Cross G++ Compiler' + arm-linux-gnueabihf-g++ -std=c++0x -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/boost/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/curl/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/fftw/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/jsoncpp/include -I/home/chaos/WorkSpace/Tools/GatewayThirdParty/sqlite/include -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$@" -o "$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + +clean: clean-wifi + +clean-wifi: + -$(RM) ./wifi/wpa_client.d ./wifi/wpa_client.o + +.PHONY: clean-wifi + diff --git a/wifi/wpa_client.cpp b/wifi/wpa_client.cpp new file mode 100644 index 0000000..539cb39 --- /dev/null +++ b/wifi/wpa_client.cpp @@ -0,0 +1,555 @@ +#include "wpa_client.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace wifi { + +size_t strlcpy (char *dst, const char *src, size_t dst_sz) +{ + size_t n; + + for (n = 0; n < dst_sz; n++) { + if ((*dst++ = *src++) == '\0') + break; + } + + if (n < dst_sz) + return n; + if (n > 0) + *(dst - 1) = '\0'; + return n + strlen (src); +} + +static std::string to_string(int val) { + char *buf = NULL; + int size; + int temp; + if (val < 0) + { + temp = -val; + size = 2; + } + else + { + temp = val; + size = 1; + } + for(; temp > 0; temp = temp / 10, size++); + size++; + + buf = (char *)malloc(size); + if (buf == NULL) + { + return ""; + } + memset(buf, 0, size); + sprintf(buf, "%d", val); + std::string re(buf); + free(buf); + return re; +} + + +MXDHCP::MXDHCP() +{ + pstream = NULL; +} + +MXDHCP::~MXDHCP() +{ + if(pstream!=NULL) + { + pclose(pstream); + pstream = NULL; + } +} + +bool MXDHCP::Start(const std::string & net_interface) +{ + if(pstream!=NULL) + { + pclose(pstream); + pstream = NULL; + } + std::string cmd = "udhcpc -b -i " + net_interface + " &"; + system("killall -9 udhcpc &"); + mssleep(1000*100); + pstream = popen(cmd.data(),"r"); + if(pstream == NULL) + { + return false; + } + return true; +} + +/* +* dhcp 这个类的主要原理是通过读取udhcpc 的输出来判断是否拿到了ip地址,实际情况中可以使用别的方法 +*/ +bool MXDHCP::GetDHCPStatus() +{ + if(pstream == NULL) + { + return false; + } + int len = 1024; + char *buff = (char *)malloc(sizeof(char)*len); + if(buff==NULL) + { + return false; + } + int res = fread(buff,sizeof(char),len,pstream); + if(res<=0) + { + free(buff); + return false; + } + if(!CheckString(buff,res)) + { + free(buff); + return false; + } + pclose(pstream); + pstream = NULL; + free(buff); + return true; +} + +bool MXDHCP::CheckString(char *buf ,int len) +{ + if(strstr(buf,"adding dns")==NULL) + { + return false; + } + return true; +} + + +WPAClient::WPAClient(const std::string & wpa_control_path) +{ + wpa_context_ = NULL; + wpa_control_path_ = wpa_control_path; + SetConnStatus(STEP_SCAN); + Init(); +} + +WPAClient::~WPAClient() +{ + Close(wpa_context_); +} + +bool WPAClient::Init() +{ + wpa_context_ = Open(wpa_control_path_); + if (wpa_context_ == NULL) + { + print_error("open wpa failed\n"); + return false; + } + SetConnStatus(STEP_SCAN); + return true; +} + +std::string WPAClient::GetCurrentSSID() +{ + std::string cmd = "STATUS"; + std::string ssid_key = "\nssid="; + std::string recv; + std::string ssid = ""; + + if (!Request(wpa_context_, cmd, recv)) + { + return ""; + } + char temp[1024] = {0}; + strcpy(temp, recv.data()); + char *key = NULL; + key = strstr(temp, ssid_key.data()); + if (key == NULL) + { + return ""; + } + key += ssid_key.length(); + for(; (*key != '\0') && (*key != '\n') && (*key != '\r'); key++) + { + ssid += *key; + } + + return ssid; +} + +std::string WPAClient::GetNetSsid() +{ + std::string cmd = "SCAN"; + std::string recv; + if (!Request(wpa_context_, cmd, recv)) + { + return ""; + } + + recv.clear(); + cmd = "SCAN_RESULTS"; + + if (!Request(wpa_context_, cmd, recv)) + { + return ""; + } + return recv; +} +int WPAClient::GetWiFiRssi() +{ + std::string cmd = "SIGNAL_POLL"; + std::string rssi_key = "RSSI"; + std::string recv; + if (!Request(wpa_context_, cmd, recv)) + { + return 0; + } + char temp[1024] = {0}; + strcpy(temp, recv.data()); + print_info("recv = %s\n",recv.c_str()); + char *key = NULL; + key = strstr(temp, rssi_key.data()); + if (key == NULL) + { + return 0; + } + for(; (*key != '\0') && (*key != '\n') && (*key != '\r'); key++) + { + if ((*key >= '0') && (*key <= '9')) + { + return atoi(key); + } + } + return 0; +} + +bool WPAClient::ConnectWiFi(const std::string & ssid, const std::string & password) { + int net_id; + SetConnStatus(STEP_SCAN); + if (!CleanAllWiFi()) + { + return false; + } + print_info("CleanAllWiFi \n"); + if (!AddWiFi(net_id)) + { + return false; + } + print_info("AddWiFi \n"); + if (!SetSSID(ssid, net_id)) + { + return false; + } + print_info("SetSSID \n"); + if (!SetPassword(password, 0)) + { + return false; + } + if (!SetProtocol(net_id, 1)) + { + return false; + } + print_info("SetProtocol\n"); + SetScanSSID(net_id); + if (!EnableWiFi(net_id)) + { + return false; + } + print_info("EnableWiFi\n"); + return CheckCommandWithOk("SAVE_CONFIG"); + //return true; +} + +bool WPAClient::ConnectWiFiWithNoPassword(const std::string & ssid) +{ + int net_id; + SetConnStatus(STEP_SCAN); + if (!CleanAllWiFi()) + { + return false; + } + print_info("CleanAllWiFi\n"); + if (!AddWiFi(net_id)) + { + return false; + } + print_info("AddWiFi\n"); + if (!SetSSID(ssid, net_id)) + { + return false; + } + print_info("SetSSID\n"); + if (!SetProtocol(net_id, 0)) + { + return false; + } + print_info("SetProtocol\n"); + SetScanSSID(net_id); + if (!EnableWiFi(net_id)) + { + return false; + } + print_info("EnableWiFi\n"); + + return CheckCommandWithOk("SAVE_CONFIG"); +} + +bool WPAClient::ConnectWiFiWithLast() +{ + SetConnStatus(STEP_SCAN); + if (!CheckCommandWithOk("ENABLE_NETWORK all")) + { + return false; + } + return true; +} + +bool WPAClient::GetConnectStatus() { + std::string cmd = "STATUS"; + std::string recv; + int addr; + switch (step_) { + case STEP_SCAN: + if (!Request(wpa_context_, cmd, recv)) { + return false; + } + addr = recv.find("COMPLETED"); + if (addr == -1) { + return false; + } + SetConnStatus(STEP_CONNECT_AP_OK); + case STEP_CONNECT_AP_OK: + if (!dhcp_.Start("wlan0")) { + return false; + } + SetConnStatus(STEP_DHCP_IP); + case STEP_DHCP_IP: + if (!dhcp_.GetDHCPStatus()) { + return false; + } + SetConnStatus(STEP_SUCCESS); + case STEP_SUCCESS: + return true; + default: + return false; + } + return false; +} + +void WPAClient::SetConnStatus(ConnectStatus status) { + step_ = status; +} + +void WPAClient::wifiup() +{ + system("ifconfig mlan0 up"); + system("ifconfig mlan0 up"); + system("ifconfig mlan0 up"); +} + +bool WPAClient::CleanWifi() +{ + bool flag = CleanAllWiFi(); + CheckCommandWithOk("SAVE_CONFIG"); + return flag; +} + +int WPAClient::GetConnStatus() { + return step_; +} + +WPAContext * WPAClient::Open(const std::string & path) { + struct WPAContext *ctrl; + ctrl = (struct WPAContext*)malloc(sizeof(struct WPAContext)); + if (ctrl == NULL) { + print_error("malloc failed\n"); + return NULL; + } + memset(ctrl, 0, sizeof(struct WPAContext)); + static int counter = 0; + int ret; + int tries = 0; + size_t res; + ctrl->s = socket(PF_UNIX, SOCK_DGRAM, 0); + if (ctrl->s < 0) { + print_error("socket failed\n"); + free(ctrl); + return NULL; + } + ctrl->local.sun_family = AF_UNIX; + counter++; +try_again: + ret = snprintf(ctrl->local.sun_path, sizeof(ctrl->local.sun_path), + "/tmp" "/" + "wpa_ctrl_" "%d-%d", + (int)getpid(), counter); + if (ret < 0 || (size_t)ret >= sizeof(ctrl->local.sun_path)) { + print_error("snprintf failed\n"); + close(ctrl->s); + free(ctrl); + return NULL; + } + tries++; + if (bind(ctrl->s, (struct sockaddr *) &ctrl->local, + sizeof(ctrl->local)) < 0) { + if (errno == EADDRINUSE && tries < 2) { + /* + * getpid() returns unique identifier for this instance + * of wpa_ctrl, so the existing socket file must have + * been left by unclean termination of an earlier run. + * Remove the file and try again. + */ + unlink(ctrl->local.sun_path); + goto try_again; + } + print_error("bind failed\n"); + close(ctrl->s); + free(ctrl); + return NULL; + } + ctrl->dest.sun_family = AF_UNIX; + res = strlcpy(ctrl->dest.sun_path, wpa_control_path_.data(), + sizeof(ctrl->dest.sun_path)); + if (res >= sizeof(ctrl->dest.sun_path)) { + close(ctrl->s); + free(ctrl); + return NULL; + } + if (connect(ctrl->s, (struct sockaddr *) &ctrl->dest, + sizeof(ctrl->dest)) < 0) { + print_error("connect failed\n"); + close(ctrl->s); + unlink(ctrl->local.sun_path); + free(ctrl); + return NULL; + } + return ctrl; +} + +void WPAClient::Close(WPAContext * context) { + if (context == NULL) + return; + unlink(context->local.sun_path); + if (context->s >= 0) + close(context->s); + free(context); +} + +bool WPAClient::Request(WPAContext * context, const std::string & cmd, std::string& reply) { + int res; + fd_set rfds; + struct timeval tv; + const char *_cmd; + char *cmd_buf = NULL; + size_t _cmd_len; + _cmd = cmd.data(); + _cmd_len = cmd.length(); + if (wpa_context_ == NULL) { + print_error("wpa_context_ is null\n"); + return false; + } + if (send(wpa_context_->s, _cmd, _cmd_len, 0) < 0) { + free(cmd_buf); + return -1; + } + free(cmd_buf); + for (;;) { + tv.tv_sec = 10; + tv.tv_usec = 0; + FD_ZERO(&rfds); + FD_SET(wpa_context_->s, &rfds); + res = select(wpa_context_->s + 1, &rfds, NULL, NULL, &tv); + if (res < 0) + return false; + if (FD_ISSET(wpa_context_->s, &rfds)) { + char temp[1024] = {0}; + int temp_len = 1024; + res = recv(wpa_context_->s, temp, temp_len, 0); + if (res < 0) + return false; + if (res > 0 && temp[0] == '<') { + continue; + } + reply = temp; + break; + } else { + return false; + } + } + return true; +} + +bool WPAClient::CheckCommandWithOk(const std::string cmd) { + std::string recv; + if (!Request(wpa_context_, cmd, recv)) { + print_error("send cmd falied\n"); + return false; + } + print_error("recv cmd %s\n",recv.data()); + if (strstr(recv.data(), "OK") == NULL) { + return false; + } + return true; +} + +bool WPAClient::AddWiFi(int & id) { + std::string add_cmd = "ADD_NETWORK"; + std::string recv; + if (!Request(wpa_context_, add_cmd, recv)) { + return false; + } + id = atoi(recv.data()); + return true; +} + +bool WPAClient::SetScanSSID(int id) { + std::string cmd = "SET_NETWORK " + to_string(id) + " scan_ssid 1"; + return CheckCommandWithOk(cmd); +} +bool WPAClient::SetSSID(const std::string & ssid, int id) { + std::string cmd = "SET_NETWORK " + to_string(id) + " ssid " + "\"" + ssid + "\""; + return CheckCommandWithOk(cmd); +} +bool WPAClient::SetPassword(const std::string & password, int id) { + std::string cmd = "SET_NETWORK " + to_string(id) + " psk " + "\"" + password + "\""; + return CheckCommandWithOk(cmd); +} +bool WPAClient::SetProtocol(int id, int en_crypt) { + std::string cmd = "SET_NETWORK " + to_string(id); + if (en_crypt) { + cmd += " key_mgmt WPA-PSK"; + return CheckCommandWithOk(cmd); + } else { + cmd += " key_mgmt NONE"; + return CheckCommandWithOk(cmd); + } +} +bool WPAClient::CleanAllWiFi() { + CheckCommandWithOk("REMOVE_NETWORK all"); + CheckCommandWithOk("DISABLE_NETWORK all"); + return true; +} +bool WPAClient::EnableWiFi(int id) { + std::string cmd = "ENABLE_NETWORK " + to_string(id); + return CheckCommandWithOk(cmd); +} + +bool WPAClient::ReconnectWiFi() { + std::string cmd = "RECONNECT"; + return CheckCommandWithOk(cmd); +} +} diff --git a/wifi/wpa_client.h b/wifi/wpa_client.h new file mode 100644 index 0000000..c3d7d0e --- /dev/null +++ b/wifi/wpa_client.h @@ -0,0 +1,90 @@ +/* +# +# wifi连接接口 +# 说明:通过进程间通信与wpa_supplicant进行交互实现wifi连接 +# 注意:使用该接口的应用运行前要确保wpa_supplicant应用已经启动 +# 并且能明确进程间通信地址。 +# +*/ +#ifndef __WPA_CLIENT_H__ +#define __WPA_CLIENT_H__ +#include +#include +#include "../utility/SH_MySingleton.hpp" +#include "../common/SH_global.h" + +namespace wifi +{ +#ifdef G2UL_GATEWAY +const std::string WPA_PATH = "/var/run/wpa_supplicant/wlan0"; //进程间通信地址加上网络接口额名称 +#endif +#ifdef IMX6UL_GATEWAY +const std::string WPA_PATH = "/var/run/wpa_supplicant/wlan2"; //进程间通信地址加上网络接口额名称 +#endif +struct WPAContext +{ + int s; + struct sockaddr_un local; + struct sockaddr_un dest; +}; + +enum ConnectStatus +{ + STEP_SCAN = 0, + STEP_CONNECT_AP_OK, + STEP_DHCP_IP, + STEP_SUCCESS +}; +class MXDHCP +{ //dhcp ip地址的工具类,实现方法不算特别合理。可以根据具体情况进行更改 +public: + MXDHCP(); + ~MXDHCP(); + bool Start(const std::string& net_interface); + bool GetDHCPStatus(); +private: + bool CheckString(char *buf,int len); + FILE *pstream; +}; + +class WPAClient //: public MySingleton +{ +public: + WPAClient(const std::string& wpa_control_path = WPA_PATH); + ~WPAClient(); + bool GetInitStatus(){return wpa_context_!=NULL;} //获取wpa进程间通信是否建立连接 + int GetWiFiRssi(); //获取wifi信号强度,需要在连接成功之后调用 + std::string GetCurrentSSID(); //获取当前连接的wifi的名称 + bool ConnectWiFi(const std::string& ssid, const std::string& password); //连接加密wifi,传入wifi名称和密码 + bool ConnectWiFiWithNoPassword(const std::string& ssid); //连接无加密的wifi,传入wifi名称即可 + bool ConnectWiFiWithLast(); //直接连接上次已保存的wifi + bool GetConnectStatus(); //获取wifi连接状态 + std::string GetNetSsid(); + void wifiup(); //mlan0 up + bool CleanWifi(); + bool ReconnectWiFi(); //重新连接WIFI +protected: + bool Init(); + struct WPAContext* Open(const std::string& path); + void Close(struct WPAContext* context); + bool Request(struct WPAContext* context, const std::string& cmd,std::string& reply); + bool CheckCommandWithOk(const std::string cmd); + bool AddWiFi(int& id); + bool SetScanSSID(int id); + bool SetSSID(const std::string& ssid, int id); + bool SetPassword(const std::string& password, int id); + bool SetProtocol(int id, int en_crypt); + bool CleanAllWiFi(); + bool EnableWiFi(int id); + void SetConnStatus(ConnectStatus status); + int GetConnStatus(); +protected: + struct WPAContext* wpa_context_; + std::string wpa_control_path_; + MXDHCP dhcp_; +private: + int step_; +}; + +} +#endif // __WPA_CLIENT_H__