Make_WirelessThroughput.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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 telnetPort;
  35. private void Make_WirelessThroughput_Load(object sender, EventArgs e)
  36. {
  37. dh = SystemInf.dh;
  38. try
  39. {
  40. string hostName = Dns.GetHostName();
  41. IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
  42. foreach (IPAddress ip in hostEntry.AddressList)
  43. {
  44. if (ip.AddressFamily == AddressFamily.InterNetwork)
  45. {
  46. IPList.Text = ip.ToString();
  47. }
  48. }
  49. }
  50. catch (Exception ex)
  51. {
  52. ShowMsg(0, $"获取iperf服务器地址失败,{ex.Message}");
  53. }
  54. if (!IPList.Text.Contains(":"))
  55. {
  56. IPList.Text = IPList.Text + ":5021";
  57. }
  58. telnetPort = "23";
  59. //if (!ProductList.Text.Contains(":"))
  60. //{
  61. // ProductList.Text = ProductList.Text + ":23";
  62. //}
  63. Locat1.Visible = false;
  64. Locat2.Visible = false;
  65. Locat3.Visible = false;
  66. Radio1.Visible = false;
  67. Radio2.Visible = false;
  68. }
  69. private void SN_KeyDown(object sender, KeyEventArgs e)
  70. {
  71. if (e.KeyCode != Keys.Enter) return;
  72. if (IPList.Text.IndexOf(':') > 0) IPList.Text = IPList.Text.Replace(":", ":");
  73. else IPList.Text = IPList.Text.Trim();
  74. SN.Text = SN.Text.Trim().Replace(";", ";");
  75. string sn = SN.Text.Trim();
  76. SQL.Clear();
  77. //SQL.Append($"SELECT pr_test_account,pr_test_password FROM makeserial,product WHERE ms_sncode = '{sn}' AND ms_prodcode = pr_code");
  78. SQL.Append($"SELECT * FROM (SELECT pr_test_account,pr_test_password FROM makeserial,product WHERE ms_sncode = '{sn}' AND ms_prodcode = pr_code ORDER BY ms_indate DESC) WHERE ROWNUM = 1");
  79. dt = (DataTable)dh.ExecuteSql(SQL.ToString(), "select");
  80. if (dt.Rows.Count == 0)
  81. {
  82. ShowMsg(0, $"序列号:{sn}未维护吞吐量测试账户密码");
  83. }
  84. else
  85. {
  86. Account.Text = dt.Rows[0]["pr_test_account"].ToString();
  87. Password.Text = dt.Rows[0]["pr_test_password"].ToString();
  88. }
  89. if (IsCheckSet()) return;
  90. UpdateSN("L", SN.Text.Trim());
  91. ShowMsg(1, $"开始测试");
  92. int iSPort = Convert.ToInt32(IPList.Text.Trim().Split(':')[1]);
  93. var tester = new CameraIperfTester(
  94. timeOut: TestTime.Text.Trim(),
  95. cameraIp: ProductList.Text.Trim().Split(':')[0],
  96. cameraPort: Convert.ToInt32(telnetPort),
  97. username: Account.Text.Trim(),
  98. password: Password.Text.Trim(),
  99. iperfServerIp: IPList.Text.Trim().Split(':')[0],
  100. iperfServerPort: iSPort
  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, comboBox1.SelectedIndex.ToString());
  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. ShowMsg(1, $"OK,上行速率: {upRate},下行速率: {downRate}");
  117. ResMax.Text = upRate;
  118. ResMin.Text = downRate;
  119. //string tDetail = $"upRate/{upRate};downRate/{downRate}";
  120. if (comboBox1.SelectedIndex.ToString() == "0")
  121. {
  122. CheckPassStation(SN.Text, "PASS", upRate, downRate, "2.4G");
  123. }
  124. else
  125. {
  126. CheckPassStation(SN.Text, "PASS", upRate, downRate, "5G");
  127. }
  128. }
  129. private void CheckPassStation(string sn, string testRes, string upRate, string downRate, string resType)
  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. string oWO, oWOId, oErrMsg = "";
  188. if (LogicHandler.CheckStepSNAndMacode(workOrder.Text, User.UserSourceCode, sn, User.UserCode, out oWO, out oWOId, out oErrMsg))
  189. {
  190. if (LogicHandler.SetStepResult(oWO, User.UserSourceCode, sn, "无线吞吐量", "OK", User.UserCode, out oErrMsg))
  191. {
  192. ShowMsg(1, $"序列号{sn},过站记录成功");
  193. }
  194. else
  195. {
  196. ShowMsg(0, $"序列号{sn},处理过站NG:{oErrMsg}");
  197. }
  198. }
  199. else
  200. {
  201. ShowMsg(0, $"序列号{sn},过站核对NG:{oErrMsg}");
  202. }
  203. }
  204. private bool IsCheckSet()
  205. {
  206. if (string.IsNullOrEmpty(IPList.Text))
  207. {
  208. ShowMsg(0, "请选择本地iperf 服务IP地址");
  209. return true;
  210. }
  211. if (string.IsNullOrEmpty(ProductList.Text))
  212. {
  213. ShowMsg(0, "请选择产品固定IP地址");
  214. return true;
  215. }
  216. if (string.IsNullOrEmpty(Account.Text))
  217. {
  218. ShowMsg(0, "请输入Telnet登录账号");
  219. return true;
  220. }
  221. if (string.IsNullOrEmpty(Password.Text))
  222. {
  223. ShowMsg(0, "请输入Telnet登录密码");
  224. return true;
  225. }
  226. if (string.IsNullOrEmpty(ExePath.Text))
  227. {
  228. ShowMsg(0, "请输入启动iperf3文件");
  229. return true;
  230. }
  231. if (!File.Exists(ExePath.Text))
  232. {
  233. Console.WriteLine("iperf3启动文件不存在");
  234. }
  235. if (string.IsNullOrEmpty(TestTime.Text))
  236. {
  237. ShowMsg(0, "请输入测试时长");
  238. return true;
  239. }
  240. if (comboBox1.SelectedIndex == -1)
  241. {
  242. ShowMsg(0, "请选择指令模式");
  243. return true;
  244. }
  245. //if (Locat1.Checked == false || Locat2.Checked == false || Locat3.Checked == false)
  246. //{
  247. // ShowMsg(0, "请选择固件位置");
  248. // return true;
  249. //}
  250. //if (Radio1.Checked == false || Radio1.Checked == false )
  251. //{
  252. // ShowMsg(0, "请选择测试类型");
  253. // return true;
  254. //}
  255. return false;
  256. }
  257. private void UpdateSN(string type, string sn)
  258. {
  259. if (type == "C")
  260. {
  261. serialNumber.Text = "";
  262. workOrder.Text = "";
  263. productCode.Text = "";
  264. productName.Text = "";
  265. }
  266. else if (type == "L")
  267. {
  268. SQL.Clear();
  269. SQL.Append($@"SELECT ms_sncode,ma_code,pr_code,pr_spec FROM makeserial,make,product
  270. WHERE ms_sncode = '{sn}' AND ms_makecode = ma_code AND ms_prodcode = pr_code");
  271. dt = (DataTable)dh.ExecuteSql(SQL.ToString(), "select");
  272. if (dt.Rows.Count > 0)
  273. {
  274. serialNumber.Text = dt.Rows[0]["ms_sncode"].ToString();
  275. workOrder.Text = dt.Rows[0]["ma_code"].ToString();
  276. productCode.Text = dt.Rows[0]["pr_code"].ToString();
  277. productName.Text = dt.Rows[0]["pr_spec"].ToString();
  278. }
  279. else
  280. {
  281. UpdateSN("C", sn);
  282. }
  283. }
  284. }
  285. public class CameraIperfTester
  286. {
  287. int timeOut;
  288. string cameraIp, iperfServerIp, username, password;
  289. int cameraPort, iperfServerPort;
  290. string SN, iperfPath, logDirectory;
  291. private TcpClient _telnetClient;
  292. private NetworkStream _telnetStream;
  293. string sVal1, sVal2, rVal1, rVal2;
  294. public CameraIperfTester(string timeOut, string cameraIp, int cameraPort, string username, string password, string iperfServerIp, int iperfServerPort)
  295. {
  296. this.timeOut = Convert.ToInt32(timeOut) * 1000;
  297. this.cameraIp = cameraIp;
  298. this.cameraPort = cameraPort;
  299. this.username = username;
  300. this.password = password;
  301. this.iperfServerIp = iperfServerIp;
  302. this.iperfServerPort = iperfServerPort;
  303. }
  304. public string TestStart(string sn, string iP, string lD,string cmdType)
  305. {
  306. StringBuilder Msg = new StringBuilder();
  307. Msg.Append(TelnetConnect());
  308. if (Msg.ToString().StartsWith("NG")) return Msg.ToString();
  309. SN = sn;
  310. iperfPath = iP;
  311. logDirectory = lD;
  312. Msg.Clear();
  313. Msg.Append(StartIperfTest(cmdType));
  314. return Msg.ToString();
  315. }
  316. public string TelnetConnect()
  317. {
  318. try
  319. {
  320. _telnetClient = new TcpClient();
  321. IAsyncResult connectResult = _telnetClient.BeginConnect(cameraIp, cameraPort, null, null);
  322. bool connected = connectResult.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeOut));
  323. if (!connected)
  324. {
  325. _telnetClient.Close();
  326. return "NG,连接超时";
  327. }
  328. try
  329. {
  330. _telnetClient.EndConnect(connectResult);
  331. }
  332. catch (SocketException ex)
  333. {
  334. return $"NG,连接失败: {ex.Message}";
  335. }
  336. _telnetStream = _telnetClient.GetStream();
  337. _telnetStream.ReadTimeout = timeOut;
  338. StringBuilder fullResponse = new StringBuilder();
  339. string welcomeResponse = ReadStream(_telnetStream);
  340. if (welcomeResponse.StartsWith("NG")) return welcomeResponse;
  341. fullResponse.Append(welcomeResponse);
  342. WriteStream(_telnetStream, username);
  343. string usernameResponse = ReadStream(_telnetStream);
  344. if (usernameResponse.StartsWith("NG")) return usernameResponse;
  345. fullResponse.Append(usernameResponse);
  346. WriteStream(_telnetStream, password);
  347. string loginResponse = ReadStream(_telnetStream);
  348. if (loginResponse.StartsWith("NG")) return loginResponse;
  349. fullResponse.Append(loginResponse);
  350. return $"OK,{fullResponse.ToString()}";
  351. }
  352. catch (Exception ex)
  353. {
  354. Close();
  355. return $"NG,{ex.Message}";
  356. }
  357. }
  358. public string StartIperfTest(string cmdType)
  359. {
  360. try
  361. {
  362. StringBuilder streamTxt = new StringBuilder();
  363. string upRate, downRate, cmdLog, upLog, downLog;
  364. if (cmdType == "0")
  365. {
  366. WriteStream(_telnetStream, "killall iperf3");
  367. streamTxt.Append(ReadStream(_telnetStream));
  368. Thread.Sleep(500);
  369. WriteStream(_telnetStream, $"iperf3 -s -p {iperfServerPort} -i 1&");
  370. streamTxt.Append(ReadStream(_telnetStream));
  371. Thread.Sleep(500);
  372. cmdLog = Path.Combine(logDirectory, $"{SN}_CMD.log");
  373. File.WriteAllText(cmdLog, streamTxt.ToString());
  374. upLog = Path.Combine(logDirectory, $"{SN}_up.log");
  375. downLog = Path.Combine(logDirectory, $"{SN}_down.log");
  376. RunIperfClient($"-c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8 -R", iperfPath, upLog);
  377. RunIperfClient($"-c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8", iperfPath, downLog);
  378. upRate = ParseIperfBitrate(upLog);
  379. downRate = ParseIperfBitrate(downLog);
  380. Close();
  381. if(string.IsNullOrEmpty(upRate) || string.IsNullOrEmpty(downRate))
  382. {
  383. return $"NG,指令一无法获测试结果,请核对指令或使用吞吐量日志解析";
  384. }
  385. return $"OK,{upRate}|{downRate}";
  386. }
  387. else
  388. {
  389. WriteStream(_telnetStream, "killall iperf3_mstar");
  390. streamTxt.Append(ReadStream(_telnetStream));
  391. Thread.Sleep(500);
  392. WriteStream(_telnetStream, "cp /mnt/tf/usb1_1/iperf3_mstar /var/tmp/ -f");
  393. streamTxt.Append(ReadStream(_telnetStream));
  394. Thread.Sleep(500);
  395. WriteStream(_telnetStream, "chmod a+x /var/tmp/iperf3_mstar");
  396. streamTxt.Append(ReadStream(_telnetStream));
  397. Thread.Sleep(500);
  398. WriteStream(_telnetStream, $"/var/tmp/iperf3_mstar -s -p {iperfServerPort} -i 1 &");
  399. streamTxt.Append(ReadStream(_telnetStream));
  400. cmdLog = Path.Combine(logDirectory, $"{SN}_CMD.log");
  401. File.WriteAllText(cmdLog, streamTxt.ToString());
  402. upLog = Path.Combine(logDirectory, $"{SN}_up.log");
  403. downLog = Path.Combine(logDirectory, $"{SN}_down.log");
  404. RunIperfClient($"/var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8 -R", iperfPath, upLog);
  405. RunIperfClient($"/var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8", iperfPath, downLog);
  406. upRate = ParseIperfBitrate(upLog);
  407. downRate = ParseIperfBitrate(downLog);
  408. Close();
  409. if (string.IsNullOrEmpty(upRate) || string.IsNullOrEmpty(downRate))
  410. {
  411. return $"NG,指令二获取测试结果,请核对指令或使用吞吐量日志解析";
  412. }
  413. return $"OK,{upRate}|{downRate}";
  414. }
  415. }
  416. catch (Exception ex)
  417. {
  418. return $"NG,{ex.Message}";
  419. }
  420. }
  421. private void RunIperfClient(string args, string path, string logPath)
  422. {
  423. var psi = new ProcessStartInfo
  424. {
  425. FileName = path,
  426. Arguments = args,
  427. RedirectStandardOutput = true,
  428. RedirectStandardError = true,
  429. UseShellExecute = false,
  430. CreateNoWindow = true,
  431. WorkingDirectory = Path.GetDirectoryName(path)
  432. };
  433. using (var process = Process.Start(psi))
  434. {
  435. StringBuilder outputBuilder = new StringBuilder();
  436. StringBuilder errorBuilder = new StringBuilder();
  437. process.OutputDataReceived += (sender, e) =>
  438. {
  439. if (!string.IsNullOrEmpty(e.Data))
  440. {
  441. outputBuilder.AppendLine(e.Data);
  442. }
  443. };
  444. process.ErrorDataReceived += (sender, e) =>
  445. {
  446. if (!string.IsNullOrEmpty(e.Data))
  447. {
  448. errorBuilder.AppendLine(e.Data);
  449. }
  450. };
  451. process.BeginOutputReadLine();
  452. process.BeginErrorReadLine();
  453. process.WaitForExit();
  454. File.WriteAllText(logPath, outputBuilder.ToString() + errorBuilder.ToString());
  455. }
  456. }
  457. public string ParseIperfBitrate(string logPath)
  458. {
  459. if (!File.Exists(logPath)) return "0.0";
  460. var lines = File.ReadAllLines(logPath);
  461. List<string> logItem = new List<string> { };
  462. foreach (var line in lines)
  463. {
  464. if (line.Trim().StartsWith("[SUM]") && line.Contains("receiver"))
  465. {
  466. logItem.Add(line);
  467. }
  468. }
  469. //if (logItem.Count > 0 && logItem[logItem.Count - 2].Contains("sender"))
  470. //{
  471. // var match = Regex.Match(logItem[logItem.Count - 2], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)");
  472. // if (match.Success)
  473. // {
  474. // sVal1 = match.Groups[1].Value;
  475. // sVal2 = match.Groups[2].Value;
  476. // }
  477. //}
  478. if (logItem.Count > 0 && logItem[logItem.Count - 1].Contains("receiver"))
  479. {
  480. //var match = Regex.Match(logItem[logItem.Count - 1], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)");
  481. var match = Regex.Match(logItem[logItem.Count - 1], @"(\d+\.?\d*)\s*MBytes\s*(\d+\.?\d*)\s*Mbits/sec");
  482. if (match.Success)
  483. {
  484. rVal1 = match.Groups[1].Value + "MBytes";
  485. rVal2 = match.Groups[2].Value + "Mbits/sec";
  486. }
  487. }
  488. //double num1 = (double.Parse(sVal1.Split(' ')[0]) + double.Parse(rVal1.Split(' ')[0])) / 2;
  489. //double num2 = (double.Parse(sVal2.Split(' ')[0]) + double.Parse(rVal2.Split(' ')[0])) / 2;
  490. return rVal2;
  491. }
  492. private string WriteStream(NetworkStream stream, string data)
  493. {
  494. try
  495. {
  496. byte[] dataBytes = Encoding.UTF8.GetBytes(data + "\r\n");
  497. stream.Write(dataBytes, 0, dataBytes.Length);
  498. stream.Flush();
  499. return $"OK";
  500. }
  501. catch (Exception ex)
  502. {
  503. Close();
  504. return $"NG,写入数据时发生错误: {ex.Message}";
  505. }
  506. }
  507. private string ReadStream(NetworkStream stream)
  508. {
  509. try
  510. {
  511. StringBuilder response = new StringBuilder();
  512. byte[] buffer = new byte[1024];
  513. int bytesRead;
  514. while (stream.DataAvailable || response.Length == 0)
  515. {
  516. bytesRead = stream.Read(buffer, 0, buffer.Length);
  517. if (bytesRead > 0)
  518. {
  519. response.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
  520. }
  521. else
  522. {
  523. break;
  524. }
  525. Thread.Sleep(100);
  526. }
  527. return response.ToString();
  528. }
  529. catch (IOException ioEx) when (ioEx.InnerException is SocketException socketEx && socketEx.SocketErrorCode == SocketError.TimedOut)
  530. {
  531. Close();
  532. return "NG,读取数据超时";
  533. }
  534. catch (Exception ex)
  535. {
  536. Close();
  537. return $"NG,读取数据时发生错误: {ex.Message}";
  538. }
  539. }
  540. private void Close()
  541. {
  542. _telnetClient?.Close();
  543. _telnetStream?.Close();
  544. }
  545. }
  546. private void ShowMsg(int type, string msg)
  547. {
  548. msg = msg.Replace("\r", "").Replace("\n", "");
  549. string msgTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  550. string showMsg = $"{msgTime}: {msg}\n";
  551. if (type == 0)
  552. {
  553. OperatResult.AppendText(showMsg, Color.Red);
  554. }
  555. else if (type == 1)
  556. {
  557. OperatResult.AppendText(showMsg, Color.Green);
  558. }
  559. }
  560. private void Radio1_Click(object sender, EventArgs e)
  561. {
  562. if (Radio1.Checked)
  563. {
  564. Radio2.Checked = false;
  565. }
  566. }
  567. private void Radio2_Click(object sender, EventArgs e)
  568. {
  569. if (Radio2.Checked)
  570. {
  571. Radio1.Checked = false;
  572. }
  573. }
  574. private void Locat1_Click(object sender, EventArgs e)
  575. {
  576. if (Locat1.Checked)
  577. {
  578. Locat2.Checked = false;
  579. Locat3.Checked = false;
  580. }
  581. }
  582. private void Locat2_Click(object sender, EventArgs e)
  583. {
  584. if (Locat2.Checked)
  585. {
  586. Locat1.Checked = false;
  587. Locat3.Checked = false;
  588. }
  589. }
  590. private void Locat3_Click(object sender, EventArgs e)
  591. {
  592. if (Locat3.Checked)
  593. {
  594. Locat1.Checked = false;
  595. Locat2.Checked = false;
  596. }
  597. }
  598. private void Account_KeyDown(object sender, KeyEventArgs e)
  599. {
  600. if (e.KeyCode != Keys.Enter) return;
  601. Password.Focus();
  602. Password.SelectAll();
  603. }
  604. private void Password_KeyDown(object sender, KeyEventArgs e)
  605. {
  606. if (e.KeyCode != Keys.Enter) return;
  607. TestTime.Focus();
  608. TestTime.SelectAll();
  609. }
  610. private void ExePath_Click(object sender, EventArgs e)
  611. {
  612. using (OpenFileDialog openFileDialog = new OpenFileDialog())
  613. {
  614. openFileDialog.Title = "选择iperf3启动文件";
  615. openFileDialog.Filter = "可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*";
  616. openFileDialog.FilterIndex = 1;
  617. openFileDialog.RestoreDirectory = true;
  618. // 设置初始目录(可选)
  619. if (!string.IsNullOrEmpty(ExePath.Text) && System.IO.File.Exists(ExePath.Text))
  620. {
  621. openFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(ExePath.Text);
  622. }
  623. else
  624. {
  625. openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  626. }
  627. if (openFileDialog.ShowDialog() == DialogResult.OK)
  628. {
  629. ExePath.Text = openFileDialog.FileName;
  630. ShowMsg(1, $"已成功选择iperf3启动文件");
  631. }
  632. }
  633. }
  634. private void Clear_Click(object sender, EventArgs e)
  635. {
  636. OperatResult.Clear();
  637. }
  638. private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
  639. {
  640. if (comboBox1.SelectedIndex == -1) return;
  641. if (string.IsNullOrEmpty(IPList.Text))
  642. {
  643. ShowMsg(0, $"请先选择iperf服务地址");
  644. comboBox1.SelectedIndex = -1;
  645. return;
  646. }
  647. if (string.IsNullOrEmpty(ProductList.Text))
  648. {
  649. ShowMsg(0, $"请先选择产品IP地址");
  650. comboBox1.SelectedIndex = -1;
  651. return;
  652. }
  653. string iperfServerPort = IPList.Text.Trim().Split(':')[1];
  654. string cameraIp = ProductList.Text.Trim().Split(':')[0];
  655. if (comboBox1.SelectedIndex == 0)
  656. {
  657. ShowMsg(1, $"指令一:");
  658. ShowMsg(1, $" killall iperf3");
  659. ShowMsg(1, $" iperf3 -s -p {iperfServerPort} -i 1&");
  660. ShowMsg(1, $" -c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8 -R");
  661. ShowMsg(1, $" -c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8");
  662. }
  663. else if (comboBox1.SelectedIndex == 1)
  664. {
  665. ShowMsg(1, $"指令二:");
  666. ShowMsg(1, $" killall iperf3_mstar");
  667. ShowMsg(1, $" cp /mnt/tf/usb1_1/iperf3_mstar /var/tmp/ -f");
  668. ShowMsg(1, $" chmod a+x /var/tmp/iperf3_mstar");
  669. ShowMsg(1, $" /var/tmp/iperf3_mstar -s -p {iperfServerPort} -i 1 &");
  670. ShowMsg(1, $" /var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8 -R");
  671. ShowMsg(1, $" /var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8");
  672. }
  673. }
  674. }
  675. }