Make_WirelessThroughput.cs 19 KB

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