Commit 667e3393 authored by 杨熙's avatar 杨熙

Initial commit

parents
CURDIR=$(shell pwd)
CROSS_COMPILE=mips-openwrt-9531-linux-
CPPFLAG = $(FLAG)
CPPFLAG += -DNOT_X86=1 -DARM -DWITH_2530_GW -DFOR_KKIT_9531 -DKK_ENCHANCE -DWITH_LED -DKK_9531 -DEMBEDED_LINUX_2530_GW -DFOR_AR9533
CPPFLAG += -I/home/sj/Port_For_Enhance_Mips/SmartHomeWs/os_lib/direct-use-lib/ace-lib/include -I/home/sj/Port_For_Enhance_Mips/SmartHomeWs/os_lib/direct-use-lib/curl-lib/include
LDFLAGS= -L/home/sj/Port_For_Enhance_Mips/SmartHomeWs/os_lib/direct-use-lib/sqlite-lib -lsqlite3 -ldl -lrt
# -L/home/sj/Port_For_Enhance_Mips/SmartHomeWs/os_lib/direct-use-lib/curl-lib/lib -lcurl -lmbedtls -lmbedcrypto -lmbedx509
CCU_BUILD_TIME = $(shell echo `date +"%Y%m%d-%H:%M:%S"`"@"`uname -n`)
CPPFLAG += -DCCU_BUILD_TIME="\"$(CCU_BUILD_TIME)\""
CCU_GIT_REVISION = $(shell git rev-parse HEAD)
CCU_GIT_COMMIT_TIME = $(shell git log --date=iso --pretty=format:"%cd" $(CCU_GIT_REVISION) -1)
CCU_GIT_INFO=$(CCU_GIT_REVISION) $(CCU_GIT_COMMIT_TIME)
CPPFLAG += -DCCU_GIT_REVISION="\"$(CCU_GIT_INFO)\""
ALL=Konkexinghai
SRCS=$(wildcard ../src/*.cpp)
SRCS+=$(wildcard ../src/lib/*.cpp)
SRCS+=$(wildcard ../src/lib/jsonlib/*.cpp)
OBJS+=$(subst .cpp,.o,$(SRCS))
DEPS=$(subst .cpp,.d,$(SRCS))
CC=$(CROSS_COMPILE)g++
LD=$(CROSS_COMPILE)g++
CPPFLAGS+=$(CPPFLAG) $(FLAG)
ifeq ($(CC),g++)
CPPFLAGS+=-I../ -I../src/include
LDFLAGS+=-lpaho-mqtt3as -lssl -lcrypto -lACE -lpthread
else
CPPFLAGS+=-I../ -I../src/include -I/home/sj/Port_For_Enhance_Mips/SmartHomeWs/os_lib/direct-use-lib/mqtt-lib/include -fPIC
LDFLAGS+=-L/home/sj/Port_For_Enhance_Mips/SmartHomeWs/os_lib/direct-use-lib/ace-lib/lib -L/home/sj/Port_For_Enhance_Mips/SmartHomeWs/os_lib/direct-use-lib/mqtt-lib/lib -lpaho-mqtt3as -lssl -lcrypto -lpthread -lACE -fPIC
endif
V=1
V?=0
ifeq ($V, 0)
Q=@
endif
all:$(ALL)
ifneq ($(MAKECMDGOALS),clean)
-include $(DEPS)
endif
$(ALL): $(OBJS)
@echo "[LINK] $(ALL)"
$(Q)$(LD) $(EXTRA_LDFLAGS) $(OBJS) -o $(ALL) $(LDFLAGS)
%.d: %.cpp
@echo "[DEP] $@"
$(Q)set -e; rm -f $@;\
$(CC) -MM $(CPPFLAGS) $< > $@.tmp;\
sed 's,\($*\)\.o[ :]*,\1.o $@: ,g' < $@.tmp > $@;\
rm -f $@.tmp
$(OBJS): %.o: %.cpp
@echo "[CC] $@"
$(Q)$(CC) -c $(CPPFLAGS) $(EXTRA_CFLAGS) $(CFLAGS_$@) $< -o $@
clean:
-rm $(OBJS) $(DEPS) $(ALL)
distclean:clean
# install all files to ROOT_FS directory
install:
cp $(ALL) $(INSTALL_BIN)
CURDIR=$(shell pwd)
CROSS_COMPILE=/home/sds/toolchain/aarch64-linux-gnu/bin/aarch64-linux-gnu-
LDFLAG = -L/home/sds/toolchain/aarch64-linux-gnu/lib -lpqxx -lACE_SSL -Wl,-rpath-link=/home/sds/toolchain/aarch64-linux-gnu/lib:/home/sds/toolchain/aarch64-linux-gnu/aarch64-linux-gnu/libc/lib:/home/sds/toolchain/aarch64-linux-gnu/lib/aarch64-linux-gnu
CPPFLAG = $(FLAG) -DGET_CUPID_NOT_X86 -O0 -g3 -I/home/sds/toolchain/aarch64-linux-gnu/include
# -lcurl -lssl
CCU_BUILD_TIME = $(shell echo `date +"%Y%m%d-%H:%M:%S"`"@"`uname -n`)
CPPFLAG += -DCCU_BUILD_TIME="\"$(CCU_BUILD_TIME)\""
CCU_GIT_REVISION = $(shell git rev-parse HEAD)
CCU_GIT_COMMIT_TIME = $(shell git log --date=iso --pretty=format:"%cd" $(CCU_GIT_REVISION) -1)
CCU_GIT_INFO=$(CCU_GIT_REVISION) $(CCU_GIT_COMMIT_TIME)
CPPFLAG += -DCCU_GIT_REVISION="\"$(CCU_GIT_INFO)\""
ALL=Konkexinghai
SRCS=$(wildcard ../src/*.cpp)
SRCS+=$(wildcard ../src/lib/*.cpp)
SRCS+=$(wildcard ../src/lib/jsonlib/*.cpp)
OBJS+=$(subst .cpp,.o,$(SRCS))
DEPS=$(subst .cpp,.d,$(SRCS))
CC=$(CROSS_COMPILE)g++
LD=$(CROSS_COMPILE)g++
CFLAGS?=-O0 -Wall -g
LDFLAGS?=
CFLAGS+=
LDFLAGS+= -lpthread -lpaho-mqtt3as -lACE -fPIC
# -lssl -lcrypto
CPPFLAGS+= -I../ -I../src/include -fPIC -O0 -g3 -DARM
CPPFLAGS+=$(CPPFLAG) $(FLAG)
LDFLAGS+=$(LDFLAG)
V=1
V?=0
ifeq ($V, 0)
Q=@
endif
all:$(ALL)
ifneq ($(MAKECMDGOALS),clean)
-include $(DEPS)
endif
$(ALL): $(OBJS)
@echo "[LINK] $(ALL)"
$(Q)$(LD) $(EXTRA_LDFLAGS) $(OBJS) -o $(ALL) $(LDFLAGS)
%.d: %.cpp
@echo "[DEP] $@"
$(Q)set -e; rm -f $@;\
$(CC) -MM $(CPPFLAGS) $< > $@.tmp;\
sed 's,\($*\)\.o[ :]*,\1.o $@: ,g' < $@.tmp > $@;\
rm -f $@.tmp
$(OBJS): %.o: %.cpp
@echo "[CC] $@"
$(Q)$(CC) -c $(CPPFLAGS) $(EXTRA_CFLAGS) $(CFLAGS_$@) $< -o $@
clean:
-rm $(OBJS) $(DEPS) $(ALL)
distclean:clean
# install all files to ROOT_FS directory
install:
cp $(ALL) $(INSTALL_BIN)
CURDIR=$(shell pwd)
CROSS_COMPILE=arm-kk-linux-gnueabihf-
LDFLAG = -L/home/hj/third_party_libs/lib -lpqxx -lssl -lACE_SSL -Wl,-rpath-link=/home/hj/third_party_libs/lib
CPPFLAG = -DGET_CUPID_NOT_X86 -O0 -g3 -I/home/hj/third_party_libs/include
# -lcurl
CCU_BUILD_TIME = $(shell echo `date +"%Y%m%d-%H:%M:%S"`"@"`uname -n`)
CPPFLAG += -DCCU_BUILD_TIME="\"$(CCU_BUILD_TIME)\""
CCU_GIT_REVISION = $(shell git rev-parse HEAD)
CCU_GIT_COMMIT_TIME = $(shell git log --date=iso --pretty=format:"%cd" $(CCU_GIT_REVISION) -1)
CCU_GIT_INFO=$(CCU_GIT_REVISION) $(CCU_GIT_COMMIT_TIME)
CPPFLAG += -DCCU_GIT_REVISION="\"$(CCU_GIT_INFO)\""
ALL=Konkexinghai
SRCS=$(wildcard ../src/*.cpp)
SRCS+=$(wildcard ../src/lib/*.cpp)
SRCS+=$(wildcard ../src/lib/jsonlib/*.cpp)
OBJS+=$(subst .cpp,.o,$(SRCS))
DEPS=$(subst .cpp,.d,$(SRCS))
CC=$(CROSS_COMPILE)g++
LD=$(CROSS_COMPILE)g++
CFLAGS?=-O0 -Wall -g
LDFLAGS?=
CFLAGS+=
LDFLAGS+= -lpthread -lpaho-mqtt3a -lssl -lcrypto -lACE -fPIC
CPPFLAGS+= -I../ -I../src/include -fPIC -O0 -g3
CPPFLAGS+=$(CPPFLAG) $(FLAG)
LDFLAGS+=$(LDFLAG)
V=1
V?=0
ifeq ($V, 0)
Q=@
endif
all:$(ALL)
ifneq ($(MAKECMDGOALS),clean)
-include $(DEPS)
endif
$(ALL): $(OBJS)
@echo "[LINK] $(ALL)"
$(Q)$(LD) $(EXTRA_LDFLAGS) $(OBJS) -o $(ALL) $(LDFLAGS)
%.d: %.cpp
@echo "[DEP] $@"
$(Q)set -e; rm -f $@;\
$(CC) -MM $(CPPFLAGS) $< > $@.tmp;\
sed 's,\($*\)\.o[ :]*,\1.o $@: ,g' < $@.tmp > $@;\
rm -f $@.tmp
$(OBJS): %.o: %.cpp
@echo "[CC] $@"
$(Q)$(CC) -c $(CPPFLAGS) $(EXTRA_CFLAGS) $(CFLAGS_$@) $< -o $@
clean:
-rm $(OBJS) $(DEPS) $(ALL)
distclean:clean
# install all files to ROOT_FS directory
install:
cp $(ALL) $(INSTALL_BIN)
/*
* KK_HwDevManager.cpp
*
* Created on: Dec 6, 2018
* Author: sds
*/
#include "KK_HwDevManager.h"
#include <fstream>
#include <string>
#include "json/writer.h"
#include "json/reader.h"
#include "json/value.h"
#include "EH_ToolKit.h"
#include "LSC_Logger.h"
#include <stdio.h>
KK_HwDevManager* KK_HwDevManager::ms_pInstance = NULL;
KK_HwDevManager* KK_HwDevManager::GetInstance() {
if (ms_pInstance == NULL) {
ms_pInstance = new KK_HwDevManager();
}
return ms_pInstance;
}
KK_HwDevManager::KK_HwDevManager() {
}
//int KK_HwDevManager::getHwProfileConfig(EH::Json::Value& config) {
// ifstream infile(PROFILE_CONFIG_FILE);
// if (!infile) {
// EH_WARNING("open config info file:%s failed.\n", PROFILE_CONFIG_FILE);
// return -1;
// }
// EH::Json::Reader reader;
// bool success = reader.parse(infile, config, false);
// infile.close();
// if (!success || !config.isArray()) {
// EH_WARNING("Message format is wrong.\n");
// return -1;
// }
// return 0;
//}
//
//int KK_HwDevManager::loadAllSubDev(map<string,KKDevBindHwTriple> &subDevs){
// ifstream infile(DEV_CONFIG_FILE);
// if (!infile) {
// EH_WARNING("open dev info file:%s failed.\n", DEV_CONFIG_FILE);
// return 0;
// }
// EH::Json::Value devList;
// EH::Json::Reader reader;
// bool success = reader.parse(infile, devList, false);
// infile.close();
// if (!success || !devList.isArray()) {
// EH_WARNING("Message format is wrong.\n");
// return -1;
// }
// for (int i = 0; i < devList.size(); i++) {
// EH::Json::Value devInfo = devList[i];
// KKDevBindHwTriple bindDev;
// bindDev.mac = devInfo["mac"].asString();
// bindDev.prodId = devInfo["prodId"].asString();
// bindDev.sn = devInfo["sn"].asString();
// subDevs[bindDev.mac] = bindDev;
// }
// EH_DEBUG("load all sub dev,now dev count:%d.\n", subDevs.size());
// return 0;
//}
//int KK_HwDevManager::loadScenePanelName(map<string,KKScenePanelName> &subDevs){ //情景按钮名称读取
// ifstream infile(ScenePaneName_FILE);
// if (!infile) {
// EH_WARNING("open dev info file:%s failed.\n", ScenePaneName_FILE);
// return 0;
// }
// EH::Json::Value devList;
// EH::Json::Reader reader;
// bool success = reader.parse(infile, devList, false);
// infile.close();
// if (!success || !devList.isArray()) {
// EH_WARNING("Message format is wrong.\n");
// return -1;
// }
// for (int i = 0; i < devList.size(); i++) {
// EH::Json::Value devInfo = devList[i];
// KKScenePanelName bindDev;
// bindDev.devsn = devInfo["devsn"].asString();
// bindDev.nodeID = devInfo["nodeID"].asString();
// bindDev.name1 = devInfo["name1"].asString();
// bindDev.name2 = devInfo["name2"].asString();
// bindDev.name3 = devInfo["name3"].asString();
// bindDev.name4 = devInfo["name4"].asString();
// subDevs[bindDev.nodeID] = bindDev;
// }
// EH_DEBUG("load all sub dev,now dev count:%d.\n", subDevs.size());
// return 0;
//}
//int KK_HwDevManager::saveScenePanelName(map<string,KKScenePanelName> &subDevs){ //情景按钮名称保存
// EH::Json::Value devArray = EH::Json::Value(EH::Json::arrayValue);
// map<string, KKScenePanelName>::iterator it = subDevs.begin();
// for (; it != subDevs.end(); it++) {
// EH::Json::Value devInfo;
// devInfo["devsn"] = it->second.devsn;
// devInfo["nodeID"] = it->second.nodeID;
// devInfo["name1"] = it->second.name1;
// devInfo["name2"] = it->second.name2;
// devInfo["name3"] = it->second.name3;
// devInfo["name4"] = it->second.name4;
// devArray.append(devInfo);
// }
//
// EH::Json::StyledStreamWriter writer;
// ofstream outFile(ScenePaneName_FILE);
// if (!outFile) {
// EH_WARNING("open dev info file:%s failed.\n", ScenePaneName_FILE);
// return -1;
// }
// writer.write(outFile, devArray);
// outFile.close();
//
// EH_DEBUG("save all sub dev,now dev count:%d.\n", subDevs.size());
// return 0;
//}
//int KK_HwDevManager::saveAllSubDev(map<string,KKDevBindHwTriple> &subDevs){
// EH::Json::Value devArray = EH::Json::Value(EH::Json::arrayValue);
// map<string, KKDevBindHwTriple>::iterator it = subDevs.begin();
// for (; it != subDevs.end(); it++) {
// EH::Json::Value devInfo;
// devInfo["mac"] = it->second.mac;
// devInfo["prodId"] = it->second.prodId;
// devInfo["sn"] = it->second.sn;
// devArray.append(devInfo);
// }
//
// EH::Json::StyledStreamWriter writer;
// ofstream outFile(DEV_CONFIG_FILE);
// if (!outFile) {
// EH_WARNING("open dev info file:%s failed.\n", DEV_CONFIG_FILE);
// return -1;
// }
// writer.write(outFile, devArray);
// outFile.close();
//
// EH_DEBUG("save all sub dev,now dev count:%d.\n", subDevs.size());
// return 0;
//}
string KK_HwDevManager::getCcuId() {
ifstream infile(CCUID_PATH);
if (!infile) {
return "";
}
char buffer[64];
infile.getline(buffer, 64);
infile.close();
return string(buffer);
}
string KK_HwDevManager::getCcuKey() {
ifstream infile(LICENSE_PATH);
if (!infile) {
return "";
}
char buffer[100];
infile.getline(buffer, 100);
infile.getline(buffer, 100);
infile.close();
return string(buffer);
}
string KK_HwDevManager::GetConnectState(){
ifstream infile(CONNECT_STATE_FILE);
string ConnectState;
if (!infile) {
LOGW("open dev info file:%s failed.\n", CONNECT_STATE_FILE);
return 0;
}
EH::Json::Value devInfo;
EH::Json::Reader reader;
bool success = reader.parse(infile, devInfo, false);
infile.close();
if (devInfo.empty() == true) {
LOGW("Message format is wrong.\n");
return "-1";
}
ConnectState = devInfo["result"].asString();
return ConnectState;
}
EH::Json::Value KK_HwDevManager::loadConnectState(){
ifstream infile(CONNECT_STATE_FILE);
EH::Json::Reader reader;
EH::Json::Value connectStateInfo;
if (!infile) {
LOGW("open dev info file:%s failed.\n", CONNECT_STATE_FILE);
return 0;
}
bool success = reader.parse(infile, connectStateInfo, false);
infile.close();
if (connectStateInfo.empty() == true) {
LOGW("Message format is wrong.\n");
return -1;
}
LOGI("load connectStateInfo:%s.\n",EH_ToolKit::JsonToString(connectStateInfo).c_str());
return connectStateInfo;
}
int KK_HwDevManager::saveConnectState(EH::Json::Value ConnectState){
EH::Json::StyledStreamWriter writer;
ofstream outFile(CONNECT_STATE_FILE);
if (!outFile) {
LOGW("open dev info file:%s failed.\n", CONNECT_STATE_FILE);
return -1;
}
writer.write(outFile, ConnectState);
outFile.close();
LOGI("save Connect State success\n");
return 0;
}
string KK_HwDevManager::GetRoomId(){
ifstream infile(ROOM_ID_FILE);
string roomid;
if (!infile) {
LOGW("open dev info file:%s failed.\n", ROOM_ID_FILE);
return 0;
}
EH::Json::Value devList;
EH::Json::Reader reader;
bool success = reader.parse(infile, devList, false);
infile.close();
//if (!success || !devList.isNull()) {
if (devList.empty() == true) {
LOGW("Message format is wrong.\n");
return "-1";
}
for (int i = 0; i < devList.size(); i++) {
EH::Json::Value devInfo = devList[i];
roomid = devInfo["roomid"].asString();
}
return roomid;
}
int KK_HwDevManager::loadroomid(map<string,KKRoomId> &roomid){
ifstream infile(ROOM_ID_FILE);
if (!infile) {
LOGW("open dev info file:%s failed.\n", ROOM_ID_FILE);
return 0;
}
EH::Json::Value devList;
EH::Json::Reader reader;
bool success = reader.parse(infile, devList, false);
infile.close();
//if (!success || !devList.isNull()) {
if (devList.empty() == true) {
LOGW("Message format is wrong.\n");
return -1;
}
for (int i = 0; i < devList.size(); i++) {
EH::Json::Value devInfo = devList[i];
KKRoomId bindDev;
bindDev.roonid = devInfo["roomid"].asString();
bindDev.name = devInfo["name"].asString();
roomid[bindDev.roonid] = bindDev;
}
LOGD("load all sub dev,now dev count:%d.\n", roomid.size());
return 0;
}
int KK_HwDevManager::saveroomid(map<string,KKRoomId> &roomid){
EH::Json::Value devArray = EH::Json::Value(EH::Json::arrayValue);
map<string, KKRoomId>::iterator it = roomid.begin();
for (; it != roomid.end(); it++) {
EH::Json::Value devInfo;
devInfo["roomid"] = it->second.roonid;
devInfo["name"] = it->second.name;
devArray.append(devInfo);
}
EH::Json::StyledStreamWriter writer;
ofstream outFile(ROOM_ID_FILE);
if (!outFile) {
LOGW("open dev info file:%s failed.\n", ROOM_ID_FILE);
return -1;
}
writer.write(outFile, devArray);
outFile.close();
LOGD("roomid:%d.\n", roomid.size());
return 0;
}
/*
* KK_HwDevManager.h
*
* Created on: Nov 29, 2018
* Author: sds
*/
#ifndef KK_HWDEVMANAGER_H_
#define KK_HWDEVMANAGER_H_
#include <map>
#include <string>
#include <map>
#include <vector>
#include <set>
#include "json/reader.h"
#include "json/writer.h"
#include "json/value.h"
using namespace std;
//#define DEV_CONFIG_FILE "/home/hj/hilink/config/hj_hwdev.json"
//#define PROFILE_CONFIG_FILE "/home/hj/hilink/config/hj_hwprofile.json"
#define ROOM_ID_FILE "/home/hj/Roma/config/hj_hwroomid.json"
#define CONNECT_STATE_FILE "/home/hj/Roma/config/hj_hwconnectstate.json"
#if defined(NOT_X86)
#define LICENSE_PATH "/etc/dropbear/accessory/hj/hj_license"
#define CCUID_PATH "/etc/dropbear/accessory/hj/hj_ccuid"
// #define PRODUCTID_PATH "/etc/dropbear/accessory/hj/hj_productid"
// #define QRTOKEN_PATH "/etc/dropbear/accessory/hj/hj_qrtoken"
#else
#define LICENSE_PATH "/etc/hj_license"
#define CCUID_PATH "/etc/hj_ccuid"
// #define PRODUCTID_PATH "/etc/hj_productid"
// #define QRTOKEN_PATH "/etc/hj_qrtoken"
#endif
class KK_HwDevManager {
public:
// class KKDevBindHwTriple {
// public:
// //hw dev info
// string prodId;
// string sn;
// //kk dev mac
// string mac;
// };
class KKRoomId {
public:
string roonid;
string name;
};
// class KKScenePanelName {//情景面板按钮的名称。
// public:
// string nodeID;
// string devsn;
// string name1;
// string name2;
// string name3;
// string name4;
// };
// class KKConnectState {
// public:
// string state;
// string client_id;
// string device_name;
// };
public:
static KK_HwDevManager* GetInstance();
//int loadAllSubDev(map<string,KKDevBindHwTriple> &subDevs);
//int saveAllSubDev(map<string,KKDevBindHwTriple> &subDevs);
// int getHwProfileConfig(EH::Json::Value& config);
int loadroomid(map<string,KKRoomId> &roomid);
int saveroomid(map<string,KKRoomId> &roomid);
//int loadScenePanelName(map<string,KKScenePanelName> &subDevs);
//int saveScenePanelName(map<string,KKScenePanelName> &subDevs);
string GetRoomId();
EH::Json::Value loadConnectState();
int saveConnectState(EH::Json::Value ConnectState);
string GetConnectState();
string getCcuId();
string getCcuKey();
private:
KK_HwDevManager();
private:
static KK_HwDevManager* ms_pInstance;
};
#endif /* KK_HWDEVMANAGER_H_ */
This diff is collapsed.
#ifndef MQ_CCU_ADAPTER_H_
#define MQ_CCU_ADAPTER_H_
#include <sys/types.h>
#include <vector>
#include <set>
#include <string>
#include <pthread.h>
#include <ace/Task.h>
#include <ace/Condition_Thread_Mutex.h>
#include <ace/Thread_Mutex.h>
#include <ace/Time_Value.h>
#include "json/value.h"
#include "json/reader.h"
#include "KK_CcuConfig.h"
#include "EH_Client.h"
#include "KK_MqttSdk.h"
#include "kk_connect.h"
#include "lib/EH_SDKDef.h"
#include "kk_handleDeviceInfo.h"
#include "KK_HwDevManager.h"
#define CENTRALAC_INDOORUNIT_NUM_MAX 64
#define MQ_VERSION "1.0.2.10"
using namespace std;
class MQ_CCU_Adapter:public ACE_Task<ACE_MT_SYNCH>,
public EH_Client::EH_ClientCallBackHandler,
public KK_MQTTSDK::EH_SDKCallbackHandler{
public:
static MQ_CCU_Adapter* GetInstance();
int svc();
int open();
//与中控连接的当前状态
void onClientStatusChanged(EH_Client::ClientStatus currentStatus);
//接收中控的信息
void onRecvMsg(string nodeId, string opcode, EH::Json::Value arg, string status);
//添加到房间里
void SendSETUPToCcu(string name,string DeviceIcon,string DevDodeId,string roomid, string opcode);
//发送信息到Roma
int sendtoRoma(EH::Json::Value payload,string respTopic);
//发送设备控制命令
int send_Control_Info(string wholeMsg);
void onCloudConnect();
void onCloudDisConnect();
void onCloudMsgRecv(string payload,string topicName);
private:
MQ_CCU_Adapter();
int Put(ACE_Message_Block* mblk, ACE_Time_Value* timeout = NULL);
void sendReqToCcu(string opcode,string nodeid,string arg,string requester);
//加载主机所有已经添加的设备
int loadAllSubDev(EH::Json::Value arg);
//当前的设备状态
void handleGetDevsHardwareInfo(EH::Json::Value arg);
void handleDevOnlinePush(EH::Json::Value arg);
void oninitmqttsdk();
//房间概念信息
int addCCuroom();
int saveCCuroom(EH::Json::Value arg);
void Specific_rooms(EH::Json::Value rooms);
//处理新设备报文
void handleNewDevice(EH::Json::Value devices, EH::Json::Value centralACdevices, EH::Json::Value newCentralAcGwsDevices);
void handleCcuDeviceToHwSubDev(string operateType,string nodeid,string mac,
string channel,string sn,EH::Json::Value status,string devroomid,string devname);
void handleACindoor(string devroomid,string devname,int indoorunitsdevCount,EH::Json::Value centralACdevices,int infocome);
//当网关离线,其下内机也推送离线
void handleACindoorDevNolinePush(string mac);
//处理已加入房间的设备报文
void handleSyncInfo(EH::Json::Value arg,string opcode);\
void SYNC_handle_AcGw_Devices(EH::Json::Value CentralAcGwsDevices);
//添加设备到云
void addCCuDevicesToCloud(map<string,kk_handleDeviceInfo::HwSubDev*> toAddSubDevs);
//设备本地进行了删除
int loadDelete(EH::Json::Value arg);
//下发查询网关信息
int on_Query_GateWay_Infomation();
//添加新设备
int onDeviceRequestJoin(bool enableJoinSubdev);
//删除子设备
int onDeviceRequestDelete(string devSn);
//删除所有设备
int deleteCCuDevices();
//删除网关时,也删除其下的内机。
int onACindoorDelete(string devMac);
//解绑网关
int on_unbind_gateway(string device_name,string client_id,string method);
//获取网关的nodeID
void handlegwNodeId(EH::Json::Value arg);
//Zigbee 设备入网推送的信息
int handle_Dev_Join_Notify(EH::Json::Value arg);
private:
EH_Client* client;
KK_MQTTSDK* mqttSdk;
private:
static MQ_CCU_Adapter* ms_pInstance;
ACE_Thread_Mutex mtx;
ACE_Condition_Thread_Mutex cond;
set<string> ccuDeleteMacs;//prepare to delete ccu devs
map<string,string> nodeId2channelMap; //nodeid -> mac:channel
map<string,kk_handleDeviceInfo::HwSubDev*> hwSubDevs; //hw dev in ccu
map<string,kk_handleDeviceInfo::KKDevmapinfo> hwBindDevMap;//
map<string,KK_HwDevManager::KKRoomId > onlyroomid; //适配程序创建的特定房间信息。
map<string,string> gwId2NodeId;//空调网关ID与空调网关的nodeID的对应关系。//空调网关不加入房间里,空调内机添加到房间里后,续空调网关的mac相关信息在SYNE—INFO,就可以去除
map<string,string> NodeId2gwId; //空调网关的nodeID与空调网关ID的对应关系。
map<string,string> operate2NodeId; //空调网关设备类型与空调网关设备nodeID的对应关系
map<string,vector<string> > controllerModel; //mac -> id //空调网关
map<string,string> indoorunitsId2AddrMap; //内机的nodeid -> 空调网关mac:内机通道channel
map<string,string> Join_productid_Map; //新加入设备mac -> 设备productid
int roomidok;
unsigned long lastCcuReqTime;
string ccuId;
string gw_id;
string gw_NodeId;//Z3的网关nodeID
string clientId;
string username;
string ptpoTopic ;
string ptpTopic;
// string willTopic;
bool KKdiscover;
bool ccuSyncOK;
bool handleNewDevices;
EH::Json::Value newDevices;
EH::Json::Value newCentralAcDevices;
EH::Json::Value newCentralAcGwsDevices;
string ccuStatus;
string Deletesn;
bool mqttOnline =true;
bool SaveRoomEnable =false;
bool discoveryEnable =false;
};
#endif
/*
* MQ_CCU_Config.cpp
*
* Created on: Dec 6, 2018
* Author: sds
*/
#include "MQ_CCU_Config.h"
#include <fstream>
#include <string>
#include "json/writer.h"
#include "json/reader.h"
#include "json/value.h"
#include "LSC_Logger.h"
#include "EH_ToolKit.h"
MQ_CCU_Config* MQ_CCU_Config::ms_pInstance = NULL;
MQ_CCU_Config* MQ_CCU_Config::GetInstance() {
if (ms_pInstance == NULL) {
ms_pInstance = new MQ_CCU_Config();
}
return ms_pInstance;
}
MQ_CCU_Config::MQ_CCU_Config() {
logLevel = "D";
}
//读取配置文件里的参数
int MQ_CCU_Config::open() {
ifstream infile(MQ_PROXY_CONFIG_FILE);
if (!infile) {
//打开配置文件失败
LOGW("open config info file:%s failed.\n", MQ_PROXY_CONFIG_FILE);
return -1;
}
EH::Json::Reader reader;
EH::Json::Value config;
bool success = reader.parse(infile, config, false);
infile.close();
if (!success || !config.isObject()) {
//消息格式错误
LOGW("Message format is wrong.\n");
return -1;
}
brokerAddr = config[MQ_BROKER_ADDRESS].asString(); //MQ代理地址
logLevel = config[LOG_LEVEL].asString(); //日志等级
cacheSize = config[REQ_SIZE].asInt(); //请求队列大小
return 0;
}
//获取代理地址
string MQ_CCU_Config::getBrokerAddr() {
return brokerAddr;
}
//获取日志等级
string MQ_CCU_Config::getLogLevel() {
return logLevel;
}
//获取请求队列大小
int MQ_CCU_Config::getReqCacheSize() {
return cacheSize;
}
//获取主机的ID
string MQ_CCU_Config::getCcuId() {
ifstream infile(CCUID_PATH);
if (!infile) {
return "";
}
char buffer[64];
infile.getline(buffer, 64);
infile.close();
return string(buffer);
}
//获取Ccu访问密钥
string MQ_CCU_Config::getCcuAccesskey() {
ifstream infile(LICENSE_PATH);
if (!infile) {
return "";
}
char buffer[512] = { 0 };
infile.read(buffer,512);
infile.close();
vector<string> infos;
EH_ToolKit::Split(string(buffer), "\n", infos);
if(infos.size()==2){
return infos[1];
}
return "";
}
#ifndef MQ_CCU_CONFIG_H_
#define MQ_CCU_CONFIG_H_
#include <map>
#include "json/value.h"
using namespace std;
#define MQ_PROXY_CONFIG_FILE "/home/hj/Roma/config/mq_config.json" //MQTT 预配置文件
#define MQ_BROKER_ADDRESS "broker_addr"
#define LOG_LEVEL "log_level"
#define REQ_SIZE "req_queue_size"
#if defined(NOT_X86)
#define LICENSE_PATH "/etc/dropbear/accessory/hj/hj_license"
#define CCUID_PATH "/etc/dropbear/accessory/hj/hj_ccuid"
#else
#define LICENSE_PATH "/etc/hj_license"
#define CCUID_PATH "/etc/hj_ccuid"
#endif
class MQ_CCU_Config {
public:
static MQ_CCU_Config* GetInstance();
int open();
string getCcuId();
string getCcuAccesskey();
string getBrokerAddr();
string getLogLevel();
int getReqCacheSize();
private:
MQ_CCU_Config();
private:
static MQ_CCU_Config* ms_pInstance;
string brokerAddr;
string logLevel;
int cacheSize;
};
#endif
#include <ace/Init_ACE.h>
#include <ace/Reactor.h>
#include <ace/Process_Mutex.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "LSC_Logger.h"
#include "MQ_CCU_Config.h"
#include "MQ_CCU_Adapter.h"
#include "EH_ToolKit.h"
#define DEF_LOG_LEAVE "D"
static void oepnDebug();
int ACE_TMAIN(int argc, ACE_TCHAR* argv[]) { //主函数
// 与程序进程管理有关?
if(argc == 2) {
string flag = argv[1];
if (flag == "-v") {
cout<<"Konkexinghai:"<< MQ_VERSION << endl;
exit(0);
}
}
//对ACE::init()组件进行初始化
if (ACE::init() == -1) {
LOGE("Init ACE failed.\n");
ACE_OS::exit(-1); //exit函数告诉系统程序已完成,从而终止进程。
}
ACE_OS::signal(SIGPIPE, SIG_IGN); //signal函数将action设置为signum的action。
//消息转储核心转储集
EH_ToolKit::SetCoredumpMsgDump();
//开启日志并开始记录
if (LSC_LOGGER::instance()->open("konkeyunzhiyi", DEF_LOG_LEAVE) != 0) {
LOGE("Init lsc logger failed.\n");
ACE_OS::exit(1);
}
//创建ACE_进程 konkeyunzhiyi
ACE_Process_Mutex processMutex("konkeyunzhiyi"); //进程名检测
if (processMutex.tryacquire() < 0) { //
//相同的进程正在运行,当前进程将中止 。异常的判段处理
LOGE("The same process is running.current process will abort.\n");
return -1;
} else {
LOGI("konke yunzhiyi Starting...Version:%s \n",MQ_VERSION);
LOGI("konke yunzhiyi Starting...Version 编译时间:%s %s \n",__DATE__,__TIME__);
LOGI("konke yunzhiyi acquired.\n");
}
if(KK_CcuConfig::GetInstance()->Open()!=0){
LOGE("Ccu Config failed.\n");
ACE_OS::exit(-1);
return -1;
}
//暂不开启延时。
//sleep(10);
int ret = MQ_CCU_Config::GetInstance()->open();
if(ret != 0){
LOGE("load config failed.\n");
ACE_OS::exit(1);
}
//更新日志级别,
// LSC_LOGGER::instance()->set_log_leave(MQ_CCU_Config::GetInstance()->getLogLevel());
//MQ_CCU_Adapter 适配器 还有相关启动。
ret = MQ_CCU_Adapter::GetInstance()->open();
if(ret != 0){
LOGE("mqtt init failed.\n");
ACE_OS::exit(1);
}
if(argc == 2 && string(argv[1]) == "-d") {
oepnDebug();
}
return ACE_Reactor::instance()->run_reactor_event_loop();
}
static int serverSocket;
static void processReq(string req) { //处理请求
if(req == "new_mqtt_tcp"){
// KK_MQTTSDK::GetInstance()->reinit("tcp://121.37.12.6:1883");
KK_MQTTSDK::GetInstance()->reinit("tcp://127.0.0.1:23883");
}else if(req == "new_mqtt_ssl"){
// KK_MQTTSDK::GetInstance()->reinit("ssl://120.55.149.201:8883");
KK_MQTTSDK::GetInstance()->reinit("ssl://127.0.0.1:23883");
}else if(req == "con_mqtt_0") {
KK_MQTTSDK::GetInstance()->con(0);
}else if(req == "con_mqtt_1") {
KK_MQTTSDK::GetInstance()->con(1);
}else if(req == "discon_mqtt") {
KK_MQTTSDK::GetInstance()->discon();
}else if(req == "del_mqtt") {
KK_MQTTSDK::GetInstance()->destroy();
}else{
LOGW("not support req:%s.\n",req.c_str());
}
}
static void* run0(void* opt){
char buff[512];
struct sockaddr_in clientAddr; /*描述Internet套接字地址的结构。*/
int n;
int len = sizeof(clientAddr);
while (true){
//接收信息
//recvfrom函数从套接字将一个数据包读入缓冲区。size参数指定要读取的最大字节数。
n = ACE_OS::recvfrom(serverSocket, buff, sizeof(buff), 0, (struct sockaddr*)&clientAddr, &len);
if (n>0){
buff[n] = 0;
LOGI("recv from [%s : %d]: %s\n",inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port),buff);
//处理请求
processReq(string(buff));
}
else{
//从接收失败。
LOGE("recvfrom failed. \n");
}
}
return NULL;
}
static void oepnDebug(){
struct sockaddr_in addr; /*描述Internet套接字地址的结构。*/
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=htonl(INADDR_ANY);
addr.sin_port=htons(8761);
//创建mqtt调试服务器
if ((serverSocket = ACE_OS::socket(AF_INET, SOCK_DGRAM, 0)) < 0){
LOGE("create mqtt debug server failed. \n");
return ;
}
//将mqtt调试服务器绑定到本地端口
/*名称:绑定
原型:int bind(int socket,struct sockaddr*addr,socklen_ntlength)
说明:
bind函数为套接字分配一个地址。addr和length参数指定地址
地址的详细格式取决于命名空间。地址的第一部分总是格式
标识符,它指定一个名称空间,并说明地址采用该名称空间的格式。
成功时返回值为0,失败时返回值为-1。为此函数定义了以下errno错误条件:
EBADF套接字参数不是有效的文件描述符。*/
if (ACE_OS::bind(serverSocket, (struct sockaddr *)&addr, sizeof(addr)) < 0){ /*描述通用套接字地址的结构。*/
ACE_OS::close(serverSocket);
LOGE("bind mqtt debug server to local port failed. \n");
}
//线程创建
/*创建一个新线程,从执行START-ROUTINE开始
正在传递ARG。创造属性来自属性。新的
句柄存储在*NEWTHREAD中。*/
pthread_t tid;
pthread_create(&tid, NULL, run0, NULL);
}
/*
* EH_Client.h
*
*/
#ifndef EH_CLIENT_H_
#define EH_CLIENT_H_
#include <sys/types.h>
#include <vector>
#include <string>
using namespace std;
#include "json/value.h"
class EH_Client {
public:
enum ClientStatus {
UNINIT,
INITING,
INIT_FINISH,
FIND_CCU_IP,
LINK_BUILDING,
LINK_BUILD_OK,
LINK_BUILD_FAILED,
LINK_BROKEN,
LOGINING,
LOGIN_FINISH_OK,
LOGIN_FINISH_FAILED,
WORKING,
STOP
};
public:
class EH_ClientCallBackHandler {
public:
virtual ~EH_ClientCallBackHandler() {} ;
virtual void onClientStatusChanged(ClientStatus currentStatus) = 0;
virtual void onRecvMsg(string nodeId, string opcode, EH::Json::Value arg, string status) = 0;
};
public:
EH_Client();
virtual ~EH_Client();
int init(string ccuId, string accessKey, EH_ClientCallBackHandler* cb,
bool autoDestroyHandler);
ClientStatus getClientStatus() const;
int sendRequest(string nodeId, string opcode,string arg, string requester);
void destroy();
public:
static string getClientStatusStr(ClientStatus status);
static void* run0(void* opt);
private:
void* run(void* opt);
void sendLoginReq();
void changeClientStatus(ClientStatus newStatus);
int sendMsgToServer(string msg);
void processRecvMsg(string msg);
EH::Json::Value parseRecvMsg(string msg, bool& error);
private:
void onCCUIpChanged(string ccuNewIp);
private:
ClientStatus currentStatus;
string ccuId;
string accessKey;
string ccuServerIp;
u_short ccuServerPort;
EH_ClientCallBackHandler* cb;
bool autoDestroyHandler;
int connectToCcuFd;
bool destroyed;
int sendMsgErrorSum;
string cacheInputMsg;
};
#endif /* EH_CLIENT_H_ */
/*
* EH_DEBUG.h
*
*/
#ifndef EH_DEBUG_H_
#define EH_DEBUG_H_
#include <stdio.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(__NR_gettid)
#define EH_DEBUG(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_INFO(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_NOTICE(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_WARNING(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_ERROR(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_CRITICAL(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_ALERT(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_EMERGENCY(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_TRACE(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_DEBUG(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_INFO(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_NOTICE(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_WARNING(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_ERROR(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_CRITICAL(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_ALERT(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_EMERGENCY(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_TRACE(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
#endif /* EH_DEBUG_H_ */
/**
* EH_Exception.h
*
*/
#ifndef EH_EXCEPTION_H_
#define EH_EXCEPTION_H_
#include <string>
#include <exception>
#include <iostream>
using namespace std;
class EH_Exception : public exception {
public:
EH_Exception(const char* error_msg,
const char* file_name,
unsigned int line_no,
const char* function_name,
int error_code = 0);
virtual ~EH_Exception() throw ();
const char* GetErrorMsg() const;
virtual const char* what() const throw () {
return m_strErrorMsg.c_str();
}
unsigned int GetLineNo() const;
const char* GetFileName() const;
const char* GetFunctionName() const;
int GetErrorCode() const;
virtual ostream& dump(ostream& arOstream) const;
friend ostream& operator<<(ostream& arOstream,
const EH_Exception& arException);
private:
string m_strErrorMsg;
string m_strFileName;
string m_strFunctionName;
unsigned int m_uiLineNo;
int m_nErrorCode;
};
#define EH_EXCEPTION(msg) EH_Exception(msg, __FILE__, __LINE__, __func__)
#define EH_EXCEPTION_ERR(msg) EH_Exception(msg, __FILE__, __LINE__, __func__, err)
#endif /* EH_EXCEPTION_H_ */
/*
* EH_FindCCU.h
*
* Created on: 2020年10月9日
* Author: hj
*/
#ifndef INCLUDE_EH_FINDCCU_H_
#define INCLUDE_EH_FINDCCU_H_
#include "EH_ToolKit.h"
class EH_FindCCU {
public:
EH_FindCCU();
virtual ~EH_FindCCU();
int init(string ccuId,string ccuLocalIP);
void destroy();
public:
static void* run0(void* opt);
private:
void* run(void* opt);
void sendFindCCUMsg();
private:
string ccuId;
string ccuSn;
string ccuIp;
string ccuLocalIP;
bool destroyed;
int searchCcuFd;
};
#endif /* INCLUDE_EH_FINDCCU_H_ */
/*
* EH_FindCCUCallBackHandler.h
*
* Created on: 2020年10月9日
* Author: hj
*/
#ifndef INCLUDE_EH_FINDCCUCALLBACKHANDLER_H_
#define INCLUDE_EH_FINDCCUCALLBACKHANDLER_H_
#include <string>
using namespace std;
class EH_FindCCUCallBackHandler {
public:
virtual void onCCUIpChanged(string ccuNewIp) {};
};
#endif /* INCLUDE_EH_FINDCCUCALLBACKHANDLER_H_ */
/*
* EH_ServerSdk.h
*
* Created on: 2020年10月9日
* Author: hj
*/
#ifndef INCLUDE_EH_SERVERSDK_H_
#define INCLUDE_EH_SERVERSDK_H_
#include <map>
#define REQEUST_MAX_WAITTIMEOUT 5
class EH_ServerSdk {
public:
static EH_ServerSdk* GetInstance();
int Open();
private:
EH_ServerSdk();
virtual ~EH_ServerSdk();
private:
static EH_ServerSdk* ms_instance;
bool start;
};
#endif /* INCLUDE_EH_SERVERSDK_H_ */
This diff is collapsed.
/**
* EH_ToolKit.h
*
* Copyright by AirDream Co., Ltd. 2010-2011 All right reserved
*
* Description:
* Created on:2011-8-25
* Modified on:2011-8-25
*
*/
#ifndef EH_TOOLKIT_H_
#define EH_TOOLKIT_H_
#include <stdint.h>
#include <sstream>
#include <string>
#include <vector>
#include <stdio.h>
#include "ace/Message_Block.h"
#include "ace/Process_Mutex.h"
#include "ace/SOCK_Stream.h"
#include "ace/UUID.h"
#include "ace/OS_NS_time.h"
#include "json/writer.h"
#include "json/reader.h"
#include "json/value.h"
#define COMPARE_VER_MORE_THAN 1
#define COMPARE_VER_LESS_THAN 2
#define COMPARE_VER_EQ_THAN 3
using namespace std;
class EH_ToolKit {
public:
static void PrintMsg(const uint8_t *msg, uint16_t msg_len,bool isDebug);
static void Split(const string& src, const string& separator, vector<string>& dest);
static string Trim(string& s);
static unsigned short CheckSum(const unsigned char* in,const int len);
static int StringToHex(const char*input, unsigned char*output,const int bufLen);
static int StringToHexNoSpace(const char* input, unsigned char* output,const int bufLen);
static int HexToStringNoSpace(const char* input, char* output, int len);
static int HexToString(const char* input, char* output, int len,const char* sep);
static int StringToInt(const string input);
static uint StringToUInt(const string input);
static double StringToDouble(const string input);
static string IntToString(const int input);
static string UIntToString(const uint input);
static string UInt64ToString(const ACE_UINT64 input);
static string DoubleToString(const double input);
static string JsonToString(const EH::Json::Value& json);
static string CreateRespJsonMsg(string opcode,string arg,int status,string nodeid = "*");
static string CreateRespJsonMsgWithErrorCode(string opcode,string arg,int status,string nodeid = "*",
int error=-1);
static string CreateReqJsonMsg(string opcode,string arg,string requester,string nodeid = "*");
static string CreateReqJsonMsgWithReqId(string opcode,string arg,string requester,string nodeid = "*",string reqId = "");
static string CreateReqJsonMsgWithArgJson(string opcode,EH::Json::Value arg,string requester,string nodeid = "*",string reqId = "");
static bool CompareNoCase(string str1,string str2);
static bool HasSpareProcess(const string processName);
static bool CheckRoot();
static const char* GetLocalIP(string interface="NOT_SET");
static void BuildAbsTimeOut(ACE_Time_Value* timeout,int timeoutMS);
static void ShowHelpInfo();
static void ShowVersionInfo(string proc,string version);
static int GetVersionInfo(string version, int& majorV, int& minorV, int& betaV, bool hasVersionPrefix=true);
static int CompareVersion(string checkVersion, string baseVersion);
static uint32_t CreateCrc32(const uint8_t *msg, uint32_t len);
static uint16_t CreateCrc16(const uint8_t *msg, uint32_t len);
static uint16_t CrcByte(uint16_t crc, uint8_t b);
static uint16_t Crc16(void* buf, uint8_t len);
static bool Ping(string destIP);
static int GetCpuCoreNum();
static bool MatchVersion(string version,string pattern);
static void SetCoredumpMsgDump();
static void PrintBacktrace(int signum);
static string GetUUID();
static string GetCurrentTime();
static ACE_UINT64 getSystemTimeInMs();
static int DoSystem(string cmd);
static string GetTimestamp();
static string GetMac();
static string GetMacNoSpace();
private:
static string GetFileContent(string filePath, bool& error);
private:
static uint32_t ms_uiCrc32Tab[256];
};
#endif /* EH_TOOLKIT_H_ */
/*
* KK_MQTTSDK.h
*
* Created on: Nov 29, 2018
* Author: sds
*/
#ifndef KK_MQTTSDK_H_
#define KK_MQTTSDK_H_
#include <string>
#include <map>
#include <vector>
#include <set>
#include "ace/Task.h"
using namespace std;
class KK_MQTTSDK : public ACE_Event_Handler {
public:
class EH_SDKCallbackHandler {
public:
virtual void onCloudConnect() = 0;
virtual void onCloudDisConnect() = 0;
virtual void onCloudMsgRecv(string payload,string topicName) = 0;
};
public:
static void* run0(void* opt);
public:
static KK_MQTTSDK* GetInstance();
int init(string brokerAddr,string clientId,string username,string password,string heartbeat_Topic,string gw_id);
int subTopic(string topic,int qos = 0,int waitTimeout = 0);
int unsubTopic(string topic,int waitTimeout = 0);
int sendMsg(string topic,string payload,int qos = 0);
int reinit(string brokerAddr);
int con(int autoRecon,int timeoutInSec = 2);
int discon();
int destroy();
void setSdkCallbackHandler(EH_SDKCallbackHandler* handler);
EH_SDKCallbackHandler* getSdkCallbackHandler();
void recon(int delayInSec);
private:
KK_MQTTSDK();
void* run(void* opt);
int handle_timeout(const ACE_Time_Value &current_time,const void *act = 0);
private:
static KK_MQTTSDK* ms_Instance ;
string gw_id;
string clientId;
string brokerAddr;
string username;
string password;
string willTopic;
string heartbeat_Topic;
string topic1 ,topic2; //订阅的主题
long reconTimerId;
EH_SDKCallbackHandler* callbackHandler;
};
#endif /* KK_MQTTSDK_H_ */
/*
* KK_Util.h
*
* Created on: 2018骞�12��10��
* Author: weiling
*/
#ifndef KK_UTIL_H_
#define KK_UTIL_H_
#include <string.h>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <bitset>
#include <sstream>
#include <netinet/in.h>
using namespace std;
#define BIGENDIAN_S(num) htons(num)
int HexToString(const char* input, char* output, int len,const char* sep);
int StringToHex(const char* input, unsigned char* output,const int bufLen);
int StringToHexNoSpace(const char* input, unsigned char* output,const int bufLen);
string IntToString(const int input);
string UIntToString(const uint input);
int StringToInt(const string input,int& error);
uint StringToUInt(const string input,int& error);
double StringToDouble(const string input,int& error);
string DoubleToString(const double input,int& error);
void Split(const string& src, const string& separator, vector<string>& dest);
unsigned long getSystemTimeInMs();
string Replace(const string& str, const string& src, const string& dest);
#endif /* KK_UTIL_H_ */
/*
* LSC_Logger.h
*
* Created on: 2014-4-10
* Author: sj
*/
#ifndef LSC_LOGGER_H_
#define LSC_LOGGER_H_
#include <ace/Log_Msg.h>
#include <ace/streams.h>
#include <ace/SOCK_Dgram.h>
#include <ace/Singleton.h>
#include <ace/Recursive_Thread_Mutex.h>
#include <string>
using namespace std;
#undef ACE_NTRACE
#define ACE_NTRACE 0
class LSC_ProcessExitLog : public ACE_Cleanup {
public:
void cleanup (void *param = 0);
};
class LSC_Logger {
public:
/// A do nothing constructor.
LSC_Logger();
/// Virtual destruction
virtual ~LSC_Logger();
int open(string process_name,string log_leave);
int set_log_leave(string log_leave);
ACE_Log_Priority get_log_leave();
private:
ACE_Log_Priority curr_log_leave;
};
typedef ACE_Singleton<LSC_Logger, ACE_Recursive_Thread_Mutex> LSC_LOGGER;
#define DEBUG_PREFIX ACE_TEXT ("DEBUG %P %t %D %N:%l# ")
#define INFO_PREFIX ACE_TEXT ("INFO %P %t %D %N:%l# ")
#define NOTICE_PREFIX ACE_TEXT ("NOTICE %P %t %D %N:%l# ")
#define WARNING_PREFIX ACE_TEXT ("WARNING %P %t %D %N:%l# ")
#define ERROR_PREFIX ACE_TEXT ("ERROR %P %t %D %N:%l# ")
#define CRITICAL_PREFIX ACE_TEXT ("CRITICAL%P %t %D %N:%l# ")
#define ALERT_PREFIX ACE_TEXT ("ALERT %P %t %D %N:%l# ")
#define EMERGENCY_PREFIX ACE_TEXT ("EMERGENC%P %t %D %N:%l# ")
#define LOGD(FMT, ...) \
do {\
ACE_DEBUG((LM_DEBUG, DEBUG_PREFIX ACE_TEXT(FMT), ## __VA_ARGS__));\
} while(0);
#define LOGI(FMT, ...) \
do {\
ACE_DEBUG((LM_INFO, INFO_PREFIX ACE_TEXT(FMT), ## __VA_ARGS__));\
} while(0);
#define LOGN(FMT, ...) \
do {\
ACE_DEBUG((LM_NOTICE, NOTICE_PREFIX ACE_TEXT(FMT), ## __VA_ARGS__));\
} while(0);
#define LOGW(FMT, ...) \
do {\
ACE_DEBUG((LM_WARNING, WARNING_PREFIX ACE_TEXT(FMT), ## __VA_ARGS__));\
} while(0);
#define LOGE(FMT, ...) \
do {\
ACE_DEBUG((LM_ERROR, ERROR_PREFIX ACE_TEXT(FMT), ## __VA_ARGS__));\
} while(0);
#define LSC_CRITICAL(FMT, ...) \
do {\
ACE_DEBUG((LM_CRITICAL, CRITICAL_PREFIX ACE_TEXT(FMT), ## __VA_ARGS__));\
} while(0);
#define LSC_ALERT(FMT, ...) \
do {\
ACE_DEBUG((LM_ALERT, ALERT_PREFIX ACE_TEXT(FMT), ## __VA_ARGS__));\
} while(0);
#define LSC_EMERGENCY(FMT, ...) \
do {\
ACE_DEBUG((LM_EMERGENCY, EMERGENCY_PREFIX ACE_TEXT(FMT), ## __VA_ARGS__));\
} while(0);
#define LSC_TRACE(FMT, ...) \
do {\
ACE_TRACE(FMT, ## __VA_ARGS__);\
} while(0);
#define LOG_HEX(FMT, ...) \
do {\
ACE_HEX_DUMP(FMT, ##__VA_ARGS__);\
} while(0);
#endif /* LSC_LOGGER_H_ */
#ifndef JSON_CONFIG_H_INCLUDED_HJ
# define JSON_CONFIG_H_INCLUDED_HJ
/// If defined, indicates that json library is embedded in CppTL library.
//# define JSON_IN_CPPTL 1
/// If defined, indicates that json may leverage CppTL library
//# define JSON_USE_CPPTL 1
/// If defined, indicates that cpptl vector based map should be used instead of std::map
/// as Value container.
//# define JSON_USE_CPPTL_SMALLMAP 1
/// If defined, indicates that Json specific container should be used
/// (hash table & simple deque container with customizable allocator).
/// THIS FEATURE IS STILL EXPERIMENTAL!
//# define JSON_VALUE_USE_INTERNAL_MAP 1
/// Force usage of standard new/malloc based allocator instead of memory pool based allocator.
/// The memory pools allocator used optimization (initializing Value and ValueInternalLink
/// as if it was a POD) that may cause some validation tool to report errors.
/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined.
//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1
/// If defined, indicates that Json use exception to report invalid type manipulation
/// instead of C assert macro.
# define JSON_USE_EXCEPTION 1
# ifdef JSON_IN_CPPTL
# include <cpptl/config.h>
# ifndef JSON_USE_CPPTL
# define JSON_USE_CPPTL 1
# endif
# endif
# ifdef JSON_IN_CPPTL
# define JSON_API CPPTL_API
# elif defined(JSON_DLL_BUILD)
# define JSON_API __declspec(dllexport)
# elif defined(JSON_DLL)
# define JSON_API __declspec(dllimport)
# else
# define JSON_API
# endif
#endif // JSON_CONFIG_H_INCLUDED
#ifndef CPPTL_JSON_FEATURES_H_INCLUDED_HJ
# define CPPTL_JSON_FEATURES_H_INCLUDED_HJ
# include "../include/json/forwards.h"
namespace EH{
namespace Json {
/** \brief Configuration passed to reader and writer.
* This configuration object can be used to force the Reader or Writer
* to behave in a standard conforming way.
*/
class JSON_API Features
{
public:
/** \brief A configuration that allows all features and assumes all strings are UTF-8.
* - C & C++ comments are allowed
* - Root object can be any JSON value
* - Assumes Value strings are encoded in UTF-8
*/
static Features all();
/** \brief A configuration that is strictly compatible with the JSON specification.
* - Comments are forbidden.
* - Root object must be either an array or an object value.
* - Assumes Value strings are encoded in UTF-8
*/
static Features strictMode();
/** \brief Initialize the configuration like JsonConfig::allFeatures;
*/
Features();
/// \c true if comments are allowed. Default: \c true.
bool allowComments_;
/// \c true if root must be either an array or an object value. Default: \c false.
bool strictRoot_;
};
} // namespace Json
} //namespace EH
#endif // CPPTL_JSON_FEATURES_H_INCLUDED
#ifndef JSON_FORWARDS_H_INCLUDED_HJ
# define JSON_FORWARDS_H_INCLUDED_HJ
# include "../include/json/config.h"
namespace EH {
namespace Json {
// writer.h
class FastWriter;
class StyledWriter;
// reader.h
class Reader;
// features.h
class Features;
// value.h
typedef int Int;
typedef unsigned int UInt;
class StaticString;
class Path;
class PathArgument;
class Value;
class ValueIteratorBase;
class ValueIterator;
class ValueConstIterator;
#ifdef JSON_VALUE_USE_INTERNAL_MAP
class ValueAllocator;
class ValueMapAllocator;
class ValueInternalLink;
class ValueInternalArray;
class ValueInternalMap;
#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
} // namespace Json
}
#endif // JSON_FORWARDS_H_INCLUDED
#ifndef JSON_JSON_H_INCLUDED_HJ
# define JSON_JSON_H_INCLUDED_HJ
# include "autolink.h"
# include "value.h"
# include "reader.h"
# include "writer.h"
# include "features.h"
#endif // JSON_JSON_H_INCLUDED
#ifndef JSONCPP_BATCHALLOCATOR_H_INCLUDED_HJ
# define JSONCPP_BATCHALLOCATOR_H_INCLUDED_HJ
# include <stdlib.h>
# include <assert.h>
# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
namespace EH{
namespace Json {
/* Fast memory allocator.
*
* This memory allocator allocates memory for a batch of object (specified by
* the page size, the number of object in each page).
*
* It does not allow the destruction of a single object. All the allocated objects
* can be destroyed at once. The memory can be either released or reused for future
* allocation.
*
* The in-place new operator must be used to construct the object using the pointer
* returned by allocate.
*/
template<typename AllocatedType
,const unsigned int objectPerAllocation>
class BatchAllocator
{
public:
typedef AllocatedType Type;
BatchAllocator( unsigned int objectsPerPage = 255 )
: freeHead_( 0 )
, objectsPerPage_( objectsPerPage )
{
// printf( "Size: %d => %s\n", sizeof(AllocatedType), typeid(AllocatedType).name() );
assert( sizeof(AllocatedType) * objectPerAllocation >= sizeof(AllocatedType *) ); // We must be able to store a slist in the object free space.
assert( objectsPerPage >= 16 );
batches_ = allocateBatch( 0 ); // allocated a dummy page
currentBatch_ = batches_;
}
~BatchAllocator()
{
for ( BatchInfo *batch = batches_; batch; )
{
BatchInfo *nextBatch = batch->next_;
free( batch );
batch = nextBatch;
}
}
/// allocate space for an array of objectPerAllocation object.
/// @warning it is the responsability of the caller to call objects constructors.
AllocatedType *allocate()
{
if ( freeHead_ ) // returns node from free list.
{
AllocatedType *object = freeHead_;
freeHead_ = *(AllocatedType **)object;
return object;
}
if ( currentBatch_->used_ == currentBatch_->end_ )
{
currentBatch_ = currentBatch_->next_;
while ( currentBatch_ && currentBatch_->used_ == currentBatch_->end_ )
currentBatch_ = currentBatch_->next_;
if ( !currentBatch_ ) // no free batch found, allocate a new one
{
currentBatch_ = allocateBatch( objectsPerPage_ );
currentBatch_->next_ = batches_; // insert at the head of the list
batches_ = currentBatch_;
}
}
AllocatedType *allocated = currentBatch_->used_;
currentBatch_->used_ += objectPerAllocation;
return allocated;
}
/// Release the object.
/// @warning it is the responsability of the caller to actually destruct the object.
void release( AllocatedType *object )
{
assert( object != 0 );
*(AllocatedType **)object = freeHead_;
freeHead_ = object;
}
private:
struct BatchInfo
{
BatchInfo *next_;
AllocatedType *used_;
AllocatedType *end_;
AllocatedType buffer_[objectPerAllocation];
};
// disabled copy constructor and assignement operator.
BatchAllocator( const BatchAllocator & );
void operator =( const BatchAllocator &);
static BatchInfo *allocateBatch( unsigned int objectsPerPage )
{
const unsigned int mallocSize = sizeof(BatchInfo) - sizeof(AllocatedType)* objectPerAllocation
+ sizeof(AllocatedType) * objectPerAllocation * objectsPerPage;
BatchInfo *batch = static_cast<BatchInfo*>( malloc( mallocSize ) );
batch->next_ = 0;
batch->used_ = batch->buffer_;
batch->end_ = batch->buffer_ + objectsPerPage;
return batch;
}
BatchInfo *batches_;
BatchInfo *currentBatch_;
/// Head of a single linked list within the allocated space of freeed object
AllocatedType *freeHead_;
unsigned int objectsPerPage_;
};
} // namespace Json
}
# endif // ifndef JSONCPP_DOC_INCLUDE_IMPLEMENTATION
#endif // JSONCPP_BATCHALLOCATOR_H_INCLUDED
#ifndef CPPTL_JSON_READER_H_INCLUDED_HJ
# define CPPTL_JSON_READER_H_INCLUDED_HJ
# include "../include/json/features.h"
# include "../include/json/value.h"
# include <deque>
# include <stack>
# include <string>
# include <iostream>
namespace EH{
namespace Json {
/** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a Value.
*
*/
class JSON_API Reader
{
public:
typedef char Char;
typedef const Char *Location;
/** \brief Constructs a Reader allowing all features
* for parsing.
*/
Reader();
/** \brief Constructs a Reader allowing the specified feature set
* for parsing.
*/
Reader( const Features &features );
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document.
* \param document UTF-8 encoded string containing the document to read.
* \param root [out] Contains the root value of the document if it was
* successfully parsed.
* \param collectComments \c true to collect comment and allow writing them back during
* serialization, \c false to discard comments.
* This parameter is ignored if Features::allowComments_
* is \c false.
* \return \c true if the document was successfully parsed, \c false if an error occurred.
*/
bool parse( const std::string &document,
Value &root,
bool collectComments = true );
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document.
* \param document UTF-8 encoded string containing the document to read.
* \param root [out] Contains the root value of the document if it was
* successfully parsed.
* \param collectComments \c true to collect comment and allow writing them back during
* serialization, \c false to discard comments.
* This parameter is ignored if Features::allowComments_
* is \c false.
* \return \c true if the document was successfully parsed, \c false if an error occurred.
*/
bool parse( const char *beginDoc, const char *endDoc,
Value &root,
bool collectComments = true );
/// \brief Parse from input stream.
/// \see Json::operator>>(std::istream&, Json::Value&).
bool parse( std::istream &is,
Value &root,
bool collectComments = true );
/** \brief Returns a user friendly string that list errors in the parsed document.
* \return Formatted error message with the list of errors with their location in
* the parsed document. An empty string is returned if no error occurred
* during parsing.
*/
std::string getFormatedErrorMessages() const;
private:
enum TokenType
{
tokenEndOfStream = 0,
tokenObjectBegin,
tokenObjectEnd,
tokenArrayBegin,
tokenArrayEnd,
tokenString,
tokenNumber,
tokenTrue,
tokenFalse,
tokenNull,
tokenArraySeparator,
tokenMemberSeparator,
tokenComment,
tokenError
};
class Token
{
public:
TokenType type_;
Location start_;
Location end_;
};
class ErrorInfo
{
public:
Token token_;
std::string message_;
Location extra_;
};
typedef std::deque<ErrorInfo> Errors;
bool expectToken( TokenType type, Token &token, const char *message );
bool readToken( Token &token );
void skipSpaces();
bool match( Location pattern,
int patternLength );
bool readComment();
bool readCStyleComment();
bool readCppStyleComment();
bool readString();
void readNumber();
bool readValue();
bool readObject( Token &token );
bool readArray( Token &token );
bool decodeNumber( Token &token );
bool decodeString( Token &token );
bool decodeString( Token &token, std::string &decoded );
bool decodeDouble( Token &token );
bool decodeUnicodeCodePoint( Token &token,
Location &current,
Location end,
unsigned int &unicode );
bool decodeUnicodeEscapeSequence( Token &token,
Location &current,
Location end,
unsigned int &unicode );
bool addError( const std::string &message,
Token &token,
Location extra = 0 );
bool recoverFromError( TokenType skipUntilToken );
bool addErrorAndRecover( const std::string &message,
Token &token,
TokenType skipUntilToken );
void skipUntilSpace();
Value &currentValue();
Char getNextChar();
void getLocationLineAndColumn( Location location,
int &line,
int &column ) const;
std::string getLocationLineAndColumn( Location location ) const;
void addComment( Location begin,
Location end,
CommentPlacement placement );
void skipCommentTokens( Token &token );
typedef std::stack<Value *> Nodes;
Nodes nodes_;
Errors errors_;
std::string document_;
Location begin_;
Location end_;
Location current_;
Location lastValueEnd_;
Value *lastValue_;
std::string commentsBefore_;
Features features_;
bool collectComments_;
};
/** \brief Read from 'sin' into 'root'.
Always keep comments from the input JSON.
This can be used to read a file into a particular sub-object.
For example:
\code
Json::Value root;
cin >> root["dir"]["file"];
cout << root;
\endcode
Result:
\verbatim
{
"dir": {
"file": {
// The input stream JSON would be nested here.
}
}
}
\endverbatim
\throw std::exception on parse error.
\see Json::operator<<()
*/
std::istream& operator>>( std::istream&, Value& );
} // namespace Json
}
#endif // CPPTL_JSON_READER_H_INCLUDED
This diff is collapsed.
#ifndef JSON_WRITER_H_INCLUDED_HJ
# define JSON_WRITER_H_INCLUDED_HJ
# include "../include/json/value.h"
# include <vector>
# include <string>
# include <iostream>
namespace EH {
namespace Json {
class Value;
/** \brief Abstract class for writers.
*/
class JSON_API Writer
{
public:
virtual ~Writer();
virtual std::string write( const Value &root ) = 0;
};
/** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format without formatting (not human friendly).
*
* The JSON document is written in a single line. It is not intended for 'human' consumption,
* but may be usefull to support feature such as RPC where bandwith is limited.
* \sa Reader, Value
*/
class JSON_API FastWriter : public Writer
{
public:
FastWriter();
virtual ~FastWriter(){}
void enableYAMLCompatibility();
public: // overridden from Writer
virtual std::string write( const Value &root );
private:
void writeValue( const Value &value );
std::string document_;
bool yamlCompatiblityEnabled_;
};
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a human friendly way.
*
* The rules for line break and indent are as follow:
* - Object value:
* - if empty then print {} without indent and line break
* - if not empty the print '{', line break & indent, print one value per line
* and then unindent and line break and print '}'.
* - Array value:
* - if empty then print [] without indent and line break
* - if the array contains no object value, empty array or some other value types,
* and all the values fit on one lines, then print the array on a single line.
* - otherwise, it the values do not fit on one line, or the array contains
* object or non empty array, then print one value per line.
*
* If the Value have comments then they are outputed according to their #CommentPlacement.
*
* \sa Reader, Value, Value::setComment()
*/
class JSON_API StyledWriter: public Writer
{
public:
StyledWriter();
virtual ~StyledWriter(){}
public: // overridden from Writer
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
* \param root Value to serialize.
* \return String containing the JSON document that represents the root value.
*/
virtual std::string write( const Value &root );
private:
void writeValue( const Value &value );
void writeArrayValue( const Value &value );
bool isMultineArray( const Value &value );
void pushValue( const std::string &value );
void writeIndent();
void writeWithIndent( const std::string &value );
void indent();
void unindent();
void writeCommentBeforeValue( const Value &root );
void writeCommentAfterValueOnSameLine( const Value &root );
bool hasCommentForValue( const Value &value );
static std::string normalizeEOL( const std::string &text );
typedef std::vector<std::string> ChildValues;
ChildValues childValues_;
std::string document_;
std::string indentString_;
int rightMargin_;
int indentSize_;
bool addChildValues_;
};
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a human friendly way,
to a stream rather than to a string.
*
* The rules for line break and indent are as follow:
* - Object value:
* - if empty then print {} without indent and line break
* - if not empty the print '{', line break & indent, print one value per line
* and then unindent and line break and print '}'.
* - Array value:
* - if empty then print [] without indent and line break
* - if the array contains no object value, empty array or some other value types,
* and all the values fit on one lines, then print the array on a single line.
* - otherwise, it the values do not fit on one line, or the array contains
* object or non empty array, then print one value per line.
*
* If the Value have comments then they are outputed according to their #CommentPlacement.
*
* \param indentation Each level will be indented by this amount extra.
* \sa Reader, Value, Value::setComment()
*/
class JSON_API StyledStreamWriter
{
public:
StyledStreamWriter( std::string indentation="\t" );
~StyledStreamWriter(){}
public:
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
* \param out Stream to write to. (Can be ostringstream, e.g.)
* \param root Value to serialize.
* \note There is no point in deriving from Writer, since write() should not return a value.
*/
void write( std::ostream &out, const Value &root );
private:
void writeValue( const Value &value );
void writeArrayValue( const Value &value );
bool isMultineArray( const Value &value );
void pushValue( const std::string &value );
void writeIndent();
void writeWithIndent( const std::string &value );
void indent();
void unindent();
void writeCommentBeforeValue( const Value &root );
void writeCommentAfterValueOnSameLine( const Value &root );
bool hasCommentForValue( const Value &value );
static std::string normalizeEOL( const std::string &text );
typedef std::vector<std::string> ChildValues;
ChildValues childValues_;
std::ostream* document_;
std::string indentString_;
int rightMargin_;
std::string indentation_;
bool addChildValues_;
};
std::string JSON_API valueToString( Int value );
std::string JSON_API valueToString( UInt value );
std::string JSON_API valueToString( double value );
std::string JSON_API valueToString( bool value );
std::string JSON_API valueToQuotedString( const char *value );
/// \brief Output using the StyledStreamWriter.
/// \see Json::operator>>()
std::ostream& operator<<( std::ostream&, const Value &root );
} // namespace Json
}
#endif // JSON_WRITER_H_INCLUDED
This diff is collapsed.
/*
* kk_handleDeviceInfo.h
*
* Created on: 2020年11月17日
* Author: hj
*/
#ifndef KK_HANDLEDEVICEINFO_H_
#define KK_HANDLEDEVICEINFO_H_
#include <sys/types.h>
#include "json/value.h"
#include <vector>
#include <set>
#include <string>
using namespace std;
//第1期接入设备 //临时定义 2020.10.14
#define ZeroFire1ChanChopinSwitch_PID "400100" //肖邦-一路灯控
#define ZeroFire2ChanChopinSwitch_PID "400200" //肖邦-二路灯控
#define ZeroFire3ChanChopinSwitch_PID "400300" //肖邦-三路灯控
//第2期接入设备 //临时定义 2020.11.18
#define Chopin1CurtainSwitch_PID "410100" //肖邦-一路窗帘
#define Chopin2CurtainSwitch_PID "410200" //肖邦-二路窗帘
#define ZeroFire2ChanModularSwitch_PID "400201" //两路智能开关模块Z3S(KONKE)
#define Chopin1ChanScenePanel_PID "420100" //肖邦-零火一路情景面板
#define WaterSensor_PID "440500" //邦德-水浸传感器
#define BodyMotionSensor_PID "440200" //KIT-人体传感器
#define DoorContact_PID "440100" //邦德-门磁传感器
#define SOSButton_PID "440400" //邦德-sos紧急呼叫
#define SoundLightAlarm_PID "440300" //邦德-声光报警器
#define DimmerLightPanel_PID "430100" //肖邦-调光面板
#define WaterHeating_PID "450300" //肖邦-水地暖
#define ElectricHeating_PID "450301" //肖邦-电地暖
#define FanCoilPanel_PID "450100" //肖邦-风机盘管面板
#define AirConditioner_PID "450101" //肖邦-中央空调线控器(大金)
#define ChopinFreshAir_PID "450200" //肖邦-新风控制面板
#define DAIKINCentralACgw_PID "450400" //中央空调网关
#define DAIKINCentralACindoor_PID "450401" //中央空调内机(等待调整)
class kk_handleDeviceInfo{
public: ////////先建立
class KKDevmapinfo {
public:
string dev_model_id;
string dev_type;
string sn;
string mac;
};
public:
class KKChannelDev {
public:
string operateId;
string nodeId;
string channel;
string devname;
string devroomid;
};
class HwSubDev {
public:
string dev_model_id; //产品ID ProdID
string dev_type; //产品类型
string operatetype; //设备的operate_type类型
string devTypeId;
string model;
string sn; //dev_id
string mac; //设备的mac
bool online;
map<string,KKChannelDev*> channelDevs;
};
class HwSwitch:public KKChannelDev { //只有开关的设备 开关灯控/插座/开关模块
public:
bool on;
};
class HwCurtain:public KKChannelDev { //窗帘面板
public:
string mode;
};
class HwScenePanel:public KKChannelDev{//情景面版 (肖邦情景面板-长供电)
public:
string num; //情景按钮编号
string leftBattery;//剩余电量百分比
};
class HwSensor:public KKChannelDev { //传感器设备 :邦德-门磁 KIT-人体 邦德-声光 邦德-水浸 邦德-紧急按钮
public:
string alarm; //触发与否
string leftbattery; //剩余电量百分比
string sound; //报警器音量
string power_style; //供电方式。0:市电,1:电池;
};
class HwDimmerLightPanel:public KKChannelDev { //肖邦-调光灯面板
public:
bool on;
string brightness;
string time;
};
class HwWaterElectricHeating:public KKChannelDev { //肖邦-水地暖 肖邦-电地暖
public:
bool on;
string mode;
bool childLockSwitch;
string current; //当前温度
string target; //目标温度 (20.0—30.0 +_0.5)
};
class HwChopinFreshAir:public KKChannelDev { //肖邦-新风控制面板
public:
bool on;
int mode;
string fan;
bool childLockSwitch;
string current; //当前温度
bool lightSwitch;
int downtime;
int totalTime;
int leftTime;
bool reset;
};
class HwConditionerPanel:public KKChannelDev { //肖邦-风机盘管面板 //肖邦-中央空调线控器(大金)
public:
bool on;
string mode;
string fan;
bool childLockSwitch; //童锁开关
string current; //当前温度
string target; //目标温度
int downtime;
bool enable;
};
class HwCentralAcgw:public KKChannelDev {//中央空调网关(四期调整)
public:
int num; //内机数目
};
class HwCentralAcindoor:public KKChannelDev {//中央空调内机(四期调整)
public:
int indoormacs;//内机的模拟mac
bool on;
int mode;
string fan;
int current; //当前温度
int target; //目标温度
};
public:
static kk_handleDeviceInfo* GetInstance();
//小K组设备,自动补充设备对应的prodID。
EH::Json::Value XiaoK_Zu_Wang(string kkDevProductId);
//更改设备状态信息
void handleDeviceStatusChanged(map<string,kk_handleDeviceInfo::HwSubDev*>&hwSubDevs,map<string,string>&nodeId2channelMap,
string nodeId,string opcode,EH::Json::Value arg,string pushTopic,string gw_id);
//空调内机更改设备状态信息
void handleCentralACStatusPush(map<string,kk_handleDeviceInfo::HwSubDev*>&hwSubDevs,map<string,string>&indoorunitsId2AddrMap,string pushTopic,
string nodeId,EH::Json::Value arg,string opcode);
//允许加入的设备类型
bool isValidJoinDeviceType(string kkDevOperateId,string kkDevProductId,string mac);
//获取全部设备信息
int onGetDevService(map<string,kk_handleDeviceInfo::HwSubDev*>&hwSubDevs,map<string,vector<string> >& controllerModel,string pushTopic,string gw_id);
//控制设备
int onSetDevService(map<string,kk_handleDeviceInfo::HwSubDev*>&hwSubDevs,string sn,string channel,string svcId,EH::Json::Value cmd);
//建立通道设备模型
kk_handleDeviceInfo::KKChannelDev* buildChannelDevice(string operateId,string nodeId,string channel,EH::Json::Value status,string devroomid,string devname);
//添加到房间里
void addCCuDevicesToRoom(map<string,kk_handleDeviceInfo::HwSubDev*>::iterator&it,map<string,string> NodeId2gwId);
EH::Json::Value centralACStatusToSet(string fanSpeed,bool on,int runModel,int settingTemperature);
private:
kk_handleDeviceInfo();
private:
static kk_handleDeviceInfo* ms_pInstance;
};
#endif
This diff is collapsed.
/*
* EH_DEBUG.h
*
*/
#ifndef EH_DEBUG_H_
#define EH_DEBUG_H_
#include <stdio.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(__NR_gettid)
#define EH_DEBUG(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_INFO(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_NOTICE(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_WARNING(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_ERROR(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_CRITICAL(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_ALERT(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_EMERGENCY(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
#define EH_TRACE(fmt, ...) syslog(LOG_DEBUG,"%ld %s(%d):" fmt ,gettid(),__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_DEBUG(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_INFO(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_NOTICE(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_WARNING(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_ERROR(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_CRITICAL(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_ALERT(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_EMERGENCY(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
//#define EH_TRACE(fmt, ...) syslog(LOG_DEBUG,"%s[%d]:"fmt,__FILE__,__LINE__,##__VA_ARGS__)
#endif /* EH_DEBUG_H_ */
/**
* EH_Exception.cpp
*
* Copyright by AirDream Co., Ltd. 2010-2011 All right reserved
*
* Description:
* Created on:2011-8-23
* Modified on:2011-8-23
*
*/
#include <EH_Exception.h>
EH_Exception::EH_Exception(const char* error_msg,
const char* file_name,
unsigned int line_no,
const char* function_name,
int error_code) :
m_strErrorMsg(error_msg),
m_strFileName(file_name),
m_strFunctionName(function_name),
m_uiLineNo(line_no),
m_nErrorCode(error_code) {
}
EH_Exception::~EH_Exception() throw () {
}
inline const char* EH_Exception::GetErrorMsg() const {
return m_strErrorMsg.c_str();
}
inline unsigned int EH_Exception::GetLineNo() const {
return m_uiLineNo;
}
inline const char* EH_Exception::GetFileName() const {
return m_strFileName.c_str();
}
inline int EH_Exception::GetErrorCode() const {
return m_nErrorCode;
}
inline const char* EH_Exception::GetFunctionName() const {
return m_strFunctionName.c_str();
}
ostream& operator<<(ostream& arOstream, const EH_Exception& arException) {
return arException.dump(arOstream);
}
ostream& EH_Exception::dump(ostream& arOstream) const {
arOstream << "Exception";
if (*GetErrorMsg() != '\0') {
arOstream << ": " << what();
}
arOstream << " (" << GetFunctionName() << "()," << GetFileName() << ":"
<< GetLineNo() << ")" << endl;
return arOstream;
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
json_reader.o: ../src/lib/jsonlib/json_reader.cpp \
../src/lib/jsonlib/../../include/json/reader.h \
../src/include/../include/json/features.h \
../src/include/../include/json/forwards.h \
../src/include/../include/json/config.h \
../src/include/../include/json/value.h \
../src/lib/jsonlib/../../include/json/value.h
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment