string类find函数返回值判定

本文分析了一个关于C++中使用string.find查找字符串时出现的Bug。详细解释了为何将string::npos错误地理解为非负数会导致逻辑判断失误,并提供了修复后的代码。

代码示例

  1. int main()  
  2. {  
  3.     string s = "Alice Bob Charlie";  
  4.     size_t position;  
  5.     position = s.find("none");  
  6.     if (position >= 0)  
  7.         cout << "Found! position is : " << position << endl;  
  8.     else  
  9.         cout << "Not found!" << endl;  
  10. }  

现象&后果

程序运行结果输出"Found! position is : 4294967295",但实际上所找的字符串"none"并不存在于字符串s中。

Bug分析

程序的目的是,在源字符串s中查找目的字符串,若找到,则显示"Found",并返回目标子串在源字符串中的位置;反之,若未找到,则返回"Not found"。string.find在未找到时会返回string::npos。

在C++中常量npos是这样定义的:

  1. static const size_t npos = -1; 

即常量npos定义的值为-1. 但又因为npos 的类型size_t是无符号整数类型,所以npos实际上是一个正数,并且是size_t类型的最大值。

上述代码中,把find函数返回的值赋给size_t类型的变量position,而size_t类型的变量position是永远大于等于0,所以即使find返回npos,if条件也为true。

正确的做法是在if条件中直接用npos作比较。

正确代码

  1. int main()  
  2. {  
  3.     string s = "Alice Bob Charlie";  
  4.     size_t position;  
  5.     position = s.find("none");  
  6.     if (position != string::npos)  
  7.         cout << "Found! position is : " << position << endl;  
  8.     else  
  9.         cout << "Not found!" << endl;  
  10. }  
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using UserHelpers.Helpers; namespace LongCheerTestHelp { public class LongCheerCommonHelpClass { string _syncExampleLogs = string.Empty; /// <summary> /// adb 读取值和关键字进行全字比对,适用于返回值比较短,如:0,1之的 /// </summary> /// <param name="item">测试项信息</param> /// <param name="adbSerialNumber">adb 序列号</param> /// <param name="command">adb 指令,不包含adb</param> /// <param name="Keywords">查和比对关键字,包括返回值为空;ByPass是对返回值不做管控,对函数返回值也不做判定</param> /// <param name="timeOut">adb指令超时时间</param> /// <returns></returns> public int Adb_Compare_Value(ITestItem item, string adbSerialNumber, string command, string Keywords,int timeOut) { bool result = false; bool isOK = false; string read = string.Empty; string resultString = string.Empty; try { _syncExampleLogs = string.Empty; isOK = ShellHelper.RunHideRead(item.AddLog, "adb.exe", ADBSN(command, adbSerialNumber), timeOut, ref read); _syncExampleLogs = read; item.AddLog("read = " + read); if (!isOK) goto ReturnAndExit; if (isOK) { var lines = read.SplitToList("\r\n"); var line = lines.FirstOrDefault(ln => (ln.CompareTo(Keywords) == 0)); if (line != null && Keywords != string.Empty) { item.AddLog("Compare keyword {" + Keywords + "} succeed"); result = true; } else { item.AddLog("Compare keyword {" + Keywords + "} failed"); } } else { item.AddLog("Adb command excute failed"); } } catch (Exception ex) { item.AddLog(ex.ToString()); } ReturnAndExit: return result ? 0 : 1; } /// <summary> /// adb devices读取adb 地址 /// </summary> /// <param name="item"></param> /// <param name="adbSerialNumber"></param> /// <param name="command"></param> /// <param name="timeOut"></param> /// <returns></returns> public int Adb_Devices(ITestItem item, string adbSerialNumber, string command, int timeOut) { bool result = false; string read = string.Empty; string resultString = string.Empty; try { if (!string.IsNullOrEmpty(command)) { _syncExampleLogs = string.Empty; bool isOK = ShellHelper.RunHideRead(item.AddLog, "adb.exe", ADBSN(command, ""), timeOut, ref read); _syncExampleLogs = read; item.AddLog("read = " + read); if (!isOK) goto ReturnAndExit; } else read = _syncExampleLogs; var lines = read.SplitToList("\r\n"); var line = lines.FirstOrDefault(ln => ln.Contains(adbSerialNumber)); if (line != null && adbSerialNumber != string.Empty) { item.AddLog("Find keywords {" + adbSerialNumber + "} succeed"); result = true; } else if(adbSerialNumber == string.Empty) { item.AddLog("adbSerialNumber is Null"); } else { item.AddLog("Find keyword failed : " + adbSerialNumber); } } catch (Exception ex) { item.AddLog(ex.ToString()); } ReturnAndExit: return result ? 0 : 1; } /// <summary> /// 查关键字: Keywords /// </summary> /// <param name="item">默认添加,打log</param> /// <param name="adbSerialNumber">adb sn</param> /// <param name="command">指令</param> /// <param name="Keywords"></param> /// <param name="timeOut"></param> /// <returns></returns> public int Adb_Find_Keyword_Func(ITestItem item,string adbSerialNumber, string command, string Keywords, int timeOut) { bool result = false; string read = string.Empty; string resultString = string.Empty; try { if (!string.IsNullOrEmpty(command)) { _syncExampleLogs = string.Empty; bool isOK = ShellHelper.RunHideRead(item.AddLog, "adb.exe", ADBSN(command, adbSerialNumber), timeOut, ref read); _syncExampleLogs = read; item.AddLog("read = " + read); if (Keywords.Contains("ByPass")) { result = true; goto ReturnAndExit; } if (!isOK) goto ReturnAndExit; } else read = _syncExampleLogs; if (Keywords == string.Empty) { read = read.Replace("\r", "").Replace("\n", ""); if(read==string.Empty) { result = true; } goto ReturnAndExit; } var lines = read.SplitToList("\r\n"); var line = lines.FirstOrDefault(ln => ln.Contains(Keywords)); if (line != null && Keywords != string.Empty) { item.AddLog("Find keywords {" + Keywords + "} succeed"); result = true; } else { item.AddLog("Find keyword failed : " + Keywords); } } catch (Exception ex) { item.AddLog(ex.ToString()); } ReturnAndExit: return result ? 0 : 1; } //功能:1. Keywords 2.截取取值 public int Adb_Get_Substring_Func(ITestItem item, string adbSerialNumber, string command, string Keywords, string Prefix, string Suffix, string IgnoreChars, int timeOut, ref string ReturnResult) { bool result = false; string read = string.Empty; string resultString = string.Empty; try { if (!string.IsNullOrEmpty(command)) { _syncExampleLogs = string.Empty; bool isOK = ShellHelper.RunHideRead(item.AddLog, "adb.exe", ADBSN(command, adbSerialNumber), timeOut, ref read); _syncExampleLogs = read; item.AddLog("read = " + read); //resultString = "adb.exe: no devices/emulators found" if (!isOK || read.Contains(@"no devices/emulators found")) { goto ReturnAndExit; } } else { read = _syncExampleLogs; } if (IgnoreChars.Equals("quot")) //这个先去掉 { read = read.Replace("\"", "").Replace(" ", "").Replace(",", ""); } if (Keywords == string.Empty) { if (IgnoreChars.Equals("CRLF")) { read = read.Replace("\r\n", "").Replace("\r", "").Replace("\n", ""); } resultString = read; result = true; goto ReturnAndExit; } var lines = read.SplitToList("\r\n"); var line = lines.FirstOrDefault(ln => ln.Contains(Keywords)); if (line != null && Keywords != string.Empty) { item.AddLog("Find keywords {" + Keywords + "} succeed"); if (Prefix.Length > 0 && read.IndexOf(Prefix) >= 0) { resultString = read.Substring(read.IndexOf(Prefix) + Prefix.Length); if (!string.IsNullOrEmpty(Suffix) && resultString.Contains(Suffix)) { resultString = resultString.Substring(0, resultString.IndexOf(Suffix)); } else if (Suffix == "LineEnd") { resultString = resultString.Substring(0, resultString.IndexOf(Environment.NewLine)); resultString = resultString.Replace("\r", "").Replace("\n",""); } if (IgnoreChars.Length > 0) { resultString = resultString.Replace(IgnoreChars, "").Replace(" ", ""); } item.AddLog("value: " + resultString); result = true; } else { resultString = line; if (IgnoreChars.Length > 0) { resultString = resultString.Replace(IgnoreChars, "").Replace(" ", ""); } item.AddLog("value: " + resultString); result = true; } } else { item.AddLog("Find keyword failed : " + Keywords); } } catch (Exception ex) { item.AddLog(ex.ToString()); } ReturnAndExit: ReturnResult = resultString; return result ? 0 : 1; } //功能:ADB 读取返回值,返回值根据特征需要拆分为多个 public int Adb_Get_MutiSubstr_Func(ITestItem item, string adbSerialNumber, string command, string Keywords, string Prefix, string Suffix, string IgnoreChars, int timeOut, ref List<string> ReturnResult) { bool result = false; string read = string.Empty; string resultString = string.Empty; List<string> prefixList =new List<string>(); List<string> suffixList= new List<string>(); try { if (!string.IsNullOrEmpty(command)) { _syncExampleLogs = string.Empty; bool isOK = ShellHelper.RunHideRead(item.AddLog, "adb.exe", ADBSN(command, adbSerialNumber), timeOut, ref read); _syncExampleLogs = read; item.AddLog("read = " + read); if (!isOK) goto ReturnAndExit; } else read = _syncExampleLogs; if (IgnoreChars.Equals("quot")) //这个先去掉 { read = read.Replace("\"", "").Replace(" ", "").Replace(",", ""); } if (Keywords == string.Empty) { resultString = read; result = true; goto ReturnAndExit; } var lines = read.SplitToList("\r\n"); var line = lines.FirstOrDefault(ln => ln.Contains(Keywords)); if (line != null && Keywords != string.Empty) { item.AddLog("Find keywords {" + Keywords + "} succeed"); if (Prefix.Length > 0) { prefixList = Prefix.SplitToList("@"); suffixList = Suffix.SplitToList("@"); int num = 0; ReturnResult.Clear(); foreach (var pref in prefixList) { var value = lines.FirstOrDefault(ln => ln.Contains(pref)); if (value != null) { resultString = ""; string TmpString = value.Substring(value.IndexOf(pref) + pref.Length).Trim(); if (suffixList.Count == prefixList.Count && !string.IsNullOrEmpty(suffixList[num])) { if (resultString.Contains(suffixList[num])) { resultString = TmpString.Substring(0, TmpString.IndexOf(suffixList[num])); } else if (suffixList[num] == "LineEnd") { if (TmpString.Contains(Environment.NewLine)) { resultString += TmpString.Substring(0, TmpString.IndexOf(Environment.NewLine)); } else { resultString = TmpString; } } else { resultString = TmpString; } if (IgnoreChars.Length > 0) { resultString = resultString.Replace(IgnoreChars, "").Replace(" ", ""); } ReturnResult.Add(resultString); } } } } else { resultString = line; item.AddLog("value: " + resultString); result = true; } } else { item.AddLog("Find keyword failed : " + Keywords); } } catch (Exception ex) { item.AddLog(ex.ToString()); } ReturnAndExit: //ReturnResult = resultString; if(ReturnResult.Count==prefixList.Count ) { result = true; } return result ? 0 : 1; } /// <summary> /// adb 读取返回值,按照起始和结束标志位进行截取,在和配置的值,进行比对 /// </summary> /// <param name="item">caesar测试项,此处用于log打印</param> /// <param name="adbSerialNumber">adb 序列号</param> /// <param name="command">adb 指令</param> /// <param name="Keywords">查关键字</param> /// <param name="Prefix">截取的开始字符</param> /// <param name="Suffix">截取的结束字符</param> /// <param name="IgnoreChars">截取值需要忽略的字符</param> /// <param name="CompareValue">比对值</param> /// <param name="timeOut">超时时间</param> /// <param name="ReturnResult">是否保存到sumarry文件中</param> /// <returns></returns> //功能:1. Keywords 2.截取取值 3. 给定值比对 public int Adb_Get_Substring_Compare_With_Config_Func(ITestItem item, string adbSerialNumber, string command, string Keywords, string Prefix, string Suffix, string IgnoreChars, string CompareValue, int timeOut, ref string ReturnResult) { bool result = false; string read = string.Empty; string resultString = string.Empty; try { if (!string.IsNullOrEmpty(command)) { _syncExampleLogs = string.Empty; bool isOK = ShellHelper.RunHideRead(item.AddLog, "adb.exe", ADBSN(command, adbSerialNumber), timeOut, ref read); _syncExampleLogs = read; item.AddLog("read = " + read); if (!isOK) goto ReturnAndExit; } else read = _syncExampleLogs; if (Keywords == string.Empty) { result = true; goto ReturnAndExit; } if (IgnoreChars.Equals("quot")) //这个先去掉 { read = read.Replace("\"", "").Replace(" ", "").Replace(",", ""); } var lines = read.SplitToList("\r\n"); var line = lines.FirstOrDefault(ln => ln.Contains(Keywords)); if (line != null && Keywords != string.Empty) { item.AddLog("Find keywords {" + Keywords + "} succeed"); if (Prefix.Length > 0 && read.IndexOf(Prefix) >= 0) { resultString = read.Substring(read.IndexOf(Prefix) + Prefix.Length); if (!string.IsNullOrEmpty(Suffix) && resultString.Contains(Suffix)) { resultString = resultString.Substring(0, resultString.IndexOf(Suffix)); } else if (Suffix == "LineEnd") { resultString = resultString.Substring(0, resultString.IndexOf("\n")); item.AddLog("[Key value]" + Prefix + resultString); } } else { resultString = read; } if (IgnoreChars.Length > 0) { resultString = resultString.Replace(IgnoreChars, "").Replace(" ", "").Replace("\n", "").Replace("\r", ""); } item.AddLog("value: " + resultString); if (!string.IsNullOrEmpty(CompareValue) && !string.IsNullOrEmpty(resultString)) { if (CompareValue.CompareTo(resultString) == 0) { result = true; } item.AddLog("read : " + resultString + ";CompareValue : " + CompareValue + ";Result : " + result.ToString()); } else if (string.IsNullOrEmpty(CompareValue)) { result = true; } } else { item.AddLog("Find keyword failed : " + Keywords); } } catch (Exception ex) { item.AddLog(ex.ToString()); } ReturnAndExit: ReturnResult = resultString; return result ? 0 : 1; } /// <summary> /// adb 读取返回值,按照起始和结束标志位进行截取,通过一定的方法转换,在和配置的值,进行比对 /// </summary> /// <param name="item">caesar测试项,此处用于log打印</param> /// <param name="adbSerialNumber">adb 序列号</param> /// <param name="command">adb 指令</param> /// <param name="Keywords">查关键字</param> /// <param name="Prefix">截取的开始字符</param> /// <param name="Suffix">截取的结束字符</param> /// <param name="IgnoreChars">截取值需要忽略的字符</param> /// <param name="Method">转换方法,如hex2bin(16进制转2进制)</param> /// <param name="CompareValue">比对值</param> /// <param name="timeOut">超时时间</param> /// <param name="ReturnResult">是否保存到sumarry文件中</param> /// <returns></returns> public int Adb_Get_Substring_Compare_With_Config_By_Method_Func(ITestItem item, string adbSerialNumber, string command, string Keywords, string Prefix, string Suffix, string IgnoreChars, string Method, string CompareValue, int timeOut,int ResultType, ref string ReturnResult) { bool result = false; string read = string.Empty; string resultString = string.Empty; string ConvertResultString = string.Empty; string resultTmpString = string.Empty; try { if (!string.IsNullOrEmpty(command)) { _syncExampleLogs = string.Empty; bool isOK = ShellHelper.RunHideRead(item.AddLog, "adb.exe", ADBSN(command, adbSerialNumber), timeOut, ref read); _syncExampleLogs = read; item.AddLog("read = " + read); if (!isOK) goto ReturnAndExit; } else read = _syncExampleLogs; if (Keywords == string.Empty) { result = true; goto ReturnAndExit; } if (IgnoreChars.Equals("quot")) //这个先去掉 { read = read.Replace("\"", "").Replace(" ", "").Replace(",", ""); } var lines = read.SplitToList("\r\n"); var line = lines.FirstOrDefault(ln => ln.Contains(Keywords)); if (line != null && Keywords != string.Empty) { item.AddLog("Find keywords {" + Keywords + "} succeed"); if (Prefix.Length > 0 && read.IndexOf(Prefix) >= 0) { resultString = read.Substring(read.IndexOf(Prefix) + Prefix.Length); if (!string.IsNullOrEmpty(Suffix) && resultString.Contains(Suffix)) { resultString = resultString.Substring(0, resultString.IndexOf(Suffix)); } else if (Suffix == "LineEnd") { resultString = resultString.Substring(0, resultString.IndexOf("\n")); item.AddLog("[Key value]" + Prefix + resultString); } } else { resultString = read; } if (IgnoreChars.Length > 0) { resultString = resultString.Replace(IgnoreChars, "").Replace(" ", "").Replace("\n", "").Replace("\r", ""); } item.AddLog("value: " + resultString); if (!string.IsNullOrEmpty(Method)) { if (Method == "hex2bin") { resultTmpString = HexStringToBinString(resultString, true); item.AddLog(Method + "(Little_endian): " + resultTmpString); } } if (!string.IsNullOrEmpty(CompareValue) && !string.IsNullOrEmpty(resultTmpString)) { string tmpStr = string.Empty; if (CompareValue.Contains("bit") && Method == "hex2bin") { var bitList = CompareValue.SplitToList("@"); int num = 0; foreach (var bit in bitList) { var bitpos = bit.Substring(3, bit.IndexOf("=") - 3); var bitval = bit.Substring(bit.IndexOf("=") + 1); tmpStr += "bit" + bitpos + "=" + resultTmpString[int.Parse(bitpos)].ToString() + "@"; if (resultTmpString[int.Parse(bitpos)].ToString() != bitval) { item.AddLog("bit" + bitpos + ": " + "compare failed"); continue; } item.AddLog("bit" + bitpos + ": " + "compare success"); num++; } if (bitList.Count == num) { result = true; } if (tmpStr.Substring(tmpStr.Length - 1) == "@") { ConvertResultString = tmpStr.Substring(0, tmpStr.Length - 1); } else { ConvertResultString = tmpStr; } item.AddLog("read : " + ConvertResultString + ";CompareValue : " + CompareValue + ";Result : " + result.ToString()); } else { if (CompareValue.CompareTo(ConvertResultString) == 0) { result = true; } item.AddLog("read : " + ConvertResultString + ";CompareValue : " + CompareValue + ";Result : " + result.ToString()); } } else if (string.IsNullOrEmpty(CompareValue)) { result = true; } } else { item.AddLog("Find keyword failed : " + Keywords); } } catch (Exception ex) { item.AddLog(ex.ToString()); } ReturnAndExit: if(ResultType==0) //等于0转换后结果 { ReturnResult = ConvertResultString; } else //等于1原始结果 { ReturnResult = resultString; } return result ? 0 : 1; } //功能:1. Keywords public int Adb_Wait_for_device(ITestItem item, string adbSerialNumber, string command, string Keywords, int timeOut) { bool result = false; string read = string.Empty; string resultString = string.Empty; try { if (!string.IsNullOrEmpty(command)) { _syncExampleLogs = string.Empty; bool isOK = ShellHelper.RunHideRead(item.AddLog, "adb.exe", ADBSN(command, adbSerialNumber), timeOut, ref read); _syncExampleLogs = read; item.AddLog("read = " + read); if (!isOK) goto ReturnAndExit; } else read = _syncExampleLogs; if (Keywords == string.Empty) { result = true; goto ReturnAndExit; } var lines = read.SplitToList("\r\n"); var line = lines.FirstOrDefault(ln => ln.Contains(Keywords)); if (line != null && Keywords != string.Empty) { item.AddLog("Find keywords {" + Keywords + "} succeed"); result = true; } else { item.AddLog("Find keyword failed : " + Keywords); } } catch (Exception ex) { item.AddLog(ex.ToString()); } ReturnAndExit: return result ? 0 : 1; } public int Execute_Console_Cmd(ITestItem item, string adbSerialNumber,string ConsoleCmd,string ConsoleKeywords, string AdbCmd, string AdbKeywords,int IntervalTime, int timeOut, ref string ReturnResult) { bool result = false; bool bConsoleResult = false; string read = string.Empty; string resultString = string.Empty; string NewCmd = string.Empty; string strConsoleValue = string.Empty; string AdbRead = string.Empty; ConsoleHelper _cmdConsole = null; try { _cmdConsole = new ConsoleHelper("cmd.exe", item.AddLog); //_cmdConsole.Process.StartInfo.CreateNoWindow= if (!_cmdConsole.StartLineMode()) { item.AddLog("start cmd failed!"); goto ReturnAndExit; } _cmdConsole.WriteLine(ConsoleCmd); DateTime dtEnd = DateTime.Now.AddMilliseconds(timeOut); while (dtEnd > DateTime.Now) { strConsoleValue = _cmdConsole.Read(); if (string.IsNullOrEmpty(strConsoleValue)) { System.Threading.Thread.Sleep(10); continue; } item.AddLog("[Console]" + strConsoleValue); read += strConsoleValue; if (strConsoleValue.Contains(ConsoleKeywords)) { bConsoleResult = true; } System.Threading.Thread.Sleep(IntervalTime); if(bConsoleResult) { bool isOK = ShellHelper.RunHideRead(item.AddLog, "adb.exe", ADBSN(AdbCmd, adbSerialNumber), timeOut, ref AdbRead); item.AddLog("[ADB]" + AdbRead); if (AdbRead.Contains(AdbKeywords)) { item.AddLog("Find keywords {" + AdbKeywords + "} succeed"); result = true; break; } } } } catch (Exception ex) { item.AddLog(ex.ToString()); } ReturnAndExit: _cmdConsole.WriteLine("exit"); _cmdConsole.Terminate(); _cmdConsole = null; item.AddLog("console terminated!!"); ReturnResult = AdbRead; return result ? 0 : 1; } //功能:adb write WIFI 地址 public int ADB_Write_Wlan_Mac(ITestItem item, string adbSerialNumber, string command, string Keywords,string Addr, string binFilePath,int timeOut) { bool result = false; string read = string.Empty; string resultString = string.Empty; string BinFile = string.Empty; string NewCmd = string.Empty; try { if (!string.IsNullOrEmpty(command)) { Create_wlanbin_File(binFilePath,Addr, ref BinFile); //adb push wlan_mac.bin /mnt/vendor/persist/wlan_mac.bin NewCmd = "push " + BinFile + " " + command; _syncExampleLogs = string.Empty; bool isOK = ShellHelper.RunHideRead(item.AddLog, "adb.exe", ADBSN(NewCmd, adbSerialNumber), timeOut, ref read); _syncExampleLogs = read; item.AddLog("read = " + read); if (!isOK) goto ReturnAndExit; } else read = _syncExampleLogs; if (Keywords == string.Empty) { result = true; goto ReturnAndExit; } var lines = read.SplitToList("\r\n"); var line = lines.FirstOrDefault(ln => ln.Contains(Keywords)); if (line != null && Keywords != string.Empty) { item.AddLog("Find keywords {" + Keywords + "} succeed"); result = true; } else { item.AddLog("Find keyword failed : " + Keywords); } } catch (Exception ex) { item.AddLog(ex.ToString()); } ReturnAndExit: return result ? 0 : 1; } /// <summary> /// 串口写数据 /// </summary> /// <param name="item"></param> /// <param name="serialPort"></param> /// <param name="command"></param> /// <param name="Keywords"></param> /// <param name="timeOut"></param> /// <param name="ReturnResult"></param> /// <returns>1:成功;0:失败</returns> public int SerialPortWriteBytes1By1(ITestItem item, SerialPort serialPort, string command, string Keywords, int timeOut,int PostDelay, ref string ReturnResult) { bool result = false; string read = string.Empty; try { if (!string.IsNullOrEmpty(command)) { if(!serialPort.IsOpen) { serialPort.Open(); } //command += Environment.NewLine; command += "\r"; //serialPort.Write(Cmd); byte[] bytes = Encoding.Default.GetBytes(command); for (int iLoop = 0; iLoop < bytes.Length; iLoop++) { serialPort.Write(bytes, iLoop, 1); Thread.Sleep(30); } item.AddLog("[DUT_Send]" + command); DateTime dtTimeOut = DateTime.Now.AddMilliseconds(timeOut); while (DateTime.Now < dtTimeOut) { Thread.Sleep(100); if (serialPort != null && serialPort.IsOpen) { string tmp = serialPort.ReadExisting(); if (!string.IsNullOrEmpty(tmp)) { item.AddLog(tmp); read += tmp; } } else { item.AddLog("[UartError]:serialPort is not Open or serialPort is null"); } ReturnResult = read; if (read.Contains(Keywords)) { Thread.Sleep(PostDelay); result = true; break; } } } if (Keywords == string.Empty) { result = true; goto ReturnAndExit; } } catch (Exception ex) { item.AddLog(ex.ToString()); } finally { //if (serialPort != null && serialPort.IsOpen) // serialPort.Close(); } ReturnAndExit: return result ? 1 : 0; } /// <summary> /// 串口命令查关键字,参数包含串口号,波特率 /// </summary> /// <param name="item"></param> /// <param name="ComPort">串口号</param> /// <param name="BaudRate">波特率</param> /// <param name="command">命令</param> /// <param name="Keywords">关键字</param> /// <param name="timeOut">读取超时时间</param> /// <param name="ReturnResult">串口返回值</param> /// <returns>1:成功,0:失败</returns> public int SerialPortWriteBytes1By1(ITestItem item, string ComPort,int BaudRate, string command, string Keywords, int timeOut,ref string ReturnResult) { bool result = false; string read = string.Empty; SerialPort serialPort = null; try { if (!string.IsNullOrEmpty(command)) { serialPort = new SerialPort(ComPort, BaudRate, Parity.None, 8, StopBits.One); serialPort.ReadBufferSize = 4096; serialPort.ReadTimeout = timeOut; serialPort.WriteTimeout = 2000; item.AddLog("PortName = " + ComPort + " ;BaudRate =" + BaudRate); if (!serialPort.IsOpen) { serialPort.Open(); } //command += Environment.NewLine; command += "\r"; byte[] bytes = Encoding.Default.GetBytes(command); for (int iLoop = 0; iLoop < bytes.Length; iLoop++) { serialPort.Write(bytes, iLoop, 1); Thread.Sleep(30); } item.AddLog("[DUT_Send]" + command); DateTime dtTimeOut = DateTime.Now.AddMilliseconds(timeOut); while (DateTime.Now < dtTimeOut) { Thread.Sleep(100); if (serialPort != null && serialPort.IsOpen) { string tmp = serialPort.ReadExisting(); if (!string.IsNullOrEmpty(tmp)) { item.AddLog(tmp); read += tmp; } } else { item.AddLog("[UartError]:serialPort is not Open or serialPort is null"); } ReturnResult = read; if (read.Contains(Keywords)) { result = true; break; } } } if (Keywords == string.Empty) { result = true; goto ReturnAndExit; } } catch (Exception ex) { item.AddLog(ex.ToString()); } finally { if (serialPort != null && serialPort.IsOpen) serialPort.Close(); } ReturnAndExit: return result ? 1 : 0; } public int SerialPortFindMutiKeywordsWriteBytes1By1(ITestItem item, string ComPort, int BaudRate, string command, string MutiKeywords, int timeOut, ref string ReturnResult) { bool result = false; string read = string.Empty; SerialPort serialPort = null; List<string> keywordsList = new List<string>(); try { if (!string.IsNullOrEmpty(command)) { serialPort = new SerialPort(ComPort, BaudRate, Parity.None, 8, StopBits.One); serialPort.ReadBufferSize = 4096; serialPort.ReadTimeout = timeOut; serialPort.WriteTimeout = 2000; item.AddLog("PortName = " + ComPort + " ;BaudRate =" + BaudRate); if (!serialPort.IsOpen) { serialPort.Open(); } //command += Environment.NewLine; command += "\r"; byte[] bytes = Encoding.Default.GetBytes(command); for (int iLoop = 0; iLoop < bytes.Length; iLoop++) { serialPort.Write(bytes, iLoop, 1); Thread.Sleep(30); } item.AddLog("[DUT_Send]" + command); DateTime dtTimeOut = DateTime.Now.AddMilliseconds(timeOut); while (DateTime.Now < dtTimeOut) { Thread.Sleep(100); if (serialPort != null && serialPort.IsOpen) { string tmp = serialPort.ReadExisting(); if (!string.IsNullOrEmpty(tmp)) { item.AddLog(tmp); read += tmp; } } else { item.AddLog("[UartError]:serialPort is not Open or serialPort is null"); } ReturnResult = read; keywordsList= MutiKeywords.SplitToList("@"); foreach (var keywords in keywordsList) { if (read.Contains(keywords)) { result = true; break; } } if(result) { break; } } } } catch (Exception ex) { item.AddLog(ex.ToString()); } finally { if (serialPort != null && serialPort.IsOpen) serialPort.Close(); } //ReturnAndExit: return result ? 1 : 0; } /// <summary> /// 串口发送接收不关闭串口 /// </summary> /// <param name="item"></param> /// <param name="serialPort"></param> /// <param name="command"></param> /// <param name="Keywords"></param> /// <param name="timeOut"></param> /// <param name="ReturnResult"></param> /// <returns></returns> public int SerialPortWriteBytes1By1_NoClose(ITestItem item, SerialPort serialPort, string command, string Keywords, int timeOut, ref string ReturnResult) { bool result = false; string read = string.Empty; try { if (!string.IsNullOrEmpty(command)) { if (!serialPort.IsOpen) { serialPort.Open(); } command += Environment.NewLine; byte[] bytes = Encoding.Default.GetBytes(command); for (int iLoop = 0; iLoop < bytes.Length; iLoop++) { serialPort.Write(bytes, iLoop, 1); } item.AddLog("[DUT_Send]" + command); DateTime dtTimeOut = DateTime.Now.AddMilliseconds(timeOut); while (DateTime.Now < dtTimeOut) { Thread.Sleep(20); if (serialPort != null && serialPort.IsOpen) { string tmp = serialPort.ReadExisting(); if (!string.IsNullOrEmpty(tmp)) { item.AddLog(tmp); read += tmp; } } else { item.AddLog("[UartError]:serialPort is not Open or serialPort is null"); } ReturnResult = read; if (read.Contains(Keywords)) { result = true; break; } } } if (Keywords == string.Empty) { result = true; goto ReturnAndExit; } } catch (Exception ex) { item.AddLog(ex.ToString()); } finally { } ReturnAndExit: return result ? 1 : 0; } /// <summary> /// 串口只接收 /// </summary> /// <param name="item"></param> /// <param name="serialPort"></param> /// <param name="command"></param> /// <param name="Keywords"></param> /// <param name="timeOut"></param> /// <param name="ReturnResult"></param> /// <returns></returns> public int SerialPortWriteBytes1By1_Only_Receive(ITestItem item, SerialPort serialPort, string command, string Keywords, int timeOut, ref string ReturnResult) { bool result = false; string read = string.Empty; try { if (!serialPort.IsOpen) { serialPort.Open(); } DateTime dtTimeOut = DateTime.Now.AddMilliseconds(timeOut); while (DateTime.Now < dtTimeOut) { Thread.Sleep(20); if (serialPort != null && serialPort.IsOpen) { string tmp = serialPort.ReadExisting(); if (!string.IsNullOrEmpty(tmp)) { item.AddLog(tmp); read += tmp; } } else { item.AddLog("[UartError]:serialPort is not Open or serialPort is null"); } ReturnResult = read; if (read.Contains(Keywords)) { result = true; break; } } if (Keywords == string.Empty) { result = true; goto ReturnAndExit; } } catch (Exception ex) { item.AddLog(ex.ToString()); } finally { } ReturnAndExit: return result ? 1:0; } /// <summary> /// adb 指令添加 -s addr /// </summary> /// <param name="args"></param> /// <param name="adbSerialNumber"></param> /// <returns></returns> private string ADBSN(string args,string adbSerialNumber) { if (!string.IsNullOrEmpty(adbSerialNumber)) return " -s " + adbSerialNumber + " " + args; return args; } private string HexStringToBinString(string hexString, bool bReverse) { string strReult = string.Empty; byte[] bytes = Enumerable.Range(0, hexString.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16)) .ToArray(); strReult = string.Join("", bytes.Select(b => Convert.ToString(b, 2).PadLeft(8, '0'))); if (bReverse) { strReult = new string(strReult.Reverse().ToArray()); } return strReult; } private bool Create_wlanbin_File(string binFilePath,string WlanAddr, ref string binPath) { bool bRet = false; string FilePath = binFilePath; string FileName = "wlan_mac.bin"; FilePath = Path.Combine(FilePath, FileName); var fi = new FileInfo(FilePath); if (fi.Exists) { fi.Delete(); } FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(fs); sw.WriteLine("Intf0MacAddress=" + WlanAddr); //sw.WriteLine("Intf1MacAddress=000AF58989FE"); //sw.WriteLine("Intf2MacAddress=000AF58989FD"); sw.WriteLine("END"); sw.Close(); fs.Close(); binPath = FilePath; bRet = true; return bRet; } } } 以上代码有实现bin烧录这个过程的相关内容吗
最新发布
09-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值