bool ConfigTool::AddConfigFromFile(const char *filename, const char *prefix) { char *line=new char[line_max]; char *key=new char[line_max]; char *value=new char[line_max]; ifstream config_file(filename); if(!config_file.is_open()) { char *fn_guess=new char[line_max]; int ret=c99_snprintf(fn_guess, line_max, "../%s", filename); if(ret>=line_max) //error handling { printf("c99_snprintf overflow in ConfigTool::AddConfigFromFile\n"); exit(-1); } config_file.clear(); config_file.open(fn_guess); if(!config_file.is_open()) { printf("Cannot find \"%s\" nor \"%s\"\n", filename, fn_guess); config_file.close(); delete[] value; delete[] key; delete[] line; return false; } delete[] fn_guess; } while(config_file.getline(line, line_max)) { if(strstr(line, "//")!=NULL) continue; //ignore comments char *sep_pos=strchr(line, '='); if(sep_pos!=NULL) { int pos=int(sep_pos-line)/sizeof(char); int key_len=pos; int value_len=(int)strlen(line)-1-key_len; memcpy(key, line, sizeof(char)*key_len); key[key_len]='\0'; memcpy(value, sep_pos+1, sizeof(char)*value_len); value[value_len]='\0'; TrimSpace(key); TrimSpace(value); the_map[CombinedKey(key, prefix)]=value; } } config_file.close(); map_str_match=false; //invalidate string representation buffer delete[] value; delete[] key; delete[] line; return true; }
void AddConfigFromCmdLine(ConfigType &cr,int argc,char** argv) { int i=0; while (i<argc) { while ((i<argc)&&(argv[i][0]!='-')) i++; // shortcut condition if (i+1<argc) { char* key=&(argv[i][1]); char* value=argv[i+1]; TrimSpace(key); TrimSpace(value); cr[key]=value; i+=2; } else return; } }
Resource::Resource(StringMap & inputmap,string keys) { string dvalue=keys; for(string::size_type index=0; index !=dvalue.size(); ++index) if(dvalue[index]==',') dvalue[index]='\n'; std::istringstream input_temp(dvalue); string tempkey; set<string> keyset; set<string>::iterator it; try{ while( std::getline(input_temp,tempkey) ) { tempkey=TrimSpace(tempkey); word *pv=NULL; if(!tempkey.empty() && ( pv=inputmap.find(tempkey.c_str()) )!=NULL) m_ResourceDict.insert(tempkey.c_str(), *pv); } } catch(...) { m_ResourceDict.clear(); cout<<"Exception to creat fast-query-resource by keys."<<endl; } }
bool CIni::GetValue(int nPos,char* pszBuf, int nBufLen,int* pRet) { if(pszBuf==NULL|| nBufLen<=0||nPos<0 ||nPos>=m_nDateLen) { return false; } int nStart = nPos+1; int nEnd; while (nPos!=m_nDateLen &&m_pData[nPos]!='\n' ) { nPos++; } if( nPos - nStart > nBufLen) //fail return false; else if(m_pData[nPos] =='\n' ) { } else if(m_pData[nPos] ==' ') { } nEnd = nPos-1; memcpy(pszBuf, &m_pData[nStart], nEnd-nStart ); TrimSpace(pszBuf); if(pRet) { *pRet= atoi(pszBuf); } return true; }
void ConfigTool::AddConfigFromCommandLine(int argc, char **argv, const char *prefix) { int i=0; while(i<argc) { while((i<argc)&&(argv[i][0]!='-')) i++; if(i+1<argc) { char *key=argv[i]+1; char *value=argv[i+1]; TrimSpace(key); TrimSpace(value); the_map[CombinedKey(key, prefix)]=value; i+=2; } else return; } map_str_match=false; //invalidate string representation buffer }
//从脚本文件的label处开始读取脚本命令,结果存入scripts bool CScript::Run(char* strFilePath, std::queue<std::string>* scripts, char* strLabel) { char* strCmd; std::string strCmdName; //打开脚本文件 if(OpenFile(strFilePath)) { m_nFileOffset = 0; //若传入指定label,计算指定label的文件偏移量 if(strcmp(strLabel,"") != 0) { if (FindLabel(strLabel) == 0) return false; } while(1) { strCmd = ReadCommand(); //读取一条命令 TrimSpace(strCmd); //去除首尾空字符 strCmdName.assign(GetCommandName(strCmd)); //命令为return,结束当前读取操作 if(strlen(strCmd) == 0 || stricmp(strCmd, "return") == 0) { SAFE_DELETE(strCmd); strCmdName.clear(); return true; } //读取的为标号,跳过该标号 else if (strCmd[strlen(strCmd)-1] == ':') { SAFE_DELETE(strCmd); strCmdName.clear(); continue; } // RunCommand(strCmd); //执行 scripts->push(std::string(strCmd)); //交命令加入结果列表中 SAFE_DELETE(strCmd); strCmdName.clear(); } } SAFE_DELETE(strCmd); strCmdName.clear(); return false; }
void AddConfigFromFile(ConfigType &cr,const char* filename) { const int LINE_LEN=1024; char line[LINE_LEN],key[LINE_LEN],value[LINE_LEN]; ifstream br(filename); if (! br.is_open()) { printf("Error opening file \"%s\"",filename); exit (1); } while (br.getline(line,LINE_LEN)){ if (strstr(line,"//")!=NULL) continue; // remove comments char* chPos=strchr(line,'='); if (chPos!=NULL) { int pos=((int)(chPos-line))/sizeof(char); int keyLen=pos; int valueLen=strlen(line)-1-keyLen; memcpy(key,&line[0],keyLen); key[keyLen]='\0'; memcpy(value,&line[pos+1],valueLen); value[valueLen]='\0'; TrimSpace(key); TrimSpace(value); cr[key]=value; } } br.close(); }
Smt_Uint TASTConnector::ParseLine(Smt_String src, Smt_String &key, Smt_String &value ) { //012345 //XX: XX Smt_Int nPos = src.find(":"); if( nPos > 0 ) { key = src.substr(0, nPos); value = src.substr( nPos + 1, src.length() - (nPos+1) ); value = TrimSpace( value ); } else { key = ""; value = ""; } return Smt_Success; }
char *CXMLParser::RemoveXMLDeclare(char *cText) { ///////////// //ljr ///分析xml头标识是否正确,并去掉 cText = TrimSpace(cText); if(cText[0] != '<' || cText[1] != '?') { return NULL; } cText += 2; while(*cText != '>') { cText++; } cText++; return cText; /////////////////////////// }
void IdcUser::PutLocalSEId(std::string str) { try{ string dvalue=str; for(string::size_type index=0; index !=dvalue.size(); ++index) if(dvalue[index]==',') dvalue[index]='\n'; std::istringstream input_temp(dvalue); string tempkey; while( std::getline(input_temp,tempkey) ) { tempkey=TrimSpace(tempkey); set_LocalSEId.insert(atoi(tempkey.c_str())); } } catch(...) { printf("Exception to PutLocalSEId.\n"); } }
bool read_UART(char* cmd_str, uint8 cmd_len , const char* screen_print) { int16 ret_val = 0; bool received = false; if(cmd_str == NULL) { UART_PRINT("read_UART failed, cmd_str is NULL\n"); return false; } if(cmd_len == 0) { UART_PRINT("read_UART failed, cmd_len is 0\n"); return false; } do { if(cmd_str == NULL) { UART_PRINT("\nScreen Print is empty, Please type#"); } else { UART_PRINT("\n%s#", screen_print); } ret_val = GetCmd(cmd_str, cmd_len); if(ret_val > 0) { ret_val = TrimSpace(cmd_str); if(cmd_str!=NULL) { cmd_str[ret_val] = '\0'a received = true; } } }while(!received) return received; }
int CIni::FindKey(const char* pszKey, int nStartPos) { if( pszKey==NULL) return -1; char szKey[MAX_INDEX_LEN]={0}; int i = nStartPos; while ( i< m_nDateLen && m_pData[i]!='[' ) { int j = i; while( j < m_nDateLen && m_pData[j]!='\n'&& m_pData[j]!= '['&& m_pData[j]!='=') { j++; } //fail must return if( j>=m_nDateLen || j-i >=MAX_KEY_LEN || m_pData[j]=='[') return -1; else if(m_pData[j]=='\n') //new line? { i = j+1; } else if ( m_pData[j]=='=') //find '=' , { memset(szKey,0,sizeof(szKey)); memcpy(szKey, &m_pData[i], j-i); TrimSpace(szKey); if( strcmp(szKey, pszKey)==0) return j; else i= j+1; } } return -1; }
int main() { std::wstring excelFile = _XEVOL_ABSPATH_(L"动作列表.xls"); std::wstring excelFilex = _XEVOL_ABSPATH_(L"动作列表.xlsx"); IExcelWriter* pExcel = createExcelWriter(); XEVOL_LOG_REDIR(_XEVOL_ABSPATH_(L"动作列表.log.txt")); if(pExcel->init(excelFile.c_str() , false ) == false) { pExcel->ReleaseObject(); pExcel = NULL; } pExcel = createExcelWriter(); if(pExcel->init(excelFilex.c_str() , false ) == false) { pExcel->ReleaseObject(); pExcel = NULL; } if(pExcel == NULL) { wchar_t file_name[512]={0}; OPENFILENAMEW ofn; ZeroMemory(&ofn, sizeof(OPENFILENAMEW)); ofn.lStructSize = sizeof(OPENFILENAMEW); ofn.hwndOwner = ::GetActiveWindow(); ofn.lpstrFile = file_name; ofn.nMaxFile = 512; ofn.lpstrFilter = L"Excel文件(*.xlsx;xls)\0*.xlsx;xls\0所有文件(*.*)\0*.*\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.lpstrDefExt = L"xlsx"; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if(GetOpenFileNameW(&ofn) == FALSE) { return 1; } excelFilex = file_name; pExcel = createExcelWriter(); if(pExcel->init(excelFilex.c_str() , false ) == false) { pExcel->ReleaseObject(); pExcel = NULL; } } IExcelSheet* pActioListSheet = NULL; pActioListSheet = pExcel->get_Sheet((int)1); if(pActioListSheet == NULL) { XSAFE_RELEASEOBJECT(pExcel); return 1; } xXmlDocument doc; doc.load(_XEVOL_ABSPATH_(L".\\动作列表.xml")); xXmlNode* pRootNode =doc.root(); if(pRootNode == NULL) { pRootNode = doc.insertNode(L"所有动作"); } int nBlankLine = 0; int iLine = 2; std::wstring lastMaxFile = L""; while(1) { wchar_t startFrame[256] = {0}; wchar_t endFrame [256] = {0}; wchar_t actionName[256] = {0}; wchar_t maxFile [256] = {0}; wchar_t actionTime[256] = {0}; pActioListSheet->get_Value(1 , iLine , startFrame, 256); pActioListSheet->get_Value(2 , iLine , endFrame , 256); pActioListSheet->get_Value(3 , iLine , actionName, 256); pActioListSheet->get_Value(4 , iLine , maxFile , 256); pActioListSheet->get_Value(5 , iLine , actionTime, 256); iLine ++; nBlankLine ++; if(wcslen_x(startFrame) > 0 ) { nBlankLine = 0; } if(nBlankLine > 10) break; if(wcslen_x(maxFile) != 0) { lastMaxFile = maxFile; } if( wcslen_x(startFrame) == 0 || wcslen_x(endFrame) == 0 || wcslen_x(actionName) == 0 ) { continue; } std::wstring _actionName = TrimSpace(actionName); std::wstring _maxFileName = TrimSpace(lastMaxFile.c_str() ); if(_maxFileName.find(L".max") == std::wstring::npos && _maxFileName.find(L".Max") == std::wstring::npos && _maxFileName.find(L".MAX") == std::wstring::npos) { _maxFileName += L".max"; } for(int i = 0 ; i < pRootNode->countNode() ; i ++) { xXmlNode* pActionNode = pRootNode->findNode(i); if(pActionNode->value(L"ActionName") == _actionName ) { XEVOL_LOG(eXL_ERROR_FALT , L"动作名重复 name=%s " , _actionName.c_str() ); XEVOL_LOG(eXL_ERROR_FALT , L"原始[%s , %d-%d] " , pActionNode->value(L"MaxFile") , pActionNode->int_value(L"StartFrame"), pActionNode->int_value(L"EndFrame") ); XEVOL_LOG(eXL_ERROR_FALT , L"重复[%s , %d-%d] \n" , _maxFileName.c_str() , startFrame , endFrame ); continue; } } xXmlNode* pActionNode = pRootNode->insertNode(L"动作"); pActionNode->setValue(L"StartFrame" , startFrame); pActionNode->setValue(L"EndFrame" , endFrame ); pActionNode->setValue(L"ActionName" , _actionName.c_str() ); pActionNode->setValue(L"MaxFile" , _maxFileName.c_str() ); if(wcslen_x(actionTime) > 0) { pActionNode->setValue(L"DurTime" , actionTime); } } system("PAUSE"); doc.save(_XEVOL_ABSPATH_(L".\\动作列表.xml")); XSAFE_RELEASEOBJECT(pActioListSheet); pExcel->close(); XSAFE_RELEASEOBJECT(pExcel); XEVOL_LOG_CLOSE(); return 0; }
//***************************************************************************** // //! Network_IF_ConnectAP Connect to an Access Point using the specified SSID //! //! \param[in] pcSsid is a string of the AP's SSID //! \param[in] SecurityParams is Security parameter for AP //! //! \return On success, zero is returned. On error, -ve value is returned // //***************************************************************************** long Network_IF_ConnectAP(char *pcSsid, SlSecParams_t SecurityParams) { #ifndef NOTERM char acCmdStore[128]; unsigned short usConnTimeout; unsigned char ucRecvdAPDetails; #endif long lRetVal; unsigned long ulIP = 0; unsigned long ulSubMask = 0; unsigned long ulDefGateway = 0; unsigned long ulDns = 0; // // Disconnect from the AP // Network_IF_DisconnectFromAP(); // // This triggers the CC3200 to connect to specific AP // lRetVal = sl_WlanConnect((signed char *)pcSsid, strlen((const char *)pcSsid), NULL, &SecurityParams, NULL); ASSERT_ON_ERROR(lRetVal); // // Wait for ~10 sec to check if connection to desire AP succeeds // while(g_usConnectIndex < 15) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif MAP_UtilsDelay(8000000); if(IS_CONNECTED(g_ulStatus) && IS_IP_ACQUIRED(g_ulStatus)) { break; } g_usConnectIndex++; } #ifndef NOTERM // // Check and loop until AP connection successful, else ask new AP SSID name // while(!(IS_CONNECTED(g_ulStatus)) || !(IS_IP_ACQUIRED(g_ulStatus))) { // // Disconnect the previous attempt // Network_IF_DisconnectFromAP(); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION); CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED); UART_PRINT("Device could not connect to %s\n\r",pcSsid); do { ucRecvdAPDetails = 0; UART_PRINT("\n\r\n\rPlease enter the AP(open) SSID name # "); // // Get the AP name to connect over the UART // lRetVal = GetCmd(acCmdStore, sizeof(acCmdStore)); if(lRetVal > 0) { // remove start/end spaces if any lRetVal = TrimSpace(acCmdStore); // // Parse the AP name // strncpy(pcSsid, acCmdStore, lRetVal); if(pcSsid != NULL) { ucRecvdAPDetails = 1; pcSsid[lRetVal] = '\0'; } } }while(ucRecvdAPDetails == 0); // // Reset Security Parameters to OPEN security type // SecurityParams.Key = (signed char *)""; SecurityParams.KeyLen = 0; SecurityParams.Type = SL_SEC_TYPE_OPEN; UART_PRINT("\n\rTrying to connect to AP: %s ...\n\r",pcSsid); // // Get the current timer tick and setup the timeout accordingly // usConnTimeout = g_usConnectIndex + 15; // // This triggers the CC3200 to connect to specific AP // lRetVal = sl_WlanConnect((signed char *)pcSsid, strlen((const char *)pcSsid), NULL, &SecurityParams, NULL); ASSERT_ON_ERROR(lRetVal); // // Wait ~10 sec to check if connection to specifed AP succeeds // while(!(IS_CONNECTED(g_ulStatus)) || !(IS_IP_ACQUIRED(g_ulStatus))) { #ifndef SL_PLATFORM_MULTI_THREADED _SlNonOsMainLoopTask(); #else osi_Sleep(1); #endif MAP_UtilsDelay(8000000); if(g_usConnectIndex >= usConnTimeout) { break; } g_usConnectIndex++; } } #endif // // Put message on UART // UART_PRINT("\n\rDevice has connected to %s\n\r",pcSsid); // // Get IP address // lRetVal = Network_IF_IpConfigGet(&ulIP,&ulSubMask,&ulDefGateway,&ulDns); ASSERT_ON_ERROR(lRetVal); // // Send the information // UART_PRINT("Device IP Address is %d.%d.%d.%d \n\r\n\r", SL_IPV4_BYTE(ulIP, 3),SL_IPV4_BYTE(ulIP, 2), SL_IPV4_BYTE(ulIP, 1),SL_IPV4_BYTE(ulIP, 0)); return 0; }
bool CJMYPassPay::WriteData(string &srcCmd) { if (-1 == m_fd) { PrintLog("写数据失败,串口已关闭。"); return false; } // 判断读线程是否存在 if (ESRCH == pthread_kill(m_thid, 0)) { PrintLog("线程已退出,重启读数据线程"); pthread_create(&m_thid, NULL, ReadThread, (void *)(&m_fd)); } static char srcBuff[CMD_BUF_SIZE] = {0}; // 存放原始字符串 static uint8 sendBuf[CMD_BUF_SIZE] = {0}; // 存储待发送的十六进制命令 static char tempBuf[CMD_BUF_SIZE] = {0}; // 临时存放去除空格的命令字符串 int srcLen = srcCmd.length(); // 待发送的命令长度 if (0 >= srcLen || srcLen > CMD_BUF_SIZE - 4) // 预留两个字节的长度和1个自己的BCC校验码 { PrintLog("cmd length must low then %d", CMD_BUF_SIZE - 4); return false; } memcpy(srcBuff, srcCmd.c_str(), srcLen); memset(tempBuf, 0x00, sizeof(tempBuf)); int tempLen = TrimSpace(tempBuf, srcBuff, srcLen); if (tempLen % 2 != 0) { PrintLog("cmd len must mod 2 == 0"); return false; } // 计算命令串的总长度,不包括一个字节的BCC长度,命令长度 + 两个字节的长度。 memset(sendBuf, 0x00, sizeof(sendBuf)); StrToHex(&sendBuf[3], tempBuf, tempLen); int cmdLen = tempLen / 2; // 加上两个字节的长度,加一个字节的设备地址 cmdLen += 3; sendBuf[0] = cmdLen & 0XFF00; sendBuf[1] = cmdLen & 0X00FF; sendBuf[2] = 0X00; // 计算BCC校验码 uint8 bcc = 0; CaculateBCC(sendBuf, cmdLen, bcc); // 命令尾部加上bcc校验码 sendBuf[cmdLen] = bcc; cmdLen += 1; char temp[CMD_BUF_SIZE]; memset(temp, 0x00, sizeof(temp)); for (int i = 0; i < cmdLen; i++) { sprintf(temp + i * 3, "%02X ", sendBuf[i]); } srcCmd = temp; int left_len = cmdLen; // 待发送的命令长度 int nfds = 0; // 可写句柄数量 fd_set write_fds; // 句柄集合 struct timeval tv; // select 等待时间 tv.tv_sec = 0; tv.tv_usec = 1; FD_ZERO(&write_fds); FD_SET(m_fd, &write_fds); uint8 *p = sendBuf; while (left_len > 0) { nfds = select(m_fd + 1, NULL, &write_fds, NULL, &tv); if (nfds < 0) { break; } else if(0 == nfds) { //PrintLog("no fd use write!"); break; } int nwrite = write(m_fd, p, left_len); if (nwrite > 0) { left_len -= nwrite; p += nwrite; } else { break; } } if (left_len != 0) { return false; } return true; }
/************************************************************************ 结点读取函数 ReadXMLNode 由递归改为循环 参数: pPreNode 根结点 返回: 正常值: >=0 异常值: <0 备注: 1、本函数用于读取结点树. ************************************************************************/ int CXMLParser::ReadXMLNode(CXMLNode *pPreNode) { if(!m_cText || !pPreNode) { return -1;//不能解析的语法, 返回失败 } m_Stack.Clear(); m_Stack.Push(pPreNode, 0);//压入根结点 LOOP_PARSE://循环解析 m_cText = TrimSpace(m_cText); if(!m_cText[0]) { printf("结束返回\r\n"); return 0;//结束返回 } if(*m_cText != '<') { return -1; } m_cText++; if(*m_cText == '!')//去除注释标签 { while(*m_cText != '>') { if(!*m_cText) { printf("XML去除注释错误\r\n"); return -1; } m_cText++; } m_cText++; goto LOOP_PARSE; } m_cText = TrimSpace(m_cText); //本次调用读完全部子结点 if(*m_cText == '/')//无子结点,本结点收敛 上级结点收敛 { m_nNum = GetEndFlagLen(m_cText); m_cText = m_cText + m_nNum; //当前是读子结点 if(!m_Stack.ExistData()) { return -1; } if(!m_Stack.m_DataList[m_Stack.m_nNum - 1].nNodeFlag)//读子结点 { m_Stack.m_DataList[m_Stack.m_nNum - 1].nNodeFlag = 1;//改读兄弟结点 goto LOOP_PARSE; } do { m_Stack.Pop(); }while(m_Stack.ExistData() && m_Stack.m_DataList[m_Stack.m_nNum - 1].nNodeFlag);//读兄弟结点 if(!m_Stack.ExistData()) { return -1; } m_Stack.m_DataList[m_Stack.m_nNum - 1].nNodeFlag = 1;//改读兄弟结点 goto LOOP_PARSE; } //取结点名称 m_nNum = 0; while(*m_cText && *m_cText != '/' && *m_cText != '>' && *m_cText != ' ' && *m_cText != '\t' && *m_cText != '\r' && *m_cText != '\n') { m_cInfoFlag[m_nNum++] = *m_cText++; if(m_nNum == NAME_LEN - 1) { return -1; } } m_cInfoFlag[m_nNum] = 0; m_cText = TrimSpace(m_cText); m_nNum = 0; if(*m_cText != '>' && *m_cText != '/')//含属性 { //读取结点属性信息 while(*m_cText && *m_cText != '>' && !(*m_cText == '/' && *(m_cText + 1) == '>')) { m_cInfoProperty[m_nNum++] = *m_cText++; if(m_nNum == PROPERTY_LEN - 1)//需要另作处理 { return -1; } } m_cInfoProperty[m_nNum] = 0; } #ifdef FN_USE_SDRAM2 CXMLNode *pNode = (CXMLNode *)FN_alloc(SDRAM2, NODE_LEN, 8); #else CXMLNode *pNode = (CXMLNode*)malloc(NODE_LEN); #endif if(!pNode) { return -1; } memset(pNode, 0, NODE_LEN); memcpy(pNode->m_cName, m_cInfoFlag, NAME_LEN); if(m_nNum) { memcpy(pNode->m_cProperty, m_cInfoProperty, m_nNum); pNode->m_cProperty[m_nNum] = 0; } if(!m_Stack.ExistData()) { #ifdef FN_USE_SDRAM2 MEM_free(SDRAM2, pNode, NODE_LEN); #else free(pNode); #endif return -1; } if(!m_Stack.m_DataList[m_Stack.m_nNum - 1].nNodeFlag) { m_Stack.m_DataList[m_Stack.m_nNum - 1].pPreNode->m_pFirstChildNode = pNode;//连入父结点 } else { m_Stack.m_DataList[m_Stack.m_nNum - 1].pPreNode->m_pFirstBrotherNode = pNode;//连入兄结点 } m_cText = TrimSpace(m_cText); if(m_cText[0] == '/' && m_cText[1] == '>') //不含子结点 { m_cText+= 2; m_cText = TrimSpace(m_cText); if(0 > m_Stack.Push(pNode, 1))//压入兄结点 { return -1; } goto LOOP_PARSE; } if(*m_cText == '>') //含子结点 { m_cText++; m_cText = TrimSpace(m_cText); if(0 > m_Stack.Push(pNode, 0))//压入父结点 { return -1; } goto LOOP_PARSE; } return -1; }
NOXREF void TextMessageParse(unsigned char *pMemFile, int fileSize) { NOXREFCHECK; char buf[512]; char trim[512]; char *pCurrentText; char *pNameHeap; char currentName[512]; char nameHeap[NAME_HEAP_SIZE]; int lastNamePos; int mode; int lineNumber; int filePos; int lastLinePos; int messageCount; client_textmessage_t textMessages[MAX_MESSAGES]; int i; int nameHeapSize; int textHeapSize; int messageSize; int nameOffset; lastNamePos = 0; lineNumber = 0; filePos = 0; lastLinePos = 0; messageCount = 0; mode = MSGFILE_NAME; while (memfgets(pMemFile, fileSize, &filePos, buf, 512) != NULL) { if(messageCount >= MAX_MESSAGES) Sys_Error("%s: messageCount >= MAX_MESSAGES", __func__); TrimSpace(buf, trim); switch (mode) { case MSGFILE_NAME: { if (IsComment(trim)) break; if (ParseDirective(trim)) break; if (IsStartOfText(trim)) { mode = MSGFILE_TEXT; pCurrentText = (char *)(pMemFile + filePos); break; } if (IsEndOfText(trim)) { Con_DPrintf("Unexpected '}' found, line %d\n", lineNumber); return; } Q_strncpy(currentName, trim, 511); currentName[511] = 0; break; } case MSGFILE_TEXT: { if (IsEndOfText(trim)) { int length = Q_strlen(currentName); if (lastNamePos + length > sizeof(nameHeap)) { Con_DPrintf("Error parsing file! length > %i bytes\n", sizeof(nameHeap)); return; } Q_strcpy(nameHeap + lastNamePos, currentName); pMemFile[lastLinePos - 1] = 0; textMessages[messageCount] = gMessageParms; textMessages[messageCount].pName = nameHeap + lastNamePos; lastNamePos += Q_strlen(currentName) + 1; textMessages[messageCount].pMessage = pCurrentText; messageCount++; mode = MSGFILE_NAME; break; } if (IsStartOfText(trim)) { Con_DPrintf("Unexpected '{' found, line %d\n", lineNumber); return; } break; } } lineNumber++; lastLinePos = filePos; } Con_DPrintf("Parsed %d text messages\n", messageCount); nameHeapSize = lastNamePos; textHeapSize = 0; for (i = 0; i < messageCount; i++) textHeapSize += Q_strlen(textMessages[i].pMessage) + 1; messageSize = (messageCount * sizeof(client_textmessage_t)); gMessageTable = (client_textmessage_t *)Mem_Malloc(textHeapSize + nameHeapSize + messageSize); Q_memcpy(gMessageTable, textMessages, messageSize); pNameHeap = ((char *)gMessageTable) + messageSize; Q_memcpy(pNameHeap, nameHeap, nameHeapSize); nameOffset = pNameHeap - gMessageTable[0].pName; pCurrentText = pNameHeap + nameHeapSize; for (i = 0; i < messageCount; i++) { gMessageTable[i].pName += nameOffset; Q_strcpy(pCurrentText, gMessageTable[i].pMessage); gMessageTable[i].pMessage = pCurrentText; pCurrentText += Q_strlen(pCurrentText) + 1; } gMessageTableCount = messageCount; }
//写数据 bool CTemperHumiCtrl::WriteData(const char *pbuf, const int len, const uint8 timeout) { static uint8 send_buf[1024] = {0}; // 存储待发送的十六进制命令 static char temp_buf[1024] = {0}; // 临时存放去除空格的命令字符串 int left_len = 0; // 待发送的命令长度 int nfds = 0; // 可写句柄数量 fd_set write_fds; // 句柄集合 struct timeval tv; // select 等待时间 if (len > sizeof(send_buf)) { MainApp.m_log.WriteLog("%s:%d 发送命令的长度必须小于 1024", __FILE__, __LINE__); return -1; } memset(temp_buf, 0x00, sizeof(temp_buf)); int temp_len = TrimSpace(temp_buf, pbuf, len); if (temp_len % 2 != 0) { MainApp.m_log.WriteLog("%s:%d 命令的长度必须是2的整数倍", __FILE__, __LINE__); return false;; } //fprintf(stdout, "len=%d, cmd=%s\n", temp_len, temp_buf); memset(send_buf, 0x00, sizeof(send_buf)); StrToHex(send_buf, temp_buf, temp_len); uint8 CRC[2]; memset(CRC, 0, sizeof(CRC)); CRC16_Modbus(send_buf, (uint16)(temp_len/2), CRC); //fprintf(stdout, "CRC[0]=%02X, CRC[1]=%02X\n", CRC[0], CRC[1]); // 待发送缓冲区加上两个字节的CRC码 send_buf[temp_len/2] = CRC[0]; send_buf[temp_len/2 + 1] = CRC[1]; left_len = temp_len/2 + 2; uint8 *p = send_buf; while (left_len > 0) { tv.tv_sec = 0; tv.tv_usec = 500000; FD_ZERO(&write_fds); FD_SET(m_fd, &write_fds); nfds = select(m_fd + 1, NULL, &write_fds, NULL, &tv); if (nfds < 0) { break; } else if(0 == nfds) { //printf("no fd use write!\n"); break; } int nwrite = write(m_fd, p, left_len); if (nwrite > 0) { left_len -= nwrite; p += nwrite; } else { break; } } if (left_len != 0) { return false; } return true; }
void TextMessageParse( byte *pMemFile, int fileSize ) { char buf[512], trim[512]; char *pCurrentText=0, *pNameHeap; char currentName[512], nameHeap[ NAME_HEAP_SIZE ]; int lastNamePos; int mode = MSGFILE_NAME; // Searching for a message name int lineNumber, filePos, lastLinePos; int messageCount; client_textmessage_t textMessages[ MAX_MESSAGES ]; int i, nameHeapSize, textHeapSize, messageSize, nameOffset; lastNamePos = 0; lineNumber = 0; filePos = 0; lastLinePos = 0; messageCount = 0; CharacterSetBuild( &g_WhiteSpace, " \r\n\t" ); while( memfgets( pMemFile, fileSize, &filePos, buf, 512 ) != NULL ) { if(messageCount>=MAX_MESSAGES) { Sys_Error("tmessage::TextMessageParse : messageCount>=MAX_MESSAGES"); } TrimSpace( buf, trim ); switch( mode ) { case MSGFILE_NAME: if ( IsComment( trim ) ) // Skip comment lines break; if ( ParseDirective( trim ) ) // Is this a directive "$command"?, if so parse it and break break; if ( IsStartOfText( trim ) ) { mode = MSGFILE_TEXT; pCurrentText = (char*)(pMemFile + filePos); break; } if ( IsEndOfText( trim ) ) { Con_DPrintf("Unexpected '}' found, line %d\n", lineNumber ); return; } strcpy( currentName, trim ); break; case MSGFILE_TEXT: if ( IsEndOfText( trim ) ) { int length = strlen(currentName); // Save name on name heap if ( lastNamePos + length > 8192 ) { Con_DPrintf("Error parsing file!\n" ); return; } strcpy( nameHeap + lastNamePos, currentName ); // Terminate text in-place in the memory file (it's temporary memory that will be deleted) pMemFile[ lastLinePos - 1 ] = 0; // Save name/text on heap textMessages[ messageCount ] = gMessageParms; textMessages[ messageCount ].pName = nameHeap + lastNamePos; lastNamePos += strlen(currentName) + 1; textMessages[ messageCount ].pMessage = pCurrentText; messageCount++; // Reset parser to search for names mode = MSGFILE_NAME; break; } if ( IsStartOfText( trim ) ) { Con_DPrintf("Unexpected '{' found, line %d\n", lineNumber ); return; } break; } lineNumber++; lastLinePos = filePos; if ( messageCount >= MAX_MESSAGES ) { Con_Printf("WARNING: TOO MANY MESSAGES IN TITLES.TXT, MAX IS %d\n", MAX_MESSAGES ); break; } } Con_DPrintf("Parsed %d text messages\n", messageCount ); nameHeapSize = lastNamePos; textHeapSize = 0; for ( i = 0; i < messageCount; i++ ) textHeapSize += strlen( textMessages[i].pMessage ) + 1; messageSize = (messageCount * sizeof(client_textmessage_t)); // Must malloc because we need to be able to clear it after initialization gMessageTable = (client_textmessage_t *)malloc( textHeapSize + nameHeapSize + messageSize ); // Copy table over memcpy( gMessageTable, textMessages, messageSize ); // Copy Name heap pNameHeap = ((char *)gMessageTable) + messageSize; memcpy( pNameHeap, nameHeap, nameHeapSize ); nameOffset = pNameHeap - gMessageTable[0].pName; // Copy text & fixup pointers pCurrentText = pNameHeap + nameHeapSize; for ( i = 0; i < messageCount; i++ ) { gMessageTable[i].pName += nameOffset; // Adjust name pointer (parallel buffer) strcpy( pCurrentText, gMessageTable[i].pMessage ); // Copy text over gMessageTable[i].pMessage = pCurrentText; pCurrentText += strlen( pCurrentText ) + 1; } #if _DEBUG if ( (pCurrentText - (char *)gMessageTable) != (textHeapSize + nameHeapSize + messageSize) ) Con_Printf("Overflow text message buffer!!!!!\n"); #endif gMessageTableCount = messageCount; }