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_ */
/*
* MQ_CCU_Adapter.cpp
*
* Created on: Dec 6, 2018
* Author: sds
*/
#include "MQ_CCU_Adapter.h"
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#include <stdio.h>
#include <fstream>
#include <string>
#include "json/writer.h"
#include "json/reader.h"
#include "json/value.h"
#include "ace/Reactor.h"
#include "KK_Util.h"
#include "EH_Client.h"
#include "MQ_CCU_Config.h"
#include "kk_connect.h"
#include "LSC_Logger.h"
#include "EH_ToolKit.h"
#include "EH_Exception.h"
#include "KK_CcuConfig.h"
#define CCU_REQ_TIMEOUT 3
//单例模式
MQ_CCU_Adapter* MQ_CCU_Adapter::ms_pInstance = NULL;
MQ_CCU_Adapter* MQ_CCU_Adapter::GetInstance() {
if (ms_pInstance == NULL) {
ms_pInstance = new MQ_CCU_Adapter();
}
return ms_pInstance;
}
MQ_CCU_Adapter::MQ_CCU_Adapter():cond(mtx) {
// int reqSize = MQ_CCU_Config::GetInstance()->getReqCacheSize(); //获取请求缓存大小
// m_pReqInfo = new REQ_MAP(reqSize,NULL);
// m_pReqTimeoutInfo = new REQTIMEOUT_MAP(reqSize,NULL);
// timoutTimerArgs = new TIMOUTTIMERARGS_MAP(reqSize,NULL);
ccuStatus = "UNINIT";
mqttSdk = KK_MQTTSDK::GetInstance(); //KK_MQTTSDK接口初始化
mqttSdk->setSdkCallbackHandler(this); //设置Sdk回调处理程序
this->msg_queue()->low_water_mark(600*1024);
this->msg_queue()->high_water_mark(600*1024);
}
int MQ_CCU_Adapter::svc(){
for (ACE_Message_Block* msg_blk; getq(msg_blk) != -1;) {
LOGI("KK_IotHandler rec a msg.\n");
try {
EH::Json::Reader reader;
EH::Json::Value json_root;
string json = string(msg_blk->rd_ptr());
if (!reader.parse(json, json_root) || !json_root.isObject()) {
LOGW("Parse json error. json is:%s\n", json.c_str());
msg_blk->release();
continue;
}
string opcode = json_root["opcode"].asString();
string nodeid = json_root["nodeid"].asString();
string arg = json_root["arg"].asString();
string requester = json_root["requester"].asString();
unsigned long nowReqTime = getSystemTimeInMs();
if( (nowReqTime - lastCcuReqTime) > 100){
client->sendRequest(nodeid,opcode,arg,requester);
lastCcuReqTime = nowReqTime;
}else{
LOGW("send req to ccu too fast,wait 100ms.\n");
usleep(200*1000);
client->sendRequest(nodeid,opcode,arg,requester);
lastCcuReqTime = getSystemTimeInMs();
}
} catch (exception &e) {
LOGW("%s.\n", e.what());
}
msg_blk->release();
}
return 0;
}
void MQ_CCU_Adapter::sendReqToCcu(string opcode,string nodeid,string arg,string requester){
LOGD("sendReqToCcu opcode:%s,nodeid:%s,arg:%s,requester:%s.\n",opcode.c_str(),nodeid.c_str(),arg.c_str(),requester.c_str());
ACE_Time_Value timeout(0, 300 * 1000);
EH::Json::Value json;
json["opcode"] = opcode;
json["nodeid"] = nodeid;
json["arg"] = arg;
json["requester"] = requester;
string wholeMsg = json.toStyledString();
ACE_Message_Block* blk = new ACE_Message_Block(wholeMsg.length() + 1);
blk->copy(wholeMsg.c_str());
int ret = Put(blk,&timeout);
if (ret <= 0) {
printf("Send msg to IotHandler failed.msg is %s\n",wholeMsg.c_str());
blk->release();
}
}
int MQ_CCU_Adapter::Put(ACE_Message_Block* mblk, ACE_Time_Value* relativeTimeout) {
ACE_Time_Value* absTimeout = NULL;
if (relativeTimeout != NULL) {
absTimeout = new ACE_Time_Value(ACE_OS::gettimeofday() + *relativeTimeout);
}
int ret = putq(mblk, absTimeout);
if (absTimeout != NULL) {
delete absTimeout;
}
return ret;
}
int MQ_CCU_Adapter::open() {
int ret = activate(THR_DETACHED, 1);
if(ret == -1){
LOGW("Init KK_IotHandler failed.\n");
}
ccuId = MQ_CCU_Config::GetInstance()->getCcuId(); //获取主机ID
gw_id = EH_ToolKit::GetMacNoSpace();
if(ccuId == ""){
LOGE("cannot find ccuid,is a konke ccu machine ???");
return -1;
}
LOGI("start mqtt for ccu:%s \n",ccuId.c_str());
//房间信息
string roomid = KK_HwDevManager::GetInstance()->GetRoomId();
roomidok = KK_HwDevManager::GetInstance()->loadroomid(onlyroomid); //是否创建了房间标志。1 创建 0 未创建
LOGI("roomid ok: %d roomid %s ",roomidok,roomid.c_str());
if(roomidok == -1){
SaveRoomEnable = true;
LOGW("未创建房间,等待创建.\n");
}else{
LOGI("Roma特定房间不可删 roomid %s ",roomid.c_str());
}
//客户端初始化
client = new EH_Client();
client->init("", "", this, false);
//连接Roma平台,绑定就进行启动
oninitmqttsdk();
return 0;
}
//---ccu communication 主机通信
//客户端状态更改时
void MQ_CCU_Adapter::onClientStatusChanged(EH_Client::ClientStatus currentStatus) {
LOGI("ccu client status:%s \n",EH_Client::getClientStatusStr(currentStatus).c_str());
if (currentStatus == EH_Client::WORKING) {
handleNewDevices = true;
ccuSyncOK = true;
string arg = "{\"conditions\":[{\"condition_type\":\"dev_list\",\"condition_arg\":[]}]}";
client->sendRequest("*", "GET_ZIGBEE_DEVS_HW_INFO", arg, "HJ_Config");
if(roomidok == -1){
LOGW("未创建房间,开始创建.\n");
sleep(1);
addCCuroom();
}
}else{
ccuSyncOK = false;
handleNewDevices = false;
}
}
//接收处理中控发来的消息
void MQ_CCU_Adapter::onRecvMsg(string nodeId, string opcode, EH::Json::Value arg, string status){ //接受中控向上推送的报文。
try {
LOGD("Konkexinghai recv MQ_CCU_AdapterMsg:\n nodeId:%s\n status:%s\n opcode:%s \n arg:%s.\n",nodeId.c_str(),status.c_str(),opcode.c_str(),EH_ToolKit::JsonToString(arg).c_str());
if (opcode == "SYNC_INFO") {
// if(!ccuSyncOK){
handleSyncInfo(arg,opcode);
ccuSyncOK = false;
// }
}if (opcode == "SYNC_INFO_PUSH" ) {
handleSyncInfo(arg,opcode);
} else if (opcode == "NEW_DEVICES") {
newDevices = arg["new_devices"];
newCentralAcDevices = arg["new_central_ac_indoorunits"];
newCentralAcGwsDevices = arg["new_central_ac_gws"];
if(handleNewDevices){
handleNewDevice(newDevices, newCentralAcDevices, newCentralAcGwsDevices);
handleNewDevices = false;
LOGI("sync ccu finish,upload %d devices status to hw cloud.\n",hwSubDevs.size());
}
}else if (opcode == "GET_CCU_INFO") {
handlegwNodeId(arg);
} else if (opcode == "NEW_DEVICES_NOTIFY") {
handleNewDevice(newDevices, newCentralAcDevices, newCentralAcGwsDevices);
newDevices = "";
newCentralAcDevices = "";
newCentralAcGwsDevices = "";
} else if (opcode == "ZIGBEE_DEV_JOIN_NOTIFY"){ //Zigbee 设备入网推送
handle_Dev_Join_Notify(arg);
} else if (opcode == "GET_ZIGBEE_DEVS_HW_INFO"){
if(ccuSyncOK){
loadAllSubDev(arg);
client->sendRequest("*", "SYNC_INFO", "*", "HJ_Config");
}else{
handleGetDevsHardwareInfo(arg);
}
} else if (opcode == "ZIGBEE_DEV_HW_INFO_PUSH"){
handleDevOnlinePush(arg);
} else if (opcode == "SWITCH" || opcode == "SETUP_NODE"||opcode == "SHORTCUT_PANEL_ACTIVE"
||opcode == "FRESH_AIR_RUN_MODEL"||opcode == "FRESH_AIR_SWITCH"||opcode == "FRESH_AIR_SPEED_SET"||opcode == "FRESH_AIR_SET_FILTER_SCREEN_TIME"
||opcode == "FRESH_AIR_CONFIG_ARGS_PUSH"||opcode == "FRESH_AIR_GET_CONFIG_ARGS"||opcode == "CHOPIN_FRESH_AIR_STATUS"||opcode == "FRESH_AIR_SET_LOCK_STATUS"
||opcode == "SENSOR_BOOL"||opcode == "POWER_NOTIFY"||opcode == "SENSOR_BOOL_STATUS"||opcode == "SOS_STATUS"||opcode == "ZIGBEE_ALERTOR_STATUS"
||opcode == "ADJUST_LUMINANCE" ||opcode == "GET_DIMMABLE_LIGHT_CONFIG"||opcode == "SET_DIMMABLE_LIGHT_CONFIG"||opcode == "DIMMABLE_LIGHT_STATUS" //调光灯
||opcode == "SET_WORK_TEMPERATURE"||opcode == "FAN_COIL_CONFIG_ARGS_PUSH"
||opcode == "SET_WORK_MODEL"||opcode == "FLOOR_HEATING_GET_CONFIG_ARGS"||opcode == "FLOOR_HEATING_SET_LOCK_STATUS" ||opcode == "FLOOR_HEATING_DEV_STATUS"
||opcode == "FAN_COIL_SET_RUN_MODEL"||opcode == "FAN_COIL_SET_FUN_SPEED"||opcode == "FAN_COIL_SET_LOCK_STATUS"||opcode == "FAN_COIL_GET_CONFIG_ARGS"
||opcode == "FAN_COIL_SET_DELAY_SWITCH_TASK"||opcode == "FAN_COIL_SET_TEMPERATURE"||opcode == "FAN_COIL_STATUS"
) { //opcode == "NIGHT_MODE" 小夜灯
//更改设备状态信息
kk_handleDeviceInfo::GetInstance()->handleDeviceStatusChanged(hwSubDevs,nodeId2channelMap,nodeId,opcode,arg,pushTopic,gw_id);
} else if(opcode == "ADD_INSTALL_CODE" && status == "success"){
sleep(1);
if(gw_NodeId == nodeId){
client->sendRequest(gw_NodeId, "OPEN_NET_CHANNEL", "*", "HJ_Server");
}else{
LOGW("未有Z3网关,主机不支持使用.\n");
}
}else if (opcode == "ADD_ROOM") { //添加特定房间
saveCCuroom(arg);
} else if (opcode == "DEL_DEV") { //小K删除设备同步到华为,给其推送离线。DEL_DEV
loadDelete(arg);
} else if (opcode == "OPEN_NET_CHANNEL"&& status == "success") { //打开组网
KKdiscover =true;//
LOGD("OPEN_NET_CHANNEL discoveryEnable:%d,KKdiscover:%d\n",discoveryEnable,this->KKdiscover);
} else if (opcode == "CLOSE_NET_CHANNEL"&& status == "success") { //关闭组网
KKdiscover =false;//
} else if (opcode == "CENTRAL_AC_INDOOR_UNIT_STATUS"||opcode == "CENTRAL_AC_INDOOR_UNIT_SETTING") { //中央空调内机
kk_handleDeviceInfo::GetInstance()->handleCentralACStatusPush(hwSubDevs,indoorunitsId2AddrMap,pushTopic,nodeId, arg,opcode);
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
//接收云端下发的消息
void MQ_CCU_Adapter::onCloudMsgRecv(string payload,string topicName){
try{
vector<string> chanMac;
Split(topicName,"/",chanMac);
string Sub_Topic = chanMac[3];
if(Sub_Topic == "publishstate"){ //获取设备信息列表
LOGI("onCloudMsgRecv is:{} topicName: %s\n",topicName.c_str());
kk_handleDeviceInfo::GetInstance()->onGetDevService(hwSubDevs,controllerModel,pushTopic,gw_id);
}else if(Sub_Topic == "commands"){ //下发控制指令
LOGI("onCloudMsgRecv is: %s topicName: %s\n",payload.c_str(),topicName.c_str());
EH::Json::Value jsonObject;
EH::Json::Reader reader;
if (!reader.parse(payload, jsonObject) || !jsonObject.isObject()) {
LOGW("Message format is wrong.primary msg is: %s\n",payload.c_str());
return;
}
//判别控制指令
if(jsonObject["method"] =="prepare_join_gw"){ //添加设备的界面下准备命令
on_Query_GateWay_Infomation();
}else if(jsonObject["method"] =="enable_join_gw"){ //打开网关允许加网模式
onDeviceRequestJoin(true);
}else if(jsonObject["method"] =="disable_join_gw"){ //关闭网关允许加网模式
onDeviceRequestJoin(false);
}else if(jsonObject["method"] =="delete_device"){ //删除子设备
string sn = jsonObject["dev_id"].asString();
onDeviceRequestDelete(sn);
}else if(jsonObject["method"] =="unbind_gateway"){ //解绑网关-删除所有子设备
string device_name = jsonObject["device_name"].asString();
string client_id = jsonObject["client_id"].asString();
string method = jsonObject["method"].asString();
on_unbind_gateway(device_name,client_id,method);
}else if(jsonObject["method"] =="unbind_gateway.keep"){ //解绑网关-不删除所有子设备
string device_name = jsonObject["device_name"].asString();
string client_id = jsonObject["client_id"].asString();
string method = jsonObject["method"].asString();
on_unbind_gateway(device_name,client_id,method);
}else if(jsonObject["method"] =="control_device"){ //控制设备状态
string sn = jsonObject["dev_id"].asString();
string channel = IntToString(jsonObject["dev_ep_id"].asInt());
string svcid = IntToString(jsonObject["cmd_type"].asInt());
EH::Json::Value cmd = jsonObject["cmd"];
kk_handleDeviceInfo::GetInstance()->onSetDevService(hwSubDevs,sn,channel,svcid,cmd); //下发控制命令
}else{
LOGW("recv unknown payload:%s.\n",jsonObject["method"].asString().c_str());
}
}else{
LOGW("recv unknown Topic:%s.\n",Sub_Topic.c_str());
}
} catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
//下发查询网关信息
int MQ_CCU_Adapter::on_Query_GateWay_Infomation(){
client->sendRequest("*", "GET_CCU_INFO", "*", "HJ_Server");
}
//发送设备控制命令
int MQ_CCU_Adapter::send_Control_Info(string wholeMsg){
ACE_Time_Value timeout(0, 300 * 1000);
ACE_Message_Block* blk = new ACE_Message_Block(wholeMsg.length() + 1);
blk->copy(wholeMsg.c_str());
int ret = Put(blk,&timeout);
if (ret <= 0) {
LOGW("Send msg to IotHandler failed.msg is %s\n",wholeMsg.c_str());
blk->release();
return -1;
}
return 0;
}
int MQ_CCU_Adapter::addCCuroom(){
EH::Json::Value roomarg;
roomarg["name"] = "xlink特定房间不可删";
roomarg["room_icon"] = "a_0";
roomarg["floor_id"] = "3";
roomarg["room_pos"] = "10";
string arg = EH_ToolKit::JsonToString(roomarg);
client->sendRequest("*","ADD_ROOM",arg,"HJ_Config");
return 0;
}
int MQ_CCU_Adapter::saveCCuroom(EH::Json::Value arg){
LOGD("prepare add room\n");
string ccuroomid = IntToString(arg.asInt());
if(SaveRoomEnable){
KK_HwDevManager::KKRoomId roominfo;
roominfo.roonid = ccuroomid;
roominfo.name = "xlink特定房间不可删";
onlyroomid[ccuroomid] = roominfo;
LOGD("prepare add room \n");
KK_HwDevManager::GetInstance()->saveroomid(onlyroomid);
SaveRoomEnable = false;
roomidok = 1;
}
return 0;
}
//检测特定房间,是否存在与否。
void MQ_CCU_Adapter::Specific_rooms(EH::Json::Value rooms) {
int roomCount = rooms.size();
map<string,string> roomMap;
for (int i = 0; i < roomCount; i++) {
EH::Json::Value room = rooms[i];
string roomID = room["id"].asString();
roomMap[roomID] = roomID;
}
string roomid = KK_HwDevManager::GetInstance()->GetRoomId();//特定的房间
map<string,string>::iterator it = roomMap.find(roomid);
if(it == roomMap.end()){
LOGW("Roma特定的房间被删除,开始重新创建,小K重新进入才会显示.\n");
onlyroomid.erase(roomid);
SaveRoomEnable = true;
addCCuroom();
}
}
int MQ_CCU_Adapter::onDeviceRequestJoin(bool enableJoinSubdev){
LOGD("onDeviceRequestJoin enableJoinSubdev:%s\n",enableJoinSubdev?"true":"false");
this->discoveryEnable = enableJoinSubdev;
if(discoveryEnable){
if(gw_NodeId!= "-1"){
// string arg = "{\"type\":1,\"mac\":\""+mac+"\",\"code\":\""+code+"\"}";
// client->sendRequest(gw_NodeId, "ADD_INSTALL_CODE", arg, "HJ_Server"); //Pin码组网
client->sendRequest(gw_NodeId, "OPEN_NET_CHANNEL", "*", "HJ_Server");
}else{
LOGW("未有Z3网关,主机不支持使用.\n");
}
}else{
if(gw_NodeId!= "-1"){
client->sendRequest(gw_NodeId, "CLOSE_NET_CHANNEL", "*", "HJ_Server");
}else{
LOGW("未有Z3网关,主机不支持使用.\n");
}
}
return 0;
}
void MQ_CCU_Adapter::handleGetDevsHardwareInfo(EH::Json::Value arg){
if(arg.isArray()){
for(int i = 0;i < arg.size();i++){
handleDevOnlinePush(arg[i]);
}
}
}
void MQ_CCU_Adapter::handleDevOnlinePush(EH::Json::Value arg){
try {
string respTopic_1 = pushTopic +"/deviceonline";//子设备在线
string respTopic_2 = pushTopic +"/deviceoffline";//子设备离线
string sn = Replace(arg["mac"].asString(),":","");
map<string, kk_handleDeviceInfo::HwSubDev*>::iterator subDevIt = hwSubDevs.find(sn);
if(subDevIt != hwSubDevs.end()){
int onlinestatus = arg["online_status"].asInt();
int product_id = arg["product_id"].asInt();
if(onlinestatus == 2){
EH::Json::Value payload;
payload["dev_id"] = sn; //请求发起者
payload["dev_type"] = subDevIt->second->dev_type;
payload["gw_id"] = gw_id;
sendtoRoma(payload,respTopic_2); //推送新设备到Roma //在线状态的推送 ,待更改 2020.10.15.9
subDevIt->second->online = false;
}else{
EH::Json::Value payload;
payload["dev_id"] = sn; //请求发起者
payload["dev_type"] = subDevIt->second->dev_type;
payload["gw_id"] = gw_id;
sendtoRoma(payload,respTopic_1); //推送新设备到Roma
subDevIt->second->online = true;
}
LOGI("hw subdev:%s product_id:%d update online_status:%d.\n",sn.c_str(),product_id, onlinestatus);
}else{
LOGW("not found hw subdev:%s for update online_status.\n",sn.c_str());
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
void MQ_CCU_Adapter::handleSyncInfo(EH::Json::Value arg,string opcode) {
try {
LOGD("handleSyncInfo:\n opcode:%s \n arg:%s.\n",opcode.c_str(),EH_ToolKit::JsonToString(arg).c_str());
EH::Json::Value deviceStatusArray = arg["device_status"];//设备的状态
map<string,EH::Json::Value> nodeIdStatusMap;
for (int i = 0;i < deviceStatusArray.size();i++){
EH::Json::Value devStatus = deviceStatusArray[i];
string opcode = devStatus["opcode"].asString();
string nodeid = EH_ToolKit::IntToString(devStatus["nodeid"].asInt());
nodeIdStatusMap[nodeid] = devStatus["arg"];
}
// 异常处理:对房间信息进行读取,判断特定房间是否还在,否 ,进入异常处理。
if(opcode == "SYNC_INFO_PUSH"){
EH::Json::Value rooms = arg["rooms"];
Specific_rooms(rooms);
}
//添加到房间的子设备
EH::Json::Value devices = arg["devices"];
int devCount = devices.size();
for (int i = 0; i < devCount; i++) {
EH::Json::Value device = devices[i];
string operateType = device["operate_type"].asString();
string nodeid = device["nodeid"].asString();
string mac = device["mac"].asString();
string devsn = Replace(mac,":","");
string channel = device["channel"].asString();
string devroomid = device["room_id"].asString(); //房间号
string devname = device["name"].asString(); //设备的名称
nodeId2channelMap[nodeid] = mac+"_"+channel;
EH::Json::Value status;
map<string,EH::Json::Value>::iterator it = nodeIdStatusMap.find(nodeid);
if(it!=nodeIdStatusMap.end()){
status = it->second;
}
map<string,kk_handleDeviceInfo::KKDevmapinfo>::iterator devIt = hwBindDevMap.find(mac);
if(devIt!=hwBindDevMap.end()){
kk_handleDeviceInfo::KKDevmapinfo tripInfo = devIt->second;
handleCcuDeviceToHwSubDev(operateType,nodeid,mac,channel,devsn,status,devroomid,devname);
}else{
LOGD("ccu dev:%s not found bind info in lcoal cache.delete fron ccu later. \n",mac.c_str());
}
}
//添加到房间的中央空调网关信息同步
EH::Json::Value CentralAcGwsDevices = arg["central_ac_gws"];
SYNC_handle_AcGw_Devices(CentralAcGwsDevices);
//添加到房间的中央空调内机信息同步
EH::Json::Value CentralAcindoorunits = arg["central_ac_indoorunits"];
int indoorunitsCount = CentralAcindoorunits.size();
if(indoorunitsCount > 0){
int infocome = 1 ;
string devroomid = "1" ;//临时默认
string devname = "内机";
handleACindoor(devroomid,devname,indoorunitsCount,CentralAcindoorunits,infocome);
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
//处理新设备
void MQ_CCU_Adapter::handleNewDevice(EH::Json::Value devices, EH::Json::Value centralACdevices, EH::Json::Value newCentralAcGwsDevices) {
try {
LOGD("handleNewDevice:\n devices:%s\n centralACdevices:%s\n newCentralAcGwsDevices:%s\n",EH_ToolKit::JsonToString(devices).c_str(),
EH_ToolKit::JsonToString(centralACdevices).c_str(),EH_ToolKit::JsonToString(newCentralAcGwsDevices).c_str());
int devCount = devices.size();
int indoorunitsdevCount = centralACdevices.size();//中央空调内机数目
string devroomid = "-1";
string devname = "新dev";
map<string,kk_handleDeviceInfo::HwSubDev*> toAddSubDevs;
for (int i = 0; i < newCentralAcGwsDevices.size(); i++) { //有多少个空调网关,要放在处理新设备的前面。
EH::Json::Value gw = newCentralAcGwsDevices[i];
string gwId = gw["id"].asString();
string gwNodeId = gw["bind_central_ac_gw_node_id"].asString();
gwId2NodeId[gwId] = gwNodeId;
NodeId2gwId[gwNodeId] = gwId;
LOGD("add ccu system gwId:%s, gwNodeId:%s \n",gwId.c_str() ,gwNodeId.c_str());
}
for (int i = 0; i < devCount; i++) {
EH::Json::Value device = devices[i];
string operateType = device["operate_type"].asString();
string nodeid = device["nodeid"].asString();
string mac = device["mac"].asString();
string devsn = Replace(mac,":","");
string channel = device["channel"].asString();
string Joinproductid;
nodeId2channelMap[nodeid] = mac+"_"+channel;
if(operateType == "12001"){ //中央空调网关
operate2NodeId[nodeid] = operateType;
}
EH::Json::Value status = device["status"]["arg"];
if(!ccuDeleteMacs.empty() && ccuDeleteMacs.find(mac)!=ccuDeleteMacs.end()){
continue;
}
map<string,kk_handleDeviceInfo::KKDevmapinfo>::iterator it = hwBindDevMap.find(mac);
if(it!=hwBindDevMap.end()){
kk_handleDeviceInfo::KKDevmapinfo tripInfo = it->second;
LOGD("mac:%s in hwBindDevMap \n",mac.c_str());
handleCcuDeviceToHwSubDev(operateType,nodeid,mac,channel,devsn,status,devroomid,devname);
}else{
map<string,string>::iterator Join_productid = Join_productid_Map.find(mac); //未添加过的,进行添加进入
if(Join_productid != Join_productid_Map.end()){
Joinproductid = Join_productid->second;
}else{
Joinproductid = "当前未接入设备";
}
if(KKdiscover && kk_handleDeviceInfo::GetInstance()->isValidJoinDeviceType(operateType,Joinproductid,mac)){ //KKdiscover 小K或华为点开组网可以进入组网状态
if(toAddSubDevs.find(mac) != toAddSubDevs.end()){
LOGD("mac: %s in toAddSubDevs \n",mac.c_str());
kk_handleDeviceInfo::KKChannelDev* chanDev = kk_handleDeviceInfo::GetInstance()->buildChannelDevice(operateType,nodeid,channel,status,devroomid,devname);
kk_handleDeviceInfo::HwSubDev* dev= toAddSubDevs[mac];
if(chanDev!=NULL){
dev->channelDevs[channel] = chanDev;
LOGD("add dev:%s, channel:%s to subdev for add to huawei cloud later.\n",mac.c_str(),channel.c_str());
}
}else{
EH::Json::Value devProductinfo = kk_handleDeviceInfo::GetInstance()->XiaoK_Zu_Wang(Joinproductid);
kk_handleDeviceInfo::HwSubDev* dev = new kk_handleDeviceInfo::HwSubDev();
dev->dev_model_id = devProductinfo["dev_model_id"].asString();
dev->dev_type = devProductinfo["dev_type"].asString();
dev->mac = mac;
dev->operatetype = operateType;
dev->sn = devsn;
kk_handleDeviceInfo::KKChannelDev* chanDev = kk_handleDeviceInfo::GetInstance()->buildChannelDevice(operateType,nodeid,channel,status,devroomid,devname);
map<string,kk_handleDeviceInfo::KKChannelDev*> channelDevs;
if(chanDev!=NULL){
channelDevs[channel] = chanDev;
}
dev->channelDevs = channelDevs;
toAddSubDevs[mac] = dev;
LOGD("found JoinDevProductkey for dev:%s,operateid:%s,channel:%s,. \n",mac.c_str(),operateType.c_str(),channel.c_str());
}
}else{
ccuDeleteMacs.insert(mac);
LOGW("ccu dev:%s not valid to add.\n",mac.c_str());
}
}
}
addCCuDevicesToCloud(toAddSubDevs);
LOGD("after handle NEW_DEVICES,total hw dev count is:%d \n",hwSubDevs.size());
//deleteCCuDevices(ccuDeleteMacs); //调试
ccuDeleteMacs.clear();
if(indoorunitsdevCount > 0){//有内机的话,单独进行处理
int infocome = 0 ;//infocome = 0为新设备列表里的
handleACindoor(devroomid,devname,indoorunitsdevCount,centralACdevices,infocome);
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
void MQ_CCU_Adapter::handleACindoor(string devroomid,string devname,int indoorunitsdevCount,EH::Json::Value centralACdevices,int infocome){
try {
LOGD("开始处理空调内机\n");
int error;
map<string,kk_handleDeviceInfo::HwSubDev*> toAddSubDevs;//需要添加到华为的设备信息。
controllerModel.clear();
for (int i = 0; i < indoorunitsdevCount; i++) { ////中央空调内机数目
string channel= "1";
EH::Json::Value centralAC = centralACdevices[i];
string indoorunitId = centralAC["id"].asString();
string indoorunitAddr = centralAC["indooruint_addr"].asString();
string centralACGwId;//中央空调网关设备 ID,注:非 zigbee 设备 ID 体系
EH::Json::Value indoorunitStatus;//内机当前的状态
if(infocome == 0){ //infocome = 0为新设备列表里的,=1表示为添加到房间里了。
centralACGwId = centralAC["bind_central_ac_gw_node_id"].asString();//
indoorunitStatus = centralAC["status"];
}else if(infocome == 1){
centralACGwId = centralAC["central_ac_gw_devid"].asString();//中央空调网关设备 ID,注:非 zigbee 设备 ID 体系
devroomid = centralAC["room_id"].asString(); //房间号
indoorunitStatus = centralAC["indoorunit_state"]; //内机当前的状态
devname =centralAC["indoorunit_name"].asString(); //内机的名称,不同步到华为。
}
string centralAcGwNodeId; //这个内机对应的空调网关ID
string centralACGwMac; //这个内机对应的空调网关Mac
string centralACGwoperateType; //这个内机对应的空调网关类型
string centralACindoorMac; //这个内机mac为空调网关Mac+id
string centralACindoorsn; //这个内机sn为空调网关Mac+id 去除“:”
//1。 这个内机对应的空调网关ID
LOGD("centralACGwId:%s,indoorunitAddr:%s,indoorunitnodeId:%s \n",centralACGwId.c_str(),indoorunitAddr.c_str(),indoorunitId.c_str());
map<string,string>::iterator gwIt = gwId2NodeId.find(centralACGwId);
if(gwIt == gwId2NodeId.end()){
LOGW("centralACGwId:%s not in gwId2NodeId.\n",centralACGwId.c_str());
continue;
} else {
centralAcGwNodeId = gwIt->second;
}
//2。 这个内机对应的空调网关类型
map<string,string>::iterator operateIt = operate2NodeId.find(centralAcGwNodeId);
if(operateIt == operate2NodeId.end()){
LOGW("centralAcGwNodeId:%s not in operate2NodeId.\n",centralAcGwNodeId.c_str());
continue;
} else {
centralACGwoperateType = "-13"; //情景模式里的内机operateId
}
//3。 这个内机对应的空调网关Mac
map<string,string>::iterator centralAcNodeIt = nodeId2channelMap.find(centralAcGwNodeId);
if(centralAcNodeIt == nodeId2channelMap.end()){
LOGW("nodeid:%s not in nodeId2channelMap.\n",centralAcGwNodeId.c_str());
continue;
} else {
vector<string> chanMac;
Split(centralAcNodeIt->second,"_",chanMac);
centralACGwMac = chanMac[0];
}
indoorunitsId2AddrMap[indoorunitId] = centralACGwMac+"_"+indoorunitAddr; //网关与内机通道id之间的对应关系
LOGD("indoorunitId:%s .\n",indoorunitId.c_str());
if(StringToInt(indoorunitAddr,error)<10){
centralACindoorMac = centralACGwMac+"0"+indoorunitAddr; //*****************内机的mac构成关系
}else{
centralACindoorMac = centralACGwMac+indoorunitAddr;
}
centralACindoorsn = Replace(centralACindoorMac,":",""); //*****************内机的sn
if(!ccuDeleteMacs.empty() && ccuDeleteMacs.find(centralACGwMac)!=ccuDeleteMacs.end()){
continue;
}
map<string,vector<string> >::iterator numIt = controllerModel.find(centralACGwMac);//说明待定
if (numIt == controllerModel.end()) {
vector<string> addrId;
addrId.push_back(centralACindoorsn);
controllerModel[centralACGwMac] = addrId;
} else {
numIt->second.push_back(centralACindoorsn);
}
map<string,kk_handleDeviceInfo::KKDevmapinfo>::iterator it = hwBindDevMap.find(centralACindoorMac);
if(it!=hwBindDevMap.end()){
kk_handleDeviceInfo::KKDevmapinfo tripInfo = it->second;
LOGD("centralACGwMac:%s in hwBindDevMap \n",centralACindoorMac.c_str());
handleCcuDeviceToHwSubDev(centralACGwoperateType,indoorunitId,centralACindoorMac,channel,tripInfo.sn,indoorunitStatus,devroomid,devname);
}else{
if(toAddSubDevs.find(centralACindoorMac) == toAddSubDevs.end()){
kk_handleDeviceInfo::HwSubDev* dev = new kk_handleDeviceInfo::HwSubDev();
dev->dev_model_id = DAIKINCentralACindoor_PID; //内机 对应的华为prodID
dev->dev_type = DAIKINCentralACindoor_PID;
dev->mac = centralACindoorMac;
dev->operatetype = centralACGwoperateType;
dev->sn = Replace(centralACindoorMac,":","");
kk_handleDeviceInfo::KKChannelDev* chanDev = kk_handleDeviceInfo::GetInstance()->buildChannelDevice(centralACGwoperateType,indoorunitId,channel,indoorunitStatus,devroomid,devname);
map<string,kk_handleDeviceInfo::KKChannelDev*> channelDevs;
if(chanDev!=NULL){
channelDevs[channel] = chanDev;
}
dev->channelDevs = channelDevs;
toAddSubDevs[centralACindoorMac] = dev;
LOGD("\n found JoinDevProductkey for dev:%s,operateid:%s,channel:%s,close zigbee net now. \n",
centralACindoorMac.c_str(),centralACGwoperateType.c_str(), channel.c_str());
}
}
}
// 空调网关数量及内机地址推送
// map<string, string> hwCentralAcList;
// for(map<string, string>::iterator addrIt = indoorunitsId2AddrMap.begin(); addrIt!=indoorunitsId2AddrMap.end(); addrIt++){
// vector<string> macChan;
// Split(addrIt->second,"_", macChan);
// EH::Json::Value batchArg;
// hwCentralAcList[macChan[0]] = macChan[1];
// }
if( toAddSubDevs.size() > 0){
discoveryEnable = true;
KKdiscover = true;
LOGD(" discoveryEnable:%d,KKdiscover:%d\n",discoveryEnable,KKdiscover);
}
addCCuDevicesToCloud(toAddSubDevs);
LOGD("after handle NEW_DEVICES,total hw dev count is:%d \n",hwSubDevs.size());
//推送内机数目
for(map<string, string>::iterator gwIt = gwId2NodeId.begin(); gwIt!=gwId2NodeId.end(); gwIt++){
map<string,string>::iterator nodeIt = nodeId2channelMap.find(gwIt->second);
if(nodeIt == nodeId2channelMap.end()){
LOGW("gwId:%s not in gwId2NodeId, affect Internal machine push.\n",gwIt->second.c_str());
continue;
}
vector<string> chanMac;
Split(nodeIt->second,"_",chanMac);
string sn = Replace(chanMac[0],":","");
string channel = chanMac[1];
map<string, kk_handleDeviceInfo::HwSubDev*>::iterator subDevIt = hwSubDevs.find(sn);
if(subDevIt == hwSubDevs.end()){
LOGW("dev:%s not in hwSubDevs.\n",sn.c_str());
continue;
} else {
string dev_model_id = subDevIt->second->dev_model_id;
string devType = subDevIt->second->devTypeId;
EH::Json::Value payload;
EH::Json::Value msgstate0;
payload["gw_id"] = EH_ToolKit::GetMacNoSpace(); //请求发起者
payload["dev_id"] = sn;
payload["dev_type"] = subDevIt->second->dev_model_id;
payload["dev_ep_id"] = StringToInt(channel,error); //通道
EH::Json::Value msgstate2;
string respTopic = pushTopic+string("/devicestatechange");//设备状态变化上报
EH::Json::Value array;
map<string,vector<string> >::iterator numIt = controllerModel.find(subDevIt->second->mac);
if (numIt != controllerModel.end()) {
for (vector<string>::iterator it = numIt->second.begin(); it != numIt->second.end(); it++) {
EH::Json::Value idJson;
idJson["sn"] = *it;
array.append(idJson);
}
msgstate2["deviceList"] = array;
} else {
msgstate2["deviceList"].resize(0);//空数组
}
payload["state"] = msgstate2;
payload["dev_ep_id"] = 3; //功能映射为通道3
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
}
//deleteCCuDevices(ccuDeleteMacs); //调试
ccuDeleteMacs.clear();
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
void MQ_CCU_Adapter::SYNC_handle_AcGw_Devices(EH::Json::Value CentralAcGwsDevices){ //SYNC_INFO 处理中央空调网关
try {
for (int i = 0; i < CentralAcGwsDevices.size(); i++) {
EH::Json::Value Gwdevice = CentralAcGwsDevices[i];
string operateType = "12001";//中央空调网关
string gwId = Gwdevice["id"].asString();
string nodeid = Gwdevice["bind_central_ac_gw_node_id"].asString();
gwId2NodeId[gwId] = nodeid;
NodeId2gwId[nodeid] = gwId;
LOGD("add ccu system gwId:%s, gwNodeId:%s \n",gwId.c_str() ,nodeid.c_str());
operate2NodeId[nodeid] = operateType;
string mac = KK_CcuConfig::GetInstance()->getCentralAcGwMac(nodeid);
string channel = "1";
string devroomid = Gwdevice["room_id"].asString(); //房间号
string devname = Gwdevice["dev_name"].asString(); //设备的名称
nodeId2channelMap[nodeid] = mac+"_"+channel;
EH::Json::Value status = "0"; //设备的状态 Gwdevice["status"].asString()"status": {"gwStatusCode": -1,"online": false}
map<string,kk_handleDeviceInfo::KKDevmapinfo>::iterator devIt = hwBindDevMap.find(mac);
if(devIt!=hwBindDevMap.end()){
kk_handleDeviceInfo::KKDevmapinfo tripInfo = devIt->second;
handleCcuDeviceToHwSubDev(operateType,nodeid,mac,channel,tripInfo.sn,status,devroomid,devname);
}else{
LOGW("ccu dev:%s not found bind info in lcoal cache.delete fron ccu later. \n",mac.c_str());
}
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
void MQ_CCU_Adapter::handleCcuDeviceToHwSubDev(string operateType,string nodeid,string mac,
string channel,string sn,EH::Json::Value status,string devroomid,string devname){
try {
LOGD("handleCcuDeviceToHwSubDev operateType:%s nodeid:%s channel:%s sn:%s. \n",operateType.c_str(),nodeid.c_str(),channel.c_str(),sn.c_str());
map<string,kk_handleDeviceInfo::HwSubDev*>::iterator subDevIt = hwSubDevs.find(sn);
if(subDevIt == hwSubDevs.end()){//add new dev in cache
kk_handleDeviceInfo::HwSubDev* dev = new kk_handleDeviceInfo::HwSubDev();
map<string,kk_handleDeviceInfo::KKDevmapinfo>::iterator devIt = hwBindDevMap.find(mac);
kk_handleDeviceInfo::KKDevmapinfo tripInfo = devIt->second;
dev->dev_model_id = tripInfo.dev_model_id;
dev->dev_type = tripInfo.dev_type;
dev->sn = sn;
dev->mac = mac;
dev->operatetype = operateType;
kk_handleDeviceInfo::KKChannelDev* chanDev = kk_handleDeviceInfo::GetInstance()-> buildChannelDevice(operateType,nodeid,channel,status,devroomid,devname);
map<string,kk_handleDeviceInfo::KKChannelDev*> channelDevs;
if(chanDev!=NULL){
channelDevs[channel] = chanDev;
}
dev->channelDevs = channelDevs;
hwSubDevs[sn] = dev;
// if(KK_HwSdk::GetInstance()->registerNewDev(dev) == 0){ //下一行临时更改,上报设备状态 ,待更改 2020.10.15.9 //解开 2020.12.14.9
if(1){
LOGI("registerdev success.dev:%s, first add to local cache.channel:%s.\n",mac.c_str(),channel.c_str());
}else{
hwSubDevs.erase(sn);
LOGW("registerdev failed. \n");
}
}else{
map<string,kk_handleDeviceInfo::KKChannelDev*> channelDevs = subDevIt->second->channelDevs;
if(channelDevs.find(channel) == channelDevs.end()){//new node
kk_handleDeviceInfo::KKChannelDev* chanDev = kk_handleDeviceInfo::GetInstance()->buildChannelDevice(operateType,nodeid,channel,status,devroomid,devname);
if(chanDev!=NULL){
subDevIt->second->channelDevs[channel] = chanDev;
}
LOGD("dev:%s has added to local cache.try to handle channel:%s dev info. \n",mac.c_str(),channel.c_str());
}
}
//当这个通道设备未添加到房间,调用这个接口。
if(devroomid == "-1"){
map<string,kk_handleDeviceInfo::HwSubDev*>::iterator DevicesToRoom = hwSubDevs.find(sn);
LOGD("添加到房间 discoveryEnable:%d,KKdiscover:%d, sn:%s\n",discoveryEnable,KKdiscover,sn.c_str());
kk_handleDeviceInfo::GetInstance()->addCCuDevicesToRoom(DevicesToRoom,NodeId2gwId); //自动添加华为组设备。
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
void MQ_CCU_Adapter::addCCuDevicesToCloud(map<string,kk_handleDeviceInfo::HwSubDev*> toAddSubDevs){
try {
LOGI("prepare to add %d new devices to Roma cloud.\n",toAddSubDevs.size());
string respTopic ;
respTopic= pushTopic + string("/devicejoined");//子设备入网
if(toAddSubDevs.empty()){
return ;
}
set<string> addFailedDevs;
for(map<string,kk_handleDeviceInfo::HwSubDev*>::iterator it = toAddSubDevs.begin();it!=toAddSubDevs.end();it++){
int ret;
EH::Json::Value payload;
string devMac = it->first;
string dev_model_id = it->second->dev_model_id;
LOGI("prepare to add dev: %s ,dev_model_id: %s. \n",devMac.c_str(),dev_model_id.c_str());
it->second->online = true;
mtx.acquire();
string devSn = it->second->sn;
//是否已经加入映射列表里
map<string, kk_handleDeviceInfo::HwSubDev*>::iterator subDevIt = hwSubDevs.find(devSn);
if(subDevIt != hwSubDevs.end() && (dev_model_id == DAIKINCentralACindoor_PID||dev_model_id == DAIKINCentralACgw_PID)){//空调内机,重复推送入网会有问题,改为推上线。
respTopic= pushTopic + string("/deviceonline");
payload["gw_id"] = gw_id; //请求发起者
payload["dev_id"] = devSn;
payload["dev_type"] = it->second->dev_model_id;
}else{
payload["gw_id"] = gw_id; //请求发起者
payload["dev_id"] = devSn;
payload["dev_type"] = it->second->dev_model_id;
payload["dev_model_id"] = it->second->dev_type;
}
ret = sendtoRoma(payload,respTopic); //推送新设备到Roma
if(ret == 0){
LOGI("add device:%s,dev_model_id:%s,to Roma cloud success!!!\n",devMac.c_str(),dev_model_id.c_str());
//添加到映射列表里
hwSubDevs[devSn] = it->second; //add to cache;
LOGD("add to cache devSn :%s.\n", devSn.c_str());
// if(discoveryEnable == true && KKdiscover == true){//小K 华为组网时,自动添加设备到特定房间里。
LOGD(" 添加到房间 discoveryEnable:%d , prodId:%d\n",discoveryEnable,KKdiscover);
kk_handleDeviceInfo::GetInstance()->addCCuDevicesToRoom(it,NodeId2gwId);
// }
mtx.release();
if(dev_model_id == DAIKINCentralACindoor_PID){
continue; //使得内机都可以添加进入
}
client->sendRequest(gw_NodeId, "CLOSE_NET_CHANNEL", "*", "HJ_Server");
this->discoveryEnable = false;
}else{
hwSubDevs.erase(devSn);
mtx.release();
addFailedDevs.insert(devMac);
LOGE("add dev:%s to hw cloud failed.\n",devMac.c_str());
}
}
this->discoveryEnable = false;
LOGD("discoveryEnable:%d,\n",discoveryEnable);
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
//发送添加房间命令
void MQ_CCU_Adapter::SendSETUPToCcu(string name,string DeviceIcon,string DevDodeId,string roomid,string opcode){
string arg;
if(opcode == "SETUP_NODE"){
EH::Json::Value devicearg;
devicearg["name"] = name;
devicearg["device_icon"] = DeviceIcon;
devicearg["device_pos"] = "1";
devicearg["room_id"] = roomid;
arg = EH_ToolKit::JsonToString(devicearg);
}else if(opcode == "SET_CENTRAL_AC_INDOOR_UNIT"||opcode == "SET_CENTRAL_AC_GW"){
EH::Json::Value devicearg;
devicearg["name"] = name;
devicearg["room_id"] = roomid;
arg = EH_ToolKit::JsonToString(devicearg);
}
client->sendRequest(DevDodeId,opcode, arg, "HJ_Config");
}
void MQ_CCU_Adapter::oninitmqttsdk() {
try {
//goto跳转,谨慎使用。
loop:
// EH::Json::Value connectStateInfo = KK_HwDevManager::GetInstance()->loadConnectState();//获取绑定信息
// if(connectStateInfo["result"] == "1"){
// string heartbeat_Topic;
// clientId = connectStateInfo["client_id"].asString();
// username = connectStateInfo["device_name"].asString();
ccuId = MQ_CCU_Config::GetInstance()->getCcuId(); //获取主机ID
//订阅的 Topic
ptpoTopic = string("$xlink/ptpo/{")+ccuId+"}"; //ptpo运维
ptpTopic = string("$xlink/ptp/{")+ccuId+"}"; //ptp交互
heartbeat_Topic = string("$xlink/ptp/{")+ccuId+"}/ptp_keepalive"; //心跳
LOGD("pushTopic is: %s subTopic is: %s \n",pushTopic.c_str(),subTopic.c_str());
int ret = mqttSdk->init(MQ_CCU_Config::GetInstance()->getBrokerAddr(), //正式环境
"KONKE-KK-QWER1234QWER1234","","",heartbeat_Topic,gw_id);
// int ret = mqttSdk->init(MQ_CCU_Config::GetInstance()->getBrokerAddr(), //正式环境
// clientId,"2CEDC38940644E439649389C08329B09","}A12a#RM^r)iXy/?|sHW:z3!",willTopic,heartbeat_Topic,gw_id);
mqttOnline = false;
if(ret == 0){
mqttSdk->con(1,3);
}else{
LOGE("init mqtt sdk failed.\n");
return;
}
}else{
LOGI("与APP未绑定 Not bound to app\n");
sleep(1);
goto loop;
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
//---mqtt broker communication mqtt代理通信
//云上连接
void MQ_CCU_Adapter::onCloudConnect(){
LOGI("mqtt 代理 通信 云上连接 .\n");
LOGI("onCloudConnect,to sub topic.\n");
EH::Json::Value online;
online["gw_id"] = gw_id;
if(mqttSdk->subTopic(subTopic,0,2000)!=0){
LOGW("sub topic:%s failed,exit now.\n",subTopic.c_str());
ACE_OS::sleep(1);
ACE_OS::exit(1);
}else{
LOGD("sub topic Many success,ready to work.\n");
mqttSdk->sendMsg(willTopic,EH_ToolKit::JsonToString(online),0);
if(mqttOnline == false){ //与云端断开重联才会发送,达到同步设备信息。
string arg = "{\"conditions\":[{\"condition_type\":\"dev_list\",\"condition_arg\":[]}]}";
client->sendRequest("*", "GET_ZIGBEE_DEVS_HW_INFO", arg, "HJ_Config");
mqttOnline = true;
}
}
}
//云端断开连接
void MQ_CCU_Adapter::onCloudDisConnect(){
mqttOnline = false;
LOGW("云端 断开 连接 .\n")
LOGW("onCloudDisConnect,reconnect in seconds.\n")
}
//解绑网关
int MQ_CCU_Adapter::on_unbind_gateway(string device_name,string client_id,string method){
LOGD("on_unbind_gateway: device_name:%s, client_id:%s\n",device_name.c_str(),client_id.c_str());
EH::Json::Value connectStateInfo = KK_HwDevManager::GetInstance()->loadConnectState();//获取绑定信息
// 不对解绑信息进行校验,先默认解绑信息正确
try{
if(connectStateInfo["client_id"] == clientId && connectStateInfo["device_name"] == username){
//关闭UDP线程
//关闭TCP服务器
//去除缓存文件里的信息
EH::Json::Value newconnectInfo;
newconnectInfo["result"] = "0";
newconnectInfo["client_id"] = "";
newconnectInfo["device_name"] = "";
int saveok = KK_HwDevManager::GetInstance()->saveConnectState(newconnectInfo);
LOGD(" 去除缓存文件里的信息 :%d.\n",saveok);
//解绑网关推送
string respTopic;
respTopic = pushTopic+string("/gwstate");//解绑网关
EH::Json::Value payload;
payload["client_id"] = clientId; //请求发起者
payload["device_name"] = username;
payload["action"] = method;
int SendOk = sendtoRoma(payload,respTopic); //推送新设备到Roma
LOGD(" 解绑网关 unbind_gateway SendOk :%d.\n",SendOk);
//删除主机内所有设备
if(method == "unbind_gateway"){
int Del_Devs = deleteCCuDevices();
LOGD("删除主机内所有设备 :%d.\n",Del_Devs);
}
if(SendOk == 0){
//程序重启
LOGD("reboot Software now.\n");
sleep(5);
system("sync;sync;sync;sync;");
system("killall Konkexinghai");
exit(0);
}else{
LOGW("发送退网信息失败 :%d.\n",SendOk);
}
}else{
}
} catch (exception &e) {
LOGW("%s.\n", e.what());
}
return -1;
}
//删除所有设备
int MQ_CCU_Adapter::deleteCCuDevices(){
LOGD("删除所有设备\n");
try{
map<string,kk_handleDeviceInfo::HwSubDev*>::iterator it = hwSubDevs.begin();
for (; it != hwSubDevs.end(); it++) {
string DevDodeId;
string devMac = it->second->mac;
string devProdId = it->second->dev_model_id;
// LOGD("临时注释删除所有所有设备mac %s\n",arg.c_str());
unsigned long nowReqTime = getSystemTimeInMs();
if( (nowReqTime - lastCcuReqTime) > 100){
if (devProdId == DAIKINCentralACgw_PID) {
// string gwNodeId = KK_CcuConfig::GetInstance()->getCentralAcGwNodeId(it->second->mac);
// client->sendRequest(gwNodeId, "DEL_CENTRAL_AC_GW", "*", "HJ_CentralAC");
map<string,string>::iterator gwIt = NodeId2gwId.find(it->second->channelDevs["1"]->nodeId); //NodeId2gwId gwId2NodeId
if(gwIt == NodeId2gwId.end()){
LOGW("centralACnodeId:%s not in gwId2NodeId.\n",it->second->channelDevs["1"]->nodeId.c_str());
} else {
DevDodeId = gwIt->second;
}
client->sendRequest(DevDodeId, "DEL_CENTRAL_AC_GW", "*", "HJ_CentralAC");
} else {
string arg = "{\"mac\":\""+devMac+"\"}";
client->sendRequest("*", "DEL_DEVICE", arg, "HJ_Server");
}
lastCcuReqTime = nowReqTime;
}else{
LOGI("delete Devicessend req to ccu too fast,wait 100ms.\n");
usleep(200*1000);
if (devProdId == DAIKINCentralACgw_PID) {
// string gwNodeId = KK_CcuConfig::GetInstance()->getCentralAcGwNodeId(it->second->mac);
// client->sendRequest(gwNodeId, "DEL_CENTRAL_AC_GW", "*", "HJ_CentralAC");
map<string,string>::iterator gwIt = NodeId2gwId.find(it->second->channelDevs["1"]->nodeId); //NodeId2gwId gwId2NodeId
if(gwIt == NodeId2gwId.end()){
LOGW("centralACnodeId:%s not in gwId2NodeId.\n",it->second->channelDevs["1"]->nodeId.c_str());
} else {
DevDodeId = gwIt->second;
}
client->sendRequest(DevDodeId, "DEL_CENTRAL_AC_GW", "*", "HJ_CentralAC");
} else {
string arg = "{\"mac\":\""+devMac+"\"}";
client->sendRequest("*", "DEL_DEVICE", arg, "HJ_Server");
}
lastCcuReqTime = getSystemTimeInMs();
}
}
} catch (exception &e) {
LOGW("%s.\n", e.what());
}
return 0;
}
//删除请求
int MQ_CCU_Adapter::onDeviceRequestDelete(string devSn){
try {
LOGD("删除设备:%s .\n",devSn.c_str());
Deletesn = devSn;
mtx.acquire();
map<string,kk_handleDeviceInfo::HwSubDev*>::iterator it = hwSubDevs.find(devSn);
if(it != hwSubDevs.end()){
string channel= "1";
string DevDodeId;
string devMac = it->second->mac;
string devProdId = it->second->dev_model_id;
hwSubDevs.erase(devSn);
if(devProdId == DAIKINCentralACindoor_PID){ //内机特殊处理
LOGD("删除内机设备:%s .\n",devSn.c_str());
mtx.release();
return 0;
}
hwBindDevMap.erase(devMac);
//KK_HwDevManager::GetInstance()->saveAllSubDev(hwBindDevMap);
if (devProdId == DAIKINCentralACgw_PID) {
// string gwNodeId = KK_CcuConfig::GetInstance()->getCentralAcGwNodeId(it->second->mac);
// sendReqToCcu("DEL_CENTRAL_AC_GW",gwNodeId,"*","HJ_CentralAC");
map<string,string>::iterator gwIt = NodeId2gwId.find(it->second->channelDevs["1"]->nodeId); //NodeId2gwId gwId2NodeId
if(gwIt == NodeId2gwId.end()){
LOGW("centralACnodeId:%s not in gwId2NodeId.\n",it->second->channelDevs["1"]->nodeId.c_str());
} else {
DevDodeId = gwIt->second;
}
client->sendRequest(DevDodeId, "DEL_CENTRAL_AC_GW", "*", "HJ_CentralAC");
onACindoorDelete(devMac);
} else {
string arg = "{\"mac\":\""+devMac+"\"}";
sendReqToCcu("DEL_DEVICE","*",arg,"HJ_Server");
//子设备解绑或移除
string respTopic;
respTopic = pushTopic+"/deviceremove";
EH::Json::Value payload;
payload["gw_id"] = gw_id;
payload["dev_id"] = devSn;
int SendOk;
SendOk = sendtoRoma(payload,respTopic);
}
}else{
LOGW("not found hw dev:%s in local triple cache.\n",devSn.c_str());
}
mtx.release();
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
return 0;
}
//小K 删除
int MQ_CCU_Adapter::loadDelete(EH::Json::Value arg){
try {
string devSn = Replace(arg.asString(),":","");
if(Deletesn == devSn){ //兴海app删
Deletesn = "";
}else{ //小K app删
mtx.acquire();
map<string, kk_handleDeviceInfo::HwSubDev*>::iterator it = hwSubDevs.find(devSn);
if(it != hwSubDevs.end()){
string channel= "1";
string devMac = it->second->mac;
// KK_HwSdk::GetInstance()->changeDevOnline(devSn, false);
it->second->online = false;
if(it->second->dev_model_id == DAIKINCentralACgw_PID){
handleACindoorDevNolinePush(arg.asString());
}
LOGI("本地删除设备sn:%s 推送设备离线:%s.\n",devSn.c_str(),devSn.c_str());
hwSubDevs.erase(devSn);
hwBindDevMap.erase(devMac);
//子设备解绑或移除
string respTopic;
respTopic = pushTopic+"/deviceoffline";//子设备离线
EH::Json::Value payload;
payload["dev_id"] = devSn; //请求发起者
sendtoRoma(payload,respTopic);
}else{
LOGW("这个设备已删除,不推送.\n");
}
mtx.release();
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
return 0;
}
//删除空调网关时,也删除其下的内机。
int MQ_CCU_Adapter::onACindoorDelete(string devMac){
string sn;
try {
map<string,vector<string> >::iterator numIt = controllerModel.find(devMac);
if (numIt != controllerModel.end()) {
for (vector<string>::iterator it = numIt->second.begin(); it != numIt->second.end(); it++) {
sn = (*it).c_str();
//子设备解绑或移除
string respTopic;
respTopic = pushTopic+"/deviceoffline";//子设备离线
EH::Json::Value payload;
payload["dev_id"] = sn; //请求发起者
sendtoRoma(payload,respTopic); //网关离线,内机向华为推送离线。 //删除空调网关也会删除内机,
LOGI("删除内机sn:%s .\n",sn.c_str());
hwSubDevs.erase(sn);
}
}else{
LOGD("这个中央空调网关没有内机.\n");
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
return 0;
}
void MQ_CCU_Adapter::handleACindoorDevNolinePush(string mac){
try {
string sn;
map<string,vector<string> >::iterator numIt = controllerModel.find(mac);
if (numIt != controllerModel.end()) {
for (vector<string>::iterator it = numIt->second.begin(); it != numIt->second.end(); it++) {
EH::Json::Value idJson;
sn = (*it).c_str();
map<string, kk_handleDeviceInfo::HwSubDev*>::iterator subDevIt = hwSubDevs.find(sn);
//子设备解绑或移除
string respTopic;
respTopic = pushTopic + "/deviceoffline";//子设备离线
EH::Json::Value payload;
payload["dev_id"] = sn; //请求发起者
sendtoRoma(payload,respTopic); //网关离线,内机向华为推送离线。 //删除空调网关也会删除内机,
subDevIt->second->online = false;
LOGI("删除内机sn:%s .\n",sn.c_str());
hwSubDevs.erase(sn);
}
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
int MQ_CCU_Adapter::sendtoRoma(EH::Json::Value payload,string respTopic){
LOGD("send to Roma msg payload:%s respTopic:%s.\n",payload.toStyledString().c_str(),respTopic.c_str());
EH::Json::FastWriter writer;
string sendPayload = writer.write(payload);
return mqttSdk->sendMsg(respTopic,sendPayload,0);
}
//获取网关的nodeID
void MQ_CCU_Adapter::handlegwNodeId(EH::Json::Value arg){
EH::Json::Value gw_lists = arg["gw_list"];
for(int i = 0;i < gw_lists.size();i++){
EH::Json::Value gw_list = gw_lists[i];
if(gw_list["gw_type"] == "6"&&gw_list["gw_link"] == "1"){ //Z3网关类型且在线。
gw_NodeId = gw_list["gw_nodeid"].asString();
}
}
}
//加载主机所有已经添加的设备
int MQ_CCU_Adapter::loadAllSubDev(EH::Json::Value arg){
try {
if(arg.isArray()){
for(int i = 0;i < arg.size();i++){
kk_handleDeviceInfo::KKDevmapinfo bindDev;
bindDev.mac = arg[i]["mac"].asString();
bindDev.sn = Replace(bindDev.mac,":","");
string productid = EH_ToolKit::IntToString(arg[i]["product_id"].asInt());
EH::Json::Value XiaoKprodId = kk_handleDeviceInfo::GetInstance()->XiaoK_Zu_Wang(productid); //调用设备是否接入华为
if ( XiaoKprodId["dev_model_id"] != "-1"){
bindDev.dev_model_id = XiaoKprodId["dev_model_id"].asString();
bindDev.dev_type = XiaoKprodId["dev_type"].asString();
}else {
continue;
}
LOGD("all_devs_info mac:%s productid:%s dev_model_id:%s.\n",arg[i]["mac"].asString().c_str(),productid.c_str(),XiaoKprodId["dev_model_id"].asString().c_str());
hwBindDevMap[bindDev.mac] = bindDev;
}
}
} catch (exception& e) {
LOGW("%s.\n",e.what());
}
LOGI("load all sub dev,now dev count:%d.\n", hwBindDevMap.size());
return 0;
}
//Zigbee 设备入网推送的信息
int MQ_CCU_Adapter::handle_Dev_Join_Notify(EH::Json::Value arg){
try {
//新加入设备mac -> 设备productid
if(Join_productid_Map.size()>50){ //临时方案,待优化,是个隐藏bug:一次组多个设备且在程序启动后的50次左右
Join_productid_Map.clear(); //新设备添加完成去除
}
string dev_mac = arg["mac"].asString();
string dev_productid = EH_ToolKit::IntToString(arg["productId"].asInt());
Join_productid_Map[dev_mac] = dev_productid;
} catch (exception& e) {
LOGW("%s.\n",e.what());
}
return 0;
}
#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 source diff could not be displayed because it is too large. You can view the blob instead.
/**
* 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
#ifndef CPPTL_JSON_H_INCLUDED_HJ
# define CPPTL_JSON_H_INCLUDED_HJ
# include "../include/json/forwards.h"
# include <string>
# include <vector>
# ifndef JSON_USE_CPPTL_SMALLMAP
# include <map>
# else
# include <cpptl/smallmap.h>
# endif
# ifdef JSON_USE_CPPTL
# include <cpptl/forwards.h>
# endif
/** \brief JSON (JavaScript Object Notation).
*/
namespace EH{
namespace Json {
/** \brief Type of the value held by a Value object.
*/
enum ValueType
{
nullValue = 0, ///< 'null' value
intValue, ///< signed integer value
uintValue, ///< unsigned integer value
realValue, ///< double value
stringValue, ///< UTF-8 string value
booleanValue, ///< bool value
arrayValue, ///< array value (ordered list)
objectValue ///< object value (collection of name/value pairs).
};
enum CommentPlacement
{
commentBefore = 0, ///< a comment placed on the line before a value
commentAfterOnSameLine, ///< a comment just after a value on the same line
commentAfter, ///< a comment on the line after a value (only make sense for root value)
numberOfCommentPlacement
};
//# ifdef JSON_USE_CPPTL
// typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
// typedef CppTL::AnyEnumerator<const Value &> EnumValues;
//# endif
/** \brief Lightweight wrapper to tag static string.
*
* Value constructor and objectValue member assignement takes advantage of the
* StaticString and avoid the cost of string duplication when storing the
* string or the member name.
*
* Example of usage:
* \code
* Json::Value aValue( StaticString("some text") );
* Json::Value object;
* static const StaticString code("code");
* object[code] = 1234;
* \endcode
*/
class JSON_API StaticString
{
public:
explicit StaticString( const char *czstring )
: str_( czstring )
{
}
operator const char *() const
{
return str_;
}
const char *c_str() const
{
return str_;
}
private:
const char *str_;
};
/** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
*
* This class is a discriminated union wrapper that can represents a:
* - signed integer [range: Value::minInt - Value::maxInt]
* - unsigned integer (range: 0 - Value::maxUInt)
* - double
* - UTF-8 string
* - boolean
* - 'null'
* - an ordered list of Value
* - collection of name/value pairs (javascript object)
*
* The type of the held value is represented by a #ValueType and
* can be obtained using type().
*
* values of an #objectValue or #arrayValue can be accessed using operator[]() methods.
* Non const methods will automatically create the a #nullValue element
* if it does not exist.
* The sequence of an #arrayValue will be automatically resize and initialized
* with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
*
* The get() methods can be used to obtanis default value in the case the required element
* does not exist.
*
* It is possible to iterate over the list of a #objectValue values using
* the getMemberNames() method.
*/
class JSON_API Value
{
friend class ValueIteratorBase;
# ifdef JSON_VALUE_USE_INTERNAL_MAP
friend class ValueInternalLink;
friend class ValueInternalMap;
# endif
public:
typedef std::vector<std::string> Members;
typedef ValueIterator iterator;
typedef ValueConstIterator const_iterator;
typedef Json::UInt UInt;
typedef Json::Int Int;
typedef UInt ArrayIndex;
static const Value null;
static const Int minInt;
static const Int maxInt;
static const UInt maxUInt;
private:
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
# ifndef JSON_VALUE_USE_INTERNAL_MAP
class CZString
{
public:
enum DuplicationPolicy
{
noDuplication = 0,
duplicate,
duplicateOnCopy
};
CZString( int index );
CZString( const char *cstr, DuplicationPolicy allocate );
CZString( const CZString &other );
~CZString();
CZString &operator =( const CZString &other );
bool operator<( const CZString &other ) const;
bool operator==( const CZString &other ) const;
int index() const;
const char *c_str() const;
bool isStaticString() const;
private:
void swap( CZString &other );
const char *cstr_;
int index_;
};
public:
# ifndef JSON_USE_CPPTL_SMALLMAP
typedef std::map<CZString, Value> ObjectValues;
# else
typedef CppTL::SmallMap<CZString, Value> ObjectValues;
# endif // ifndef JSON_USE_CPPTL_SMALLMAP
# endif // ifndef JSON_VALUE_USE_INTERNAL_MAP
#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
public:
/** \brief Create a default Value of the given type.
This is a very useful constructor.
To create an empty array, pass arrayValue.
To create an empty object, pass objectValue.
Another Value can then be set to this one by assignment.
This is useful since clear() and resize() will not alter types.
Examples:
\code
Json::Value null_value; // null
Json::Value arr_value(Json::arrayValue); // []
Json::Value obj_value(Json::objectValue); // {}
\endcode
*/
Value( ValueType type = nullValue );
Value( Int value );
Value( UInt value );
Value( double value );
Value( const char *value );
Value( const char *beginValue, const char *endValue );
/** \brief Constructs a value from a static string.
* Like other value string constructor but do not duplicate the string for
* internal storage. The given string must remain alive after the call to this
* constructor.
* Example of usage:
* \code
* Json::Value aValue( StaticString("some text") );
* \endcode
*/
Value( const StaticString &value );
Value( const std::string &value );
# ifdef JSON_USE_CPPTL
Value( const CppTL::ConstString &value );
# endif
Value( bool value );
Value( const Value &other );
~Value();
Value &operator=( const Value &other );
/// Swap values.
/// \note Currently, comments are intentionally not swapped, for
/// both logic and efficiency.
void swap( Value &other );
ValueType type() const;
bool operator <( const Value &other ) const;
bool operator <=( const Value &other ) const;
bool operator >=( const Value &other ) const;
bool operator >( const Value &other ) const;
bool operator ==( const Value &other ) const;
bool operator !=( const Value &other ) const;
int compare( const Value &other );
const char *asCString() const;
std::string asString() const;
# ifdef JSON_USE_CPPTL
CppTL::ConstString asConstString() const;
# endif
Int asInt() const;
UInt asUInt() const;
double asDouble() const;
bool asBool() const;
bool isNull() const;
bool isBool() const;
bool isInt() const;
bool isUInt() const;
bool isIntegral() const;
bool isDouble() const;
bool isNumeric() const;
bool isString() const;
bool isArray() const;
bool isObject() const;
bool isConvertibleTo( ValueType other ) const;
/// Number of values in array or object
UInt size() const;
/// \brief Return true if empty array, empty object, or null;
/// otherwise, false.
bool empty() const;
/// Return isNull()
bool operator!() const;
/// Remove all object members and array elements.
/// \pre type() is arrayValue, objectValue, or nullValue
/// \post type() is unchanged
void clear();
/// Resize the array to size elements.
/// New elements are initialized to null.
/// May only be called on nullValue or arrayValue.
/// \pre type() is arrayValue or nullValue
/// \post type() is arrayValue
void resize( UInt size );
/// Access an array element (zero based index ).
/// If the array contains less than index element, then null value are inserted
/// in the array so that its size is index+1.
/// (You may need to say 'value[0u]' to get your compiler to distinguish
/// this from the operator[] which takes a string.)
Value &operator[]( UInt index );
/// Access an array element (zero based index )
/// (You may need to say 'value[0u]' to get your compiler to distinguish
/// this from the operator[] which takes a string.)
const Value &operator[]( UInt index ) const;
/// If the array contains at least index+1 elements, returns the element value,
/// otherwise returns defaultValue.
Value get( UInt index,
const Value &defaultValue ) const;
/// Return true if index < size().
bool isValidIndex( UInt index ) const;
/// \brief Append value to array at the end.
///
/// Equivalent to jsonvalue[jsonvalue.size()] = value;
Value &append( const Value &value );
void remove(ArrayIndex index);
/// Access an object value by name, create a null member if it does not exist.
Value &operator[]( const char *key );
/// Access an object value by name, returns null if there is no member with that name.
const Value &operator[]( const char *key ) const;
/// Access an object value by name, create a null member if it does not exist.
Value &operator[]( const std::string &key );
/// Access an object value by name, returns null if there is no member with that name.
const Value &operator[]( const std::string &key ) const;
/** \brief Access an object value by name, create a null member if it does not exist.
* If the object as no entry for that name, then the member name used to store
* the new entry is not duplicated.
* Example of use:
* \code
* Json::Value object;
* static const StaticString code("code");
* object[code] = 1234;
* \endcode
*/
Value &operator[]( const StaticString &key );
# ifdef JSON_USE_CPPTL
/// Access an object value by name, create a null member if it does not exist.
Value &operator[]( const CppTL::ConstString &key );
/// Access an object value by name, returns null if there is no member with that name.
const Value &operator[]( const CppTL::ConstString &key ) const;
# endif
/// Return the member named key if it exist, defaultValue otherwise.
Value get( const char *key,
const Value &defaultValue ) const;
/// Return the member named key if it exist, defaultValue otherwise.
Value get( const std::string &key,
const Value &defaultValue ) const;
# ifdef JSON_USE_CPPTL
/// Return the member named key if it exist, defaultValue otherwise.
Value get( const CppTL::ConstString &key,
const Value &defaultValue ) const;
# endif
/// \brief Remove and return the named member.
///
/// Do nothing if it did not exist.
/// \return the removed Value, or null.
/// \pre type() is objectValue or nullValue
/// \post type() is unchanged
Value removeMember( const char* key );
/// Same as removeMember(const char*)
Value removeMember( const std::string &key );
/// Return true if the object has a member named key.
bool isMember( const char *key ) const;
/// Return true if the object has a member named key.
bool isMember( const std::string &key ) const;
# ifdef JSON_USE_CPPTL
/// Return true if the object has a member named key.
bool isMember( const CppTL::ConstString &key ) const;
# endif
/// \brief Return a list of the member names.
///
/// If null, return an empty list.
/// \pre type() is objectValue or nullValue
/// \post if type() was nullValue, it remains nullValue
Members getMemberNames() const;
//# ifdef JSON_USE_CPPTL
// EnumMemberNames enumMemberNames() const;
// EnumValues enumValues() const;
//# endif
/// Comments must be //... or /* ... */
void setComment( const char *comment,
CommentPlacement placement );
/// Comments must be //... or /* ... */
void setComment( const std::string &comment,
CommentPlacement placement );
bool hasComment( CommentPlacement placement ) const;
/// Include delimiters and embedded newlines.
std::string getComment( CommentPlacement placement ) const;
std::string toStyledString() const;
const_iterator begin() const;
const_iterator end() const;
iterator begin();
iterator end();
private:
Value &resolveReference( const char *key,
bool isStatic );
# ifdef JSON_VALUE_USE_INTERNAL_MAP
inline bool isItemAvailable() const
{
return itemIsUsed_ == 0;
}
inline void setItemUsed( bool isUsed = true )
{
itemIsUsed_ = isUsed ? 1 : 0;
}
inline bool isMemberNameStatic() const
{
return memberNameIsStatic_ == 0;
}
inline void setMemberNameIsStatic( bool isStatic )
{
memberNameIsStatic_ = isStatic ? 1 : 0;
}
# endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP
private:
struct CommentInfo
{
CommentInfo();
~CommentInfo();
void setComment( const char *text );
char *comment_;
};
//struct MemberNamesTransform
//{
// typedef const char *result_type;
// const char *operator()( const CZString &name ) const
// {
// return name.c_str();
// }
//};
union ValueHolder
{
Int int_;
UInt uint_;
double real_;
bool bool_;
char *string_;
# ifdef JSON_VALUE_USE_INTERNAL_MAP
ValueInternalArray *array_;
ValueInternalMap *map_;
#else
ObjectValues *map_;
# endif
} value_;
ValueType type_ : 8;
int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
# ifdef JSON_VALUE_USE_INTERNAL_MAP
unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container.
int memberNameIsStatic_ : 1; // used by the ValueInternalMap container.
# endif
CommentInfo *comments_;
};
/** \brief Experimental and untested: represents an element of the "path" to access a node.
*/
class PathArgument
{
public:
friend class Path;
PathArgument();
PathArgument( UInt index );
PathArgument( const char *key );
PathArgument( const std::string &key );
private:
enum Kind
{
kindNone = 0,
kindIndex,
kindKey
};
std::string key_;
UInt index_;
Kind kind_;
};
/** \brief Experimental and untested: represents a "path" to access a node.
*
* Syntax:
* - "." => root node
* - ".[n]" => elements at index 'n' of root node (an array value)
* - ".name" => member named 'name' of root node (an object value)
* - ".name1.name2.name3"
* - ".[0][1][2].name1[3]"
* - ".%" => member name is provided as parameter
* - ".[%]" => index is provied as parameter
*/
class Path
{
public:
Path( const std::string &path,
const PathArgument &a1 = PathArgument(),
const PathArgument &a2 = PathArgument(),
const PathArgument &a3 = PathArgument(),
const PathArgument &a4 = PathArgument(),
const PathArgument &a5 = PathArgument() );
const Value &resolve( const Value &root ) const;
Value resolve( const Value &root,
const Value &defaultValue ) const;
/// Creates the "path" to access the specified node and returns a reference on the node.
Value &make( Value &root ) const;
private:
typedef std::vector<const PathArgument *> InArgs;
typedef std::vector<PathArgument> Args;
void makePath( const std::string &path,
const InArgs &in );
void addPathInArg( const std::string &path,
const InArgs &in,
InArgs::const_iterator &itInArg,
PathArgument::Kind kind );
void invalidPath( const std::string &path,
int location );
Args args_;
};
/** \brief Experimental do not use: Allocator to customize member name and string value memory management done by Value.
*
* - makeMemberName() and releaseMemberName() are called to respectively duplicate and
* free an Json::objectValue member name.
* - duplicateStringValue() and releaseStringValue() are called similarly to
* duplicate and free a Json::stringValue value.
*/
class ValueAllocator
{
public:
enum { unknown = (unsigned)-1 };
virtual ~ValueAllocator();
virtual char *makeMemberName( const char *memberName ) = 0;
virtual void releaseMemberName( char *memberName ) = 0;
virtual char *duplicateStringValue( const char *value,
unsigned int length = unknown ) = 0;
virtual void releaseStringValue( char *value ) = 0;
};
#ifdef JSON_VALUE_USE_INTERNAL_MAP
/** \brief Allocator to customize Value internal map.
* Below is an example of a simple implementation (default implementation actually
* use memory pool for speed).
* \code
class DefaultValueMapAllocator : public ValueMapAllocator
{
public: // overridden from ValueMapAllocator
virtual ValueInternalMap *newMap()
{
return new ValueInternalMap();
}
virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other )
{
return new ValueInternalMap( other );
}
virtual void destructMap( ValueInternalMap *map )
{
delete map;
}
virtual ValueInternalLink *allocateMapBuckets( unsigned int size )
{
return new ValueInternalLink[size];
}
virtual void releaseMapBuckets( ValueInternalLink *links )
{
delete [] links;
}
virtual ValueInternalLink *allocateMapLink()
{
return new ValueInternalLink();
}
virtual void releaseMapLink( ValueInternalLink *link )
{
delete link;
}
};
* \endcode
*/
class JSON_API ValueMapAllocator
{
public:
virtual ~ValueMapAllocator();
virtual ValueInternalMap *newMap() = 0;
virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other ) = 0;
virtual void destructMap( ValueInternalMap *map ) = 0;
virtual ValueInternalLink *allocateMapBuckets( unsigned int size ) = 0;
virtual void releaseMapBuckets( ValueInternalLink *links ) = 0;
virtual ValueInternalLink *allocateMapLink() = 0;
virtual void releaseMapLink( ValueInternalLink *link ) = 0;
};
/** \brief ValueInternalMap hash-map bucket chain link (for internal use only).
* \internal previous_ & next_ allows for bidirectional traversal.
*/
class JSON_API ValueInternalLink
{
public:
enum { itemPerLink = 6 }; // sizeof(ValueInternalLink) = 128 on 32 bits architecture.
enum InternalFlags {
flagAvailable = 0,
flagUsed = 1
};
ValueInternalLink();
~ValueInternalLink();
Value items_[itemPerLink];
char *keys_[itemPerLink];
ValueInternalLink *previous_;
ValueInternalLink *next_;
};
/** \brief A linked page based hash-table implementation used internally by Value.
* \internal ValueInternalMap is a tradional bucket based hash-table, with a linked
* list in each bucket to handle collision. There is an addional twist in that
* each node of the collision linked list is a page containing a fixed amount of
* value. This provides a better compromise between memory usage and speed.
*
* Each bucket is made up of a chained list of ValueInternalLink. The last
* link of a given bucket can be found in the 'previous_' field of the following bucket.
* The last link of the last bucket is stored in tailLink_ as it has no following bucket.
* Only the last link of a bucket may contains 'available' item. The last link always
* contains at least one element unless is it the bucket one very first link.
*/
class JSON_API ValueInternalMap
{
friend class ValueIteratorBase;
friend class Value;
public:
typedef unsigned int HashKey;
typedef unsigned int BucketIndex;
# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
struct IteratorState
{
IteratorState()
: map_(0)
, link_(0)
, itemIndex_(0)
, bucketIndex_(0)
{
}
ValueInternalMap *map_;
ValueInternalLink *link_;
BucketIndex itemIndex_;
BucketIndex bucketIndex_;
};
# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
ValueInternalMap();
ValueInternalMap( const ValueInternalMap &other );
ValueInternalMap &operator =( const ValueInternalMap &other );
~ValueInternalMap();
void swap( ValueInternalMap &other );
BucketIndex size() const;
void clear();
bool reserveDelta( BucketIndex growth );
bool reserve( BucketIndex newItemCount );
const Value *find( const char *key ) const;
Value *find( const char *key );
Value &resolveReference( const char *key,
bool isStatic );
void remove( const char *key );
void doActualRemove( ValueInternalLink *link,
BucketIndex index,
BucketIndex bucketIndex );
ValueInternalLink *&getLastLinkInBucket( BucketIndex bucketIndex );
Value &setNewItem( const char *key,
bool isStatic,
ValueInternalLink *link,
BucketIndex index );
Value &unsafeAdd( const char *key,
bool isStatic,
HashKey hashedKey );
HashKey hash( const char *key ) const;
int compare( const ValueInternalMap &other ) const;
private:
void makeBeginIterator( IteratorState &it ) const;
void makeEndIterator( IteratorState &it ) const;
static bool equals( const IteratorState &x, const IteratorState &other );
static void increment( IteratorState &iterator );
static void incrementBucket( IteratorState &iterator );
static void decrement( IteratorState &iterator );
static const char *key( const IteratorState &iterator );
static const char *key( const IteratorState &iterator, bool &isStatic );
static Value &value( const IteratorState &iterator );
static int distance( const IteratorState &x, const IteratorState &y );
private:
ValueInternalLink *buckets_;
ValueInternalLink *tailLink_;
BucketIndex bucketsSize_;
BucketIndex itemCount_;
};
/** \brief A simplified deque implementation used internally by Value.
* \internal
* It is based on a list of fixed "page", each page contains a fixed number of items.
* Instead of using a linked-list, a array of pointer is used for fast item look-up.
* Look-up for an element is as follow:
* - compute page index: pageIndex = itemIndex / itemsPerPage
* - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage]
*
* Insertion is amortized constant time (only the array containing the index of pointers
* need to be reallocated when items are appended).
*/
class JSON_API ValueInternalArray
{
friend class Value;
friend class ValueIteratorBase;
public:
enum { itemsPerPage = 8 }; // should be a power of 2 for fast divide and modulo.
typedef Value::ArrayIndex ArrayIndex;
typedef unsigned int PageIndex;
# ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
struct IteratorState // Must be a POD
{
IteratorState()
: array_(0)
, currentPageIndex_(0)
, currentItemIndex_(0)
{
}
ValueInternalArray *array_;
Value **currentPageIndex_;
unsigned int currentItemIndex_;
};
# endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
ValueInternalArray();
ValueInternalArray( const ValueInternalArray &other );
ValueInternalArray &operator =( const ValueInternalArray &other );
~ValueInternalArray();
void swap( ValueInternalArray &other );
void clear();
void resize( ArrayIndex newSize );
Value &resolveReference( ArrayIndex index );
Value *find( ArrayIndex index ) const;
ArrayIndex size() const;
int compare( const ValueInternalArray &other ) const;
private:
static bool equals( const IteratorState &x, const IteratorState &other );
static void increment( IteratorState &iterator );
static void decrement( IteratorState &iterator );
static Value &dereference( const IteratorState &iterator );
static Value &unsafeDereference( const IteratorState &iterator );
static int distance( const IteratorState &x, const IteratorState &y );
static ArrayIndex indexOf( const IteratorState &iterator );
void makeBeginIterator( IteratorState &it ) const;
void makeEndIterator( IteratorState &it ) const;
void makeIterator( IteratorState &it, ArrayIndex index ) const;
void makeIndexValid( ArrayIndex index );
Value **pages_;
ArrayIndex size_;
PageIndex pageCount_;
};
/** \brief Experimental: do not use. Allocator to customize Value internal array.
* Below is an example of a simple implementation (actual implementation use
* memory pool).
\code
class DefaultValueArrayAllocator : public ValueArrayAllocator
{
public: // overridden from ValueArrayAllocator
virtual ~DefaultValueArrayAllocator()
{
}
virtual ValueInternalArray *newArray()
{
return new ValueInternalArray();
}
virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other )
{
return new ValueInternalArray( other );
}
virtual void destruct( ValueInternalArray *array )
{
delete array;
}
virtual void reallocateArrayPageIndex( Value **&indexes,
ValueInternalArray::PageIndex &indexCount,
ValueInternalArray::PageIndex minNewIndexCount )
{
ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1;
if ( minNewIndexCount > newIndexCount )
newIndexCount = minNewIndexCount;
void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount );
if ( !newIndexes )
throw std::bad_alloc();
indexCount = newIndexCount;
indexes = static_cast<Value **>( newIndexes );
}
virtual void releaseArrayPageIndex( Value **indexes,
ValueInternalArray::PageIndex indexCount )
{
if ( indexes )
free( indexes );
}
virtual Value *allocateArrayPage()
{
return static_cast<Value *>( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) );
}
virtual void releaseArrayPage( Value *value )
{
if ( value )
free( value );
}
};
\endcode
*/
class JSON_API ValueArrayAllocator
{
public:
virtual ~ValueArrayAllocator();
virtual ValueInternalArray *newArray() = 0;
virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other ) = 0;
virtual void destructArray( ValueInternalArray *array ) = 0;
/** \brief Reallocate array page index.
* Reallocates an array of pointer on each page.
* \param indexes [input] pointer on the current index. May be \c NULL.
* [output] pointer on the new index of at least
* \a minNewIndexCount pages.
* \param indexCount [input] current number of pages in the index.
* [output] number of page the reallocated index can handle.
* \b MUST be >= \a minNewIndexCount.
* \param minNewIndexCount Minimum number of page the new index must be able to
* handle.
*/
virtual void reallocateArrayPageIndex( Value **&indexes,
ValueInternalArray::PageIndex &indexCount,
ValueInternalArray::PageIndex minNewIndexCount ) = 0;
virtual void releaseArrayPageIndex( Value **indexes,
ValueInternalArray::PageIndex indexCount ) = 0;
virtual Value *allocateArrayPage() = 0;
virtual void releaseArrayPage( Value *value ) = 0;
};
#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
/** \brief base class for Value iterators.
*
*/
class ValueIteratorBase
{
public:
typedef unsigned int size_t;
typedef int difference_type;
typedef ValueIteratorBase SelfType;
ValueIteratorBase();
#ifndef JSON_VALUE_USE_INTERNAL_MAP
explicit ValueIteratorBase( const Value::ObjectValues::iterator &current );
#else
ValueIteratorBase( const ValueInternalArray::IteratorState &state );
ValueIteratorBase( const ValueInternalMap::IteratorState &state );
#endif
bool operator ==( const SelfType &other ) const
{
return isEqual( other );
}
bool operator !=( const SelfType &other ) const
{
return !isEqual( other );
}
difference_type operator -( const SelfType &other ) const
{
return computeDistance( other );
}
/// Return either the index or the member name of the referenced value as a Value.
Value key() const;
/// Return the index of the referenced Value. -1 if it is not an arrayValue.
UInt index() const;
/// Return the member name of the referenced Value. "" if it is not an objectValue.
const char *memberName() const;
protected:
Value &deref() const;
void increment();
void decrement();
difference_type computeDistance( const SelfType &other ) const;
bool isEqual( const SelfType &other ) const;
void copy( const SelfType &other );
private:
#ifndef JSON_VALUE_USE_INTERNAL_MAP
Value::ObjectValues::iterator current_;
// Indicates that iterator is for a null value.
bool isNull_;
#else
union
{
ValueInternalArray::IteratorState array_;
ValueInternalMap::IteratorState map_;
} iterator_;
bool isArray_;
#endif
};
/** \brief const iterator for object and array value.
*
*/
class ValueConstIterator : public ValueIteratorBase
{
friend class Value;
public:
typedef unsigned int size_t;
typedef int difference_type;
typedef const Value &reference;
typedef const Value *pointer;
typedef ValueConstIterator SelfType;
ValueConstIterator();
private:
/*! \internal Use by Value to create an iterator.
*/
#ifndef JSON_VALUE_USE_INTERNAL_MAP
explicit ValueConstIterator( const Value::ObjectValues::iterator &current );
#else
ValueConstIterator( const ValueInternalArray::IteratorState &state );
ValueConstIterator( const ValueInternalMap::IteratorState &state );
#endif
public:
SelfType &operator =( const ValueIteratorBase &other );
SelfType operator++( int )
{
SelfType temp( *this );
++*this;
return temp;
}
SelfType operator--( int )
{
SelfType temp( *this );
--*this;
return temp;
}
SelfType &operator--()
{
decrement();
return *this;
}
SelfType &operator++()
{
increment();
return *this;
}
reference operator *() const
{
return deref();
}
};
/** \brief Iterator for object and array value.
*/
class ValueIterator : public ValueIteratorBase
{
friend class Value;
public:
typedef unsigned int size_t;
typedef int difference_type;
typedef Value &reference;
typedef Value *pointer;
typedef ValueIterator SelfType;
ValueIterator();
ValueIterator( const ValueConstIterator &other );
ValueIterator( const ValueIterator &other );
private:
/*! \internal Use by Value to create an iterator.
*/
#ifndef JSON_VALUE_USE_INTERNAL_MAP
explicit ValueIterator( const Value::ObjectValues::iterator &current );
#else
ValueIterator( const ValueInternalArray::IteratorState &state );
ValueIterator( const ValueInternalMap::IteratorState &state );
#endif
public:
SelfType &operator =( const SelfType &other );
SelfType operator++( int )
{
SelfType temp( *this );
++*this;
return temp;
}
SelfType operator--( int )
{
SelfType temp( *this );
--*this;
return temp;
}
SelfType &operator--()
{
decrement();
return *this;
}
SelfType &operator++()
{
increment();
return *this;
}
reference operator *() const
{
return deref();
}
};
} // namespace Json
}
#endif // CPPTL_JSON_H_INCLUDED_HJ
#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
/*
* kk_handleDeviceInfo.cpp
*
* Created on: 2020年11月17日
* Author: hj
*/
#include "kk_handleDeviceInfo.h"
#include "json/writer.h"
#include "json/reader.h"
#include "json/value.h"
#include "EH_ToolKit.h"
#include "LSC_Logger.h"
#include <stdio.h>
#include "KK_Util.h"
#include "MQ_CCU_Adapter.h"
#include "EH_Client.h"
kk_handleDeviceInfo* kk_handleDeviceInfo::ms_pInstance = NULL;
kk_handleDeviceInfo* kk_handleDeviceInfo::GetInstance() {
if (ms_pInstance == NULL) {
ms_pInstance = new kk_handleDeviceInfo();
}
return ms_pInstance;
}
kk_handleDeviceInfo::kk_handleDeviceInfo() {
}
//小K组设备,自动补充设备对应的prodID。
EH::Json::Value kk_handleDeviceInfo::XiaoK_Zu_Wang(string kkDevProductId){
EH::Json::Value devProductinfo;
try {
if (kkDevProductId == "3022"){
devProductinfo["dev_model_id"] = ZeroFire1ChanChopinSwitch_PID;//肖邦一路灯控
devProductinfo["dev_type"] = "400100";
}else if (kkDevProductId == "3023"){
devProductinfo["dev_model_id"] = ZeroFire2ChanChopinSwitch_PID;//肖邦二路灯控
devProductinfo["dev_type"] = "400200";
}else if (kkDevProductId == "3024"){
devProductinfo["dev_model_id"] = ZeroFire3ChanChopinSwitch_PID;//肖邦三路灯控
devProductinfo["dev_type"] = "400300";
}else if (kkDevProductId == "3026"){
devProductinfo["dev_model_id"] = Chopin1CurtainSwitch_PID; //肖邦一路窗帘
devProductinfo["dev_type"] = "410100";
}else if (kkDevProductId == "3027"){
devProductinfo["dev_model_id"] = Chopin2CurtainSwitch_PID; //肖邦二路窗帘
devProductinfo["dev_type"] = "410200";
}else if (kkDevProductId == "3069"){
devProductinfo["dev_model_id"] = ZeroFire2ChanModularSwitch_PID;//两路智能开关模块Z3S(KONKE)
devProductinfo["dev_type"] = "400201";
}else if (kkDevProductId == "3025"){
devProductinfo["dev_model_id"] = Chopin1ChanScenePanel_PID; //肖邦零火一路情景面板
devProductinfo["dev_type"] = "420100";
}else if (kkDevProductId == "3055"){
devProductinfo["dev_model_id"] = WaterSensor_PID; //邦德水浸传感器
devProductinfo["dev_type"] = "440500";
}else if (kkDevProductId == "3054"){
devProductinfo["dev_model_id"] = SOSButton_PID; //邦德紧急按钮
devProductinfo["dev_type"] = "440400";
}else if (kkDevProductId == "3057"){
devProductinfo["dev_model_id"] = SoundLightAlarm_PID; //邦德声光报警器
devProductinfo["dev_type"] = "440300";
}else if (kkDevProductId == "3049"){
devProductinfo["dev_model_id"] = BodyMotionSensor_PID; //KIT人体传感器
devProductinfo["dev_type"] = "440200";
}else if (kkDevProductId == "3051"){
devProductinfo["dev_model_id"] = DoorContact_PID; //邦德门磁传感器
devProductinfo["dev_type"] = "440100";
}else if (kkDevProductId == "3029"){
devProductinfo["dev_model_id"] = WaterHeating_PID ; //肖邦水地暖
devProductinfo["dev_type"] = "450300";
}else if (kkDevProductId == "3030"){
devProductinfo["dev_model_id"] = ElectricHeating_PID; //肖邦电地暖
devProductinfo["dev_type"] = "450301";
}else if (kkDevProductId == "3032"){
devProductinfo["dev_model_id"] = ChopinFreshAir_PID; //肖邦新风控制面板
devProductinfo["dev_type"] = "450200";
}else if (kkDevProductId == "3028"){
devProductinfo["dev_model_id"] = DimmerLightPanel_PID; //肖邦零火线调光面板
devProductinfo["dev_type"] = "430100";
}else if (kkDevProductId == "3031"){
devProductinfo["dev_model_id"] = FanCoilPanel_PID; //肖邦风机盘管面板
devProductinfo["dev_type"] = "450100";
}else if (kkDevProductId == "142"){
devProductinfo["dev_model_id"] = AirConditioner_PID; //肖邦中央空调线控器(大金)
devProductinfo["dev_type"] = "450101";
}else if (kkDevProductId == "3062"){
devProductinfo["dev_model_id"] = DAIKINCentralACgw_PID; //中央空调网关 /中央空调内机 400401 空调内机
devProductinfo["dev_type"] = "450400";
}else {
devProductinfo["dev_model_id"] = "-1";
devProductinfo["dev_type"] = "-1";
LOGW("unknown dev_type Productid:%s \n",kkDevProductId.c_str());
} //当为-1时,这个设备未对接华为。
// LOGD("小K的Productid:%s 对应对接兴海的Productid:%s \n",kkDevProductId.c_str(),devProductid.c_str());
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
return devProductinfo;
}
bool kk_handleDeviceInfo::isValidJoinDeviceType(string kkDevOperateId,string kkDevProductId,string mac){
LOGD("isValidJoinDeviceType kkDevOperateId:%s, kkDevProductId:%s, mac:%s \n",kkDevOperateId.c_str(),kkDevProductId.c_str(),mac.c_str());
try {
if (kkDevOperateId=="3") {
return (kkDevProductId == "3022")||(kkDevProductId == "3023")||(kkDevProductId == "3024");
} else if (kkDevOperateId=="510") {
return (kkDevProductId == "3069");//肖邦-一路窗帘
} else if (kkDevOperateId=="1006") {
return (kkDevProductId == "3026");//肖邦-二路窗帘
} else if (kkDevOperateId=="1007") {
return (kkDevProductId == "3027");//两路智能开关模块Z3S(KONKE)
} else if (kkDevOperateId=="11503") {
return (kkDevProductId == "3025");//肖邦-零火一路情景面板
} else if (kkDevOperateId=="3004") {
return (kkDevProductId == "3055");//邦德-水浸传感器
} else if (kkDevOperateId=="3504") {
return (kkDevProductId == "3054");//邦德-紧急按钮
} else if (kkDevOperateId=="11002") {
return (kkDevProductId == "3057");//邦德-声光报警器
} else if (kkDevOperateId=="3007") {
return (kkDevProductId == "3049");//KIT-人体传感器
} else if (kkDevOperateId=="3497") {
return (kkDevProductId == "3051");//邦德-门磁传感器
} else if (kkDevOperateId=="12504") {
return (kkDevProductId == "3029");//肖邦-水地暖
} else if (kkDevOperateId=="12503") {
return (kkDevProductId == "3030");//肖邦-电地暖
} else if (kkDevOperateId=="14002") {
return (kkDevProductId == "3032");//肖邦-新风控制面板
} else if (kkDevOperateId=="507") {
return (kkDevProductId == "3028");//肖邦-零火线调光面板
} else if (kkDevOperateId=="15002") {
return (kkDevProductId == "3031");//肖邦-风机盘管面板
}else if (kkDevOperateId=="15003") {
return (kkDevProductId == "142");//肖邦-中央空调线控器(大金)
}else if (kkDevOperateId=="12001") {
return (kkDevProductId == "3062");//中央空调网关 /中央空调内机不做类型判断
}
LOGW("invalid join device type,kkDevOperateId:%s,kkDevProductId:%s,.\n",
kkDevOperateId.c_str(),kkDevProductId.c_str());
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
return false;
}
//建立通道设备模型
kk_handleDeviceInfo::KKChannelDev* kk_handleDeviceInfo::buildChannelDevice(string operateId,string nodeId,string channel,EH::Json::Value status,string devroomid,string devname){
LOGD("buildChannelDevice operateId:%s\n nodeId:%s\n channel:%s\n status:%s\n",operateId.c_str(),nodeId.c_str(),channel.c_str(),EH_ToolKit::JsonToString(status).c_str());
//刚上报的status设备信息里有的是没有参数,要做异常处理
kk_handleDeviceInfo::KKChannelDev* chanDev = NULL;
int error;
try {
if(operateId=="1"||operateId=="3"||operateId=="510"){ //灯控 /灯控模块
HwSwitch* light = new HwSwitch();
if(status.isNull() == true){
light->on = (status.asString() == "ON");
}else{
light->on = (status.asString() == "ON");
}
light->devroomid = devroomid;
light->devname = devname;
chanDev = light;
} else if (operateId=="1001"||operateId=="1006"||operateId=="1007") {//窗帘面板
HwCurtain* curtain = new HwCurtain();
string sMode = status.asString();
if (sMode == "OPEN") {
curtain->mode = "1";
} else if (sMode == "CLOSE") {
curtain->mode = "0";
} else if (sMode == "STOP"){
curtain->mode = "2";
}else {
curtain->mode = "0";
LOGW("not support:%s,默认为关.\n", sMode.c_str());
}
curtain->devroomid = devroomid;
curtain->devname = devname;
chanDev = curtain;
} else if (operateId=="11502"||operateId=="11503") {// //铂金情景面板3按键 肖邦情景面板4按键
HwScenePanel* shortcutPanel = new HwScenePanel();
shortcutPanel->num = "switch0";
shortcutPanel->devroomid = devroomid;
shortcutPanel->devname = devname;
chanDev = shortcutPanel;
} else if (operateId == "3004"||operateId == "3007"){//邦德-水浸传感器3004 //邦德-人体传感器3007 (待确认是否合并2020.11.25)
HwSensor* Sensor = new HwSensor();
if(status.isNull() == true){
Sensor->alarm = "0";
Sensor->leftbattery = "100";
}else{
Sensor->alarm = status["alarm"]["normal"].asString();
Sensor->leftbattery = status["battery"].asString();
}
Sensor->devroomid = devroomid;
Sensor->devname = devname;
chanDev = Sensor;
} else if (operateId == "11002"){//邦德-声光11002
HwSensor* Sensor = new HwSensor();
if(status.isNull() == true){
Sensor->alarm = "0";
Sensor->leftbattery = "100";
Sensor->sound = "0";
Sensor->power_style = "1";
}else{
Sensor->alarm = status["alarm"].asString();
Sensor->leftbattery = status["battery"].asString();
Sensor->sound = status["sound"].asString();
Sensor->power_style = status["power"].asString();
}
Sensor->devroomid = devroomid;
Sensor->devname = devname;
chanDev = Sensor;
} else if (operateId == "3504"){//邦德-sos紧急呼叫3504
HwSensor* Sensor = new HwSensor();
if(status.isNull() == true){
Sensor->alarm = "0";
Sensor->leftbattery = "100";
}else{
Sensor->alarm = status["alarm"].asString();
Sensor->leftbattery = status["battery"].asString();
}
Sensor->devroomid = devroomid;
Sensor->devname = devname;
chanDev = Sensor;
} else if (operateId == "3497") {////邦德-门磁传感器3497
HwSensor* Sensor = new HwSensor();
if(status.isNull() == true){
Sensor->alarm = "1";
}else{
Sensor->alarm = status["status"].asString()=="OPEN" ? "1":"0";
}
Sensor->leftbattery = "100";
Sensor->devroomid = devroomid;
Sensor->devname = devname;
chanDev = Sensor;
} else if (operateId == "507") { //肖邦-零火线调光面板
HwDimmerLightPanel* DimmerLightPanel = new HwDimmerLightPanel();
if(status.isNull() == true){
DimmerLightPanel->on = true;
DimmerLightPanel->brightness = "100";
}else{
DimmerLightPanel->on = status["on"].asBool();
DimmerLightPanel->brightness = IntToString(status["bri"].asInt());
}
DimmerLightPanel->devroomid = devroomid;
DimmerLightPanel->devname = devname;
chanDev = DimmerLightPanel;
} else if (operateId == "12503"||operateId == "12504") { //肖邦-水地暖 //肖邦-电地暖
HwWaterElectricHeating* DiNuan = new HwWaterElectricHeating();
if(status.isNull() == true){
DiNuan->on = true;
DiNuan->mode = "1";
DiNuan->target = "100";
DiNuan->current = "100";
}else{
DiNuan->on = status["on"].asBool();
DiNuan->mode = status["run_model"].asString()=="AUTO"? "0":"1";
DiNuan->target = DoubleToString(status["work_temperature"].asDouble()* 10,error);
DiNuan->current = DoubleToString(status["current_real_temperature"].asDouble()* 10,error);
}
DiNuan->devroomid = devroomid;
DiNuan->devname = devname;
chanDev = DiNuan;
} else if (operateId == "14002") { //肖邦-新风控制面板
HwChopinFreshAir* chopinFreshAir = new HwChopinFreshAir();
if(status.isNull() == true){
chopinFreshAir->fan = "1";
chopinFreshAir->on = true ;
chopinFreshAir->mode = 1;
chopinFreshAir->current = "100";
chopinFreshAir->downtime = 0;
chopinFreshAir->totalTime = 4000;
chopinFreshAir->leftTime = 4000;
}else{
chopinFreshAir->fan = IntToString(status["speed"].asInt());
chopinFreshAir->on = status["on"].asBool();
chopinFreshAir->mode = status["runModel"].asString()=="MANUAL" ? 0 : 1;
chopinFreshAir->current = EH_ToolKit::DoubleToString(status["cur_temperature"].asDouble() * 10);
string Stime = status["time_off"].asString();
if(Stime!="00:00"){
chopinFreshAir->downtime = (StringToInt(Stime.substr(0.1), error))*6 + StringToInt(Stime.substr(3.4), error);
}else{
chopinFreshAir->downtime = 0;
}
chopinFreshAir->totalTime = status["filterScreenAlarmTime"].asInt();
chopinFreshAir->leftTime = chopinFreshAir->totalTime - status["filterScreenWorkTime"].asInt();
if (chopinFreshAir->leftTime < 0) {
chopinFreshAir->leftTime = 0;
}
}
chopinFreshAir->devroomid = devroomid;
chopinFreshAir->devname = devname;
chanDev = chopinFreshAir;
} else if (operateId == "15002"||operateId == "15003") { //肖邦-风机盘管面板 //肖邦-大金中央空调线控器(大金)
HwConditionerPanel* FanCoilPanel = new HwConditionerPanel();
if(status.isNull() == true){
FanCoilPanel->on = true ;
FanCoilPanel->fan = "0";
FanCoilPanel->current= "100"; //当前温度 参数注意!!!!!!
FanCoilPanel->target = "100"; //目标温度
FanCoilPanel->mode = "1";
FanCoilPanel->downtime = 0;
FanCoilPanel->enable= true;
}else{
FanCoilPanel->on = status["on"].asBool();
string sSpeed =status["fan_speed"].asString();
if (sSpeed == "AUTO") {
FanCoilPanel->fan = "0";
} else if (sSpeed == "LOW") {
FanCoilPanel->fan = "1";
} else if (sSpeed == "MID") {
FanCoilPanel->fan = "2";
} else if (sSpeed == "HIGH") {
FanCoilPanel->fan = "3";
} else {
LOGW("not support:%s.\n",sSpeed.c_str());
}
FanCoilPanel->current= EH_ToolKit::DoubleToString(status["room_temperature"].asDouble()*10); //当前温度 参数注意!!!!!!
FanCoilPanel->target = EH_ToolKit::DoubleToString(status["setting_temperature"].asDouble()*10); //目标温度
string smode = status["run_model"].asString();
if (smode == "COLD") {
FanCoilPanel->mode = "1";
} else if (smode == "HOT") {
FanCoilPanel->mode = "2";
} else if (smode == "WIND") {
FanCoilPanel->mode = "3";
} else if (smode == "DEHUMIDIFICATION") {
FanCoilPanel->mode = "4";
} else {
LOGW("not support:%s.\n",smode.c_str());
}
string Stime = status["timing_shutdown"]["time"].asString();
if(Stime!=""){
FanCoilPanel->downtime = (StringToInt(Stime.substr(0.1), error))*6 + StringToInt(Stime.substr(3.4), error);
}else{
FanCoilPanel->downtime = 0;
}
FanCoilPanel->enable= status["timing_shutdown"]["enable"].asBool();
}
FanCoilPanel->devroomid = devroomid;
FanCoilPanel->devname = devname;
chanDev = FanCoilPanel;
} else if (operateId == "12001") { //中央空调网关
HwCentralAcgw* centralAc = new HwCentralAcgw();
centralAc->num = 0;
centralAc->devroomid = devroomid;
centralAc->devname = devname;
chanDev = centralAc;
} else if (operateId == "-13") { //情景模式里的内机operateId
HwCentralAcindoor* centralAcindoor = new HwCentralAcindoor();
if(status == ""){
centralAcindoor->on = true ;
centralAcindoor->current = 100;
centralAcindoor->target = 100;
centralAcindoor->fan = "1";
centralAcindoor->mode = 1;
}else{
centralAcindoor->on = status["on"].asBool();
centralAcindoor->current = (status["roomTemperature"].asDouble());
centralAcindoor->target = (status["settingTemperature"].asDouble());
string sSpeed = status["fanSpeed"].asString();
if (sSpeed == "LOW") {
centralAcindoor->fan = "1";
} else if (sSpeed == "MID") {
centralAcindoor->fan = "2";
} else if (sSpeed == "HIGH") {
centralAcindoor->fan = "3";
} else {
LOGW("UNKNOWN style speed");
}
string sModel = status["runModel"].asString();
if (sModel == "AUTO") {
centralAcindoor->mode = 5;
} else if (sModel == "AIR_SUPPLY") {
centralAcindoor->mode = 3;
} else if (sModel == "COLD") {
centralAcindoor->mode = 1;
} else if (sModel == "HOT") {
centralAcindoor->mode = 2;
} else if (sModel == "DEHUMIDIFICATION") {
centralAcindoor->mode = 4;
} else {
LOGW("UNKNOWN style model");
}
}
centralAcindoor->devroomid = devroomid;
centralAcindoor->devname = devname;
chanDev = centralAcindoor;
} else{
LOGW("no device build operateId %s.\n",operateId.c_str());
}
}catch (exception &e) {
LOGW("%s.\n", e.what());
}
if(chanDev!=NULL){
chanDev->channel = channel;
chanDev->nodeId = nodeId;
chanDev->operateId = operateId;
}else{
LOGW("no device build.\n");
}
return chanDev;
}
//添加到房间里
void kk_handleDeviceInfo::addCCuDevicesToRoom(map<string,kk_handleDeviceInfo::HwSubDev*>::iterator&it,map<string,string> NodeId2gwId){
LOGD(" addCCuDevicesToRoom 开始,自动添加到房间\n");
int error;
string roomid = KK_HwDevManager::GetInstance()->GetRoomId();//特定的房间
string dev_model_id = it->second->dev_model_id;
//map<string, KK_HwSdk::HwSubDev*>::iterator subDevIt = hwSubDevs.begin();
try
{
if(dev_model_id == ZeroFire1ChanChopinSwitch_PID || dev_model_id == ZeroFire2ChanChopinSwitch_PID || dev_model_id == ZeroFire3ChanChopinSwitch_PID
|| dev_model_id == ZeroFire2ChanModularSwitch_PID){ //灯控 /灯控模块
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwSwitch* device = (HwSwitch*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "灯控"+IntToString(StringToInt(subIt->second->channel,error));
string DeviceIcon = "l_0";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("灯控设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == Chopin1CurtainSwitch_PID||dev_model_id == Chopin2CurtainSwitch_PID) { //肖邦一路二路窗帘面板
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwCurtain* device = (HwCurtain*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "窗帘面板"+IntToString(StringToInt(subIt->second->channel,error));
string DeviceIcon = "m_0";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("窗帘面板设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == Chopin1ChanScenePanel_PID) { //肖邦-情景面板
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwScenePanel* device = (HwScenePanel*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "快捷按键设备";
string DeviceIcon = "q_0";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("快捷按键设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == WaterSensor_PID) { //邦德-水浸传感器
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwSensor* device = (HwSensor*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "水浸探测器";
string DeviceIcon = "t_16";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("水浸探测器设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == BodyMotionSensor_PID) { //KIT-人体传感器
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwSensor* device = (HwSensor*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "人体传感器";
string DeviceIcon = "t_2";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("人体传感器设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == DoorContact_PID) { //邦德-门窗传感器
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwSensor* device = (HwSensor*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "门窗传感器";
string DeviceIcon = "t_3";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("门窗传感器设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == SOSButton_PID) { //邦德-sos紧急呼叫
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwSensor* device = (HwSensor*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "SOS按钮";
string DeviceIcon = "SOS";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("SOS按钮设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == SoundLightAlarm_PID) { //邦德-声光报警器
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwSensor* device = (HwSensor*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "声光报警器";
string DeviceIcon = "icon_edit_alarm_bangde";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("声光报警器 设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == DimmerLightPanel_PID) { //肖邦-调光面板
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwDimmerLightPanel* device = (HwDimmerLightPanel*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "肖邦调光面板";
string DeviceIcon = "l_0";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("肖邦调光面板设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == WaterHeating_PID||dev_model_id == ElectricHeating_PID) { //肖邦-水地暖 肖邦-电地暖
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwWaterElectricHeating* device = (HwWaterElectricHeating*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "地暖设备";
string DeviceIcon = "icon_xinf_s";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("地暖设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == ChopinFreshAir_PID) { //肖邦-新风控制面板
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwChopinFreshAir* device = (HwChopinFreshAir*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "新风控制面板";
string DeviceIcon = "icon_xinf_s";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("新风控制面板设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == FanCoilPanel_PID) { //肖邦-风机盘管面板
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwConditionerPanel* device = (HwConditionerPanel*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "肖邦风机盘管面板";
string DeviceIcon = "ac";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("肖邦风机盘管面板设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == AirConditioner_PID) { //肖邦-中央空调线控器(大金)
for (map<string,kk_handleDeviceInfo::KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwConditionerPanel* device = (HwConditionerPanel*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
if(device->devroomid == "-1"){
string name = "大金中央空调线控器";
string DeviceIcon = "ac";
string DevDodeId = subIt->second->nodeId;
string opcode = "SETUP_NODE";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
LOGD("肖邦中央空调线控器nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}else{
continue;
}
}
} else if (dev_model_id == DAIKINCentralACindoor_PID) { //四期 肖邦中央空调内机
map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.find("1");
HwCentralAcindoor* device = (HwCentralAcindoor*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
LOGD("空调内机devroomid:%s\n",device->devroomid.c_str());
if(device->devroomid == "-1"){
string DevDodeId = subIt->second->nodeId;
string name = "中央空调内机";
string DeviceIcon = "ac";
string opcode = "SET_CENTRAL_AC_INDOOR_UNIT";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
subIt->second->devroomid = roomid;
LOGD("中央空调内机设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}
} else if (dev_model_id == DAIKINCentralACgw_PID) { //四期 空调网关
map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.find("1");
HwCentralAcgw* device = (HwCentralAcgw*)it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
LOGD("中央空调网关设备 devroomid:%s\n",device->devroomid.c_str());
if(device->devroomid == "-1"){
string DevDodeId;
map<string,string>::iterator gwIt = NodeId2gwId.find(subIt->second->nodeId); //NodeId2gwId gwId2NodeId
if(gwIt == NodeId2gwId.end()){
LOGW("centralACnodeId:%s not in gwId2NodeId.\n",subIt->second->nodeId.c_str());
} else {
DevDodeId = gwIt->second;
}
string name = "中央空调网关";
string DeviceIcon = "ac"; //无效参数,补全格式
// string DevDodeId = subIt->second->nodeId;
string opcode = "SET_CENTRAL_AC_GW";
MQ_CCU_Adapter::GetInstance()->SendSETUPToCcu( name,DeviceIcon,DevDodeId,roomid,opcode);
subIt->second->devroomid = roomid;
LOGD("中央空调网关设备nodeID:%s 自动添加到房间roomid:%s \n",device->nodeId.c_str(),roomid.c_str());
}
} else{
LOGW("dev_model_id:%s not .\n",dev_model_id.c_str());
}
} catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
//下发控制命令
int kk_handleDeviceInfo::onSetDevService(map<string,kk_handleDeviceInfo::HwSubDev*>&hwSubDevs,string sn,string channel,string svcId,EH::Json::Value cmd){
LOGD("onSetDevService sn:%s channel:%s svcId:%s cmd:%s . \n",sn.c_str(),channel.c_str(),svcId.c_str(),cmd.toStyledString().c_str());
map<string, HwSubDev*>::iterator subDevIt = hwSubDevs.find(sn);
if(subDevIt == hwSubDevs.end()){
LOGW("not found hw dev sn:%s in local cache.\n",sn.c_str());
return -1;
}
int error;
string jsonarg = "";
string opcode = "";
string nodeid = "*";
string arg = "*";
string dev_model_id = subDevIt->second->dev_model_id;
EH::Json::Value::Members members(cmd.getMemberNames());
for (EH::Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it) {
jsonarg = *it;
}
LOGD("prodId:%s . \n",dev_model_id.c_str());
try {
if(dev_model_id == ZeroFire1ChanChopinSwitch_PID||dev_model_id == ZeroFire2ChanChopinSwitch_PID||dev_model_id == ZeroFire3ChanChopinSwitch_PID
|| dev_model_id == ZeroFire2ChanModularSwitch_PID){ //灯控 /灯控模块
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
bool on = true;
on = cmd["State"].asString() == "1";
if(chanDev!=NULL){
opcode = "SWITCH";
nodeid = chanDev->nodeId;
arg = on?"ON":"OFF";
}
} else if (dev_model_id == Chopin1CurtainSwitch_PID|| dev_model_id == Chopin2CurtainSwitch_PID) { //肖邦一路二路窗帘面板
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
string mode;
string sMode;
mode = cmd["Operate"].asString();
if (mode == "1") {
sMode = "OPEN";
} else if (mode == "0"){
sMode = "CLOSE";
} else if (mode == "2"){
sMode = "STOP";
} else {
LOGW("not support type:%s.\n",mode.c_str());
return -1;
}
if(chanDev!=NULL){
opcode = "SWITCH";
nodeid = chanDev->nodeId;
arg = sMode;
}
} else if (dev_model_id == SoundLightAlarm_PID) { //邦德-声光报警器
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
string mode;
string sMode;
EH::Json::Value::Members members(cmd.getMemberNames());
for (EH::Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it) {
jsonarg = *it;
}
if(jsonarg == "Sound"){
if(chanDev!=NULL){
opcode = "ADJUST_VOLUME";
nodeid = chanDev->nodeId;
arg = cmd["Sound"].asString();
}
}else{}
} else if (dev_model_id == ChopinFreshAir_PID) { //肖邦-新风控制面板
string channel = "0";
if (jsonarg == "On") {
channel = "1";
bool on = cmd["On"].asString() == "1";
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FRESH_AIR_SWITCH";
nodeid = chanDev->nodeId;
arg = on?"ON":"OFF";
}
} else if (jsonarg == "Mode") {
channel = "1";
string mode = cmd["Mode"].asString();
if (mode == "0") {
arg = "MANUAL";
} else if (mode == "1") {
arg = "AUTO";
} else {
LOGW("not found svcId:%s.\n", mode.c_str());
return -1;
}
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FRESH_AIR_RUN_MODEL";
nodeid = chanDev->nodeId;
}
} else if (jsonarg == "Wind_num") {
channel = "1";
string fan = cmd["Wind_num"].asString();
if (fan == "1") {
arg = "LOW";
} else if (fan == "2") {
arg = "MID";
} else if (fan == "3") {
arg = "HIGH";
} else {
LOGW("not found svcId:%s.\n", fan.c_str());
return -1;
}
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FRESH_AIR_SPEED_SET";
nodeid = chanDev->nodeId;
}
} else if (jsonarg == "SwitchChildLock") {
channel = "1";
bool bChildLock = cmd["SwitchChildLock"].asString() == "1";
EH::Json::Value childLockArg;
if (bChildLock) {
childLockArg["model_lock"] = true;
childLockArg["child_lock"] = true;
childLockArg["time_lock"] = true;
childLockArg["switch_lock"] = true;
childLockArg["rotate_lock"] = true;
}else{
childLockArg["model_lock"] = false;
childLockArg["child_lock"] = false;
childLockArg["time_lock"] = false;
childLockArg["switch_lock"] = false;
childLockArg["rotate_lock"] = false;
}
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FRESH_AIR_SET_LOCK_STATUS";
nodeid = chanDev->nodeId;
arg = childLockArg.toStyledString();
}
} else if (jsonarg == "Query_Action") { //查询状态动作
channel = "1";
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL ){
opcode = "FRESH_AIR_GET_CONFIG_ARGS";
nodeid = chanDev->nodeId;
arg = "*";
}
} else if (jsonarg == "TotalTime_FilterElement") {
channel = "1";
EH::Json::Value filter;
filter["resetWorktime"] = false;
filter["alarmTime"] = EH_ToolKit::StringToInt(cmd["TotalTime_FilterElement"].asString());
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FRESH_AIR_SET_FILTER_SCREEN_TIME";
nodeid = chanDev->nodeId;
arg = filter.toStyledString();
}
} else if (jsonarg == "Reset_FilterElement") {
channel = "1";
EH::Json::Value filter;
filter["resetWorktime"] = true;
filter["alarmTime"] = 65535; //65535 表示不改变
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FRESH_AIR_SET_FILTER_SCREEN_TIME";
nodeid = chanDev->nodeId;
arg = filter.toStyledString();
}
} else if (jsonarg == "Time_AutoOff") {
channel = "1";
string bLight = "";
string timehour = EH_ToolKit::IntToString(EH_ToolKit::StringToInt(cmd["Time_AutoOff"].asString())/60);//( cmd["Time_AutoOff"].asInt())/60;
string timeminute = EH_ToolKit::IntToString(EH_ToolKit::StringToInt(cmd["Time_AutoOff"].asString())%60);//( cmd["Time_AutoOff"].asInt())%60;
LOGD("timehour:%s timeminute:%s.\n",timehour.c_str(),timeminute.c_str());
EH::Json::Value timing_switch;
if (timeminute == "0"){
timing_switch = timehour + ":00";
}else{
timing_switch = timehour + ":30";
}
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FRESH_AIR_SET_TIME_OFF";
nodeid = chanDev->nodeId;
arg = timing_switch.toStyledString();
}
} else {
LOGW("not found svcId:%s.\n",jsonarg.c_str());
return -1;
}
} else if (dev_model_id == DimmerLightPanel_PID) { //肖邦-调光灯面板
string channel = "0";
if (jsonarg == "On") {
channel = "1";
bool on = cmd["On"].asString() == "1";
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "SWITCH";
nodeid = chanDev->nodeId;
arg = on?"ON":"OFF";
}
} else if (jsonarg == "Brightness") {
channel = "1";
string brightness = cmd["Brightness"].asString();
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "ADJUST_LUMINANCE";
nodeid = chanDev->nodeId;
arg = brightness;
}
} else if (jsonarg == "Query_Action") {
channel = "1";
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL ){
opcode = "GET_DIMMABLE_LIGHT_CONFIG";
nodeid = chanDev->nodeId;
arg = "*";
}
} else if (jsonarg == "FadeTime") {
channel = "1";
HwDimmerLightPanel* device = (HwDimmerLightPanel*)subDevIt->second->channelDevs[channel];
device->time = cmd["FadeTime"].asString();
EH::Json::Value childLockArg;
childLockArg["ilumHighValue"] = 100;
childLockArg["ilumLowValue"] = 10;
childLockArg["softOnValue"] = EH_ToolKit::StringToInt(cmd["FadeTime"].asString())*10;
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "SET_DIMMABLE_LIGHT_CONFIG";
nodeid = chanDev->nodeId;
arg = childLockArg.toStyledString();
}
} else {
LOGW("not found svcId:%s.\n",jsonarg.c_str());
return -1;
}
} else if(dev_model_id == WaterHeating_PID||dev_model_id == ElectricHeating_PID) { //肖邦-水地暖 //肖邦-电地暖
string channel = "1";
bool on = true;
if(jsonarg == "On"){ //地暖开关
on = cmd["On"].asString() == "1";
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "SWITCH";
nodeid = chanDev->nodeId;
arg = on?"ON":"OFF";
}
} else if(jsonarg == "Temperature") { //地暖设置工作温度(手动模式下)
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "SET_WORK_TEMPERATURE";
nodeid = chanDev->nodeId;
double filter;
double t2 = 10;
float t1 = EH_ToolKit::StringToDouble(cmd["Temperature"].asString());
filter = t1/t2;
arg = DoubleToString(filter,error);
}
} else if (jsonarg == "Mode"){ //工作模式,自动 手动
bool workmodel = cmd["Mode"].asString() == "1";
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "SET_WORK_MODEL"; //切换工作模式的报文
nodeid = chanDev->nodeId;
arg = workmodel?"AUTO":"MANUAL"; //模式
}
} else if (jsonarg == "Query_Action"){
channel = "1";
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL ){
opcode = "FLOOR_HEATING_GET_CONFIG_ARGS";
nodeid = chanDev->nodeId;
arg = "*";
}
} else if (jsonarg == "SwitchChildLock") {
channel = "1";
bool bChildLock = cmd["SwitchChildLock"].asString() == "1";
EH::Json::Value childLockArg;
if (bChildLock) {
childLockArg["model_lock"] = true;
childLockArg["child_lock"] = true;
childLockArg["time_lock"] = true;
childLockArg["switch_lock"] = true;
childLockArg["rotate_lock"] = true;
}else{
childLockArg["model_lock"] = false;
childLockArg["child_lock"] = false;
childLockArg["time_lock"] = false;
childLockArg["switch_lock"] = false;
childLockArg["rotate_lock"] = false;
}
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FLOOR_HEATING_SET_LOCK_STATUS";
nodeid = chanDev->nodeId;
arg = childLockArg.toStyledString();
}
} else{
LOGW("not found svcId:%s.\n",jsonarg.c_str());
return -1;
}
} else if (dev_model_id == FanCoilPanel_PID||dev_model_id == AirConditioner_PID) { //四期 肖邦风机盘管面板 肖邦中央空调线控器(大金)
string channel = "0";
if (jsonarg == "On") {
channel = "1";
bool on = cmd["On"].asString() == "1";
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "SWITCH";
nodeid = chanDev->nodeId;
arg = on?"ON":"OFF";
}
} else if (jsonarg == "Pattern") {
channel = "1";
string mode = cmd["Pattern"].asString();
if (mode == "1") {
arg = "COLD";
} else if (mode == "2") {
arg = "HOT";
}else if (mode == "3") {
arg = "WIND";
}else if (mode == "4") {
arg = "DEHUMIDIFICATION"; //只有肖邦中央空调线控器上有这个功能。
} else {
LOGW("not found mode:%s.\n", mode.c_str());
return -1;
}
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FAN_COIL_SET_RUN_MODEL";
nodeid = chanDev->nodeId;
}
} else if (jsonarg == "Wind_num") {
channel = "1";
string fan = cmd["Wind_num"].asString();
if (fan == "0") {
arg = "AUTO";
} else if (fan == "1") {
arg = "LOW";
} else if (fan == "2") {
arg = "MID";
} else if (fan == "3") {
arg = "HIGH";
} else {
LOGW("not found fan:%s.\n", fan.c_str());
return -1;
}
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FAN_COIL_SET_FUN_SPEED";
nodeid = chanDev->nodeId;
}
} else if (jsonarg == "SwitchChildLock") {
channel = "1";
bool bChildLock = cmd["SwitchChildLock"].asString() == "1";
EH::Json::Value childLockArg;
childLockArg["model_lock"] = false;
childLockArg["speed_lock"] = false;
childLockArg["time_lock"] = false;
childLockArg["switch_lock"] = false;
childLockArg["rotate_lock"] = false;
if (bChildLock) {
childLockArg["model_lock"] = true;
childLockArg["speed_lock"] = true;
childLockArg["time_lock"] = true;
childLockArg["switch_lock"] = true;
childLockArg["rotate_lock"] = true;
}
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FAN_COIL_SET_LOCK_STATUS";
nodeid = chanDev->nodeId;
arg = childLockArg.toStyledString();
}
} else if (jsonarg == "Query_Action") {
channel = "1";
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL ){
opcode = "FAN_COIL_GET_CONFIG_ARGS";
nodeid = chanDev->nodeId;
arg = "*";
}
} else if (jsonarg == "Time_AutoOff") {
channel = "1";
string bLight;
string timehour = EH_ToolKit::IntToString(EH_ToolKit::StringToInt(cmd["Time_AutoOff"].asString())/60);//( cmd["Time_AutoOff"].asInt())/60;
string timeminute = EH_ToolKit::IntToString(EH_ToolKit::StringToInt(cmd["Time_AutoOff"].asString())%60);//( cmd["Time_AutoOff"].asInt())%60;
LOGD("timehour:%s timeminute:%s.\n",timehour.c_str(),timeminute.c_str());
EH::Json::Value timing;
timing["enable"] = false;
timing["time"] = "00:00";
EH::Json::Value timing_switch;
timing_switch["timing_boot"] = timing;
if (timeminute == "0"){
bLight = timehour+":00";
}else{
bLight = timehour+":30";
}
timing["enable"] = bLight!="0:00"? true : false;
timing["time"] = bLight;
timing_switch["timing_shutdown"] = timing;
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FAN_COIL_SET_DELAY_SWITCH_TASK";
nodeid = chanDev->nodeId;
arg = timing_switch.toStyledString();
}
} else if (jsonarg == "Temperature") {
channel = "1";
double filter;
double t2 = 10;
float t1 = EH_ToolKit::StringToDouble(cmd["Temperature"].asString());//jsonObject["target"].asDouble();
filter = t1/t2;
KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
if(chanDev!=NULL){
opcode = "FAN_COIL_SET_TEMPERATURE";
nodeid = chanDev->nodeId;
arg = DoubleToString(filter,error);
}
}
else {
LOGW("not found svcId:%s.\n",jsonarg.c_str());
return -1;
}
} else if (dev_model_id == DAIKINCentralACindoor_PID) { //中央空调内机(四期调整)
KKChannelDev* chanDev = subDevIt->second->channelDevs["1"];
HwCentralAcindoor* device = (HwCentralAcindoor*)subDevIt->second->channelDevs["1"];
nodeid = chanDev->nodeId;
EH::Json::Value contronlSet = centralACStatusToSet(device->fan,device->on,device->mode,device->target);
if (jsonarg == "On") {
bool on = cmd["On"].asString() == "1";
if(chanDev!=NULL){
opcode = "CENTRAL_AC_INDOOR_UNIT_SETTING";
contronlSet["on"] = on;
arg = contronlSet.toStyledString();
}
} else if (jsonarg == "Pattern") {
string mode = cmd["Pattern"].asString();
if(chanDev!=NULL){
opcode = "CENTRAL_AC_INDOOR_UNIT_SETTING";
contronlSet["runModel"] = mode;
if ("5" == mode) {
contronlSet["runModel"] = "AUTO";
} else if ("1" == mode) {
contronlSet["runModel"] = "COLD";
} else if ("2" == mode) {
contronlSet["runModel"] = "HOT";
} else if ("3" == mode) {
contronlSet["runModel"] = "AIR_SUPPLY";
} else if ("4" == mode) {
contronlSet["runModel"] = "DEHUMIDIFICATION";
} else {
LOGW("not suppert set runModel style\n");
}
arg = contronlSet.toStyledString();
}
} else if (jsonarg == "Wind_num") {
string speed = cmd["Wind_num"].asString();
if(chanDev!=NULL){
opcode = "CENTRAL_AC_INDOOR_UNIT_SETTING";
contronlSet["fanSpeed"] = speed;
if ("1" == speed) {
contronlSet["fanSpeed"] = "LOW";
} else if ("2" == speed) {
contronlSet["fanSpeed"] = "MID";
} else if ("3" == speed) {
contronlSet["fanSpeed"] = "HIGH";
} else {
LOGW("not suppert set WindSpeed style\n");
}
arg = contronlSet.toStyledString();
}
} else if(jsonarg == "Temperature") { //设置工作温度
if(chanDev!=NULL){
opcode = "CENTRAL_AC_INDOOR_UNIT_SETTING";
nodeid = chanDev->nodeId;
double filter;
float t1 = EH_ToolKit::StringToDouble(cmd["Temperature"].asString());
double t2 =10;
filter = t1/t2;
contronlSet["settingTemperature"] = filter;
arg = contronlSet.toStyledString();
}
}
/*
EH::Json::Value::Members keys = jsonObject.getMemberNames(); ///将所有内机放到一个设备下的多通道设备。通过属性后两位代表通道来进行区别;
for (int j = 0; j < keys.size(); j++) {
string strKey = keys[j];
channel = strKey.substr(strKey.size() - 2, 2);
double temperature = jsonObject[strKey].asDouble();
KK_HwSdk::KKChannelDev* chanDev = subDevIt->second->channelDevs[IntToString(StringToInt(channel,error))];
if(chanDev!=NULL){
opcode = "CENTRAL_AC_INDOOR_UNIT_SETTING";
nodeid = chanDev->nodeId;
// string contronl = KK_CcuConfig::GetInstance()->getCentralAcStatus(chanDev->nodeId);
EH::Json::Value contronlSet = centralACStatusToSet(contronl);
contronlSet["settingTemperature"] = temperature;
arg = contronlSet.toStyledString();
}
}
*/
// }
// else if (dev_model_id == SOSButton_PID) { //邦德-sos紧急呼叫 //待定
// string channel= "0";
// //bool on = true;
// if(svcId == "pushButton"){
// channel = "1";
// } else {
// LOGW("not found svcId:%s.\n",svcId.c_str());
// return -1;
// }
// //on = 0;
// KKChannelDev* chanDev = subDevIt->second->channelDevs[channel];
// if(chanDev!=NULL){
// opcode = "CLEAR_SOS_ALARM";
// nodeid = chanDev->nodeId;
// arg = "*";
// }
// //默认返回成功,同时将命令下发下去
// if (dev_model_id == SOSButton_PID) { ////四期 控客-SOS按钮
// HwSensor* device = (HwSensor*)subDevIt->second->channelDevs[channel];
// device->alarm = false;
// string msg = "{\"on\":"+IntToString(device->alarm)+"}";EH::Json::Value event;
// }
}
} catch (exception &e) {
LOGW("%s.\n", e.what());
}
if(opcode!=""){
EH::Json::Value json;
json["opcode"] = opcode;
json["nodeid"] = nodeid;
json["arg"] = arg;
if (dev_model_id == DAIKINCentralACindoor_PID) { //中央空调内机
json["requester"] = "HJ_CentralAC";
}else if(opcode == "SETUP_NODE"){
json["requester"] = "HJ_Config";
} else{
json["requester"] = "HJ_Server";
}
string wholeMsg = EH_ToolKit::JsonToString(json);
if(MQ_CCU_Adapter::GetInstance()->send_Control_Info(wholeMsg) != 0){
LOGW("Send msg to IotHandler failed.msg is %s\n",wholeMsg.c_str());
}
}else{
LOGW("dev:%s not support set property. \n",sn.c_str());
return -1;
}
return 0;
}
EH::Json::Value kk_handleDeviceInfo::centralACStatusToSet(string fanSpeed,bool on,int runModel,int settingTemperature) {
LOGI("centralACStatusToSet , fanSpeed:%s runModel:%d \n",fanSpeed.c_str(),runModel);
EH::Json::Value contronlSet;
if ("1" == fanSpeed) {
contronlSet["fanSpeed"] = "LOW";
} else if ("2" == fanSpeed) {
contronlSet["fanSpeed"] = "MID";
} else if ("3" == fanSpeed) {
contronlSet["fanSpeed"] = "HIGH";
} else {
LOGW("not suppert set WindSpeed style\n");
}
if (5 == runModel) {
contronlSet["runModel"] = "AUTO";
} else if (1 == runModel) {
contronlSet["runModel"] = "COLD";
} else if (2 == runModel) {
contronlSet["runModel"] = "HOT";
} else if (3 == runModel) {
contronlSet["runModel"] = "AIR_SUPPLY";
} else if (4 == runModel) {
contronlSet["runModel"] = "DEHUMIDIFICATION";
} else {
LOGW("not suppert set runModel style runModel:%d\n",runModel);
}
contronlSet["on"] = on;
contronlSet["settingTemperature"] = settingTemperature;//contronlStatus["settingTemperature"].asDouble();
return contronlSet;
}
//更改设备状态信息
void kk_handleDeviceInfo::handleDeviceStatusChanged(map<string,kk_handleDeviceInfo::HwSubDev*>&hwSubDevs,map<string,string>&nodeId2channelMap,string nodeId,string opcode,EH::Json::Value arg,string pushTopic,string gw_id){
LOGI("handleDeviceStatusChanged , nodeId:%s opcode:%s \n arg:%s.\n",nodeId.c_str(),opcode.c_str(),EH_ToolKit::JsonToString(arg).c_str());
map<string,string>::iterator it = nodeId2channelMap.find(nodeId);
if(it == nodeId2channelMap.end()){
LOGW("nodeid:%s not in nodeId2channelMap.\n",nodeId.c_str());
return;
}
int error;
vector<string> chanMac;
Split(it->second,"_",chanMac);
string sn = Replace(chanMac[0],":","");
string channel = chanMac[1];
map<string,HwSubDev*>::iterator subDevIt = hwSubDevs.find(sn);
if(subDevIt == hwSubDevs.end()){
LOGW("dev:%s not in hwSubDevs.\n",sn.c_str());
return;
}
string respTopic = pushTopic+"/devicestatechange";//设备状态变化上报
string dev_model_id = subDevIt->second->dev_model_id;
string devType = subDevIt->second->devTypeId;
EH::Json::Value payload;
EH::Json::Value msgstate0;
payload["gw_id"] = gw_id; //请求发起者
payload["dev_id"] = sn;
payload["dev_type"] = subDevIt->second->dev_model_id;
payload["dev_ep_id"] = StringToInt(channel,error); //通道
LOGD("设备信息 dev_model_id:%s sn:%s channel:%s \n",dev_model_id.c_str(),sn.c_str(),channel.c_str());
try {
if(dev_model_id == ZeroFire1ChanChopinSwitch_PID || dev_model_id == ZeroFire2ChanChopinSwitch_PID || dev_model_id == ZeroFire3ChanChopinSwitch_PID
|| dev_model_id == ZeroFire2ChanModularSwitch_PID){ //灯控 /灯控模块
HwSwitch* device = (HwSwitch*)subDevIt->second->channelDevs[channel];
if(opcode == "SWITCH"){
if(device->on != (arg.asString()=="ON")){ //状态不改变不进行推送
device->on = arg.asString()=="ON";
if(arg.asString()=="ON"){
msgstate0["State"] = "1";
}else{
msgstate0["State"] = "0";
}
payload["state"] = msgstate0;
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
}else if(opcode == "SETUP_NODE"){
}
} else if (dev_model_id == Chopin1CurtainSwitch_PID||dev_model_id == Chopin2CurtainSwitch_PID) {//窗帘面板
HwCurtain* device = (HwCurtain*)subDevIt->second->channelDevs[channel];
if(opcode == "SWITCH"){
string CurtainMode;
string sMode = arg.asString();
if (sMode == "OPEN") {
CurtainMode = "1";
} else if (sMode == "CLOSE") {
CurtainMode = "0";
} else if (sMode == "STOP") {
CurtainMode = "2";
}
if(device->mode != CurtainMode){
device->mode = CurtainMode;
msgstate0["Operate"] = CurtainMode;
payload["state"] = msgstate0;
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
}else if(opcode == "SETUP_NODE"){
}
} else if (dev_model_id == Chopin1ChanScenePanel_PID) { // 长供电(肖邦-情景面板)
HwScenePanel* device = (HwScenePanel*)subDevIt->second->channelDevs[channel];
if(opcode == "SHORTCUT_PANEL_ACTIVE"){
device->num = "switch"+arg.asString();
msgstate0["KeyValue"] = device->num;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}else if(opcode == "SETUP_NODE"){
}
} else if (dev_model_id == DoorContact_PID ||dev_model_id == BodyMotionSensor_PID||dev_model_id == WaterSensor_PID) { //邦德-门磁 KIT-人体 邦德-水浸
HwSensor* device = (HwSensor*)subDevIt->second->channelDevs[channel];
if (opcode == "SENSOR_BOOL") {
if (device->alarm != arg.asString()) {
LOGD("judge old alarm: %s, new alarm: %s",device->alarm.c_str(),arg.asString().c_str());
device->alarm = arg.asString();
msgstate0["Alarm"] = device->alarm;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
} else if (opcode == "SENSOR_BOOL_STATUS") {
if (device->leftbattery != arg["battery"].asString()) {
LOGD("judge old level: %s, new level: %s",device->leftbattery.c_str(), arg["battery"].asString().c_str());
device->leftbattery = arg["battery"].asString();
msgstate0["battery"] = device->leftbattery;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 2; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
} else if(opcode == "SETUP_NODE"){
}
} else if (dev_model_id == SOSButton_PID) { //邦德-SOS紧急按钮
HwSensor* device = (HwSensor*)subDevIt->second->channelDevs[channel];
if (opcode == "SOS_STATUS") { //(SOS紧急按钮状态)
if (device->alarm != arg["alarm"].asString()) {
LOGD("judge old alarm: %s, new alarm: %s",device->alarm.c_str(),arg["alarm"].asString().c_str());
device->alarm = arg["alarm"].asString();
msgstate0["Alarm"] = device->alarm;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
if (device->leftbattery != arg["battery"].asString()) {
LOGD("judge old level: %s, new level: %s",device->leftbattery.c_str(),arg["battery"].asString().c_str());
device->leftbattery = arg["battery"].asString();
EH::Json::Value msgstate1;
msgstate1["battery"] = device->leftbattery;
payload["state"] = msgstate1;
payload["dev_ep_id"] = 2; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
} else if(opcode == "SETUP_NODE"){
}
} else if (dev_model_id == SoundLightAlarm_PID) { //邦德-声光报警器
HwSensor* device = (HwSensor*)subDevIt->second->channelDevs[channel];
if (opcode == "ZIGBEE_ALERTOR_STATUS") { //Zigbee报警器状态)
if (device->alarm != arg["alarm"].asString()) {
LOGD("judge old alarm: %s, new alarm: %s",device->alarm.c_str(),arg["alarm"].asString().c_str());
device->alarm = arg["alarm"].asString();
msgstate0["Alarm"] = device->alarm;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
if (device->leftbattery != arg["battery"].asString()) {
LOGD("judge old level: %s, new level: %s",device->leftbattery.c_str(),arg["battery"].asString().c_str());
device->leftbattery = arg["battery"].asString();
EH::Json::Value msgstate1;
msgstate1["battery"] = device->leftbattery;
payload["state"] = msgstate1;
payload["dev_ep_id"] = 2; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
if (device->power_style != arg["power"].asString()) {
LOGD("judge old power_style: %s, new power_style: %s",device->power_style.c_str(),arg["power"].asString().c_str());
device->power_style = arg["power"].asString();
EH::Json::Value msgstate2;
msgstate2["power_style"] = device->power_style;
payload["state"] = msgstate2;
payload["dev_ep_id"] = 3; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
if (device->sound != arg["battery"].asString()) {
LOGD("judge old sound: %s, new sound: %s",device->sound.c_str(),arg["sound"].asString().c_str());
device->sound = arg["sound"].asString();
EH::Json::Value msgstate3;
msgstate3["Sound"] = device->sound;
payload["state"] = msgstate3;
payload["dev_ep_id"] = 4; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
} else if(opcode == "SETUP_NODE"){
}
} else if (dev_model_id == DimmerLightPanel_PID) { //控客-肖邦调光面板
HwDimmerLightPanel* device = (HwDimmerLightPanel*)subDevIt->second->channelDevs[channel];
if(opcode == "DIMMABLE_LIGHT_STATUS"){
if(device->on != arg["on"].asBool()){
device->on = arg["on"].asBool();
if(device->on){
msgstate0["On"] = "1";
}else{
msgstate0["On"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
if(device->brightness != IntToString(arg["bri"].asInt())){
device->brightness = IntToString(arg["bri"].asInt());
EH::Json::Value msgstate3;
msgstate3["Brightness"] = device->brightness;
payload["state"] = msgstate3;
payload["dev_ep_id"] = 2; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
} else if (opcode == "GET_DIMMABLE_LIGHT_CONFIG") { //
device->time = IntToString(arg["softOnValue"].asInt()/10);
msgstate0["FadeTime"] = device->time;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 4; //功能映射为通道4
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "SET_DIMMABLE_LIGHT_CONFIG") { //
msgstate0["FadeTime"] = device->time;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 4; //功能映射为通道4
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if(opcode == "SETUP_NODE"){
}
} else if (dev_model_id == WaterHeating_PID||dev_model_id == ElectricHeating_PID){ //肖邦-水地暖 肖邦-电地暖
HwWaterElectricHeating* device = (HwWaterElectricHeating*)subDevIt->second->channelDevs[channel];
if(opcode == "SWITCH"){ //远程反馈
device->on = arg.asString()=="ON";
if(device->on){
msgstate0["On"] = "1";
}else{
msgstate0["On"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if(opcode == "SET_WORK_MODEL"){ //设置工作模式
if(arg.asString()=="MANUAL"){ //MANUAL(手动模式),AUTO(自动模式)。
device->mode = "0";
}else{
device->mode = "1";
}
msgstate0["Mode"] = device->mode;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 2; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FLOOR_HEATING_SET_LOCK_STATUS") {
device->childLockSwitch = arg["switch_lock"].asString() == "true";
if(device->childLockSwitch){
msgstate0["SwitchChildLock"] = "1";
}else{
msgstate0["SwitchChildLock"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 3; //功能映射为通道4
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FLOOR_HEATING_GET_CONFIG_ARGS") {
device->childLockSwitch = arg["lock_status"]["switch_lock"].asString() == "true";
if(device->childLockSwitch){
msgstate0["SwitchChildLock"] = "1";
}else{
msgstate0["SwitchChildLock"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 3; //功能映射为通道4
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if(opcode == "SET_WORK_TEMPERATURE"){ //设置工作温度
device->target = DoubleToString(arg.asDouble() * 10,error);
msgstate0["Temperature"] = device->target;
msgstate0["Current_Temperature"] = device->current;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 4; //功能映射为通道3
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}else if(opcode == "FLOOR_HEATING_DEV_STATUS"){ //本地状态改变上报推送 FLOOR_HEATING_DEV_STATUS
//开关
if(arg["on"].asBool() != device->on){
device->on = arg["on"].asBool();
if(device->on){
msgstate0["On"] = "1";
}else{
msgstate0["On"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
//工作模式
if(device->mode != (arg["run_model"].asString() == "MANUAL"?"0":"1")){
if(arg["run_model"].asString() == "MANUAL"){ //MANUAL(手动模式),AUTO(自动模式)。
device->mode = "0";
}else{
device->mode = "1";
}
EH::Json::Value msgstate1;
msgstate1["Mode"] = device->mode;
payload["state"] = msgstate1;
payload["dev_ep_id"] = 2; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
//温度
if(device->target != DoubleToString(arg["work_temperature"].asDouble() * 10,error)||
device->current != DoubleToString(arg["current_real_temperature"].asDouble() * 10,error)){
device->target = DoubleToString(arg["work_temperature"].asDouble() * 10,error);
device->current = DoubleToString(arg["current_real_temperature"].asDouble() * 10,error);
EH::Json::Value msgstate2;
msgstate2["Temperature"] = device->target;
msgstate2["Current_Temperature"] = device->current;
payload["state"] = msgstate2;
payload["dev_ep_id"] = 4; //功能映射为通道3
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
} else if(opcode == "SETUP_NODE"){
}else {
LOGW("opcode:%s not handle handleDeviceStatusChanged.\n",opcode.c_str());
}
} else if (dev_model_id == ChopinFreshAir_PID) { //肖邦-新风控制面板
HwChopinFreshAir* device = (HwChopinFreshAir*)subDevIt->second->channelDevs[channel];
if (opcode == "FRESH_AIR_SWITCH") {
device->on = arg.asString()=="ON";
if(arg.asString()=="ON"){
msgstate0["On"] = "1";
}else{
msgstate0["On"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FRESH_AIR_RUN_MODEL") {
device->mode = arg.asString()=="MANUAL"? 0 : 1;
EH::Json::Value msgstate1;
if(arg.asString()=="MANUAL"){
msgstate1["Mode"] = "0";
}else{
msgstate1["Mode"] = "1";
}
payload["state"] = msgstate1;
payload["dev_ep_id"] = 2; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FRESH_AIR_SPEED_SET") {
string sSpeed = arg.asString();
EH::Json::Value msgstate2;
if (sSpeed == "LOW") {
device->fan = "1";
} else if (sSpeed == "MID") {
device->fan = "2";
} else if (sSpeed == "HIGH") {
device->fan = "3";
} else {
LOGW("not support:%s.\n",sSpeed.c_str());
}
msgstate2["Wind_num"] = device->fan;
payload["state"] = msgstate2;
payload["dev_ep_id"] = 3; //功能映射为通道3
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FRESH_AIR_CONFIG_ARGS_PUSH" ||opcode == "FRESH_AIR_GET_CONFIG_ARGS") {
device->childLockSwitch = arg["lock_status"]["switch_lock"].asBool();
if(device->childLockSwitch){
msgstate0["SwitchChildLock"] = "1";
}else{
msgstate0["SwitchChildLock"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 4; //功能映射为通道4
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "CHOPIN_FRESH_AIR_STATUS") {
if (device->on != arg["on"].asBool()) {
device->on = arg["on"].asBool();
if(arg["on"].asBool() == true){
msgstate0["On"] = "1";
}else{
msgstate0["On"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
if (device->mode != (arg["runModel"].asString() == "MANUAL" ? 0 : 1)) {
device->mode = arg["runModel"].asString() == "MANUAL" ? 0 : 1;
EH::Json::Value msgstate2;
if(arg["runModel"].asString() == "MANUAL"){
msgstate2["Mode"] = "0";
}else{
msgstate2["Mode"] = "1";
}
payload["state"] = msgstate2;
payload["dev_ep_id"] = 2; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
if (device->fan != IntToString(arg["speed"].asInt())) {
device->fan = IntToString(arg["speed"].asInt());
EH::Json::Value msgstate3;
msgstate3["Wind_num"] = device->fan;
payload["state"] = msgstate3;
payload["dev_ep_id"] = 3; //功能映射为通道3
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
if (device->current != DoubleToString(arg["cur_temperature"].asDouble() * 10, error)) {
device->current = DoubleToString(arg["cur_temperature"].asDouble() * 10, error); //arg["cur_temperature"].asDouble() * 10;
EH::Json::Value msgstate4;
msgstate4["Current_Temperature"] = device->current;
payload["state"] = msgstate4;
payload["dev_ep_id"] = 6; //功能映射为通道6
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
string Stime = arg["time_off"].asString();
int stime1 = StringToInt(Stime.substr(0.1), error);
int stime2 =StringToInt(Stime.substr(3.4), error);
int HWTIME = stime1*60 + stime2;
if (device->downtime != HWTIME) { //延迟时间 时间格式转换
device->downtime = HWTIME;
msgstate0["Time_AutoOff"] = IntToString(device->downtime);
payload["state"] = msgstate0;
payload["dev_ep_id"] = 5; //功能映射为通道5
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
if (device->totalTime != arg["filterScreenAlarmTime"].asInt() ||
device->leftTime != device->totalTime - arg["filterScreenWorkTime"].asInt()) {
device->totalTime = arg["filterScreenAlarmTime"].asInt();
device->leftTime = device->totalTime - arg["filterScreenWorkTime"].asInt();
if (device->leftTime < 0) {
device->leftTime = 0;
}
EH::Json::Value msgstate4;
// msgstate4["TotalTime_FilterElement"] = IntToString(device->totalTime);
msgstate4["LeftTime_FilterElement"] = IntToString(device->leftTime);
payload["state"] = msgstate4;
payload["dev_ep_id"] = 8; //功能映射为通道8
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
} else if(opcode == "SETUP_NODE"){
}
} else if (dev_model_id == FanCoilPanel_PID||dev_model_id == AirConditioner_PID) { //肖邦-风机盘管面板 //肖邦-中央空调线控器(大金)
HwConditionerPanel* device = (HwConditionerPanel*)subDevIt->second->channelDevs[channel];
if (opcode == "SWITCH") {
device->on = arg.asString()=="ON";
if(arg.asString()=="ON"){
msgstate0["On"] = "1";
}else{
msgstate0["On"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FAN_COIL_SET_RUN_MODEL") {
string smode = arg.asString();
if (smode == "COLD") {
device->mode = "1";
} else if (smode == "HOT") {
device->mode = "2";
} else if (smode == "WIND") {
device->mode = "3";
} else if (smode == "DEHUMIDIFICATION") {
device->mode = "4";
} else {
LOGW("not support:%s.\n",smode.c_str());
}
msgstate0["Pattern"] = device->mode;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 2; //功能映射为通道3
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FAN_COIL_SET_FUN_SPEED") {
string sSpeed = arg.asString();
if (sSpeed == "AUTO") {
device->fan = "0";
} else if (sSpeed == "LOW") {
device->fan = "1";
} else if (sSpeed == "MID") {
device->fan = "2";
} else if (sSpeed == "HIGH") {
device->fan = "3";
} else {
LOGW("not support:%s.\n",sSpeed.c_str());
}
msgstate0["Wind_num"] = device->fan;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 3; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FAN_COIL_SET_TEMPERATURE") {
device->target = DoubleToString(StringToDouble(arg.asString(), error) * 10, error);
msgstate0["Temperature"] = device->target;
msgstate0["Current_Temperature"] = device->current;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 6; //功能映射为通道6
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FAN_COIL_CONFIG_ARGS_PUSH"||opcode == "FAN_COIL_GET_CONFIG_ARGS") {
device->childLockSwitch = arg["lock_status"]["model_lock"].asBool();
if(device->childLockSwitch){
msgstate0["SwitchChildLock"] = "1";
}else{
msgstate0["SwitchChildLock"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 4; //功能映射为通道4
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FAN_COIL_SET_DELAY_SWITCH_TASK") {
string stime = arg["timing_shutdown"]["time"].asString(); //延迟时间 时间格式转换
int HWTIME = (StringToInt(stime.substr(0.1), error))* 60 + StringToInt(stime.substr(3.4), error);
device->downtime = HWTIME;
device->enable = arg["timing_shutdown"]["enable"].asInt();
msgstate0["Time_AutoOff"] = IntToString(device->downtime);
payload["state"] = msgstate0;
payload["dev_ep_id"] = 5; //功能映射为通道5
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
} else if (opcode == "FAN_COIL_STATUS") {
if (device->on != arg["on"].asBool()) {
device->on = arg["on"].asBool();
if(arg["on"].asBool() == true ){
msgstate0["On"] = "1";
}else{
msgstate0["On"] = "0";
}
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
string smode = arg["run_model"].asString();
string Tmpmode;
if (smode == "COLD") {
Tmpmode = "1";
} else if (smode == "HOT") {
Tmpmode = "2";
} else if (smode == "WIND") {
Tmpmode = "3";
} else if (smode == "DEHUMIDIFICATION") {
Tmpmode = "4";
} else {
LOGW("not support mode:%s.\n",smode.c_str());
}
if (device->mode != Tmpmode) {
device->mode = Tmpmode;
msgstate0["Pattern"] = device->mode;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 2; //功能映射为通道3
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
string sSpeed = arg["fan_speed"].asString();
string TmpSpeed;
if (sSpeed == "AUTO") {
TmpSpeed = "0";
} else if (sSpeed == "LOW") {
TmpSpeed = "1";
} else if (sSpeed == "MID") {
TmpSpeed = "2";
} else if (sSpeed == "HIGH") {
TmpSpeed = "3";
} else {
LOGW("not support:%s.\n",sSpeed.c_str());
}
if (device->fan != TmpSpeed) {
device->fan = TmpSpeed;
msgstate0["Wind_num"] = device->fan;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 3; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
string Stime = arg["timing_shutdown"]["time"].asString();
int stime1 = StringToInt(Stime.substr(0.1), error);
int stime2 =StringToInt(Stime.substr(3.4), error);
int HWTIME = stime1*60 + stime2;
if (device->downtime != HWTIME||device->enable != arg["timing_shutdown"]["enable"].asBool()) { //延迟时间 时间格式转换
device->downtime = HWTIME;
device->enable = arg["timing_shutdown"]["enable"].asBool();
msgstate0["Time_AutoOff"] = IntToString(device->downtime);
payload["state"] = msgstate0;
payload["dev_ep_id"] = 5; //功能映射为通道5
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
//DoubleToString(StringToDouble(arg.asString(), error) * 10, error);
if (device->current != EH_ToolKit::DoubleToString((arg["room_temperature"].asDouble())*10) ||device->target != EH_ToolKit::DoubleToString(arg["setting_temperature"].asDouble()*10)) {
device->current = EH_ToolKit::DoubleToString((arg["room_temperature"].asDouble())*10);
device->target = EH_ToolKit::DoubleToString(arg["setting_temperature"].asDouble()*10);
msgstate0["Temperature"] = device->target;
msgstate0["Current_Temperature"] = device->current;
payload["state"] = msgstate0;
payload["dev_ep_id"] = 6; //功能映射为通道6
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
} else if(opcode == "SETUP_NODE"){
}
}
else {
LOGW("dev_model_id:%s not handle handleDeviceStatusChanged.\n",dev_model_id.c_str());
}
} catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
void kk_handleDeviceInfo::handleCentralACStatusPush(map<string,kk_handleDeviceInfo::HwSubDev*>&hwSubDevs,map<string,string>&indoorunitsId2AddrMap,string pushTopic,
string nodeId,EH::Json::Value arg,string opcode){
LOGI("handleCentralACStatusPush , nodeId:%s opcode:%s \n arg:%s.\n",nodeId.c_str(),opcode.c_str(),EH_ToolKit::JsonToString(arg).c_str());
int error;
map<string,string>::iterator it = indoorunitsId2AddrMap.find(nodeId);
if(it == indoorunitsId2AddrMap.end()){
LOGW("indoorunits:%s not in indoorunitsId2AddrMap.\n",nodeId.c_str());
return;
}
vector<string> chanMac;
Split(it->second,"_",chanMac);
string sn; //内机的sn为mac+id
string channel = "1";
if(StringToInt(chanMac[1],error)<10){
sn = Replace(chanMac[0],":","")+"0"+chanMac[1]; //内机的sn为mac+id
}else{
sn = Replace(chanMac[0],":","")+chanMac[1]; //内机的sn为mac+id
}
LOGD("sn:%s.\n",sn.c_str());
map<string, HwSubDev*>::iterator subDevIt = hwSubDevs.find(sn);
if(subDevIt == hwSubDevs.end()){
LOGW("dev:%s not in hwSubDevs.\n",sn.c_str());
return;
}
string dev_model_id = subDevIt->second->dev_model_id;
LOGD("prodId:%s.\n",dev_model_id.c_str());
if(subDevIt->second->channelDevs.count(channel) == 0){
LOGW("centralAddr:%s not found in channelDevs.\n",channel.c_str());
return;
}
string respTopic = pushTopic+"/devicestatechange";//设备状态变化上报
string devType = subDevIt->second->devTypeId;
EH::Json::Value payload;
EH::Json::Value msgstate0;
payload["gw_id"] = EH_ToolKit::GetMacNoSpace(); //请求发起者
payload["dev_id"] = sn;
payload["dev_type"] = subDevIt->second->dev_model_id;
payload["dev_ep_id"] = StringToInt(channel,error); //通道
try
{
if (dev_model_id == DAIKINCentralACindoor_PID) {
HwCentralAcindoor* device = (HwCentralAcindoor*)subDevIt->second->channelDevs[channel];
if(opcode == "CENTRAL_AC_INDOOR_UNIT_STATUS"){
string respTopic_line;
//内机的在线离线
if(arg["online"].asBool() == true){ //当空调网关在线时,内机的离线在线,由状态报文进行推送
respTopic_line = pushTopic+"/deviceonline";//子设备在线
EH::Json::Value payload;
payload["dev_id"] = sn; //请求发起者
payload["dev_type"] = subDevIt->second->dev_type;
payload["gw_id"] = EH_ToolKit::GetMacNoSpace();
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic_line); //推送新设备到Roma
subDevIt->second->online = true;
}else{
respTopic_line = pushTopic+"/deviceoffline";//子设备离线
EH::Json::Value payload;
payload["dev_id"] = sn; //请求发起者
payload["dev_type"] = subDevIt->second->dev_type;
payload["gw_id"] = EH_ToolKit::GetMacNoSpace();
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic_line); //推送新设备到Roma //在线状态的推送 ,待更改 2020.10.15.9
subDevIt->second->online = false;
}
//温度
if (device->current != arg["roomTemperature"].asInt()) {
device->current = arg["roomTemperature"].asInt();
device->target = arg["settingTemperature"].asInt();
LOGD("update now old target: %d, new target: %d, old current: %d, new current: %d, will push huawei", device->target
, arg["settingTemperature"].asInt(),device->current, arg["roomTemperature"].asInt());
EH::Json::Value msgstate1;
msgstate1["Temperature"] = IntToString(device->target*10);
msgstate1["Current_Temperature"] = IntToString(device->current*10);
payload["state"] = msgstate1;
payload["dev_ep_id"] = 6; //功能映射为通道6
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
}
//开关部分
if (device->on != arg["on"].asBool()) {
device->on = arg["on"].asBool();
LOGD("update now old on: %d, new on: %d, will push huawei", device->on ,arg["on"].asBool());
msgstate0["On"] = device->on?"1":"0";
payload["state"] = msgstate0;
payload["dev_ep_id"] = 1; //功能映射为通道1
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
if (device->target != arg["settingTemperature"].asInt()) {
device->target = arg["settingTemperature"].asInt();
LOGD("update now old target: %d, new target: %d, old current: %d, new current: %d, will push huawei", device->target
, arg["settingTemperature"].asInt(),device->current, arg["roomTemperature"].asInt());
EH::Json::Value msgstate1;
msgstate1["Temperature"] = IntToString(device->target*10);
msgstate1["Current_Temperature"] = IntToString(device->current*10);
payload["state"] = msgstate1;
payload["dev_ep_id"] = 6; //功能映射为通道6
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
string sModel = arg["runModel"].asString();
int iModel;
if (sModel == "AUTO") {
iModel = 5;
} else if (sModel == "AIR_SUPPLY") {
iModel = 3;
} else if (sModel == "COLD") {
iModel = 1;
} else if (sModel == "HOT") {
iModel = 2;
} else if (sModel == "DEHUMIDIFICATION") {
iModel = 4;
} else {
LOGW("UNKNOWN style model");
return;
}
if (iModel != device->mode) {
device->mode = iModel;
LOGD("update now old mode: %d, new mode: %s, will push huawei", device->mode,arg["runModel"].asString().c_str());
EH::Json::Value msgstate2;
msgstate2["Pattern"] = IntToString(device->mode);
payload["state"] = msgstate2;
payload["dev_ep_id"] = 2; //功能映射为通道2
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
string sSpeed = arg["fanSpeed"].asString();
string iSpeed;
if (sSpeed == "LOW") {
iSpeed = "1";
} else if (sSpeed == "MID") {
iSpeed = "2";
} else if (sSpeed == "HIGH") {
iSpeed = "3";
} else {
LOGW("UNKNOWN style speed");
return;
}
if (iSpeed != device->fan){
device->fan = iSpeed;
LOGD("update now old gear: %s, new gear: %s, will push huawei", device->fan.c_str(),arg["fanSpeed"].asString().c_str());
EH::Json::Value msgstate2;
msgstate2["Wind_num"] = device->fan;
payload["state"] = msgstate2;
payload["dev_ep_id"] = 3; //功能映射为通道3
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic);
}
}
} catch (exception &e) {
LOGW("%s.\n", e.what());
}
}
//获取全部设备信息
int kk_handleDeviceInfo::onGetDevService(map<string,kk_handleDeviceInfo::HwSubDev*>&hwSubDevs,map<string,vector<string> >& controllerModel,string pushTopic,string gw_id){
int error;
string respTopic ;
EH::Json::Value payload;
EH::Json::Value Panel;
EH::Json::Value jsonObject;
respTopic = pushTopic+"/devices";//全部设备信息
map<string,HwSubDev*>::iterator it = hwSubDevs.begin();
try
{
if(it != hwSubDevs.end()){
for (; it != hwSubDevs.end(); it++) {
jsonObject["dev_id"] = it->second->sn;
jsonObject["dev_type"] = it->second->dev_type;
jsonObject["online"] = it->second->online;
string dev_model_id = it->second->dev_model_id;
EH::Json::Value fieldinfo;
if(dev_model_id == ZeroFire1ChanChopinSwitch_PID || dev_model_id == ZeroFire2ChanChopinSwitch_PID || dev_model_id == ZeroFire3ChanChopinSwitch_PID
|| dev_model_id == ZeroFire2ChanModularSwitch_PID){ //灯控 /灯控模块
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwSwitch* chanDev = (HwSwitch* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
string channelnum = "switch" + IntToString(StringToInt(subIt->second->channel,error));
fieldinfo[channelnum] = chanDev->on ? "1":"0";
}
}else if(dev_model_id == Chopin1CurtainSwitch_PID||dev_model_id == Chopin2CurtainSwitch_PID) {//窗帘面板
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwCurtain* chanDev = (HwCurtain* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
string channelnum = "mode" + IntToString(StringToInt(subIt->second->channel,error));
fieldinfo[channelnum] = chanDev->mode;
}
}else if(dev_model_id == Chopin1ChanScenePanel_PID) { // 长供电(肖邦情景面板)
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwScenePanel* chanDev = (HwScenePanel* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
fieldinfo["KeyValue"] = "switch0";
}
}else if(dev_model_id == DoorContact_PID ) { //邦德-门磁
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwSensor* chanDev = (HwSensor* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
fieldinfo["alarm"] = "2"; //不推送当前值状态
fieldinfo["battery"] = chanDev->leftbattery;
}
}else if(dev_model_id == BodyMotionSensor_PID||dev_model_id == WaterSensor_PID
||dev_model_id == SOSButton_PID) { // KIT-人体 邦德-水浸 邦德-SOS紧急按钮
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwSensor* chanDev = (HwSensor* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
fieldinfo["alarm"] = chanDev->alarm;
fieldinfo["battery"] = chanDev->leftbattery;
}
}else if(dev_model_id == SoundLightAlarm_PID) { // 邦德-声光报警器
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwSensor* chanDev = (HwSensor* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
fieldinfo["alarm"] = chanDev->alarm;
fieldinfo["battery"] = chanDev->leftbattery;
fieldinfo["power_style"] = chanDev->power_style;
fieldinfo["Sound"] = chanDev->sound;
}
}else if(dev_model_id == DimmerLightPanel_PID) { //控客-肖邦调光面板
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwDimmerLightPanel* chanDev = (HwDimmerLightPanel* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
fieldinfo["On"] = chanDev->on ? "1":"0";
fieldinfo["Brightness"] = chanDev->brightness;
}
}else if(dev_model_id == WaterHeating_PID||dev_model_id == ElectricHeating_PID){ //肖邦-水地暖 肖邦-电地暖
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwWaterElectricHeating* chanDev = (HwWaterElectricHeating* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
fieldinfo["On"] = chanDev->on ? "1":"0";
fieldinfo["Mode"] = chanDev->mode;
fieldinfo["Current_Temperature"] = chanDev->current;
fieldinfo["Temperature"] = chanDev->target;
}
}else if(dev_model_id == ChopinFreshAir_PID) { //肖邦-新风控制面板
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwChopinFreshAir* chanDev = (HwChopinFreshAir* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
fieldinfo["On"] = chanDev->on ? "1":"0";
fieldinfo["Mode"] = IntToString(chanDev->mode);
fieldinfo["Wind_num"] = chanDev->fan;
fieldinfo["Current_Temperature"] = chanDev->current;
// fieldinfo["TotalTime_FilterElement"] = IntToString(chanDev->totalTime);
fieldinfo["LeftTime_FilterElement"] = IntToString(chanDev->leftTime);
fieldinfo["Time_AutoOff"] = IntToString(chanDev->downtime);
}
}else if(dev_model_id == FanCoilPanel_PID||dev_model_id == AirConditioner_PID) { //肖邦-风机盘管面板 //肖邦-中央空调线控器(大金)
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwConditionerPanel* chanDev = (HwConditionerPanel* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
fieldinfo["On"] = chanDev->on ? "1":"0";
fieldinfo["Pattern"] = chanDev->mode;
fieldinfo["Wind_num"] = chanDev->fan;
fieldinfo["Time_AutoOff"] = IntToString(chanDev->downtime);
fieldinfo["Current_Temperature"] = chanDev->current;
fieldinfo["Temperature"] = chanDev->target;
}
} else if (dev_model_id == DAIKINCentralACgw_PID) { //空调网关
EH::Json::Value array;
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwCentralAcgw* chanDev = (HwCentralAcgw* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
map<string,vector<string> >::iterator numIt = controllerModel.find(it->second->mac);
if (numIt != controllerModel.end()) {
for (vector<string>::iterator it = numIt->second.begin(); it != numIt->second.end(); it++) {
EH::Json::Value idJson;
//idJson["id"] = StringToInt(*it, error);
idJson["sn"] = *it;
array.append(idJson);
}
fieldinfo["deviceList"] = array;
} else {
fieldinfo["deviceList"].resize(0);//空数组
}
}
}else if(dev_model_id == DAIKINCentralACindoor_PID) { //中央空调内机
for (map<string,KKChannelDev*>::iterator subIt = it->second->channelDevs.begin();subIt!= it->second->channelDevs.end(); subIt++){
HwCentralAcindoor* chanDev = (HwCentralAcindoor* )it->second->channelDevs[IntToString(StringToInt(subIt->second->channel,error))];
fieldinfo["On"] = chanDev->on ? "1":"0";
fieldinfo["Pattern"] = IntToString(chanDev->mode);
fieldinfo["Wind_num"] = chanDev->fan;
fieldinfo["Current_Temperature"] = IntToString(chanDev->current*10);
fieldinfo["Temperature"] = IntToString(chanDev->target*10);
}
}
jsonObject["field"] = fieldinfo;
Panel.append(jsonObject);
// LOGD("发送全部的设备信息 all devs infos %s.\n",Panel.toStyledString().c_str());
}
payload["gw_id"] = gw_id; //请求发起者
payload["device_list"] = Panel;
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic); //推送新设备到Roma
}else{
LOGW("not found hw dev in local cache.\n");
jsonObject.append(Panel);
payload["gw_id"] = gw_id; //请求发起者
payload["device_list"].resize(0);//空数组
MQ_CCU_Adapter::GetInstance()->sendtoRoma(payload,respTopic); //推送新设备到Roma
return 0;
}
} catch (exception &e) {
LOGW("%s.\n", e.what());
}
return -1;
}
/*
* 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
/*
* EH_Client.cpp
*
*/
#include <arpa/inet.h>
#include <errno.h>
#include <EH_Exception.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "EH_Client.h"
#include "json/reader.h"
#include "json/writer.h"
#include "json/value.h"
#include "LSC_Logger.h"
#include "../lib/EH_DEBUG.h"
#include "EH_ToolKit.h"
#include "../lib/EH_SDKDef.h"
string EH_Client::getClientStatusStr(ClientStatus status) {
string statusString = "UNKNOWN";
switch (status) {
case UNINIT:
statusString = "UNINIT";
break;
case INITING:
statusString = "INITING";
break;
case INIT_FINISH:
statusString = "INIT_FINISH";
break;
case FIND_CCU_IP:
statusString = "FIND_CCU_IP";
break;
case LINK_BUILDING:
statusString = "LINK_BUILDING";
break;
case LINK_BUILD_OK:
statusString = "LINK_BUILD_OK";
break;
case LINK_BUILD_FAILED:
statusString = "LINK_BUILD_FAILED";
break;
case LINK_BROKEN:
statusString = "LINK_BROKEN";
break;
case LOGINING:
statusString = "LOGINING";
break;
case LOGIN_FINISH_OK:
statusString = "LOGIN_FINISH_OK";
break;
case LOGIN_FINISH_FAILED:
statusString = "LOGIN_FINISH_FAILED";
break;
case WORKING:
statusString = "WORKING";
break;
case STOP:
statusString = "STOP";
break;
default:
statusString = "UNKNOWN";
break;
}
return statusString;
}
void* EH_Client::run0(void* opt) {
EH_Client* client = (EH_Client*) opt; //这个的含义是什么?
return client->run(opt);
}
EH_Client::EH_Client() :sendMsgErrorSum(0) {
connectToCcuFd = -1;
ccuServerIp = "";
destroyed = false;
}
int EH_Client::init(string ccuId, string accessKey,
EH_ClientCallBackHandler* cb, bool autoDestroyHandler) {
if (cb == NULL) {
EH_WARNING("please set client callback handler.\n");
return -1;
}
LOGI("EH_Client:%p.\n", this);
this->cb = cb;
changeClientStatus(INITING);
this->ccuId = ccuId;
this->accessKey = accessKey;
this->ccuServerPort = SERVER_LISTEN_PORT;
this->autoDestroyHandler = autoDestroyHandler;
changeClientStatus(INIT_FINISH);
if (this->ccuId == "") {
ccuServerIp = "127.0.0.1";
ccuServerPort = 5000;
}
/*线程标识符。属性类型的结构不是故意暴露。*/
pthread_t tid;
/*创建一个新线程,从执行START-ROUTINE开始
正在传递ARG。创造属性来自属性。新的
句柄存储在*NEWTHREAD中。*/
pthread_create(&tid, NULL, run0, this);
return 0;
}
EH_Client::ClientStatus EH_Client::getClientStatus() const {
return currentStatus;
}
int EH_Client::sendRequest(string nodeId, string opcode, string arg,
string requester) {
if (currentStatus != WORKING) {
EH_WARNING("Client current status:%s NOT in WORKING,please wait...\n",
getClientStatusStr(currentStatus).c_str());
return -1;
}
/*create json request*/
string loginReq = "!"
+ EH_ToolKit::CreateReqJsonMsg(opcode, arg, requester, nodeId)
+ "$";
return sendMsgToServer(loginReq);
}
void EH_Client::processRecvMsg(string msg) {
// EH_DEBUG("recvMsgFromServer:%s. \n", msg.c_str());
if (currentStatus == LOGINING || currentStatus == WORKING) {
bool error = false;
EH::Json::Value recvMsgObj = parseRecvMsg(msg, error);
if (error) {
return;
}
if (currentStatus == LOGINING) {
if (recvMsgObj["opcode"].asString() == "LC_LOGIN"
|| recvMsgObj["opcode"].asString() == "LOGIN") {
if (recvMsgObj["status"].asString() == "success") {
changeClientStatus(LOGIN_FINISH_OK);
changeClientStatus(WORKING);
} else {
changeClientStatus(LOGIN_FINISH_FAILED);
}
} else {/*not login resp msg,drop it*/
}
} else if (currentStatus == WORKING) {
/*push msg to 3rd handler*/
if (cb) {
if(recvMsgObj["opcode"].asString()!= "SET_HOMEBRIDGE_STATUS"){
cb->onRecvMsg(recvMsgObj["nodeid"].asString(),
recvMsgObj["opcode"].asString(), recvMsgObj["arg"],
recvMsgObj["status"].asString());
}
}
}
} else {/*drop msg*/
EH_WARNING("client status not in WORKING,drop recv msg:%s.\n",
msg.c_str());
}
//// EH_DEBUG("recvMsgFromServer:%s. \n", msg.c_str());
// if (currentStatus == WORKING) {
// /*push msg to 3rd handler*/
// if (cb) {
//// cb->onRecvMsg(msg);
// }
//
// } else {/*drop msg*/
// EH_WARNING("client status not in WORKING,drop recv msg:%s.\n",msg.c_str());
// }
}
EH::Json::Value EH_Client::parseRecvMsg(string msg, bool& error) {
error = false;
EH::Json::Value jsonObject;
try {
EH::Json::Reader reader;
if (!reader.parse(msg, jsonObject) || !jsonObject.isObject()) {
EH_WARNING("Message format is wrong.primary msg is: %s\n",
msg.c_str());
error = true;
}
} catch (EH_Exception &e) {
EH_WARNING(
"Messege is not match with our protocol. primary msg is:%s\n",
msg.c_str());
error = true;
}
return jsonObject;
}
void EH_Client::sendLoginReq() {
string loginReq = "";
if (ccuId == "") {
loginReq = "!{\"nodeid\":\"*\",\"opcode\":\"LC_LOGIN\",\"arg\":{\"username\":\"local_root\",\"password\":\"local_root\"},\"requester\":\"EH_Server\"}$";
} else {
EH::Json::Value arg;
arg["device"] = "kk_c++_sdk";
arg["seq"] = "100";
arg["device_id"] = "CCU_" + ccuId;
arg["access_key"] = accessKey;
arg["token"] = "1212";
arg["version"] = "1.0.0";
arg["username"] = "C++_SDK";
loginReq = "!"+ EH_ToolKit::CreateReqJsonMsg("LOGIN_ACCESSKEY",arg.toStyledString(), "HJ_Server") + "$";
}
int len = sendMsgToServer(loginReq);
if(len > 0){
changeClientStatus(WORKING);
}
}
void EH_Client::changeClientStatus(ClientStatus newStatus) {
currentStatus = newStatus;
if (cb) {
cb->onClientStatusChanged(currentStatus);
}
}
int EH_Client::sendMsgToServer(string msg) {
char* buf = (char*) msg.c_str();
LOGI("sendMsgToServer:%s. \n", msg.c_str());
int msgLen = msg.length();
int result, oldLen = msg.length();
do {
result = send(connectToCcuFd, buf, msgLen, 0);
if (result == -1)
return -1;
msgLen -= result;
buf += result;
} while (msgLen);
return oldLen;
}
void EH_Client::onCCUIpChanged(string ccuNewIp) {
EH_DEBUG("ccuId:%s ip:%s.try connect to ccu.\n", ccuId.c_str(),ccuNewIp.c_str());
ccuServerIp = ccuNewIp;
if (currentStatus == WORKING) {
/*try connect...*/
}
}
void* EH_Client::run(void* opt) {
while (!destroyed) {
if (ccuServerIp == "") {/*ccu ip not set,unit FIND_CCU return ccu addr ccu ip未设置,单元查找ccu返回ccu地址*/
sleep(2);
continue;
}
changeClientStatus(LINK_BUILDING);
/*build connection*/
connectToCcuFd = socket(AF_INET, SOCK_STREAM, 0);
if (connectToCcuFd < 0) {
//创建失败
perror("socket");
changeClientStatus(LINK_BUILD_FAILED);
connectToCcuFd = -1;
sleep(2);
continue;
}
// 名称:memset
// 原型:void*memset(void*block,int c,size\t size)
// 说明:
// 此函数将c的值(转换为无符号字符)复制到对象的每个第一个大小字节中
// 从块开始。它返回block的值。
// 头文件:
// memset(&addr, 0, sizeof(addr));
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(ccuServerPort);
addr.sin_addr.s_addr = inet_addr(ccuServerIp.c_str());
// addr.sin_addr.s_addr = htonl(INADDR_ANY) ; //把一个u_long类型的值转化为网络字节顺序
// addr.sin_addr.s_addr = INADDR_ANY; //ip匹配所有的ip
socklen_t addr_len = sizeof(addr);
int connect_fd = connect(connectToCcuFd, (struct sockaddr*) &addr,
addr_len);
if (connect_fd < 0) {
perror("connect");
changeClientStatus(LINK_BUILD_FAILED);
close(connectToCcuFd);
connectToCcuFd = -1;
sleep(2);
continue;
}
timeval tv = { 2, 0 };
int nb = setsockopt(connectToCcuFd, SOL_SOCKET, SO_RCVTIMEO,
(char*) &tv, sizeof(timeval));
if (nb == -1) {
perror("setsockopt");
changeClientStatus(LINK_BUILD_FAILED);
close(connectToCcuFd);
connectToCcuFd = -1;
sleep(2);
continue;
}
changeClientStatus(LINK_BUILD_OK);
changeClientStatus(LOGINING);
sendLoginReq();
while (!destroyed) {
char buf[RECV_MSG_SIZE] = { 0 };
int rec = recv(connectToCcuFd, buf, RECV_MSG_SIZE - 1, 0); //接收信息
if (rec > 0) {
string msg = cacheInputMsg + string(buf);
vector<string> msgs;
EH_ToolKit::Split(msg, "$", msgs);
/*
* split:
* !xxxx$
* return:
* 1:!xxxx
* 2:space
*/
for (uint i = 0; i < msgs.size() - 1; i++) {
string totalMsg = EH_ToolKit::Trim(msgs[i]);
if (totalMsg.find('!') == 0) {
totalMsg.erase(0, 1);/*remove !*/
/*recv total msg*/
processRecvMsg(totalMsg);
} else {/*should not happen 不应该发生*/
EH_WARNING("recv invaild msg:%s.\n", totalMsg.c_str()); //无损MSG
}
}
/*
* no found $
* if (msgs.size() == 1) {
}
*/
cacheInputMsg = msgs[msgs.size() - 1];
} else if (rec < 0) {
if (errno == EWOULDBLOCK) {
continue;
}
} else {/*rec == 0*/
changeClientStatus(LINK_BROKEN); //LINK_BROKEN 连接断开
break;
}
}
}
delete this;
return NULL;
}
void EH_Client::destroy() { //摧毁 ——》主要是什么作用???
destroyed = true;
close(connectToCcuFd);
EH_DEBUG("destroy:%s.\n", ccuId.c_str());
}
EH_Client::~EH_Client() {
close(connectToCcuFd);
cb = NULL;
EH_INFO("~EH_Client:%p.\n", this);
}
/*
* 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;
}
/*
* EH_FindCCU.cpp
*
* Created on: 2020年10月9日
* Author: hj
*/
#include "EH_FindCCU.h"
#include "../lib/EH_DEBUG.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include "LSC_Logger.h"
#include "../KK_HwDevManager.h"
#include "../lib/EH_SDKDef.h"
#include "../MQ_CCU_Adapter.h"
#include "EH_ToolKit.h"
EH_FindCCU::EH_FindCCU() {
destroyed = false;
}
// int EH_FindCCU::init(string ccuId, EH_FindCCUCallBackHandler* cb,string LocalIP) {
int EH_FindCCU::init(string ccuId,string LocalIP) {
this->ccuId = ccuId;
// this->cb = cb;
this->ccuLocalIP = LocalIP;
ccuSn = EH_ToolKit::GetMacNoSpace();
LOGD("socket init.\n");
searchCcuFd = -1;
if ((searchCcuFd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
cout << "socket error" << endl;
return -1;
}
const int opt = 1;
//璁剧疆璇ュ��ュ��涓哄箍��绫诲��锛�
int nb = 0;
nb = setsockopt(searchCcuFd, SOL_SOCKET, SO_BROADCAST, (char *) &opt, sizeof(opt));
if (nb == -1) {
cout << "set socket error..." << endl;
close(searchCcuFd);
return -1;
}
timeval tv = {10, 0};
nb = setsockopt(searchCcuFd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(timeval));
if (nb == -1) {
cout << "setsockopt failed" << endl;
close(searchCcuFd);
return -1;
}
pthread_t tid;
pthread_create(&tid, NULL, run0, this);
LOGD("find ccu init OK.\n");
return 0;
}
void EH_FindCCU::destroy() {
destroyed = true;
}
void* EH_FindCCU::run0(void* opt) {
EH_FindCCU* findCcu = (EH_FindCCU*)opt;
return findCcu->run(opt);
}
void* EH_FindCCU::run(void* opt) {
while(true) {
sendFindCCUMsg();
sleep(2);
}
delete this;
return NULL;
}
//UDP 广播
void EH_FindCCU::sendFindCCUMsg() {
string findMsg = "";
EH::Json::Value arg;
// arg["ip"] = ccuLocalIP;
#ifdef NOT_X86
arg["ip"] = string(EH_ToolKit::GetLocalIP("eth1"));
#else
arg["ip"] = string(EH_ToolKit::GetLocalIP());
// arg["ip"] = string("127.0.0.1");
#endif
arg["proto"] = "zigbee";//网关类型
arg["ccu_id"] = ccuId;
arg["kk_version"] = MQ_VERSION;
arg["gw_id"] = ccuSn;//网关id,采用mac地址
arg["gw_model_id"] = "KK-CC-H31"; //设备类型 //控客的
arg["version"] = "1.2";
arg["state"] = KK_HwDevManager::GetInstance()->GetConnectState();//要改成动态的获取
findMsg = EH_ToolKit::JsonToString(arg);
struct sockaddr_in addrto;
memset (&addrto, 0, sizeof(struct sockaddr_in));
addrto.sin_family = AF_INET;
addrto.sin_addr.s_addr = inet_addr("255.255.255.255");
addrto.sin_port = htons(6767); //兴海定的端口号
int nlen = sizeof(addrto);
if (sendto(searchCcuFd, findMsg.c_str(), strlen(findMsg.c_str()), 0, (sockaddr*) &addrto, nlen) > 0) {
LOGD("Send search ccu msg ok.%s.\n",findMsg.c_str()); //临时注释,避免日志过多。2020.10.14
} else {
LOGW("Send search ccu msg failed.error:%s.\n",strerror(errno));
}
}
EH_FindCCU::~EH_FindCCU() {
close(searchCcuFd);
LOGD("~EH_FindCCU:%s.\n",ccuId.c_str());
}
/*
* Debug_GetCallstack.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 06.04.12.
* code under LGPL
*
* https://github.com/albertz/openlierox/blob/0.59/src/common/Debug_GetCallstack.cpp
*
*/
/*
About the POSIX solution:
Initially, I wanted to implement something similar as suggested
here <http://stackoverflow.com/a/4778874/133374>, i.e. getting
somehow the top frame pointer of the thread and unwinding it
manually (the linked source is derived from Apples `backtrace`
implementation, thus might be Apple-specific, but the idea is
generic).
However, to have that safe (and the source above is not and
may even be broken anyway), you must suspend the thread while
you access its stack. I searched around for different ways to
suspend a thread and found:
- http://stackoverflow.com/questions/2208833/how-do-i-suspend-another-thread-not-the-current-one
- http://stackoverflow.com/questions/6367308/sigstop-and-sigcont-equivalent-in-threads
- http://stackoverflow.com/questions/2666059/nptl-sigcont-and-thread-scheduling
Basically, there is no really good way. The common hack, also
used by the Hotspot JAVA VM (<http://stackoverflow.com/a/2221906/133374>),
is to use signals and sending a custom signal to your thread via
`pthread_kill` (<http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_kill.html>).
So, as I would need such signal-hack anyway, I can have it a bit
simpler and just use `backtrace` inside the called signal handler
which is executed in the target thread (as also suggested here:
<http://stackoverflow.com/a/6407683/133374>). This is basically
what this implementation is doing.
If you are also interested in printing the backtrace, see:
- backtrace_symbols_str() in Debug_extended_backtrace.cpp
- DumpCallstack() in Debug_DumpCallstack.cpp
*/
/*
#include "Debug.h"
#include "Mutex.h"
#include "util/StaticVar.h"
*/
// When implementing iterating over threads on Mac, this might be useful:
// http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/darwin-threads/examine-threads.c?view=markup
// For getting the callback, maybe libunwind can be useful: http://www.nongnu.org/libunwind/
#ifndef HAVE_EXECINFO
# if defined(__linux__)
# define HAVE_EXECINFO 1
# elif defined(__DARWIN_VERS_1050)
# define HAVE_EXECINFO 1
# else
# define HAVE_EXECINFO 0
# endif
#endif
#if HAVE_EXECINFO
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#endif
#if HAVE_EXECINFO
#include <string.h>
#include <signal.h>
#include <pthread.h>
#include "EH_DEBUG.h"
extern pthread_t mainThreadId;
typedef pthread_t ThreadId;
//static StaticVar<Mutex> callstackMutex;
static ThreadId callingThread = 0;
static ThreadId targetThread = 0;
static void** threadCallstackBuffer = NULL;
static int threadCallstackBufferSize = 0;
static int threadCallstackCount = 0;
#define CALLSTACK_SIG SIGUSR2
__attribute__((noinline))
static void _callstack_signal_handler(int signr, siginfo_t *info, void *secret) {
ThreadId myThread = (ThreadId)pthread_self();
if(myThread != targetThread)
return;
#if 0
threadCallstackCount = backtrace(threadCallstackBuffer, threadCallstackBufferSize);
// Search for the frame origin.
for(int i = 1; i < threadCallstackCount; ++i) {
if(threadCallstackBuffer[i] != NULL) continue;
// Found it at stack[i]. Thus remove the first i.
const int IgnoreTopFramesNum = i;
threadCallstackCount -= IgnoreTopFramesNum;
memmove(threadCallstackBuffer, threadCallstackBuffer + IgnoreTopFramesNum, threadCallstackCount * sizeof(void*));
//threadCallstackBuffer[0] = GetPCFromUContext(secret); // replace by real PC ptr
threadCallstackBuffer[0] = (char*)"***********";
break;
}
#else
EH_ERROR("Thread(%u) call stack:\n",targetThread);
void *array[20];
size_t size;
char **strings;
size_t i;
size = backtrace(array, 20);
strings = (char **) backtrace_symbols(array, size);
for (i = 0; i < size; i++) {
EH_ERROR("%d %s.\n", i, strings[i]);
}
free(strings);
#endif
// continue calling thread
pthread_kill((pthread_t)callingThread, CALLSTACK_SIG);
}
static void _setup_callstack_signal_handler() {
struct sigaction sa;
sigfillset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = _callstack_signal_handler;
sigaction(CALLSTACK_SIG, &sa, NULL);
}
__attribute__((noinline))
int GetCallstack(ThreadId threadId, void **buffer, int size) {
if(threadId == 0 || threadId == (ThreadId)pthread_self()) {
EH_ERROR("Thread(%u) call stack:\n",threadId);
void *array[20];
size_t size;
char **strings;
size_t i;
size = backtrace (array, 20);
strings = (char **)backtrace_symbols (array, size);
for (i = 0; i < size; i++) {
EH_ERROR("%d %s.\n",i,strings[i]);
}
free (strings);
return 0;
}
//Mutex::ScopedLock lock(callstackMutex.get());
callingThread = (ThreadId)pthread_self();
targetThread = threadId;
threadCallstackBuffer = buffer;
threadCallstackBufferSize = size;
_setup_callstack_signal_handler();
// call _callstack_signal_handler in target thread
if(pthread_kill((pthread_t)threadId, CALLSTACK_SIG) != 0)
// something failed ...
return 0;
{
sigset_t mask;
sigfillset(&mask);
sigdelset(&mask, CALLSTACK_SIG);
// wait for CALLSTACK_SIG on this thread
sigsuspend(&mask);
}
threadCallstackBuffer = NULL;
threadCallstackBufferSize = 0;
return threadCallstackCount;
}
#else // !HAVE_EXECINFO
// TODO: win32 implementation
// This might be useful: http://stackwalker.codeplex.com/SourceControl/changeset/view/66907#604665
// Esp, SuspendThread, ResumeThread, GetThreadContext, STACKFRAME64, ...
int GetCallstack(ThreadId threadId, void **buffer, int size) {
return 0;
}
#endif
/*
* EH_SDKDef.h
*
*/
#ifndef EH_SDKDEF_H_
#define EH_SDKDEF_H_
#define RECV_MSG_SIZE 2048
//#define SERVER_LISTEN_PORT 5000
#define SERVER_LISTEN_PORT 5000 //服务器监听端口
#define ACK_LOCAL_PORT 4545 //ACK_本地端口 //测试4545
#define SHORT_TIMEOUT 300 //短时间超时
#define LONG_TIMEOUT 500 //长时间超时
class CcuMsgFingerprint {
public:
CcuMsgFingerprint();
CcuMsgFingerprint(string nodeid,string opcode,string reqId);
~CcuMsgFingerprint();
public:
string nodeid;
string opcode;
string reqId;
};
#endif /* EH_SDKDEF_H_ */
/*
* EH_ServerSdk.cpp
*
* Created on: 2020年10月9日
* Author: hj
*/
#include "EH_ServerSdk.h"
#include "LSC_Logger.h"
#include "EH_ToolKit.h"
#include "../lib/EH_SDKDef.h"
EH_ServerSdk* EH_ServerSdk::ms_instance = NULL;
EH_ServerSdk* EH_ServerSdk::GetInstance() {
if (ms_instance == NULL) {
ms_instance = new EH_ServerSdk();
}
return ms_instance;
}
EH_ServerSdk::EH_ServerSdk() {
start = false;
}
int EH_ServerSdk::Open() {
return 0;
}
EH_ServerSdk::~EH_ServerSdk() {
}
/**
* EH_ToolKit.cpp
*
* Copyright by AirDream Co., Ltd. 2010-2011 All right reserved
*
* Description:
* Created on:2011-8-25
* Modified on:2011-8-25
*
*/
#include <EH_Exception.h>
#include <regex.h>
#include "ace/FILE_Addr.h"
#include "ace/FILE_IO.h"
#include "ace/FILE_Connector.h"
#include "EH_ToolKit.h"
#include "EH_DEBUG.h"
#define BOOL uint8_t
#define TRUE 1
#define FALSE 0
uint32_t EH_ToolKit::ms_uiCrc32Tab[256] = { /* CRC polynomial 0xedb88320 */
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
void EH_ToolKit::PrintMsg(const uint8_t* msg, uint16_t msg_len,bool isDebug) {
#if 0
if (isDebug) {
ACE_DEBUG((LM_DEBUG,"msg is: \n"));
} else {
ACE_DEBUG((LM_WARNING,"msg is: \n"));
}
//performance problem
for (int i = 0; i < msg_len; i++) {
if (isDebug) {
ACE_DEBUG((LM_DEBUG,"0x%02X ",msg[i]));
} else {
ACE_DEBUG((LM_WARNING,"0x%02X ",msg[i]));
}
}
if (isDebug) {
ACE_DEBUG((LM_DEBUG,"\n msg content len is %d: \n", msg_len));
} else {
ACE_DEBUG((LM_WARNING,"\n msg content len is %d: \n", msg_len));
}
#else
#define MAX_LOG 4096
char* buf = new char[MAX_LOG];
char* p = buf;
char* errinfo = "";
int leftLen = MAX_LOG-1;
int i = 0;
while (i < msg_len) {
int len = ACE_OS::snprintf(p,leftLen,"0x%02X ",msg[i]);
leftLen -= len;
if (leftLen < 0) {
errinfo = "[msg length over msg dump buffer!]";
break;
}
p += len;
i++;
}
if (isDebug) {
EH_DEBUG("%s\nmsg content len is %d.%s\n", buf, msg_len,errinfo);
} else {
EH_WARNING("%s\nmsg content len is %d.%s\n", buf, msg_len,errinfo);
}
delete[] buf;
#endif
}
void EH_ToolKit::Split(const string& src, const string& separator, vector<string>& dest) {
if (src == "") {
return;
}
string str = src;
string substring;
string::size_type start = 0, index;
do {
index = str.find_first_of(separator, start);
if (index != string::npos) {
substring = str.substr(start, index - start);
dest.push_back(substring);
start = str.find_first_not_of(separator, index);
if (start == string::npos) {
dest.push_back("");
return;
}
}
} while (index != string::npos);
substring = str.substr(start);
dest.push_back(substring);
}
string EH_ToolKit::Trim(string &s) {
if (s.length() == 0)
return s;
size_t beg = s.find_first_not_of(" \a\b\f\n\r\t\v");
size_t end = s.find_last_not_of(" \a\b\f\n\r\t\v");
if (beg == string::npos)
return "";
return string(s, beg, end-beg+1);
}
int EH_ToolKit::HexToStringNoSpace(const char* input, char* output, int len) {
char * p = output;
int total = 0, ret;
for (int i = 0; i < len; i++) {
ret = sprintf(p, "%02X", (unsigned char) (*(input + i)));
p += ret;
total += ret;
}
return total;
}
int EH_ToolKit::HexToString(const char* input, char* output, int len,const char* sep) {
char * p = output;
int total = 0, ret;
for (int i = 0; i < len; i++) {
ret = sprintf(p, "%02X", (unsigned char) (*(input + i)));
p += ret;
total += ret;
if (i < len - 1) {
*p = *sep;
}
++p;
++total;
}
return total;
}
int EH_ToolKit::StringToHex(const char* input, unsigned char* output,const int bufLen) {
int i, len = strlen(input);
int j = 0; //length
for (i = 0; i < len; i += 3) {
if(j > bufLen) {
return -1;
}
int c;
sscanf(input + i, "%02X", &c);
*(output + j) = c;
j++;
}
return j;
}
int EH_ToolKit::StringToHexNoSpace(const char* input, unsigned char* output,const int bufLen) {
int i, len = strlen(input);
int j = 0; //length
for (i = 0; i < len; i += 2) {
if(j > bufLen) {
return -1;
}
int c;
sscanf(input + i, "%02X", &c);
*(output + j) = c;
j++;
}
return j;
}
unsigned short EH_ToolKit::CheckSum(const unsigned char* in,const int len) {
unsigned short sum = 0;
for (int i = 0; i < len; i++) {
sum += *(in+i);
}
return sum;
}
int EH_ToolKit::StringToInt(const string input) {
stringstream oss;
oss << input;
int output = 0;
oss >> output;
if (oss.fail() || !oss.eof()) {
string exception = "Convert string to int error. string is"+input;
EH_WARNING("%s.\n",exception.c_str());
output = -1;
}
return output;
}
uint EH_ToolKit::StringToUInt(const string input) {
stringstream oss;
oss << input;
uint output = 0;
oss >> output;
if (oss.fail() || !oss.eof()) {
string exception = "Convert string to uint error. string is"+input;
EH_WARNING("%s.\n",exception.c_str());
output = 0;
}
return output;
}
double EH_ToolKit::StringToDouble(const string input) {
stringstream oss;
oss << input;
double output = -1;
oss >> output;
if (oss.fail() || !oss.eof()) {
string exception = "Convert string to double error. string is"+input;
EH_WARNING("%s.\n",exception.c_str());
}
return output;
}
string EH_ToolKit::IntToString(const int input) {
stringstream oss;
oss << input;
string output;
oss >> output;
return output;
}
string EH_ToolKit::UIntToString(const uint input) {
stringstream oss;
oss << input;
string output;
oss >> output;
return output;
}
string EH_ToolKit::UInt64ToString(const ACE_UINT64 input) {
stringstream oss;
oss << input;
string output;
oss >> output;
return output;
}
string EH_ToolKit::DoubleToString(const double input) {
stringstream oss;
oss << input;
string output;
oss >> output;
return output;
}
string EH_ToolKit::JsonToString(const EH::Json::Value& json) {
EH::Json::FastWriter writer;
string jsonStr = writer.write(json);
return Trim(jsonStr);
}
string EH_ToolKit::CreateRespJsonMsg(string opcode,string arg,int status,string nodeid) {
EH::Json::Reader reader;
EH::Json::Value msgObj;
EH::Json::Value argObj;
if (!reader.parse(arg.c_str(), argObj)) {
argObj = EH::Json::Value(arg);
}
msgObj["nodeid"] = EH::Json::Value(nodeid);
msgObj["opcode"] = EH::Json::Value(opcode);
msgObj["arg"] = argObj;
msgObj["status"] = EH::Json::Value(status == -1 ? "failed" : "success");
string ret = msgObj.toStyledString();
return Trim(ret);
}
string CreateRespJsonMsgWithErrorCode(string opcode,string arg,int status,string nodeid,int error) {
return "";
}
string EH_ToolKit::CreateReqJsonMsg(string opcode,string arg,string requester,string nodeid) {
EH::Json::Reader reader;
EH::Json::Value msgObj;
EH::Json::Value argObj;
if(!reader.parse(arg.c_str(), argObj)) {
argObj = EH::Json::Value(arg);//as string
}
msgObj["nodeid"] = EH::Json::Value(nodeid);
msgObj["opcode"] = EH::Json::Value(opcode);
msgObj["arg"] = argObj;
msgObj["requester"] = requester;
string ret = JsonToString(msgObj); //msgObj.toStyledString(); //两种方法有区别
return Trim(ret);
}
string EH_ToolKit::CreateReqJsonMsgWithReqId(string opcode,string arg,string requester,string nodeid,string reqId) {
EH::Json::Reader reader;
EH::Json::Value msgObj;
EH::Json::Value argObj;
if(!reader.parse(arg.c_str(), argObj)) {
argObj = EH::Json::Value(arg);//as string
}
msgObj["nodeid"] = EH::Json::Value(nodeid);
msgObj["opcode"] = EH::Json::Value(opcode);
msgObj["arg"] = argObj;
if(reqId!= ""){
msgObj["reqId"] = reqId;
}
msgObj["requester"] = requester;
string ret = msgObj.toStyledString();
return Trim(ret);
}
string EH_ToolKit::CreateReqJsonMsgWithArgJson(string opcode,EH::Json::Value argObj,string requester,string nodeid,string reqId) {
EH::Json::Reader reader;
EH::Json::Value msgObj;
msgObj["nodeid"] = EH::Json::Value(nodeid);
msgObj["opcode"] = EH::Json::Value(opcode);
msgObj["arg"] = argObj;
if(reqId!= ""){
msgObj["reqId"] = reqId;
}
msgObj["requester"] = requester;
string ret = msgObj.toStyledString();
return Trim(ret);
}
bool EH_ToolKit::CompareNoCase(string str1,string str2) {
if (strcasecmp(str1.c_str(),str2.c_str()) == 0) {
return true;
} else {
return false;
}
}
bool EH_ToolKit::HasSpareProcess(const string processName) {
static ACE_Process_Mutex processMutex(processName.c_str());
if (processMutex.tryacquire() < 0) {
EH_WARNING("The same process is running.This process will abort.\n");
return true;
}
return false;
}
bool EH_ToolKit::CheckRoot() {
if (ACE_OS::geteuid() == 0) {
EH_ERROR("\"root\" execution of the program is not permitted.\n"
"The program must be started under an unprivileged user ID to prevent\n"
"possible system security compromise.\n");
return false;
}
if (ACE_OS::getuid() != ACE_OS::geteuid()) {
EH_ERROR("real and effective user IDs must match\n");
return false;
}
return true;
}
void EH_ToolKit::BuildAbsTimeOut(ACE_Time_Value* timeout,int timeoutMS) {
*timeout = ACE_OS::gettimeofday();
timeout->usec(timeout->usec()+timeoutMS);
}
/*if you need use the return string,you should copy it.*/
const char* EH_ToolKit::GetLocalIP(string interface) {
int MAXINTERFACES = 16;
char* localIP = "";
int fd, intrface;
struct ifreq buf[MAXINTERFACES];
struct ifconf ifc;
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = (caddr_t) buf;
if (!ioctl(fd, SIOCGIFCONF, (char *) &ifc)) {
intrface = ifc.ifc_len / sizeof(struct ifreq);
while (intrface-- > 0) {
if (interface == "NOT_SET") {/*get first ip*/
if (!(ioctl(fd, SIOCGIFADDR, (char *) &buf[intrface]))) {
localIP = inet_ntoa(((struct sockaddr_in*) (&buf[intrface].ifr_addr))->sin_addr);
break;
}
} else {
if (string(buf[intrface].ifr_name) == interface) {
if (!(ioctl(fd, SIOCGIFADDR, (char *) &buf[intrface]))) {
localIP = inet_ntoa(((struct sockaddr_in*) (&buf[intrface].ifr_addr))->sin_addr);
break;
}
}
}
}
}
close(fd);
}
return localIP;
}
string EH_ToolKit::GetFileContent(string filePath, bool& error) {
string fileContent;
ACE_FILE_IO file;
ACE_FILE_Connector fileConnector;
error = false;
if (fileConnector.connect(file, ACE_FILE_Addr(filePath.c_str()), 0, ACE_Addr::sap_any,
0, O_RDONLY, ACE_DEFAULT_FILE_PERMS) == -1) {
EH_WARNING("Open file:%s error:%s.\n", filePath.c_str(), ACE_OS::strerror(ACE_OS::last_error()));
error = true;
fileContent = "";
} else {
char buf[200] = { 0 };
while(true) {
bzero(buf,sizeof(buf));
int len = file.recv(buf, sizeof(buf) - 1);
if (len == -1) {/*ERROR*/
EH_WARNING("Read from file:%s error:%s.\n", filePath.c_str(), ACE_OS::strerror(ACE_OS::last_error()));
fileContent = "";
error = true;
break;
} else if (len == 0) {/*EOF*/
break;
} else {
fileContent.append(buf);
}
}
file.close();
}
return fileContent;
}
bool EH_ToolKit::Ping(string destIP) {
bool pingOk;
string ping_cmd = "ping -c 1 -W 1 "+destIP+" > /dev/null";
int sys_ret = DoSystem(ping_cmd);
if (sys_ret == 0) {
pingOk = true;
} else {
pingOk = false;
}
return pingOk;
}
int EH_ToolKit::GetCpuCoreNum() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
bool EH_ToolKit::MatchVersion(string version,string pattern) {
const size_t nmatch = 10;
regmatch_t pm[10];
int z;
regex_t reg;
regcomp(&reg, pattern.c_str(), REG_EXTENDED | REG_NOSUB);
z = regexec(&reg, version.c_str(), nmatch, pm, REG_NOTBOL);
return z != REG_NOMATCH;
}
typedef pthread_t ThreadId;
int GetCallstack(ThreadId, void **buffer, int size);
pthread_t mainThreadId;
static void WidebrightSegvHandler(int signum) {
EH_ToolKit::PrintBacktrace(signum);
if (mainThreadId != (ThreadId)pthread_self()) {
GetCallstack(mainThreadId, NULL, 1);
} else {
EH_ERROR("Main thread call stack as above.\n");
}
exit(1);
}
void EH_ToolKit::SetCoredumpMsgDump() {
mainThreadId = pthread_self();
signal(SIGSEGV, WidebrightSegvHandler);
signal(SIGABRT, WidebrightSegvHandler);
signal(SIGALRM, WidebrightSegvHandler);
signal(SIGBUS, WidebrightSegvHandler);
signal(SIGFPE, WidebrightSegvHandler);
signal(SIGHUP, WidebrightSegvHandler);
signal(SIGILL, WidebrightSegvHandler);
signal(SIGINT, WidebrightSegvHandler);
signal(SIGIO, WidebrightSegvHandler);
signal(SIGIOT, WidebrightSegvHandler);
signal(SIGPOLL, WidebrightSegvHandler);
signal(SIGPWR, WidebrightSegvHandler);
signal(SIGPROF, WidebrightSegvHandler);
signal(SIGQUIT, WidebrightSegvHandler);
//signal(SIGSTKFLT, WidebrightSegvHandler);
signal(SIGTERM, WidebrightSegvHandler);
signal(SIGTRAP, WidebrightSegvHandler);
signal(SIGSYS, WidebrightSegvHandler);
signal(SIGVTALRM, WidebrightSegvHandler);
signal(SIGXCPU, WidebrightSegvHandler);
signal(SIGXFSZ, WidebrightSegvHandler);
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <execinfo.h>
void EH_ToolKit::PrintBacktrace(int signum) {
void *array[20];
size_t size;
char **strings;
size_t i;
signal(signum, SIG_DFL); /* 还原默认的信号处理handler */
size = backtrace (array, 20);
strings = (char **)backtrace_symbols (array, size);
string sig;
if (signum == SIGSEGV) {
sig = "SIGSEGV";
} else if(signum == SIGABRT) {
sig = "SIGABRT";
} else {
sig = EH_ToolKit::IntToString(signum);
}
EH_ERROR("Process received %s! Stack trace:\n",sig.c_str());
for (i = 0; i < size; i++) {
EH_ERROR("%d %s.\n",i,strings[i]);
}
free (strings);
}
string EH_ToolKit::GetTimestamp(){
struct timeval now;
gettimeofday(&now, 0);
ACE_UINT64 nowInMs = (ACE_UINT64)now.tv_sec * 1000;
nowInMs += now.tv_usec / 1000;
return EH_ToolKit::UInt64ToString(nowInMs);
}
string EH_ToolKit::GetUUID() {
ACE_Utils::UUID_GENERATOR::instance()->init();
ACE_Utils::UUID uuid;
ACE_Utils::UUID_GENERATOR::instance()->generate_UUID(uuid);
return uuid.to_string()->c_str();
}
string EH_ToolKit::GetCurrentTime() {
long nowSec = time(NULL);
struct tm *nowTM = localtime(&nowSec);
char currentTime[256] = {0};
snprintf(currentTime, sizeof(currentTime)-1,"%d-%02d-%02d %02d:%02d:%02d",
nowTM->tm_year+1900,
nowTM->tm_mon+1,
nowTM->tm_mday,
nowTM->tm_hour,
nowTM->tm_min,
nowTM->tm_sec);
return currentTime;
}
ACE_UINT64 EH_ToolKit::getSystemTimeInMs() {
struct timeval now;
gettimeofday(&now, 0);
ACE_UINT64 nowInMs = now.tv_sec * 1000;
nowInMs += now.tv_usec / 1000;
return nowInMs;
}
int EH_ToolKit::DoSystem(string cmd) {
int ret = 0;
sighandler_t old_handler;
old_handler = signal(SIGCHLD, SIG_DFL);
int status = system(cmd.c_str());
signal(SIGCHLD, old_handler);
if (-1 != status) {
if (WIFEXITED(status)) {/*normal exit*/
if (0 == WEXITSTATUS(status)) {/*success*/
EH_INFO("do cmd:%s ok.exit with code:%d\n",cmd.c_str(),WEXITSTATUS(status));
return 0;
} else {
EH_WARNING("do cmd:%s failed.exit with code:%d\n",cmd.c_str(),WEXITSTATUS(status));
return WEXITSTATUS(status);
}
} else {
EH_WARNING("do cmd:%s failed.exit none normal.\n",cmd.c_str());
}
} else {
EH_WARNING("do cmd:%s failed.system return -1.error:%s\n",cmd.c_str(),strerror(errno));
}
return -1;
}
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
// data structs to store interface name list
char ifname_buf[2048];
char *ifnames = ifname_buf;
int mac_count = 0;
void add_interface_name(const char * name)
{
int i;
for (i=0;i<mac_count;i++)
{
if (!strcmp(ifnames+i*IFNAMSIZ, name))
return;
}
strncpy(ifnames+(mac_count++)*IFNAMSIZ, name, IFNAMSIZ-1);
}
char * get_name(char *name, char *p)
{
while (isspace(*p))
p++;
while (*p) {
if (isspace(*p))
break;
if (*p == ':') { /* could be an alias */
char *dot = p, *dotname = name;
*name++ = *p++;
while (isdigit(*p))
*name++ = *p++;
if (*p != ':') { /* it wasn't, backup */
p = dot;
name = dotname;
}
if (*p == '\0')
return NULL;
p++;
break;
}
*name++ = *p++;
}
*name++ = '\0';
return p;
}
// get /proc/net/dev interface name list into buffer
// return 0 if success
int get_procnet_list()
{
FILE *fh;
char buf[512];
fh = fopen("/proc/net/dev", "r");
if (!fh)
return -1;
fgets(buf, sizeof buf, fh); /* eat title lines */
fgets(buf, sizeof buf, fh);
while (fgets(buf, sizeof buf, fh))
{
char name[IFNAMSIZ];
get_name(name, buf);
add_interface_name(name);
}
fclose(fh);
return 0;
}
long mac_addr_sys ( char *addr) {
/* implementation for Linux */
struct ifreq ifr;
struct ifreq *IFR;
struct ifconf ifc;
char buf[1024];
int s, i;
int ok = 0;
// clear buffer
memset(ifname_buf, 0, sizeof(ifname_buf));
mac_count = 0;
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s==-1) {
return -1;
}
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
ioctl(s, SIOCGIFCONF, &ifc);
IFR = ifc.ifc_req;
// put the ioctl interface names in the list
for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) {
add_interface_name(IFR->ifr_name);
}
// put the /proc/net/dev interface names in the list
if (get_procnet_list())
return -1;
// get the first mac address of eth* device hardware address
for (i = 0; i < mac_count; i++) {
strcpy(ifr.ifr_name, ifnames + i*IFNAMSIZ);
#if !defined(MIPS_ENCHANCE)
if (!strncmp(ifr.ifr_name, "eth", 3))
if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
char *p = (char *)ifr.ifr_hwaddr.sa_data;
if (!*((int *)p) && !*((int *)(p+2)) )
continue;
// if not 00:00:00:00:00:00, yes, we get the real mac addr
ok = 1;
break;
}
}
}
#else
if (!strncmp(ifr.ifr_name, "eth1", 4))
if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
char *p = (char *)ifr.ifr_hwaddr.sa_data;
if (!*((int *)p) && !*((int *)(p+2)) )
continue;
// if not 00:00:00:00:00:00, yes, we get the real mac addr
ok = 1;
break;
}
}
}
#endif
}
close(s);
if (ok) {
bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
}
else {
return -1;
}
return 0;
}
string EH_ToolKit::GetMac() {
long stat;
char addr[6] = {0};
char macStr[30] = {0};
stat = mac_addr_sys(addr);
if (0 == stat) {
HexToString(addr,macStr,6,":");
return macStr;
} else {
return "";
}
}
string EH_ToolKit::GetMacNoSpace() {
long stat;
char addr[6] = {0};
char macStr[30] = {0};
stat = mac_addr_sys(addr);
if (0 == stat) {
HexToStringNoSpace(addr,macStr,6);
return macStr;
} else {
return "";
}
}
void EH_ToolKit::ShowHelpInfo() {
cout<<(" -A : 'A' means 'Print All Log Message'\n");
cout<<(" -D : 'D' means 'Print Above(include) DEBUG Message'\n");
cout<<(" -I : 'I' means 'Print Above(include) INFO Message'\n");
cout<<(" -N : 'N' means 'Print Above(include) NOTICE Message'\n");
cout<<(" -W : 'W' means 'Print Above(include) WARNING Message'\n");
cout<<(" -E : 'E' means 'Print Above(include) ERROR Message'\n");
cout<<(" -H : printing help information\n");
cout<<(" -V : printing version information\n");
}
void EH_ToolKit::ShowVersionInfo(string proc,string version) {
cout<<"["<<proc<<"]:"<<version<<endl;
}
/*
* version type:
* v_x.x.x
*/
int EH_ToolKit::GetVersionInfo(string version, int& majorV, int& minorV, int& betaV, bool hasVersionPrefix) {
string digitVersion;
if (hasVersionPrefix) {
vector<string> versionInfo;
EH_ToolKit::Split(version, "_", versionInfo);
if (versionInfo.size() == 2) {
digitVersion = versionInfo[1];
} else {
return -1;
}
} else {
digitVersion = version;
}
vector<string> subversionInfo;
EH_ToolKit::Split(digitVersion,".",subversionInfo);
if (subversionInfo.size() == 3) {
majorV = StringToInt(subversionInfo[0]);
minorV = StringToInt(subversionInfo[1]);
betaV = StringToInt(subversionInfo[2]);
} else {
return -1;
}
return 0;
}
/*
* version type:
* x.x.x
*/
int EH_ToolKit::CompareVersion(string checkVersion, string baseVersion) {
int ret = -1;
do {
int checkMajorV;
int checkMinoV;
int checkBetaV;
int checkGetRet = GetVersionInfo(checkVersion,checkMajorV,checkMinoV,checkBetaV,false);
if (checkGetRet == -1) {
break;
}
int baseMajorV;
int baseMinoV;
int baseBetaV;
int baseGetRet = GetVersionInfo(baseVersion, baseMajorV, baseMinoV, baseBetaV, false);
if (baseGetRet == -1) {
break;
}
int checkVersionSum = checkMajorV * 1000000 + checkMinoV * 1000 + checkBetaV;
int baseVersionSum = baseMajorV * 1000000 + baseMinoV * 1000 + baseBetaV;
if (checkVersionSum > baseVersionSum) {
ret = COMPARE_VER_MORE_THAN;
} else if (checkVersionSum < baseVersionSum) {
ret = COMPARE_VER_LESS_THAN;
} else {
ret = COMPARE_VER_EQ_THAN;
}
} while (false);
return ret;
}
uint32_t EH_ToolKit::CreateCrc32(const uint8_t* s, uint32_t len) {
uint32_t i;
uint32_t crc32val;
crc32val = ~0;
for (i = 0; i < len; i++) {
crc32val = EH_ToolKit::ms_uiCrc32Tab[(crc32val ^ s[i]) & 0xff] ^ (crc32val >> 8);
}
return ~crc32val;
}
uint16_t EH_ToolKit::CreateCrc16(const uint8_t* msg, uint32_t len) {
uint16_t crc = 0xFFFF;
uint32_t i, j = 0;
for (i = 0; i < len; i++) {
for (j = 0; j < 8; j++) {
BOOL c15 = ((crc >> 15 & 1) == 1);
BOOL bit = ((msg[i] >> (7 - j) & 1) == 1);
crc <<= 1;
if (c15 ^ bit) {
crc ^= 0x1021;
}
}
}
return crc;
}
uint16_t EH_ToolKit::CrcByte(uint16_t crc, uint8_t b) {
crc = (uint8_t) (crc >> 8) | (crc << 8);
crc ^= b;
crc ^= (uint8_t) (crc & 0xff) >> 4;
crc ^= crc << 12;
crc ^= (crc & 0xff) << 5;
return crc;
}
uint16_t EH_ToolKit::Crc16(void* buf, uint8_t len) {
uint8_t* tmpBuf = (uint8_t* ) buf;
uint16_t crc;
for (crc = 0; len > 0; len--) {
crc = CrcByte(crc, *tmpBuf); // Calculates running CRC
tmpBuf++;
}
return crc;
}
/*
* KK_MqttSdk.cpp
*
* Created on: Dec 2, 2018
* Author: sds
*/
#include "KK_MqttSdk.h"
#include "EH_DEBUG.h"
#include "json/reader.h"
#include "json/writer.h"
#include "json/value.h"
#include "LSC_Logger.h"
#include "ace/Reactor.h"
extern "C"{
#include "MQTTAsync.h"
#include "string.h"
#include <time.h>
}
using namespace std;
#define TIMEOUT 10000L
static MQTTAsync S_client = NULL;
static bool S_Working;
static const char* OPT_SEND = "MQTTAsync_sendMessage";
static const char* OPT_SUB = "MQTTAsync_subscribe";
static const char* OPT_UNSUB = "MQTTAsync_unsubscribe";
KK_MQTTSDK* KK_MQTTSDK::GetInstance() {
if (ms_Instance == NULL) {
ms_Instance = new KK_MQTTSDK();
}
return ms_Instance;
}
KK_MQTTSDK* KK_MQTTSDK::ms_Instance = NULL;
KK_MQTTSDK::KK_MQTTSDK() {
}
//连接丢失
static void onConnectLost(void *context, char *cause){
S_Working = false;
LOGW(" 连接丢失 断开原因onConnectLost,disconnect cause:%s \n",cause);
KK_MQTTSDK::EH_SDKCallbackHandler* callback = KK_MQTTSDK::GetInstance()->getSdkCallbackHandler();
callback->onCloudDisConnect();
// KK_MQTTSDK::GetInstance()->recon(3);
}
//连接断开时
static void onDisConnected(void *context, MQTTProperties* properties,enum MQTTReasonCodes reasonCode){
S_Working = false;
LOGW("onDisConnected,断开连接,可能被broker踢出.\n");
KK_MQTTSDK::EH_SDKCallbackHandler* callback = KK_MQTTSDK::GetInstance()->getSdkCallbackHandler();
callback->onCloudDisConnect();
// KK_MQTTSDK::GetInstance()->recon(3);
}
//连接建立
static void onConnectBuild(void *context, char *cause){
S_Working = true;
LOGI("onConnectBuild,disconnect cause:%s \n",cause);
KK_MQTTSDK::EH_SDKCallbackHandler* callback = KK_MQTTSDK::GetInstance()->getSdkCallbackHandler();
callback->onCloudConnect();
}
//连接失败
static void onConnectFailure(void* context, MQTTAsync_failureData* response){
LOGW("onConnectFailure, return: %d\n", response ? response->code : 0);
// KK_MQTTSDK::GetInstance()->recon(3);
}
//连接成功
static void onConnectSuccess(void* context, MQTTAsync_successData* response){
LOGI("onConnectSuccess to server:%s,version:%d,sessionPresent:%d \n",
response->alt.connect.serverURI,response->alt.connect.MQTTVersion,
response->alt.connect.sessionPresent);
}
//消息到达时
static int onMessageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message){
string payload((char *)message->payload,message->payloadlen);
string TopicName = topicName;
LOGI("MQTT topic:%s, payload:%s.\n",topicName,payload.c_str());
KK_MQTTSDK::EH_SDKCallbackHandler* callback = KK_MQTTSDK::GetInstance()->getSdkCallbackHandler();
callback->onCloudMsgRecv(payload,TopicName);
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
//当事件完成时
static void onDeliveryComplete(void* context, MQTTAsync_token token){
LOGD("onDeliveryComplete,token:%d \n",token);
}
static void onOptSuccess(void* context, MQTTAsync_successData* response){
if(strcmp((char *)context,OPT_SEND)==0){
LOGD("MQTTAsync_sendMessage success,return token:%d,msg length:%d \n",
response->token,response->alt.pub.message.payloadlen);
}else if(strcmp((char *)context,OPT_SUB)==0){
LOGI("MQTTAsync_subscribe success,return token:%d \n",response->token);
}else if(strcmp((char *)context,OPT_UNSUB)==0){
LOGI("MQTTAsync_unsubscribe success,return token:%d \n",response->token);
}
}
static void onOptFail(void* context, MQTTAsync_failureData* response){
if(strcmp((char *)context,OPT_SEND)==0){
LOGW("MQTTAsync_sendMessage fail,token:%d,code:%d,msg:%s \n",
response->token,response->code,response->message);
}else if(strcmp((char *)context,OPT_SUB)==0){
LOGW("MQTTAsync_subscribe fail,return token:%d \n",response->token);
}else if(strcmp((char *)context,OPT_UNSUB)==0){
LOGW("MQTTAsync_unsubscribe fail,return token:%d \n",response->token);
}
}
//回调打印日志的接口
static void mqttTraceCallback(enum MQTTASYNC_TRACE_LEVELS level, char *message){
// LOGD("mqttTraceCallback level:%d,msg:%s.\n",level,message);
}
int KK_MQTTSDK::handle_timeout(const ACE_Time_Value &current_time, const void *act) {
destroy();
if(reinit("")!= 0){
ACE_OS::exit(1);
return 0;
}
con(0,2);
return 0;
}
void KK_MQTTSDK::recon(int delayInSec){
ACE_Time_Value delay(delayInSec);
reconTimerId = ACE_Reactor::instance()->schedule_timer(this, NULL, delay);
if(reconTimerId!=-1){
LOGI("set recon timer:%d in %d seconds delay.\n",reconTimerId,delayInSec); //设置恢复计时器:%d(延迟%d秒)
}else{
LOGW("set recon timer failed.\n");
}
}
int KK_MQTTSDK::init(string brokerAddr,string clientId,string username,string password,string heartbeat_Topic,string gw_id) {
LOGD("MQTT 初始化.\n");
if(this->callbackHandler == NULL){
LOGE("callbackHandler not set.\n");
return -1;
}
this->brokerAddr = brokerAddr;
this->clientId = clientId;
this->username = username;
this->password = password;
// this->willTopic = willTopic;
this->heartbeat_Topic = heartbeat_Topic;
this->gw_id = gw_id;
//打印日志的回调函数
MQTTAsync_setTraceCallback(mqttTraceCallback);
MQTTAsync_createOptions opts = MQTTAsync_createOptions_initializer;
// opts.MQTTVersion = MQTTVERSION_3_1_1;
opts.MQTTVersion = MQTTVERSION_5;
//此函数创建一个MQTT客户端,准备连接到*指定的服务器并使用指定的持久性存储(请参阅* MQTTAsync_persistence)
int rc = MQTTAsync_createWithOptions(&S_client,(const char* )brokerAddr.c_str(),
(const char* )clientId.c_str(), MQTTCLIENT_PERSISTENCE_NONE,NULL,&opts);
LOGI("MQTTAsync_create new client:0x%0x.\n",S_client);
if(rc != MQTTASYNC_SUCCESS){
LOGW("Failed to create mqtt sdk client, return code %d\n", rc);
return -1;
}
//此函数用于为特定客户端的连接丢失事件设置回调函数
MQTTAsync_setConnectionLostCallback(S_client,NULL,onConnectLost);
//此函数用于为特定客户端的消息到达事件设置回调函数
MQTTAsync_setMessageArrivedCallback(S_client,NULL,onMessageArrived);
//此函数用于为特定客户端的传递完成事件设置回调函数
MQTTAsync_setDeliveryCompleteCallback(S_client,NULL,onDeliveryComplete);
//为客户端设置MQTTAsync_connected()回调函数
MQTTAsync_setConnected(S_client,NULL,onConnectBuild);
//为客户端设置MQTTAsync_disconnected()回调函数
MQTTAsync_setDisconnected(S_client,NULL,onDisConnected);
return 0;
}
//设置回调,
void KK_MQTTSDK::setSdkCallbackHandler(EH_SDKCallbackHandler* handler){
callbackHandler = handler;
}
KK_MQTTSDK::EH_SDKCallbackHandler* KK_MQTTSDK::getSdkCallbackHandler(){
return callbackHandler;
}
int KK_MQTTSDK::subTopic(string topic,int qos,int waitTimeout){
if(!S_Working){
LOGW("No Connection build to MQ Server.\n");
return -1;
}
LOGI("to subtopic:%s \n",topic.c_str());
// Init list of topics to subscribe
char** topicsPath = (char**)calloc(2, sizeof(char*));
int* topicsQoS = (int*)calloc(2, sizeof(int));
topic1 = topic+"/publishstate";
topicsPath[0] = const_cast<char*>(topic1.c_str());
topicsQoS[0] = 0;
topic2 = topic+"/commands";
topicsPath[1] = const_cast<char*>(topic2.c_str());
topicsQoS[1] = 0;
// Create subcribe parameters
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc ;
opts.onSuccess = onOptSuccess;
opts.onFailure = onOptFail;
opts.context = (void*)OPT_SUB;
for(int i = 0; i < 2; i++)
{
LOGI("test:%s %d\n",topicsPath[i], topicsQoS[i]);
}
// Subscribe and disconnect if error
if ((rc = MQTTAsync_subscribeMany(S_client,2,topicsPath,topicsQoS, &opts)) != MQTTASYNC_SUCCESS){//订阅多个主题
// if ((rc = MQTTAsync_subscribe(S_client,topic.c_str(), qos, &opts)) != MQTTASYNC_SUCCESS){//订阅单个主题
LOGW("Failed to start subscribe Many, return code:%d.\n", rc);
return -1;
}else{
LOGI("SUCCESS to start subscribe Many, return code:%d.\n", rc);
}
return MQTTAsync_waitForCompletion(S_client, opts.token, waitTimeout);
}
//删除指定客户端进行的现有订阅
int KK_MQTTSDK::unsubTopic(string topic,int waitTimeout){
LOGI("删除指定客户端进行的现有订阅 to unsubtopic:%s \n",topic.c_str());
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
opts.onSuccess = onOptSuccess;
opts.onFailure = onOptFail;
opts.context = (void*)OPT_UNSUB;
if ((rc = MQTTAsync_unsubscribe(S_client,topic.c_str(), &opts)) != MQTTASYNC_SUCCESS){
LOGW("Failed to start unubscribe, return code:%d.\n", rc);
return -1;
}
return MQTTAsync_waitForCompletion(S_client, opts.token, waitTimeout);
}
int KK_MQTTSDK::sendMsg(string topic,string payload,int qos){
if(!S_Working){
LOGW("No Connection build to MQ Server.\n");
return -1;
}
//连接状态
int connite = MQTTAsync_isConnected(S_client);
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
opts.onSuccess = onOptSuccess;
opts.onFailure = onOptFail;
opts.context = (void*)OPT_SEND;
pubmsg.payload = (void*)payload.c_str();
pubmsg.payloadlen = payload.length();
pubmsg.qos = qos;
pubmsg.retained = 0;
LOGD("客户机当前连接服务器状态 :%d mqtt send payload len:%d, QOS:%d.\n",connite,pubmsg.payloadlen,qos);
if ((rc = MQTTAsync_sendMessage(S_client, topic.c_str(), &pubmsg, &opts)) != MQTTASYNC_SUCCESS){
LOGW("Failed to start sendMessage, return code:%d.\n", rc);
return -1;
}
return 0;
}
int KK_MQTTSDK::reinit(string serverAddr) {
LOGE("MQTT 重新 初始化.\n");
if(this->callbackHandler == NULL){
LOGE("callbackHandler not set.\n");
return -1;
}
if(S_client!=NULL){
LOGE("MQTTAsync handle not NULL.\n");
return -1;
}
if(serverAddr!=""){
this->brokerAddr = serverAddr;
}
MQTTAsync_createOptions opts = MQTTAsync_createOptions_initializer;
opts.MQTTVersion = MQTTVERSION_3_1_1;
int rc = MQTTAsync_createWithOptions(&S_client,(const char* )brokerAddr.c_str(),
(const char* )clientId.c_str(), MQTTCLIENT_PERSISTENCE_NONE,NULL,&opts);
LOGD("MQTTAsync_create new client:0x%0x.\n",S_client);
if(rc != MQTTASYNC_SUCCESS){
LOGW("Failed to create mqtt sdk client, return code %d\n", rc);
return -1;
}
MQTTAsync_setConnectionLostCallback(S_client,NULL,onConnectLost);
MQTTAsync_setMessageArrivedCallback(S_client,NULL,onMessageArrived);
MQTTAsync_setDeliveryCompleteCallback(S_client,NULL,onDeliveryComplete);
MQTTAsync_setConnected(S_client,NULL,onConnectBuild);
MQTTAsync_setDisconnected(S_client,NULL,onDisConnected);
return 0;
}
int KK_MQTTSDK::con(int autoRecon,int timeoutInSec){
if(S_client!=NULL){
//连接状态信息
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
unsigned int seed = time(NULL);
conn_opts.keepAliveInterval = ACE_OS::rand_r(&seed)%120+60;
conn_opts.connectTimeout = timeoutInSec;
conn_opts.automaticReconnect = autoRecon;
conn_opts.minRetryInterval = 1;
conn_opts.maxRetryInterval = 32;
conn_opts.username = this->username.c_str();
conn_opts.password = this->password.c_str();
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnectSuccess;
conn_opts.onFailure = onConnectFailure;
LOGD("MQTTAsync_connectOptions [keepAliveInterval:%d,automaticReconnect:%d,"
"minRetryInterval:%d,maxRetryInterval:%d,cleansession:%d]\n",
conn_opts.keepAliveInterval,conn_opts.automaticReconnect,conn_opts.minRetryInterval,
conn_opts.maxRetryInterval,conn_opts.cleansession);
//遗嘱信息
MQTTAsync_willOptions will_opts = MQTTAsync_willOptions_initializer;
will_opts.topicName = willTopic.c_str();
will_opts.qos = 0;
will_opts.retained = 0;
will_opts.message= "offline";
conn_opts.will = &will_opts;
if(brokerAddr.substr(0,3)=="ssl"){
LOGI("connect to broker use ssl.\n");
MQTTAsync_SSLOptions ssl_opts = MQTTAsync_SSLOptions_initializer;
ssl_opts.verify = 0;
ssl_opts.enableServerCertAuth = 0;
conn_opts.ssl = &ssl_opts;
}else{
LOGI("connect to broker use tcp.\n");
conn_opts.ssl = NULL;
}
int rc = 0;
LOGI("MQTTAsync_connect for client:0x%0x.\n",S_client);
if ((rc = MQTTAsync_connect(S_client, &conn_opts)) != MQTTASYNC_SUCCESS){
LOGW("Failed to start connect, return code %d\n", rc);
return -1;
}
/*线程标识符。属性类型的结构不是故意暴露。*/
pthread_t tid;
/*创建一个新线程,从执行START-ROUTINE开始
正在传递ARG。创造属性来自属性。新的
句柄存储在*NEWTHREAD中。*/
pthread_create(&tid, NULL, run0, this);
}
return -1;
}
void* KK_MQTTSDK::run0(void* opt) {
KK_MQTTSDK* mqttheartbeat_pthread = (KK_MQTTSDK*) opt; //这个的含义是什么?
return mqttheartbeat_pthread->run(opt);
}
void* KK_MQTTSDK::run(void* opt){
while (true) {
EH::Json::FastWriter writer;
EH::Json::Value Payload;
Payload["gw_id"] = gw_id;
string sendPayload = writer.write(Payload);
//与Roma平台30秒心跳
sleep(30);
LOGD("Topic:%s Payload:%s\n",heartbeat_Topic.c_str(),sendPayload.c_str());
sendMsg(heartbeat_Topic,sendPayload,0);
}
//delete this;
return NULL;
}
int KK_MQTTSDK::discon(){
int rc = MQTTAsync_isConnected(S_client);
LOGI("client:0x%0x is connected:%d.\n",S_client,rc);
if(S_client!=NULL){
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int ret = MQTTAsync_disconnect(S_client,&opts);
LOGI("MQTTAsync_disconnect ret:%d.\n",ret);
return ret;
}
return -1;
}
int KK_MQTTSDK::destroy(){
S_Working = false;
if(S_client!=NULL){
LOGI("MQTTAsync_destroy client:0x%0x.\n",S_client);
MQTTAsync_destroy(&S_client);
S_client = NULL;
}
return 0;
}
/*
* EH_Util.cpp
*
* Copyright by AirDream Co., Ltd. 2010-2011 All right reserved
*
* Description:
* Created on:2013-5-31
* Modified on:####-##-##
*
*/
#include "KK_Util.h"
#include <sys/time.h>
int StringToHex(const char* input, unsigned char* output,const int bufLen) {
int i, len = strlen(input);
int j = 0; //length
for (i = 0; i < len; i += 3) {
if(j > bufLen) {
return -1;
}
int c;
sscanf(input + i, "%02X", &c);
*(output + j) = c;
j++;
}
return j;
}
int StringToHexNoSpace(const char* input, unsigned char* output,const int bufLen) {
int i, len = strlen(input);
int j = 0; //length
for (i = 0; i < len; i += 2) {
if(j > bufLen) {
return -1;
}
int c;
sscanf(input + i, "%02X", &c);
*(output + j) = c;
j++;
}
return j;
}
int HexToString(const char* input, char* output, int len,const char* sep) {
char * p = output;
int total = 0, ret;
for (int i = 0; i < len; i++) {
ret = sprintf(p, "%02X", (unsigned char) (*(input + i)));
p += ret;
total += ret;
if (i < len - 1) {
*p = *sep;
}
++p;
++total;
}
return total;
}
void Split(const string& src, const string& separator, vector<string>& dest) {
if (src == "") {
return;
}
string str = src;
string substring;
string::size_type start = 0, index;
do {
index = str.find_first_of(separator, start);
if (index != string::npos) {
substring = str.substr(start, index - start);
dest.push_back(substring);
start = str.find_first_not_of(separator, index);
if (start == string::npos) {
dest.push_back("");
return;
}
if (start != (index + 1)) {
int separatorCount = start - index - 1;
for (int i = 0; i < separatorCount; i++) {
dest.push_back("");
}
}
}
} while (index != string::npos);
substring = str.substr(start);
dest.push_back(substring);
}
string Replace(const string& str, const string& src, const string& dest)
{
string ret;
string::size_type pos_begin = 0;
string::size_type pos = str.find(src);
while (pos != string::npos)
{
ret.append(str.data() + pos_begin, pos - pos_begin);
ret += dest;
pos_begin = pos + 1;
pos = str.find(src, pos_begin);
}
if (pos_begin < str.length())
{
ret.append(str.begin() + pos_begin, str.end());
}
return ret;
}
string IntToString(const int input) {
stringstream oss;
oss << input;
string output;
oss >> output;
return output;
}
string UIntToString(const uint input) {
stringstream oss;
oss << input;
string output;
oss >> output;
return output;
}
int StringToInt(const string input,int& error) {
stringstream oss;
oss << input;
int output = 0;
oss >> output;
if (oss.fail() || !oss.eof()) {
error = -1;
} else {
error = 0;
}
return output;
}
uint StringToUInt(const string input,int& error) {
stringstream oss;
oss << input;
uint output = 0;
oss >> output;
if (oss.fail() || !oss.eof()) {
error = -1;
} else {
error = 0;
}
return output;
}
double StringToDouble(const string input,int& error) {
stringstream oss;
oss << input;
double output = 0;
oss >> output;
if (oss.fail() || !oss.eof()) {
error = -1;
} else {
error = 0;
}
return output;
}
string DoubleToString(const double input,int& error) {
stringstream oss;
oss << input;
if (oss.fail() || !oss.eof()) {
error = -1;
} else {
error = 0;
}
return oss.str();
}
unsigned long getSystemTimeInMs() {
struct timeval now;
gettimeofday(&now, 0);
unsigned long nowInMs = (unsigned long )now.tv_sec * 1000;
nowInMs += now.tv_usec / 1000;
return nowInMs;
}
/*
* LSC_Logger.cpp
*
* Created on: 2014-4-10
* Author: sj
*/
#include "LSC_Logger.h"
/*
* no use...
* just for test ACE_Object_Manager::at_exit.
*/
void LSC_ProcessExitLog::cleanup (void *param) {
ACE_UNUSED_ARG(param);
LOGN("Process Exit!\n");
}
LSC_Logger::LSC_Logger(){
curr_log_leave = LM_INFO;
ACE_Object_Manager::instance()->at_exit(new LSC_ProcessExitLog());
}
LSC_Logger::~LSC_Logger() {
LOGI("~LSC_Logger()\n");
}
int LSC_Logger::open(string process_name,string log_leave) {
ACE_LOG_MSG->open(process_name.c_str(), ACE_Log_Msg::SYSLOG|ACE_Log_Msg::STDERR);
/*
* log leave setting
*/
return set_log_leave(log_leave);
}
int LSC_Logger::set_log_leave(string log_leave) {
if (log_leave == "D") {/*debug*/
ACE_LOG_MSG->priority_mask(
LM_DEBUG | LM_INFO | LM_NOTICE | LM_WARNING | LM_ERROR,
ACE_Log_Msg::PROCESS);
ACE_LOG_MSG->priority_mask(
LM_DEBUG | LM_INFO | LM_NOTICE | LM_WARNING | LM_ERROR,
ACE_Log_Msg::THREAD);
curr_log_leave = LM_DEBUG;
} else if (log_leave == "I") {/*info*/
ACE_LOG_MSG->priority_mask(LM_INFO | LM_NOTICE | LM_WARNING | LM_ERROR,
ACE_Log_Msg::PROCESS);
ACE_LOG_MSG->priority_mask(LM_INFO | LM_NOTICE | LM_WARNING | LM_ERROR,
ACE_Log_Msg::THREAD);
curr_log_leave = LM_INFO;
} else if (log_leave == "N") {/*notice*/
ACE_LOG_MSG->priority_mask(LM_NOTICE | LM_WARNING | LM_ERROR,
ACE_Log_Msg::PROCESS);
ACE_LOG_MSG->priority_mask(LM_NOTICE | LM_WARNING | LM_ERROR,
ACE_Log_Msg::THREAD);
curr_log_leave = LM_NOTICE;
} else if (log_leave == "W") {/*warning*/
ACE_LOG_MSG->priority_mask(LM_WARNING | LM_ERROR, ACE_Log_Msg::PROCESS);
ACE_LOG_MSG->priority_mask(LM_WARNING | LM_ERROR, ACE_Log_Msg::THREAD);
curr_log_leave = LM_WARNING;
} else if (log_leave == "E") {/*error*/
ACE_LOG_MSG->priority_mask(LM_ERROR, ACE_Log_Msg::PROCESS);
ACE_LOG_MSG->priority_mask(LM_ERROR, ACE_Log_Msg::THREAD);
curr_log_leave = LM_ERROR;
} else {
LOGW("Unknown log leave:%s.\n", log_leave.c_str());
return -1;
}
// LOGI("Now log leave:%s.\n",log_leave.c_str());
return 0;
}
ACE_Log_Priority LSC_Logger::get_log_leave() {
return curr_log_leave;
}
// included by json_value.cpp
// everything is within Json namespace
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueInternalArray
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueArrayAllocator::~ValueArrayAllocator()
{
}
// //////////////////////////////////////////////////////////////////
// class DefaultValueArrayAllocator
// //////////////////////////////////////////////////////////////////
#ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
class DefaultValueArrayAllocator : public ValueArrayAllocator
{
public: // overridden from ValueArrayAllocator
virtual ~DefaultValueArrayAllocator()
{
}
virtual ValueInternalArray *newArray()
{
return new ValueInternalArray();
}
virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other )
{
return new ValueInternalArray( other );
}
virtual void destructArray( ValueInternalArray *array )
{
delete array;
}
virtual void reallocateArrayPageIndex( Value **&indexes,
ValueInternalArray::PageIndex &indexCount,
ValueInternalArray::PageIndex minNewIndexCount )
{
ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1;
if ( minNewIndexCount > newIndexCount )
newIndexCount = minNewIndexCount;
void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount );
if ( !newIndexes )
throw std::bad_alloc();
indexCount = newIndexCount;
indexes = static_cast<Value **>( newIndexes );
}
virtual void releaseArrayPageIndex( Value **indexes,
ValueInternalArray::PageIndex indexCount )
{
if ( indexes )
free( indexes );
}
virtual Value *allocateArrayPage()
{
return static_cast<Value *>( malloc( sizeof(Value) * ValueInternalArray::itemsPerPage ) );
}
virtual void releaseArrayPage( Value *value )
{
if ( value )
free( value );
}
};
#else // #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
/// @todo make this thread-safe (lock when accessign batch allocator)
class DefaultValueArrayAllocator : public ValueArrayAllocator
{
public: // overridden from ValueArrayAllocator
virtual ~DefaultValueArrayAllocator()
{
}
virtual ValueInternalArray *newArray()
{
ValueInternalArray *array = arraysAllocator_.allocate();
new (array) ValueInternalArray(); // placement new
return array;
}
virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other )
{
ValueInternalArray *array = arraysAllocator_.allocate();
new (array) ValueInternalArray( other ); // placement new
return array;
}
virtual void destructArray( ValueInternalArray *array )
{
if ( array )
{
array->~ValueInternalArray();
arraysAllocator_.release( array );
}
}
virtual void reallocateArrayPageIndex( Value **&indexes,
ValueInternalArray::PageIndex &indexCount,
ValueInternalArray::PageIndex minNewIndexCount )
{
ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1;
if ( minNewIndexCount > newIndexCount )
newIndexCount = minNewIndexCount;
void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount );
if ( !newIndexes )
throw std::bad_alloc();
indexCount = newIndexCount;
indexes = static_cast<Value **>( newIndexes );
}
virtual void releaseArrayPageIndex( Value **indexes,
ValueInternalArray::PageIndex indexCount )
{
if ( indexes )
free( indexes );
}
virtual Value *allocateArrayPage()
{
return static_cast<Value *>( pagesAllocator_.allocate() );
}
virtual void releaseArrayPage( Value *value )
{
if ( value )
pagesAllocator_.release( value );
}
private:
BatchAllocator<ValueInternalArray,1> arraysAllocator_;
BatchAllocator<Value,ValueInternalArray::itemsPerPage> pagesAllocator_;
};
#endif // #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
static ValueArrayAllocator *&arrayAllocator()
{
static DefaultValueArrayAllocator defaultAllocator;
static ValueArrayAllocator *arrayAllocator = &defaultAllocator;
return arrayAllocator;
}
static struct DummyArrayAllocatorInitializer {
DummyArrayAllocatorInitializer()
{
arrayAllocator(); // ensure arrayAllocator() statics are initialized before main().
}
} dummyArrayAllocatorInitializer;
// //////////////////////////////////////////////////////////////////
// class ValueInternalArray
// //////////////////////////////////////////////////////////////////
bool
ValueInternalArray::equals( const IteratorState &x,
const IteratorState &other )
{
return x.array_ == other.array_
&& x.currentItemIndex_ == other.currentItemIndex_
&& x.currentPageIndex_ == other.currentPageIndex_;
}
void
ValueInternalArray::increment( IteratorState &it )
{
JSON_ASSERT_MESSAGE( it.array_ &&
(it.currentPageIndex_ - it.array_->pages_)*itemsPerPage + it.currentItemIndex_
!= it.array_->size_,
"ValueInternalArray::increment(): moving iterator beyond end" );
++(it.currentItemIndex_);
if ( it.currentItemIndex_ == itemsPerPage )
{
it.currentItemIndex_ = 0;
++(it.currentPageIndex_);
}
}
void
ValueInternalArray::decrement( IteratorState &it )
{
JSON_ASSERT_MESSAGE( it.array_ && it.currentPageIndex_ == it.array_->pages_
&& it.currentItemIndex_ == 0,
"ValueInternalArray::decrement(): moving iterator beyond end" );
if ( it.currentItemIndex_ == 0 )
{
it.currentItemIndex_ = itemsPerPage-1;
--(it.currentPageIndex_);
}
else
{
--(it.currentItemIndex_);
}
}
Value &
ValueInternalArray::unsafeDereference( const IteratorState &it )
{
return (*(it.currentPageIndex_))[it.currentItemIndex_];
}
Value &
ValueInternalArray::dereference( const IteratorState &it )
{
JSON_ASSERT_MESSAGE( it.array_ &&
(it.currentPageIndex_ - it.array_->pages_)*itemsPerPage + it.currentItemIndex_
< it.array_->size_,
"ValueInternalArray::dereference(): dereferencing invalid iterator" );
return unsafeDereference( it );
}
void
ValueInternalArray::makeBeginIterator( IteratorState &it ) const
{
it.array_ = const_cast<ValueInternalArray *>( this );
it.currentItemIndex_ = 0;
it.currentPageIndex_ = pages_;
}
void
ValueInternalArray::makeIterator( IteratorState &it, ArrayIndex index ) const
{
it.array_ = const_cast<ValueInternalArray *>( this );
it.currentItemIndex_ = index % itemsPerPage;
it.currentPageIndex_ = pages_ + index / itemsPerPage;
}
void
ValueInternalArray::makeEndIterator( IteratorState &it ) const
{
makeIterator( it, size_ );
}
ValueInternalArray::ValueInternalArray()
: pages_( 0 )
, size_( 0 )
, pageCount_( 0 )
{
}
ValueInternalArray::ValueInternalArray( const ValueInternalArray &other )
: pages_( 0 )
, pageCount_( 0 )
, size_( other.size_ )
{
PageIndex minNewPages = other.size_ / itemsPerPage;
arrayAllocator()->reallocateArrayPageIndex( pages_, pageCount_, minNewPages );
JSON_ASSERT_MESSAGE( pageCount_ >= minNewPages,
"ValueInternalArray::reserve(): bad reallocation" );
IteratorState itOther;
other.makeBeginIterator( itOther );
Value *value;
for ( ArrayIndex index = 0; index < size_; ++index, increment(itOther) )
{
if ( index % itemsPerPage == 0 )
{
PageIndex pageIndex = index / itemsPerPage;
value = arrayAllocator()->allocateArrayPage();
pages_[pageIndex] = value;
}
new (value) Value( dereference( itOther ) );
}
}
ValueInternalArray &
ValueInternalArray::operator =( const ValueInternalArray &other )
{
ValueInternalArray temp( other );
swap( temp );
return *this;
}
ValueInternalArray::~ValueInternalArray()
{
// destroy all constructed items
IteratorState it;
IteratorState itEnd;
makeBeginIterator( it);
makeEndIterator( itEnd );
for ( ; !equals(it,itEnd); increment(it) )
{
Value *value = &dereference(it);
value->~Value();
}
// release all pages
PageIndex lastPageIndex = size_ / itemsPerPage;
for ( PageIndex pageIndex = 0; pageIndex < lastPageIndex; ++pageIndex )
arrayAllocator()->releaseArrayPage( pages_[pageIndex] );
// release pages index
arrayAllocator()->releaseArrayPageIndex( pages_, pageCount_ );
}
void
ValueInternalArray::swap( ValueInternalArray &other )
{
Value **tempPages = pages_;
pages_ = other.pages_;
other.pages_ = tempPages;
ArrayIndex tempSize = size_;
size_ = other.size_;
other.size_ = tempSize;
PageIndex tempPageCount = pageCount_;
pageCount_ = other.pageCount_;
other.pageCount_ = tempPageCount;
}
void
ValueInternalArray::clear()
{
ValueInternalArray dummy;
swap( dummy );
}
void
ValueInternalArray::resize( ArrayIndex newSize )
{
if ( newSize == 0 )
clear();
else if ( newSize < size_ )
{
IteratorState it;
IteratorState itEnd;
makeIterator( it, newSize );
makeIterator( itEnd, size_ );
for ( ; !equals(it,itEnd); increment(it) )
{
Value *value = &dereference(it);
value->~Value();
}
PageIndex pageIndex = (newSize + itemsPerPage - 1) / itemsPerPage;
PageIndex lastPageIndex = size_ / itemsPerPage;
for ( ; pageIndex < lastPageIndex; ++pageIndex )
arrayAllocator()->releaseArrayPage( pages_[pageIndex] );
size_ = newSize;
}
else if ( newSize > size_ )
resolveReference( newSize );
}
void
ValueInternalArray::makeIndexValid( ArrayIndex index )
{
// Need to enlarge page index ?
if ( index >= pageCount_ * itemsPerPage )
{
PageIndex minNewPages = (index + 1) / itemsPerPage;
arrayAllocator()->reallocateArrayPageIndex( pages_, pageCount_, minNewPages );
JSON_ASSERT_MESSAGE( pageCount_ >= minNewPages, "ValueInternalArray::reserve(): bad reallocation" );
}
// Need to allocate new pages ?
ArrayIndex nextPageIndex =
(size_ % itemsPerPage) != 0 ? size_ - (size_%itemsPerPage) + itemsPerPage
: size_;
if ( nextPageIndex <= index )
{
PageIndex pageIndex = nextPageIndex / itemsPerPage;
PageIndex pageToAllocate = (index - nextPageIndex) / itemsPerPage + 1;
for ( ; pageToAllocate-- > 0; ++pageIndex )
pages_[pageIndex] = arrayAllocator()->allocateArrayPage();
}
// Initialize all new entries
IteratorState it;
IteratorState itEnd;
makeIterator( it, size_ );
size_ = index + 1;
makeIterator( itEnd, size_ );
for ( ; !equals(it,itEnd); increment(it) )
{
Value *value = &dereference(it);
new (value) Value(); // Construct a default value using placement new
}
}
Value &
ValueInternalArray::resolveReference( ArrayIndex index )
{
if ( index >= size_ )
makeIndexValid( index );
return pages_[index/itemsPerPage][index%itemsPerPage];
}
Value *
ValueInternalArray::find( ArrayIndex index ) const
{
if ( index >= size_ )
return 0;
return &(pages_[index/itemsPerPage][index%itemsPerPage]);
}
ValueInternalArray::ArrayIndex
ValueInternalArray::size() const
{
return size_;
}
int
ValueInternalArray::distance( const IteratorState &x, const IteratorState &y )
{
return indexOf(y) - indexOf(x);
}
ValueInternalArray::ArrayIndex
ValueInternalArray::indexOf( const IteratorState &iterator )
{
if ( !iterator.array_ )
return ArrayIndex(-1);
return ArrayIndex(
(iterator.currentPageIndex_ - iterator.array_->pages_) * itemsPerPage
+ iterator.currentItemIndex_ );
}
int
ValueInternalArray::compare( const ValueInternalArray &other ) const
{
int sizeDiff( size_ - other.size_ );
if ( sizeDiff != 0 )
return sizeDiff;
for ( ArrayIndex index =0; index < size_; ++index )
{
int diff = pages_[index/itemsPerPage][index%itemsPerPage].compare(
other.pages_[index/itemsPerPage][index%itemsPerPage] );
if ( diff != 0 )
return diff;
}
return 0;
}
// included by json_value.cpp
// everything is within Json namespace
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueInternalMap
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
/** \internal MUST be safely initialized using memset( this, 0, sizeof(ValueInternalLink) );
* This optimization is used by the fast allocator.
*/
ValueInternalLink::ValueInternalLink()
: previous_( 0 )
, next_( 0 )
{
}
ValueInternalLink::~ValueInternalLink()
{
for ( int index =0; index < itemPerLink; ++index )
{
if ( !items_[index].isItemAvailable() )
{
if ( !items_[index].isMemberNameStatic() )
free( keys_[index] );
}
else
break;
}
}
ValueMapAllocator::~ValueMapAllocator()
{
}
#ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
class DefaultValueMapAllocator : public ValueMapAllocator
{
public: // overridden from ValueMapAllocator
virtual ValueInternalMap *newMap()
{
return new ValueInternalMap();
}
virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other )
{
return new ValueInternalMap( other );
}
virtual void destructMap( ValueInternalMap *map )
{
delete map;
}
virtual ValueInternalLink *allocateMapBuckets( unsigned int size )
{
return new ValueInternalLink[size];
}
virtual void releaseMapBuckets( ValueInternalLink *links )
{
delete [] links;
}
virtual ValueInternalLink *allocateMapLink()
{
return new ValueInternalLink();
}
virtual void releaseMapLink( ValueInternalLink *link )
{
delete link;
}
};
#else
/// @todo make this thread-safe (lock when accessign batch allocator)
class DefaultValueMapAllocator : public ValueMapAllocator
{
public: // overridden from ValueMapAllocator
virtual ValueInternalMap *newMap()
{
ValueInternalMap *map = mapsAllocator_.allocate();
new (map) ValueInternalMap(); // placement new
return map;
}
virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other )
{
ValueInternalMap *map = mapsAllocator_.allocate();
new (map) ValueInternalMap( other ); // placement new
return map;
}
virtual void destructMap( ValueInternalMap *map )
{
if ( map )
{
map->~ValueInternalMap();
mapsAllocator_.release( map );
}
}
virtual ValueInternalLink *allocateMapBuckets( unsigned int size )
{
return new ValueInternalLink[size];
}
virtual void releaseMapBuckets( ValueInternalLink *links )
{
delete [] links;
}
virtual ValueInternalLink *allocateMapLink()
{
ValueInternalLink *link = linksAllocator_.allocate();
memset( link, 0, sizeof(ValueInternalLink) );
return link;
}
virtual void releaseMapLink( ValueInternalLink *link )
{
link->~ValueInternalLink();
linksAllocator_.release( link );
}
private:
BatchAllocator<ValueInternalMap,1> mapsAllocator_;
BatchAllocator<ValueInternalLink,1> linksAllocator_;
};
#endif
static ValueMapAllocator *&mapAllocator()
{
static DefaultValueMapAllocator defaultAllocator;
static ValueMapAllocator *mapAllocator = &defaultAllocator;
return mapAllocator;
}
static struct DummyMapAllocatorInitializer {
DummyMapAllocatorInitializer()
{
mapAllocator(); // ensure mapAllocator() statics are initialized before main().
}
} dummyMapAllocatorInitializer;
// h(K) = value * K >> w ; with w = 32 & K prime w.r.t. 2^32.
/*
use linked list hash map.
buckets array is a container.
linked list element contains 6 key/values. (memory = (16+4) * 6 + 4 = 124)
value have extra state: valid, available, deleted
*/
ValueInternalMap::ValueInternalMap()
: buckets_( 0 )
, tailLink_( 0 )
, bucketsSize_( 0 )
, itemCount_( 0 )
{
}
ValueInternalMap::ValueInternalMap( const ValueInternalMap &other )
: buckets_( 0 )
, tailLink_( 0 )
, bucketsSize_( 0 )
, itemCount_( 0 )
{
reserve( other.itemCount_ );
IteratorState it;
IteratorState itEnd;
other.makeBeginIterator( it );
other.makeEndIterator( itEnd );
for ( ; !equals(it,itEnd); increment(it) )
{
bool isStatic;
const char *memberName = key( it, isStatic );
const Value &aValue = value( it );
resolveReference(memberName, isStatic) = aValue;
}
}
ValueInternalMap &
ValueInternalMap::operator =( const ValueInternalMap &other )
{
ValueInternalMap dummy( other );
swap( dummy );
return *this;
}
ValueInternalMap::~ValueInternalMap()
{
if ( buckets_ )
{
for ( BucketIndex bucketIndex =0; bucketIndex < bucketsSize_; ++bucketIndex )
{
ValueInternalLink *link = buckets_[bucketIndex].next_;
while ( link )
{
ValueInternalLink *linkToRelease = link;
link = link->next_;
mapAllocator()->releaseMapLink( linkToRelease );
}
}
mapAllocator()->releaseMapBuckets( buckets_ );
}
}
void
ValueInternalMap::swap( ValueInternalMap &other )
{
ValueInternalLink *tempBuckets = buckets_;
buckets_ = other.buckets_;
other.buckets_ = tempBuckets;
ValueInternalLink *tempTailLink = tailLink_;
tailLink_ = other.tailLink_;
other.tailLink_ = tempTailLink;
BucketIndex tempBucketsSize = bucketsSize_;
bucketsSize_ = other.bucketsSize_;
other.bucketsSize_ = tempBucketsSize;
BucketIndex tempItemCount = itemCount_;
itemCount_ = other.itemCount_;
other.itemCount_ = tempItemCount;
}
void
ValueInternalMap::clear()
{
ValueInternalMap dummy;
swap( dummy );
}
ValueInternalMap::BucketIndex
ValueInternalMap::size() const
{
return itemCount_;
}
bool
ValueInternalMap::reserveDelta( BucketIndex growth )
{
return reserve( itemCount_ + growth );
}
bool
ValueInternalMap::reserve( BucketIndex newItemCount )
{
if ( !buckets_ && newItemCount > 0 )
{
buckets_ = mapAllocator()->allocateMapBuckets( 1 );
bucketsSize_ = 1;
tailLink_ = &buckets_[0];
}
// BucketIndex idealBucketCount = (newItemCount + ValueInternalLink::itemPerLink) / ValueInternalLink::itemPerLink;
return true;
}
const Value *
ValueInternalMap::find( const char *key ) const
{
if ( !bucketsSize_ )
return 0;
HashKey hashedKey = hash( key );
BucketIndex bucketIndex = hashedKey % bucketsSize_;
for ( const ValueInternalLink *current = &buckets_[bucketIndex];
current != 0;
current = current->next_ )
{
for ( BucketIndex index=0; index < ValueInternalLink::itemPerLink; ++index )
{
if ( current->items_[index].isItemAvailable() )
return 0;
if ( strcmp( key, current->keys_[index] ) == 0 )
return &current->items_[index];
}
}
return 0;
}
Value *
ValueInternalMap::find( const char *key )
{
const ValueInternalMap *constThis = this;
return const_cast<Value *>( constThis->find( key ) );
}
Value &
ValueInternalMap::resolveReference( const char *key,
bool isStatic )
{
HashKey hashedKey = hash( key );
if ( bucketsSize_ )
{
BucketIndex bucketIndex = hashedKey % bucketsSize_;
ValueInternalLink **previous = 0;
BucketIndex index;
for ( ValueInternalLink *current = &buckets_[bucketIndex];
current != 0;
previous = &current->next_, current = current->next_ )
{
for ( index=0; index < ValueInternalLink::itemPerLink; ++index )
{
if ( current->items_[index].isItemAvailable() )
return setNewItem( key, isStatic, current, index );
if ( strcmp( key, current->keys_[index] ) == 0 )
return current->items_[index];
}
}
}
reserveDelta( 1 );
return unsafeAdd( key, isStatic, hashedKey );
}
void
ValueInternalMap::remove( const char *key )
{
HashKey hashedKey = hash( key );
if ( !bucketsSize_ )
return;
BucketIndex bucketIndex = hashedKey % bucketsSize_;
for ( ValueInternalLink *link = &buckets_[bucketIndex];
link != 0;
link = link->next_ )
{
BucketIndex index;
for ( index =0; index < ValueInternalLink::itemPerLink; ++index )
{
if ( link->items_[index].isItemAvailable() )
return;
if ( strcmp( key, link->keys_[index] ) == 0 )
{
doActualRemove( link, index, bucketIndex );
return;
}
}
}
}
void
ValueInternalMap::doActualRemove( ValueInternalLink *link,
BucketIndex index,
BucketIndex bucketIndex )
{
// find last item of the bucket and swap it with the 'removed' one.
// set removed items flags to 'available'.
// if last page only contains 'available' items, then desallocate it (it's empty)
ValueInternalLink *&lastLink = getLastLinkInBucket( index );
BucketIndex lastItemIndex = 1; // a link can never be empty, so start at 1
for ( ;
lastItemIndex < ValueInternalLink::itemPerLink;
++lastItemIndex ) // may be optimized with dicotomic search
{
if ( lastLink->items_[lastItemIndex].isItemAvailable() )
break;
}
BucketIndex lastUsedIndex = lastItemIndex - 1;
Value *valueToDelete = &link->items_[index];
Value *valueToPreserve = &lastLink->items_[lastUsedIndex];
if ( valueToDelete != valueToPreserve )
valueToDelete->swap( *valueToPreserve );
if ( lastUsedIndex == 0 ) // page is now empty
{ // remove it from bucket linked list and delete it.
ValueInternalLink *linkPreviousToLast = lastLink->previous_;
if ( linkPreviousToLast != 0 ) // can not deleted bucket link.
{
mapAllocator()->releaseMapLink( lastLink );
linkPreviousToLast->next_ = 0;
lastLink = linkPreviousToLast;
}
}
else
{
Value dummy;
valueToPreserve->swap( dummy ); // restore deleted to default Value.
valueToPreserve->setItemUsed( false );
}
--itemCount_;
}
ValueInternalLink *&
ValueInternalMap::getLastLinkInBucket( BucketIndex bucketIndex )
{
if ( bucketIndex == bucketsSize_ - 1 )
return tailLink_;
ValueInternalLink *&previous = buckets_[bucketIndex+1].previous_;
if ( !previous )
previous = &buckets_[bucketIndex];
return previous;
}
Value &
ValueInternalMap::setNewItem( const char *key,
bool isStatic,
ValueInternalLink *link,
BucketIndex index )
{
char *duplicatedKey = valueAllocator()->makeMemberName( key );
++itemCount_;
link->keys_[index] = duplicatedKey;
link->items_[index].setItemUsed();
link->items_[index].setMemberNameIsStatic( isStatic );
return link->items_[index]; // items already default constructed.
}
Value &
ValueInternalMap::unsafeAdd( const char *key,
bool isStatic,
HashKey hashedKey )
{
JSON_ASSERT_MESSAGE( bucketsSize_ > 0, "ValueInternalMap::unsafeAdd(): internal logic error." );
BucketIndex bucketIndex = hashedKey % bucketsSize_;
ValueInternalLink *&previousLink = getLastLinkInBucket( bucketIndex );
ValueInternalLink *link = previousLink;
BucketIndex index;
for ( index =0; index < ValueInternalLink::itemPerLink; ++index )
{
if ( link->items_[index].isItemAvailable() )
break;
}
if ( index == ValueInternalLink::itemPerLink ) // need to add a new page
{
ValueInternalLink *newLink = mapAllocator()->allocateMapLink();
index = 0;
link->next_ = newLink;
previousLink = newLink;
link = newLink;
}
return setNewItem( key, isStatic, link, index );
}
ValueInternalMap::HashKey
ValueInternalMap::hash( const char *key ) const
{
HashKey hash = 0;
while ( *key )
hash += *key++ * 37;
return hash;
}
int
ValueInternalMap::compare( const ValueInternalMap &other ) const
{
int sizeDiff( itemCount_ - other.itemCount_ );
if ( sizeDiff != 0 )
return sizeDiff;
// Strict order guaranty is required. Compare all keys FIRST, then compare values.
IteratorState it;
IteratorState itEnd;
makeBeginIterator( it );
makeEndIterator( itEnd );
for ( ; !equals(it,itEnd); increment(it) )
{
if ( !other.find( key( it ) ) )
return 1;
}
// All keys are equals, let's compare values
makeBeginIterator( it );
for ( ; !equals(it,itEnd); increment(it) )
{
const Value *otherValue = other.find( key( it ) );
int valueDiff = value(it).compare( *otherValue );
if ( valueDiff != 0 )
return valueDiff;
}
return 0;
}
void
ValueInternalMap::makeBeginIterator( IteratorState &it ) const
{
it.map_ = const_cast<ValueInternalMap *>( this );
it.bucketIndex_ = 0;
it.itemIndex_ = 0;
it.link_ = buckets_;
}
void
ValueInternalMap::makeEndIterator( IteratorState &it ) const
{
it.map_ = const_cast<ValueInternalMap *>( this );
it.bucketIndex_ = bucketsSize_;
it.itemIndex_ = 0;
it.link_ = 0;
}
bool
ValueInternalMap::equals( const IteratorState &x, const IteratorState &other )
{
return x.map_ == other.map_
&& x.bucketIndex_ == other.bucketIndex_
&& x.link_ == other.link_
&& x.itemIndex_ == other.itemIndex_;
}
void
ValueInternalMap::incrementBucket( IteratorState &iterator )
{
++iterator.bucketIndex_;
JSON_ASSERT_MESSAGE( iterator.bucketIndex_ <= iterator.map_->bucketsSize_,
"ValueInternalMap::increment(): attempting to iterate beyond end." );
if ( iterator.bucketIndex_ == iterator.map_->bucketsSize_ )
iterator.link_ = 0;
else
iterator.link_ = &(iterator.map_->buckets_[iterator.bucketIndex_]);
iterator.itemIndex_ = 0;
}
void
ValueInternalMap::increment( IteratorState &iterator )
{
JSON_ASSERT_MESSAGE( iterator.map_, "Attempting to iterator using invalid iterator." );
++iterator.itemIndex_;
if ( iterator.itemIndex_ == ValueInternalLink::itemPerLink )
{
JSON_ASSERT_MESSAGE( iterator.link_ != 0,
"ValueInternalMap::increment(): attempting to iterate beyond end." );
iterator.link_ = iterator.link_->next_;
if ( iterator.link_ == 0 )
incrementBucket( iterator );
}
else if ( iterator.link_->items_[iterator.itemIndex_].isItemAvailable() )
{
incrementBucket( iterator );
}
}
void
ValueInternalMap::decrement( IteratorState &iterator )
{
if ( iterator.itemIndex_ == 0 )
{
JSON_ASSERT_MESSAGE( iterator.map_, "Attempting to iterate using invalid iterator." );
if ( iterator.link_ == &iterator.map_->buckets_[iterator.bucketIndex_] )
{
JSON_ASSERT_MESSAGE( iterator.bucketIndex_ > 0, "Attempting to iterate beyond beginning." );
--(iterator.bucketIndex_);
}
iterator.link_ = iterator.link_->previous_;
iterator.itemIndex_ = ValueInternalLink::itemPerLink - 1;
}
}
const char *
ValueInternalMap::key( const IteratorState &iterator )
{
JSON_ASSERT_MESSAGE( iterator.link_, "Attempting to iterate using invalid iterator." );
return iterator.link_->keys_[iterator.itemIndex_];
}
const char *
ValueInternalMap::key( const IteratorState &iterator, bool &isStatic )
{
JSON_ASSERT_MESSAGE( iterator.link_, "Attempting to iterate using invalid iterator." );
isStatic = iterator.link_->items_[iterator.itemIndex_].isMemberNameStatic();
return iterator.link_->keys_[iterator.itemIndex_];
}
Value &
ValueInternalMap::value( const IteratorState &iterator )
{
JSON_ASSERT_MESSAGE( iterator.link_, "Attempting to iterate using invalid iterator." );
return iterator.link_->items_[iterator.itemIndex_];
}
int
ValueInternalMap::distance( const IteratorState &x, const IteratorState &y )
{
int offset = 0;
IteratorState it = x;
while ( !equals( it, y ) )
increment( it );
return offset;
}
#include "../../include/json/reader.h"
#include "../../include/json/value.h"
#include <utility>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <iostream>
#include <stdexcept>
#if _MSC_VER >= 1400 // VC++ 8.0
#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated.
#endif
namespace EH{
namespace Json {
// Implementation of class Features
// ////////////////////////////////
Features::Features()
: allowComments_( true )
, strictRoot_( false )
{
}
Features
Features::all()
{
return Features();
}
Features
Features::strictMode()
{
Features features;
features.allowComments_ = false;
features.strictRoot_ = true;
return features;
}
// Implementation of class Reader
// ////////////////////////////////
static inline bool
in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 )
{
return c == c1 || c == c2 || c == c3 || c == c4;
}
static inline bool
in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 )
{
return c == c1 || c == c2 || c == c3 || c == c4 || c == c5;
}
static bool
containsNewLine( Reader::Location begin,
Reader::Location end )
{
for ( ;begin < end; ++begin )
if ( *begin == '\n' || *begin == '\r' )
return true;
return false;
}
static std::string codePointToUTF8(unsigned int cp)
{
std::string result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
if (cp <= 0x7f)
{
result.resize(1);
result[0] = static_cast<char>(cp);
}
else if (cp <= 0x7FF)
{
result.resize(2);
result[1] = static_cast<char>(0x80 | (0x3f & cp));
result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
}
else if (cp <= 0xFFFF)
{
result.resize(3);
result[2] = static_cast<char>(0x80 | (0x3f & cp));
result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6)));
result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12)));
}
else if (cp <= 0x10FFFF)
{
result.resize(4);
result[3] = static_cast<char>(0x80 | (0x3f & cp));
result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
}
return result;
}
// Class Reader
// //////////////////////////////////////////////////////////////////
Reader::Reader()
: features_( Features::all() )
{
}
Reader::Reader( const Features &features )
: features_( features )
{
}
bool
Reader::parse( const std::string &document,
Value &root,
bool collectComments )
{
document_ = document;
const char *begin = document_.c_str();
const char *end = begin + document_.length();
return parse( begin, end, root, collectComments );
}
bool
Reader::parse( std::istream& sin,
Value &root,
bool collectComments )
{
//std::istream_iterator<char> begin(sin);
//std::istream_iterator<char> end;
// Those would allow streamed input from a file, if parse() were a
// template function.
// Since std::string is reference-counted, this at least does not
// create an extra copy.
std::string doc;
std::getline(sin, doc, (char)EOF);
return parse( doc, root, collectComments );
}
bool
Reader::parse( const char *beginDoc, const char *endDoc,
Value &root,
bool collectComments )
{
if ( !features_.allowComments_ )
{
collectComments = false;
}
begin_ = beginDoc;
end_ = endDoc;
collectComments_ = collectComments;
current_ = begin_;
lastValueEnd_ = 0;
lastValue_ = 0;
commentsBefore_ = "";
errors_.clear();
while ( !nodes_.empty() )
nodes_.pop();
nodes_.push( &root );
bool successful = readValue();
Token token;
skipCommentTokens( token );
if ( collectComments_ && !commentsBefore_.empty() )
root.setComment( commentsBefore_, commentAfter );
if ( features_.strictRoot_ )
{
if ( !root.isArray() && !root.isObject() )
{
// Set error location to start of doc, ideally should be first token found in doc
token.type_ = tokenError;
token.start_ = beginDoc;
token.end_ = endDoc;
addError( "A valid JSON document must be either an array or an object value.",
token );
return false;
}
}
return successful;
}
bool
Reader::readValue()
{
Token token;
skipCommentTokens( token );
bool successful = true;
if ( collectComments_ && !commentsBefore_.empty() )
{
currentValue().setComment( commentsBefore_, commentBefore );
commentsBefore_ = "";
}
switch ( token.type_ )
{
case tokenObjectBegin:
successful = readObject( token );
break;
case tokenArrayBegin:
successful = readArray( token );
break;
case tokenNumber:
successful = decodeNumber( token );
break;
case tokenString:
successful = decodeString( token );
break;
case tokenTrue:
currentValue() = true;
break;
case tokenFalse:
currentValue() = false;
break;
case tokenNull:
currentValue() = Value();
break;
default:
return addError( "Syntax error: value, object or array expected.", token );
}
if ( collectComments_ )
{
lastValueEnd_ = current_;
lastValue_ = &currentValue();
}
return successful;
}
void
Reader::skipCommentTokens( Token &token )
{
if ( features_.allowComments_ )
{
do
{
readToken( token );
}
while ( token.type_ == tokenComment );
}
else
{
readToken( token );
}
}
bool
Reader::expectToken( TokenType type, Token &token, const char *message )
{
readToken( token );
if ( token.type_ != type )
return addError( message, token );
return true;
}
bool
Reader::readToken( Token &token )
{
skipSpaces();
token.start_ = current_;
Char c = getNextChar();
bool ok = true;
switch ( c )
{
case '{':
token.type_ = tokenObjectBegin;
break;
case '}':
token.type_ = tokenObjectEnd;
break;
case '[':
token.type_ = tokenArrayBegin;
break;
case ']':
token.type_ = tokenArrayEnd;
break;
case '"':
token.type_ = tokenString;
ok = readString();
break;
case '/':
token.type_ = tokenComment;
ok = readComment();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
token.type_ = tokenNumber;
readNumber();
break;
case 't':
token.type_ = tokenTrue;
ok = match( "rue", 3 );
break;
case 'f':
token.type_ = tokenFalse;
ok = match( "alse", 4 );
break;
case 'n':
token.type_ = tokenNull;
ok = match( "ull", 3 );
break;
case ',':
token.type_ = tokenArraySeparator;
break;
case ':':
token.type_ = tokenMemberSeparator;
break;
case 0:
token.type_ = tokenEndOfStream;
break;
default:
ok = false;
break;
}
if ( !ok )
token.type_ = tokenError;
token.end_ = current_;
return true;
}
void
Reader::skipSpaces()
{
while ( current_ != end_ )
{
Char c = *current_;
if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' )
++current_;
else
break;
}
}
bool
Reader::match( Location pattern,
int patternLength )
{
if ( end_ - current_ < patternLength )
return false;
int index = patternLength;
while ( index-- )
if ( current_[index] != pattern[index] )
return false;
current_ += patternLength;
return true;
}
bool
Reader::readComment()
{
Location commentBegin = current_ - 1;
Char c = getNextChar();
bool successful = false;
if ( c == '*' )
successful = readCStyleComment();
else if ( c == '/' )
successful = readCppStyleComment();
if ( !successful )
return false;
if ( collectComments_ )
{
CommentPlacement placement = commentBefore;
if ( lastValueEnd_ && !containsNewLine( lastValueEnd_, commentBegin ) )
{
if ( c != '*' || !containsNewLine( commentBegin, current_ ) )
placement = commentAfterOnSameLine;
}
addComment( commentBegin, current_, placement );
}
return true;
}
void
Reader::addComment( Location begin,
Location end,
CommentPlacement placement )
{
assert( collectComments_ );
if ( placement == commentAfterOnSameLine )
{
assert( lastValue_ != 0 );
lastValue_->setComment( std::string( begin, end ), placement );
}
else
{
if ( !commentsBefore_.empty() )
commentsBefore_ += "\n";
commentsBefore_ += std::string( begin, end );
}
}
bool
Reader::readCStyleComment()
{
while ( current_ != end_ )
{
Char c = getNextChar();
if ( c == '*' && *current_ == '/' )
break;
}
return getNextChar() == '/';
}
bool
Reader::readCppStyleComment()
{
while ( current_ != end_ )
{
Char c = getNextChar();
if ( c == '\r' || c == '\n' )
break;
}
return true;
}
void
Reader::readNumber()
{
while ( current_ != end_ )
{
if ( !(*current_ >= '0' && *current_ <= '9') &&
!in( *current_, '.', 'e', 'E', '+', '-' ) )
break;
++current_;
}
}
bool
Reader::readString()
{
Char c = 0;
while ( current_ != end_ )
{
c = getNextChar();
if ( c == '\\' )
getNextChar();
else if ( c == '"' )
break;
}
return c == '"';
}
bool
Reader::readObject( Token &tokenStart )
{
Token tokenName;
std::string name;
currentValue() = Value( objectValue );
while ( readToken( tokenName ) )
{
bool initialTokenOk = true;
while ( tokenName.type_ == tokenComment && initialTokenOk )
initialTokenOk = readToken( tokenName );
if ( !initialTokenOk )
break;
if ( tokenName.type_ == tokenObjectEnd && name.empty() ) // empty object
return true;
if ( tokenName.type_ != tokenString )
break;
name = "";
if ( !decodeString( tokenName, name ) )
return recoverFromError( tokenObjectEnd );
Token colon;
if ( !readToken( colon ) || colon.type_ != tokenMemberSeparator )
{
return addErrorAndRecover( "Missing ':' after object member name",
colon,
tokenObjectEnd );
}
Value &value = currentValue()[ name ];
nodes_.push( &value );
bool ok = readValue();
nodes_.pop();
if ( !ok ) // error already set
return recoverFromError( tokenObjectEnd );
Token comma;
if ( !readToken( comma )
|| ( comma.type_ != tokenObjectEnd &&
comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment ) )
{
return addErrorAndRecover( "Missing ',' or '}' in object declaration",
comma,
tokenObjectEnd );
}
bool finalizeTokenOk = true;
while ( comma.type_ == tokenComment &&
finalizeTokenOk )
finalizeTokenOk = readToken( comma );
if ( comma.type_ == tokenObjectEnd )
return true;
}
return addErrorAndRecover( "Missing '}' or object member name",
tokenName,
tokenObjectEnd );
}
bool
Reader::readArray( Token &tokenStart )
{
currentValue() = Value( arrayValue );
skipSpaces();
if ( *current_ == ']' ) // empty array
{
Token endArray;
readToken( endArray );
return true;
}
int index = 0;
while ( true )
{
Value &value = currentValue()[ index++ ];
nodes_.push( &value );
bool ok = readValue();
nodes_.pop();
if ( !ok ) // error already set
return recoverFromError( tokenArrayEnd );
Token token;
// Accept Comment after last item in the array.
ok = readToken( token );
while ( token.type_ == tokenComment && ok )
{
ok = readToken( token );
}
bool badTokenType = ( token.type_ == tokenArraySeparator &&
token.type_ == tokenArrayEnd );
if ( !ok || badTokenType )
{
return addErrorAndRecover( "Missing ',' or ']' in array declaration",
token,
tokenArrayEnd );
}
if ( token.type_ == tokenArrayEnd )
break;
}
return true;
}
bool
Reader::decodeNumber( Token &token )
{
bool isDouble = false;
for ( Location inspect = token.start_; inspect != token.end_; ++inspect )
{
isDouble = isDouble
|| in( *inspect, '.', 'e', 'E', '+' )
|| ( *inspect == '-' && inspect != token.start_ );
}
if ( isDouble )
return decodeDouble( token );
Location current = token.start_;
bool isNegative = *current == '-';
if ( isNegative )
++current;
Value::UInt threshold = (isNegative ? Value::UInt(-Value::minInt)
: Value::maxUInt) / 10;
Value::UInt value = 0;
while ( current < token.end_ )
{
Char c = *current++;
if ( c < '0' || c > '9' )
return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
if ( value >= threshold )
return decodeDouble( token );
value = value * 10 + Value::UInt(c - '0');
}
if ( isNegative )
currentValue() = -Value::Int( value );
else if ( value <= Value::UInt(Value::maxInt) )
currentValue() = Value::Int( value );
else
currentValue() = value;
return true;
}
bool
Reader::decodeDouble( Token &token )
{
double value = 0;
const int bufferSize = 32;
int count;
int length = int(token.end_ - token.start_);
if ( length <= bufferSize )
{
Char buffer[bufferSize];
memcpy( buffer, token.start_, length );
buffer[length] = 0;
count = sscanf( buffer, "%lf", &value );
}
else
{
std::string buffer( token.start_, token.end_ );
count = sscanf( buffer.c_str(), "%lf", &value );
}
if ( count != 1 )
return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
currentValue() = value;
return true;
}
bool
Reader::decodeString( Token &token )
{
std::string decoded;
if ( !decodeString( token, decoded ) )
return false;
currentValue() = decoded;
return true;
}
bool
Reader::decodeString( Token &token, std::string &decoded )
{
decoded.reserve( token.end_ - token.start_ - 2 );
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while ( current != end )
{
Char c = *current++;
if ( c == '"' )
break;
else if ( c == '\\' )
{
if ( current == end )
return addError( "Empty escape sequence in string", token, current );
Char escape = *current++;
switch ( escape )
{
case '"': decoded += '"'; break;
case '/': decoded += '/'; break;
case '\\': decoded += '\\'; break;
case 'b': decoded += '\b'; break;
case 'f': decoded += '\f'; break;
case 'n': decoded += '\n'; break;
case 'r': decoded += '\r'; break;
case 't': decoded += '\t'; break;
case 'u':
{
unsigned int unicode;
if ( !decodeUnicodeCodePoint( token, current, end, unicode ) )
return false;
decoded += codePointToUTF8(unicode);
}
break;
default:
return addError( "Bad escape sequence in string", token, current );
}
}
else
{
decoded += c;
}
}
return true;
}
bool
Reader::decodeUnicodeCodePoint( Token &token,
Location &current,
Location end,
unsigned int &unicode )
{
if ( !decodeUnicodeEscapeSequence( token, current, end, unicode ) )
return false;
if (unicode >= 0xD800 && unicode <= 0xDBFF)
{
// surrogate pairs
if (end - current < 6)
return addError( "additional six characters expected to parse unicode surrogate pair.", token, current );
unsigned int surrogatePair;
if (*(current++) == '\\' && *(current++)== 'u')
{
if (decodeUnicodeEscapeSequence( token, current, end, surrogatePair ))
{
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
}
else
return false;
}
else
return addError( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current );
}
return true;
}
bool
Reader::decodeUnicodeEscapeSequence( Token &token,
Location &current,
Location end,
unsigned int &unicode )
{
if ( end - current < 4 )
return addError( "Bad unicode escape sequence in string: four digits expected.", token, current );
unicode = 0;
for ( int index =0; index < 4; ++index )
{
Char c = *current++;
unicode *= 16;
if ( c >= '0' && c <= '9' )
unicode += c - '0';
else if ( c >= 'a' && c <= 'f' )
unicode += c - 'a' + 10;
else if ( c >= 'A' && c <= 'F' )
unicode += c - 'A' + 10;
else
return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current );
}
return true;
}
bool
Reader::addError( const std::string &message,
Token &token,
Location extra )
{
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = extra;
errors_.push_back( info );
return false;
}
bool
Reader::recoverFromError( TokenType skipUntilToken )
{
int errorCount = int(errors_.size());
Token skip;
while ( true )
{
if ( !readToken(skip) )
errors_.resize( errorCount ); // discard errors caused by recovery
if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream )
break;
}
errors_.resize( errorCount );
return false;
}
bool
Reader::addErrorAndRecover( const std::string &message,
Token &token,
TokenType skipUntilToken )
{
addError( message, token );
return recoverFromError( skipUntilToken );
}
Value &
Reader::currentValue()
{
return *(nodes_.top());
}
Reader::Char
Reader::getNextChar()
{
if ( current_ == end_ )
return 0;
return *current_++;
}
void
Reader::getLocationLineAndColumn( Location location,
int &line,
int &column ) const
{
Location current = begin_;
Location lastLineStart = current;
line = 0;
while ( current < location && current != end_ )
{
Char c = *current++;
if ( c == '\r' )
{
if ( *current == '\n' )
++current;
lastLineStart = current;
++line;
}
else if ( c == '\n' )
{
lastLineStart = current;
++line;
}
}
// column & line start at 1
column = int(location - lastLineStart) + 1;
++line;
}
std::string
Reader::getLocationLineAndColumn( Location location ) const
{
int line, column;
getLocationLineAndColumn( location, line, column );
char buffer[18+16+16+1];
sprintf( buffer, "Line %d, Column %d", line, column );
return buffer;
}
std::string
Reader::getFormatedErrorMessages() const
{
std::string formattedMessage;
for ( Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError )
{
const ErrorInfo &error = *itError;
formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n";
formattedMessage += " " + error.message_ + "\n";
if ( error.extra_ )
formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n";
}
return formattedMessage;
}
std::istream& operator>>( std::istream &sin, Value &root )
{
Json::Reader reader;
bool ok = reader.parse(sin, root, true);
//JSON_ASSERT( ok );
if (!ok) throw std::runtime_error(reader.getFormatedErrorMessages());
return sin;
}
} // namespace Json
}
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
#include <iostream>
#include "../../include/json/value.h"
#include "../../include/json/writer.h"
#include <utility>
#include <stdexcept>
#include <cstring>
#include <cassert>
#ifdef JSON_USE_CPPTL
# include <cpptl/conststring.h>
#endif
#include <cstddef> // size_t
#ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
# include "../../include/json/json_batchallocator.h"
#endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
#include <EH_Exception.h>
#include "../../lib/EH_DEBUG.h"
#define JSON_ASSERT_UNREACHABLE assert( false )
/*change by shijian 13.3.2*/
#if 0
#define JSON_ASSERT( condition ) assert( condition ); // @todo <= change this into an exception throw
#endif
/*add by shijian 13.3.2*/
#define JSON_ASSERT( condition ) \
if (!( condition )) { \
EH_ERROR("ASSERT:"__STRING(condition)"\n"); \
throw EH_EXCEPTION("ASSERT:"__STRING(condition)); \
}
#define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) throw EH_EXCEPTION( message );
namespace EH{
namespace Json {
const Value Value::null;
const Int Value::minInt = Int( ~(UInt(-1)/2) );
const Int Value::maxInt = Int( UInt(-1)/2 );
const UInt Value::maxUInt = UInt(-1);
// A "safe" implementation of strdup. Allow null pointer to be passed.
// Also avoid warning on msvc80.
//
//inline char *safeStringDup( const char *czstring )
//{
// if ( czstring )
// {
// const size_t length = (unsigned int)( strlen(czstring) + 1 );
// char *newString = static_cast<char *>( malloc( length ) );
// memcpy( newString, czstring, length );
// return newString;
// }
// return 0;
//}
//
//inline char *safeStringDup( const std::string &str )
//{
// if ( !str.empty() )
// {
// const size_t length = str.length();
// char *newString = static_cast<char *>( malloc( length + 1 ) );
// memcpy( newString, str.c_str(), length );
// newString[length] = 0;
// return newString;
// }
// return 0;
//}
ValueAllocator::~ValueAllocator()
{
}
class DefaultValueAllocator : public ValueAllocator
{
public:
virtual ~DefaultValueAllocator()
{
}
virtual char *makeMemberName( const char *memberName )
{
return duplicateStringValue( memberName );
}
virtual void releaseMemberName( char *memberName )
{
releaseStringValue( memberName );
}
virtual char *duplicateStringValue( const char *value,
unsigned int length = unknown )
{
//@todo invesgate this old optimization
//if ( !value || value[0] == 0 )
// return 0;
if ( length == unknown )
length = (unsigned int)strlen(value);
char *newString = static_cast<char *>( malloc( length + 1 ) );
memcpy( newString, value, length );
newString[length] = 0;
return newString;
}
virtual void releaseStringValue( char *value )
{
if ( value )
free( value );
}
};
static ValueAllocator *&valueAllocator()
{
static DefaultValueAllocator defaultAllocator;
static ValueAllocator *valueAllocator = &defaultAllocator;
return valueAllocator;
}
static struct DummyValueAllocatorInitializer {
DummyValueAllocatorInitializer()
{
valueAllocator(); // ensure valueAllocator() statics are initialized before main().
}
} dummyValueAllocatorInitializer;
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// ValueInternals...
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
#ifdef JSON_VALUE_USE_INTERNAL_MAP
# include "../../lib/jsonlib/json_internalarray.inl"
# include "../../lib/jsonlib/json_internalmap.inl"
#endif // JSON_VALUE_USE_INTERNAL_MAP
# include "../../lib/jsonlib/json_valueiterator.inl"
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::CommentInfo
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
Value::CommentInfo::CommentInfo()
: comment_( 0 )
{
}
Value::CommentInfo::~CommentInfo()
{
if ( comment_ )
valueAllocator()->releaseStringValue( comment_ );
}
void
Value::CommentInfo::setComment( const char *text )
{
if ( comment_ )
valueAllocator()->releaseStringValue( comment_ );
JSON_ASSERT( text );
JSON_ASSERT_MESSAGE( text[0]=='\0' || text[0]=='/', "Comments must start with /");
// It seems that /**/ style comments are acceptable as well.
comment_ = valueAllocator()->duplicateStringValue( text );
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::CZString
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
# ifndef JSON_VALUE_USE_INTERNAL_MAP
// Notes: index_ indicates if the string was allocated when
// a string is stored.
Value::CZString::CZString( int index )
: cstr_( 0 )
, index_( index )
{
}
Value::CZString::CZString( const char *cstr, DuplicationPolicy allocate )
: cstr_( allocate == duplicate ? valueAllocator()->makeMemberName(cstr)
: cstr )
, index_( allocate )
{
}
Value::CZString::CZString( const CZString &other )
: cstr_( other.index_ != noDuplication && other.cstr_ != 0
? valueAllocator()->makeMemberName( other.cstr_ )
: other.cstr_ )
, index_( other.cstr_ ? (other.index_ == noDuplication ? noDuplication : duplicate)
: other.index_ )
{
}
Value::CZString::~CZString()
{
if ( cstr_ && index_ == duplicate )
valueAllocator()->releaseMemberName( const_cast<char *>( cstr_ ) );
}
void
Value::CZString::swap( CZString &other )
{
std::swap( cstr_, other.cstr_ );
std::swap( index_, other.index_ );
}
Value::CZString &
Value::CZString::operator =( const CZString &other )
{
CZString temp( other );
swap( temp );
return *this;
}
bool
Value::CZString::operator<( const CZString &other ) const
{
if ( cstr_ )
return strcmp( cstr_, other.cstr_ ) < 0;
return index_ < other.index_;
}
bool
Value::CZString::operator==( const CZString &other ) const
{
if ( cstr_ )
return strcmp( cstr_, other.cstr_ ) == 0;
return index_ == other.index_;
}
int
Value::CZString::index() const
{
return index_;
}
const char *
Value::CZString::c_str() const
{
return cstr_;
}
bool
Value::CZString::isStaticString() const
{
return index_ == noDuplication;
}
#endif // ifndef JSON_VALUE_USE_INTERNAL_MAP
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::Value
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
/*! \internal Default constructor initialization must be equivalent to:
* memset( this, 0, sizeof(Value) )
* This optimization is used in ValueInternalMap fast allocator.
*/
Value::Value( ValueType type )
: type_( type )
, allocated_( 0 )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
switch ( type )
{
case nullValue:
break;
case intValue:
case uintValue:
value_.int_ = 0;
break;
case realValue:
value_.real_ = 0.0;
break;
case stringValue:
value_.string_ = 0;
break;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
value_.map_ = new ObjectValues();
break;
#else
case arrayValue:
value_.array_ = arrayAllocator()->newArray();
break;
case objectValue:
value_.map_ = mapAllocator()->newMap();
break;
#endif
case booleanValue:
value_.bool_ = false;
break;
default:
JSON_ASSERT_UNREACHABLE;
}
}
Value::Value( Int value )
: type_( intValue )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.int_ = value;
}
Value::Value( UInt value )
: type_( uintValue )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.uint_ = value;
}
Value::Value( double value )
: type_( realValue )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.real_ = value;
}
Value::Value( const char *value )
: type_( stringValue )
, allocated_( true )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.string_ = valueAllocator()->duplicateStringValue( value );
}
Value::Value( const char *beginValue,
const char *endValue )
: type_( stringValue )
, allocated_( true )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.string_ = valueAllocator()->duplicateStringValue( beginValue,
UInt(endValue - beginValue) );
}
Value::Value( const std::string &value )
: type_( stringValue )
, allocated_( true )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.string_ = valueAllocator()->duplicateStringValue( value.c_str(),
(unsigned int)value.length() );
}
Value::Value( const StaticString &value )
: type_( stringValue )
, allocated_( false )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.string_ = const_cast<char *>( value.c_str() );
}
# ifdef JSON_USE_CPPTL
Value::Value( const CppTL::ConstString &value )
: type_( stringValue )
, allocated_( true )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.string_ = valueAllocator()->duplicateStringValue( value, value.length() );
}
# endif
Value::Value( bool value )
: type_( booleanValue )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.bool_ = value;
}
Value::Value( const Value &other )
: type_( other.type_ )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
switch ( type_ )
{
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
value_ = other.value_;
break;
case stringValue:
if ( other.value_.string_ )
{
value_.string_ = valueAllocator()->duplicateStringValue( other.value_.string_ );
allocated_ = true;
}
else
value_.string_ = 0;
break;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
value_.map_ = new ObjectValues( *other.value_.map_ );
break;
#else
case arrayValue:
value_.array_ = arrayAllocator()->newArrayCopy( *other.value_.array_ );
break;
case objectValue:
value_.map_ = mapAllocator()->newMapCopy( *other.value_.map_ );
break;
#endif
default:
JSON_ASSERT_UNREACHABLE;
}
if ( other.comments_ )
{
comments_ = new CommentInfo[numberOfCommentPlacement];
for ( int comment =0; comment < numberOfCommentPlacement; ++comment )
{
const CommentInfo &otherComment = other.comments_[comment];
if ( otherComment.comment_ )
comments_[comment].setComment( otherComment.comment_ );
}
}
}
Value::~Value()
{
switch ( type_ )
{
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
break;
case stringValue:
if ( allocated_ )
valueAllocator()->releaseStringValue( value_.string_ );
break;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
delete value_.map_;
break;
#else
case arrayValue:
arrayAllocator()->destructArray( value_.array_ );
break;
case objectValue:
mapAllocator()->destructMap( value_.map_ );
break;
#endif
default:
JSON_ASSERT_UNREACHABLE;
}
if ( comments_ )
delete[] comments_;
}
Value &
Value::operator=( const Value &other )
{
Value temp( other );
swap( temp );
return *this;
}
void
Value::swap( Value &other )
{
ValueType temp = type_;
type_ = other.type_;
other.type_ = temp;
std::swap( value_, other.value_ );
int temp2 = allocated_;
allocated_ = other.allocated_;
other.allocated_ = temp2;
}
ValueType
Value::type() const
{
return type_;
}
int
Value::compare( const Value &other )
{
/*
int typeDelta = other.type_ - type_;
switch ( type_ )
{
case nullValue:
return other.type_ == type_;
case intValue:
if ( other.type_.isNumeric()
case uintValue:
case realValue:
case booleanValue:
break;
case stringValue,
break;
case arrayValue:
delete value_.array_;
break;
case objectValue:
delete value_.map_;
default:
JSON_ASSERT_UNREACHABLE;
}
*/
return 0; // unreachable
}
bool
Value::operator <( const Value &other ) const
{
int typeDelta = type_ - other.type_;
if ( typeDelta )
return typeDelta < 0 ? true : false;
switch ( type_ )
{
case nullValue:
return false;
case intValue:
return value_.int_ < other.value_.int_;
case uintValue:
return value_.uint_ < other.value_.uint_;
case realValue:
return value_.real_ < other.value_.real_;
case booleanValue:
return value_.bool_ < other.value_.bool_;
case stringValue:
return ( value_.string_ == 0 && other.value_.string_ )
|| ( other.value_.string_
&& value_.string_
&& strcmp( value_.string_, other.value_.string_ ) < 0 );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
{
int delta = int( value_.map_->size() - other.value_.map_->size() );
if ( delta )
return delta < 0;
return (*value_.map_) < (*other.value_.map_);
}
#else
case arrayValue:
return value_.array_->compare( *(other.value_.array_) ) < 0;
case objectValue:
return value_.map_->compare( *(other.value_.map_) ) < 0;
#endif
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable
}
bool
Value::operator <=( const Value &other ) const
{
return !(other > *this);
}
bool
Value::operator >=( const Value &other ) const
{
return !(*this < other);
}
bool
Value::operator >( const Value &other ) const
{
return other < *this;
}
bool
Value::operator ==( const Value &other ) const
{
//if ( type_ != other.type_ )
// GCC 2.95.3 says:
// attempt to take address of bit-field structure member `Json::Value::type_'
// Beats me, but a temp solves the problem.
int temp = other.type_;
if ( type_ != temp )
return false;
switch ( type_ )
{
case nullValue:
return true;
case intValue:
return value_.int_ == other.value_.int_;
case uintValue:
return value_.uint_ == other.value_.uint_;
case realValue:
return value_.real_ == other.value_.real_;
case booleanValue:
return value_.bool_ == other.value_.bool_;
case stringValue:
return ( value_.string_ == other.value_.string_ )
|| ( other.value_.string_
&& value_.string_
&& strcmp( value_.string_, other.value_.string_ ) == 0 );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
return value_.map_->size() == other.value_.map_->size()
&& (*value_.map_) == (*other.value_.map_);
#else
case arrayValue:
return value_.array_->compare( *(other.value_.array_) ) == 0;
case objectValue:
return value_.map_->compare( *(other.value_.map_) ) == 0;
#endif
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable
}
bool
Value::operator !=( const Value &other ) const
{
return !( *this == other );
}
const char *
Value::asCString() const
{
JSON_ASSERT( type_ == stringValue );
return value_.string_;
}
std::string
Value::asString() const
{
switch ( type_ )
{
case nullValue:
return "";
case stringValue:
return value_.string_ ? value_.string_ : "";
case booleanValue:
return value_.bool_ ? "true" : "false";
case intValue:
case uintValue:
case realValue:
case arrayValue:
case objectValue: {
string errorMsg = this->toStyledString()+"Type is not convertible to string";
JSON_ASSERT_MESSAGE( false, errorMsg.c_str() );
}
default:
JSON_ASSERT_UNREACHABLE;
}
return ""; // unreachable
}
# ifdef JSON_USE_CPPTL
CppTL::ConstString
Value::asConstString() const
{
return CppTL::ConstString( asString().c_str() );
}
# endif
Value::Int
Value::asInt() const
{
switch ( type_ )
{
case nullValue:
return 0;
case intValue:
return value_.int_;
case uintValue:
JSON_ASSERT_MESSAGE( value_.uint_ < (unsigned)maxInt, "integer out of signed integer range" );
return value_.uint_;
case realValue:
JSON_ASSERT_MESSAGE( value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range" );
return Int( value_.real_ );
case booleanValue:
return value_.bool_ ? 1 : 0;
case stringValue:
case arrayValue:
case objectValue:
JSON_ASSERT_MESSAGE( false, "Type is not convertible to int" );
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable;
}
Value::UInt
Value::asUInt() const
{
switch ( type_ )
{
case nullValue:
return 0;
case intValue:
JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to unsigned integer" );
return value_.int_;
case uintValue:
return value_.uint_;
case realValue:
JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range" );
return UInt( value_.real_ );
case booleanValue:
return value_.bool_ ? 1 : 0;
case stringValue:
case arrayValue:
case objectValue:
JSON_ASSERT_MESSAGE( false, "Type is not convertible to uint" );
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable;
}
double
Value::asDouble() const
{
switch ( type_ )
{
case nullValue:
return 0.0;
case intValue:
return value_.int_;
case uintValue:
return value_.uint_;
case realValue:
return value_.real_;
case booleanValue:
return value_.bool_ ? 1.0 : 0.0;
case stringValue:
case arrayValue:
case objectValue:
JSON_ASSERT_MESSAGE( false, "Type is not convertible to double" );
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable;
}
bool
Value::asBool() const
{
switch ( type_ )
{
case nullValue:
return false;
case intValue:
case uintValue:
return value_.int_ != 0;
case realValue:
return value_.real_ != 0.0;
case booleanValue:
return value_.bool_;
case stringValue:
return value_.string_ && value_.string_[0] != 0;
case arrayValue:
case objectValue:
return value_.map_->size() != 0;
default:
JSON_ASSERT_UNREACHABLE;
}
return false; // unreachable;
}
bool
Value::isConvertibleTo( ValueType other ) const
{
switch ( type_ )
{
case nullValue:
return true;
case intValue:
return ( other == nullValue && value_.int_ == 0 )
|| other == intValue
|| ( other == uintValue && value_.int_ >= 0 )
|| other == realValue
|| other == stringValue
|| other == booleanValue;
case uintValue:
return ( other == nullValue && value_.uint_ == 0 )
|| ( other == intValue && value_.uint_ <= (unsigned)maxInt )
|| other == uintValue
|| other == realValue
|| other == stringValue
|| other == booleanValue;
case realValue:
return ( other == nullValue && value_.real_ == 0.0 )
|| ( other == intValue && value_.real_ >= minInt && value_.real_ <= maxInt )
|| ( other == uintValue && value_.real_ >= 0 && value_.real_ <= maxUInt )
|| other == realValue
|| other == stringValue
|| other == booleanValue;
case booleanValue:
return ( other == nullValue && value_.bool_ == false )
|| other == intValue
|| other == uintValue
|| other == realValue
|| other == stringValue
|| other == booleanValue;
case stringValue:
return other == stringValue
|| ( other == nullValue && (!value_.string_ || value_.string_[0] == 0) );
case arrayValue:
return other == arrayValue
|| ( other == nullValue && value_.map_->size() == 0 );
case objectValue:
return other == objectValue
|| ( other == nullValue && value_.map_->size() == 0 );
default:
JSON_ASSERT_UNREACHABLE;
}
return false; // unreachable;
}
/// Number of values in array or object
Value::UInt
Value::size() const
{
switch ( type_ )
{
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
case stringValue:
return 0;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue: // size of the array is highest index + 1
if ( !value_.map_->empty() )
{
ObjectValues::const_iterator itLast = value_.map_->end();
--itLast;
return (*itLast).first.index()+1;
}
return 0;
case objectValue:
return Int( value_.map_->size() );
#else
case arrayValue:
return Int( value_.array_->size() );
case objectValue:
return Int( value_.map_->size() );
#endif
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable;
}
bool
Value::empty() const
{
if ( isNull() || isArray() || isObject() )
return size() == 0u;
else
return false;
}
bool
Value::operator!() const
{
return isNull();
}
void
Value::clear()
{
JSON_ASSERT( type_ == nullValue || type_ == arrayValue || type_ == objectValue );
switch ( type_ )
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
value_.map_->clear();
break;
#else
case arrayValue:
value_.array_->clear();
break;
case objectValue:
value_.map_->clear();
break;
#endif
default:
break;
}
}
void
Value::resize( UInt newSize )
{
JSON_ASSERT( type_ == nullValue || type_ == arrayValue );
if ( type_ == nullValue )
*this = Value( arrayValue );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
UInt oldSize = size();
if ( newSize == 0 )
clear();
else if ( newSize > oldSize )
(*this)[ newSize - 1 ];
else
{
for ( UInt index = newSize; index < oldSize; ++index )
value_.map_->erase( index );
assert( size() == newSize );
}
#else
value_.array_->resize( newSize );
#endif
}
Value &
Value::operator[]( UInt index )
{
JSON_ASSERT( type_ == nullValue || type_ == arrayValue );
if ( type_ == nullValue )
*this = Value( arrayValue );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString key( index );
ObjectValues::iterator it = value_.map_->lower_bound( key );
if ( it != value_.map_->end() && (*it).first == key )
return (*it).second;
ObjectValues::value_type defaultValue( key, null );
it = value_.map_->insert( it, defaultValue );
return (*it).second;
#else
return value_.array_->resolveReference( index );
#endif
}
const Value &
Value::operator[]( UInt index ) const
{
JSON_ASSERT( type_ == nullValue || type_ == arrayValue );
if ( type_ == nullValue )
return null;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString key( index );
ObjectValues::const_iterator it = value_.map_->find( key );
if ( it == value_.map_->end() )
return null;
return (*it).second;
#else
Value *value = value_.array_->find( index );
return value ? *value : null;
#endif
}
Value &
Value::operator[]( const char *key )
{
return resolveReference( key, false );
}
Value &
Value::resolveReference( const char *key,
bool isStatic )
{
JSON_ASSERT( type_ == nullValue || type_ == objectValue );
if ( type_ == nullValue )
*this = Value( objectValue );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString actualKey( key, isStatic ? CZString::noDuplication
: CZString::duplicateOnCopy );
ObjectValues::iterator it = value_.map_->lower_bound( actualKey );
if ( it != value_.map_->end() && (*it).first == actualKey )
return (*it).second;
ObjectValues::value_type defaultValue( actualKey, null );
it = value_.map_->insert( it, defaultValue );
Value &value = (*it).second;
return value;
#else
return value_.map_->resolveReference( key, isStatic );
#endif
}
Value
Value::get( UInt index,
const Value &defaultValue ) const
{
const Value *value = &((*this)[index]);
return value == &null ? defaultValue : *value;
}
bool
Value::isValidIndex( UInt index ) const
{
return index < size();
}
const Value &
Value::operator[]( const char *key ) const
{
JSON_ASSERT( type_ == nullValue || type_ == objectValue );
if ( type_ == nullValue )
return null;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString actualKey( key, CZString::noDuplication );
ObjectValues::const_iterator it = value_.map_->find( actualKey );
if ( it == value_.map_->end() )
return null;
return (*it).second;
#else
const Value *value = value_.map_->find( key );
return value ? *value : null;
#endif
}
Value &
Value::operator[]( const std::string &key )
{
return (*this)[ key.c_str() ];
}
const Value &
Value::operator[]( const std::string &key ) const
{
return (*this)[ key.c_str() ];
}
Value &
Value::operator[]( const StaticString &key )
{
return resolveReference( key, true );
}
# ifdef JSON_USE_CPPTL
Value &
Value::operator[]( const CppTL::ConstString &key )
{
return (*this)[ key.c_str() ];
}
const Value &
Value::operator[]( const CppTL::ConstString &key ) const
{
return (*this)[ key.c_str() ];
}
# endif
Value &
Value::append( const Value &value )
{
return (*this)[size()] = value;
}
void Value::remove(ArrayIndex index)
{
if (type_ == arrayValue){
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString key(index);
ObjectValues::iterator it = value_.map_->find(key);
if (it != value_.map_->end()){
ArrayIndex oldSize = size();
// shift left all items left, into the place of the "removed"
for (ArrayIndex i=index; i<oldSize-1; i++){
CZString key(i);
(*value_.map_)[key] = (*this)[i+1];
}
// erase the last one ("leftover")
CZString keyLast(oldSize-1);
ObjectValues::iterator itLast = value_.map_->find(keyLast);
value_.map_->erase(itLast);
}
#else
NOT SUPPORTED
#endif
}
}
Value
Value::get( const char *key,
const Value &defaultValue ) const
{
const Value *value = &((*this)[key]);
return value == &null ? defaultValue : *value;
}
Value
Value::get( const std::string &key,
const Value &defaultValue ) const
{
return get( key.c_str(), defaultValue );
}
Value
Value::removeMember( const char* key )
{
JSON_ASSERT( type_ == nullValue || type_ == objectValue );
if ( type_ == nullValue )
return null;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString actualKey( key, CZString::noDuplication );
ObjectValues::iterator it = value_.map_->find( actualKey );
if ( it == value_.map_->end() )
return null;
Value old(it->second);
value_.map_->erase(it);
return old;
#else
Value *value = value_.map_->find( key );
if (value){
Value old(*value);
value_.map_.remove( key );
return old;
} else {
return null;
}
#endif
}
Value
Value::removeMember( const std::string &key )
{
return removeMember( key.c_str() );
}
# ifdef JSON_USE_CPPTL
Value
Value::get( const CppTL::ConstString &key,
const Value &defaultValue ) const
{
return get( key.c_str(), defaultValue );
}
# endif
bool
Value::isMember( const char *key ) const
{
const Value *value = &((*this)[key]);
return value != &null;
}
bool
Value::isMember( const std::string &key ) const
{
return isMember( key.c_str() );
}
# ifdef JSON_USE_CPPTL
bool
Value::isMember( const CppTL::ConstString &key ) const
{
return isMember( key.c_str() );
}
#endif
Value::Members
Value::getMemberNames() const
{
JSON_ASSERT( type_ == nullValue || type_ == objectValue );
if ( type_ == nullValue )
return Value::Members();
Members members;
members.reserve( value_.map_->size() );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
ObjectValues::const_iterator it = value_.map_->begin();
ObjectValues::const_iterator itEnd = value_.map_->end();
for ( ; it != itEnd; ++it )
members.push_back( std::string( (*it).first.c_str() ) );
#else
ValueInternalMap::IteratorState it;
ValueInternalMap::IteratorState itEnd;
value_.map_->makeBeginIterator( it );
value_.map_->makeEndIterator( itEnd );
for ( ; !ValueInternalMap::equals( it, itEnd ); ValueInternalMap::increment(it) )
members.push_back( std::string( ValueInternalMap::key( it ) ) );
#endif
return members;
}
//
//# ifdef JSON_USE_CPPTL
//EnumMemberNames
//Value::enumMemberNames() const
//{
// if ( type_ == objectValue )
// {
// return CppTL::Enum::any( CppTL::Enum::transform(
// CppTL::Enum::keys( *(value_.map_), CppTL::Type<const CZString &>() ),
// MemberNamesTransform() ) );
// }
// return EnumMemberNames();
//}
//
//
//EnumValues
//Value::enumValues() const
//{
// if ( type_ == objectValue || type_ == arrayValue )
// return CppTL::Enum::anyValues( *(value_.map_),
// CppTL::Type<const Value &>() );
// return EnumValues();
//}
//
//# endif
bool
Value::isNull() const
{
return type_ == nullValue;
}
bool
Value::isBool() const
{
return type_ == booleanValue;
}
bool
Value::isInt() const
{
return type_ == intValue;
}
bool
Value::isUInt() const
{
return type_ == uintValue;
}
bool
Value::isIntegral() const
{
return type_ == intValue
|| type_ == uintValue
|| type_ == booleanValue;
}
bool
Value::isDouble() const
{
return type_ == realValue;
}
bool
Value::isNumeric() const
{
return isIntegral() || isDouble();
}
bool
Value::isString() const
{
return type_ == stringValue;
}
bool
Value::isArray() const
{
return type_ == nullValue || type_ == arrayValue;
}
bool
Value::isObject() const
{
return type_ == nullValue || type_ == objectValue;
}
void
Value::setComment( const char *comment,
CommentPlacement placement )
{
if ( !comments_ )
comments_ = new CommentInfo[numberOfCommentPlacement];
comments_[placement].setComment( comment );
}
void
Value::setComment( const std::string &comment,
CommentPlacement placement )
{
setComment( comment.c_str(), placement );
}
bool
Value::hasComment( CommentPlacement placement ) const
{
return comments_ != 0 && comments_[placement].comment_ != 0;
}
std::string
Value::getComment( CommentPlacement placement ) const
{
if ( hasComment(placement) )
return comments_[placement].comment_;
return "";
}
std::string
Value::toStyledString() const
{
StyledWriter writer;
return writer.write( *this );
}
Value::const_iterator
Value::begin() const
{
switch ( type_ )
{
#ifdef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
if ( value_.array_ )
{
ValueInternalArray::IteratorState it;
value_.array_->makeBeginIterator( it );
return const_iterator( it );
}
break;
case objectValue:
if ( value_.map_ )
{
ValueInternalMap::IteratorState it;
value_.map_->makeBeginIterator( it );
return const_iterator( it );
}
break;
#else
case arrayValue:
case objectValue:
if ( value_.map_ )
return const_iterator( value_.map_->begin() );
break;
#endif
default:
break;
}
return const_iterator();
}
Value::const_iterator
Value::end() const
{
switch ( type_ )
{
#ifdef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
if ( value_.array_ )
{
ValueInternalArray::IteratorState it;
value_.array_->makeEndIterator( it );
return const_iterator( it );
}
break;
case objectValue:
if ( value_.map_ )
{
ValueInternalMap::IteratorState it;
value_.map_->makeEndIterator( it );
return const_iterator( it );
}
break;
#else
case arrayValue:
case objectValue:
if ( value_.map_ )
return const_iterator( value_.map_->end() );
break;
#endif
default:
break;
}
return const_iterator();
}
Value::iterator
Value::begin()
{
switch ( type_ )
{
#ifdef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
if ( value_.array_ )
{
ValueInternalArray::IteratorState it;
value_.array_->makeBeginIterator( it );
return iterator( it );
}
break;
case objectValue:
if ( value_.map_ )
{
ValueInternalMap::IteratorState it;
value_.map_->makeBeginIterator( it );
return iterator( it );
}
break;
#else
case arrayValue:
case objectValue:
if ( value_.map_ )
return iterator( value_.map_->begin() );
break;
#endif
default:
break;
}
return iterator();
}
Value::iterator
Value::end()
{
switch ( type_ )
{
#ifdef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
if ( value_.array_ )
{
ValueInternalArray::IteratorState it;
value_.array_->makeEndIterator( it );
return iterator( it );
}
break;
case objectValue:
if ( value_.map_ )
{
ValueInternalMap::IteratorState it;
value_.map_->makeEndIterator( it );
return iterator( it );
}
break;
#else
case arrayValue:
case objectValue:
if ( value_.map_ )
return iterator( value_.map_->end() );
break;
#endif
default:
break;
}
return iterator();
}
// class PathArgument
// //////////////////////////////////////////////////////////////////
PathArgument::PathArgument()
: kind_( kindNone )
{
}
PathArgument::PathArgument( Value::UInt index )
: index_( index )
, kind_( kindIndex )
{
}
PathArgument::PathArgument( const char *key )
: key_( key )
, kind_( kindKey )
{
}
PathArgument::PathArgument( const std::string &key )
: key_( key.c_str() )
, kind_( kindKey )
{
}
// class Path
// //////////////////////////////////////////////////////////////////
Path::Path( const std::string &path,
const PathArgument &a1,
const PathArgument &a2,
const PathArgument &a3,
const PathArgument &a4,
const PathArgument &a5 )
{
InArgs in;
in.push_back( &a1 );
in.push_back( &a2 );
in.push_back( &a3 );
in.push_back( &a4 );
in.push_back( &a5 );
makePath( path, in );
}
void
Path::makePath( const std::string &path,
const InArgs &in )
{
const char *current = path.c_str();
const char *end = current + path.length();
InArgs::const_iterator itInArg = in.begin();
while ( current != end )
{
if ( *current == '[' )
{
++current;
if ( *current == '%' )
addPathInArg( path, in, itInArg, PathArgument::kindIndex );
else
{
Value::UInt index = 0;
for ( ; current != end && *current >= '0' && *current <= '9'; ++current )
index = index * 10 + Value::UInt(*current - '0');
args_.push_back( index );
}
if ( current == end || *current++ != ']' )
invalidPath( path, int(current - path.c_str()) );
}
else if ( *current == '%' )
{
addPathInArg( path, in, itInArg, PathArgument::kindKey );
++current;
}
else if ( *current == '.' )
{
++current;
}
else
{
const char *beginName = current;
while ( current != end && !strchr( "[.", *current ) )
++current;
args_.push_back( std::string( beginName, current ) );
}
}
}
void
Path::addPathInArg( const std::string &path,
const InArgs &in,
InArgs::const_iterator &itInArg,
PathArgument::Kind kind )
{
if ( itInArg == in.end() )
{
// Error: missing argument %d
}
else if ( (*itInArg)->kind_ != kind )
{
// Error: bad argument type
}
else
{
args_.push_back( **itInArg );
}
}
void
Path::invalidPath( const std::string &path,
int location )
{
// Error: invalid path.
}
const Value &
Path::resolve( const Value &root ) const
{
const Value *node = &root;
for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it )
{
const PathArgument &arg = *it;
if ( arg.kind_ == PathArgument::kindIndex )
{
if ( !node->isArray() || node->isValidIndex( arg.index_ ) )
{
// Error: unable to resolve path (array value expected at position...
}
node = &((*node)[arg.index_]);
}
else if ( arg.kind_ == PathArgument::kindKey )
{
if ( !node->isObject() )
{
// Error: unable to resolve path (object value expected at position...)
}
node = &((*node)[arg.key_]);
if ( node == &Value::null )
{
// Error: unable to resolve path (object has no member named '' at position...)
}
}
}
return *node;
}
Value
Path::resolve( const Value &root,
const Value &defaultValue ) const
{
const Value *node = &root;
for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it )
{
const PathArgument &arg = *it;
if ( arg.kind_ == PathArgument::kindIndex )
{
if ( !node->isArray() || node->isValidIndex( arg.index_ ) )
return defaultValue;
node = &((*node)[arg.index_]);
}
else if ( arg.kind_ == PathArgument::kindKey )
{
if ( !node->isObject() )
return defaultValue;
node = &((*node)[arg.key_]);
if ( node == &Value::null )
return defaultValue;
}
}
return *node;
}
Value &
Path::make( Value &root ) const
{
Value *node = &root;
for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it )
{
const PathArgument &arg = *it;
if ( arg.kind_ == PathArgument::kindIndex )
{
if ( !node->isArray() )
{
// Error: node is not an array at position ...
}
node = &((*node)[arg.index_]);
}
else if ( arg.kind_ == PathArgument::kindKey )
{
if ( !node->isObject() )
{
// Error: node is not an object at position...
}
node = &((*node)[arg.key_]);
}
}
return *node;
}
} // namespace Json
}
json_value.o: ../src/lib/jsonlib/json_value.cpp \
../src/lib/jsonlib/../../include/json/value.h \
../src/include/../include/json/forwards.h \
../src/include/../include/json/config.h \
../src/lib/jsonlib/../../include/json/writer.h \
../src/include/../include/json/value.h \
../src/lib/jsonlib/../../include/json/json_batchallocator.h \
../src/include/EH_Exception.h ../src/lib/jsonlib/../../lib/EH_DEBUG.h \
../src/lib/jsonlib/../../lib/jsonlib/json_valueiterator.inl
// included by json_value.cpp
// everything is within Json namespace
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueIteratorBase
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueIteratorBase::ValueIteratorBase()
#ifndef JSON_VALUE_USE_INTERNAL_MAP
: current_()
, isNull_( true )
{
}
#else
: isArray_( true )
, isNull_( true )
{
iterator_.array_ = ValueInternalArray::IteratorState();
}
#endif
#ifndef JSON_VALUE_USE_INTERNAL_MAP
ValueIteratorBase::ValueIteratorBase( const Value::ObjectValues::iterator &current )
: current_( current )
, isNull_( false )
{
}
#else
ValueIteratorBase::ValueIteratorBase( const ValueInternalArray::IteratorState &state )
: isArray_( true )
{
iterator_.array_ = state;
}
ValueIteratorBase::ValueIteratorBase( const ValueInternalMap::IteratorState &state )
: isArray_( false )
{
iterator_.map_ = state;
}
#endif
Value &
ValueIteratorBase::deref() const
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
return current_->second;
#else
if ( isArray_ )
return ValueInternalArray::dereference( iterator_.array_ );
return ValueInternalMap::value( iterator_.map_ );
#endif
}
void
ValueIteratorBase::increment()
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
++current_;
#else
if ( isArray_ )
ValueInternalArray::increment( iterator_.array_ );
ValueInternalMap::increment( iterator_.map_ );
#endif
}
void
ValueIteratorBase::decrement()
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
--current_;
#else
if ( isArray_ )
ValueInternalArray::decrement( iterator_.array_ );
ValueInternalMap::decrement( iterator_.map_ );
#endif
}
ValueIteratorBase::difference_type
ValueIteratorBase::computeDistance( const SelfType &other ) const
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
# ifdef JSON_USE_CPPTL_SMALLMAP
return current_ - other.current_;
# else
// Iterator for null value are initialized using the default
// constructor, which initialize current_ to the default
// std::map::iterator. As begin() and end() are two instance
// of the default std::map::iterator, they can not be compared.
// To allow this, we handle this comparison specifically.
if ( isNull_ && other.isNull_ )
{
return 0;
}
// Usage of std::distance is not portable (does not compile with Sun Studio 12 RogueWave STL,
// which is the one used by default).
// Using a portable hand-made version for non random iterator instead:
// return difference_type( std::distance( current_, other.current_ ) );
difference_type myDistance = 0;
for ( Value::ObjectValues::iterator it = current_; it != other.current_; ++it )
{
++myDistance;
}
return myDistance;
# endif
#else
if ( isArray_ )
return ValueInternalArray::distance( iterator_.array_, other.iterator_.array_ );
return ValueInternalMap::distance( iterator_.map_, other.iterator_.map_ );
#endif
}
bool
ValueIteratorBase::isEqual( const SelfType &other ) const
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
if ( isNull_ )
{
return other.isNull_;
}
return current_ == other.current_;
#else
if ( isArray_ )
return ValueInternalArray::equals( iterator_.array_, other.iterator_.array_ );
return ValueInternalMap::equals( iterator_.map_, other.iterator_.map_ );
#endif
}
void
ValueIteratorBase::copy( const SelfType &other )
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
current_ = other.current_;
#else
if ( isArray_ )
iterator_.array_ = other.iterator_.array_;
iterator_.map_ = other.iterator_.map_;
#endif
}
Value
ValueIteratorBase::key() const
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
const Value::CZString czstring = (*current_).first;
if ( czstring.c_str() )
{
if ( czstring.isStaticString() )
return Value( StaticString( czstring.c_str() ) );
return Value( czstring.c_str() );
}
return Value( czstring.index() );
#else
if ( isArray_ )
return Value( ValueInternalArray::indexOf( iterator_.array_ ) );
bool isStatic;
const char *memberName = ValueInternalMap::key( iterator_.map_, isStatic );
if ( isStatic )
return Value( StaticString( memberName ) );
return Value( memberName );
#endif
}
UInt
ValueIteratorBase::index() const
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
const Value::CZString czstring = (*current_).first;
if ( !czstring.c_str() )
return czstring.index();
return Value::UInt( -1 );
#else
if ( isArray_ )
return Value::UInt( ValueInternalArray::indexOf( iterator_.array_ ) );
return Value::UInt( -1 );
#endif
}
const char *
ValueIteratorBase::memberName() const
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
const char *name = (*current_).first.c_str();
return name ? name : "";
#else
if ( !isArray_ )
return ValueInternalMap::key( iterator_.map_ );
return "";
#endif
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueConstIterator
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueConstIterator::ValueConstIterator()
{
}
#ifndef JSON_VALUE_USE_INTERNAL_MAP
ValueConstIterator::ValueConstIterator( const Value::ObjectValues::iterator &current )
: ValueIteratorBase( current )
{
}
#else
ValueConstIterator::ValueConstIterator( const ValueInternalArray::IteratorState &state )
: ValueIteratorBase( state )
{
}
ValueConstIterator::ValueConstIterator( const ValueInternalMap::IteratorState &state )
: ValueIteratorBase( state )
{
}
#endif
ValueConstIterator &
ValueConstIterator::operator =( const ValueIteratorBase &other )
{
copy( other );
return *this;
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueIterator
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueIterator::ValueIterator()
{
}
#ifndef JSON_VALUE_USE_INTERNAL_MAP
ValueIterator::ValueIterator( const Value::ObjectValues::iterator &current )
: ValueIteratorBase( current )
{
}
#else
ValueIterator::ValueIterator( const ValueInternalArray::IteratorState &state )
: ValueIteratorBase( state )
{
}
ValueIterator::ValueIterator( const ValueInternalMap::IteratorState &state )
: ValueIteratorBase( state )
{
}
#endif
ValueIterator::ValueIterator( const ValueConstIterator &other )
: ValueIteratorBase( other )
{
}
ValueIterator::ValueIterator( const ValueIterator &other )
: ValueIteratorBase( other )
{
}
ValueIterator &
ValueIterator::operator =( const SelfType &other )
{
copy( other );
return *this;
}
#include "../../include/json/writer.h"
#include <utility>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <iomanip>
#if _MSC_VER >= 1400 // VC++ 8.0
#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated.
#endif
namespace EH {
namespace Json {
static bool isControlCharacter(char ch)
{
return ch > 0 && ch <= 0x1F;
}
static bool containsControlCharacter( const char* str )
{
while ( *str )
{
if ( isControlCharacter( *(str++) ) )
return true;
}
return false;
}
static void uintToString( unsigned int value,
char *&current )
{
*--current = 0;
do
{
*--current = (value % 10) + '0';
value /= 10;
}
while ( value != 0 );
}
std::string valueToString( Int value )
{
char buffer[32];
char *current = buffer + sizeof(buffer);
bool isNegative = value < 0;
if ( isNegative )
value = -value;
uintToString( UInt(value), current );
if ( isNegative )
*--current = '-';
assert( current >= buffer );
return current;
}
std::string valueToString( UInt value )
{
char buffer[32];
char *current = buffer + sizeof(buffer);
uintToString( value, current );
assert( current >= buffer );
return current;
}
std::string valueToString( double value )
{
char buffer[32];
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with visual studio 2005 to avoid warning.
sprintf_s(buffer, sizeof(buffer), "%#.16g", value);
#else
sprintf(buffer, "%#.16g", value);
#endif
char* ch = buffer + strlen(buffer) - 1;
if (*ch != '0') return buffer; // nothing to truncate, so save time
while(ch > buffer && *ch == '0'){
--ch;
}
char* last_nonzero = ch;
while(ch >= buffer){
switch(*ch){
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
--ch;
continue;
case '.':
// Truncate zeroes to save bytes in output, but keep one.
*(last_nonzero+2) = '\0';
return buffer;
default:
return buffer;
}
}
return buffer;
}
std::string valueToString( bool value )
{
return value ? "true" : "false";
}
std::string valueToQuotedString( const char *value )
{
// Not sure how to handle unicode...
if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL && !containsControlCharacter( value ))
return std::string("\"") + value + "\"";
// We have to walk value and escape any special characters.
// Appending to std::string is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
unsigned maxsize = strlen(value)*2 + 3; // allescaped+quotes+NULL
std::string result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
for (const char* c=value; *c != 0; ++c)
{
switch(*c)
{
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
//case '/':
// Even though \/ is considered a legal escape in JSON, a bare
// slash is also legal, so I see no reason to escape it.
// (I hope I am not misunderstanding something.
// blep notes: actually escaping \/ may be useful in javascript to avoid </
// sequence.
// Should add a flag to allow this compatibility mode and prevent this
// sequence from occurring.
default:
if ( isControlCharacter( *c ) )
{
std::ostringstream oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << static_cast<int>(*c);
result += oss.str();
}
else
{
result += *c;
}
break;
}
}
result += "\"";
return result;
}
// Class Writer
// //////////////////////////////////////////////////////////////////
Writer::~Writer()
{
}
// Class FastWriter
// //////////////////////////////////////////////////////////////////
FastWriter::FastWriter()
: yamlCompatiblityEnabled_( false )
{
}
void
FastWriter::enableYAMLCompatibility()
{
yamlCompatiblityEnabled_ = true;
}
std::string
FastWriter::write( const Value &root )
{
document_ = "";
writeValue( root );
document_ += "\n";
return document_;
}
void
FastWriter::writeValue( const Value &value )
{
switch ( value.type() )
{
case nullValue:
document_ += "null";
break;
case intValue:
document_ += valueToString( value.asInt() );
break;
case uintValue:
document_ += valueToString( value.asUInt() );
break;
case realValue:
document_ += valueToString( value.asDouble() );
break;
case stringValue:
document_ += valueToQuotedString( value.asCString() );
break;
case booleanValue:
document_ += valueToString( value.asBool() );
break;
case arrayValue:
{
document_ += "[";
int size = value.size();
for ( int index =0; index < size; ++index )
{
if ( index > 0 )
document_ += ",";
writeValue( value[index] );
}
document_ += "]";
}
break;
case objectValue:
{
Value::Members members( value.getMemberNames() );
document_ += "{";
for ( Value::Members::iterator it = members.begin();
it != members.end();
++it )
{
const std::string &name = *it;
if ( it != members.begin() )
document_ += ",";
document_ += valueToQuotedString( name.c_str() );
document_ += yamlCompatiblityEnabled_ ? ": "
: ":";
writeValue( value[name] );
}
document_ += "}";
}
break;
}
}
// Class StyledWriter
// //////////////////////////////////////////////////////////////////
StyledWriter::StyledWriter()
: rightMargin_( 74 )
, indentSize_( 3 )
{
}
std::string
StyledWriter::write( const Value &root )
{
document_ = "";
addChildValues_ = false;
indentString_ = "";
writeCommentBeforeValue( root );
writeValue( root );
writeCommentAfterValueOnSameLine( root );
document_ += "\n";
return document_;
}
void
StyledWriter::writeValue( const Value &value )
{
switch ( value.type() )
{
case nullValue:
pushValue( "null" );
break;
case intValue:
pushValue( valueToString( value.asInt() ) );
break;
case uintValue:
pushValue( valueToString( value.asUInt() ) );
break;
case realValue:
pushValue( valueToString( value.asDouble() ) );
break;
case stringValue:
pushValue( valueToQuotedString( value.asCString() ) );
break;
case booleanValue:
pushValue( valueToString( value.asBool() ) );
break;
case arrayValue:
writeArrayValue( value);
break;
case objectValue:
{
Value::Members members( value.getMemberNames() );
if ( members.empty() )
pushValue( "{}" );
else
{
writeWithIndent( "{" );
indent();
Value::Members::iterator it = members.begin();
while ( true )
{
const std::string &name = *it;
const Value &childValue = value[name];
writeCommentBeforeValue( childValue );
writeWithIndent( valueToQuotedString( name.c_str() ) );
document_ += " : ";
writeValue( childValue );
if ( ++it == members.end() )
{
writeCommentAfterValueOnSameLine( childValue );
break;
}
document_ += ",";
writeCommentAfterValueOnSameLine( childValue );
}
unindent();
writeWithIndent( "}" );
}
}
break;
}
}
void
StyledWriter::writeArrayValue( const Value &value )
{
unsigned size = value.size();
if ( size == 0 )
pushValue( "[]" );
else
{
bool isArrayMultiLine = isMultineArray( value );
if ( isArrayMultiLine )
{
writeWithIndent( "[" );
indent();
bool hasChildValue = !childValues_.empty();
unsigned index =0;
while ( true )
{
const Value &childValue = value[index];
writeCommentBeforeValue( childValue );
if ( hasChildValue )
writeWithIndent( childValues_[index] );
else
{
writeIndent();
writeValue( childValue );
}
if ( ++index == size )
{
writeCommentAfterValueOnSameLine( childValue );
break;
}
document_ += ",";
writeCommentAfterValueOnSameLine( childValue );
}
unindent();
writeWithIndent( "]" );
}
else // output on a single line
{
assert( childValues_.size() == size );
document_ += "[ ";
for ( unsigned index =0; index < size; ++index )
{
if ( index > 0 )
document_ += ", ";
document_ += childValues_[index];
}
document_ += " ]";
}
}
}
bool
StyledWriter::isMultineArray( const Value &value )
{
int size = value.size();
bool isMultiLine = size*3 >= rightMargin_ ;
childValues_.clear();
for ( int index =0; index < size && !isMultiLine; ++index )
{
const Value &childValue = value[index];
isMultiLine = isMultiLine ||
( (childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0 );
}
if ( !isMultiLine ) // check if line length > max line length
{
childValues_.reserve( size );
addChildValues_ = true;
int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]'
for ( int index =0; index < size && !isMultiLine; ++index )
{
writeValue( value[index] );
lineLength += int( childValues_[index].length() );
isMultiLine = isMultiLine && hasCommentForValue( value[index] );
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void
StyledWriter::pushValue( const std::string &value )
{
if ( addChildValues_ )
childValues_.push_back( value );
else
document_ += value;
}
void
StyledWriter::writeIndent()
{
if ( !document_.empty() )
{
char last = document_[document_.length()-1];
if ( last == ' ' ) // already indented
return;
if ( last != '\n' ) // Comments may add new-line
document_ += '\n';
}
document_ += indentString_;
}
void
StyledWriter::writeWithIndent( const std::string &value )
{
writeIndent();
document_ += value;
}
void
StyledWriter::indent()
{
indentString_ += std::string( indentSize_, ' ' );
}
void
StyledWriter::unindent()
{
assert( int(indentString_.size()) >= indentSize_ );
indentString_.resize( indentString_.size() - indentSize_ );
}
void
StyledWriter::writeCommentBeforeValue( const Value &root )
{
if ( !root.hasComment( commentBefore ) )
return;
document_ += normalizeEOL( root.getComment( commentBefore ) );
document_ += "\n";
}
void
StyledWriter::writeCommentAfterValueOnSameLine( const Value &root )
{
if ( root.hasComment( commentAfterOnSameLine ) )
document_ += " " + normalizeEOL( root.getComment( commentAfterOnSameLine ) );
if ( root.hasComment( commentAfter ) )
{
document_ += "\n";
document_ += normalizeEOL( root.getComment( commentAfter ) );
document_ += "\n";
}
}
bool
StyledWriter::hasCommentForValue( const Value &value )
{
return value.hasComment( commentBefore )
|| value.hasComment( commentAfterOnSameLine )
|| value.hasComment( commentAfter );
}
std::string
StyledWriter::normalizeEOL( const std::string &text )
{
std::string normalized;
normalized.reserve( text.length() );
const char *begin = text.c_str();
const char *end = begin + text.length();
const char *current = begin;
while ( current != end )
{
char c = *current++;
if ( c == '\r' ) // mac or dos EOL
{
if ( *current == '\n' ) // convert dos EOL
++current;
normalized += '\n';
}
else // handle unix EOL & other char
normalized += c;
}
return normalized;
}
// Class StyledStreamWriter
// //////////////////////////////////////////////////////////////////
StyledStreamWriter::StyledStreamWriter( std::string indentation )
: document_(NULL)
, rightMargin_( 74 )
, indentation_( indentation )
{
}
void
StyledStreamWriter::write( std::ostream &out, const Value &root )
{
document_ = &out;
addChildValues_ = false;
indentString_ = "";
writeCommentBeforeValue( root );
writeValue( root );
writeCommentAfterValueOnSameLine( root );
*document_ << "\n";
document_ = NULL; // Forget the stream, for safety.
}
void
StyledStreamWriter::writeValue( const Value &value )
{
switch ( value.type() )
{
case nullValue:
pushValue( "null" );
break;
case intValue:
pushValue( valueToString( value.asInt() ) );
break;
case uintValue:
pushValue( valueToString( value.asUInt() ) );
break;
case realValue:
pushValue( valueToString( value.asDouble() ) );
break;
case stringValue:
pushValue( valueToQuotedString( value.asCString() ) );
break;
case booleanValue:
pushValue( valueToString( value.asBool() ) );
break;
case arrayValue:
writeArrayValue( value);
break;
case objectValue:
{
Value::Members members( value.getMemberNames() );
if ( members.empty() )
pushValue( "{}" );
else
{
writeWithIndent( "{" );
indent();
Value::Members::iterator it = members.begin();
while ( true )
{
const std::string &name = *it;
const Value &childValue = value[name];
writeCommentBeforeValue( childValue );
writeWithIndent( valueToQuotedString( name.c_str() ) );
*document_ << " : ";
writeValue( childValue );
if ( ++it == members.end() )
{
writeCommentAfterValueOnSameLine( childValue );
break;
}
*document_ << ",";
writeCommentAfterValueOnSameLine( childValue );
}
unindent();
writeWithIndent( "}" );
}
}
break;
}
}
void
StyledStreamWriter::writeArrayValue( const Value &value )
{
unsigned size = value.size();
if ( size == 0 )
pushValue( "[]" );
else
{
bool isArrayMultiLine = isMultineArray( value );
if ( isArrayMultiLine )
{
writeWithIndent( "[" );
indent();
bool hasChildValue = !childValues_.empty();
unsigned index =0;
while ( true )
{
const Value &childValue = value[index];
writeCommentBeforeValue( childValue );
if ( hasChildValue )
writeWithIndent( childValues_[index] );
else
{
writeIndent();
writeValue( childValue );
}
if ( ++index == size )
{
writeCommentAfterValueOnSameLine( childValue );
break;
}
*document_ << ",";
writeCommentAfterValueOnSameLine( childValue );
}
unindent();
writeWithIndent( "]" );
}
else // output on a single line
{
assert( childValues_.size() == size );
*document_ << "[ ";
for ( unsigned index =0; index < size; ++index )
{
if ( index > 0 )
*document_ << ", ";
*document_ << childValues_[index];
}
*document_ << " ]";
}
}
}
bool
StyledStreamWriter::isMultineArray( const Value &value )
{
int size = value.size();
bool isMultiLine = size*3 >= rightMargin_ ;
childValues_.clear();
for ( int index =0; index < size && !isMultiLine; ++index )
{
const Value &childValue = value[index];
isMultiLine = isMultiLine ||
( (childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0 );
}
if ( !isMultiLine ) // check if line length > max line length
{
childValues_.reserve( size );
addChildValues_ = true;
int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]'
for ( int index =0; index < size && !isMultiLine; ++index )
{
writeValue( value[index] );
lineLength += int( childValues_[index].length() );
isMultiLine = isMultiLine && hasCommentForValue( value[index] );
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void
StyledStreamWriter::pushValue( const std::string &value )
{
if ( addChildValues_ )
childValues_.push_back( value );
else
*document_ << value;
}
void
StyledStreamWriter::writeIndent()
{
/*
Some comments in this method would have been nice. ;-)
if ( !document_.empty() )
{
char last = document_[document_.length()-1];
if ( last == ' ' ) // already indented
return;
if ( last != '\n' ) // Comments may add new-line
*document_ << '\n';
}
*/
*document_ << '\n' << indentString_;
}
void
StyledStreamWriter::writeWithIndent( const std::string &value )
{
writeIndent();
*document_ << value;
}
void
StyledStreamWriter::indent()
{
indentString_ += indentation_;
}
void
StyledStreamWriter::unindent()
{
assert( indentString_.size() >= indentation_.size() );
indentString_.resize( indentString_.size() - indentation_.size() );
}
void
StyledStreamWriter::writeCommentBeforeValue( const Value &root )
{
if ( !root.hasComment( commentBefore ) )
return;
*document_ << normalizeEOL( root.getComment( commentBefore ) );
*document_ << "\n";
}
void
StyledStreamWriter::writeCommentAfterValueOnSameLine( const Value &root )
{
if ( root.hasComment( commentAfterOnSameLine ) )
*document_ << " " + normalizeEOL( root.getComment( commentAfterOnSameLine ) );
if ( root.hasComment( commentAfter ) )
{
*document_ << "\n";
*document_ << normalizeEOL( root.getComment( commentAfter ) );
*document_ << "\n";
}
}
bool
StyledStreamWriter::hasCommentForValue( const Value &value )
{
return value.hasComment( commentBefore )
|| value.hasComment( commentAfterOnSameLine )
|| value.hasComment( commentAfter );
}
std::string
StyledStreamWriter::normalizeEOL( const std::string &text )
{
std::string normalized;
normalized.reserve( text.length() );
const char *begin = text.c_str();
const char *end = begin + text.length();
const char *current = begin;
while ( current != end )
{
char c = *current++;
if ( c == '\r' ) // mac or dos EOL
{
if ( *current == '\n' ) // convert dos EOL
++current;
normalized += '\n';
}
else // handle unix EOL & other char
normalized += c;
}
return normalized;
}
std::ostream& operator<<( std::ostream &sout, const Value &root )
{
Json::StyledStreamWriter writer;
writer.write(sout, root);
return sout;
}
} // namespace Json
}
json_writer.o: ../src/lib/jsonlib/json_writer.cpp \
../src/lib/jsonlib/../../include/json/writer.h \
../src/include/../include/json/value.h \
../src/include/../include/json/forwards.h \
../src/include/../include/json/config.h
#!/bin/bash
cd /home/hj/Roma/bin/
nohup /home/hj/Roma/bin/Konkexinghai >> /dev/null 2>&1 &
#nohup ./Konkexinghai 2>&1|logger -i -t "Konkexinghai" &
#!/bin/sh
while :
do
stillRunning=$(ps -e |grep Konkexinghai)
if [ "$stillRunning" ] ; then
echo "Konkexinghai is running."
else
echo "try to start Konkexinghai"
killall Konkexinghai
sleep 1
mv /tmp/Roma/bin/Konkexinghai /home/hj/Roma/bin/
mv /tmp/Roma/config/hj_hwprofile.json /home/hj/Roma/config/
sh /home/hj/Roma/bin/start.sh &
fi
sleep 60
done
#!/bin/bash
#1:system config
#2:Roma config
mkdir /home/hj/Roma/
mv bin/ /home/hj/Roma/
mv config/ /home/hj/Roma/
#3:ccu config
mv check_Konkexinghai.sh /usr/local/bin/hj/
mv on_boot.sh /usr/local/bin/hj/
echo "install Konkexinghai ok,sys will reboot in 1s."
reboot
{
"client_id" : "",
"device_name" : "",
"result" : "0"
}
{
"broker_addr":"121.0.0.1:23883",
"log_level":"I",
"req_queue_size":16
}
#!/bin/bash
/usr/local/bin/hj/s700_oled >> /dev/null 2>&1 &
sysctl -p;
CRON_FILE="/etc/crontab"
#disable crontab
service cron stop
sed -i 's%\(.*/home/hj/smarthome/script/monitor.sh\)%#\1%' $CRON_FILE;
#/usr/local/bin/hj/hj_auth_ccuid.sh
ccuid_hostname=`cat /etc/hj_ccuid`;
curr_hostname=`cat /etc/hostname`;
if [ "$ccuid_hostname" != "$curr_hostname" ]; then
echo "$ccuid_hostname" > /etc/hostname;
hostname $ccuid_hostname;
fi
ping -c 1 -W 1 114.114.114.114
if [ $? -eq 0 ];then
ntpdate -p 2 0.debian.pool.ntp.org && hwclock -w --utc
fi
/usr/local/bin/hj/HJ_Firmware monitor upgrade.cloud.hijaytech.com upgrade.cloud.hijaytech.com >/dev/null 2>&1 &
sh /usr/local/bin/hj/check_Konkexinghai.sh &
sleep 1
#enable crontab
sed -i 's%\(^##*\)\(.*/home/hj/smarthome/script/monitor.sh\)%\2%' $CRON_FILE;
service cron start
[COMMON]
XCG_IfrName=enp2s0
LOG_DIR=./
LOG_FILESIZE=1048576
LOG_LEVEL_FILE=20
LOG_LEVEL_TERM=20
LOG_FILENUM=10
LINKGW_IP=127.0.0.1
LINKGW_PORT=23883
LINKGW_USER=
LINKGW_PWD=
LINK_PTPID=
CLOUDGW_APPID=32000aba01b96e00
CLOUDGW_ACCESSID=32000aba01b96e00
CLOUDGW_ACCESSSECRET=35b55924d066fed133d599ee71dbbee5
CLOUDGW_HOST=52.83.109.187
CLOUDGW_PORT=21883
CLOUDGW_SSL=false
API_HOST=http://testpark.hzgxtc.com/cloudpark-web/home/record/media
SNAPSHOT_DIR=/home/xjj/MyBuild/xlinkCY/cy-ptp/bin/snap/
PARKING_NAME=杭州东宁路停车场
SNAP_UPLOAD_TYPE=2
[LANES]
LANELIST_COUNT=1
LANE_ID_1=1028888999977
LANE_PID_1=160008bb9a4405ba160008bb9a443c01
LANE_NAME_1=cy停车场入口1
TTCLOUD_HOST_1=testpark.hzgxtc.com
TTCLOUD_PORT_1=21883
TTCLOUD_CLIENT_ID_1=M000661
TTCLOUD_CHANNEL_NUM_1=1
TTCLOUD_CHANNEL_LSN_1=1028888999901
TTCLOUD_DEVICE1_LSN_1=407293281
TTCLOUD_DEVICE2_LSN_1=407293282
TTCLOUD_DEVICE3_LSN_1=407293283
TTCLOUD_DEVICE4_LSN_1=
TTCLOUD_PARK_ID_1=9003064
TTCLOUD_USERNAME_1=M00066
TTCLOUD_PASSWORD_1=M00066
TTCLOUD_MCU_PRIVATE_KEY_1=MIICXgIBAAKBgQDJjDf8oH1EgS7dYwJuZogI6XKuqKTTqzZmjHbLGQ9qk+LMT4Ft/D14PivULHgAPtOy3MNueW/dZ+FnZ/4QaY5j5w95XIkZ7zJ9CY5Qz5H0zrnYtuSPDVPOlUqYL8r7m/KyiQtpaALMoeKq6VGHgjjybINYKP9H1kRYv49ZJcJKFQIDAQABAoGBAImmCSqxFTyvGam7kBKEVg34GgntRb0GZr382rj04ZGBdNjix9us9PJlS5u5zy8juYOjwJl3uI22/7uWy268GLEtkPI1IsZKiHSajmmgJwVjEMrra7wIiMdhaz3yO6gqcoHdjYY+jwJ1yu0wu9IhNIplo4IKR58ibqfXiGx/vOjhAkEA71RVrB405jXhmkYxOBzAdXw1GB/TmDG/ViEhlBM9L2yXgzUjRBhy78GtKeDPpYE9p/lLwVO8TgrDDPdB0t4ffQJBANeWK3M2jBPgzzx/fjfFtCI03wcSVnvNlqTPukjd9xHHod8gBFS91FuXH0zrFRiOno7Ml1hCB2qn/ihqKcYniHkCQQDbBnpVR1uwJzVtI7ndmWqE2oQYrN/PlA+AOlfplOXU5fOPL20z35AoXT4lakl+NNYBSMQMjJ5zaaPx1MLXwVJdAkBNTd/OtGSOTDKDcwQDY7Uv/t1qX7z7L8Ew3/vgXRdXHMqCg6yJ5nfbT9k9b55k698XPW2XjDW0nQCZ5VeNYmehAkEAnWOh4JrpwPqjZ6PjGFuJA3tCsm9qkGAyyP6/hlThGdUx7+uEIrhCNcGoJqisuvZ3tARMj4sPIhBcuSFnH+KkIw==
TTCLOUD_MCU_PUBLIC_KEY_1=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDoIeMzBw6L+p+FAYMRjJ3KxJa+Tvv+RLhgjlVhYWhdKLq3mTeRsNRP2CiUv/G9N99YfSEAA0M1DB6s6vt9n1hc8tTwL6isz0yBST+vbMmNFR4Y93Ei7Ym5pARm12m/0As74K7lsDz4n/IgYBvj6Sew7Y2VI8MhSPx71/T+3cVNVwIDAQAB
LANE_ID_2=1028888999988
LANE_PID_2=160008bb9a4405ba160008bb9a443c01
LANE_NAME_2=cy停车场出口1
TTCLOUD_HOST_2=122.224.122.76
TTCLOUD_PORT_2=21883
TTCLOUD_CLIENT_ID_2=IOT-9003044-2
TTCLOUD_CHANNEL_NUM_2=2
TTCLOUD_CHANNEL_LSN_2=E40729329
TTCLOUD_DEVICE1_LSN_2=E407293291
TTCLOUD_DEVICE2_LSN_2=E407293292
TTCLOUD_DEVICE3_LSN_2=E407293293
TTCLOUD_DEVICE4_LSN_2=
TTCLOUD_PARK_ID_2=9003044
TTCLOUD_USERNAME_2=IOT-9003044-2
TTCLOUD_PASSWORD_2=Egova_2019_LOT
TTCLOUD_MCU_PRIVATE_KEY_2=MIICXgIBAAKBgQDJjDf8oH1EgS7dYwJuZogI6XKuqKTTqzZmjHbLGQ9qk+LMT4Ft/D14PivULHgAPtOy3MNueW/dZ+FnZ/4QaY5j5w95XIkZ7zJ9CY5Qz5H0zrnYtuSPDVPOlUqYL8r7m/KyiQtpaALMoeKq6VGHgjjybINYKP9H1kRYv49ZJcJKFQIDAQABAoGBAImmCSqxFTyvGam7kBKEVg34GgntRb0GZr382rj04ZGBdNjix9us9PJlS5u5zy8juYOjwJl3uI22/7uWy268GLEtkPI1IsZKiHSajmmgJwVjEMrra7wIiMdhaz3yO6gqcoHdjYY+jwJ1yu0wu9IhNIplo4IKR58ibqfXiGx/vOjhAkEA71RVrB405jXhmkYxOBzAdXw1GB/TmDG/ViEhlBM9L2yXgzUjRBhy78GtKeDPpYE9p/lLwVO8TgrDDPdB0t4ffQJBANeWK3M2jBPgzzx/fjfFtCI03wcSVnvNlqTPukjd9xHHod8gBFS91FuXH0zrFRiOno7Ml1hCB2qn/ihqKcYniHkCQQDbBnpVR1uwJzVtI7ndmWqE2oQYrN/PlA+AOlfplOXU5fOPL20z35AoXT4lakl+NNYBSMQMjJ5zaaPx1MLXwVJdAkBNTd/OtGSOTDKDcwQDY7Uv/t1qX7z7L8Ew3/vgXRdXHMqCg6yJ5nfbT9k9b55k698XPW2XjDW0nQCZ5VeNYmehAkEAnWOh4JrpwPqjZ6PjGFuJA3tCsm9qkGAyyP6/hlThGdUx7+uEIrhCNcGoJqisuvZ3tARMj4sPIhBcuSFnH+KkIw==
TTCLOUD_MCU_PUBLIC_KEY_2=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDoIeMzBw6L+p+FAYMRjJ3KxJa+Tvv+RLhgjlVhYWhdKLq3mTeRsNRP2CiUv/G9N99YfSEAA0M1DB6s6vt9n1hc8tTwL6isz0yBST+vbMmNFR4Y93Ei7Ym5pARm12m/0As74K7lsDz4n/IgYBvj6Sew7Y2VI8MhSPx71/T+3cVNVwIDAQAB
[DEVICES]
DEVICELIST_COUNT=1
LOGIN_IPAD_1=192.168.2.243
LOGIN_PORT_1=8000
LOGIN_USER_1=admin
LOGIN_CODE_1=yixin2017
LINKS_MODE_1=0
PVIEW_TYPE_1=0
SRATE_TYPE_1=0
LANE_INDEX_1=1
LANE_MAIN_1=true
LOGIN_IPAD_2=192.168.1.65
LOGIN_PORT_2=8000
LOGIN_USER_2=admin
LOGIN_CODE_2=admin123
LINKS_MODE_2=0
PVIEW_TYPE_2=0
SRATE_TYPE_2=0
LANE_INDEX_2=2
LANE_MAIN_2=true
[OSS]
USE_OSS_UPLOAD=true
OSS_ENDPOINT=oss-cn-hz-hty-d01-a.wtops-procloud.com
OSS_ACCESSKEYID=s66XlmChYC15GA74
OSS_ACCESSKEYSECRET=DW9hMIEwf4kSXCEWLy4k9PAn0eVkRO
OSS_BACKETNAME=hztc-oss
OSS_OBJECTNAME=
[LICENCE]
LICENCE_CODE=zh2ef9XQJ2xiTbNaY2slW4nVC7/mcWdY4I6t77SUhVG7QsJrO1qtYPvm7F0uqe2Ur5c3L74HCgqVTfYGBSTozoC9cepHaXp8pcTY1++oonvuqOnNhL6rZ1K5ksOPswYUZXyEwBsgiaSynJGJYqz8hpZv0YJdxjiT5V9eTH0Sa5v8ueCio5eIqzK0LQcoDQiU0pwagueFoESp1h/AXGq80pXUWMjvN6oOPeEC3mOmu9vnM23R/5u69tdojwNFnsI5tC/wZlT9X9tEr0VLCszIsBPriVkpQrIJV96Bd4cQT4ru2cyWPo6p125ZZt/EDs23OZBD96xBqTO2c0g7So0cPKlb/9PoBd1oumAxI0/+u0I=
[TTCLOUD]
TTCLOUD_HOST=testpark.hzgxtc.com
TTCLOUD_PORT=21883
TTCLOUD_CLIENT_ID=M000661
TTCLOUD_CHANNEL_LSN=16400000018214
TTCLOUD_PARK_ID=9003064
TTCLOUD_USERNAME=M00066
TTCLOUD_PASSWORD=M00066
TTCLOUD_MCU_PRIVATE_KEY=MIICXgIBAAKBgQDJjDf8oH1EgS7dYwJuZogI6XKuqKTTqzZmjHbLGQ9qk+LMT4Ft/D14PivULHgAPtOy3MNueW/dZ+FnZ/4QaY5j5w95XIkZ7zJ9CY5Qz5H0zrnYtuSPDVPOlUqYL8r7m/KyiQtpaALMoeKq6VGHgjjybINYKP9H1kRYv49ZJcJKFQIDAQABAoGBAImmCSqxFTyvGam7kBKEVg34GgntRb0GZr382rj04ZGBdNjix9us9PJlS5u5zy8juYOjwJl3uI22/7uWy268GLEtkPI1IsZKiHSajmmgJwVjEMrra7wIiMdhaz3yO6gqcoHdjYY+jwJ1yu0wu9IhNIplo4IKR58ibqfXiGx/vOjhAkEA71RVrB405jXhmkYxOBzAdXw1GB/TmDG/ViEhlBM9L2yXgzUjRBhy78GtKeDPpYE9p/lLwVO8TgrDDPdB0t4ffQJBANeWK3M2jBPgzzx/fjfFtCI03wcSVnvNlqTPukjd9xHHod8gBFS91FuXH0zrFRiOno7Ml1hCB2qn/ihqKcYniHkCQQDbBnpVR1uwJzVtI7ndmWqE2oQYrN/PlA+AOlfplOXU5fOPL20z35AoXT4lakl+NNYBSMQMjJ5zaaPx1MLXwVJdAkBNTd/OtGSOTDKDcwQDY7Uv/t1qX7z7L8Ew3/vgXRdXHMqCg6yJ5nfbT9k9b55k698XPW2XjDW0nQCZ5VeNYmehAkEAnWOh4JrpwPqjZ6PjGFuJA3tCsm9qkGAyyP6/hlThGdUx7+uEIrhCNcGoJqisuvZ3tARMj4sPIhBcuSFnH+KkIw==
TTCLOUD_MCU_PUBLIC_KEY=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDoIeMzBw6L+p+FAYMRjJ3KxJa+Tvv+RLhgjlVhYWhdKLq3mTeRsNRP2CiUv/G9N99YfSEAA0M1DB6s6vt9n1hc8tTwL6isz0yBST+vbMmNFR4Y93Ei7Ym5pARm12m/0As74K7lsDz4n/IgYBvj6Sew7Y2VI8MhSPx71/T+3cVNVwIDAQAB
# Application settings
[Application]
EmbedPTPServer=true
PTPServerPort=23883
LogPath=/tmp/
RunMode=0
SlaverAllow=0
IsOfficial=true
UnPairDirectDel=1
DetectedMode=6
FirmwareVer=3
SNuseMAC=1
CMSSL=false
CMPort=1883
#SIT
#CMHost=cm-release-sit.xlink.cn
#APIHost=https://api-release-sit.xlink.cn
#IOT
CMHost=mqtt.xlink.cn
APIHost=https://api2.xlink.cn
# User settings
[User]
#SIT
; ProductID=16000eb9e1e2200816000eb9e1e22c01
; ProductKey=ca85b01c25868d70141482243069c4ab
; CertificationID=5f16c339553dfa69fafe7b6f
; CertificationKey=56395fde-3b1c-46dc-a3a6-f3b1aa62be3b
#IOT
ProductID=1603bcc0b2ca03e91603bcc0b2cab201
ProductKey=219e6b59c46282a67cea36050111e779
CertificationID=605980cd6fb0bd27b23545fa
CertificationKey=60259c95-a5e0-43d6-a1a5-9bf45aa79b06
IfrName=enp2s0
[Alarm]
AlarmCount=7
# 门磁告警
Alarm1=160fa8b41a6303e9160fa8b41a638001|1|1|true|false|true
# 红外告警
Alarm2=160fa8b41a7103e9160fa8b41a71e201|1|1|true|false|true
# 可燃气体
Alarm3=160fa8b41a7403e9160fa8b41a745401|0|1|true|true|true
Alarm4=160fa8b41a7403e9160fa8b41a745401|1|1|true|true|true
# 智能紧急按钮
Alarm5=160fa2b41a7303e9160fa2b41a735c01|1|1|true|true|true
# 豪恩门磁告警
Alarm6=160fa8b42d2503e9160fa8b42d259201|1|1|true|false|true
# 豪恩红外告警
Alarm7=160fa2b42d2603e9160fa2b42d267601|1|1|true|false|true
[Category]
Category1=1|0|2|我的房间
[Trigger]
Trigger1=1|1|离家
Trigger2=2|1|回家
Trigger3=3|1|睡觉
Trigger4=4|1|起床
#AuthSvr Config File
#author: xiaojiajie xiaojiajie@xlink.cn
#create: 2017-08-04
[global]
### log级别
slog_level=DEBUG
slog_term_level=DEBUG
#slog_level=INFO
### log文件名
slog_log_name=/tmp/logs/xlinkupgrade.log
### log 文件最大大小(单位M)
slog_log_maxsize=2M
### log文件最多个数
slog_log_maxcount=2
### log缓冲区大小(单位KB,默认512KB)
slog_flush_size=512
### log缓冲区刷新间隔(单位s,默认1s)
slog_flush_interval=2
### log动态更新配置参数时间间隔(单位s,默认60s)
config_update_interval=3600
DB_PATH=/xlink-gw/db/core.db
UPGRADE_URL=http://api2.xlink.cn
BEGIN_HOUR=0
END_HOUR=3
#!/bin/sh
/xlink-gw/xsepproject -c /xlink-gw/xsep.conf &
/xlink-gw/xlink-gw-core-cpp > /dev/null 2>&1 &
[COMMON]
IfrName=enp2s0
DB_DIR=./
LOG_DIR=./
LOG_FILESIZE=1048576
LOG_LEVEL_FILE=20
LOG_LEVEL_TERM=20
LOG_FILENUM=10
LINKGW_HOST=127.0.0.1
LINKGW_PORT=23883
LINKGW_CLIENT_ID=SEP789456
LINKGW_USERNAME=
LINKGW_PASSWORD=
# SIT
# API_HOST=https://api-release-sit.xlink.cn
# CertificationID=5f16c339553dfa69fafe7b6f
# CertificationKey=56395fde-3b1c-46dc-a3a6-f3b1aa62be3b
# IOT
API_HOST=https://api2.xlink.cn
CertificationID=5a0d2c45a493ae270f3a87ed
CertificationKey=cd212b40-542d-4661-ab6a-e57babd774aa
\ No newline at end of file
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