Make_WirelessThroughput.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. using DevExpress.Utils.Drawing.Helpers;
  2. using DevExpress.XtraReports;
  3. using NPOI.SS.Formula.Functions;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.ComponentModel;
  7. using System.Data;
  8. using System.Diagnostics;
  9. using System.Drawing;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Net.Sockets;
  14. using System.Text;
  15. using System.Text.RegularExpressions;
  16. using System.Threading;
  17. using System.Web.Services.Description;
  18. using System.Web.UI.WebControls.WebParts;
  19. using System.Windows.Forms;
  20. using UAS_MES_NEW.DataOperate;
  21. using UAS_MES_NEW.Entity;
  22. using UAS_MES_NEW.PublicMethod;
  23. namespace UAS_MES_NEW.Make
  24. {
  25. public partial class Make_WirelessThroughput : Form
  26. {
  27. public Make_WirelessThroughput()
  28. {
  29. InitializeComponent();
  30. }
  31. StringBuilder SQL = new StringBuilder();
  32. DataTable dt;
  33. DataHelper dh;
  34. string curIp, telnetPort,testType;
  35. List<string> cmdList = new List<string>();
  36. private void Make_WirelessThroughput_Load(object sender, EventArgs e)
  37. {
  38. dh = SystemInf.dh;
  39. try
  40. {
  41. IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
  42. foreach (IPAddress ip in hostEntry.AddressList)
  43. {
  44. if (ip.AddressFamily == AddressFamily.InterNetwork)
  45. {
  46. curIp = ip.ToString();
  47. }
  48. }
  49. }
  50. catch (Exception ex)
  51. {
  52. ShowMsg(0, $"获取iperf服务器地址或产品IP失败,请手动填写,{ex.Message}");
  53. }
  54. IPList.Text = "5021";
  55. telnetPort = "23";
  56. Locat1.Visible = false;
  57. Locat2.Visible = false;
  58. Locat3.Visible = false;
  59. }
  60. private void SN_KeyDown(object sender, KeyEventArgs e)
  61. {
  62. if (e.KeyCode != Keys.Enter) return;
  63. if (IPList.Text.IndexOf(':') > 0) IPList.Text = IPList.Text.Replace(":", ":");
  64. else IPList.Text = IPList.Text.Trim();
  65. SN.Text = SN.Text.Trim().Replace(";", ";");
  66. string sn = SN.Text.Trim();
  67. SQL.Clear();
  68. SQL.Append($@"SELECT pr_test_account,pr_test_password,pr_test_start,pr_test_cmd1,pr_test_cmd2,pr_test_cmd3 FROM makeserial,product
  69. WHERE ms_sncode = '{sn}' AND ms_prodcode = pr_code ORDER BY ms_id DESC");
  70. dt = (DataTable)dh.ExecuteSql(SQL.ToString(), "select");
  71. if (dt.Rows.Count == 0)
  72. {
  73. ShowMsg(0, $"序列号:{sn}未维护吞吐量基础信息");
  74. }
  75. else
  76. {
  77. Account.Text = dt.Rows[0]["pr_test_account"].ToString();
  78. Password.Text = dt.Rows[0]["pr_test_password"].ToString();
  79. cmdList.Add(dt.Rows[0]["pr_test_start"].ToString());
  80. if(testType == "2.4G")
  81. {
  82. cmdList.Add(dt.Rows[0]["pr_test_cmd1"].ToString());
  83. }
  84. else
  85. {
  86. cmdList.Add(dt.Rows[0]["pr_test_cmd2"].ToString());
  87. }
  88. cmdList.Add(dt.Rows[0]["pr_test_cmd3"].ToString());
  89. }
  90. if (IsCheckSet()) return;
  91. UpdateSN("L", SN.Text.Trim());
  92. ShowMsg(1, $"开始测试");
  93. var tester = new CameraIperfTester(
  94. timeOut: TestTime.Text.Trim(),
  95. cameraIp: ProductList.Text.Trim(),
  96. cameraPort: Convert.ToInt32(telnetPort),
  97. username: Account.Text.Trim(),
  98. password: Password.Text.Trim(),
  99. iperfServerIp: curIp,
  100. iperfServerPort: Convert.ToInt32(IPList.Text.Trim())
  101. );
  102. string parentPath = Path.GetDirectoryName(ExePath.Text.Trim());
  103. string logsPath = Path.Combine(parentPath, "iperf_logs");
  104. if (!Directory.Exists(logsPath))
  105. {
  106. Directory.CreateDirectory(logsPath);
  107. }
  108. string Msg = tester.TestStart(SN.Text.Trim(), ExePath.Text.Trim(), logsPath, cmdList, testType);
  109. if (Msg.StartsWith("NG"))
  110. {
  111. ShowMsg(0, Msg);
  112. return;
  113. }
  114. string upRate = Msg.Split('|')[0].Split(',')[1];
  115. string downRate = Msg.Split('|')[1];
  116. string signalNum = Msg.Split('|')[2];
  117. ShowMsg(1, $"OK,上行速率: {upRate},下行速率: {downRate}");
  118. ResMax.Text = upRate;
  119. ResMin.Text = downRate;
  120. if (testType == "2.4G")
  121. {
  122. CheckPassStation(SN.Text, "PASS", upRate, downRate, testType, signalNum);
  123. }
  124. else
  125. {
  126. CheckPassStation(SN.Text, "PASS", upRate, downRate, testType, signalNum);
  127. }
  128. }
  129. private void CheckPassStation(string sn, string testRes, string upRate, string downRate, string resType,string signalNum)
  130. {
  131. List<string> param = new List<string>() { };
  132. string outMsg = "";
  133. param.Add(workOrder.Text);
  134. param.Add(sn);
  135. param.Add(User.CurrentStepCode);
  136. param.Add(testRes);
  137. param.Add("");
  138. param.Add("");
  139. param.Add("ThruputCmd");
  140. param.Add($"upRate/{upRate};downRate/{downRate}");
  141. param.Add(outMsg);
  142. string[] paramList = param.ToArray();
  143. dh.CallProcedure("cs_insert_testrejects", ref paramList);
  144. if (paramList[8].Substring(0, 2) == "OK")
  145. {
  146. ShowMsg(1, $"序列号{sn}采集成功:测试结果为{testRes}");
  147. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, workOrder.Text, User.UserLineCode, User.UserSourceCode, "无线吞吐量", "无线吞吐量过站成功", sn, "");
  148. }
  149. dt = (DataTable)dh.ExecuteSql($"SELECT mp_id FROM makeprocess WHERE mp_sncode = '{sn}' AND instr(mp_stepname, '吞吐量') > 0", "select");
  150. if (dt.Rows.Count > 0)
  151. {
  152. ShowMsg(1, $"序列号:{sn}已经过站记录");
  153. return;
  154. }
  155. dt = (DataTable)dh.ExecuteSql($"select sm_id from steptestmain where INSTR(sm_sourcetype, 'Thruput') > 0 and sm_sn = '{sn}' order by sm_indate desc", "select");
  156. string sm_id = dt.Rows[0]["sm_id"].ToString();
  157. Dictionary<string, string> testArr = new Dictionary<string, string>();
  158. testArr.Add("测试项", $"{resType}吞吐量测试");
  159. testArr.Add("参数名称", $"{resType}上行测试值");
  160. testArr.Add("结果", "0");
  161. testArr.Add("结果描述", "OK");
  162. testArr.Add("产测指标门限", "");
  163. testArr.Add("测试时长", "10");
  164. testArr.Add("值", upRate);
  165. foreach (var item in testArr)
  166. {
  167. dh.ExecuteSql($@"INSERT INTO steptestdetail (sd_id,sd_smid,sd_sn,sd_makecode,sd_machinecode,sd_indate,
  168. sd_class,sd_length,sd_actvalue,sd_detno) VALUES
  169. ( steptestdetail_seq.NEXTVAL,'{sm_id}','{sn}','{workOrder.Text.Trim()}', 'ZTE',sysdate,
  170. '{item.Key}','100','{item.Value}',1 )", "insert");
  171. }
  172. Dictionary<string, string> testArr1 = new Dictionary<string, string>();
  173. testArr1.Add("测试项", $"{resType}吞吐量测试");
  174. testArr1.Add("参数名称", $"{resType}下行测试值");
  175. testArr1.Add("结果", "0");
  176. testArr1.Add("结果描述", "OK");
  177. testArr1.Add("产测指标门限", "");
  178. testArr1.Add("测试时长", "10");
  179. testArr1.Add("值", downRate);
  180. foreach (var item in testArr1)
  181. {
  182. dh.ExecuteSql($@"INSERT INTO steptestdetail (sd_id,sd_smid,sd_sn,sd_makecode,sd_machinecode,sd_indate,
  183. sd_class,sd_length,sd_actvalue,sd_detno) VALUES
  184. ( steptestdetail_seq.NEXTVAL,'{sm_id}','{sn}','{workOrder.Text.Trim()}', 'ZTE',sysdate,
  185. '{item.Key}','100','{item.Value}',2 )", "insert");
  186. }
  187. Dictionary<string, string> testArr2 = new Dictionary<string, string>();
  188. testArr2.Add("测试项", $"SSID测试");
  189. testArr2.Add("参数名称", $"信号强度值");
  190. testArr2.Add("结果", "0");
  191. testArr2.Add("结果描述", "OK");
  192. testArr2.Add("产测指标门限", "-55");
  193. testArr2.Add("测试时长", "1");
  194. testArr2.Add("值", signalNum);
  195. foreach (var item in testArr2)
  196. {
  197. dh.ExecuteSql($@"INSERT INTO steptestdetail (sd_id,sd_smid,sd_sn,sd_makecode,sd_machinecode,sd_indate,
  198. sd_class,sd_length,sd_actvalue,sd_detno) VALUES
  199. ( steptestdetail_seq.NEXTVAL,'{sm_id}','{sn}','{workOrder.Text.Trim()}', 'ZTE',sysdate,
  200. '{item.Key}','100','{item.Value}',3 )", "insert");
  201. }
  202. string oWO, oWOId, oErrMsg = "";
  203. if (LogicHandler.CheckStepSNAndMacode(workOrder.Text, User.UserSourceCode, sn, User.UserCode, out oWO, out oWOId, out oErrMsg))
  204. {
  205. if (LogicHandler.SetStepResult(oWO, User.UserSourceCode, sn, "无线吞吐量", "OK", User.UserCode, out oErrMsg))
  206. {
  207. ShowMsg(1, $"序列号{sn},过站记录成功");
  208. }
  209. else
  210. {
  211. ShowMsg(0, $"序列号{sn},处理过站NG:{oErrMsg}");
  212. }
  213. }
  214. else
  215. {
  216. ShowMsg(0, $"序列号{sn},过站核对NG:{oErrMsg}");
  217. }
  218. }
  219. private bool IsCheckSet()
  220. {
  221. if (string.IsNullOrEmpty(IPList.Text))
  222. {
  223. ShowMsg(0, "请选择本地iperf 服务IP地址");
  224. return true;
  225. }
  226. if (string.IsNullOrEmpty(ProductList.Text))
  227. {
  228. ShowMsg(0, "请选择产品固定IP地址");
  229. return true;
  230. }
  231. if (string.IsNullOrEmpty(Account.Text))
  232. {
  233. ShowMsg(0, "请输入Telnet登录账号");
  234. return true;
  235. }
  236. if (string.IsNullOrEmpty(Password.Text))
  237. {
  238. ShowMsg(0, "请输入Telnet登录密码");
  239. return true;
  240. }
  241. if (string.IsNullOrEmpty(ExePath.Text))
  242. {
  243. ShowMsg(0, "请输入启动iperf3文件");
  244. return true;
  245. }
  246. if (!File.Exists(ExePath.Text))
  247. {
  248. Console.WriteLine("iperf3启动文件不存在");
  249. }
  250. if (string.IsNullOrEmpty(TestTime.Text))
  251. {
  252. ShowMsg(0, "请输入测试时长");
  253. return true;
  254. }
  255. //if (comboBox1.SelectedIndex == -1)
  256. //{
  257. // ShowMsg(0, "请选择指令模式");
  258. // return true;
  259. //}
  260. //if (Locat1.Checked == false || Locat2.Checked == false || Locat3.Checked == false)
  261. //{
  262. // ShowMsg(0, "请选择固件位置");
  263. // return true;
  264. //}
  265. if (Radio1.Checked == false || Radio1.Checked == false)
  266. {
  267. ShowMsg(0, "请选择测试类型");
  268. return true;
  269. }
  270. return false;
  271. }
  272. private void UpdateSN(string type, string sn)
  273. {
  274. if (type == "C")
  275. {
  276. serialNumber.Text = "";
  277. workOrder.Text = "";
  278. productCode.Text = "";
  279. productName.Text = "";
  280. }
  281. else if (type == "L")
  282. {
  283. SQL.Clear();
  284. SQL.Append($@"SELECT ms_sncode,ma_code,pr_code,pr_spec FROM makeserial,make,product
  285. WHERE ms_sncode = '{sn}' AND ms_makecode = ma_code AND ms_prodcode = pr_code");
  286. dt = (DataTable)dh.ExecuteSql(SQL.ToString(), "select");
  287. if (dt.Rows.Count > 0)
  288. {
  289. serialNumber.Text = dt.Rows[0]["ms_sncode"].ToString();
  290. workOrder.Text = dt.Rows[0]["ma_code"].ToString();
  291. productCode.Text = dt.Rows[0]["pr_code"].ToString();
  292. productName.Text = dt.Rows[0]["pr_spec"].ToString();
  293. }
  294. else
  295. {
  296. UpdateSN("C", sn);
  297. }
  298. }
  299. }
  300. public class CameraIperfTester
  301. {
  302. int timeOut;
  303. string cameraIp, iperfServerIp, username, password;
  304. int cameraPort, iperfServerPort;
  305. string SN, iperfPath, logDirectory;
  306. private TcpClient _telnetClient;
  307. private NetworkStream _telnetStream;
  308. string sVal1, sVal2, rVal1, rVal2;
  309. string signalNum;
  310. public CameraIperfTester(string timeOut, string cameraIp, int cameraPort, string username, string password, string iperfServerIp, int iperfServerPort)
  311. {
  312. this.timeOut = Convert.ToInt32(timeOut) * 1000;
  313. this.cameraIp = cameraIp;
  314. this.cameraPort = cameraPort;
  315. this.username = username;
  316. this.password = password;
  317. this.iperfServerIp = iperfServerIp;
  318. this.iperfServerPort = iperfServerPort;
  319. }
  320. public string TestStart(string sn, string iP, string lD,List<string> cmdList,string testType)
  321. {
  322. StringBuilder Msg = new StringBuilder();
  323. Msg.Append(TelnetConnect());
  324. if (Msg.ToString().StartsWith("NG")) return Msg.ToString();
  325. SN = sn;
  326. iperfPath = iP;
  327. logDirectory = lD;
  328. Msg.Clear();
  329. Msg.Append(StartIperfTest(cmdList, testType));
  330. return Msg.ToString();
  331. }
  332. public string TelnetConnect()
  333. {
  334. try
  335. {
  336. _telnetClient = new TcpClient();
  337. IAsyncResult connectResult = _telnetClient.BeginConnect(cameraIp, cameraPort, null, null);
  338. bool connected = connectResult.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeOut));
  339. if (!connected)
  340. {
  341. _telnetClient.Close();
  342. return "NG,连接超时";
  343. }
  344. try
  345. {
  346. _telnetClient.EndConnect(connectResult);
  347. }
  348. catch (SocketException ex)
  349. {
  350. return $"NG,连接失败: {ex.Message}";
  351. }
  352. _telnetStream = _telnetClient.GetStream();
  353. _telnetStream.ReadTimeout = timeOut;
  354. StringBuilder fullResponse = new StringBuilder();
  355. string welcomeResponse = ReadStream(_telnetStream);
  356. if (welcomeResponse.StartsWith("NG")) return welcomeResponse;
  357. fullResponse.Append(welcomeResponse);
  358. WriteStream(_telnetStream, username);
  359. string usernameResponse = ReadStream(_telnetStream);
  360. if (usernameResponse.StartsWith("NG")) return usernameResponse;
  361. fullResponse.Append(usernameResponse);
  362. WriteStream(_telnetStream, password);
  363. string loginResponse = ReadStream(_telnetStream);
  364. if (loginResponse.StartsWith("NG")) return loginResponse;
  365. fullResponse.Append(loginResponse);
  366. return $"OK,{fullResponse.ToString()}";
  367. }
  368. catch (Exception ex)
  369. {
  370. Close();
  371. return $"NG,{ex.Message}";
  372. }
  373. }
  374. public string StartIperfTest(List<string> cmdList,string testType)
  375. {
  376. try
  377. {
  378. StringBuilder streamTxt = new StringBuilder();
  379. string upRate, downRate, cmdLog, upLog, downLog;
  380. WriteStream(_telnetStream, cmdList[2]);
  381. streamTxt.Append(ReadStream(_telnetStream));
  382. var pattern = @"Bit Rate:\s*(\d+\s*[GMK]?b/s)";
  383. var match = Regex.Match(streamTxt.ToString(), pattern);
  384. if (match.Success)
  385. {
  386. if(testType == "2.4G")
  387. {
  388. signalNum = match.Groups[1].Value.Trim();
  389. }
  390. else
  391. {
  392. signalNum = match.Groups[2].Value.Trim();
  393. }
  394. }
  395. WriteStream(_telnetStream, cmdList[0].Trim().Replace("Port", iperfServerPort.ToString()));
  396. streamTxt.Append(ReadStream(_telnetStream));
  397. cmdLog = Path.Combine(logDirectory, $"{SN}_CMD.log");
  398. File.WriteAllText(cmdLog, streamTxt.ToString());
  399. upLog = Path.Combine(logDirectory, $"{SN}_up.log");
  400. downLog = Path.Combine(logDirectory, $"{SN}_down.log");
  401. RunIperfClient(cmdList[1].Trim().Replace("IP", cameraIp).Replace("Port", iperfServerPort.ToString()) + " -R", iperfPath, upLog);
  402. RunIperfClient(cmdList[1].Trim().Replace("IP", cameraIp).Replace("Port", iperfServerPort.ToString()), iperfPath, downLog);
  403. upRate = ParseIperfBitrate(upLog);
  404. downRate = ParseIperfBitrate(downLog);
  405. Close();
  406. if (string.IsNullOrEmpty(upRate) || string.IsNullOrEmpty(downRate))
  407. {
  408. return $"NG,产前维护指令测试失败,请核对指令或使用吞吐量日志解析";
  409. }
  410. return $"OK,{upRate}|{downRate}|{signalNum}";
  411. /*if (cmdType == "0")
  412. {
  413. WriteStream(_telnetStream, "killall iperf3");
  414. streamTxt.Append(ReadStream(_telnetStream));
  415. Thread.Sleep(500);
  416. WriteStream(_telnetStream, $"iperf3 -s -p {iperfServerPort} -i 1&");
  417. streamTxt.Append(ReadStream(_telnetStream));
  418. Thread.Sleep(500);
  419. cmdLog = Path.Combine(logDirectory, $"{SN}_CMD.log");
  420. File.WriteAllText(cmdLog, streamTxt.ToString());
  421. upLog = Path.Combine(logDirectory, $"{SN}_up.log");
  422. downLog = Path.Combine(logDirectory, $"{SN}_down.log");
  423. RunIperfClient($"-c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8 -R", iperfPath, upLog);
  424. RunIperfClient($"-c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8", iperfPath, downLog);
  425. upRate = ParseIperfBitrate(upLog);
  426. downRate = ParseIperfBitrate(downLog);
  427. Close();
  428. if(string.IsNullOrEmpty(upRate) || string.IsNullOrEmpty(downRate))
  429. {
  430. return $"NG,指令一无法获测试结果,请核对指令或使用吞吐量日志解析";
  431. }
  432. return $"OK,{upRate}|{downRate}";
  433. }
  434. else
  435. {
  436. WriteStream(_telnetStream, "killall iperf3_mstar");
  437. streamTxt.Append(ReadStream(_telnetStream));
  438. Thread.Sleep(500);
  439. WriteStream(_telnetStream, "cp /mnt/tf/usb1_1/iperf3_mstar /var/tmp/ -f");
  440. streamTxt.Append(ReadStream(_telnetStream));
  441. Thread.Sleep(500);
  442. WriteStream(_telnetStream, "chmod a+x /var/tmp/iperf3_mstar");
  443. streamTxt.Append(ReadStream(_telnetStream));
  444. Thread.Sleep(500);
  445. WriteStream(_telnetStream, $"/var/tmp/iperf3_mstar -s -p {iperfServerPort} -i 1 &");
  446. streamTxt.Append(ReadStream(_telnetStream));
  447. cmdLog = Path.Combine(logDirectory, $"{SN}_CMD.log");
  448. File.WriteAllText(cmdLog, streamTxt.ToString());
  449. upLog = Path.Combine(logDirectory, $"{SN}_up.log");
  450. downLog = Path.Combine(logDirectory, $"{SN}_down.log");
  451. RunIperfClient($"/var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8 -R", iperfPath, upLog);
  452. RunIperfClient($"/var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8", iperfPath, downLog);
  453. upRate = ParseIperfBitrate(upLog);
  454. downRate = ParseIperfBitrate(downLog);
  455. Close();
  456. if (string.IsNullOrEmpty(upRate) || string.IsNullOrEmpty(downRate))
  457. {
  458. return $"NG,指令二获取测试结果,请核对指令或使用吞吐量日志解析";
  459. }
  460. return $"OK,{upRate}|{downRate}";
  461. }*/
  462. }
  463. catch (Exception ex)
  464. {
  465. return $"NG,{ex.Message}";
  466. }
  467. }
  468. private void RunIperfClient(string args, string path, string logPath)
  469. {
  470. var psi = new ProcessStartInfo
  471. {
  472. FileName = path,
  473. Arguments = args,
  474. RedirectStandardOutput = true,
  475. RedirectStandardError = true,
  476. UseShellExecute = false,
  477. CreateNoWindow = true,
  478. WorkingDirectory = Path.GetDirectoryName(path)
  479. };
  480. using (var process = Process.Start(psi))
  481. {
  482. StringBuilder outputBuilder = new StringBuilder();
  483. StringBuilder errorBuilder = new StringBuilder();
  484. process.OutputDataReceived += (sender, e) =>
  485. {
  486. if (!string.IsNullOrEmpty(e.Data))
  487. {
  488. outputBuilder.AppendLine(e.Data);
  489. }
  490. };
  491. process.ErrorDataReceived += (sender, e) =>
  492. {
  493. if (!string.IsNullOrEmpty(e.Data))
  494. {
  495. errorBuilder.AppendLine(e.Data);
  496. }
  497. };
  498. process.BeginOutputReadLine();
  499. process.BeginErrorReadLine();
  500. process.WaitForExit();
  501. File.WriteAllText(logPath, outputBuilder.ToString() + errorBuilder.ToString());
  502. }
  503. }
  504. public string ParseIperfBitrate(string logPath)
  505. {
  506. if (!File.Exists(logPath)) return "0.0";
  507. var lines = File.ReadAllLines(logPath);
  508. List<string> logItem = new List<string> { };
  509. foreach (var line in lines)
  510. {
  511. if (line.Trim().StartsWith("[SUM]") && line.Contains("receiver"))
  512. {
  513. logItem.Add(line);
  514. }
  515. }
  516. //if (logItem.Count > 0 && logItem[logItem.Count - 2].Contains("sender"))
  517. //{
  518. // var match = Regex.Match(logItem[logItem.Count - 2], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)");
  519. // if (match.Success)
  520. // {
  521. // sVal1 = match.Groups[1].Value;
  522. // sVal2 = match.Groups[2].Value;
  523. // }
  524. //}
  525. if (logItem.Count > 0 && logItem[logItem.Count - 1].Contains("receiver"))
  526. {
  527. //var match = Regex.Match(logItem[logItem.Count - 1], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)");
  528. var match = Regex.Match(logItem[logItem.Count - 1], @"(\d+\.?\d*)\s*MBytes\s*(\d+\.?\d*)\s*Mbits/sec");
  529. if (match.Success)
  530. {
  531. rVal1 = match.Groups[1].Value + "MBytes";
  532. rVal2 = match.Groups[2].Value + "Mbits/sec";
  533. }
  534. }
  535. //double num1 = (double.Parse(sVal1.Split(' ')[0]) + double.Parse(rVal1.Split(' ')[0])) / 2;
  536. //double num2 = (double.Parse(sVal2.Split(' ')[0]) + double.Parse(rVal2.Split(' ')[0])) / 2;
  537. return rVal2;
  538. }
  539. private string WriteStream(NetworkStream stream, string data)
  540. {
  541. try
  542. {
  543. byte[] dataBytes = Encoding.UTF8.GetBytes(data + "\r\n");
  544. stream.Write(dataBytes, 0, dataBytes.Length);
  545. stream.Flush();
  546. return $"OK";
  547. }
  548. catch (Exception ex)
  549. {
  550. Close();
  551. return $"NG,写入数据时发生错误: {ex.Message}";
  552. }
  553. }
  554. private string ReadStream(NetworkStream stream)
  555. {
  556. try
  557. {
  558. StringBuilder response = new StringBuilder();
  559. byte[] buffer = new byte[1024];
  560. int bytesRead;
  561. while (stream.DataAvailable || response.Length == 0)
  562. {
  563. bytesRead = stream.Read(buffer, 0, buffer.Length);
  564. if (bytesRead > 0)
  565. {
  566. response.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
  567. }
  568. else
  569. {
  570. break;
  571. }
  572. Thread.Sleep(100);
  573. }
  574. return response.ToString();
  575. }
  576. catch (IOException ioEx) when (ioEx.InnerException is SocketException socketEx && socketEx.SocketErrorCode == SocketError.TimedOut)
  577. {
  578. Close();
  579. return "NG,读取数据超时";
  580. }
  581. catch (Exception ex)
  582. {
  583. Close();
  584. return $"NG,读取数据时发生错误: {ex.Message}";
  585. }
  586. }
  587. private void Close()
  588. {
  589. _telnetClient?.Close();
  590. _telnetStream?.Close();
  591. }
  592. }
  593. private void ShowMsg(int type, string msg)
  594. {
  595. msg = msg.Replace("\r", "").Replace("\n", "");
  596. string msgTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  597. string showMsg = $"{msgTime}: {msg}\n";
  598. if (type == 0)
  599. {
  600. OperatResult.AppendText(showMsg, Color.Red);
  601. }
  602. else if (type == 1)
  603. {
  604. OperatResult.AppendText(showMsg, Color.Green);
  605. }
  606. }
  607. private void Radio1_Click(object sender, EventArgs e)
  608. {
  609. if (Radio1.Checked)
  610. {
  611. testType = "2.4G";
  612. Radio2.Checked = false;
  613. }
  614. }
  615. private void Radio2_Click(object sender, EventArgs e)
  616. {
  617. if (Radio2.Checked)
  618. {
  619. testType = "5G";
  620. Radio1.Checked = false;
  621. }
  622. }
  623. private void Locat1_Click(object sender, EventArgs e)
  624. {
  625. if (Locat1.Checked)
  626. {
  627. Locat2.Checked = false;
  628. Locat3.Checked = false;
  629. }
  630. }
  631. private void Locat2_Click(object sender, EventArgs e)
  632. {
  633. if (Locat2.Checked)
  634. {
  635. Locat1.Checked = false;
  636. Locat3.Checked = false;
  637. }
  638. }
  639. private void Locat3_Click(object sender, EventArgs e)
  640. {
  641. if (Locat3.Checked)
  642. {
  643. Locat1.Checked = false;
  644. Locat2.Checked = false;
  645. }
  646. }
  647. private void Account_KeyDown(object sender, KeyEventArgs e)
  648. {
  649. if (e.KeyCode != Keys.Enter) return;
  650. Password.Focus();
  651. Password.SelectAll();
  652. }
  653. private void Password_KeyDown(object sender, KeyEventArgs e)
  654. {
  655. if (e.KeyCode != Keys.Enter) return;
  656. TestTime.Focus();
  657. TestTime.SelectAll();
  658. }
  659. private void ExePath_Click(object sender, EventArgs e)
  660. {
  661. using (OpenFileDialog openFileDialog = new OpenFileDialog())
  662. {
  663. openFileDialog.Title = "选择iperf3启动文件";
  664. openFileDialog.Filter = "可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*";
  665. openFileDialog.FilterIndex = 1;
  666. openFileDialog.RestoreDirectory = true;
  667. // 设置初始目录(可选)
  668. if (!string.IsNullOrEmpty(ExePath.Text) && System.IO.File.Exists(ExePath.Text))
  669. {
  670. openFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(ExePath.Text);
  671. }
  672. else
  673. {
  674. openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  675. }
  676. if (openFileDialog.ShowDialog() == DialogResult.OK)
  677. {
  678. ExePath.Text = openFileDialog.FileName;
  679. ShowMsg(1, $"已成功选择iperf3启动文件");
  680. }
  681. }
  682. }
  683. private void Clear_Click(object sender, EventArgs e)
  684. {
  685. OperatResult.Clear();
  686. }
  687. private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
  688. {
  689. if (comboBox1.SelectedIndex == -1) return;
  690. if (string.IsNullOrEmpty(IPList.Text))
  691. {
  692. ShowMsg(0, $"请先选择iperf服务地址");
  693. comboBox1.SelectedIndex = -1;
  694. return;
  695. }
  696. if (string.IsNullOrEmpty(ProductList.Text))
  697. {
  698. ShowMsg(0, $"请先选择产品IP地址");
  699. comboBox1.SelectedIndex = -1;
  700. return;
  701. }
  702. string iperfServerPort = IPList.Text.Trim().Split(':')[1];
  703. string cameraIp = ProductList.Text.Trim().Split(':')[0];
  704. if (comboBox1.SelectedIndex == 0)
  705. {
  706. ShowMsg(1, $"指令一:");
  707. ShowMsg(1, $" killall iperf3");
  708. ShowMsg(1, $" iperf3 -s -p {iperfServerPort} -i 1&");
  709. ShowMsg(1, $" -c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8 -R");
  710. ShowMsg(1, $" -c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8");
  711. }
  712. else if (comboBox1.SelectedIndex == 1)
  713. {
  714. ShowMsg(1, $"指令二:");
  715. ShowMsg(1, $" killall iperf3_mstar");
  716. ShowMsg(1, $" cp /mnt/tf/usb1_1/iperf3_mstar /var/tmp/ -f");
  717. ShowMsg(1, $" chmod a+x /var/tmp/iperf3_mstar");
  718. ShowMsg(1, $" /var/tmp/iperf3_mstar -s -p {iperfServerPort} -i 1 &");
  719. ShowMsg(1, $" /var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8 -R");
  720. ShowMsg(1, $" /var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8");
  721. }
  722. }
  723. }
  724. }