From b497f4cbdbe89d30f754ee0c8da3d67cb29f2c97 Mon Sep 17 00:00:00 2001 From: zhouhuang Date: Mon, 14 Oct 2024 20:27:48 +0800 Subject: [PATCH] deleted 101/104 --- das-dn/subgdw104/sub_gdw104.cpp | 2542 ----------------- das-dn/subgdw104/sub_gdw104.h | 474 --- .../subiec101balanced/sub_iec101_balanced.cpp | 241 -- .../subiec101balanced/sub_iec101_balanced.h | 63 - .../sub_iec101_unbalanced.cpp | 404 --- .../sub_iec101_unbalanced.h | 88 - das-dn/submodbustcp/sub_modbus_rtu_tcp.cpp | 1030 ------- das-dn/submodbustcp/sub_modbus_rtu_tcp.h | 92 - 8 files changed, 4934 deletions(-) delete mode 100644 das-dn/subgdw104/sub_gdw104.cpp delete mode 100644 das-dn/subgdw104/sub_gdw104.h delete mode 100644 das-dn/subiec101balanced/sub_iec101_balanced.cpp delete mode 100644 das-dn/subiec101balanced/sub_iec101_balanced.h delete mode 100644 das-dn/subiec101unbalanced/sub_iec101_unbalanced.cpp delete mode 100644 das-dn/subiec101unbalanced/sub_iec101_unbalanced.h delete mode 100644 das-dn/submodbustcp/sub_modbus_rtu_tcp.cpp delete mode 100644 das-dn/submodbustcp/sub_modbus_rtu_tcp.h diff --git a/das-dn/subgdw104/sub_gdw104.cpp b/das-dn/subgdw104/sub_gdw104.cpp deleted file mode 100644 index 334d408c..00000000 --- a/das-dn/subgdw104/sub_gdw104.cpp +++ /dev/null @@ -1,2542 +0,0 @@ -#include "sub_gdw104.h" -#include - -//国网DLT634.5104-2009实施细则(试行) -static const BYTE GDW_M_FT_NA_1 = 0x2A; //故障事件 -static const BYTE GDW_M_KY_NA_1 = 0x6C; //108 ECC公钥传输报文 -static const BYTE GDW_C_SE_ND_1 = 0x88; //多点设定 归一化 -static const BYTE GDW_C_SR_NA_1 = 0xC8; //切换定值区 -static const BYTE GDW_C_RR_NA_1 = 0xC9; //读取定值区 -static const BYTE GDW_C_RS_NA_1 = 0xCA; //读取定值 -static const BYTE GDW_C_WS_NA_1 = 0xCB; //设定定值 -static const BYTE GDW_M_IT_NB_1 = 0xCE; //累计量,短浮点数 -static const BYTE GDW_M_IT_TC_1 = 0xCF; //带CP56Time2a时标的累计量,短浮点数 -static const BYTE GDW_M_EM_NA_1 = 0xCE; //电量当前值 -static const BYTE GDW_M_FM_NA_1 = 0xCF; //电量冻结值 -static const BYTE GDW_F_FR_NA_1 = 0xD2; //文件传输 -static const BYTE GDW_F_SR_NA_1 = 0xD3; //软件升级 - -static const BYTE FILE_TRS_TYPE = 0x02; -static const BYTE ReadFileDirAct = 0x01; -static const BYTE ReadFileDirCon = 0x02; -static const BYTE ReadFileSelAct = 0x03; -static const BYTE ReadFileSelCon = 0x04; -static const BYTE ReadFileDataAct = 0x05; -static const BYTE ReadFileDataCon = 0x06; -static const BYTE WriteFileSelAct = 0x07; -static const BYTE WriteFileSelCon = 0x08; -static const BYTE WriteFileDataAct = 0x09; -static const BYTE WriteFileDataCon = 0x0A; - -#define FILE_SOE_PATH_NAME "%s/soe.msg" -#define FILE_CO_PATH_NAME "%s/co.msg" -#define FILE_EXV_PATH_NAME "%s/exv%04d%02d%02d.msg" -#define FILE_FIXPT_PATH_NAME "%s/fixpt%04d%02d%02d.msg" -#define FILE_FRZ_PATH_NAME "%s/frz%04d%02d%02d.msg" -#define FILE_FLOWREV_PATH_NAME "%s/flowrev.msg" -#define FILE_ULOG_PATH_NAME "%s/ulog.msg" - -static const value_string yk_type[] = -{ - {YKT_NULL, "空闲"}, - {YKT_SELREQ, "选择"}, - {YKT_SELRET, "选择确认"}, - {YKT_ABRREQ, "撤销"}, - {YKT_EXEREQ, "执行"}, - {YKT_EXERET, "执行确认"} -}; - -static void* main_file_process(void* param) -{ - CGDW104FileProcess* proc = (CGDW104FileProcess *)param; - - DWORD old_ticks = 0; - - while (TRUE) - { - if (old_ticks != system32.ticks) - { - old_ticks = system32.ticks; - proc->OnTimer(); - } - usleep(5000); - } - - pthread_exit(0); - - return ((void*)0); -} - -BOOLEAN CGDW104FileProcess::SaveMapToFile(void) -{ - std::ofstream file("gdw104mapext.dmp"); - - if (file.is_open()) - { - std::map::iterator it; - file << system32.timers << std::endl; - for (it = mapYcExetremumRecordDatas.begin(); it != mapYcExetremumRecordDatas.end(); it++) - { - file << it->first << " " \ - << it->second.datetime << " "\ - << it->second.fMaxVal << " "\ - << it->second.fMinVal << " " \ - << it->second.fCoef << " " \ - << it->second.fBase << " " \ - << it->second.iMaxVal << " " \ - << it->second.iMinVal << " " \ - << it->second.MaxTime << " " \ - << it->second.MinTime << " " \ - << it->second.iCurVal << std::endl; - } - file.close(); - return TRUE; - } - return FALSE; -} - -BOOLEAN CGDW104FileProcess::LoadMapFromFile(int size) -{ - std::ifstream file("gdw104mapext.dmp"); - if (file.is_open()) - { - int count = 0; - std::string line; - int key; - STRUCT_YCEXTREMUM value; - - mapYcExetremumRecordDatas.clear(); - - while (std::getline(file, line)) - { - std::stringstream stream(line); - if (count == 0) - { - LONG dt; - stream >> dt; - m_last_day = Time_ttounionCP56Time((time_t)dt).dayofmonth; - if (m_last_day <= 0) - { - file.close(); - return FALSE; - } - } - else - { - stream >> key >> value.datetime >> value.fMaxVal >> value.fMinVal >> value.fCoef >> value.fBase >> value.iMaxVal >> value.iMinVal >> value.MaxTime >> value.MinTime >> value.iCurVal; - if (mapYcExetremumRecordDatas.find(key) == mapYcExetremumRecordDatas.end()) - { - mapYcExetremumRecordDatas.insert(std::map::value_type(key, value)); - } - } - count++; - } - - file.close(); - if (size != (count - 1)) - { - vLog(LOG_ERROR, "yccount is: %d, and count is: %d\n", size, count); - unlink("gdw104mapext.dmp"); - return FALSE; - } - return TRUE; - } - - return FALSE; -} - -BYTE CGDW104FileProcess::GetCheckSum8(BYTE* pData, int count) -{ - int i; - BYTE result = 0; - BYTE* pBuf = pData; - - for (i = 0; i < count; i++) - { - result += *pBuf; - pBuf++; - } - - return result; -} - -void CGDW104FileProcess::delete_files_in_dir(const char* folder_path) -{ - DIR* dir; - struct dirent* entry; - char file_path[256]; - - // 打开目录 - dir = opendir(folder_path); - if (dir == NULL) - { - vLog(LOG_ERROR, "无法打开目录:%s", folder_path); - return; - } - - // 遍历目录 - while ((entry = readdir(dir)) != NULL) - { - // 忽略当前目录和上级目录 - if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) - { - continue; - } - // 构建文件路径 - snprintf(file_path, sizeof(file_path), "%s/%s", folder_path, entry->d_name); - // 检查文件类型 - struct stat statbuf; - if (lstat(file_path, &statbuf) == -1) - { - vLog(LOG_ERROR, "获取文件<%s>状态失败(%d,%s)\n", file_path, errno, strerror(errno)); - return; - } - // 如果是文件则删除 - if (S_ISREG(statbuf.st_mode)) - { - if (unlink(file_path) != 0) - { - vLog(LOG_ERROR, "删除文件<%s>失败(%d,%s)", file_path, errno, strerror(errno)); - return; - } - } - // 如果是文件夹则递归删除 - else if (S_ISDIR(statbuf.st_mode)) - { - delete_files_in_dir(file_path); - } - } - // 关闭目录 - closedir(dir); -} - -BOOLEAN CGDW104FileProcess::OnCreate(int uid, const void* pUnit, const void* param) -{ - if (uid < 0 || uid >= UNIT_NUM) return FALSE; - if (pUnit == NULL || param == NULL) return FALSE; - mapYcExetremumRecordDatas.clear(); - m_uid = uid; - struGDW104Option m_nOption = *(struGDW104Option *)param; - struUnit unit = *(struUnit *)pUnit; - - m_pUnitYM = NULL; - if (unit.ymcount) - { - m_total_ym = unit.ymcount; - m_pUnitYM = new struUnitYM[unit.ymcount]; - if (m_pUnitYM) - { - memcpy(m_pUnitYM, unit.yms, sizeof(struUnitYM) * unit.ymcount); - } - } - m_information_address_length = m_nOption.iec104.info_addr_size; - m_yx_information_address_start = m_nOption.iec104.yx_start_address; - m_yc_information_address_start = m_nOption.iec104.yc_start_address; - m_ym_information_address_start = m_nOption.iec104.ym_start_address; - - if (m_nOption.soeDir[0] == '\0') str_SOERecordDir = "soe"; - else str_SOERecordDir = m_nOption.soeDir; - if (m_nOption.coDir[0] == '\0') str_coRecordDir = "co"; - else str_coRecordDir = m_nOption.coDir; - if (m_nOption.fixptDir[0] == '\0') str_fixptRecordDir = "fixpt"; - else str_fixptRecordDir = m_nOption.fixptDir; - if (m_nOption.exvDir[0] == '\0') str_exvRecordDir = "exv"; - else str_exvRecordDir = m_nOption.exvDir; - if (m_nOption.frzDir[0] == '\0') str_frzRecordDir = "frz"; - else str_frzRecordDir = m_nOption.frzDir; - if (m_nOption.flowrevDir[0] == '\0') str_flowrevRecordDir = "flowrev"; - else str_flowrevRecordDir = m_nOption.flowrevDir; - if (m_nOption.ulogDir[0] == '\0') str_ulogRecordDir = "ulog"; - else str_ulogRecordDir = m_nOption.ulogDir; - //根据配置来创建文件夹 - mkLogDir(str_SOERecordDir.c_str()); - mkLogDir(str_coRecordDir.c_str()); - mkLogDir(str_fixptRecordDir.c_str()); - mkLogDir(str_exvRecordDir.c_str()); - mkLogDir(str_frzRecordDir.c_str()); - mkLogDir(str_flowrevRecordDir.c_str()); - mkLogDir(str_ulogRecordDir.c_str()); - - char pathName[512]; - FILE* pf; - snprintf(pathName, sizeof(pathName), "%s/%s", configpath, FILE_UNIT_STATIC); - pf = fopen(pathName, "rb"); - if (pf) - { - memset(&m_unit, '\0', sizeof(m_unit)); - if (fseek(pf, sizeof(struUnitStatic) * uid, SEEK_SET) == 0) - { - fread(&m_unit, sizeof(struUnitStatic), 1, pf); - } - fclose(pf); - } - - //创建极值列表 - if (!LoadMapFromFile(unit.yccount)) - { - for (int i = 0; i < unit.yccount; i++) - { - STRUCT_YCEXTREMUM data; - data.datetime = system32.timers; - data.iMaxVal = 0x80000000; - data.iMinVal = 0x7FFFFFFF; - data.MaxTime = system32.timers; - data.MinTime = system32.timers; - data.fCoef = unit.ycs[i].coef; - data.fBase = unit.ycs[i].base; - if (mapYcExetremumRecordDatas.find(i) == mapYcExetremumRecordDatas.end()) - { - mapYcExetremumRecordDatas.insert(std::map::value_type(i, data)); - } - } - } - m_database.Open("./gdw104.db", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); - m_database.MoveDatabaseToMemory(); - //创建数据库表 - try - { - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - pStmt->SqlStatement("CREATE TABLE IF NOT EXISTS SOE_RECORD_TABLE (" - "Yxpoint INTEGER NOT NULL," - "Yxvalue INTEGER NOT NULL," - "Yxdatetime INTEGER NOT NULL," - "Yxmillisecond INTEGER NOT NULL," - "CONSTRAINT SOE_RECORD_TABLE_PK PRIMARY KEY (Yxpoint, Yxvalue, Yxdatetime, Yxmillisecond));"); - - pStmt->SqlStatement("CREATE TABLE IF NOT EXISTS YKLOG_RECORD_TABLE (" - "Ykpoint INTEGER NOT NULL," - "Yktype INTEGER NOT NULL," - "Ykvalue INTEGER NOT NULL," - "Ykdatetime INTEGER NOT NULL," - "Ykmillisecond INTEGER NOT NULL," - "CONSTRAINT YKLOG_RECORD_TABLE_PK PRIMARY KEY (Ykpoint, Yktype, Ykvalue, Ykdatetime, Ykmillisecond));"); - //创建极值库 - pStmt->SqlStatement("CREATE TABLE IF NOT EXISTS YCEXV_RECORD_TABLE (" - "Ycpoint INTEGER NOT NULL," - "Ycdatetime INTEGER NOT NULL," - "YciMaxval INTEGER NOT NULL," - "YciMinval INTEGER NOT NULL," - "YcfMaxval REAL NOT NULL," - "YcfMinval REAL NOT NULL," - "YcMaxdatetime INTEGER NOT NULL," - "YcMindatetime INTEGER NOT NULL," - "CONSTRAINT YCEXV_RECORD_TABLE_PK PRIMARY KEY (Ycpoint, Ycdatetime));"); - - //创建遥测历史数据表YcHisRecordTable - pStmt->SqlStatement("CREATE TABLE IF NOT EXISTS YCHIS_RECORD_TABLE (" - "Ycpoint INTEGER NOT NULL," - "Ycdatetime INTEGER NOT NULL," - "YciVal INTEGER NOT NULL," - "Ycfval REAL NOT NULL," - "CONSTRAINT YCHIS_RECORD_TABLE PRIMARY KEY (Ycpoint, Ycdatetime));"); - //创建冻结电度量表 - pStmt->SqlStatement("CREATE TABLE IF NOT EXISTS FMHIS_RECORD_TABLE (" - "Ympoint INTEGER NOT NULL," - "Ymdatetime INTEGER NOT NULL," - "YmiVal INTEGER NOT NULL," - "Ymfval REAL NOT NULL," - "CONSTRAINT FMHIS_RECORD_TABLE PRIMARY KEY (Ympoint, Ymdatetime));"); - //比较表空间 - delete pStmt; - } - catch (SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "SQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - return FALSE; - } - return TRUE; -} - -BOOLEAN CGDW104FileProcess::OnTimer(void) -{ - BOOLEAN sec_changed = FALSE; - if (last_sec != system32.timers) - { - last_sec = system32.timers; - sec_changed = TRUE; - } - do - { - if (m_nCmdID == FIOCMD_OPEN_FILE) - { - m_nCmdID = 0; - if (m_pFileHandle) - { - fclose(m_pFileHandle); - m_pFileHandle = NULL; - } - m_pFileHandle = fopen(m_pathName.c_str(), m_bWr ? "wb+" : "rb"); - if (m_pFileHandle == NULL) m_nCmdIDConfirm |= CMD_EXEC_ERR; - //获取文件长度 - m_nFileLength = FileLength(m_pathName); - m_nCmdIDConfirm = FIOCMD_OPEN_FILE; - } - else if (m_nCmdID == FIOCMD_CLOSE_FILE) - { - m_nCmdID = 0; - if (m_pFileHandle) - { - fclose(m_pFileHandle); - m_pFileHandle = NULL; - } - m_nFileLength = 0; - m_nFilePos = 0; - m_nReadLen = 0; - } - else if (m_nCmdID == FIOCMD_READ_FILE) - { - m_nCmdID = 0; - if (fseek(m_pFileHandle, m_nFilePos, SEEK_SET) != 0) - { - m_nCmdIDConfirm |= CMD_EXEC_ERR; - } - else - { - int count = (FileLeftLength() > MAX_FILEDATA_LEN) ? MAX_FILEDATA_LEN : FileLeftLength(); - fread((char *)m_fileBuffer, count, 1, m_pFileHandle); - m_nReadLen = count; - } - m_nCmdIDConfirm = FIOCMD_READ_FILE; - } - else if (m_nCmdID == FIOCMD_READ_DIR) - { - //删除目录下所有文件 - delete_files_in_dir(str_SOERecordDir.c_str()); - delete_files_in_dir(str_coRecordDir.c_str()); - delete_files_in_dir(str_exvRecordDir.c_str()); - delete_files_in_dir(str_fixptRecordDir.c_str()); - delete_files_in_dir(str_frzRecordDir.c_str()); - delete_files_in_dir(str_flowrevRecordDir.c_str()); - delete_files_in_dir(str_ulogRecordDir.c_str()); - m_nCmdID = 0; - //生成事件记录文件 - createSOEFile(); - //生成遥控记录文件 - createYKLogFile(); - //生成极值文件 - createExtremumRecordFile(); - //生成遥测定点记录数据文件 - createYCHisRecordFile(); - //生成冻结数据文件 - createFmHisRecordFile(); - //将数据保存到本地数据库 - m_database.SaveDatabaseFromMemoryToFile("./gdw104.db"); - - if (ReadDir(m_pathName.c_str()) <= 0) - { - vLog(LOG_ERROR, "Read %s dir error.\n", m_pathName.c_str()); - m_nCmdIDConfirm |= CMD_EXEC_ERR; - } - m_nCmdIDConfirm = FIOCMD_READ_DIR; - } - } while (0); - - if (sec_changed) - { - DumpSOE(); - DumpYKLog(); - if (m_last_day != system32.now.dayofmonth) - { - UpdateExtremumRecord(TRUE); - m_last_day = system32.now.dayofmonth; - } - else - { - UpdateExtremumRecord(FALSE); - } - if ((system32.timers % 300) == 0) //此处最好根据配置来设置定点数据频率 - { //5分钟保存一次 - //保存一次遥测历史 - DumpYCHisRecord(system32.timers); - //保存一次冻结数据 - DumpFmHisRecord(system32.timers); - // save the memory database to a file - m_database.SaveDatabaseFromMemoryToFile("./gdw104.db"); - } - } - return TRUE; -} - -void CGDW104FileProcess::createSOEFile(void) -{ - int count = 0; - char sql[512]; - char query[512]; - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - try - { - //生成soe文件 - if (m_bCallAllFile) - { - snprintf(query, sizeof(query), "SELECT * FROM SOE_RECORD_TABLE;"); - count = (int)pStmt->SqlAggregateFuncResult("SELECT COUNT(*) FROM SOE_RECORD_TABLE;"); - } - else - { - snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM SOE_RECORD_TABLE WHERE Yxdatetime >= %d AND Yxdatetime <= %d;", (DWORD)m_start_time, (DWORD)m_end_time); - snprintf(query, sizeof(query), "SELECT * FROM SOE_RECORD_TABLE WHERE Yxdatetime >= %d AND Yxdatetime <= %d;", (DWORD)m_start_time, (DWORD)m_end_time); - count = (int)pStmt->SqlAggregateFuncResult(sql); - } - char text[64]; - snprintf(text, sizeof(text), FILE_SOE_PATH_NAME, str_SOERecordDir.c_str()); - FILE *pf = fopen(text, "wb+"); - if (pf != NULL) - { - fprintf(pf, "soe.msg, v1.0\r\n%s,%02d,%02d\r\n", m_unit.name, count, m_information_address_length); - pStmt->BeginTransaction(); - pStmt->Sql(query); - while (pStmt->FetchRow()) - { - char buffer[32]; - struct tm info; - time_t t = (time_t)pStmt->GetColumnInt(2); - localtime_r(&t, &info); - strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &info); - fprintf(pf, "%04x,%d,%s.%3d\r\n", - pStmt->GetColumnInt(0) + m_yx_information_address_start, - pStmt->GetColumnInt(1), - buffer, - pStmt->GetColumnInt(3)); - } - pStmt->FreeQuery(); - pStmt->CommitTransaction(); - - fclose(pf); - } - } - catch(SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "SQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - } - delete pStmt; -} - -void CGDW104FileProcess::createYKLogFile(void) -{ - int count = 0; - char sql[512]; - char query[512]; - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - try - { - if (m_bCallAllFile) - { - snprintf(query, sizeof(query), "SELECT * FROM YKLOG_RECORD_TABLE;"); - count = (int)pStmt->SqlAggregateFuncResult("SELECT COUNT(*) FROM YKLOG_RECORD_TABLE;"); - } - else - { - snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM YKLOG_RECORD_TABLE WHERE Yxdatetime >= %d AND Yxdatetime <= %d;", (DWORD)m_start_time, (DWORD)m_end_time); - snprintf(query, sizeof(query), "SELECT * FROM YKLOG_RECORD_TABLE WHERE Yxdatetime >= %d AND Yxdatetime <= %d;", (DWORD)m_start_time, (DWORD)m_end_time); - count = (int)pStmt->SqlAggregateFuncResult(sql); - } - char text[64]; - snprintf(text, sizeof(text), FILE_CO_PATH_NAME, str_coRecordDir.c_str()); - FILE *pf = fopen(text, "wb+"); - if (pf != NULL) - { - fprintf(pf, "co.msg, v1.0\r\n%s,%02d,%02d\r\n", m_unit.name, count, m_information_address_length); - pStmt->BeginTransaction(); - pStmt->Sql(query); - while (pStmt->FetchRow()) - { - char buffer[32]; - struct tm info; - time_t t = (time_t)pStmt->GetColumnInt(3); - localtime_r(&t, &info); - strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &info); - fprintf(pf, "%04x,%s,%s,%s.%03d\r\n", - pStmt->GetColumnInt(0), - val_to_str(pStmt->GetColumnInt(1), yk_type, "STATE=%d"), - pStmt->GetColumnInt(2) ? "合" : "分", - buffer, - pStmt->GetColumnInt(4)); - } - pStmt->FreeQuery(); - pStmt->CommitTransaction(); - - fclose(pf); - } - } - catch(SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "SQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - } - delete pStmt; -} - -void CGDW104FileProcess::createExtremumRecordFile(void) -{ - char query[512]; - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - try - { - if (m_bCallAllFile) - { - snprintf(query, sizeof(query), "SELECT * FROM YCEXV_RECORD_TABLE;"); - } - else - { - snprintf(query, sizeof(query), "SELECT * FROM YCEXV_RECORD_TABLE WHERE Ycdatetime >= %d AND Ycdatetime <= %d;", (DWORD)m_start_time, (DWORD)m_end_time); - } - - std::map mapExvFileBuffers; - mapExvFileBuffers.clear(); - pStmt->BeginTransaction(); - pStmt->Sql(query); - while (pStmt->FetchRow()) - { - char buffer[256]; - unionCP56Time ut = Time_ttounionCP56Time((time_t)pStmt->GetColumnInt(1)); - snprintf(buffer, sizeof(buffer), FILE_EXV_PATH_NAME, str_exvRecordDir.c_str(), ut.year + 2000, ut.month, ut.dayofmonth); - std::string filename = buffer; - std::string maxbuffer; - std::string minbuffer; - int point = pStmt->GetColumnInt(0); - float maxVal = pStmt->GetColumnDouble(4); - float minVal = pStmt->GetColumnDouble(5); - unionCP56Time maxTime = Time_ttounionCP56Time((time_t)pStmt->GetColumnInt(6)); - unionCP56Time minTime = Time_ttounionCP56Time((time_t)pStmt->GetColumnInt(7)); - snprintf(buffer, sizeof(buffer), "%4x,%4.3f,%04d-%02d-%02d %02d:%02d:%02d.%03d", point + m_yc_information_address_start, maxVal, - maxTime.year + 2000, maxTime.month, maxTime.dayofmonth, maxTime.hour, maxTime.minute, maxTime.millisecond / 1000, maxTime.millisecond % 1000); - maxbuffer = buffer; - snprintf(buffer, sizeof(buffer), "%4x,%4.3f,%04d-%02d-%02d %02d:%02d:%02d.%03d", point + m_yc_information_address_start, minVal, - minTime.year + 2000, minTime.month, minTime.dayofmonth, minTime.hour, minTime.minute, minTime.millisecond / 1000, minTime.millisecond % 1000); - minbuffer = buffer; - if (mapExvFileBuffers.find(filename) == mapExvFileBuffers.end()) - { - STRUCT_FILEBUFFER fb; - fb.count = 1; - fb.ss_outmax = maxbuffer; - fb.ss_outmin = minbuffer; - mapExvFileBuffers.insert(std::map::value_type(filename, fb)); - } - else - { - mapExvFileBuffers[filename].count++; - mapExvFileBuffers[filename].ss_outmax += "," + maxbuffer; - mapExvFileBuffers[filename].ss_outmin += "," + minbuffer; - } - } - pStmt->FreeQuery(); - pStmt->CommitTransaction(); - std::map::iterator it; - for (it = mapExvFileBuffers.begin(); it != mapExvFileBuffers.end(); it++) - { - FILE* pf = fopen(it->first.c_str(), "wb+"); - if (pf) - { - fprintf(pf, "%s, v1.0\r\n%s,%04d-%02d-%02d,%02d\r\n", it->first.c_str(), m_unit.name, system32.now.year+2000, system32.now.month, system32.now.dayofmonth, m_information_address_length); - fprintf(pf, "%d,%s\r\n", it->second.count, it->second.ss_outmax.c_str()); - fprintf(pf, "%d,%s\r\n", it->second.count, it->second.ss_outmin.c_str()); - fclose(pf); - } - } - } - catch(SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "SQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - } - delete pStmt; -} - -void CGDW104FileProcess::createYCHisRecordFile(void) -{ - int count = 0; - char query[512]; - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - try - { - if (m_bCallAllFile) - { - snprintf(query, sizeof(query), "SELECT * FROM YCHIS_RECORD_TABLE WHERE Ycdatetime %% 900 == 0;"); - } - else - { - snprintf(query, sizeof(query), "SELECT * FROM YCHIS_RECORD_TABLE WHERE Ycdatetime >= %d AND Ycdatetime <= %d AND Ycdatetime %% 900 == 0;", (DWORD)m_start_time, (DWORD)m_end_time); - } - vLog(LOG_DEBUG, "ychis file query is: %s\n", query); - std::map mapFixptFileBuffers; - mapFixptFileBuffers.clear(); - pStmt->BeginTransaction(); - pStmt->Sql(query); - count = 0; - int max_count = mapYcExetremumRecordDatas.size(); - while (pStmt->FetchRow()) - { - char buffer[256]; - - unionCP56Time ut = Time_ttounionCP56Time((time_t)pStmt->GetColumnInt(1)); //数据时间 - snprintf(buffer, sizeof(buffer), FILE_FIXPT_PATH_NAME, str_fixptRecordDir.c_str(), ut.year + 2000, ut.month, ut.dayofmonth); - std::string filename = buffer; - int point = pStmt->GetColumnInt(0); - float fVal = pStmt->GetColumnDouble(3); - snprintf(buffer, sizeof(buffer), "%4x,%4.3f", point + m_yc_information_address_start, fVal); - std::string valbuffer = buffer; - if (mapFixptFileBuffers.find(filename) == mapFixptFileBuffers.end()) - { - char temp[64]; - snprintf(temp, sizeof(temp), "%d,%04d-%02d-%02d %02d:%02d:%02d.%03d,", max_count, ut.year + 2000, ut.month, ut.dayofmonth, ut.hour, ut.minute, ut.millisecond / 1000, ut.millisecond % 1000); - STRUCT_FILEBUFFER fb; - fb.count = 1; - fb.ss_outmax = temp + valbuffer; - mapFixptFileBuffers.insert(std::map::value_type(filename, fb)); - } - else if (count == 0) - { - char temp[64]; - snprintf(temp, sizeof(temp), "%d,%04d-%02d-%02d %02d:%02d:%02d.%03d,", max_count, ut.year + 2000, ut.month, ut.dayofmonth, ut.hour, ut.minute, ut.millisecond / 1000, ut.millisecond % 1000); - mapFixptFileBuffers[filename].count++; - mapFixptFileBuffers[filename].ss_outmax += temp + valbuffer; - } - else - { - mapFixptFileBuffers[filename].ss_outmax += "," + valbuffer; - } - count++; - if (count >= max_count) - { - count = 0; - mapFixptFileBuffers[filename].ss_outmax += "\r\n"; - } - } - pStmt->FreeQuery(); - pStmt->CommitTransaction(); - std::map::iterator it; - for (it = mapFixptFileBuffers.begin(); it != mapFixptFileBuffers.end(); it++) - { - FILE* pf = fopen(it->first.c_str(), "wb+"); - if (pf) - { - fprintf(pf, "%s, v1.0\r\n%s,%04d-%02d-%02d,%d,%02d\r\n", it->first.c_str(), m_unit.name, system32.now.year+2000, system32.now.month, system32.now.dayofmonth, it->second.count, m_information_address_length); - fprintf(pf, "%s\r\n", it->second.ss_outmax.c_str()); - fclose(pf); - } - } - } - - catch(SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "SQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - } - delete pStmt; -} - -void CGDW104FileProcess::createFmHisRecordFile(void) -{ - int count = 0; - char query[512]; - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - try - { - if (m_bCallAllFile) - { - snprintf(query, sizeof(query), "SELECT * FROM FMHIS_RECORD_TABLE WHERE Ymdatetime %% 900 == 0;"); - } - else - { - snprintf(query, sizeof(query), "SELECT * FROM FMHIS_RECORD_TABLE WHERE Ymdatetime >= %d AND Ymdatetime <= %d AND Ymdatetime %% 900 == 0;", (DWORD)m_start_time, (DWORD)m_end_time); - } - vLog(LOG_DEBUG, "create frz data query is: %s\n", query); - std::map mapFmHisFileBuffers; - mapFmHisFileBuffers.clear(); - pStmt->BeginTransaction(); - pStmt->Sql(query); - count = 0; - while (pStmt->FetchRow()) - { - char buffer[256]; - - unionCP56Time ut = Time_ttounionCP56Time((time_t)pStmt->GetColumnInt(1)); //数据时间 - snprintf(buffer, sizeof(buffer), FILE_FRZ_PATH_NAME, str_frzRecordDir.c_str(), ut.year + 2000, ut.month, ut.dayofmonth); - std::string filename = buffer; - int point = pStmt->GetColumnInt(0); - float fVal = pStmt->GetColumnDouble(3); - snprintf(buffer, sizeof(buffer), "%4x,%4.3f", point + m_ym_information_address_start, fVal); - std::string valbuffer = buffer; - if (mapFmHisFileBuffers.find(filename) == mapFmHisFileBuffers.end()) - { - char temp[64]; - snprintf(temp, sizeof(temp), "%d,%04d-%02d-%02d %02d:%02d:%02d.%03d,", m_total_ym, ut.year + 2000, ut.month, ut.dayofmonth, ut.hour, ut.minute, ut.millisecond / 1000, ut.millisecond % 1000); - STRUCT_FILEBUFFER fb; - fb.count = 1; - fb.ss_outmax = temp + valbuffer; - mapFmHisFileBuffers.insert(std::map::value_type(filename, fb)); - } - else if (count == 0) - { - char temp[64]; - snprintf(temp, sizeof(temp), "%d,%04d-%02d-%02d %02d:%02d:%02d.%03d,", m_total_ym, ut.year + 2000, ut.month, ut.dayofmonth, ut.hour, ut.minute, ut.millisecond / 1000, ut.millisecond % 1000); - mapFmHisFileBuffers[filename].count++; - mapFmHisFileBuffers[filename].ss_outmax += temp + valbuffer; - } - else - { - mapFmHisFileBuffers[filename].ss_outmax += "," + valbuffer; - } - count++; - if (count >= m_total_ym) - { - count = 0; - mapFmHisFileBuffers[filename].ss_outmax += "\r\n"; - } - } - pStmt->FreeQuery(); - pStmt->CommitTransaction(); - std::map::iterator it; - for (it = mapFmHisFileBuffers.begin(); it != mapFmHisFileBuffers.end(); it++) - { - FILE* pf = fopen(it->first.c_str(), "wb+"); - if (pf) - { - fprintf(pf, "%s, v1.0\r\n%s,%04d-%02d-%02d,%d,%02d\r\n", it->first.c_str(), m_unit.name, system32.now.year+2000, system32.now.month, system32.now.dayofmonth, it->second.count, m_information_address_length); - fprintf(pf, "%s\r\n", it->second.ss_outmax.c_str()); - fclose(pf); - } - } - } - - catch(SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "SQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - } - delete pStmt; -} - -void CGDW104FileProcess::DumpSOE(void) -{ - if (m_soe_load == m_soe_save) return; - - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - try - { - pStmt->BeginTransaction(); - pStmt->Sql("INSERT INTO SOE_RECORD_TABLE VALUES(?,?,?,?)"); - //保存SOE数据 - while (m_soe_load != m_soe_save) - { - pStmt->BindInt(1, m_soes[m_soe_load].order); - pStmt->BindInt(2, m_soes[m_soe_load].value); - pStmt->BindInt(3, unionCP56TimetoTime_t(&m_soes[m_soe_load].st)); - pStmt->BindInt(4, (m_soes[m_soe_load].st.millisecond % 1000)); - pStmt->Execute(); - pStmt->Reset(); - m_soe_load++; - m_soe_load = m_soe_load % DATABASE_SOE_NUM; - } - pStmt->FreeQuery(); - pStmt->CommitTransaction(); - } - catch (SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "SQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - } - delete pStmt; -} - -void CGDW104FileProcess::DumpYKLog(void) -{ - if (m_yklog_load == m_yklog_save) return; - - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - try - { - pStmt->BeginTransaction(); - pStmt->Sql("INSERT INTO YKLOG_RECORD_TABLE VALUES(?,?,?,?,?)"); - //保存SOE数据 - while (m_yklog_load != m_yklog_save) - { - pStmt->BindInt(1, m_yklogs[m_yklog_load].point); - pStmt->BindInt(2, m_yklogs[m_yklog_load].type); - pStmt->BindInt(3, m_yklogs[m_yklog_load].value); - pStmt->BindInt(4, unionCP56TimetoTime_t(&m_yklogs[m_yklog_load].st)); - pStmt->BindInt(5, (m_yklogs[m_yklog_load].st.millisecond % 1000)); - pStmt->Execute(); - pStmt->Reset(); - m_yklog_load++; - m_yklog_load = m_yklog_load % DATABASE_YK_LOG_NUM; - } - pStmt->FreeQuery(); - pStmt->CommitTransaction(); - } - catch (SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "SQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - } - delete pStmt; -} - -void CGDW104FileProcess::UpdateExtremumRecord(BOOLEAN bAddNew) -{ - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - try - { - pStmt->BeginTransaction(); - if (bAddNew) - { - pStmt->Sql("INSERT INTO YCEXV_RECORD_TABLE VALUES(?,?,?,?,?,?,?,?)"); - //保存极值数据 - std::map::iterator it; - for (it = mapYcExetremumRecordDatas.begin(); it != mapYcExetremumRecordDatas.end(); it++) - { - pStmt->BindInt(1, it->first); - //将数据都更新为当前数据和当前时间 - it->second.datetime = system32.timers; - it->second.iMaxVal = it->second.iCurVal; - it->second.iMinVal = it->second.iCurVal; - it->second.fMaxVal = it->second.iCurVal * it->second.fCoef + it->second.fBase; - it->second.fMinVal = it->second.iCurVal * it->second.fCoef + it->second.fBase; - it->second.MaxTime = system32.timers; - it->second.MinTime = system32.timers; - - pStmt->BindInt(2, (LONG)it->second.datetime); - pStmt->BindInt(3, it->second.iMaxVal); - pStmt->BindInt(4, it->second.iMinVal); - pStmt->BindDouble(5, it->second.fMaxVal); - pStmt->BindDouble(6, it->second.fMinVal); - pStmt->BindInt(7, (LONG)it->second.MaxTime); - pStmt->BindInt(8, (LONG)it->second.MinTime); - pStmt->Execute(); - pStmt->Reset(); - } - } - else - { - pStmt->Sql("UPDATE YCEXV_RECORD_TABLE SET " - "YciMaxval=@YciMaxval, " - "YciMinval=@YciMinval, " - "YcfMaxval=@YcfMaxval, " - "YcfMinval=@YcfMinval," - "YcMaxdatetime=@YcMaxdatetime, " - "YcMindatetime=@YcMindatetime " - "WHERE Ycpoint=@Ycpoint"); - //保存极值数据 - std::map::iterator it; - for (it = mapYcExetremumRecordDatas.begin(); it != mapYcExetremumRecordDatas.end(); it++) - { - pStmt->BindInt(1, it->second.iMaxVal); - pStmt->BindInt(2, it->second.iMinVal); - pStmt->BindDouble(3, it->second.fMaxVal); - pStmt->BindDouble(4, it->second.fMinVal); - pStmt->BindInt(5, (LONG)it->second.MaxTime); - pStmt->BindInt(6, (LONG)it->second.MinTime); - pStmt->BindInt(7, it->first); - pStmt->Execute(); - pStmt->Reset(); - } - } - - pStmt->FreeQuery(); - pStmt->CommitTransaction(); - } - catch (SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "aaaaSQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - } - delete pStmt; -} - -void CGDW104FileProcess::DumpYCHisRecord(LONG now) -{ - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - try - { - pStmt->BeginTransaction(); - pStmt->Sql("INSERT INTO YCHIS_RECORD_TABLE VALUES(?,?,?,?)"); - std::map::iterator it; - for (it = mapYcExetremumRecordDatas.begin(); it != mapYcExetremumRecordDatas.end(); it++) - { - pStmt->BindInt(1, it->first); - pStmt->BindInt(2, now); - pStmt->BindInt(3, it->second.iCurVal); - pStmt->BindDouble(4, ((it->second.iCurVal * it->second.fCoef) + it->second.fBase)); - pStmt->Execute(); - pStmt->Reset(); - } - pStmt->FreeQuery(); - pStmt->CommitTransaction(); - } - catch (SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "SQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - } - delete pStmt; -} - -void CGDW104FileProcess::DumpFmHisRecord(LONG now) -{ - SQLiteStatement *pStmt = new SQLiteStatement(&m_database); - try - { - pStmt->BeginTransaction(); - //pStmt->Sql("INSERT INTO FMHIS_RECORD_TABLE VALUES(?,?,?,?)"); - pStmt->Sql("REPLACE INTO FMHIS_RECORD_TABLE VALUES(?,?,?,?)"); - for (int i = 0; i < m_total_ym; i++) - { - pStmt->BindInt(1, m_pUnitYM[i].order); - pStmt->BindInt(2, now); - pStmt->BindInt(3, m_pUnitYM[i].value); - pStmt->BindDouble(4, ((m_pUnitYM[i].value * m_pUnitYM[i].coef) + m_pUnitYM[i].base)); - pStmt->Execute(); - pStmt->Reset(); - } - pStmt->FreeQuery(); - pStmt->CommitTransaction(); - } - catch (SQLiteException &exception) - { - vLog(LOG_ERROR, "\nException Occured"); - exception.Show(); - vLog(LOG_ERROR, "SQLite result code: %d,%s\n", exception.GetSqliteResultCode(), exception.GetErrorDescription().c_str()); - } - delete pStmt; -} - -CSubGDW104Process::CSubGDW104Process() -{ - last_sec = system32.timers; - - m_dwFileType = 0; - memset(&m_nOption, 0, sizeof(m_nOption)); -} - -CSubGDW104Process::~CSubGDW104Process() -{ -} - -BOOLEAN CSubGDW104Process::OnPreCreate(int id) -{ - if (!CIEC104Process::OnPreCreate(id)) return FALSE; - - m_yx_start_address = m_nOption.yx_start_address; - m_yc_start_address = m_nOption.yc_start_address; - m_ym_start_address = m_nOption.ym_start_address; - - if (m_yx_start_address <= 0) m_yx_start_address = IEC_101_104_YX_START_ADDR; - if (m_yc_start_address <= 0) m_yc_start_address = IEC_101_104_YC_START_ADDR; - if (m_ym_start_address <= 0) m_ym_start_address = IEC_101_104_YM_START_ADDR; - - if (!GetOption(&gdw_option, sizeof(gdw_option))) - { - return FALSE; - } - - int i; - int uid; - CIEC104ProcessItem *pItem; - //更新配置 - for (i = 0; i < PROCESS_UNIT_NUM; i++) - { - pItem = (CIEC104ProcessItem *)GetItem(i); - if (NULL == pItem) continue; - pItem->apdu_k_max = m_nOption.k; - pItem->apdu_w_max = m_nOption.w; - pItem->apdu_t0_begin = 10; - uid = GetUnitID(i); - if (uid < 0 || uid >= UNIT_NUM) continue; - m_gdwFile.OnCreate(uid, &config.units[uid], &gdw_option); - } - - return TRUE; -} - -BOOLEAN CSubGDW104Process::OnCreated(int id) -{ - pthread_attr_t attr; - - pthread_attr_init(&attr); - pthread_attr_setstacksize(&attr, MEMERY_1M); - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - - pthread_t pid; - if (pthread_create(&pid, &attr, main_file_process, &m_gdwFile) < 0) - { - vLog(LOG_ERROR, "create main_run_process error(%d,%s).\n", errno, strerror(errno)); - return FALSE; - } - - pthread_attr_destroy(&attr); - - return CIEC104Process::OnCreated(id); -} - -void CSubGDW104Process::GetItemEvents(CIEC104ProcessItem* pItem) -{ - int i, uid, count; - int soe_point; - BOOLEAN soe_value; - BYTE soe_qds; - unionCP56Time soe_time; - - if (NULL == pItem) return; - uid = pItem->GetUnitID(); - if (uid < 0 || uid >= UNIT_NUM) return; - if (NULL == pItem->events.data) return; - count = pItem->events.count; - if (count < 0 || count >= DATABASE_SOE_NUM) count = 0; - int max_count = DATABASE_SOE_NUM - count; - for (i = 0; i < max_count; i++) - { - soe_point = GetUnitSOE(uid, soe_value, soe_qds, soe_time); - if (soe_point < 0) break; - pItem->events.data[count].order = soe_point; - pItem->events.data[count].value = soe_value; - pItem->events.data[count].qds = soe_qds; - memcpy(&pItem->events.data[count].ct, &soe_time, sizeof(soe_time)); - m_gdwFile.PushSOE(soe_time, soe_point, soe_value, uid); - count++; - } - pItem->events.count = count; -} - -BOOLEAN CSubGDW104Process::FetchUnitYC(int order) -{ - int i; - int uid; - int oid; - struUnit* pUnit; - - if (order < 0 || order >= PROCESS_UNIT_NUM) return FALSE; - uid = config.processes[m_nProcess].units[order]; - if (uid < 0 || uid >= UNIT_NUM) return FALSE; - pUnit = &config.units[uid]; - if ((pUnit->state & 0x01) != TRUE) return FALSE; - for (i = 0; i < pUnit->yccount; i++) - { - oid = pUnit->ycs[i].order; - if (oid < 0 || oid >= DATABASE_YC_NUM) continue; - pUnit->ycs[i].qds = database.ycs[oid].qds; - if (pUnit->ycs[i].value != database.ycs[oid].value) - { //此处家里如极值判断,并入库 - if (pUnit->ycs[i].change_pos >= 0) - { - if (abs(pUnit->ycs[i].value - database.ycs[oid].value) >= pUnit->ycs[i].change_pos) - { //40码值变化量认为是遥测变位 - pUnit->ycs[i].value = database.ycs[oid].value; - pUnit->ycs[i].update_time = database.ycs[oid].update_time; - pUnit->ycs[i].ycbw = TRUE; - } - } - } - m_gdwFile.AddExtremumRecord(i, database.ycs[oid].value); - } - - return TRUE; -} - -BOOLEAN CSubGDW104Process::FetchUnitYM(int order) -{ - int i; - int uid; - int oid; - struUnit* pUnit; - - if (order < 0 || order >= PROCESS_UNIT_NUM) return FALSE; - uid = config.processes[m_nProcess].units[order]; - if (uid < 0 || uid >= UNIT_NUM) return FALSE; - pUnit = &config.units[uid]; - if ((pUnit->state & 0x01) != TRUE) return FALSE; - for (i = 0; i < pUnit->ymcount; i++) - { - oid = pUnit->yms[i].order; - if (oid < 0 || oid >= DATABASE_YM_NUM) continue; - if (pUnit->yms[i].value != database.yms[oid].value) - { - pUnit->yms[i].value = database.yms[oid].value; - pUnit->yms[i].update_time = database.yms[oid].update_time; - } - } - m_gdwFile.AddFmRecord(pUnit->yms, pUnit->ymcount); - - return TRUE; -} - - -BOOLEAN CSubGDW104Process::Run(void) -{ - if (!CIEC104Process::Run()) return FALSE; - int i, uid; - CIEC104ProcessItem* pItem; - FeedDog(); - for (i = 0; i < PROCESS_UNIT_NUM; i++) - { - pItem = (CIEC104ProcessItem *)GetItem(i); - if (NULL == pItem) continue; - uid = pItem->GetUnitID(); - if (uid < 0 || uid >= UNIT_NUM) continue; - if (pItem->interrogation_finish) - { - GetItemYXBWs(pItem); - } - //刷新事件记录库 - GetItemEvents(pItem); - //刷新遥测库 - FetchUnitYC(i); - //刷新遥脉库 - FetchUnitYM(i); - //总召唤结束,开始刷新遥测变位缓冲。 - if (pItem->interrogation_finish) - { //刷新遥测变位 - if (pItem->ycbws.count <= 0) - { //当遥测变位发送结束后才更新 - GetItemYCBWs(pItem); - } - } - } - return TRUE; -} - -BOOLEAN CSubGDW104Process::OnTimer(void) -{ - int uid; - int i; - int ret; - CIEC104ProcessItem *pItem; - BOOLEAN sec_changed = FALSE; - if (!CIEC104Process::OnTimer()) return FALSE; - //是否发生了秒变化 - if (last_sec != (time_t)system32.timers) - { - last_sec = system32.timers; - sec_changed = TRUE; - } - for (i = 0; i < PROCESS_UNIT_NUM; i++) - { - pItem = (CIEC104ProcessItem *)GetItem(i); - if (NULL == pItem) continue; - uid = pItem->GetUnitID(); - if (uid < 0 || uid >= UNIT_NUM) continue; - - if (pItem->GetSock() < 0) - { - continue; - } - pItem->apdu_t0_begin = system32.timers; - //判断t3超时 - if (pItem->apdu_t3_begin > 0 && system32.timers > (pItem->apdu_t3_begin + apdu_t3_max)) - { - if (!SendUFrame(FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, i)) - { - vLog(LOG_ERROR, "Unit(%d) SendUFrame error.\n", uid); - pItem->Release(); - continue; - } - pItem->apdu_t3_begin = 0; - //启动t1计时 - pItem->apdu_t1_begin = system32.timers; - pItem->apdu_wait_test = TRUE; - continue; - } - //判断t1超时 - if (pItem->apdu_t1_begin > 0 && system32.timers > (pItem->apdu_t1_begin + apdu_t1_max)) - { //直接复位链路 - vLog(LOG_ERROR, "Unit(%d) t1 expired (begin at %lu).\n", uid, pItem->apdu_t1_begin); - pItem->Release(); - continue; - } - //判断t2超时 - if (pItem->apdu_t2_begin > 0 && system32.timers > (pItem->apdu_t2_begin + apdu_t2_max)) - { //发送S帧 - if (!SendSFrame(i)) - { - vLog(LOG_ERROR, "Unit(%d) SendSFrame error.\n", uid); - pItem->Release(); - continue; - } - continue; - } - - //如果链路通信未启动则不发送任何报文 - if (!pItem->apdu_setup) continue; - //是否已经达到k值,若k值已经达到则不再发送数据报文 - if (pItem->apdu_k >= pItem->apdu_k_max) continue; - //总召唤没有结束,不响应遥控。不上送遥信变位及SOE - if (pItem->interrogation_finish) - { //发送遥控返校 - ret = MakeYKFrame(pItem, i); - if (ret < 0) - { - pItem->Release(); - continue; - } - else if (ret > 0) continue; - //发送遥调返校 - ret = MakeYTFrame(pItem, i); - if (ret < 0) - { - pItem->Release(); - continue; - } - else if (ret > 0) continue; - //发送遥信变位 - ret = Send_Single_point_information(pItem, i); - if (ret < 0) - { - pItem->Release(); - continue; - } - else if (ret > 0) continue; - //发送SOE信息 - ret = Send_Single_point_information_with_time_tag_cp56time2a(pItem, i); - if (ret < 0) - { - pItem->Release(); - continue; - } - else if (ret > 0) continue; - } - //响应总召唤命令 - if (pItem->interrogation_start) - { - if (pItem->interrogation_type != IEC_101_104_COT_INTERROGATION) - { //组召唤 - //激活终止 - ret = Send_FrameInterrogation(pItem, i); - if (ret < 0) - { - vLog(LOG_ERROR, "Unit(%d) Send_FrameInterrogation error.\n", uid); - pItem->Release(); - continue; - } - else if (ret > 0) - { - pItem->interrogation_type = 0; - pItem->interrogation_finish = TRUE; - pItem->interrogation_start = FALSE; - pItem->interrogation_yx_fin = TRUE; - pItem->interrogation_yc_fin = TRUE; - continue; - } - } - if (!pItem->interrogation_yx_fin) - { - ret = Send_Single_point_information(pItem, i, IEC_101_104_COT_INTERROGATION); - if (ret < 0) - { - vLog(LOG_ERROR, "Unit(%d) Send_Single_point_information IEC_101_104_COT_INTERROGATION error.\n", uid); - pItem->Release(); - continue; - } - else if (ret > 0) continue; - } - if (!pItem->interrogation_yc_fin) - { - switch (m_nOption.yc_type) - { - case USE_YC_NB: //标度化值 - ret = Send_Measured_value_scaled(pItem, i, IEC_101_104_COT_INTERROGATION); - break; - case USE_YC_NC: //短浮点数 - ret = Send_Measured_value_short_floating_point(pItem, i, IEC_101_104_COT_INTERROGATION); - break; - case USE_YC_ND: //不带品质归一化值 - ret = Send_Measured_value_normalised_without_quality(pItem, i, IEC_101_104_COT_INTERROGATION); - break; - default: //USE_YC_NA: 归一化值 - ret = Send_Measured_value_normalised(pItem, i, IEC_101_104_COT_INTERROGATION); - break; - } - if (ret < 0) - { - vLog(LOG_ERROR, "Unit(%d) Send_Measured_value IEC_101_104_COT_INTERROGATION error.\n", uid); - pItem->Release(); - continue; - } - else if (ret > 0) continue; - } - //激活终止 - ret = Send_FrameInterrogation(pItem, i); - if (ret < 0) - { - vLog(LOG_ERROR, "Unit(%d) Send_FrameInterrogation error.\n", uid); - pItem->Release(); - continue; - } - else if (ret > 0) - { - pItem->interrogation_type = 0; - pItem->interrogation_finish = TRUE; - pItem->interrogation_start = FALSE; - pItem->interrogation_yx_fin = TRUE; - pItem->interrogation_yc_fin = TRUE; - continue; - } - } - //响应召唤电能脉冲 - if (pItem->pulse_start) - { - if (!pItem->pulse_fin) - { - ret = Send_Integrated_totals(pItem, i, IEC_101_104_COT_REQCOGEN); - if (ret < 0) - { - vLog(LOG_ERROR, "Unit(%d) Send_Integrated_totals error.\n", uid); - pItem->Release(); - continue; - } - else if (ret > 0) continue; - } - //激活终止 - ret = Send_FrameCounterInterrogation(pItem, i); - if (ret < 0) - { - vLog(LOG_ERROR, "Unit(%d) Send_FrameCounterInterrogation error.\n", uid); - pItem->Release(); - continue; - } - else if (ret > 0) - { - pItem->pulse_type = 0; - pItem->pulse_start = FALSE; - pItem->pulse_fin = TRUE; - continue; - } - } - //文件 - ret = MakeFileFrame(pItem, i); - if (ret < 0) - { - pItem->Release(); - continue; - } - else if (ret > 0) - { - vLog(LOG_DEBUG, "here......MakeFileFrame.\n"); - continue; - } - //总召唤没有结束,不上送变位遥测 - if (pItem->interrogation_finish) - { //发送遥测变位 - if (sec_changed) - { - switch (m_nOption.yc_type) - { - case USE_YC_NB: //标度化值 - ret = Send_Measured_value_scaled(pItem, i); - break; - case USE_YC_NC: //短浮点数 - ret = Send_Measured_value_short_floating_point(pItem, i); - break; - case USE_YC_ND: //不带品质归一化值 - ret = Send_Measured_value_normalised_without_quality(pItem, i); - break; - default: //USE_YC_NA: 归一化值 - ret = Send_Measured_value_normalised(pItem, i); - break; - } - if (ret < 0) - { - vLog(LOG_ERROR, "Unit(%d) Send_Measured_value IEC_101_104_COT_SPONT error.\n", uid); - pItem->Release(); - continue; - } - else if (ret > 0) continue; - } - } - } - return TRUE; -} - -BOOLEAN CSubGDW104Process::OnIFrameReceived(WORD ns, WORD nr, BYTE* pBuf, int count, int ord) -{ - int uid; - CIEC104ProcessItem* pItem = (CIEC104ProcessItem *)GetItem(ord); - if (NULL == pItem) return FALSE; - uid = (int)pItem->GetUnitID(); - if (uid < 0 || uid >= UNIT_NUM) return FALSE; - //处理接收序号 - if (!OnDealWithPeerNS(pItem, ns)) return FALSE; - //处理发送序号 - if (!OnDealWithPeerNR(pItem, nr)) return FALSE; - //启动t2计时 - if (pItem->apdu_t2_begin == 0) - { - pItem->apdu_t2_begin = system32.timers; - } - - pItem->apdu_w++; - if (pItem->apdu_w >= pItem->apdu_w_max) - { - if (!SendSFrame(ord)) return FALSE; - } - //重置t3计时 - pItem->apdu_t3_begin = system32.timers; - //处理接收到的报文 - int ret; - int len; - BYTE buffer[256]; - BYTE* pData = pBuf; - BYTE TI; -// BYTE VSQ; - WORD COT; - BYTE cause_of_transmission; - - TI = *pData; pData++; - //VSQ = *pData; - pData++; - COT = GetCOT(pData); pData += cot_length; - //判断CA地址是否正确 - short apdu_addr = GetAsduAddr(pData); pData += asdu_addr_length; - if (apdu_addr != pItem->apdu_addr) - { - vLog(LOG_WARN, "Unit(%d) invalid CA(%d) received.\n", uid, apdu_addr); - return FALSE; - } - cause_of_transmission = GET_COT(COT); - len = 0; - memset(buffer, 0, sizeof(buffer)); - switch (TI) - { - case C_IC_NA_1: //总召唤命令 - ret = Receive_Interrogation_command(pItem, pData, cause_of_transmission, buffer, len); - if (NO_ERROR == ret) - { - pItem->interrogation_start = TRUE; - pItem->interrogation_yx_fin = FALSE; - pItem->interrogation_yc_fin = FALSE; - pItem->yx_pos = 0; - pItem->yc_pos = 0; - //清空原先YXBW库 - ClearUnitYXBW(uid); - } - break; - case C_SC_NA_1: //单点遥控命令.没有总召唤,不响应遥控报文 - if (!pItem->interrogation_finish) return TRUE; - ret = Receive_Single_command(pItem, pData, cause_of_transmission, buffer, len); - break; - case C_DC_NA_1: //双点遥控命令.没有总召唤,不响应遥控报文 - if (!pItem->interrogation_finish) return TRUE; - ret = Receive_Double_command(pItem, pData, cause_of_transmission, buffer, len); - break; - case C_CI_NA_1: //脉冲量召唤命令 - Receive_Counter_interrogation_command(pItem, pData,cause_of_transmission, buffer, len); - break; - case C_CS_NA_1: //时间同步命令 - Receive_Clock_synchronisation_command(pItem, pData, cause_of_transmission, buffer, len); - break; - case C_SE_NA_1: //设定命令,归一化值.没有总召唤,不响应设定报文 - if (!pItem->interrogation_finish) return TRUE; - Receive_Set_point_command_normalized(pItem, pData, cause_of_transmission, buffer, len); //设定规一化值命令 - break; - case C_SE_NB_1: //设定命令,标度化值.没有总召唤,不响应设定报文 - if (!pItem->interrogation_finish) return TRUE; - Receive_Set_point_command_scaled(pItem, pData, cause_of_transmission, buffer, len); //设定标度化值命令 - break; - case C_SE_NC_1: //设定命令,短浮点数.没有总召唤,不响应设定报文 - if (!pItem->interrogation_finish) return TRUE; - Receive_Set_point_command_short_floating(pItem, pData, cause_of_transmission, buffer, len); //设定短浮点值命令 - break; - case GDW_F_FR_NA_1: - Receive_FileTrans(pItem, pData, cause_of_transmission); - break; - default: - vLog(LOG_WARN, "Unit(%d) Unsupported I frame type = 0x%02x\n", uid, (int)pBuf[0]); - len = count; - memcpy(buffer, pBuf, count); - buffer[1] = 1; - SetCOT(&buffer[2], (IEC_101_104_COT_UNKNOWN_TI | IEC_101_104_COT_PN)); - } - if (len) - { - return SendIFrame(buffer, len, ord); - } - return TRUE; -} - -BOOLEAN CSubGDW104Process::OnUFrameReceived(BOOLEAN STARTDT_ACT, BOOLEAN STARTDT_CON, BOOLEAN STOPDT_ACT, BOOLEAN STOPDT_CON, BOOLEAN TESTFR_ACT, BOOLEAN TESTFR_CON, int ord) -{ - int uid; - BYTE phy_addr[6]; - - CIEC104ProcessItem* pItem = (CIEC104ProcessItem *)GetItem(ord); - if (NULL == pItem) return FALSE; - uid = (int)pItem->GetUnitID(); - if (uid < 0 || uid >= UNIT_NUM) return FALSE; - vLog(LOG_DEBUG, "Unit(%d) Received U Frame%s%s%s%s%s%s\n", - uid, - (STARTDT_ACT ? " STARTDT active": ""), - (STOPDT_ACT ? " STOPDT active": ""), - (TESTFR_ACT ? " TESTFR active": ""), - (STARTDT_CON ? " STARTDT confirm": ""), - (STOPDT_CON ? " STOPDT confirm": ""), - (TESTFR_CON ? " TESTFR confirm": "")); - if (STARTDT_ACT) - { - if (!SendUFrame(FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, ord)) return FALSE; - //链路链接建立 - if (!GetUnitAddr(uid, (BYTE *)phy_addr, 6)) - { - pItem->apdu_addr = 0x0001; - } - else - { - pItem->apdu_addr = ((phy_addr[5] << 8) | phy_addr[4]); - } - vLog(LOG_DEBUG, "Unit(%d) apdu_addr(%d)\n", uid, pItem->apdu_addr); - pItem->apdu_setup = TRUE; - pItem->apdu_ns = 0; - pItem->apdu_nr = 0; - pItem->apdu_ack = 0; - pItem->apdu_t3_begin = system32.timers; //启动t3计时 - pItem->apdu_wait_test = FALSE; - pItem->apdu_k = 0; - pItem->interrogation_start = FALSE; - pItem->interrogation_yx_fin = FALSE; - pItem->interrogation_yc_fin = FALSE; - - pItem->total_yx = GetUnitYXCount(uid); - vLog(LOG_DEBUG, "Unit(%d) total yx count is %d.\n", uid, pItem->total_yx); - pItem->total_yc = GetUnitYCCount(uid); - vLog(LOG_DEBUG, "Unit(%d) total yc count is %d.\n", uid, pItem->total_yc); - pItem->total_ym = GetUnitYMCount(uid); - vLog(LOG_DEBUG, "Unit(%d) total ym count is %d.\n", uid, pItem->total_ym); - - pItem->yx_pos = 0; - pItem->yc_pos = 0; - pItem->ym_pos = 0; - //初始化结束帧 - if (!pItem->end_of_initialisation) - { - pItem->end_of_initialisation = TRUE; - if (!Send_End_of_initialisation(pItem, ord)) return FALSE; - } - } - if (STARTDT_CON) - { - vLog(LOG_WARN, "UNSUPPORT STARTDT CONFIRM! Disconnect link!\n"); - pItem->Release(); - return FALSE; - } - if (STOPDT_ACT) - { - vLog(LOG_WARN, "UNSUPPORT STOPDT COMMAND! Disconnect link!\n"); - pItem->Release(); - return FALSE; - } - if (STOPDT_CON) - { - vLog(LOG_WARN, "UNSUPPORT STOPDT CONFIRM! Disconnect link!\n"); - pItem->Release(); - return FALSE; - } - if (TESTFR_ACT) - { - if (!SendUFrame(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, ord)) - { - vLog(LOG_WARN, "Send U Frame Error.\n"); - pItem->Release(); - return FALSE; - } - pItem->apdu_t1_begin = 0; - pItem->apdu_t3_begin = system32.timers; //重置t3计时 - } - if (TESTFR_CON) - { - if (pItem->apdu_wait_test) - { - pItem->apdu_t1_begin = 0; - pItem->apdu_t3_begin = system32.timers; //重置t3计时 - pItem->apdu_wait_test = FALSE; - } - else - { - vLog(LOG_WARN, "UNSUPPORT TESTFR CONFIRM! Disconnect link!\n"); - pItem->Release(); - return FALSE; - } - } - return TRUE; -} - -int CSubGDW104Process::MakeYKFrame(CIEC104ProcessItem* pItem, int ord) -{ - BYTE buffer[32]; - if (NULL == pItem) return -1; - - int order; - BYTE value, action, result; - - if (!GetUnitYK(pItem->GetUnitID(), order, value, action, result)) - { - return 0; - } - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is %s result is %s\n", pItem->GetUnitID(), order, (value ? "CLOSE" : "TRIP"), val_to_str(action, yk_state, "STATE=%d"), val_to_str(result, yk_result, "RESULT=%d")); - memset(buffer, 0, sizeof(buffer)); - if (YKS_SELED == action && YKR_FAIL == result) - { - buffer[2 + cot_length + asdu_addr_length + info_addr_length] |= IEC_101_104_SE; - action = YKS_ABRED; - } - else if (YKS_SELREQ == action && YKR_OVER == result) - { - buffer[2 + cot_length + asdu_addr_length + info_addr_length] |= IEC_101_104_SE; - action = YKS_ABRED; - } - else if (YKS_SELING == action && YKR_OVER == result) - { - buffer[2 + cot_length + asdu_addr_length + info_addr_length] |= IEC_101_104_SE; - action = YKS_ABRED; - } - BYTE* param; - BOOLEAN yk_type; - //BYTE relay_type; - DWORD ioa; - param = GetUnitYKParamByPoint(pItem->GetUnitID(), order); - ioa = MAKEDWORD(MAKEWORD(param[0], param[1]), MAKEWORD(param[2], param[3])); - yk_type = param[4]; - //relay_type = param[5]; - if (yk_type == USE_YK_DC || yk_type == USE_YK_DEF) - { //双点遥控 - buffer[0] = C_DC_NA_1; - buffer[2 + cot_length + asdu_addr_length + info_addr_length] |= value ? DCO_ON : DCO_OFF; - } - else - { - buffer[0] = C_SC_NA_1; - buffer[2 + cot_length + asdu_addr_length + info_addr_length] |= value ? SCO_ON : SCO_OFF; - } - buffer[1] = 1; - if (YKS_SELED == action) - { - buffer[2 + cot_length + asdu_addr_length + info_addr_length] |= IEC_101_104_SE; - SetCOT(&buffer[2], IEC_101_104_COT_ACTCON); - m_gdwFile.PushYKLog(system32.now, ioa, value, YKT_SELRET, YKS_PROC, pItem->GetUnitID()); - } - else if (YKS_ABRED == action) - { - SetCOT(&buffer[2], IEC_101_104_COT_DEACTCON); - } - else if (YKS_EXEED == action) - { - SetCOT(&buffer[2], IEC_101_104_COT_ACTTREM); - m_gdwFile.PushYKLog(system32.now, ioa, value, YKT_EXERET, YKS_PROC, pItem->GetUnitID()); - } - else - { - return 0; - } - SetAsduAddr(&buffer[2 + cot_length], pItem->apdu_addr); - SetInformationAddr(&buffer[2 + cot_length + asdu_addr_length], ioa); - if (!SendIFrame(buffer, (3 + cot_length + asdu_addr_length + info_addr_length), ord)) return -1; - - return 1; -} - -int CSubGDW104Process::MakeYTFrame(CIEC104ProcessItem* pItem, int ord) -{ - BYTE buffer[32]; - if (NULL == pItem) return -1; - - int order; - BYTE action, result; - DWORD value; - - if (!GetUnitYT(pItem->GetUnitID(), order, value, action, result)) - { - return 0; - } - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is %s result is %s\n", pItem->GetUnitID(), order, value, val_to_str(action, yt_state, "STATE=%d"), val_to_str(result, yt_result, "RESULT=%d")); - memset(buffer, 0, sizeof(buffer)); - BYTE* param; - BOOLEAN yt_type; - DWORD ioa; - int data_length = 2; - param = GetUnitYTParamByPoint(pItem->GetUnitID(), order); - ioa = MAKEDWORD(MAKEWORD(param[0], param[1]), MAKEWORD(param[2], param[3])); - yt_type = param[4]; - if (yt_type == USE_YT_NA) - { //双点遥控 - data_length = 2; - buffer[0] = C_SE_NA_1; - buffer[2 + cot_length + asdu_addr_length + info_addr_length] = value & 0xff; - buffer[2 + cot_length + asdu_addr_length + info_addr_length + 1] = (value >> 8) & 0xff; - } - else if (yt_type == USE_YT_NB) - { - data_length = 2; - buffer[0] = C_SE_NB_1; - buffer[2 + cot_length + asdu_addr_length + info_addr_length] = value & 0xff; - buffer[2 + cot_length + asdu_addr_length + info_addr_length + 1] = (value >> 8) & 0xff; - } - else - { - data_length = 4; - buffer[0] = C_SE_NC_1; - buffer[2 + cot_length + asdu_addr_length + info_addr_length] = value & 0xff; - buffer[2 + cot_length + asdu_addr_length + info_addr_length + 1] = (value >> 8) & 0xff; - buffer[2 + cot_length + asdu_addr_length + info_addr_length + 2] = (value >> 16) & 0xff; - buffer[2 + cot_length + asdu_addr_length + info_addr_length + 3] = (value >> 24) & 0xff; - } - buffer[1] = 1; - if (YTS_SELED == action && YTR_FAIL == result) - { - buffer[2 + cot_length + asdu_addr_length + info_addr_length + data_length] |= IEC_101_104_SE; - action = YTS_ABRED; - } - else if (YTS_SELREQ == action && YTR_OVER == result) - { - buffer[2 + cot_length + asdu_addr_length + info_addr_length + data_length] |= IEC_101_104_SE; - action = YTS_ABRED; - } - else if (YTS_SELING == action && YTR_OVER == result) - { - buffer[2 + cot_length + asdu_addr_length + info_addr_length + data_length] |= IEC_101_104_SE; - action = YTS_ABRED; - } - - if (YTS_SELED == action) - { - buffer[2 + cot_length + asdu_addr_length + info_addr_length + data_length] |= IEC_101_104_SE; - SetCOT(&buffer[2], IEC_101_104_COT_ACTCON); - } - else if (YTS_ABRED == action) - { - SetCOT(&buffer[2], IEC_101_104_COT_DEACTCON); - } - else if (YTS_EXEED == action) - { - SetCOT(&buffer[2], IEC_101_104_COT_ACTTREM); - } - else - { - return FALSE; - } - SetAsduAddr(&buffer[2 + cot_length], pItem->apdu_addr); - SetInformationAddr(&buffer[2 + cot_length + asdu_addr_length], ioa); - if (!SendIFrame(buffer, (3 + cot_length + asdu_addr_length + info_addr_length + data_length), ord)) return -1; - - return 1; -} - -int CSubGDW104Process::MakeFileFrame(CIEC104ProcessItem* pItem, int ord) -{ - //BYTE buffer[256]; - if (NULL == pItem) return -1; - - //文件上送判断 - m_dwFileType = m_gdwFile.getCMD(); - if (m_dwFileType) - { - if ((m_dwFileType & FIOCMD_VALID) == FIOCMD_READ_DIR) - { - return Send_CallFileDir_Confirm(pItem, m_dwFileType, ord); - } - else if ((m_dwFileType & FIOCMD_VALID) == FIOCMD_OPEN_FILE) - { - return Send_CallFileSel_Confirm(pItem, m_dwFileType, ord); - } - else if ((m_dwFileType & FIOCMD_VALID) == FIOCMD_READ_FILE) - { - return Send_CallFileDat_Ack(pItem, m_dwFileType, ord); - } - } - return 0; -} - -int CSubGDW104Process::Receive_Single_command(CIEC104ProcessItem* pItem, const BYTE* pBuf, BYTE cause_of_transmission, BYTE* pTarget, int& count) //单点令 -{ - BYTE* pData = (BYTE*)pBuf; - BYTE command; - int uid, point; - DWORD information_address; - BOOLEAN value; - BYTE SE; - - if (NULL == pItem) return ERROR_UNKNOWN; - - information_address = GetInformationAddr(pData); pData += info_addr_length; - command = *pData; - - pTarget[0] = C_SC_NA_1; - pTarget[1] = 1; - SetAsduAddr(&pTarget[2 + cot_length], pItem->apdu_addr); - SetInformationAddr(&pTarget[2 + cot_length + asdu_addr_length], information_address); - pTarget[2 + cot_length + asdu_addr_length + info_addr_length] = command; - count = 3 + cot_length + asdu_addr_length + info_addr_length; - if (IEC_101_104_COT_ACT == cause_of_transmission || IEC_101_104_COT_DEACT == cause_of_transmission) - { - uid = pItem->GetUnitID(); - BYTE ioa[4]; - ioa[0] = information_address & 0xff; - ioa[1] = (information_address >> 8) & 0xff; - ioa[2] = (information_address >> 16) & 0xff; - ioa[3] = (information_address >> 24) & 0xff; - - point = GetUnitYKPointByParam(uid, ioa, 4); - if (point < 0) - { //信息体地址错误 - SetCOT(&pTarget[2], IEC_101_104_COT_UNKNOWN_INFO); - return ERROR_INFORMATION_ADDRESS; - } - SE = GET_SE(command); - value = GET_SCO(command); pData++; - //判断该点是否为单点遥控及参数状态 - BYTE* param; - BOOLEAN yk_type; - BYTE relay_type; - param = GetUnitYKParamByPoint(uid, point); - yk_type = param[4]; - relay_type = param[5]; - if (yk_type != USE_YK_SC) - { //遥控类型错误,返回否定确认 - SetCOT(&pTarget[2], ((cause_of_transmission + 1) | IEC_101_104_COT_PN)); - return ERROR_PARAM; - } - if (relay_type) - { - if (relay_type == 1) - { //Only on - if (!value) - { - vLog(LOG_ERROR, "Only on,Cann't off!\n"); - SetCOT(&pTarget[2], ((cause_of_transmission + 1) | IEC_101_104_COT_PN)); - return ERROR_PARAM; - } - } - else - { //Only off - if (value) - { - vLog(LOG_ERROR, "Only off,Cann't on!\n"); - SetCOT(&pTarget[2], ((cause_of_transmission + 1) | IEC_101_104_COT_PN)); - return ERROR_PARAM; - } - } - } - if (IEC_101_104_COT_ACT == cause_of_transmission) - { //激活 - if (SE) - { //选择 - count = 0; - SetUnitYK(uid, point, value, YKS_SELREQ, YKR_IDLE); - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is YKS_SELREQ result is YKR_IDLE.\n", uid, point, (value ? "CLOSE" : "TRIP")); - m_gdwFile.PushYKLog(system32.now, information_address, value, YKT_SELREQ, YKS_PROC, uid); - return NO_ERROR; - } - else - { //执行 - SetUnitYK(uid, point, value, YKS_EXEREQ, YKR_IDLE); - SetCOT(&pTarget[2], IEC_101_104_COT_ACTCON); - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is YKS_EXEREQ result is YKR_IDLE.\n", uid, point, (value ? "CLOSE" : "TRIP")); - m_gdwFile.PushYKLog(system32.now, information_address, value, YKT_EXEREQ, YKS_PROC, uid); - return NO_ERROR; - } - } - else if (IEC_101_104_COT_DEACT == cause_of_transmission) - { //激活终止 - SetUnitYK(uid, point, value, YKS_ABRREQ, YKR_IDLE); - SetCOT(&pTarget[2], IEC_101_104_COT_DEACTCON); - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is YKS_ABRREQ result is YKR_IDLE.\n", uid, point, (value ? "CLOSE" : "TRIP")); - m_gdwFile.PushYKLog(system32.now, information_address, value, YKT_ABRREQ, YKS_PROC, uid); - return NO_ERROR; - } - } - SetCOT(&pTarget[2], IEC_101_104_COT_UNKNOWN_COT); - return ERROR_CAUSE_OF_TRANSMISSION; -} - -int CSubGDW104Process::Receive_Double_command(CIEC104ProcessItem* pItem, const BYTE* pBuf, BYTE cause_of_transmission, BYTE* pTarget, int& count) //单点令 -{ - BYTE* pData = (BYTE*)pBuf; - BYTE command; - int uid, point; - DWORD information_address; - BOOLEAN value; - BYTE SE; - if (NULL == pItem) return ERROR_UNKNOWN; - information_address = GetInformationAddr(pData); pData += info_addr_length; - command = *pData; - - pTarget[0] = C_DC_NA_1; - pTarget[1] = 1; - SetAsduAddr(&pTarget[2 + cot_length], pItem->apdu_addr); - SetInformationAddr(&pTarget[2 + cot_length + asdu_addr_length], information_address); - pTarget[2 + cot_length + asdu_addr_length + info_addr_length] = command; - count = 3 + cot_length + asdu_addr_length + info_addr_length; - if (IEC_101_104_COT_ACT == cause_of_transmission || IEC_101_104_COT_DEACT == cause_of_transmission) - { - uid = pItem->GetUnitID(); - BYTE ioa[4]; - - ioa[0] = information_address & 0xff; - ioa[1] = (information_address >> 8) & 0xff; - ioa[2] = (information_address >> 16) & 0xff; - ioa[3] = (information_address >> 24) & 0xff; - - point = GetUnitYKPointByParam(uid, ioa, 4); - if (point < 0) - { - SetCOT(&pTarget[2], IEC_101_104_COT_UNKNOWN_INFO); - count = 3 + cot_length + asdu_addr_length + info_addr_length; - return ERROR_INFORMATION_ADDRESS; - } - SE = GET_SE(command); - value = GET_DCO(command); pData++; - //判断该点是否为单点遥控及参数状态 - BYTE* param; - BOOLEAN yk_type; - //BYTE relay_type; - param = GetUnitYKParamByPoint(uid, point); - yk_type = param[4]; - //relay_type = param[5]; - if (yk_type == USE_YK_SC) - { //遥控类型错误,返回否定确认 - SetCOT(&pTarget[2], ((cause_of_transmission + 1) | IEC_101_104_COT_PN)); - return ERROR_PARAM; - } - if (IEC_101_104_COT_ACT == cause_of_transmission) - { //激活 - if (SE) - { //选择 - count = 0; - SetUnitYK(uid, point, value, YKS_SELREQ, YKR_IDLE); - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is YKS_SELREQ result is YKR_IDLE.\n", uid, point, (value ? "CLOSE" : "TRIP")); - m_gdwFile.PushYKLog(system32.now, information_address, value, YKT_SELREQ, YKS_PROC, uid); - return NO_ERROR; - } - else - { //执行 - SetUnitYK(uid, point, value, YKS_EXEREQ, YKR_IDLE); - SetCOT(&pTarget[2], IEC_101_104_COT_ACTCON); - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is YKS_EXEREQ result is YKR_IDLE.\n", uid, point, (value ? "CLOSE" : "TRIP")); - m_gdwFile.PushYKLog(system32.now, information_address, value, YKT_EXEREQ, YKS_PROC, uid); - return NO_ERROR; - } - } - else if (IEC_101_104_COT_DEACT == cause_of_transmission) - { //激活终止 - SetUnitYK(uid, point, value, YKS_ABRREQ, YKR_IDLE); - SetCOT(&pTarget[2], IEC_101_104_COT_DEACTCON); - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is YKS_ABRREQ result is YKR_IDLE.\n", uid, point, (value ? "CLOSE" : "TRIP")); - m_gdwFile.PushYKLog(system32.now, information_address, value, YKT_ABRREQ, YKS_PROC, uid); - return NO_ERROR; - } - } - SetCOT(&pTarget[2], IEC_101_104_COT_UNKNOWN_COT); - return ERROR_CAUSE_OF_TRANSMISSION; -} - - -int CSubGDW104Process::Receive_Set_point_command_normalized(CIEC104ProcessItem* pItem, const BYTE* pBuf, BYTE cause_of_transmission, BYTE* pTarget, int& count) //设定规一化值命令 -{ - BYTE* pData = (BYTE*)pBuf; - BYTE command; - int uid, point; - int information_address; - WORD value = 0; - BYTE SE; - - if (NULL == pItem) return ERROR_UNKNOWN; - information_address = GetInformationAddr(pData); - pData += info_addr_length; - value = (WORD)(pData[0] | pData[1] << 8); - pData += 2; - command = *pData; - - pTarget[0] = C_SE_NA_1; - pTarget[1] = 1; - SetAsduAddr(&pTarget[2 + cot_length], pItem->apdu_addr); - SetInformationAddr(&pTarget[2 + cot_length + asdu_addr_length], information_address); - pTarget[2 + cot_length + asdu_addr_length + info_addr_length] = value & 0xff; - pTarget[2 + cot_length + asdu_addr_length + info_addr_length + 1] = (value >> 8) & 0xff; - pTarget[2 + cot_length + asdu_addr_length + info_addr_length + 2] = command; - count = 3 + cot_length + asdu_addr_length + info_addr_length + 2; - if (IEC_101_104_COT_ACT == cause_of_transmission || IEC_101_104_COT_DEACT == cause_of_transmission) - { - uid = pItem->GetUnitID(); - BYTE ioa[4]; - ioa[0] = information_address & 0xff; - ioa[1] = (information_address >> 8) & 0xff; - ioa[2] = (information_address >> 16) & 0xff; - ioa[3] = (information_address >> 24) & 0xff; - point = GetUnitYTPointByParam(uid, ioa, 4); - if (point < 0) - { - SetCOT(&pTarget[2], IEC_101_104_COT_UNKNOWN_INFO); - count = 3 + cot_length + asdu_addr_length + info_addr_length + 2; - return ERROR_INFORMATION_ADDRESS; - } - SE = GET_SE(command); - //判断该点是否为单点遥控及参数状态 - BYTE* param; - BOOLEAN yt_type; - param = GetUnitYTParamByPoint(pItem->GetUnitID(), point); - yt_type = param[4]; - if (yt_type != USE_YT_NA) - { //遥控类型错误,返回否定确认 - SetCOT(&pTarget[2], ((cause_of_transmission + 1) | IEC_101_104_COT_PN)); - return ERROR_PARAM; - } - if (IEC_101_104_COT_ACT == cause_of_transmission) - { //激活 - if (SE) - { //选择 - count = 0; - SetUnitYT(uid, point, value, YTS_SELREQ, YTR_IDLE); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_SELREQ result is YTR_IDLE.\n", uid, point, value); - return NO_ERROR; - } - else - { //执行 - SetUnitYT(uid, point, value, YTS_EXEREQ, YTR_IDLE); - SetCOT(&pTarget[2], IEC_101_104_COT_ACTCON); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_EXEREQ result is YTR_IDLE.\n", uid, point, value); - return NO_ERROR; - } - } - else if (IEC_101_104_COT_DEACT == cause_of_transmission) - { //激活终止 - SetUnitYT(uid, point, value, YTS_ABRREQ, YTR_IDLE); - SetCOT(&pTarget[2], IEC_101_104_COT_DEACTCON); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_ABRREQ result is YTR_IDLE.\n", uid, point, value); - return NO_ERROR; - } - } - SetCOT(&pTarget[2], IEC_101_104_COT_UNKNOWN_COT); - return ERROR_CAUSE_OF_TRANSMISSION; -} - -int CSubGDW104Process::Receive_Set_point_command_scaled(CIEC104ProcessItem* pItem, const BYTE* pBuf, BYTE cause_of_transmission, BYTE* pTarget, int& count) //设定标度化值命令 -{ - BYTE* pData = (BYTE*)pBuf; - BYTE command; - int uid, point; - int information_address; - WORD value = 0; - BYTE SE; - - if (NULL == pItem) return ERROR_UNKNOWN; - information_address = GetInformationAddr(pData); - pData += info_addr_length; - value = (WORD)(pData[0] | pData[1] << 8); - pData += 2; - command = *pData; - - pTarget[0] = C_SE_NB_1; - pTarget[1] = 1; - SetAsduAddr(&pTarget[2 + cot_length], pItem->apdu_addr); - SetInformationAddr(&pTarget[2 + cot_length + asdu_addr_length], information_address); - pTarget[2 + cot_length + asdu_addr_length + info_addr_length] = value & 0xff; - pTarget[2 + cot_length + asdu_addr_length + info_addr_length + 1] = (value >> 8) & 0xff; - pTarget[2 + cot_length + asdu_addr_length + info_addr_length + 2] = command; - count = 3 + cot_length + asdu_addr_length + info_addr_length + 2; - if (IEC_101_104_COT_ACT == cause_of_transmission || IEC_101_104_COT_DEACT == cause_of_transmission) - { - uid = pItem->GetUnitID(); - BYTE ioa[4]; - ioa[0] = information_address & 0xff; - ioa[1] = (information_address >> 8) & 0xff; - ioa[2] = (information_address >> 16) & 0xff; - ioa[3] = (information_address >> 24) & 0xff; - point = GetUnitYTPointByParam(uid, ioa, 4); - if (point < 0) - { - SetCOT(&pTarget[2], IEC_101_104_COT_UNKNOWN_INFO); - count = 3 + cot_length + asdu_addr_length + info_addr_length + 2; - return ERROR_INFORMATION_ADDRESS; - } - SE = GET_SE(command); - //判断该点是否为单点遥控及参数状态 - BYTE* param; - BOOLEAN yt_type; - param = GetUnitYTParamByPoint(pItem->GetUnitID(), point); - yt_type = param[4]; - if (yt_type != USE_YT_NB) - { //遥控类型错误,返回否定确认 - SetCOT(&pTarget[2], ((cause_of_transmission + 1) | IEC_101_104_COT_PN)); - return ERROR_PARAM; - } - if (IEC_101_104_COT_ACT == cause_of_transmission) - { //激活 - if (SE) - { //选择 - count = 0; - SetUnitYT(uid, point, value, YTS_SELREQ, YTR_IDLE); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_SELREQ result is YTR_IDLE.\n", uid, point, value); - return NO_ERROR; - } - else - { //执行 - SetUnitYT(uid, point, value, YTS_EXEREQ, YTR_IDLE); - SetCOT(&pTarget[2], IEC_101_104_COT_ACTCON); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_EXEREQ result is YTR_IDLE.\n", uid, point, value); - return NO_ERROR; - } - } - else if (IEC_101_104_COT_DEACT == cause_of_transmission) - { //激活终止 - SetUnitYT(uid, point, value, YTS_ABRREQ, YTR_IDLE); - SetCOT(&pTarget[2], IEC_101_104_COT_DEACTCON); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_ABRREQ result is YTR_IDLE.\n", uid, point, value); - return NO_ERROR; - } - } - SetCOT(&pTarget[2], IEC_101_104_COT_UNKNOWN_COT); - return ERROR_CAUSE_OF_TRANSMISSION; -} - -int CSubGDW104Process::Receive_Set_point_command_short_floating(CIEC104ProcessItem* pItem, const BYTE* pBuf, BYTE cause_of_transmission, BYTE* pTarget, int& count) //设定短浮点值命令 -{ - BYTE* pData = (BYTE*)pBuf; - BYTE command; - int uid, point; - int information_address; - DWORD value; - BYTE SE; - - if (NULL == pItem) return ERROR_UNKNOWN; - information_address = GetInformationAddr(pData); - pData += info_addr_length; - value = (DWORD)(pData[0] | (pData[1] << 8) | (pData[2] << 16) | (pData[3] << 24)); - pData += 4; - - command = *pData; - - pTarget[0] = C_SE_NC_1; - pTarget[1] = 1; - SetAsduAddr(&pTarget[2 + cot_length], pItem->apdu_addr); - SetInformationAddr(&pTarget[2 + cot_length + asdu_addr_length], information_address); - pTarget[2 + cot_length + asdu_addr_length + info_addr_length] = value & 0xff; - pTarget[2 + cot_length + asdu_addr_length + info_addr_length + 1] = (value >> 8) & 0xff; - pTarget[2 + cot_length + asdu_addr_length + info_addr_length + 2] = (value >> 16) & 0xff; - pTarget[2 + cot_length + asdu_addr_length + info_addr_length + 3] = (value >> 24) & 0xff; - pTarget[2 + cot_length + asdu_addr_length + info_addr_length + 4] = command; - count = 3 + cot_length + asdu_addr_length + info_addr_length + 4; - if (IEC_101_104_COT_ACT == cause_of_transmission || IEC_101_104_COT_DEACT == cause_of_transmission) - { - uid = pItem->GetUnitID(); - BYTE ioa[4]; - ioa[0] = information_address & 0xff; - ioa[1] = (information_address >> 8) & 0xff; - ioa[2] = (information_address >> 16) & 0xff; - ioa[3] = (information_address >> 24) & 0xff; - point = GetUnitYTPointByParam(uid, ioa, 4); - if (point < 0) - { - SetCOT(&pTarget[2], IEC_101_104_COT_UNKNOWN_INFO); - count = 3 + cot_length + asdu_addr_length + info_addr_length + 4; - return ERROR_INFORMATION_ADDRESS; - } - SE = GET_SE(command); - //判断该点是否为单点遥控及参数状态 - BYTE* param; - BOOLEAN yt_type; - param = GetUnitYTParamByPoint(pItem->GetUnitID(), point); - yt_type = param[4]; - if (yt_type != USE_YT_NC) - { //遥控类型错误,返回否定确认 - SetCOT(&pTarget[2], ((cause_of_transmission + 1) | IEC_101_104_COT_PN)); - return ERROR_PARAM; - } - if (IEC_101_104_COT_ACT == cause_of_transmission) - { //激活 - if (SE) - { //选择 - count = 0; - SetUnitYT(uid, point, value, YTS_SELREQ, YTR_IDLE); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_SELREQ result is YTR_IDLE.\n", uid, point, value); - return NO_ERROR; - } - else - { //执行 - SetUnitYT(uid, point, value, YTS_EXEREQ, YTR_IDLE); - SetCOT(&pTarget[2], IEC_101_104_COT_ACTCON); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_EXEREQ result is YTR_IDLE.\n", uid, point, value); - return NO_ERROR; - } - } - else if (IEC_101_104_COT_DEACT == cause_of_transmission) - { //激活终止 - SetUnitYT(uid, point, value, YTS_ABRREQ, YTR_IDLE); - SetCOT(&pTarget[2], IEC_101_104_COT_DEACTCON); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_ABRREQ result is YTR_IDLE.\n", uid, point, value); - return NO_ERROR; - } - } - SetCOT(&pTarget[2], IEC_101_104_COT_UNKNOWN_COT); - return ERROR_CAUSE_OF_TRANSMISSION; -} - -int CSubGDW104Process::Receive_FileTrans(CIEC104ProcessItem* pItem, const BYTE* pBuf, BYTE cause_of_transmission) //读取文件 -{ - BYTE* pData = (BYTE*)pBuf; - - if (NULL == pItem) return ERROR_UNKNOWN; - - int information_address = GetInformationAddr(pData); pData += info_addr_length; - if (information_address != 0) return ERROR_CAUSE_OF_TRANSMISSION; - BYTE frameType = *pData; pData++; - if (frameType != FILE_TRS_TYPE) return ERROR_UNKNOWN; - BYTE command = *pData; pData++; - if (command == ReadFileDirAct) - { - return parseFileReadDirAct(pItem, pData); - } - else if (command == ReadFileSelAct) - { - return parseFileReadFileSelAct(pItem, pData); - } - else if (command == ReadFileDataCon) - { - return parseFileReadFileDataCon(pItem, pData); - } - else if (command == WriteFileSelAct) - { - - } - else if (command == WriteFileDataAct) - { - - } - else - { - vLog(LOG_ERROR, "文件传输报文错误,不识别的操作标识 = %d.\n", command); - } - return ERROR_UNKNOWN; -} - -BOOLEAN CSubGDW104Process::parseFileReadDirAct(CIEC104ProcessItem* pItem, const BYTE* pData) -{ - DWORD dirID = (DWORD)(pData[0] | (pData[1] << 8) | (pData[2] << 16) | (pData[3] << 24)); pData += 4; - BYTE dirNameLength = *pData; pData++; - char dirName[FILE_PATH_LEN]; - memset(dirName, '\0', sizeof(dirName)); - if (dirNameLength > 0) - { - memcpy(dirName, pData, dirNameLength); - pData += dirNameLength; - } - BYTE callFlag = *pData; pData++; - BOOLEAN callAllFiles = (callFlag == 0) ? TRUE : FALSE; - unionCP56Time startTime; - memcpy(&startTime, &system32.now, sizeof(startTime)); - unionCP56Time endTime; - memcpy(&endTime, &system32.now, sizeof(endTime)); - if (!callAllFiles) - { - startTime.millisecond = *pData; pData++; - startTime.millisecond |= (*pData << 8); pData++; - startTime.minute = *pData & 0x3f; - startTime.IV = (*pData & 0x80) == 0x80 ? TRUE : FALSE; pData++; - startTime.hour = *pData & 0x1f; - startTime.SU = (*pData & 0x80) == 0x80 ? TRUE : FALSE; pData++; - startTime.dayofmonth = *pData & 0x1f; - startTime.dayofweek = ((*pData & 0xe0) >> 5); pData++; - startTime.month = *pData & 0x0f; pData++; - startTime.year = *pData & 0x7f; pData++; - - endTime.millisecond = *pData; pData++; - endTime.millisecond |= (*pData << 8); pData++; - endTime.minute = *pData & 0x3f; - endTime.IV = (*pData & 0x80) == 0x80 ? TRUE : FALSE; pData++; - endTime.hour = *pData & 0x1f; - endTime.SU = (*pData & 0x80) == 0x80 ? TRUE : FALSE; pData++; - endTime.dayofmonth = *pData & 0x1f; - endTime.dayofweek = ((*pData & 0xe0) >> 5); pData++; - endTime.month = *pData & 0x0f; pData++; - endTime.year = *pData & 0x7f; pData++; - } - - //判断文件目录 - memset(&m_FileDir, 0, sizeof(stCallFileDir)); - m_FileDir.allfile = callAllFiles; - strcpy(m_FileDir.dirname, dirName); - m_FileDir.loadptr = 0; - m_FileDir.dirID = dirID; - - m_gdwFile.ReadDir(dirName, callAllFiles, startTime, endTime); - return TRUE; -} - -BOOLEAN CSubGDW104Process::parseFileReadFileSelAct(CIEC104ProcessItem* pItem, const BYTE* pData) -{ - int fileNameLen = 0; - fileNameLen = *pData; pData++; - if (fileNameLen <= 0) - { - vLog(LOG_ERROR, "文件名长度错误,文件名长度 = %d\n", fileNameLen); - return FALSE; - } - char fileName[FILE_PATH_LEN]; - memset(fileName, '\0', sizeof(fileName)); - memcpy(fileName, pData, fileNameLen); pData += fileNameLen; - - strcpy(m_FileDir.filename, fileName); - m_FileDir.length = m_gdwFile.FileLength(fileName); - m_gdwFile.OpenFile(fileName); - return TRUE; -} - -BOOLEAN CSubGDW104Process::parseFileReadFileDataCon(CIEC104ProcessItem* pItem, const BYTE* pData) -{ - LONG fileID = (DWORD)(pData[0] | (pData[1] << 8) | (pData[2] << 16) | (pData[3] << 24)); pData += 4; - LONG filePos = (DWORD)(pData[0] | (pData[1] << 8) | (pData[2] << 16) | (pData[3] << 24)); pData += 4; - vLog(LOG_DEBUG, "收到文件ID = %d 传输确认,数据段号 = %d, 原始文件应有长度 = %d\n", fileID, filePos, m_FileDir.length); - m_gdwFile.CloseFile(); - return FALSE; -} - -int CSubGDW104Process::Send_FileDir(CIEC104ProcessItem* pItem, BOOLEAN bErr, BOOLEAN follow, int count, int pos, int ord) -{ - int len = 0; - BYTE buffer[1024]; - if (pItem == NULL) return -1; - - buffer[len++] = GDW_F_FR_NA_1; - buffer[len++] = 0; //VSQ此处无效 - SetCOT(&buffer[len], IEC_101_104_COT_ACTCON); len += cot_length; - SetAsduAddr(&buffer[len], pItem->apdu_addr); len += asdu_addr_length; - SetInformationAddr(&buffer[len], 0); len += info_addr_length; - - buffer[len++] = FILE_TRS_TYPE; //文件传输 - buffer[len++] = ReadFileDirCon; //读目录 - - if (bErr) - { - buffer[len++] = 1; - if (!SendIFrame(buffer, len, ord)) return -1; - return 1; - } - //结果描述字 - buffer[len++] = 0; //成功 - //目录ID - buffer[len++] = (m_FileDir.dirID & 0xff); - buffer[len++] = ((m_FileDir.dirID >> 8) & 0xff); - buffer[len++] = ((m_FileDir.dirID >> 16) & 0xff); - buffer[len++] = ((m_FileDir.dirID >> 24) & 0xff); - buffer[len++] = follow; //无后续 - buffer[len++] = count; //文件数量 - for (int i = 0; i < count; i++) - { - std::string filename = m_gdwFile.FileName(i + pos); - //名称长度 - buffer[len++] = filename.length(); - //文件名称 - for (int j = 0; j < (int)filename.length(); j ++) - { - buffer[len++] = filename[j]; - } - //文件属性 - buffer[len++] = 0; - //文件大小 - len += ValToBuf(&buffer[len], m_gdwFile.FileLength(i + pos), 4); - //文件时间 - unionCP56Time ct; - ct = Time_ttounionCP56Time(m_gdwFile.FileTime(i + pos)); - len += unionCP56TimeToBuf(&buffer[len], ct); - } - if (!SendIFrame(buffer, len, ord)) return -1; - return 1; -} - -int CSubGDW104Process::Send_CallFileDir_Confirm(CIEC104ProcessItem* pItem, DWORD cmd, int ord) -{ - if (cmd & CMD_EXEC_ERR) - { - return Send_FileDir(pItem, TRUE, FALSE, 0, 0, ord); - } - - int count = m_gdwFile.FileCount(); - //默认文件名长度为32个字节 - //一个文件信息长度为:文件名称长度(1)+文件名长度(32)+文件属性(1)+文件大小(4)+文件时间(7) - //默认一个文件信息占用48字节 - //到此信息计算出一帧报文所能携带文件个数 - int acount = (max_frame - 17 - cot_length - asdu_addr_length - info_addr_length) / 48; // = 4 - - int full_frame = count / acount; - int si_frame = count % acount; - int pos = 0; - for (int i = 0; i < full_frame; i++) - { - Send_FileDir(pItem, FALSE, TRUE, acount, pos, ord); - pos += acount; - } - if (si_frame) Send_FileDir(pItem, FALSE, FALSE, si_frame, pos, ord); - - return 1; -} - -int CSubGDW104Process::Send_CallFileSel_Confirm(CIEC104ProcessItem* pItem, DWORD cmd, int ord) -{ - int len = 0; - BYTE buffer[1024]; - if (pItem == NULL) return -1; - - buffer[len++] = GDW_F_FR_NA_1; - buffer[len++] = 0; //VSQ此处无效 - SetCOT(&buffer[len], IEC_101_104_COT_ACTCON); len += cot_length; - SetAsduAddr(&buffer[len], pItem->apdu_addr); len += asdu_addr_length; - SetInformationAddr(&buffer[len], 0); len += info_addr_length; - - buffer[len++] = FILE_TRS_TYPE; //文件传输 - buffer[len++] = ReadFileSelCon; //读文件激活确认 - if (cmd & CMD_EXEC_ERR) - { - //结果描述字 - buffer[len++] = 1; //失败 - //没有文件 - if (!SendIFrame(buffer, len, ord)) return -1; - return 1; - } - //结果描述字 - buffer[len++] = 0; //成功 - std::string filename = m_FileDir.filename; - //名称长度 - buffer[len++] = filename.length(); - //文件名称 - for (int j = 0; j < (int)filename.length(); j ++) - { - buffer[len++] = filename[j]; - } - //文件ID - len += ValToBuf(&buffer[len], 0, 4); - //文件大小 - len += ValToBuf(&buffer[len], m_FileDir.length, 4); - if (!SendIFrame(buffer, len, ord)) return -1; - - m_gdwFile.ReadFile(); - return 1; -} - -int CSubGDW104Process::Send_CallFileDat_Ack(CIEC104ProcessItem* pItem, DWORD cmd, int ord) -{ - int len = 0; - BYTE buffer[1024]; - if (pItem == NULL) return -1; - - buffer[len++] = GDW_F_FR_NA_1; - buffer[len++] = 0; //VSQ此处无效 - SetCOT(&buffer[len], IEC_101_104_COT_ACTCON); len += cot_length; - SetAsduAddr(&buffer[len], pItem->apdu_addr); len += asdu_addr_length; - SetInformationAddr(&buffer[len], 0); len += info_addr_length; - - buffer[len++] = FILE_TRS_TYPE; //文件传输 - buffer[len++] = ReadFileDataAct; //读文件激活确认 - //文件ID - len += ValToBuf(&buffer[len], 0, 4); - //结果描述字 - len += m_gdwFile.FileData(&buffer[len]); - if (!SendIFrame(buffer, len, ord)) return -1; - - return 1; -} diff --git a/das-dn/subgdw104/sub_gdw104.h b/das-dn/subgdw104/sub_gdw104.h deleted file mode 100644 index f702fedc..00000000 --- a/das-dn/subgdw104/sub_gdw104.h +++ /dev/null @@ -1,474 +0,0 @@ -#ifndef _ZJD_SUB_GDW104_PROCESS_H_ -#define _ZJD_SUB_GDW104_PROCESS_H_ - -#include "iec104.h" -#include "sqlite/KompexSQLitePrerequisites.h" -#include "sqlite/KompexSQLiteDatabase.h" -#include "sqlite/KompexSQLiteStatement.h" -#include "sqlite/KompexSQLiteException.h" -#include "sqlite/KompexSQLiteStreamRedirection.h" -#include "sqlite/KompexSQLiteBlob.h" -#include -#include -#include - -using namespace Kompex; - -#define FILE_PATH_LEN 64 -#define MAX_FILEDATA_LEN 200 -#define EPS 1e-7 -#pragma pack(1) -typedef struct -{ - struIEC104Option iec104; - char soeDir[FILE_PATH_LEN]; - char coDir[FILE_PATH_LEN]; - char fixptDir[FILE_PATH_LEN]; - char exvDir[FILE_PATH_LEN]; - char frzDir[FILE_PATH_LEN]; - char flowrevDir[FILE_PATH_LEN]; - char ulogDir[FILE_PATH_LEN]; -} struGDW104Option; -#pragma pack() - -typedef struct -{ - time_t datetime; - float fMaxVal; - float fMinVal; - float fCoef; - float fBase; - int iMaxVal; - int iMinVal; - int MaxTime; - int MinTime; - int iCurVal; -} STRUCT_YCEXTREMUM; - -typedef struct -{ - time_t datetime; - float fCoef; - float fBase; - float fCurVal; - int iCurVal; -} STRUCT_FMRECORD; - -typedef struct -{ - int count; - std::string ss_outmax; - std::string ss_outmin; -} STRUCT_FILEBUFFER; -#if 1 - -#define CMD_GET_SOE_INFO 1 -#define CMD_GET_CO_INFO (1 << 1) -#define CMD_GET_EXV_INFO (1 << 2) -#define CMD_GET_FIXPT_INFO (1 << 3) -#define CMD_GET_FRZ_INFO (1 << 4) -#define CMD_GET_FLOWREV_INFO (1 << 5) -#define CMD_GET_ULOG_INFO (1 << 6) -#define CMD_GET_FILE_INFO (1 << 7) -#define CMD_READ_FILE (1 << 8) -#define CMD_GET_DIR_INFO (1 << 9) - -#define FIOCMD_IDLE 0 -#define FIOCMD_CREATE_FILE 1 -#define FIOCMD_OPEN_FILE 2 -#define FIOCMD_GET_FILEINFO 3 -#define FIOCMD_DEL_FILE 4 -#define FIOCMD_MAKE_DIR 5 -#define FIOCMD_REMOVE_DIR 6 -#define FIOCMD_OPEN_DIR 7 -#define FIOCMD_READ_FILE 8 -#define FIOCMD_WRITE_FILE 9 -#define FIOCMD_READ_DIR 10 -#define FIOCMD_CLOSE_FILE 11 -#define FIOCMD_CLOSE_DIR 12 - -#define FIOCMD_VALID 0x7fffffff -#define CMD_EXEC_ERR 0x80000000 - -typedef struct -{ - std::string st_name; - struct stat st_st; -} struFileStat; - -typedef std::vector vecFileStat; -class CGDW104FileProcess -{ -private: - DWORD last_sec; - int m_uid; - int m_information_address_length; - int m_yx_information_address_start; - int m_yc_information_address_start; - int m_ym_information_address_start; - - SQLiteDatabase m_database; - struUnitStatic m_unit; - - FILE* m_pFileHandle; - BYTE m_fileBuffer[256]; - LONG m_nFilePos; - LONG m_nFileLength; - LONG m_nReadLen; - -public: - CGDW104FileProcess() - { - m_pFileHandle = NULL; - m_nFilePos = 0; - m_nReadLen = 0; - m_nFileLength = 0; - m_nCmdID = 0; - m_bWr = FALSE; - m_soe_save = 0; - m_soe_load = 0; - m_yklog_save = 0; - m_yklog_load = 0; - m_uid = -1; - m_bCallAllFile = FALSE; - last_sec = 0; - m_last_day = -1; - m_nCmdIDConfirm = 0; - m_information_address_length = 3; - m_yx_information_address_start = IEC_101_104_YX_START_ADDR; - m_yc_information_address_start = IEC_101_104_YC_START_ADDR; - m_ym_information_address_start = IEC_101_104_YM_START_ADDR; - }; - virtual ~CGDW104FileProcess() - { - SaveMapToFile(); - if (m_pUnitYM) - { - delete [] m_pUnitYM; - m_pUnitYM = NULL; - } - m_database.SaveDatabaseFromMemoryToFile("./gdw104.db"); - fprintf(stderr, "SaveDatabaseFromMemoryToFile finished.\n"); - if (m_pFileHandle) - { - fclose(m_pFileHandle); - m_pFileHandle = NULL; - } - }; - BOOLEAN OnCreate(int, const void*, const void*); - BOOLEAN OnTimer(void); - -private: - struSOE m_soes[DATABASE_SOE_NUM]; - int m_soe_save; - int m_soe_load; - struYKLog m_yklogs[DATABASE_YK_LOG_NUM]; - int m_yklog_save; - int m_yklog_load; - - BOOLEAN m_bWr; - DWORD m_nCmdID; - DWORD m_nCmdIDConfirm; - - std::string m_pathName; - vecFileStat m_vecFileStat; - - std::string str_SOERecordDir; - std::string str_coRecordDir; - std::string str_exvRecordDir; - std::string str_fixptRecordDir; - std::string str_frzRecordDir; - std::string str_flowrevRecordDir; - std::string str_ulogRecordDir; - - BOOLEAN m_bCallAllFile; - time_t m_start_time; - time_t m_end_time; - - WORD m_last_day; - - struUnitYM *m_pUnitYM; - LONG m_total_ym; - std::map mapYcExetremumRecordDatas; - std::map mapFmHisRecordDatas; - - BOOLEAN SaveMapToFile(void); - BOOLEAN LoadMapFromFile(int); - BYTE GetCheckSum8(BYTE* pData, int count); - int ReadDir(const char* pathName) - { - DIR *dir; // 定义目录指针 - struct dirent *dir_info; // 定义目录结构体 - m_vecFileStat.clear(); - char buf[260]; // 用于存放文件路径 - struFileStat filestat; - if ((dir = opendir(pathName)) == NULL) - { // 打开目录 - vLog(LOG_ERROR, "打开文件目录:%s失败<%d,%s>\n", pathName, errno, strerror(errno)); - return -1; - } - while ((dir_info = readdir(dir)) != NULL) - { // 读取目录下文件列表 - if (dir_info->d_name[0] == '.') - { // 过滤掉 '.' 和 '..' - continue; - } - // 获取文件全路径,并打印 - sprintf(buf, "%s/%s", pathName, dir_info->d_name); - //获取文件属性 - if (stat(buf, &filestat.st_st) != 0) - { - vLog(LOG_ERROR, "获取文件%s属性失败<%d,%s>\n", buf, errno, strerror(errno)); - continue; - } - filestat.st_name = buf; - m_vecFileStat.push_back(filestat); - } - closedir(dir); // 关闭目录 - return m_vecFileStat.size(); - } - - int mkLogDir(const char* pathName) - { - if (access(pathName, F_OK) == 0) return 0; - // 创建目录 - if (mkdir(pathName, 0777) == -1) - { - vLog(LOG_ERROR, "创建文件夹 %s失败<%d,%s>\r\n", pathName, errno, strerror(errno)); - return -1; - } - return 1; - } - void delete_files_in_dir(const char*); - void DumpSOE(void); - void DumpYKLog(void); - void UpdateExtremumRecord(BOOLEAN); - void DumpYCHisRecord(LONG); - void DumpFmHisRecord(LONG); - - void createSOEFile(void); - void createYKLogFile(void); - void createExtremumRecordFile(void); - void createYCHisRecordFile(void); - void createFmHisRecordFile(void); -public: - void AddFmRecord(struUnitYM* yms, int count) - { - memcpy(m_pUnitYM, yms, sizeof(struUnitYM) * count); - } - void AddExtremumRecord(int point, LONG value) - { - if (mapYcExetremumRecordDatas.find(point) == mapYcExetremumRecordDatas.end()) return; - LONG maxVal = mapYcExetremumRecordDatas[point].iMaxVal; - LONG minVal = mapYcExetremumRecordDatas[point].iMinVal; - if (value > maxVal) - { - mapYcExetremumRecordDatas[point].fMaxVal = value * mapYcExetremumRecordDatas[point].fCoef + mapYcExetremumRecordDatas[point].fBase; - mapYcExetremumRecordDatas[point].iMaxVal = value; - mapYcExetremumRecordDatas[point].MaxTime = system32.timers; - } - if (value < minVal) - { - mapYcExetremumRecordDatas[point].fMinVal = value * mapYcExetremumRecordDatas[point].fCoef + mapYcExetremumRecordDatas[point].fBase; - mapYcExetremumRecordDatas[point].iMinVal = value; - mapYcExetremumRecordDatas[point].MinTime = system32.timers; - } - mapYcExetremumRecordDatas[point].iCurVal = value; - } - void PushSOE(unionCP56Time& st, int order, BOOLEAN value, BYTE qds, int uid = -1, int point = -1) - { - m_soes[m_soe_save].st.year = st.year; - m_soes[m_soe_save].st.month = st.month; - m_soes[m_soe_save].st.dayofmonth = st.dayofmonth; - m_soes[m_soe_save].st.dayofweek = st.dayofweek; - m_soes[m_soe_save].st.hour = st.hour; - m_soes[m_soe_save].st.minute = st.minute; - m_soes[m_soe_save].st.millisecond = st.millisecond; - if (order < 0 || order >= DATABASE_YX_NUM) - { - m_soes[m_soe_save].order = -1; - } - else - { - m_soes[m_soe_save].order = order; - } - m_soes[m_soe_save].value = value; - m_soes[m_soe_save].uid = uid; - m_soes[m_soe_save].point = point; - m_soes[m_soe_save].qds = qds; - m_soe_save++; - m_soe_save = m_soe_save % DATABASE_SOE_NUM; - } - - void PushYKLog(unionCP56Time& st, int point, BOOLEAN value, BYTE type, BYTE source = -1, int uid = -1) - { - m_yklogs[m_yklog_save].st.year = st.year; - m_yklogs[m_yklog_save].st.month = st.month; - m_yklogs[m_yklog_save].st.dayofmonth = st.dayofmonth; - m_yklogs[m_yklog_save].st.dayofweek = st.dayofweek; - m_yklogs[m_yklog_save].st.hour = st.hour; - m_yklogs[m_yklog_save].st.minute = st.minute; - m_yklogs[m_yklog_save].st.millisecond = st.millisecond; - m_yklogs[m_yklog_save].point = point; - m_yklogs[m_yklog_save].value = value; - m_yklogs[m_yklog_save].type = type; - m_yklogs[m_yklog_save].source = source; - m_yklogs[m_yklog_save].uid = uid; - m_yklog_save++; - m_yklog_save = m_yklog_save % DATABASE_YK_LOG_NUM; - } - - void ReadDir(const char* dirName, BOOLEAN callAllFile, unionCP56Time st, unionCP56Time et) - { - m_nCmdID = FIOCMD_READ_DIR; - m_pathName = dirName; - m_bCallAllFile = callAllFile; - m_start_time = unionCP56TimetoTime_t(&st); - m_end_time = unionCP56TimetoTime_t(&et); - } - - void OpenFile(const char* filename, bool bWr = FALSE) - { - m_nCmdID = FIOCMD_OPEN_FILE; - m_pathName = filename; - m_bWr = bWr; - } - void CloseFile() - { - m_nCmdID = FIOCMD_CLOSE_FILE; - } - void ReadFile() - { - m_nCmdID = FIOCMD_READ_FILE; - } - DWORD getCMD(void) - { - DWORD result = m_nCmdIDConfirm; - m_nCmdIDConfirm = 0; - return result; - } - - int FileData(BYTE* pData) - { - ValToBuf(pData, m_nFilePos, 4); pData+= 4; - if (FileLeftLength() <= 0) - { - *pData = 0; pData++; - } - else - { - *pData = 1; pData++; - ReadFile(); - } - memcpy(pData, m_fileBuffer, m_nReadLen); pData += m_nReadLen; - *pData = GetCheckSum8(m_fileBuffer, m_nReadLen); - m_nFilePos += m_nReadLen; - return (m_nReadLen + 6); - } - LONG FilePos(void) const - { - return m_nFilePos; - } - LONG FileLeftLength(void) const - { - return (m_nFileLength - m_nFilePos); - } - int FileCount(void) const - { - return m_vecFileStat.size(); - } - std::string FileName(int order) const - { - if (order >= (int)m_vecFileStat.size()) return NULL; - return m_vecFileStat[order].st_name; - } - LONG FileLength(int order) const - { - if (order >= (int)m_vecFileStat.size()) return -1; - return m_vecFileStat[order].st_st.st_size; - } - time_t FileTime(int order) const - { - if (order >= (int)m_vecFileStat.size()) return -1; - return m_vecFileStat[order].st_st.st_atime; - } - LONG FileLength(std::string name) const - { - for (int i = 0; i < (int)m_vecFileStat.size(); i++) - { - if (name == m_vecFileStat[i].st_name) - { - return m_vecFileStat[i].st_st.st_size; - } - } - return -1; - } - time_t FileTime(std::string name) const - { - for (int i = 0; i < (int)m_vecFileStat.size(); i++) - { - if (name == m_vecFileStat[i].st_name) - { - return m_vecFileStat[i].st_st.st_atime; - } - } - return -1; - } -}; -#endif - -typedef struct -{ - char dirname[FILE_PATH_LEN]; - char filename[FILE_PATH_LEN]; - LONG loadptr; - DWORD dirID; - DWORD length; - BOOLEAN allfile; - BYTE ret_val; -} stCallFileDir; - -class CSubGDW104Process : public CIEC104Process -{ -private: - CGDW104FileProcess m_gdwFile; - struGDW104Option gdw_option; - DWORD m_dwFileType; - stCallFileDir m_FileDir; - -public: - CSubGDW104Process(); - virtual ~CSubGDW104Process(); - - BOOLEAN OnPreCreate(int); - BOOLEAN OnCreated(int); - BOOLEAN Run(void); - BOOLEAN OnTimer(void); - BOOLEAN FetchUnitYC(int); - BOOLEAN FetchUnitYM(int); -public: - void GetItemEvents(CIEC104ProcessItem*); -public: - int MakeYKFrame(CIEC104ProcessItem*, int); - int MakeYTFrame(CIEC104ProcessItem*, int); - int MakeFileFrame(CIEC104ProcessItem*, int); - - BOOLEAN OnUFrameReceived(BOOLEAN, BOOLEAN, BOOLEAN, BOOLEAN, BOOLEAN, BOOLEAN, int); - BOOLEAN OnIFrameReceived(WORD, WORD, BYTE*, int, int); - - int Receive_Single_command(CIEC104ProcessItem*, const BYTE*, BYTE, BYTE*, int&); //单点令 - int Receive_Double_command(CIEC104ProcessItem*, const BYTE*, BYTE, BYTE*, int&); //单点令 - int Receive_Set_point_command_normalized(CIEC104ProcessItem*, const BYTE*, BYTE, BYTE*, int&); //设定规一化值命令 - int Receive_Set_point_command_scaled(CIEC104ProcessItem*, const BYTE*, BYTE, BYTE*, int&); //设定标度化值命令 - int Receive_Set_point_command_short_floating(CIEC104ProcessItem*, const BYTE*, BYTE, BYTE*, int&); //设定短浮点值命令 - int Receive_FileTrans(CIEC104ProcessItem*, const BYTE*, BYTE); //读取文件 - BOOLEAN parseFileReadDirAct(CIEC104ProcessItem*, const BYTE*); - BOOLEAN parseFileReadFileSelAct(CIEC104ProcessItem*, const BYTE*); - BOOLEAN parseFileReadFileDataCon(CIEC104ProcessItem*, const BYTE*); - int Send_CallFileDir_Confirm(CIEC104ProcessItem*, DWORD, int); - int Send_FileDir(CIEC104ProcessItem*, BOOLEAN, BOOLEAN, int, int, int); - int Send_CallFileSel_Confirm(CIEC104ProcessItem*, DWORD, int); - int Send_CallFileDat_Ack(CIEC104ProcessItem*, DWORD, int); -}; - -#endif //_ZJD_SUB_GDW104_PROCESS_H_ diff --git a/das-dn/subiec101balanced/sub_iec101_balanced.cpp b/das-dn/subiec101balanced/sub_iec101_balanced.cpp deleted file mode 100644 index 8548dc05..00000000 --- a/das-dn/subiec101balanced/sub_iec101_balanced.cpp +++ /dev/null @@ -1,241 +0,0 @@ -#include "sub_iec101_balanced.h" - - -/***************************************************************************************/ -BOOLEAN CIEC101SecondaryBalancedProcess::OnPreCreate(int id) -{ - if (!CIEC101Process::OnPreCreate(id)) return FALSE; - - int i; - int uid; - CIEC101SecondaryBalancedProcessItem* pItem; - for (i = 0; i < PROCESS_UNIT_NUM; i++) - { - pItem = (CIEC101SecondaryBalancedProcessItem *)GetItem(i); - if (NULL == pItem) continue; - uid = pItem->GetUnitID(); - if (uid < 0 || uid >= UNIT_NUM) continue; - BYTE phy_addr[2]; - GetUnitAddr(uid, phy_addr, 2); - pItem->Attach(uid, phy_addr[0], phy_addr[0], m_option.originatorAddress); //默认公共地址和物理地址一致 - pItem->setAppLayerParameters(m_option.sizeOfCOT, m_option.sizeOfCA, m_option.sizeOfIOA, m_option.maxSizeOfASDU); - - Slave_setLinkLayerAddressOtherStation(pItem, phy_addr[1]); - - pItem->setAppLayerIOABase(); - pItem->setAppLayerDataCount(GetUnitYXCount(uid), GetUnitYCCount(uid), GetUnitYMCount(uid)); - } - - last_sec != (time_t)system32.timers; - return TRUE; -} - -BOOLEAN CIEC101SecondaryBalancedProcess::Run(void) -{ - if (!CIEC101Process::Run()) return FALSE; - - FeedDog(); - CIEC101ProcessItem* pItem = (CIEC101ProcessItem *)GetCurItem(); - LinkLayerPrimaryBalanced_runStateMachine(pItem); - return TRUE; -} - -BOOLEAN CIEC101SecondaryBalancedProcess::OnTimer(void) -{ - if (!CIEC101Process::OnTimer()) return FALSE; - - BOOLEAN sec_changed = FALSE; - if (last_sec != (time_t)system32.timers) - { - last_sec = (time_t)system32.timers; - sec_changed = TRUE; - } - - CIEC101ProcessItem* pItem = (CIEC101ProcessItem *)GetCurItem(); - if (NULL == pItem) return TRUE; - int uid = pItem->GetUnitID(); - if (uid < 0 || uid >= UNIT_NUM) return TRUE; - - //刷新事件记录库 - GetItemEvents(pItem); - //刷新遥测库 - FetchUnitYC(0); - - if (pItem->interrogation_finish) - { - //总召唤结束,开始上送遥信变位 - GetItemYXBWs(pItem); - //总召唤结束,开始刷新遥测变位缓冲。 - if (pItem->ycbws.count <= 0) - { //当遥测变位发送结束后才更新 - GetItemYCBWs(pItem); - } - //发送遥控返校 - if (MakeYKFrame(pItem)) return TRUE; - if (MakeYTFrame(pItem)) return TRUE; - if (Send_Single_point_information(pItem)) return TRUE; - if (Send_Single_point_information_with_time_tag_cp56time2a(pItem)) return TRUE; - if (!pItem->interrogation_start) - { //变位遥测优先级在总召唤之后。 - if (sec_changed) - { - switch (m_option.yc_type) - { - case USE_YC_NB: //标度化值 - return Send_Measured_value_scaled(pItem); - case USE_YC_NC: //短浮点数 - return Send_Measured_value_short_floating_point(pItem); - case USE_YC_ND: //不带品质归一化值 - return Send_Measured_value_normalised_without_quality(pItem); - default: //USE_YC_NA: 归一化值 - return Send_Measured_value_normalised(pItem); - } - } - } - } - //响应总召唤命令 - if (pItem->interrogation_start) - { - if (pItem->call_type != IEC_101_104_COT_INTERROGATION) - { //组召唤 - //激活终止 - Send_FrameInterrogation(pItem); - pItem->call_type = 0; - pItem->interrogation_finish = TRUE; - pItem->interrogation_start = FALSE; - pItem->interrogation_yx_fin = TRUE; - pItem->interrogation_yc_fin = TRUE; - } - else if (!pItem->interrogation_yx_fin) - { - Send_Single_point_information(pItem, IEC_101_104_COT_INTERROGATION); - } - else if (!pItem->interrogation_yc_fin) - { - switch (m_option.yc_type) - { - case USE_YC_NB: //标度化值 - return Send_Measured_value_scaled(pItem, IEC_101_104_COT_INTERROGATION); - case USE_YC_NC: //短浮点数 - return Send_Measured_value_short_floating_point(pItem, IEC_101_104_COT_INTERROGATION); - case USE_YC_ND: //不带品质归一化值 - return Send_Measured_value_normalised_without_quality(pItem, IEC_101_104_COT_INTERROGATION); - default: //USE_YC_NA: 归一化值 - return Send_Measured_value_normalised(pItem, IEC_101_104_COT_INTERROGATION); - } - } - else - { - Send_FrameInterrogation(pItem); - pItem->call_type = 0; - pItem->interrogation_finish = TRUE; - pItem->interrogation_start = FALSE; - pItem->interrogation_yx_fin = TRUE; - pItem->interrogation_yc_fin = TRUE; - } - } - else if (pItem->pulse_start) - { - if (!pItem->pulse_fin) - { - Send_Integrated_totals(pItem, IEC_101_104_COT_REQCOGEN); - } - else - { - Send_FrameCounterInterrogation(pItem); - pItem->call_type = 0; - pItem->pulse_start = FALSE; - pItem->pulse_fin = TRUE; - } - } - return TRUE; -} - -//平衡方式从协议接收到主站报文 -void CIEC101SecondaryBalancedProcess::LinkLayerSecondaryBalanced_ReceivedMessage(BYTE fc, BOOLEAN isBroadcast, BOOLEAN fcb, BOOLEAN fcv, int address, BYTE* msg, int userDataStart, int userDataLength) -{ - CIEC101ProcessItem* pItem; - if (address == -1) pItem = (CIEC101ProcessItem *)GetCurItem(); - else - { - int uid = GetUnitByAddr((BYTE *)&address, m_linkLayer.linkLayerParameters.addressLength); - if (uid < 0 || uid >= UNIT_NUM) return; - pItem = (CIEC101ProcessItem *)GetItem(GetOrderByUnitID(uid)); - - UnitFeedDog(uid); - } - if (pItem == NULL) - { - vLog(LOG_DEBUG, "PLL RECV - response from unknown slave %i\n", address); - return; - } - - pIEC101_LinkLayerSecondaryBalanced self = &(pItem->secondaryLinkBalanced); - if (fcv) - { - if (LinkLayerSecondaryBalanced_checkFCB(self, fcb) == FALSE) return; - } - switch (fc) - { - case LL_FC_00_RESET_REMOTE_LINK: - //vLog(LOG_DEBUG, "SLL - RECV FC 00 - RESET REMOTE LINK\n"); - self->expectedFcb = TRUE; - //vLog(LOG_DEBUG, "SLL - SEND FC 00 - ACK\n"); - if (m_linkLayer.linkLayerParameters.useSingleCharACK) - { - SendSingleCharCharacter(); - } - else - { - SendFixedFrame(LL_FC_00_ACK, pItem->address, FALSE, m_linkLayer.dir, FALSE, FALSE); - } - break; - case LL_FC_02_TEST_FUNCTION_FOR_LINK: - //vLog(LOG_DEBUG, "SLL - RECV FC 02 - TEST FUNCTION FOR LINK\n"); - //vLog(LOG_DEBUG, "SLL - SEND FC 00 - ACK\n"); - if (m_linkLayer.linkLayerParameters.useSingleCharACK) - { - SendSingleCharCharacter(); - } - else - { - SendFixedFrame(LL_FC_00_ACK, pItem->address, FALSE, m_linkLayer.dir, FALSE, FALSE); - } - break; - case LL_FC_03_USER_DATA_CONFIRMED: - //vLog(LOG_DEBUG, "SLL - RECV FC 03 - USER DATA CONFIRMED\n"); - if (userDataLength > 0) - { - if (ApplicationLayer_ReceivedData(pItem, msg, isBroadcast, userDataStart, userDataLength)) - { - //vLog(LOG_DEBUG, "SLL - SEND FC 00 - ACK\n"); - if (m_linkLayer.linkLayerParameters.useSingleCharACK) - { - SendSingleCharCharacter(); - } - else - { - SendFixedFrame(LL_FC_00_ACK, pItem->address, FALSE, m_linkLayer.dir, FALSE, FALSE); - } - } - } - break; - case LL_FC_04_USER_DATA_NO_REPLY: - //vLog(LOG_DEBUG, "SLL -FC 04 - USER DATA NO REPLY\n"); - if (userDataLength > 0) - { - ApplicationLayer_ReceivedData(pItem, msg, isBroadcast, userDataStart, userDataLength); - } - break; - case LL_FC_09_REQUEST_LINK_STATUS: - //vLog(LOG_DEBUG, "SLL - RECV FC 09 - REQUEST LINK STATUS"); - //vLog(LOG_DEBUG, "SLL - SEND FC 11 - STATUS OF LINK\n"); - SendFixedFrame(LL_FC_11_STATUS_OF_LINK_OR_ACCESS_DEMAND, pItem->address, FALSE, m_linkLayer.dir, FALSE, FALSE); - break; - default: - //vLog(LOG_DEBUG, "SLL - UNEXPECTED LINK LAYER MESSAGE"); - //vLog(LOG_DEBUG, "SLL - SEND FC 15 - SERVICE NOT IMPLEMENTED\n"); - SendFixedFrame(LL_FC_15_SERVICE_NOT_IMPLEMENTED, pItem->address, FALSE, m_linkLayer.dir, FALSE, FALSE); - break; - } -} diff --git a/das-dn/subiec101balanced/sub_iec101_balanced.h b/das-dn/subiec101balanced/sub_iec101_balanced.h deleted file mode 100644 index eb8efe1a..00000000 --- a/das-dn/subiec101balanced/sub_iec101_balanced.h +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef _ZJD_SUB_IEC101_BALANCED_PROCESS_H_ -#define _ZJD_SUB_IEC101_BALANCED_PROCESS_H_ - -#include "iec101.h" - -class CIEC101SecondaryBalancedProcessItem : public CIEC101ProcessItem -{ -public: - CIEC101SecondaryBalancedProcessItem() {}; - virtual ~CIEC101SecondaryBalancedProcessItem() {}; -public: - void Attach(int uid, int physicsAddress = 0, int commonAddress = 0, int originatorAddress = 0) - { - CIEC101ProcessItem::Attach(uid, physicsAddress, commonAddress, m_originatorAddress); - primaryLinkBalanced.otherStationAddress = physicsAddress; - common_address = commonAddress; - applicationlParameters.originatorAddress = originatorAddress; - } - void setAppLayerDataCount(int yx = 0, int yc = 0, int ym = 0) - { - total_yx = yx; - total_yc = yc; - total_ym = ym; - yx_pos = 0; - yc_pos = 0; - ym_pos = 0; - } -}; - -class CIEC101SecondaryBalancedProcess : public CIEC101SecondaryProcess -{ -public: - CIEC101SecondaryBalancedProcess() {m_linkLayer.mode = llSecBalanced;}; - virtual ~CIEC101SecondaryBalancedProcess() {}; - BOOLEAN OnPreCreate(int id); - BOOLEAN Run(void); - BOOLEAN OnTimer(void); - - CIEC101ProcessItem *CreateItem(int ord) - { - return dynamic_cast(new CIEC101SecondaryBalancedProcessItem); - } - - void Slave_setLinkLayerAddressOtherStation(CIEC101ProcessItem* pItem, int address) - { - pItem->address = address; - } -private: - BOOLEAN LinkLayerSecondaryBalanced_checkFCB(pIEC101_LinkLayerSecondaryBalanced self, BOOLEAN fcb) - { - if (fcb != self->expectedFcb) - { - //vLog(LOG_DEBUG, "ERROR: Frame count bit (FCB) invalid!\n"); - /* TODO change link status */ - return FALSE; - } - self->expectedFcb = !(self->expectedFcb); - return TRUE; - } - virtual void LinkLayerSecondaryBalanced_ReceivedMessage(BYTE fc, BOOLEAN isBroadcast, BOOLEAN fcb, BOOLEAN fcv, int address, BYTE* msg, int userDataStart, int userDataLength); -}; - -#endif // _ZJD_SUB_IEC101_BALANCED_PROCESS_H_ \ No newline at end of file diff --git a/das-dn/subiec101unbalanced/sub_iec101_unbalanced.cpp b/das-dn/subiec101unbalanced/sub_iec101_unbalanced.cpp deleted file mode 100644 index 0e82d2ac..00000000 --- a/das-dn/subiec101unbalanced/sub_iec101_unbalanced.cpp +++ /dev/null @@ -1,404 +0,0 @@ -#include "sub_iec101_unbalanced.h" - - -/***************************************************************************************/ -BOOLEAN CIEC101SecondaryUnbalancedProcess::OnPreCreate(int id) -{ - if (!CIEC101Process::OnPreCreate(id)) return FALSE; - - int i; - int uid; - CIEC101SecondaryUnbalancedProcessItem* pItem; - for (i = 0; i < PROCESS_UNIT_NUM; i++) - { - pItem = (CIEC101SecondaryUnbalancedProcessItem *)GetItem(i); - if (NULL == pItem) continue; - uid = pItem->GetUnitID(); - if (uid < 0 || uid >= UNIT_NUM) continue; - BYTE phy_addr[2]; - GetUnitAddr(uid, phy_addr, 2); - pItem->Attach(uid, phy_addr[0], phy_addr[0], m_option.originatorAddress); //默认公共地址和物理地址一致 - pItem->setAppLayerParameters(m_option.sizeOfCOT, m_option.sizeOfCA, m_option.sizeOfIOA, m_option.maxSizeOfASDU); - - Slave_setLinkLayerAddressOtherStation(pItem, phy_addr[1]); - pItem->setAppLayerIOABase(); - pItem->setAppLayerDataCount(GetUnitYXCount(uid), GetUnitYCCount(uid), GetUnitYMCount(uid)); - } - - last_sec = (time_t)system32.timers; - return TRUE; -} - -BOOLEAN CIEC101SecondaryUnbalancedProcess::Run(void) -{ - if (!CIEC101Process::Run()) return FALSE; - - FeedDog(); - - if (m_state != LL_STATE_IDLE) - { - if ((getTimeInMs() - m_lastReceivedMsg) > (unsigned int) m_idleTimeout) - { - llsu_setState(LL_STATE_IDLE); - } - } - return TRUE; -} - -BOOLEAN CIEC101SecondaryUnbalancedProcess::OnTimer(void) -{ - if (!CIEC101Process::OnTimer()) return FALSE; - - BOOLEAN sec_changed = FALSE; - if (last_sec != (time_t)system32.timers) - { - last_sec = (time_t)system32.timers; - sec_changed = TRUE; - } - - CIEC101ProcessItem* pItem = (CIEC101ProcessItem *)GetCurItem(); - if (NULL == pItem) return TRUE; - int uid = pItem->GetUnitID(); - if (uid < 0 || uid >= UNIT_NUM) return TRUE; - - //刷新事件记录库 - GetItemEvents(pItem); - //刷新遥测库 - FetchUnitYC(0); - - if (pItem->interrogation_finish) - { - //总召唤结束,开始上送遥信变位 - GetItemYXBWs(pItem); - //总召唤结束,开始刷新遥测变位缓冲。 - if (pItem->ycbws.count <= 0) - { //当遥测变位发送结束后才更新 - GetItemYCBWs(pItem); - } - //发送遥控返校 - if (MakeYKFrame(pItem)) return TRUE; - if (MakeYTFrame(pItem)) return TRUE; - if (Send_Single_point_information(pItem)) return TRUE; - if (Send_Single_point_information_with_time_tag_cp56time2a(pItem)) return TRUE; - if (!pItem->interrogation_start) - { //变位遥测优先级在总召唤之后。 - if (sec_changed) - { - switch (m_option.yc_type) - { - case USE_YC_NB: //标度化值 - return Send_Measured_value_scaled(pItem); - case USE_YC_NC: //短浮点数 - return Send_Measured_value_short_floating_point(pItem); - case USE_YC_ND: //不带品质归一化值 - return Send_Measured_value_normalised_without_quality(pItem); - default: //USE_YC_NA: 归一化值 - return Send_Measured_value_normalised(pItem); - } - } - } - } - //响应总召唤命令 - if (pItem->interrogation_start) - { - if (pItem->call_type != IEC_101_104_COT_INTERROGATION) - { //组召唤 - //激活终止 - Send_FrameInterrogation(pItem); - pItem->call_type = 0; - pItem->interrogation_finish = TRUE; - pItem->interrogation_start = FALSE; - pItem->interrogation_yx_fin = TRUE; - pItem->interrogation_yc_fin = TRUE; - } - else if (!pItem->interrogation_yx_fin) - { - Send_Single_point_information(pItem, IEC_101_104_COT_INTERROGATION); - } - else if (!pItem->interrogation_yc_fin) - { - switch (m_option.yc_type) - { - case USE_YC_NB: //标度化值 - return Send_Measured_value_scaled(pItem, IEC_101_104_COT_INTERROGATION); - case USE_YC_NC: //短浮点数 - return Send_Measured_value_short_floating_point(pItem, IEC_101_104_COT_INTERROGATION); - case USE_YC_ND: //不带品质归一化值 - return Send_Measured_value_normalised_without_quality(pItem, IEC_101_104_COT_INTERROGATION); - default: //USE_YC_NA: 归一化值 - return Send_Measured_value_normalised(pItem, IEC_101_104_COT_INTERROGATION); - } - } - else - { - Send_FrameInterrogation(pItem); - pItem->call_type = 0; - pItem->interrogation_finish = TRUE; - pItem->interrogation_start = FALSE; - pItem->interrogation_yx_fin = TRUE; - pItem->interrogation_yc_fin = TRUE; - } - } - else if (pItem->pulse_start) - { - if (!pItem->pulse_fin) - { - Send_Integrated_totals(pItem, IEC_101_104_COT_REQCOGEN); - } - else - { - Send_FrameCounterInterrogation(pItem); - pItem->call_type = 0; - pItem->pulse_start = FALSE; - pItem->pulse_fin = TRUE; - } - } - - return TRUE; -} - -int CIEC101SecondaryUnbalancedProcess::OnPackageReceived(BYTE* pBuf, int msgSize, int /* ord = -1 */) -{ - m_lastReceivedMsg = getTimeInMs(); - - int userDataLength = 0; - int userDataStart = 0; - BYTE c; - int csStart; - int csIndex; - int address = 0; - int addressLength = m_linkLayer.linkLayerParameters.addressLength; - BYTE* msg = (BYTE *)pBuf; - - if (msg [0] == 0x68) - { - if (msg [1] != msg [2]) - { - vLog(LOG_DEBUG, "ERROR: L fields differ!\n"); - llsu_setState(LL_STATE_ERROR); - return 1; - } - - userDataLength = (int)msg [1] - addressLength - 1; - userDataStart = 5 + addressLength; - csStart = 4; - csIndex = userDataStart + userDataLength; - /* check if message size is reasonable */ - if (msgSize != (userDataStart + userDataLength + 2 /* CS + END */)) - { - vLog(LOG_DEBUG, "ERROR: Invalid message length\n"); - llsu_setState(LL_STATE_ERROR); - return 1; - } - c = msg [4]; - } - else if (msg [0] == 0x10) - { - c = msg [1]; - csStart = 1; - csIndex = 2 + addressLength; - } - else - { - vLog(LOG_DEBUG, "ERROR: Received unexpected message type in unbalanced slave mode!\n"); - llsu_setState(LL_STATE_ERROR); - return 1; - } - BOOLEAN isBroadcast = false; - CIEC101ProcessItem* pItem; - /* check address */ - if (addressLength > 0) - { - address = msg[csStart + 1]; - if (addressLength > 1) - { - address += msg [csStart + 2] * 0x100; - if (address == 65535) isBroadcast = TRUE; - } - else - { - if (address == 255) isBroadcast = TRUE; - } - } - int fc = c & 0x0f; - if (isBroadcast) - { - if (fc != LL_FC_04_USER_DATA_NO_REPLY) - { - vLog(LOG_DEBUG, "ERROR: Invalid function code for broadcast message!\n"); - llsu_setState(LL_STATE_ERROR); - return 1; - } - } - else - { - int uid = GetUnitByAddr((BYTE *)&address, m_linkLayer.linkLayerParameters.addressLength); - if (uid < 0 || uid >= UNIT_NUM) - { - vLog(LOG_DEBUG, "INFO: unknown link layer address(%i) -> ignore message\n", address); - return 1; - } - pItem = (CIEC101ProcessItem *)GetItem(GetOrderByUnitID(uid)); - if (pItem == NULL) - { - vLog(LOG_DEBUG, "INFO: unknown link layer address(%i) -> ignore message\n", address); - return 1; - } - UnitFeedDog(uid); - } - /* check checksum */ - BYTE checksum = 0; - int i; - for (i = csStart; i < csIndex; i++) checksum += msg [i]; - if (checksum != msg [csIndex]) - { - vLog(LOG_DEBUG, "ERROR: checksum invalid!\n"); - llsu_setState(LL_STATE_ERROR); - return 1; - } - /* parse C field bits */ - BOOLEAN prm = ((c & 0x40) == 0x40); - if (prm == FALSE) - { - vLog(LOG_DEBUG, "ERROR: Received secondary message in unbalanced slave mode!\n"); - llsu_setState(LL_STATE_ERROR); - return 1; - } - BOOLEAN fcb = ((c & 0x20) == 0x20); - BOOLEAN fcv = ((c & 0x10) == 0x10); - - LinkLayerSecondaryUnbalanced_ReceivedMessage(pItem, fc, isBroadcast, fcb, fcv, msg, userDataStart, userDataLength); - - return 1; -} - -//不平衡方式从协议接收到主站报文 -void CIEC101SecondaryUnbalancedProcess::LinkLayerSecondaryUnbalanced_ReceivedMessage(CIEC101ProcessItem* pItem, BYTE fc, BOOLEAN isBroadcast, BOOLEAN fcb, BOOLEAN fcv, BYTE* msg, int userDataStart, int userDataLength) -{ - pIEC101_LinkLayerSecondaryUnbalanced self = &(pItem->secondaryLinkUnbalanced); - if (fcv) - { - if (checkFCB(self, fcb) == FALSE) - { - vLog(LOG_DEBUG, "SLL - FCB check failed\n"); - llsu_setState(LL_STATE_ERROR); - return; - } - } - llsu_setState(LL_STATE_AVAILABLE); - switch (fc) - { - case LL_FC_09_REQUEST_LINK_STATUS: - //vLog(LOG_DEBUG, "SLL - REQUEST LINK STATUS\n"); - { - BOOLEAN accessDemand = IsClass1DataAvailable(pItem); - SendFixedFrame(LL_FC_11_STATUS_OF_LINK_OR_ACCESS_DEMAND, pItem->address, FALSE, FALSE, accessDemand, FALSE); - } - break; - case LL_FC_00_RESET_REMOTE_LINK: - //vLog(LOG_DEBUG, "SLL - RESET REMOTE LINK\n"); - { - self->expectedFcb = TRUE; - if (m_linkLayer.linkLayerParameters.useSingleCharACK) - { - SendSingleCharCharacter(); - } - else - { - SendFixedFrame(LL_FC_00_ACK, pItem->address, FALSE, FALSE, FALSE, FALSE); - } - ResetCUReceived(pItem, FALSE); - } - break; - case LL_FC_07_RESET_FCB: - //vLog(LOG_DEBUG, "SLL - RESET FCB\n"); - { - self->expectedFcb = TRUE; - if (m_linkLayer.linkLayerParameters.useSingleCharACK) - { - SendSingleCharCharacter(); - } - else - { - SendFixedFrame(LL_FC_00_ACK, pItem->address, FALSE, FALSE, FALSE, FALSE); - } - ResetCUReceived(pItem, TRUE); - } - break; - case LL_FC_11_REQUEST_USER_DATA_CLASS_2: - //vLog(LOG_DEBUG, "SLL - REQUEST USER DATA CLASS 2\n"); - { - /* provide a buffer where the application layer can encode the user data */ - pIEC101_QueueElement element = GetClass2Data(pItem); - BOOLEAN accessDemand = IsClass1DataAvailable(pItem); - if (element) - { - SendVariableLengthFrame(LL_FC_08_RESP_USER_DATA, pItem->address, FALSE, FALSE, accessDemand, FALSE, element->buffer, element->size); - } - else - { - if (m_linkLayer.linkLayerParameters.useSingleCharACK && !accessDemand) - { - SendSingleCharCharacter(); - } - else - { - SendFixedFrame(LL_FC_09_RESP_NACK_NO_DATA, pItem->address, FALSE, FALSE, accessDemand, FALSE); - } - } - } - break; - case LL_FC_10_REQUEST_USER_DATA_CLASS_1: - //vLog(LOG_DEBUG, "SLL - REQUEST USER DATA CLASS 1\n"); - { - /* provide a buffer where the application layer can encode the user data */ - pIEC101_QueueElement element = GetClass1Data(pItem); - BOOLEAN accessDemand = IsClass1DataAvailable(pItem); - if (element) - { - SendVariableLengthFrame(LL_FC_08_RESP_USER_DATA, pItem->address, FALSE, FALSE, accessDemand, FALSE, element->buffer, element->size); - } - else - { - if (m_linkLayer.linkLayerParameters.useSingleCharACK && !accessDemand) - { - SendSingleCharCharacter(); - } - else - { - SendFixedFrame(LL_FC_09_RESP_NACK_NO_DATA, pItem->address, FALSE, FALSE, accessDemand, FALSE); - } - } - } - break; - case LL_FC_03_USER_DATA_CONFIRMED: - //vLog(LOG_DEBUG, "SLL - USER DATA CONFIRMED\n"); - if (userDataLength > 0) - { - if (ApplicationLayer_ReceivedData(pItem, msg, isBroadcast, userDataStart, userDataLength)) - { - BOOLEAN accessDemand = IsClass1DataAvailable(pItem); - if (m_linkLayer.linkLayerParameters.useSingleCharACK && !accessDemand) - { - SendSingleCharCharacter(); - } - else - { - SendFixedFrame(LL_FC_00_ACK, pItem->address, FALSE, FALSE, accessDemand, FALSE); - } - } - } - break; - case LL_FC_04_USER_DATA_NO_REPLY: - //vLog(LOG_DEBUG, "SLL - USER DATA NO REPLY\n"); - if (userDataLength > 0) - { - ApplicationLayer_ReceivedData(pItem, msg, isBroadcast, userDataStart, userDataLength); - } - break; - default: - //vLog(LOG_DEBUG, "SLL - UNEXPECTED LINK LAYER MESSAGE\n"); - SendFixedFrame(LL_FC_15_SERVICE_NOT_IMPLEMENTED, pItem->address, FALSE, FALSE, FALSE, FALSE); - break; - } -} \ No newline at end of file diff --git a/das-dn/subiec101unbalanced/sub_iec101_unbalanced.h b/das-dn/subiec101unbalanced/sub_iec101_unbalanced.h deleted file mode 100644 index f9f3f06e..00000000 --- a/das-dn/subiec101unbalanced/sub_iec101_unbalanced.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef _ZJD_SUB_IEC101_UNBALANCED_PROCESS_H_ -#define _ZJD_SUB_IEC101_UNBALANCED_PROCESS_H_ - -#include "iec101.h" - -class CIEC101SecondaryUnbalancedProcessItem : public CIEC101ProcessItem -{ -public: - CIEC101SecondaryUnbalancedProcessItem() {}; - virtual ~CIEC101SecondaryUnbalancedProcessItem() {}; -public: - void Attach(int uid, int physicsAddress = 0, int commonAddress = 0, int originatorAddress = 0) - { - CIEC101ProcessItem::Attach(uid, physicsAddress, commonAddress, m_originatorAddress); - primaryLinkBalanced.otherStationAddress = physicsAddress; - common_address = commonAddress; - applicationlParameters.originatorAddress = originatorAddress; - } - void setAppLayerDataCount(int yx = 0, int yc = 0, int ym = 0) - { - total_yx = yx; - total_yc = yc; - total_ym = ym; - yx_pos = 0; - yc_pos = 0; - ym_pos = 0; - } -}; - -class CIEC101SecondaryUnbalancedProcess : public CIEC101SecondaryProcess -{ -private: - enumIEC101_LinkLayerState m_state; - QWORD m_lastReceivedMsg; - int m_idleTimeout; /* connection timeout in ms */ -public: - CIEC101SecondaryUnbalancedProcess() - { - m_linkLayer.mode = llSecUnbalanced; - m_state = LL_STATE_IDLE; - } - virtual ~CIEC101SecondaryUnbalancedProcess() {}; - BOOLEAN OnPreCreate(int id); - BOOLEAN Run(void); - BOOLEAN OnTimer(void); - - CIEC101ProcessItem *CreateItem(int ord) - { - return dynamic_cast(new CIEC101SecondaryUnbalancedProcessItem); - } - - void Slave_setLinkLayerAddressOtherStation(CIEC101ProcessItem* pItem, int address) - { - pItem->address = address; - } - - int OnPackageReceived(BYTE* pBuf, int count, int ord = -1); -private: - void llsu_setState(enumIEC101_LinkLayerState newState) - { - if (m_state != newState) - { - m_state = newState; - } - } - BOOLEAN checkFCB(pIEC101_LinkLayerSecondaryUnbalanced self, BOOLEAN fcb) - { - if (fcb != self->expectedFcb) return FALSE; - self->expectedFcb = !(self->expectedFcb); - return TRUE; - } - void ResetCUReceived(CIEC101ProcessItem* pItem, bool onlyFCB) - { - if (onlyFCB) - { - //vLog(LOG_DEBUG, "CS101 slave: Reset FCB received\n"); - } - else - { - //vLog(LOG_DEBUG, "Received reset CU\n"); - pItem->userDataClass1Queue.flush(); - pItem->userDataClass2Queue.flush(); - } - } - void LinkLayerSecondaryUnbalanced_ReceivedMessage(CIEC101ProcessItem* self, BYTE fc, BOOLEAN isBroadcast, BOOLEAN fcb, BOOLEAN fcv, BYTE* msg, int userDataStart, int userDataLength); -}; - -#endif // _ZJD_SUB_IEC101_UNBALANCED_PROCESS_H_ \ No newline at end of file diff --git a/das-dn/submodbustcp/sub_modbus_rtu_tcp.cpp b/das-dn/submodbustcp/sub_modbus_rtu_tcp.cpp deleted file mode 100644 index e5f35e7b..00000000 --- a/das-dn/submodbustcp/sub_modbus_rtu_tcp.cpp +++ /dev/null @@ -1,1030 +0,0 @@ -#include "sub_modbus_rtu_tcp.h" - -#define MB_TCP_TID 0 -#define MB_TCP_PID 2 -#define MB_TCP_LEN 4 -#define MB_TCP_UID 6 -#define MB_TCP_FUNC 7 - -#define MB_TCP_BUF_SIZE ( 256 + 7 ) /* Must hold a complete Modbus TCP frame. */ - -/////////////////////////////////////////////////////////////////////////////////// -CSubModbusTcpProcessItem::CSubModbusTcpProcessItem() -{ - ied_addr = 255; - m_nNum = 0; - - m_CoilRegCount; - m_DiscreteRegCount = 0; - m_HoldingRegCount = 0; - m_InputregCount = 0; - - m_pCoilRegTable = NULL; - m_pDiscreteRegTable = NULL; - m_pHoldingRegTable = NULL; - m_pInputRegTable = NULL; -} - -CSubModbusTcpProcessItem::~CSubModbusTcpProcessItem() -{ - ied_addr = 255; - m_nNum = 0; - - if (m_pCoilRegTable) - { - delete[] m_pCoilRegTable; - m_pCoilRegTable = NULL; - } - - if (m_pDiscreteRegTable) - { - delete[] m_pDiscreteRegTable; - m_pDiscreteRegTable = NULL; - } - - if (m_pHoldingRegTable) - { - delete[] m_pHoldingRegTable; - m_pHoldingRegTable = NULL; - } - - if (m_pInputRegTable) - { - delete[] m_pInputRegTable; - m_pInputRegTable = NULL; - } -} - -void CSubModbusTcpProcessItem::Attach(int uid, int sock, DWORD peer_addr, WORD peer_port) -{ - CNetProcessItem::Attach(uid, sock, peer_addr, peer_port); - - m_nNum = 0; -} - -void CSubModbusTcpProcessItem::Release(void) -{ - m_nNum = 0; - - CNetProcessItem::Release(); -} - -CSubModbusTcpProcess::CSubModbusTcpProcess() -{ - -} - -CSubModbusTcpProcess::~CSubModbusTcpProcess() -{ -} - -CNetProcessItem *CSubModbusTcpProcess::CreateItem(int ord) -{ - return dynamic_cast(new CSubModbusTcpProcessItem); -} - -void CSubModbusTcpProcess::DestroyItem(int ord, BOOLEAN bDeleted /* = FALSE */) -{ - CSubModbusTcpProcessItem *pItem = (CSubModbusTcpProcessItem *)GetItem(ord); - if (pItem != NULL && !bDeleted) - { - delete pItem; - return CNetProcess::DestroyItem(ord, TRUE); - } - - return CNetProcess::DestroyItem(ord, bDeleted); -} - -BOOLEAN CSubModbusTcpProcess::OnPreCreate(int id) -{ - int i, j; - int uid; - BYTE addr[6]; - CSubModbusTcpProcessItem *pItem; - if (!CNetProcess::OnPreCreate(id)) return FALSE; - - struSubModbusTCPOption m_option; - if (!GetOption(&m_option, sizeof(m_option))) return FALSE; - - m_YC_Type = m_option.defaultYCType; - for (i = 0; i < PROCESS_UNIT_NUM; i++) - { - pItem = (CSubModbusTcpProcessItem *)GetItem(i); - if (NULL == pItem) continue; - uid = GetUnitID(i); - - if (uid < 0 || uid >= UNIT_NUM) continue; - if (GetUnitAddr(uid, addr, 6)) - { //获取单元地址成功,则该段原地址采用配置地址,否则该单元为无效地址。 - pItem->ied_addr = addr[4]; //配置地址 - } - //此处增加判断 - m_CoilRegTable.clear(); - m_DiscreteTable.clear(); - m_HoldingRegTable.clear(); - m_InputRegTable.clear(); - //获取遥信数量 - int yxcount = GetUnitYXCount(uid); - //获取coil和discrete寄存器 - for (j = 0; j < yxcount; j++) { - BYTE* param = GetUnitYXParamByPoint(uid, j); - if (param) { - if (param[0] == 0 || param[0] == 1) { - m_DiscreteTable.push_back(j); - } else { - m_CoilRegTable.push_back(j); - } - } - } - - int yccount = GetUnitYCCount(uid); - for (j = 0; j < yccount; j++) { - BYTE* param = GetUnitYCParamByPoint(uid, j); - if (param) { - if (param[0] == 0 || param[0] == 1) { - m_InputRegTable.push_back(j); - } else { - m_HoldingRegTable.push_back(j); - } - } - } - - if (m_CoilRegTable.size() > 0) - { - pItem->m_CoilRegCount = m_CoilRegTable.size(); - pItem->m_pCoilRegTable = new BYTE[pItem->m_CoilRegCount]; - memset(pItem->m_pCoilRegTable, 0, sizeof(BYTE) * pItem->m_CoilRegCount); - } - if (m_DiscreteTable.size() > 0) - { - pItem->m_DiscreteRegCount = m_DiscreteTable.size(); - pItem->m_pDiscreteRegTable = new BYTE[pItem->m_DiscreteRegCount]; - memset(pItem->m_pDiscreteRegTable, 0, sizeof(BYTE) * pItem->m_DiscreteRegCount); - } - if (m_InputRegTable.size() > 0) - { - int count = 0; - if (m_YC_Type == M_ME_NC) count = (m_InputRegTable.size() << 1); - else count = m_InputRegTable.size(); - pItem->m_InputregCount = count; - pItem->m_pInputRegTable = new WORD[count]; - memset(pItem->m_pInputRegTable, 0, sizeof(WORD) * count); - } - int ymcount = GetUnitYMCount(uid); - if (m_HoldingRegTable.size() > 0 || ymcount > 0) - { - int count = m_HoldingRegTable.size(); - if (m_YC_Type == M_ME_NC) count = (count << 1); - count += (ymcount << 1); - pItem->m_HoldingRegCount = count; - pItem->m_pHoldingRegTable = new WORD[count]; - memset(pItem->m_pHoldingRegTable, 0, sizeof(WORD) * count); - } - } - return TRUE; -} - -BOOLEAN CSubModbusTcpProcess::Run(void) -{ - if (!CNetProcess::Run()) return FALSE; - - int i, j, uid; - - FeedDog(); - for (i = 0; i < PROCESS_UNIT_NUM; i++) - { - CSubModbusTcpProcessItem *pItem = (CSubModbusTcpProcessItem *)GetItem(i); - if (NULL == pItem) continue; - uid = pItem->GetUnitID(); - if (uid < 0) continue; - //刷新寄存器 - WORD *wd_input = NULL; - WORD *wd_hold = NULL; - BYTE *bt_coil = NULL; - BYTE *bt_discrete = NULL; - - if (pItem->m_pInputRegTable) { - wd_input = (WORD *)pItem->m_pInputRegTable; - } - if (pItem->m_pHoldingRegTable) { - wd_hold = (WORD *)pItem->m_pHoldingRegTable; - } - for (j = 0; j < m_InputRegTable.size(); j++) - { - if (m_YC_Type == M_ME_NC) - { - union - { - float fv; - DWORD dv; - } val; - - val.fv = GetUnitYCReal(uid, m_InputRegTable[j]); - *wd_input = ((val.dv >> 16) & 0xffff); wd_input++; - *wd_input = (val.dv & 0xffff); wd_input++; - } - else - { - *wd_input = (WORD)GetUnitYC(uid, m_InputRegTable[j]); wd_input++; - } - } - for (j = 0; j < m_HoldingRegTable.size(); j++) - { - if (m_YC_Type == M_ME_NC) - { - union - { - float fv; - DWORD dv; - } val; - - val.fv = GetUnitYCReal(uid, m_HoldingRegTable[j]); - *wd_hold = ((val.dv >> 16) & 0xffff); wd_hold++; - *wd_hold = (val.dv & 0xffff); wd_hold++; - } - else - { - *wd_hold = (WORD)GetUnitYC(uid, m_HoldingRegTable[j]); wd_hold++; - } - } - for (j = 0; j < GetUnitYMCount(uid); j++) - { - DWORD val = (DWORD)GetUnitYM(uid, j); - *wd_hold = ((val >> 16) & 0xffff); wd_hold++; - *wd_hold = (val & 0xffff); wd_hold++; - } - - if (pItem->m_pCoilRegTable) { - bt_coil = (BYTE *)pItem->m_pCoilRegTable; - for (j = 0; j < m_CoilRegTable.size(); j++) - { - *bt_coil = (BYTE)GetUnitYX(uid, m_CoilRegTable[j]); bt_coil++; - } - } - if (pItem->m_pDiscreteRegTable) { - bt_discrete = (BYTE *)pItem->m_pDiscreteRegTable; - for (j = 0; j < m_DiscreteTable.size(); j++) - { - *bt_discrete = (BYTE)GetUnitYX(uid, m_DiscreteTable[j]); bt_discrete++; - } - } - } - return TRUE; -} - -BOOLEAN CSubModbusTcpProcess::OnTimer(void) -{ - if (!CNetProcess::OnTimer()) return FALSE; - - int i, uid; - for (i = 0; i < PROCESS_UNIT_NUM; i++) - { - CSubModbusTcpProcessItem *pItem = (CSubModbusTcpProcessItem *)GetItem(i); - if (NULL == pItem) continue; - uid = pItem->GetUnitID(); - if (uid < 0) continue; - - int order; - BYTE action, result; - DWORD value; - BYTE by_value; - if (GetUnitYT(uid, order, value, action, result)) - { - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is %s result is %s\n", uid, order, value, val_to_str(action, yt_state, "STATE=%d"), val_to_str(result, yt_result, "RESULT=%d")); - if (YTS_SELED == action && YTR_FAIL == result) - { - action = YTS_ABRED; - } - else if (YTS_SELREQ == action && YTR_OVER == result) - { - action = YTS_ABRED; - } - else if (YTS_SELING == action && YTR_OVER == result) - { - action = YTS_ABRED; - } - - if (YTS_SELED == action) - { - SetUnitYT(uid, order, value, YTS_EXEREQ, YTR_IDLE); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_EXEREQ result is YTR_IDLE.\n", uid, order, value); - } - else if (YTS_ABRED == action) - { - SetUnitYT(uid, order, value, YTS_ABRREQ, YTR_IDLE); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_ABRREQ result is YTR_IDLE.\n", uid, order, value); - } - } - if (GetUnitYK(uid, order, by_value, action, result)) - { - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is %s result is %s\n", uid, order, (by_value ? "CLOSE" : "TRIP"), val_to_str(action, yk_state, "STATE=%d"), val_to_str(result, yk_result, "RESULT=%d")); - if (YKS_SELED == action && YKR_FAIL == result) - { - action = YKS_ABRED; - } - else if (YKS_SELREQ == action && YKR_OVER == result) - { - action = YKS_ABRED; - } - else if (YKS_SELING == action && YKR_OVER == result) - { - action = YKS_ABRED; - } - if (YKS_ABRED == action) - { - SetUnitYK(uid, order, by_value, YKS_ABRREQ, YKR_IDLE); - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is YKS_ABRREQ result is YKR_IDLE.\n", uid, order, (by_value ? "CLOSE" : "TRIP")); - } - else if (YKS_SELED == action) - { - SetUnitYK(uid, order, by_value, YKS_EXEREQ, YKR_IDLE); - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is YKS_EXEREQ result is YKR_IDLE.\n", uid, order, (by_value ? "CLOSE" : "TRIP")); - } - } - } - return TRUE; -} - -int CSubModbusTcpProcess::OnPackageReceived(BYTE* pBuf, int count, int ord) -{ - int uid; - CSubModbusTcpProcessItem* pItem; - pItem = (CSubModbusTcpProcessItem *)GetItem(ord); - if (NULL == pItem) return -1; - uid = pItem->GetUnitID(); - if (uid < 0 || uid >= UNIT_NUM) return -1; - //头尾判断。 - WORD usLength; - WORD usTID; - WORD usPID; - - if (count < MB_TCP_FUNC) - { //数据长度不足 - return 0; - } - usLength = pBuf[MB_TCP_LEN] << 8U; - usLength |= pBuf[MB_TCP_LEN + 1]; - if (count < (MB_TCP_UID + usLength)) - { //数据接收未完 - vLog(LOG_WARN, "数据没有接收完成.\n"); - return 0; - } - usPID = pBuf[MB_TCP_PID] << 8U; - usPID |= pBuf[MB_TCP_PID + 1]; - if (usPID != MB_TCP_PROTOCOL_ID) - { //未知协议 - vLog(LOG_ERROR, "未知协议\n"); - return -1; - } - usTID = pBuf[MB_TCP_TID] << 8U; - usTID |= pBuf[MB_TCP_TID + 1]; - usLength = count - MB_TCP_FUNC; - - BYTE *ppucFrame = &pBuf[MB_TCP_FUNC]; - BYTE ucRcvAddress = pBuf[MB_TCP_UID]; - if (ucRcvAddress != pItem->ied_addr && ucRcvAddress != MB_ADDRESS_BROADCAST) - { - vLog(LOG_DEBUG, "数据不是发送给我的.\n"); - return count; - } - BYTE ucFunctionCode = ppucFrame[MB_PDU_FUNC_OFF]; - eMBException eException; - eMBErrorCode eStatus = MB_ENOERR; - - DisplayRxData(pBuf, (MB_TCP_UID + usLength + 1), TRUE, uid); - UnitFeedDog(uid); - eException = MB_EX_ILLEGAL_FUNCTION; - switch (ucFunctionCode) - { - case MB_FUNC_READ_INPUT_REGISTER: - eException = eMBFuncReadInputRegister(pItem, ppucFrame, &usLength); - break; - case MB_FUNC_READ_HOLDING_REGISTER: - eException = eMBFuncReadHoldingRegister(pItem, ppucFrame, &usLength); - break; - case MB_FUNC_WRITE_MULTIPLE_REGISTERS: - eException = eMBFuncWriteMultipleHoldingRegister(pItem, ppucFrame, &usLength); - break; - case MB_FUNC_WRITE_REGISTER: - eException = eMBFuncWriteHoldingRegister(pItem, ppucFrame, &usLength); - break; - case MB_FUNC_READ_COILS: - eException = eMBFuncReadCoils(pItem, ppucFrame, &usLength); - break; - case MB_FUNC_WRITE_SINGLE_COIL: - eException = eMBFuncWriteCoil(pItem, ppucFrame, &usLength); - break; - case MB_FUNC_WRITE_MULTIPLE_COILS: - eException = eMBFuncWriteMultipleCoils(pItem, ppucFrame, &usLength); - break; - case MB_FUNC_READ_DISCRETE_INPUTS: - eException = eMBFuncReadDiscreteInputs(pItem, ppucFrame, &usLength); - break; - default: - break; - - } - if (ucRcvAddress != MB_ADDRESS_BROADCAST) - { - if (eException != MB_EX_NONE) - { - usLength = 0; - ppucFrame[usLength++] = (BYTE)(ucFunctionCode | MB_FUNC_ERROR); - ppucFrame[usLength++] = eException; - } - - eStatus = eMBTCPSend(ucRcvAddress, ppucFrame, usLength); - if (eStatus != MB_ENOERR) - { - vLog(LOG_ERROR, "modbus tcp send error(%d)\n", eStatus); - return -1; - } - } - return (count); -} - -eMBErrorCode CSubModbusTcpProcess::eMBTCPSend(BYTE ucSlaveAddress, const BYTE *pucFrame, WORD usLength) -{ - eMBErrorCode eStatus = MB_ENOERR; - BYTE *pucMBTCPFrame = (BYTE *) pucFrame - MB_TCP_FUNC; - WORD usTCPLength = usLength + MB_TCP_FUNC; - - pucMBTCPFrame[MB_TCP_LEN] = (usLength + 1) >> 8U; - pucMBTCPFrame[MB_TCP_LEN + 1] = (usLength + 1) & 0xFF; - if (WriteData(pucMBTCPFrame, usTCPLength, GetCurOrder())) - { - DisplayTxData(pucMBTCPFrame, usTCPLength, TRUE); - } - else - { - eStatus = MB_EIO; - } - return eStatus; -} - -eMBException CSubModbusTcpProcess::prveMBError2Exception(eMBErrorCode eErrorCode) -{ - eMBException eStatus; - - switch (eErrorCode) - { - case MB_ENOERR: - eStatus = MB_EX_NONE; - break; - case MB_ENOREG: - eStatus = MB_EX_ILLEGAL_DATA_ADDRESS; - break; - case MB_ETIMEDOUT: - eStatus = MB_EX_SLAVE_BUSY; - break; - default: - eStatus = MB_EX_SLAVE_DEVICE_FAILURE; - break; - } - return eStatus; -} - -eMBException CSubModbusTcpProcess::eMBFuncReadInputRegister(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen) -{ - WORD usRegAddress; - WORD usRegCount; - BYTE *pucFrameCur; - - eMBException eStatus = MB_EX_NONE; - eMBErrorCode eRegStatus; - - if (*usLen == (MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN)) - { - usRegAddress = (WORD)(pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8); - usRegAddress |= (WORD)(pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1]); - - usRegCount = (WORD)(pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF] << 8); - usRegCount |= (WORD)(pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF + 1]); - - if ((usRegCount >= 1) && (usRegCount < MB_PDU_FUNC_READ_REGCNT_MAX)) - { - pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; - *usLen = MB_PDU_FUNC_OFF; - - *pucFrameCur++ = MB_FUNC_READ_INPUT_REGISTER; - *usLen += 1; - - *pucFrameCur++ = (BYTE)(usRegCount << 1); - *usLen += 1; - eRegStatus = eMBRegInputCB(pItem, pucFrameCur, usRegAddress, usRegCount); - - if (eRegStatus != MB_ENOERR) - { - eStatus = prveMBError2Exception(eRegStatus); - } - else - { - *usLen += usRegCount << 1; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - return eStatus; -} - -eMBException CSubModbusTcpProcess::eMBFuncWriteHoldingRegister(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen) -{ - WORD usRegAddress; - eMBException eStatus = MB_EX_NONE; - eMBErrorCode eRegStatus; - - if (*usLen == (MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN)) - { - usRegAddress = (WORD)(pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF] << 8); - usRegAddress |= (WORD)(pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF + 1]); - - eRegStatus = eMBRegHoldingCB(pItem, &pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF], usRegAddress, 1, MB_REG_WRITE); - - if (eRegStatus != MB_ENOERR) - { - eStatus = prveMBError2Exception(eRegStatus); - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - return eStatus; -} - -eMBException CSubModbusTcpProcess::eMBFuncWriteMultipleHoldingRegister(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen) -{ - WORD usRegAddress; - WORD usRegCount; - BYTE ucRegByteCount; - - eMBException eStatus = MB_EX_NONE; - eMBErrorCode eRegStatus; - - if (*usLen >= (MB_PDU_FUNC_WRITE_MUL_SIZE_MIN + MB_PDU_SIZE_MIN)) - { - usRegAddress = (WORD)(pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF] << 8); - usRegAddress |= (WORD)(pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF + 1]); - - usRegCount = (WORD)(pucFrame[MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF] << 8); - usRegCount |= (WORD)(pucFrame[MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF + 1]); - - ucRegByteCount = pucFrame[MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF]; - - if ((usRegCount >= 1) && (usRegCount <= MB_PDU_FUNC_WRITE_MUL_REGCNT_MAX) && (ucRegByteCount == (BYTE) (usRegCount << 1))) - { - eRegStatus = eMBRegHoldingCB(pItem, &pucFrame[MB_PDU_FUNC_WRITE_MUL_VALUES_OFF], usRegAddress, usRegCount, MB_REG_WRITE); - - if (eRegStatus != MB_ENOERR) - { - eStatus = prveMBError2Exception(eRegStatus); - } - else - { - *usLen = MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - return eStatus; -} - -eMBException CSubModbusTcpProcess::eMBFuncReadHoldingRegister(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen) -{ - WORD usRegAddress; - WORD usRegCount; - BYTE *pucFrameCur; - - eMBException eStatus = MB_EX_NONE; - eMBErrorCode eRegStatus; - - if (*usLen == (MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN)) - { - usRegAddress = (WORD)(pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8); - usRegAddress |= (WORD)(pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1]); - - usRegCount = (WORD)(pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF] << 8); - usRegCount = (WORD)(pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF + 1]); - - if ((usRegCount >= 1) && (usRegCount <= MB_PDU_FUNC_READ_REGCNT_MAX)) - { - pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; - *usLen = MB_PDU_FUNC_OFF; - - *pucFrameCur++ = MB_FUNC_READ_HOLDING_REGISTER; - *usLen += 1; - - *pucFrameCur++ = (BYTE) (usRegCount << 1); - *usLen += 1; - - eRegStatus = eMBRegHoldingCB(pItem, pucFrameCur, usRegAddress, usRegCount, MB_REG_READ); - - if (eRegStatus != MB_ENOERR) - { - eStatus = prveMBError2Exception(eRegStatus); - } - else - { - *usLen += usRegCount << 1; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - return eStatus; -} - -eMBException CSubModbusTcpProcess::eMBFuncReadCoils(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen) -{ - WORD usRegAddress; - WORD usCoilCount; - BYTE ucNBytes; - BYTE *pucFrameCur; - - eMBException eStatus = MB_EX_NONE; - eMBErrorCode eRegStatus; - - if (*usLen == (MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN)) - { - usRegAddress = (WORD)(pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8); - usRegAddress |= (WORD)(pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1]); - - usCoilCount = (WORD)(pucFrame[MB_PDU_FUNC_READ_COILCNT_OFF] << 8); - usCoilCount |= (WORD)(pucFrame[MB_PDU_FUNC_READ_COILCNT_OFF + 1]); - - if ((usCoilCount >= 1) && (usCoilCount < MB_PDU_FUNC_READ_COILCNT_MAX)) - { - pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; - *usLen = MB_PDU_FUNC_OFF; - - *pucFrameCur++ = MB_FUNC_READ_COILS; - *usLen += 1; - - if ((usCoilCount & 0x0007) != 0) - { - ucNBytes = (BYTE)((usCoilCount >> 3) + 1); - } - else - { - ucNBytes = (BYTE)(usCoilCount >> 3); - } - *pucFrameCur++ = ucNBytes; - *usLen += 1; - - eRegStatus = eMBRegCoilsCB(pItem, pucFrameCur, usRegAddress, usCoilCount, MB_REG_READ); - - if (eRegStatus != MB_ENOERR) - { - eStatus = prveMBError2Exception(eRegStatus); - } - else - { - - *usLen += ucNBytes;; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - } - else - { - - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - return eStatus; -} - -eMBException CSubModbusTcpProcess::eMBFuncWriteCoil(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen) -{ - WORD usRegAddress; - BYTE ucBuf[2]; - - eMBException eStatus = MB_EX_NONE; - eMBErrorCode eRegStatus; - - if (*usLen == (MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN)) - { - usRegAddress = (WORD)(pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF] << 8); - usRegAddress |= (WORD)(pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF + 1]); - - if ((pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF + 1] == 0x00) && ((pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0xFF) || (pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0x00))) - { - ucBuf[1] = 0; - if (pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0xFF) - { - ucBuf[0] = 1; - } - else - { - ucBuf[0] = 0; - } - eRegStatus = eMBRegCoilsCB(pItem, &ucBuf[0], usRegAddress, 1, MB_REG_WRITE); - - if (eRegStatus != MB_ENOERR) - { - eStatus = prveMBError2Exception(eRegStatus); - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - } - else - { - - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - return eStatus; -} - -eMBException CSubModbusTcpProcess::eMBFuncWriteMultipleCoils(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen) -{ - WORD usRegAddress; - WORD usCoilCnt; - BYTE ucByteCount; - BYTE ucByteCountVerify; - - eMBException eStatus = MB_EX_NONE; - eMBErrorCode eRegStatus; - - if (*usLen > (MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN)) - { - usRegAddress = (WORD)(pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF] << 8); - usRegAddress |= (WORD)(pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF + 1]); - - usCoilCnt = (WORD)(pucFrame[MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF] << 8); - usCoilCnt |= (WORD)(pucFrame[MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF + 1]); - - ucByteCount = pucFrame[MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF]; - - if ((usCoilCnt & 0x0007) != 0) - { - ucByteCountVerify = (BYTE)(usCoilCnt / 8 + 1); - } - else - { - ucByteCountVerify = (BYTE)(usCoilCnt / 8); - } - - if ((usCoilCnt >= 1) && - (usCoilCnt <= MB_PDU_FUNC_WRITE_MUL_COILCNT_MAX) && - (ucByteCountVerify == ucByteCount)) - { - eRegStatus = eMBRegCoilsCB(pItem, &pucFrame[MB_PDU_FUNC_WRITE_MUL_VALUES_OFF], usRegAddress, usCoilCnt, MB_REG_WRITE); - - if (eRegStatus != MB_ENOERR) - { - eStatus = prveMBError2Exception(eRegStatus); - } - else - { - *usLen = MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - return eStatus; -} - -eMBException CSubModbusTcpProcess::eMBFuncReadDiscreteInputs(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen) -{ - WORD usRegAddress; - WORD usDiscreteCnt; - BYTE ucNBytes; - BYTE *pucFrameCur; - - eMBException eStatus = MB_EX_NONE; - eMBErrorCode eRegStatus; - - if (*usLen == (MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN)) - { - usRegAddress = (WORD)(pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8); - usRegAddress |= (WORD)(pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1]); - - usDiscreteCnt = (WORD)(pucFrame[MB_PDU_FUNC_READ_DISCCNT_OFF] << 8); - usDiscreteCnt |= (WORD)(pucFrame[MB_PDU_FUNC_READ_DISCCNT_OFF + 1]); - - if ((usDiscreteCnt >= 1) && (usDiscreteCnt < MB_PDU_FUNC_READ_DISCCNT_MAX)) - { - pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; - *usLen = MB_PDU_FUNC_OFF; - - *pucFrameCur++ = MB_FUNC_READ_DISCRETE_INPUTS; - *usLen += 1; - - if ((usDiscreteCnt & 0x0007) != 0) - { - ucNBytes = (BYTE) ((usDiscreteCnt >> 3) + 1); - } - else - { - ucNBytes = (BYTE) (usDiscreteCnt >> 3); - } - *pucFrameCur++ = ucNBytes; - *usLen += 1; - - eRegStatus = eMBRegDiscreteCB(pItem, pucFrameCur, usRegAddress, usDiscreteCnt); - - if (eRegStatus != MB_ENOERR) - { - eStatus = prveMBError2Exception(eRegStatus); - } - else - { - *usLen += ucNBytes;; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - } - else - { - eStatus = MB_EX_ILLEGAL_DATA_VALUE; - } - return eStatus; -} - -eMBErrorCode CSubModbusTcpProcess::eMBRegInputCB(CSubModbusTcpProcessItem *pItem, BYTE* pucRegBuffer, WORD usAddress, WORD usNRegs) -{ - eMBErrorCode eStatus = MB_ENOERR; - int iRegIndex; - - if ((usAddress >= 0) && (usAddress + usNRegs <= 0 + pItem->m_InputregCount)) - { - iRegIndex = (int)(usAddress - 0); - while (usNRegs > 0) - { - *pucRegBuffer++ = (BYTE)(pItem->m_pInputRegTable[iRegIndex] >> 8); - *pucRegBuffer++ = (BYTE)(pItem->m_pInputRegTable[iRegIndex] & 0xFF); - iRegIndex++; - usNRegs--; - } - } - else - { - eStatus = MB_ENOREG; - } - - return eStatus; -} - -eMBErrorCode CSubModbusTcpProcess::eMBRegHoldingCB(CSubModbusTcpProcessItem *pItem, BYTE* pucRegBuffer, WORD usAddress, WORD usNRegs, eMBRegisterMode eMode) -{ - eMBErrorCode eStatus = MB_ENOERR; - WORD usRegHoldingValue; - int iRegIndex; - int uid; - - uid = pItem->GetUnitID(); - - if ((usAddress >= 0) && (usAddress + usNRegs <= 0 + pItem->m_HoldingRegCount)) - { - iRegIndex = (int)(usAddress - 0); - switch (eMode) - { - case MB_REG_READ: - while (usNRegs > 0) - { - *pucRegBuffer++ = (BYTE)(pItem->m_pHoldingRegTable[iRegIndex] >> 8); - *pucRegBuffer++ = (BYTE)(pItem->m_pHoldingRegTable[iRegIndex] & 0xFF); - iRegIndex++; - usNRegs--; - } - break; - case MB_REG_WRITE: - while (usNRegs > 0) - { - usRegHoldingValue = *pucRegBuffer++ << 8; - usRegHoldingValue |= *pucRegBuffer++; - //写寄存器 - SetUnitYT(uid, iRegIndex, usRegHoldingValue, YTS_EXEREQ, YTR_IDLE); - vLog(LOG_DEBUG, "Unit(%d) set point(%d) %d state is YTS_EXEREQ result is YTR_IDLE.\n", uid, iRegIndex, usRegHoldingValue); - iRegIndex++; - usNRegs--; - } - } - } - else - { - eStatus = MB_ENOREG; - } - return eStatus; -} - - -eMBErrorCode CSubModbusTcpProcess::eMBRegCoilsCB(CSubModbusTcpProcessItem *pItem, BYTE* pucRegBuffer, WORD usAddress, WORD usNCoils, eMBRegisterMode eMode) -{ - eMBErrorCode eStatus = MB_ENOERR; - WORD usCoilGroups = ((usNCoils - 1) / 8 + 1); - BYTE ucStatus = 0; - BYTE usRegCoilsValue; - BYTE ucBits = 0; - BYTE ucDisp = 0; - int iRegIndex = usAddress - 0; - int uid; - - uid = pItem->GetUnitID(); - if ((usAddress >= 0) && (usAddress + usNCoils <= 0 + pItem->m_CoilRegCount)) - { - iRegIndex = (int)(usAddress - 0); - switch (eMode) - { /* Pass current register values to the protocol stack. */ - case MB_REG_READ: - while (usCoilGroups--) - { - ucDisp = 0; - ucBits = 8; - ucStatus = 0; - while((usNCoils--) != 0 && (ucBits--) != 0) - { - ucStatus |= (pItem->m_pCoilRegTable[iRegIndex++] << (ucDisp++)); - } - *pucRegBuffer++ = ucStatus; - } - break; - case MB_REG_WRITE: - while (usCoilGroups--) - { - ucStatus = *pucRegBuffer++; - ucBits = 8; - while ((usNCoils--) != 0 && (ucBits--) != 0) - { - usRegCoilsValue = ucStatus & 0X01; - //写线圈 - SetUnitYK(uid, iRegIndex, usRegCoilsValue, YKS_SELREQ, YKR_IDLE); - vLog(LOG_WARN, "Unit(%d) yk(%d) %s state is YKS_EXEREQ result is YKR_IDLE.\n", uid, iRegIndex, (usRegCoilsValue ? "CLOSE" : "TRIP")); - iRegIndex++; - ucStatus >>= 1; - } - } - } - } - else - { - eStatus = MB_ENOREG; - } - return eStatus; -} - -eMBErrorCode CSubModbusTcpProcess::eMBRegDiscreteCB(CSubModbusTcpProcessItem *pItem, BYTE* pucRegBuffer, WORD usAddress, WORD usNDiscrete) -{ - eMBErrorCode eStatus = MB_ENOERR; - WORD usDiscreteGroups = ((usNDiscrete - 1) / 8 + 1); - BYTE ucStatus = 0; - BYTE ucBits = 0; - BYTE ucDisp = 0; - int iRegIndex = usAddress - 0; - - if ((usAddress >= 0) && (usAddress + usNDiscrete <= 0 + pItem->m_DiscreteRegCount)) - { - iRegIndex = (int)(usAddress - 0); - while (usDiscreteGroups--) - { - ucDisp = 0; - ucBits = 8; - ucStatus = 0; - while((usNDiscrete--) != 0 && (ucBits--) != 0) - { - ucStatus |= (pItem->m_pDiscreteRegTable[iRegIndex++] << (ucDisp++)); - } - *pucRegBuffer++ = ucStatus; - } - } - else - { - eStatus = MB_ENOREG; - } - return eStatus; -} diff --git a/das-dn/submodbustcp/sub_modbus_rtu_tcp.h b/das-dn/submodbustcp/sub_modbus_rtu_tcp.h deleted file mode 100644 index 99c1aa29..00000000 --- a/das-dn/submodbustcp/sub_modbus_rtu_tcp.h +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef _ZJD_SUB_MODBUS_RTU_TCP_PROCESS_H_ -#define _ZJD_SUB_MODBUS_RTU_TCP_PROCESS_H_ - -#include "netproc.h" -#include "modbus_def.h" -#include - -#pragma pack(1) -typedef struct -{ - struNetWorkOption net; - BYTE defaultYCType; -} struSubModbusTCPOption; -#pragma pack() - -typedef std::vector vecInt; - -class CSubModbusTcpProcessItem : public CNetProcessItem -{ -public: - BYTE ied_addr; - WORD m_nNum; - - short m_CoilRegCount; - short m_DiscreteRegCount; - short m_HoldingRegCount; - short m_InputregCount; - - BYTE *m_pCoilRegTable; - BYTE *m_pDiscreteRegTable; - WORD *m_pHoldingRegTable; - WORD *m_pInputRegTable; - -public: - CSubModbusTcpProcessItem(); - virtual ~CSubModbusTcpProcessItem(); - - void Attach(int uid, int sock, DWORD peer_addr, WORD peer_port); - void Release(void); - -}; - -class CSubModbusTcpProcess : public CNetProcess -{ -public: - CSubModbusTcpProcess(); - virtual ~CSubModbusTcpProcess(); - - CNetProcessItem *CreateItem(int ord); - void DestroyItem(int ord, BOOLEAN bDeleted = FALSE); - - virtual BOOLEAN OnPreCreate(int id); - virtual BOOLEAN Run(void); - virtual BOOLEAN OnTimer(void); -private: - struSubModbusTCPOption m_option; - BYTE m_YC_Type; - enum - { - M_ME_NA, - M_ME_NC - }; - - vecInt m_CoilRegTable; - vecInt m_DiscreteTable; - vecInt m_HoldingRegTable; - vecInt m_InputRegTable; - -private: - int OnPackageReceived(BYTE* pBuf, int count, int ord /* = -1 */); - BOOLEAN OnReceiveData(CSubModbusTcpProcessItem *pItem, BYTE* pData, int count, int uid); - - eMBErrorCode eMBTCPSend(BYTE ucSlaveAddress, const BYTE *pucFrame, WORD usLength); - - eMBException prveMBError2Exception(eMBErrorCode eErrorCode); - eMBException eMBFuncReadInputRegister(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen); - eMBException eMBFuncReadHoldingRegister(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen); - eMBException eMBFuncWriteHoldingRegister(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen); - eMBException eMBFuncWriteMultipleHoldingRegister(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen); - eMBException eMBFuncReadCoils(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen); - eMBException eMBFuncWriteCoil(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen); - eMBException eMBFuncWriteMultipleCoils(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen); - eMBException eMBFuncReadDiscreteInputs(CSubModbusTcpProcessItem *pItem, BYTE* pucFrame, WORD* usLen); - - - eMBErrorCode eMBRegInputCB(CSubModbusTcpProcessItem *pItem, BYTE* pucRegBuffer, WORD usAddress, WORD usNRegs); - eMBErrorCode eMBRegHoldingCB(CSubModbusTcpProcessItem *pItem, BYTE* pucRegBuffer, WORD usAddress, WORD usNRegs, eMBRegisterMode eMode); - eMBErrorCode eMBRegCoilsCB(CSubModbusTcpProcessItem *pItem, BYTE* pucRegBuffer, WORD usAddress, WORD usNCoils, eMBRegisterMode eMode); - eMBErrorCode eMBRegDiscreteCB(CSubModbusTcpProcessItem *pItem, BYTE* pucRegBuffer, WORD usAddress, WORD usNDiscrete); -}; - -#endif //_ZJD_SUB_MODBUS_RTU_TCP_PROCESS_H_