Make_WirelessThroughput.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. using DevExpress.Utils.Drawing.Helpers;
  2. using NPOI.SS.Formula.Functions;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Diagnostics;
  8. using System.Drawing;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Net.Sockets;
  13. using System.Text;
  14. using System.Text.RegularExpressions;
  15. using System.Threading;
  16. using System.Web.Services.Description;
  17. using System.Web.UI.WebControls.WebParts;
  18. using System.Windows.Forms;
  19. using UAS_MES_NEW.DataOperate;
  20. using UAS_MES_NEW.Entity;
  21. using UAS_MES_NEW.PublicMethod;
  22. namespace UAS_MES_NEW.Make
  23. {
  24. public partial class Make_WirelessThroughput : Form
  25. {
  26. public Make_WirelessThroughput()
  27. {
  28. InitializeComponent();
  29. }
  30. StringBuilder SQL = new StringBuilder();
  31. DataTable dt;
  32. DataHelper dh;
  33. private void Make_WirelessThroughput_Load(object sender, EventArgs e)
  34. {
  35. dh = SystemInf.dh;
  36. try
  37. {
  38. string hostName = Dns.GetHostName();
  39. IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
  40. foreach (IPAddress ip in hostEntry.AddressList)
  41. {
  42. if (ip.AddressFamily == AddressFamily.InterNetwork)
  43. {
  44. IPList.Text = ip.ToString();
  45. }
  46. }
  47. }
  48. catch (Exception ex)
  49. {
  50. ShowMsg(0, $"获取iperf服务器地址失败,{ex.Message}");
  51. }
  52. if (!IPList.Text.Contains(":"))
  53. {
  54. IPList.Text = IPList.Text + ":5001";
  55. }
  56. if (!ProductList.Text.Contains(":"))
  57. {
  58. ProductList.Text = ProductList.Text + ":23";
  59. }
  60. }
  61. private void SN_KeyDown(object sender, KeyEventArgs e)
  62. {
  63. if (e.KeyCode != Keys.Enter) return;
  64. if (IsCheckSet()) return;
  65. string sn = SN.Text.Trim();
  66. if (IPList.Text.IndexOf(':') > 0) IPList.Text = IPList.Text.Replace(":", ":");
  67. else IPList.Text = IPList.Text.Trim();
  68. if (SN.Text.IndexOf(';') > 0) SN.Text = sn.Replace(";", ";");
  69. else SN.Text = sn;
  70. UpdateSN("L", SN.Text.Trim());
  71. ShowMsg(1, $"开始测试");
  72. int cSPort = Convert.ToInt32(ProductList.Text.Trim().Split(':')[1]);
  73. int iSPort = Convert.ToInt32(IPList.Text.Trim().Split(':')[1]);
  74. var tester = new CameraIperfTester(
  75. timeOut: TestTime.Text.Trim(),
  76. cameraIp: ProductList.Text.Trim().Split(':')[0],
  77. cameraPort: cSPort,
  78. username: Account.Text.Trim(),
  79. password: ProductList.Text.Trim(),
  80. iperfServerIp: IPList.Text.Trim().Split(':')[0],
  81. iperfServerPort: iSPort
  82. );
  83. string Msg = tester.TelnetConnect();
  84. if (Msg.Substring(0, 2) != "OK")
  85. {
  86. ShowMsg(0, $"Telnet登录失败,{Msg}");
  87. return;
  88. }
  89. ShowMsg(1, $"Telnet登录成功");
  90. string parentPath = Path.GetDirectoryName(ExePath.Text.Trim());
  91. string logsPath = Path.Combine(parentPath, "iperf_logs");
  92. if (!Directory.Exists(logsPath))
  93. {
  94. Directory.CreateDirectory(logsPath);
  95. }
  96. //string[] comList = new string[] {
  97. // "killall iperf3",
  98. // $"iperf3 -s -p {iSPort} -i 1&"
  99. //};
  100. string[] comList = new string[] {
  101. "cd /tmp/",
  102. "ls iperf3_mstar",
  103. "chmod a+x iperf3_mstar",
  104. $"iperf3_mstar -s -p {iSPort} -i 1 &"
  105. };
  106. Msg = tester.StartIperfTest(SN.Text.Trim(), ExePath.Text.Trim(), logsPath, comList);
  107. if (Msg.Substring(0, 2) != "OK")
  108. {
  109. ShowMsg(0, $"iperf3启动失败,{Msg}");
  110. return;
  111. }
  112. string upRate = Msg.Split('|')[0].Split(',')[1];
  113. string downRate = Msg.Split('|')[1];
  114. ShowMsg(1, $"OK,上行速率: {upRate},下行速率: {downRate}");
  115. ResMax.Text = upRate;
  116. ResMin.Text = downRate;
  117. string tDetail = $"upRate/{upRate};downRate/{downRate}";
  118. CheckPassStation(SN.Text, upRate, downRate, "PASS", tDetail);
  119. }
  120. private void CheckPassStation(string sn, string upRate, string downRate, string testRes,string testDetail)
  121. {
  122. string oWO, oWOId, oErrMsg = "";
  123. if (LogicHandler.CheckStepSNAndMacode(workOrder.Text, User.UserSourceCode, sn, User.UserCode, out oWO, out oWOId, out oErrMsg))
  124. {
  125. if (LogicHandler.SetStepResult(oWO, User.UserSourceCode, sn, "无线吞吐量", "OK", User.UserCode, out oErrMsg))
  126. {
  127. List<string> param = new List<string>() { };
  128. string outMsg = "";
  129. param.Add(oWO);
  130. param.Add(sn);
  131. param.Add(User.UserSourceCode);
  132. param.Add(testRes);
  133. param.Add("");
  134. param.Add("");
  135. param.Add("WirelessThroughput");
  136. param.Add(testDetail);
  137. param.Add(outMsg);
  138. string[] paramList = param.ToArray();
  139. dh.CallProcedure("cs_insert_testrejects", ref paramList);
  140. if (paramList[8].Substring(0, 2) == "OK")
  141. {
  142. ShowMsg(1, $"序列号{sn}采集成功:测试结果为{testRes}");
  143. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, oWO, User.UserLineCode, User.UserSourceCode, "无线吞吐量", "无线吞吐量过站成功", sn, "");
  144. }
  145. }
  146. else
  147. {
  148. ShowMsg(0, $"序列号{sn},处理过站NG:{oErrMsg}");
  149. }
  150. }
  151. else
  152. {
  153. ShowMsg(0, $"序列号{sn},过站核对NG:{oErrMsg}");
  154. }
  155. }
  156. private bool IsCheckSet()
  157. {
  158. if (string.IsNullOrEmpty(IPList.Text))
  159. {
  160. ShowMsg(0, "请选择本地iperf 服务IP地址");
  161. return true;
  162. }
  163. if (string.IsNullOrEmpty(ProductList.Text))
  164. {
  165. ShowMsg(0, "请选择产品固定IP地址");
  166. return true;
  167. }
  168. if (string.IsNullOrEmpty(Account.Text))
  169. {
  170. ShowMsg(0, "请输入Telnet登录账号");
  171. return true;
  172. }
  173. if (string.IsNullOrEmpty(Password.Text))
  174. {
  175. ShowMsg(0, "请输入Telnet登录密码");
  176. return true;
  177. }
  178. if (string.IsNullOrEmpty(ExePath.Text))
  179. {
  180. ShowMsg(0, "请输入启动iperf3文件");
  181. return true;
  182. }
  183. if (!File.Exists(ExePath.Text))
  184. {
  185. Console.WriteLine("iperf3启动文件不存在");
  186. }
  187. if (string.IsNullOrEmpty(TestTime.Text))
  188. {
  189. ShowMsg(0, "请输入测试时长");
  190. return true;
  191. }
  192. //if (Locat1.Checked == false || Locat2.Checked == false || Locat3.Checked == false)
  193. //{
  194. // ShowMsg(0, "请选择固件位置");
  195. // return true;
  196. //}
  197. //if (Radio1.Checked == false || Radio1.Checked == false )
  198. //{
  199. // ShowMsg(0, "请选择测试类型");
  200. // return true;
  201. //}
  202. return false;
  203. }
  204. private void UpdateSN(string type, string sn)
  205. {
  206. if (type == "C")
  207. {
  208. serialNumber.Text = "";
  209. workOrder.Text = "";
  210. productCode.Text = "";
  211. productName.Text = "";
  212. }
  213. else if (type == "L")
  214. {
  215. SQL.Clear();
  216. SQL.Append($@"SELECT ms_sncode,ma_code,pr_code,pr_spec FROM makeserial,make,product
  217. WHERE ms_sncode = '{sn}' AND ms_makecode = ma_code AND ms_prodcode = pr_code");
  218. dt = (DataTable)dh.ExecuteSql(SQL.ToString(), "select");
  219. if (dt.Rows.Count > 0)
  220. {
  221. serialNumber.Text = dt.Rows[0]["ms_sncode"].ToString();
  222. workOrder.Text = dt.Rows[0]["ma_code"].ToString();
  223. productCode.Text = dt.Rows[0]["pr_code"].ToString();
  224. productName.Text = dt.Rows[0]["pr_spec"].ToString();
  225. }
  226. else
  227. {
  228. UpdateSN("C", sn);
  229. }
  230. }
  231. }
  232. public class CameraIperfTester
  233. {
  234. int timeOut;
  235. string cameraIp;
  236. int cameraPort;
  237. string username;
  238. string password;
  239. string iperfServerIp;
  240. int iperfServerPort;
  241. private TcpClient _telnetClient;
  242. private NetworkStream _telnetStream;
  243. string sVal1, sVal2, rVal1, rVal2;
  244. public CameraIperfTester(string timeOut, string cameraIp, int cameraPort, string username, string password, string iperfServerIp, int iperfServerPort)
  245. {
  246. this.timeOut = Convert.ToInt32(timeOut) * 1000;
  247. this.cameraIp = cameraIp;
  248. this.cameraPort = cameraPort;
  249. this.username = username;
  250. this.password = password;
  251. this.iperfServerIp = iperfServerIp;
  252. this.iperfServerPort = iperfServerPort;
  253. }
  254. public string StartIperfTest(string SN, string iperfPath,string logDirectory, string[] CList)
  255. {
  256. if (_telnetStream == null)
  257. return "NG,未建立连接";
  258. try
  259. {
  260. foreach (var comItem in CList)
  261. {
  262. WriteStream(_telnetStream, comItem);
  263. ReadStream(_telnetStream);
  264. }
  265. Thread.Sleep(1000); // 等服务端启动
  266. string upLog = Path.Combine(logDirectory, $"{SN}_up.log");
  267. string downLog = Path.Combine(logDirectory, $"{SN}_down.log");
  268. //RunIperfClient($"-c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8 -R", iperfPath, upLog);
  269. //RunIperfClient($"-c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8", iperfPath, downLog);
  270. RunIperfClient($"./iperf3_mstar -c {cameraIp} -p {iperfServerPort} -i l -b 100M -t 10 -R", iperfPath, upLog);
  271. RunIperfClient($"./iperf3_mstar -c {cameraIp} -p {iperfServerPort} -i l -b 100M -t 10", iperfPath, downLog);
  272. string upRate = ParseIperfBitrate(upLog);
  273. string downRate = ParseIperfBitrate(downLog);
  274. return $"OK,{upRate}|{downRate}";
  275. }
  276. catch (Exception ex)
  277. {
  278. return $"NG,{ex.Message}";
  279. }
  280. }
  281. public string TelnetConnect()
  282. {
  283. try
  284. {
  285. _telnetClient = new TcpClient();
  286. IAsyncResult connectResult = _telnetClient.BeginConnect(cameraIp, cameraPort, null, null);
  287. bool connected = connectResult.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeOut));
  288. if (!connected)
  289. {
  290. _telnetClient.Close();
  291. return "NG,连接超时";
  292. }
  293. try
  294. {
  295. _telnetClient.EndConnect(connectResult);
  296. }
  297. catch (SocketException ex)
  298. {
  299. return $"NG,连接失败: {ex.Message}";
  300. }
  301. _telnetStream = _telnetClient.GetStream();
  302. _telnetStream.ReadTimeout = 3000; // 3S读取超时
  303. StringBuilder fullResponse = new StringBuilder();
  304. string welcomeResponse = ReadStream(_telnetStream);
  305. fullResponse.Append(welcomeResponse);
  306. WriteStream(_telnetStream, username);
  307. string usernameResponse = ReadStream(_telnetStream);
  308. fullResponse.Append(usernameResponse);
  309. WriteStream(_telnetStream, password);
  310. string loginResponse = ReadStream(_telnetStream);
  311. fullResponse.Append(loginResponse);
  312. return $"OK,{fullResponse.ToString()}";
  313. }
  314. catch (Exception ex)
  315. {
  316. return $"NG,{ex.Message}";
  317. }
  318. }
  319. private void RunIperfClient(string args, string path, string logPath)
  320. {
  321. var psi = new ProcessStartInfo
  322. {
  323. FileName = path,
  324. Arguments = args,
  325. RedirectStandardOutput = true,
  326. RedirectStandardError = true,
  327. UseShellExecute = false,
  328. CreateNoWindow = true
  329. };
  330. using (var process = Process.Start(psi))
  331. {
  332. string output = process.StandardOutput.ReadToEnd();
  333. string error = process.StandardError.ReadToEnd();
  334. process.WaitForExit(5000); // 最多等 15 秒
  335. File.WriteAllText(logPath, output + Environment.NewLine + error);
  336. }
  337. }
  338. public string ParseIperfBitrate(string logPath)
  339. {
  340. if (!File.Exists(logPath)) return "0.0";
  341. var lines = File.ReadAllLines(logPath);
  342. List<string> logItem = new List<string> { };
  343. foreach (var line in lines)
  344. {
  345. if (line.Trim().StartsWith("[SUM]"))
  346. {
  347. logItem.Add(line);
  348. }
  349. }
  350. if (logItem.Count > 0 && logItem[logItem.Count - 2].Contains("sender"))
  351. {
  352. var match = Regex.Match(logItem[logItem.Count - 2], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)");
  353. if (match.Success)
  354. {
  355. sVal1 = match.Groups[1].Value;
  356. sVal2 = match.Groups[2].Value;
  357. }
  358. }
  359. if (logItem.Count > 0 && logItem[logItem.Count -1].Contains("receiver"))
  360. {
  361. var match = Regex.Match(logItem[logItem.Count - 1], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)");
  362. if (match.Success)
  363. {
  364. rVal1 = match.Groups[1].Value;
  365. rVal2 = match.Groups[2].Value;
  366. }
  367. }
  368. //double num1 = (double.Parse(sVal1.Split(' ')[0]) + double.Parse(rVal1.Split(' ')[0])) / 2;
  369. //double num2 = (double.Parse(sVal2.Split(' ')[0]) + double.Parse(rVal2.Split(' ')[0])) / 2;
  370. return rVal2;
  371. }
  372. private void WriteStream(NetworkStream stream, string text)
  373. {
  374. byte[] data = Encoding.ASCII.GetBytes(text + "\r\n");
  375. stream.Write(data, 0, data.Length);
  376. stream.Flush();
  377. }
  378. private string ReadStream(NetworkStream stream)
  379. {
  380. StringBuilder sb = new StringBuilder();
  381. byte[] buffer = new byte[1024];
  382. int totalBytesRead = 0;
  383. int currentBytesRead = 0;
  384. DateTime lastReadTime = DateTime.UtcNow;
  385. TimeSpan idleTimeout = TimeSpan.FromMilliseconds(800); // 空闲超时
  386. try
  387. {
  388. do
  389. {
  390. currentBytesRead = stream.Read(buffer, 0, buffer.Length);
  391. if (currentBytesRead > 0)
  392. {
  393. sb.Append(Encoding.ASCII.GetString(buffer, 0, currentBytesRead));
  394. totalBytesRead += currentBytesRead;
  395. lastReadTime = DateTime.UtcNow;
  396. }
  397. } while ((DateTime.UtcNow - lastReadTime) < idleTimeout);
  398. }
  399. catch (IOException ioEx)
  400. {
  401. }
  402. catch (ObjectDisposedException)
  403. {
  404. throw;
  405. }
  406. catch (SocketException sockEx)
  407. {
  408. throw new IOException($"NG,网络错误: {sockEx.Message}", sockEx);
  409. }
  410. return sb.ToString();
  411. }
  412. }
  413. private void ShowMsg(int type, string msg)
  414. {
  415. msg = msg.Replace("\r", "").Replace("\n", "");
  416. string msgTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  417. string showMsg = $"{msgTime}: {msg}\n";
  418. if (type == 0)
  419. {
  420. OperatResult.AppendText(showMsg, Color.Red);
  421. }
  422. else if (type == 1)
  423. {
  424. OperatResult.AppendText(showMsg, Color.Green);
  425. }
  426. }
  427. private void Radio1_Click(object sender, EventArgs e)
  428. {
  429. if (Radio1.Checked)
  430. {
  431. Radio2.Checked = false;
  432. }
  433. }
  434. private void Radio2_Click(object sender, EventArgs e)
  435. {
  436. if (Radio2.Checked)
  437. {
  438. Radio1.Checked = false;
  439. }
  440. }
  441. private void Locat1_Click(object sender, EventArgs e)
  442. {
  443. if (Locat1.Checked)
  444. {
  445. Locat2.Checked = false;
  446. Locat3.Checked = false;
  447. }
  448. }
  449. private void Locat2_Click(object sender, EventArgs e)
  450. {
  451. if (Locat2.Checked)
  452. {
  453. Locat1.Checked = false;
  454. Locat3.Checked = false;
  455. }
  456. }
  457. private void Locat3_Click(object sender, EventArgs e)
  458. {
  459. if (Locat3.Checked)
  460. {
  461. Locat1.Checked = false;
  462. Locat2.Checked = false;
  463. }
  464. }
  465. private void Account_KeyDown(object sender, KeyEventArgs e)
  466. {
  467. if (e.KeyCode != Keys.Enter) return;
  468. Password.Focus();
  469. Password.SelectAll();
  470. }
  471. private void Password_KeyDown(object sender, KeyEventArgs e)
  472. {
  473. if (e.KeyCode != Keys.Enter) return;
  474. TestTime.Focus();
  475. TestTime.SelectAll();
  476. }
  477. private void ExePath_Click(object sender, EventArgs e)
  478. {
  479. using (OpenFileDialog openFileDialog = new OpenFileDialog())
  480. {
  481. openFileDialog.Title = "选择iperf3启动文件";
  482. openFileDialog.Filter = "可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*";
  483. openFileDialog.FilterIndex = 1;
  484. openFileDialog.RestoreDirectory = true;
  485. // 设置初始目录(可选)
  486. if (!string.IsNullOrEmpty(ExePath.Text) && System.IO.File.Exists(ExePath.Text))
  487. {
  488. openFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(ExePath.Text);
  489. }
  490. else
  491. {
  492. openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  493. }
  494. if (openFileDialog.ShowDialog() == DialogResult.OK)
  495. {
  496. ExePath.Text = openFileDialog.FileName;
  497. ShowMsg(1, $"已成功选择iperf3启动文件");
  498. }
  499. }
  500. }
  501. private void Clear_Click(object sender, EventArgs e)
  502. {
  503. OperatResult.Clear();
  504. }
  505. }
  506. }