first init.

This commit is contained in:
pandx 2024-10-19 16:02:41 +08:00
commit 83183b011e
77 changed files with 38180 additions and 0 deletions

110
API_log/SH_log.cpp Normal file
View File

@ -0,0 +1,110 @@
#include "SH_log.h"
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <stdarg.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#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);
}

21
API_log/SH_log.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef LOG_H
#define LOG_H
#include <stdio.h>
#include <stdarg.h>
#include <pthread.h>
#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

31
API_log/subdir.mk Normal file
View File

@ -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

304
MD5/md5.cpp Normal file
View File

@ -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 <openssl/md5.h>
#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() );
}

16
MD5/md5.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef MD5_H
#define MD5_H
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string>
#include <cstring>
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

31
MD5/subdir.mk Normal file
View File

@ -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

73
Makefile Normal file
View File

@ -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

571
aes/aes.c Normal file
View File

@ -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 <string.h> // 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)

90
aes/aes.h Normal file
View File

@ -0,0 +1,90 @@
#ifndef _AES_H_
#define _AES_H_
#include <stdint.h>
// #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_

12
aes/aes.hpp Normal file
View File

@ -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_

31
aes/subdir.mk Normal file
View File

@ -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

546
calculation/Calculation.cpp Normal file
View File

@ -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<float> & 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<float> & vecrealData,std::vector<float> & vecimageData,std::vector<float> & 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<float> & vecData, std::vector<float> & vecFFTrealData,std::vector<float> & 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 &amplitude, 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<float> & vecData)
{
std::vector<float>::iterator it;
it = std::max_element(vecData.begin(), vecData.end());
if (it != vecData.end()) {
return *it;
}
return 0;
}
float Calculation::min(std::vector<float> & vecData)
{
std::vector<float>::iterator it;
it = std::min_element(vecData.begin(), vecData.end());
if (it != vecData.end()) {
return *it;
}
return 0;
}
void Calculation::absVec(std::vector<float> & vecAbsData, std::vector<float> & vecData)
{
for (int i = 0; i < vecData.size(); i++) {
vecAbsData.push_back(fabs(vecData[i]));
}
return;
}
float Calculation::mean(std::vector<float> & 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<float> & vecDropMeanData, std::vector<float> & 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<float> & 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<float> & 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<float> 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<float> & 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<float> & 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<float> & 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<float> & vecData,std::vector<float> & 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<float> & vecData, std::vector<float> & 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<N; n++ )//输出
{
// xr[n]=cos(n*pi/6);//原始信号
// y_r[n] = s_i[n];
complex complex_after;
complex_after.real = out[n][1];
complex_after.imag = out[n][0];
float amp = sqrt(complex_after.real * complex_after.real +complex_after.imag * complex_after.imag);
vecHilbertData.push_back(amp);
// printf("%d %f\n",n,vecHilbertData[n]);
}
fftw_free(out);
}
void Calculation::fftShift(fftw_complex* in, int l)
{
double temp;
double temp2;
for (int j = 0;j<l/2;j++) {
temp = in[j+l/2][0];
temp2 = in[j+l/2][1];
in[j+l/2][0] = in[j][0];
in[j+l/2][1] = in[j][1];
in[j][0] = temp;
in[j][1] = temp2;
}
}
void Calculation::FFTSpec(std::vector<float> & vecData, std::vector<float> & 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<float> & vecData, std::vector<float> & vecEnvSpecData,int StartFrequency,int EndFrequency)
{
/*std::vector<float> vecDropMeanData;
drop_mean(vecDropMeanData, vecData);
std::vector<float> 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<float> vecFFTrealData,vecFFTimageData;
std::vector<float> vecRealData,vecImageData;
std::vector<float> veciFFtData;
std::vector<float> veciFFtData2;
std::vector<float> 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<float> & 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<double> 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<float> & vecData,std::vector<float>& retData,double & resolution)
{
std::vector<float> realshiftfft;
std::vector<float> imageshiftfft;
std::vector<float> 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保持一致
}
}*/

160
calculation/Calculation.hpp Normal file
View File

@ -0,0 +1,160 @@
#ifndef CALCULATION_H_
#define CALCULATION_H_
#include <vector>
#include <math.h>
#include <fftw3.h>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <string.h>
#include "../utility/SH_MySingleton.hpp"
#define pi 3.1415
typedef struct
{
float real,imag;
}complex;
class Calculation : public MySingleton<Calculation>
{
public:
Calculation();
~Calculation();
//最大值
float max(std::vector<float> & vecData);
//最小值
float min(std::vector<float> & vecData);
//将数据取绝对值
void absVec(std::vector<float> & vecAbsData, std::vector<float> & vecData);
//将数据取平均值
float mean(std::vector<float> & vecData);
//将数据平方处理 数据有效值
float rms(std::vector<float> & vecData);
//获取样本方差
float getSample_variance(std::vector<float> a);
//去数据的直流分量
void drop_mean(std::vector<float> & vecDropMeanData, std::vector<float> & vecData);
//方根幅值
float srm(std::vector<float> & vecData);
//方差
float variance(std::vector<float> & vecDropMeanData);
//偏态指标
float skew_state(std::vector<float> & vecDropMeanData, float fVariance);
//峭度指标
float kurtosis(std::vector<float> & vecDropMeanData, float fVariance);
//hanning 窗
void Hanning(std::vector<float> & vecData,std::vector<float> & vecHanningData);
//快速傅里叶变换函数
void FFT(int n, fftw_complex* in, fftw_complex* out);
//快速傅里叶实数变换函数
void FFT_R(int n, std::vector<float> & vecData, fftw_complex* out);
//快速傅里叶逆变换
void iFFT(int n, fftw_complex* in, fftw_complex* out);
void _iFFT(std::vector<float> & vecData, std::vector<float> & vecFFTSpecData,std::vector<float> & veciFFTData);
void _FFT(std::vector<float> & vecData, std::vector<float> & vecFFTrealData,std::vector<float> & vecFFTimageData);
//通道幅值和相位提取
//输入为FFT变换后的数据长度及数据指定的频率输出为计算后得到的幅值 和 相位
void caculateAmp_Pha(int n, fftw_complex* in, int frequency, double &amplitude, double &phase);
//希尔伯特变换
void hilbert(std::vector<float> & vecData, std::vector<float> & vecHilbertData, int N);
//生成正弦信号
void GenerateSin(std::vector<float> & vecData);
//FFT shift
void fftShift(fftw_complex* in, int l);
//频谱图数据
void FFTSpec(std::vector<float> & vecData, std::vector<float> & vecFFTSpecData);
//包络图谱数据
void envSpec(std::vector<float> & vecData, std::vector<float> & vecEnvSpecData,int StartFrequency,int EndFrequency);
void Integration(std::vector<float> & vecData,std::vector<float>& retData,double & resolution);
};
#endif

31
calculation/subdir.mk Normal file
View File

@ -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

20
common/Mutex.h Normal file
View File

@ -0,0 +1,20 @@
#ifndef _MY_COMM_H_
#define _MY_COMM_H_
#include <pthread.h>
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_

2574
common/SH_CommonFunc.cpp Normal file

File diff suppressed because it is too large Load Diff

838
common/SH_CommonFunc.hpp Normal file
View File

@ -0,0 +1,838 @@
#ifndef _COMMONFUNC_
#define _COMMONFUNC_
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <stdlib.h>
#include <memory.h>
#include <string>
#include <list>
#include <boost/algorithm/string/split.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <iostream>
#include <fstream>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <boost/lexical_cast.hpp>
#include <sys/statfs.h>
#include <json/json.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <memory.h>
#include <sys/ipc.h>//ipc
#include <sys/shm.h>
#include "dirent.h"
#include <iconv.h>
#include <termios.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#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; // 通信模式,有线通信模式 = 14G 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 <std::string> 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 1200
* @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<float> & 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 <DataNodeUpdate> 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

182
common/SH_global.h Normal file
View File

@ -0,0 +1,182 @@
#ifndef _GLOBALCONFIG_H_
#define _GLOBALCONFIG_H_
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <sys/syscall.h>
#include <signal.h>
#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

31
common/subdir.mk Normal file
View File

@ -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

1
common/u2g.h Normal file
View File

@ -0,0 +1 @@
void utf2gbk(char *utf,char* gbk);

View File

@ -0,0 +1,581 @@
#include "SH_Datatrans.hpp"
#include "dirent.h"
#include <stdio.h>
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*>((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<<stderr<<res<<endl;
return -1;
}
}
printf("strResponse = %s\n",strResponse.c_str());
if(bDownload){
if(dlfile.stream)
{
//关闭文件流
fclose(dlfile.stream);
}
}else{
}
//释放全局curl对象
curl_global_cleanup();
return 0;
}
//下载文件数据接收函数
size_t writedata2file(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
//http POST请求文件下载
int DataTrans::dl_curl_post_req(const string &url, const string &postParams, string& filename)
{
CURL *curl;
FILE *fp;
CURLcode res;
/* 调用curl_global_init()初始化libcurl */
res = curl_global_init(CURL_GLOBAL_ALL);
if (CURLE_OK != res)
{
printf("init libcurl failed.");
curl_global_cleanup();
return -1;
}
/* 调用curl_easy_init()函数得到 easy interface型指针 */
curl = curl_easy_init();
if (curl) {
fp = fopen(filename.c_str(),"wb");
/* 调用curl_easy_setopt()设置传输选项 */
res = curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
if (res != CURLE_OK)
{
fclose(fp);
curl_easy_cleanup(curl);
return -1;
}
/* 根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务 */
res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writedata2file);
if (res != CURLE_OK){
fclose(fp);
curl_easy_cleanup(curl);
return -1;
}
/* 根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务 */
res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
if (res != CURLE_OK)
{
fclose(fp);
curl_easy_cleanup(curl);
return -1;
}
res = curl_easy_perform(curl);
// 调用curl_easy_perform()函数完成传输任务
fclose(fp);
/* Check for errors */
if(res != CURLE_OK){
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
curl_easy_cleanup(curl);
return -1;
}
/* always cleanup */
curl_easy_cleanup(curl);
// 调用curl_easy_cleanup()释放内存
}
curl_global_cleanup();
return 0;
}
int DataTrans::Post(const std::string & strUrl, const std::string & strPost, std::string & strResponse)
{
CURLcode res;
CURL* curl = curl_easy_init();
if(NULL == curl) {
return CURLE_FAILED_INIT;
}
if(m_bDebug)
{
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
}
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strPost.c_str());
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_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return res;
}
int DataTrans::Get(const std::string & strUrl, std::string & strResponse)
{
CURLcode res;
CURL* curl = curl_easy_init();
if(NULL == curl) {
return CURLE_FAILED_INIT;
}
if(m_bDebug) {
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
}
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
/**
* 线使线sleep或是wait等操作
* libcurl将会发信号打断这个wait从而导致程序退出
*/
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return res;
}
int DataTrans::Posts(const std::string & strUrl, const std::string & strPost, std::string & strResponse, const char * pCaPath)
{
CURLcode res;
CURL* curl = curl_easy_init();
if(NULL == curl) {
return CURLE_FAILED_INIT;
}
if(m_bDebug) {
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
}
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strPost.c_str());
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_NOSIGNAL, 1);
if(NULL == pCaPath) {
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
} else {
//缺省情况就是PEM所以无需设置另外支持DER
//curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"PEM");
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true);
curl_easy_setopt(curl, CURLOPT_CAINFO, pCaPath);
}
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return res;
}
int DataTrans::Gets(const std::string & strUrl, std::string & strResponse, const char * pCaPath)
{
CURLcode res;
CURL* curl = curl_easy_init();
if(NULL == curl) {
return CURLE_FAILED_INIT;
}
if(m_bDebug) {
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
}
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
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_NOSIGNAL, 1);
if(NULL == pCaPath) {
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
} else {
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true);
curl_easy_setopt(curl, CURLOPT_CAINFO, pCaPath);
}
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return res;
}
int DataTrans::upload_file(const std::string &strUrl, const std::string &filename, std::string &response)
{
CURL *curl;
CURLM *multi_handle;
int still_running;
char res[60];
struct curl_httppost *formpost = NULL;
struct curl_httppost *lastptr = NULL;
struct curl_slist *headerlist = NULL;
static const char buf[] = "Expect:";
curl_global_init(CURL_GLOBAL_ALL);
/* Fill in the file upload field. This makes libcurl load data from
the given file name when curl_easy_perform() is called. */
/* Fill in the filename field */
curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "filename", CURLFORM_FILE, filename.c_str(), CURLFORM_END);
curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "submit", CURLFORM_COPYCONTENTS, "upload", CURLFORM_END);
curl = curl_easy_init();
multi_handle = curl_multi_init();
/* initalize custom header list (stating that Expect: 100-continue is not wanted */
headerlist = curl_slist_append(headerlist, buf);
if (curl && multi_handle) {
/* what URL that receives this POST */
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, res);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
curl_multi_add_handle(multi_handle, curl);
curl_multi_perform(multi_handle, &still_running);
do {
struct timeval timeout;
int rc;
fd_set fdread;
fd_set fdwrite;
fd_set fdexcep;
int maxfd = -1;
long curl_timeo = -1;
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
FD_ZERO(&fdexcep);
/* set a suitable timeout to play around with */
timeout.tv_sec = 1;
timeout.tv_usec = 0;
curl_multi_timeout(multi_handle, &curl_timeo);
if (curl_timeo >= 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<string> 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<std::string>::iterator iter;
for(iter = v.begin();iter != v.end();++iter) {
temp = *iter;
cout << temp.c_str() <<endl;
int file_name_length = (int)strlen(temp.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,temp.c_str(),file_name_length,0) < 0) {
print_error("Send File_Name Failed!\n");
} else {
print_info("Send File_Name Success!\n");
}
/*
*
*/
std::string filename = std::string(dirname + temp);
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;
}
}
void DataTrans::SetDebug(bool bDebug)
{
m_bDebug = bDebug;
}

View File

@ -0,0 +1,108 @@
#ifndef _DATATRANS_H_
#define _DATATRANS_H_
#include <stdio.h>
#include <string>
#include <curl/curl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#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<DataTrans>
{
public:
DataTrans();
~DataTrans();
/**
* @brief HTTP POST请求
* @param strUrl ,Url地址,:http://www.baidu.com
* @param strPost ,使para1=val12=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=val12=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

31
datatransfer/subdir.mk Normal file
View File

@ -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

1577
dbaccess/SH_SqlDB.cpp Normal file

File diff suppressed because it is too large Load Diff

204
dbaccess/SH_SqlDB.hpp Normal file
View File

@ -0,0 +1,204 @@
#ifndef _SQLDB_H_L
#define _SQLDB_H_L
extern "C"{
#include <sqlite3.h>
}
#include <stdio.h>
#include <string.h>
#include <list>
#include <map>
#include <vector>
#include <string>
#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<std::string, std::string> map_t;
typedef std::vector<std::string> vec_t;
typedef std::vector<float> vec_Value;
typedef std::vector<vec_t> 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

31
dbaccess/subdir.mk Normal file
View File

@ -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

296
dial5G/Dial.cpp Normal file
View File

@ -0,0 +1,296 @@
/*
* Dial.cpp
*
* Created on: 2023613
* Author: chaos
*/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#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);
}

70
dial5G/Dial.h Normal file
View File

@ -0,0 +1,70 @@
/*
* Dial.h
*
* Created on: 2023613
* Author: chaos
*/
#ifndef DIAL5G_DIAL_H_
#define DIAL5G_DIAL_H_
#include <string>
#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_ */

31
dial5G/subdir.mk Normal file
View File

@ -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

2828
jsonparse/SH_JsonCmd.cpp Normal file

File diff suppressed because it is too large Load Diff

141
jsonparse/SH_JsonCmd.hpp Normal file
View File

@ -0,0 +1,141 @@
#ifndef _JSONCMD_H_
#define _JSONCMD_H_
#include <json/json.h>
#include <list>
#include <vector>
#include <string>
#include <iostream>
#include <stdint.h>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/thread/thread.hpp>
#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 &param);
// std::string JsonCmd_21(Param_21 &param);
std::string JsonCmd_22(Param_22 &param); //时区配置
std::string JsonCmd_23(Param_23 &param); //服务器配置
std::string JsonCmd_25(Param_25 &param);
std::string JsonCmd_26(Param_26 &param);
std::string JsonCmd_27(Json::Value & recvBody);
std::string JsonCmd_29(Param_29 &param); //系统配置信息
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 &param); //用户操作处理
std::string JsonCmd_Cgi_02(Param_02 &param); //时间校准接口
std::string JsonCmd_Cgi_07(); //获取系统内存温度硬盘等信息
std::string JsonCmd_07(); //获取系统内存温度硬盘等信息
std::string JsonCmd_Cgi_08(); //重启
std::string JsonCmd_Cgi_09(Param_09 &param); //实时数据获取
std::string JsonCmd_Cgi_10(Param_10 &param); //
std::string JsonCmd_Cgi_11(Param_11 &param); //
std::string JsonCmd_Cgi_20(Param_20 &param); //终端信息获取
std::string JsonCmd_Cgi_22(Param_22 &param); //时区配置
std::string JsonCmd_Cgi_23(Param_23 &param); //服务器配置
std::string JsonCmd_Cgi_25(Param_25 &param); //网口配置
std::string JsonCmd_Cgi_26(Param_26 &param);
std::string JsonCmd_Cgi_27(Param_27 &param);
std::string JsonCmd_Cgi_28(Param_28 &param);
std::string JsonCmd_Cgi_29(Param_29 &param); //获取原始数据
std::string JsonCmd_Cgi_30(Param_30 &param); //获取频域数据
std::string JsonCmd_Cgi_31(Param_31 &param);//配置通信通道
std::string JsonCmd_Cgi_32(Param_32 &param); //
std::string JsonCmd_Cgi_40(Param_40 &param); //
std::string JsonCmd_Cgi_41(std::vector<Param_41> &param,int isServer = 0); //
std::string JsonCmd_Cgi_42(Param_42 &param); //从web端更新程序
std::string JsonCmd_Cgi_43(); //检测网口状态
std::string JsonCmd_Cgi_45(Param_45 &param); //国家区域配置
std::string JsonCmd_Cgi_46(Param_46 &param); //升级固件
std::string JsonCmd_Cgi_47(Param_47 &param); //替换Logo
std::string JsonCmd_Cgi_50(); //
std::string JsonCmd_Cgi_51(Param_51 &param); //
std::string JsonCmd_Cgi_52(Param_52 &param);
std::string JsonCmd_Cgi_53(std::vector<Param_53> &param);
std::string JsonCmd_Cgi_54(Param_54 &param);
std::string JsonCmd_Cgi_55(Param_55 &param);
std::string JsonCmd_Cgi_56(Param_56 &param);
std::string JsonCmd_Cgi_57(Param_57 &param);
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

31
jsonparse/subdir.mk Normal file
View File

@ -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

View File

@ -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<Param_41> 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<std::string>(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<Param_41> 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<Param_53> 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);
}
}

View File

@ -0,0 +1,30 @@
#ifndef _LOCALSERVER_H_
#define _LOCALSERVER_H_
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <boost/unordered_set.hpp>
#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<LocalServer>
{
private:
boost::mutex mMutex;
// _Event mWaveEvent;
std::vector<std::string> m_VecFileName;
public:
LocalServer();
virtual ~LocalServer();
void HandleFromServer(const char *pData, int pLen, const char *topic);
std::string HandleCgi_cmd(std::string &pData);
};
#endif

31
localserver/subdir.mk Normal file
View File

@ -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

175
main.cpp Normal file
View File

@ -0,0 +1,175 @@
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <boost/thread.hpp>
#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<RecvData> g_VecWaveDataX;
extern std::vector<RecvData> g_VecWaveDataY;
extern std::vector<RecvData> 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;
}

339
minilzo-2.10/COPYING Normal file
View File

@ -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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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.
<signature of Ty Coon>, 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.

123
minilzo-2.10/README.LZO Normal file
View File

@ -0,0 +1,123 @@
============================================================================
miniLZO -- mini subset of the LZO real-time data compression library
============================================================================
Author : Markus Franz Xaver Johannes Oberhumer
<markus@oberhumer.com>
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.

453
minilzo-2.10/lzoconf.h Normal file
View File

@ -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
<markus@oberhumer.com>
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 <config.h>
#endif
#include <limits.h>
#include <stddef.h>
/***********************************************************************
// LZO requires a conforming <limits.h>
************************************************************************/
#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 <lzodefs.h>
#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: */

3268
minilzo-2.10/lzodefs.h Normal file

File diff suppressed because it is too large Load Diff

6365
minilzo-2.10/minilzo.c Normal file

File diff suppressed because it is too large Load Diff

106
minilzo-2.10/minilzo.h Normal file
View File

@ -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
<markus@oberhumer.com>
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 <config.h>
#endif
#include <limits.h>
#include <stddef.h>
#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: */

View File

@ -0,0 +1,375 @@
#include <signal.h>
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <memory.h>
#include <errno.h>
#include <json/json.h>
#include <sys/types.h>
#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);
}

View File

@ -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

3271
mqttclient/mosquitto.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,561 @@
/*
Copyright (c) 2009-2020 Roger Light <roger@atchoo.org>
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 <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <time.h>
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 <mosquitto_plugin_init>.
* 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 <mosquitto_plugin_init>.
* 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

View File

@ -0,0 +1,420 @@
/*
Copyright (c) 2012-2020 Roger Light <roger@atchoo.org>
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 <stdbool.h>
#include <stdint.h>
#include <mosquitto_broker.h>
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<path to mosquitto_plugin.h> -fPIC -shared plugin.c -o plugin.so
*
* On Mac OS X:
*
* gcc -I<path to mosquitto_plugin.h> -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 <mosquitto_plugin_version>
* 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 <mosquitto_plugin_init>.
* 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 <mosquitto_auth_plugin_version>
* 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 <mosquitto_auth_security_cleanup> will be called directly before
* this function.
*
* Parameters:
*
* user_data - The pointer provided in <mosquitto_auth_plugin_init>.
* 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, <mosquitto_auth_security_cleanup> 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 <mosquitto_auth_plugin_init>.
* 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
* <mosquitto_auth_security_init>. In this situation, the reload parameter
* will be true.
*
* Parameters:
*
* user_data - The pointer provided in <mosquitto_auth_plugin_init>.
* 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 <mosquitto_auth_plugin_init>.
* 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 <mosquitto_auth_plugin_init>.
* 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

282
mqttclient/mqtt_protocol.h Normal file
View File

@ -0,0 +1,282 @@
/*
Copyright (c) 2009-2020 Roger Light <roger@atchoo.org>
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

31
mqttclient/subdir.mk Normal file
View File

@ -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

View File

@ -0,0 +1,376 @@
#include <fstream>
#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<string,compressWaveChannel> 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
}

View File

@ -0,0 +1,68 @@
#ifndef _PLATFORMINIT_H_
#define _PLATFORMINIT_H_
#include <vector>
#include <algorithm>
#include "../utility/SH_MySingleton.hpp"
#include "../common/SH_CommonFunc.hpp"
class PlatformInit : public MySingleton<PlatformInit>
{
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

31
platform/subdir.mk Normal file
View File

@ -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

149
searchdev/SH_SearchDev.cpp Normal file
View File

@ -0,0 +1,149 @@
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#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();
}

View File

@ -0,0 +1,39 @@
#ifndef _WL_SEARCHDEV_
#define _WL_SEARCHDEV_
#include <boost/asio/ip/udp.hpp>
#include <boost/asio.hpp>
#include <json/json.h>
#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<SearchDev>
{
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

31
searchdev/subdir.mk Normal file
View File

@ -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

1436
secure/SH_Secure.cpp Normal file

File diff suppressed because it is too large Load Diff

53
secure/SH_Secure.hpp Normal file
View File

@ -0,0 +1,53 @@
#ifndef _WL_SECUREAPI_H_
#define _WL_SECUREAPI_H_
#include <string>
#include "../utility/SH_MySingleton.hpp"
typedef unsigned char u_char;
typedef unsigned long u_long;
/************************
*
*
*
*************************/
class Secure : public MySingleton<Secure>{
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

31
secure/subdir.mk Normal file
View File

@ -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

503
serial/serial.c Normal file
View File

@ -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 <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>
#include <sys/select.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#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;
}
}

193
serial/serial.h Normal file
View File

@ -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 <stdlib.h>
/* 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__ */

31
serial/subdir.mk Normal file
View File

@ -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

1031
threadfunc/SH_ThreadFunc.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,37 @@
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lexical_cast.hpp>
#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();

31
threadfunc/subdir.mk Normal file
View File

@ -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

4501
uart/SH_Uart.cpp Normal file

File diff suppressed because it is too large Load Diff

130
uart/SH_Uart.hpp Normal file
View File

@ -0,0 +1,130 @@
#ifndef _UART_H_
#define _UART_H_
#include <list>
#include <map>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#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<Uart>
{
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<float> 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<float>& 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<RecvData> VecWaveDataX;
std::vector<RecvData> VecWaveDataY;
std::vector<RecvData> VecWaveDataZ;
};
#endif

31
uart/subdir.mk Normal file
View File

@ -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

194
udpqt/SH_UdpQt.cpp Normal file
View File

@ -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() <<std::endl;
print_brown("sys send single : %s \n", pData.c_str());
udpSock.async_send_to(boost::asio::buffer(mi,len + 3), remoteEndPoint,
boost::bind(&UdpSys::handle_send_to, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
delete [] mi;
}
void UdpSys::recvUdpData()
{
udpSock.async_receive_from(boost::asio::buffer(m_buffer), senderEndPoint,
boost::bind(&UdpSys::HandleRead, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void UdpSys::HandleRead(const boost::system::error_code& pEc,
std::size_t pBytesTransferred)
{
std::string ip = senderEndPoint.address().to_string();
if (pEc) {
std::cerr << pEc.value() <<std::endl;
std::cerr << pEc.category().name() << std::endl;
std::cerr << pEc.message() << std::endl;
} else if (pBytesTransferred == 0) {
std::cout << "rev has rec!" << std::endl;
if (pBytesTransferred == 0) {
std::cerr << "[ Read 0 Bytes ][ " << ip << " Quit ! ]" << std::endl;
}
} else {
std::string read_cmd(m_buffer.data(), pBytesTransferred);
print_light_purple("%s", read_cmd.c_str());
if(read_cmd.length()>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();
}

105
udpqt/SH_UdpQt.hpp Normal file
View File

@ -0,0 +1,105 @@
#ifndef UDPQT_H
#define UDPQT_H
#include <vector>
#include <string>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <boost/lexical_cast.hpp>
#include <json/json.h>
#include <boost/array.hpp>
#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<UdpSys> {
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<char,8192> m_buffer;
std::string mData;
bool status;
int times;
};
#endif

31
udpqt/subdir.mk Normal file
View File

@ -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

201
utility/Caculation.h Normal file
View File

@ -0,0 +1,201 @@
#ifndef CACULATION_H_
#define CACULATION_H_
#include <vector>
#include <math.h>
#include <fftw3.h>
using namespace std;
class Caculation
{
public:
Caculation();
~Caculation();
template<typename T, int N>
static T maxValue(T(&data)[N]);
template<typename T, int N>
static T minValue(T(&data)[N]);
template<typename T, int N> //<2F><><EFBFBD><EFBFBD>ƽ<EFBFBD><C6BD>ֵ
static T dcValue(T(&data)[N]);
template<typename T, int N> //<2F><><EFBFBD><EFBFBD>RMS
static T caculateRMS(T(&data)[N]);
template<typename T, int N> //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֵ
static T caculatePKtoPk(T(&data)[N]);
//<2F><><EFBFBD>ٸ<EFBFBD><D9B8><EFBFBD>Ҷ<EFBFBD><EFBFBD><E4BBBB><EFBFBD><EFBFBD>
static void FFT(int n, fftw_complex* in, fftw_complex* out);
//ͨ<><CDA8><EFBFBD><EFBFBD>ֵ<EFBFBD><D6B5><EFBFBD><EFBFBD>λ<EFBFBD><CEBB>ȡ
//<2F><><EFBFBD><EFBFBD>ΪFFT<46><EFBFBD><E4BBBB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݳ<EFBFBD><DDB3>ȼ<EFBFBD><C8BC><EFBFBD><EFBFBD>ݣ<EFBFBD>ָ<EFBFBD><D6B8><EFBFBD><EFBFBD>Ƶ<EFBFBD>ʣ<EFBFBD><CAA3><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD>õ<EFBFBD><C3B5>ķ<EFBFBD>ֵ <20><> <20><>λ
static void caculateAmp_Pha(int n, fftw_complex* in, int frequency, double &amplitude, double &phase);
template <typename T> //<2F><><EFBFBD><EFBFBD>hanning<6E><67><EFBFBD><EFBFBD>
static vector<T> hanning(int N, T amp);
template <typename T> //<2F><><EFBFBD><EFBFBD>hamming<6E><67><EFBFBD><EFBFBD>
static vector<T> hamming(int N, T amp);
//ͳ<>Ƽ<EFBFBD><C6BC><EFBFBD>
};
Caculation::Caculation()
{
}
Caculation::~Caculation()
{
}
/************************************************************************/
/*<2A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݵ<EFBFBD><DDB5><EFBFBD><EFBFBD>ֵ */
/************************************************************************/
template<typename T, int N>
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;
}
/************************************************************************/
/*<2A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݵ<EFBFBD><DDB5><EFBFBD>Сֵ */
/************************************************************************/
template<typename T, int N>
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;
}
/************************************************************************/
/*<2A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݵ<EFBFBD>ƽ<EFBFBD><C6BD>ֵ */
/************************************************************************/
template<typename T, int N>
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;
}
/************************************************************************/
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>RMS */
/************************************************************************/
template<typename T, int N>
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);
}
/************************************************************************/
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݷ<EFBFBD><DDB7>ֵ */
/************************************************************************/
template<typename T, int N>
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;
}
/************************************************************************/
/* һά<D2BB><CEAC><EFBFBD>ݵĿ<DDB5><C4BF>ٸ<EFBFBD><D9B8><EFBFBD>Ҷ<EFBFBD>任 */
/************************************************************************/
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
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ǽ<EFBFBD><C7BC><EFBFBD><EFBFBD>ض<EFBFBD>Ƶ<EFBFBD>ʵķ<CAB5>ֵ<EFBFBD><D6B5><EFBFBD><EFBFBD>λ<EFBFBD><CEBB>ԭ<EFBFBD><D4AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ǵ<EFBFBD><C7B4><EFBFBD>һ<EFBFBD><D2BB><EFBFBD>ض<EFBFBD><D8B6><EFBFBD>Ƶ<EFBFBD>ʣ<EFBFBD>Ȼ<EFBFBD><C8BB><EFBFBD>ڸ<EFBFBD><DAB8><EFBFBD><EFBFBD><EFBFBD>Ƶ<EFBFBD><C6B5><EFBFBD><EFBFBD><EFBFBD>ҷ<EFBFBD>Χ<EFBFBD><CEA7><EFBFBD>ҷ<EFBFBD>ֵ<EFBFBD><D6B5><EFBFBD><EFBFBD>λ
// Ŀǰ<C4BF>ĺ<EFBFBD><C4BA><EFBFBD>ʵ<EFBFBD><CAB5><EFBFBD>Ǽ<EFBFBD><C7BC><EFBFBD>FFT<46><EFBFBD><E4BBBB><EFBFBD>ض<EFBFBD><D8B6><EFBFBD>ķ<EFBFBD>ֵ<EFBFBD><D6B5><EFBFBD><EFBFBD>λ
// Ȼ<><C8BB><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD>ط<EFBFBD><D8B7><EFBFBD>Ҫ<EFBFBD>޸ģ<DEB8><C4A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƶ<EFBFBD>ʺ<EFBFBD>FFT<46><EFBFBD><E4BBBB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
//************************************
void Caculation::caculateAmp_Pha(int n, fftw_complex* in, int frequency, double &amplitude, 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;
}
/************************************************************************/
/* <20><><EFBFBD><EFBFBD>hanning<6E><67><EFBFBD><EFBFBD> */
/************************************************************************/
template <typename T>
vector<T> Caculation::hanning(int N, T amp)
{
vector<T> 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;
}
/************************************************************************/
/* <20><><EFBFBD><EFBFBD>hamming<6E><67><EFBFBD><EFBFBD> */
/************************************************************************/
template <typename T>
vector<T> Caculation::hamming(int N, T amp)
{
vector<T> 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

44
utility/RuleCheck.cpp Normal file
View File

@ -0,0 +1,44 @@
#include <stdio.h>
#include <string.h>
/***************************************************************************
* 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;
}

View File

@ -0,0 +1,23 @@
#ifndef MYSINGLETON_H_
#define MYSINGLETON_H_
template<class T>
class MySingleton {
public:
static T* instance() {
static T _instance;
return &_instance;
}
;
protected:
MySingleton() {
}
;
virtual ~MySingleton() {
}
;
MySingleton(const MySingleton &);
MySingleton& operator=(const MySingleton &);
};
#endif

31
utility/subdir.mk Normal file
View File

@ -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

31
wifi/subdir.mk Normal file
View File

@ -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

555
wifi/wpa_client.cpp Normal file
View File

@ -0,0 +1,555 @@
#include "wpa_client.h"
#include <string>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
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);
}
}

90
wifi/wpa_client.h Normal file
View File

@ -0,0 +1,90 @@
/*
#
# wifi连接接口
# 说明通过进程间通信与wpa_supplicant进行交互实现wifi连接
# 注意使用该接口的应用运行前要确保wpa_supplicant应用已经启动
# 并且能明确进程间通信地址。
#
*/
#ifndef __WPA_CLIENT_H__
#define __WPA_CLIENT_H__
#include <string>
#include <sys/un.h>
#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<WPAClient>
{
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__