XYD_ScrewDriver.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using TeamAAS_VP.Enums;
  8. using TeamAAS_VP.Interfaces;
  9. namespace TeamAAS_VP.Core.ScrewDriver
  10. {
  11. /*
  12. 计划(伪代码):
  13. 1. 为类添加 XML 文档注释,描述此驱动器的用途与协议相关信息。
  14. 2. 为构造函数、属性、事件、公开方法(Connect/ConnectAsync/GetData/GetDataAsync/Dispose)添加注释,说明用途与返回值。
  15. 3. 为内部重要方法(EnsureSocket/SendGetTspc/ReceiveOnce/UpdateConnectState/DataAnalysis/ToInt16/ToInt32N)添加注释,解释实现细节与特殊字节序处理。
  16. 4. 在 DataAnalysis 中为每个解析字段添加注释,标明字节偏移与单位转换,保留对异常与边界检查的说明。
  17. 5. 保持原有逻辑不变,只增加注释,保证与现有代码风格一致并能通过编译。
  18. */
  19. /// <summary>
  20. /// XYD 系列电动螺丝刀数据读取与解析器。
  21. /// 通过 UDP 向设备发送 "GET_TSPC" 探测命令并接收包含 TSPB/TSPA 数据包的响应,
  22. /// 解析设备返回的扭矩、角度、速度、时间等曲线和结果信息。
  23. /// </summary>
  24. public class XYD_ScrewDriver : IScrewDriver
  25. {
  26. private Socket _socket;
  27. private IPEndPoint _endPoint;
  28. // 协议最小数据长度(TSPB 固定头与描述长度)
  29. private const int MinDataLength = 508;
  30. #region 属性
  31. public Guid Id { get; private set; }
  32. private bool _isConnected;
  33. /// <summary>
  34. /// 当前连接状态(是否已与设备建立连接并成功接收过有效数据)。
  35. /// </summary>
  36. public bool IsConnected => _isConnected;
  37. /// <summary>
  38. /// 螺丝刀设备 IP 地址。
  39. /// </summary>
  40. public string IPAdress { get; private set; }
  41. /// <summary>
  42. /// 设备端口号。
  43. /// </summary>
  44. public int Port { get; private set; }
  45. /// <summary>
  46. /// 螺丝刀品牌标识(XYD 固定)。
  47. /// </summary>
  48. public ElectricScrewdriverBrand Brand => ElectricScrewdriverBrand.XYD;
  49. /// <summary>
  50. /// 螺丝编号(设备返回的整型编号)。
  51. /// </summary>
  52. public int ScrewNum { get; private set; }
  53. /// <summary>
  54. /// 曲线采样频率(单位:Hz 或协议定义的采样单位)。
  55. /// </summary>
  56. public int Frequency { get; private set; }
  57. /// <summary>
  58. /// 结果时间戳(设备返回的年月日时分秒)。
  59. /// </summary>
  60. public DateTime ResultDateTime { get; private set; }
  61. /// <summary>
  62. /// 锁止角(单位:度)。
  63. /// </summary>
  64. public double LockAngel { get; private set; }
  65. public double StrokeAngle1 { get; private set; }
  66. public double StrokeAngle2 { get; private set; }
  67. public double StrokeAngle3 { get; private set; }
  68. public double StrokeAngle4 { get; private set; }
  69. public double StrokeAngle5 { get; private set; }
  70. public double StrokeTorque1 { get; private set; }
  71. public double StrokeTorque2 { get; private set; }
  72. public double StrokeTorque3 { get; private set; }
  73. public double StrokeTorque4 { get; private set; }
  74. public double StrokeTorque5 { get; private set; }
  75. /// <summary>
  76. /// 峰值扭矩(单位:N·m,协议返回值需乘以 0.001)。
  77. /// </summary>
  78. public double MaxTorque { get; private set; }
  79. public double OverlockAngle { get; private set; }
  80. /// <summary>
  81. /// 过锁扭矩(单位:N·m)。
  82. /// </summary>
  83. public double OverlockTorque { get; private set; }
  84. public double SlopeCheck { get; private set; }
  85. public double ClampingAngle { get; private set; }
  86. public double ClampingAngleCheck { get; private set; }
  87. public double FitAngle { get; private set; }
  88. public double FitAngleCheck { get; private set; }
  89. /// <summary>
  90. /// 夹紧扭矩(单位:N·m)。
  91. /// </summary>
  92. public double ClampingTorque { get; private set; }
  93. public double ClampingTorqueCheck { get; private set; }
  94. /// <summary>
  95. /// 过程最大扭矩(单位:N·m)。
  96. /// </summary>
  97. public double ProcessMaxTorque { get; private set; }
  98. public double ProcessMaxTorqueCheck { get; private set; }
  99. public double FitPointCoord { get; private set; }
  100. public double FitAngle1 { get; private set; }
  101. /// <summary>
  102. /// 贴合点扭矩(单位:N·m)。
  103. /// </summary>
  104. public double FitTorque { get; private set; }
  105. public double SectionTooth { get; private set; }
  106. public double SectionStroke1 { get; private set; }
  107. public double SectionStroke2 { get; private set; }
  108. public double SectionStroke3 { get; private set; }
  109. public double SectionStroke4 { get; private set; }
  110. public double SectionStroke5 { get; private set; }
  111. public double SectionLockAngle { get; private set; }
  112. public double SectionLockFinish1 { get; private set; }
  113. public double SectionOverLock { get; private set; }
  114. public double SectionFinalEnd { get; private set; }
  115. /// <summary>
  116. /// 解析出的错误信息或结果说明(根据设备返回码映射)。
  117. /// </summary>
  118. public string ErrorInfo { get; private set; }
  119. /// <summary>
  120. /// 本次结果是否判定为成功(设备返回结果码为 4 表示成功)。
  121. /// </summary>
  122. public bool Success { get; private set; }
  123. public int ProgramNumber { get; private set; }
  124. /// <summary>
  125. /// 总圈数(单位:圈,协议返回为度需除以 360)。
  126. /// </summary>
  127. public double Truns { get; private set; }
  128. /// <summary>
  129. /// 结果扭矩值(单位:N·m)。
  130. /// </summary>
  131. public double TorqueValue { get; private set; }
  132. public int FinalTime { get; private set; }
  133. /// <summary>
  134. /// 曲线数据集合(解析后的时间、角度、扭矩、斜率等)。
  135. /// </summary>
  136. public List<WaveData> WaveDatas { get; } = new List<WaveData>();
  137. #endregion
  138. #region 事件
  139. /// <summary>
  140. /// 连接状态变化事件,参数:sender, connected。
  141. /// 当连接状态改变时触发(包括连接失败/成功与获取数据后状态更新)。
  142. /// </summary>
  143. public event Action<object, bool> ConnectStateChangedEvent;
  144. #endregion
  145. /// <summary>
  146. /// 构造函数,初始化目标设备的 IP 与端口。
  147. /// </summary>
  148. /// <param name="ip">设备 IP 地址</param>
  149. /// <param name="port">设备 UDP 端口</param>
  150. public XYD_ScrewDriver(string ip, int port)
  151. {
  152. IPAdress = ip;
  153. Port = port;
  154. Id=Guid.NewGuid();
  155. }
  156. /// <summary>
  157. /// 确保内部 Socket 已创建并配置好超时与目标 EndPoint。
  158. /// 如果已存在则直接返回。
  159. /// </summary>
  160. private void EnsureSocket()
  161. {
  162. if (_socket == null)
  163. {
  164. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  165. // 发送/接收超时,避免阻塞 UI 线程过久
  166. _socket.SendTimeout = 1000;
  167. _socket.ReceiveTimeout = 2000;
  168. _endPoint = new IPEndPoint(System.Net.IPAddress.Parse(IPAdress), Port);
  169. }
  170. }
  171. /// <summary>
  172. /// 同步连接到设备并进行一次探测(发送 GET_TSPC 并解析响应)。
  173. /// 返回是否成功连接并解析到有效数据。
  174. /// </summary>
  175. public bool Connect()
  176. {
  177. try
  178. {
  179. EnsureSocket();
  180. _socket.Connect(_endPoint);
  181. // 发送探测命令并等待响应
  182. if (!SendGetTspc())
  183. {
  184. UpdateConnectState(false);
  185. return false;
  186. }
  187. byte[] data = ReceiveOnce();
  188. if (data == null || !DataAnalysis(data))
  189. {
  190. UpdateConnectState(false);
  191. return false;
  192. }
  193. UpdateConnectState(true);
  194. return true;
  195. }
  196. catch (Exception)
  197. {
  198. UpdateConnectState(false);
  199. return false;
  200. }
  201. }
  202. /// <summary>
  203. /// 异步版本的 Connect。
  204. /// </summary>
  205. public Task<bool> ConnectAsync()
  206. {
  207. return Task.Run(() => Connect());
  208. }
  209. /// <summary>
  210. /// 向设备请求数据并解析,最多尝试若干次(容错网络丢包)。
  211. /// </summary>
  212. public bool GetData()
  213. {
  214. if (_socket == null)
  215. {
  216. EnsureSocket();
  217. }
  218. // 允许多次重试以应对 UDP 丢包/超时
  219. for (int i = 0; i < 10; i++)
  220. {
  221. try
  222. {
  223. if (!SendGetTspc())
  224. continue;
  225. byte[] data = ReceiveOnce();
  226. if (data == null)
  227. continue;
  228. if (!DataAnalysis(data))
  229. continue;
  230. UpdateConnectState(true);
  231. return true;
  232. }
  233. catch (Exception)
  234. {
  235. UpdateConnectState(false);
  236. }
  237. }
  238. return false;
  239. }
  240. /// <summary>
  241. /// 异步版本的 GetData。
  242. /// </summary>
  243. public Task<bool> GetDataAsync()
  244. {
  245. return Task.Run(() => GetData());
  246. }
  247. /// <summary>
  248. /// 发送协议探测命令 "GET_TSPC" 到设备。
  249. /// 返回是否发送成功。
  250. /// </summary>
  251. private bool SendGetTspc()
  252. {
  253. try
  254. {
  255. var cmd = "GET_TSPC";
  256. var bytes = Encoding.ASCII.GetBytes(cmd);
  257. _socket.SendTo(bytes, _endPoint);
  258. return true;
  259. }
  260. catch
  261. {
  262. // 发送失败通常来自网络/Socket 状态,调用方会做重试或断开处理
  263. return false;
  264. }
  265. }
  266. /// <summary>
  267. /// 从 Socket 接收一次数据(单次 ReceiveFrom),并返回实际接收到的字节数组。
  268. /// 超时或异常返回 null。
  269. /// </summary>
  270. private byte[] ReceiveOnce()
  271. {
  272. try
  273. {
  274. EndPoint remote = new IPEndPoint(System.Net.IPAddress.Any, 0);
  275. byte[] buf = new byte[_socket.ReceiveBufferSize];
  276. int len = _socket.ReceiveFrom(buf, ref remote);
  277. if (len <= 0) return null;
  278. var data = new byte[len];
  279. Array.Copy(buf, 0, data, 0, len);
  280. return data;
  281. }
  282. catch
  283. {
  284. // 接收异常(例如超时),返回 null 以触发上层重试逻辑
  285. return null;
  286. }
  287. }
  288. /// <summary>
  289. /// 更新连接状态并触发事件。
  290. /// </summary>
  291. /// <param name="connected">新的连接状态</param>
  292. private void UpdateConnectState(bool connected)
  293. {
  294. _isConnected = connected;
  295. ConnectStateChangedEvent?.Invoke(this, connected);
  296. }
  297. /// <summary>
  298. /// 释放资源实现(受保护,可由派生类覆盖)。
  299. /// </summary>
  300. /// <param name="disposing">是否为显式释放</param>
  301. protected virtual void Dispose(bool disposing)
  302. {
  303. if (disposing)
  304. {
  305. if (_socket != null)
  306. {
  307. try
  308. {
  309. _socket.Shutdown(SocketShutdown.Both);
  310. }
  311. catch { }
  312. _socket.Close();
  313. _socket.Dispose();
  314. _socket = null;
  315. }
  316. }
  317. }
  318. /// <summary>
  319. /// 释放所有托管资源并抑制终结化。
  320. /// </summary>
  321. public void Dispose()
  322. {
  323. Dispose(true);
  324. GC.SuppressFinalize(this);
  325. }
  326. /// <summary>
  327. /// 解析设备返回的字节数据(TSPB + 可选的 TSPA 曲线数据)。
  328. /// 对协议字段按固定偏移解析并进行单位转换。
  329. /// 返回解析是否成功(数据完整且符合长度要求)。
  330. /// </summary>
  331. /// <param name="data">原始字节数据</param>
  332. /// <returns>是否解析成功</returns>
  333. private bool DataAnalysis(byte[] data)
  334. {
  335. if (data == null || data.Length < MinDataLength)
  336. return false;
  337. try
  338. {
  339. #region 注释(协议字段说明)
  340. // 协议字节说明(基于设备文档):
  341. // 1 - 4 “TSPB”
  342. // 5 - 8 螺丝编号 (4 bytes, DCBA order)
  343. // 9 - 10 曲线采样频率 (2 bytes)
  344. // 11 - 22 结果日期 - 年 月 日 时 分 秒 (每项 2 bytes)
  345. // 23 - 24 程序编号
  346. // 25 - 26 总圈数 (单位:度)
  347. // 27 锁止角度 (2 bytes)
  348. // 29 结果扭矩 (2 bytes)
  349. // 31 结果时间 (2 bytes)
  350. // 33 锁附结果 (2 bytes)
  351. // 35 ... 94 各阶段角度/扭矩等(按文档固定偏移)
  352. // 205 TSPA 数据起始坐标(协议中以 1-base 或 0-base 可能不同)
  353. // 207 TSPA 数据总数(样本点数)
  354. // 随后按扭矩/速度/角度/斜率分别存放(每项为 2 bytes,sectionBytes = length * 2)
  355. #endregion
  356. // 基本字段解析
  357. ScrewNum = ToInt32N(data, 4);
  358. Frequency = ToInt16(data, 8);
  359. int year = ToInt16(data, 10);
  360. int month = ToInt16(data, 12);
  361. int day = ToInt16(data, 14);
  362. int hour = ToInt16(data, 16);
  363. int minute = ToInt16(data, 18);
  364. int second = ToInt16(data, 20);
  365. ResultDateTime = new DateTime(year, month, day, hour, minute, second);
  366. ProgramNumber = ToInt16(data, 22);
  367. // 设备返回的总圈数字段以度为单位,转换为圈
  368. Truns = ToInt16(data, 24) / 360.0;
  369. LockAngel = ToInt16(data, 26);
  370. // 扭矩值以 mN·m(或协议指定单位)返回,乘以 0.001 转换为 N·m
  371. TorqueValue = ToInt16(data, 28) * 0.001;
  372. FinalTime = ToInt16(data, 30);
  373. int finalResult = ToInt16(data, 32);
  374. switch (finalResult)
  375. {
  376. case 1: ErrorInfo = "圈数异常"; break;
  377. case 2: ErrorInfo = "区段行程NG"; break;
  378. case 3: ErrorInfo = "超时"; break;
  379. case 4: ErrorInfo = string.Empty; break;
  380. case 5: ErrorInfo = "中断"; break;
  381. case 6: ErrorInfo = "转矩过大"; break;
  382. case 7: ErrorInfo = "反转"; break;
  383. case 8: ErrorInfo = "锁止角不合格"; break;
  384. case 9: ErrorInfo = "过锁异常"; break;
  385. case 10: ErrorInfo = "斜率异常"; break;
  386. case 11: ErrorInfo = "夹角异常"; break;
  387. case 12: ErrorInfo = "贴合角异常"; break;
  388. case 13: ErrorInfo = "夹紧力异常"; break;
  389. case 14: ErrorInfo = "过程力异常"; break;
  390. default: ErrorInfo = finalResult.ToString(); break;
  391. }
  392. Success = finalResult == 4;
  393. // 阶段行程角度:协议中以度为单位,代码将其转换为圈(度/360)
  394. StrokeAngle1 = ToInt16(data, 34) / 360.0;
  395. StrokeAngle2 = ToInt16(data, 36) / 360.0;
  396. StrokeAngle3 = ToInt16(data, 38) / 360.0;
  397. StrokeAngle4 = ToInt16(data, 40) / 360.0;
  398. StrokeAngle5 = ToInt16(data, 42) / 360.0;
  399. // 阶段扭矩转换(单位缩放)
  400. StrokeTorque1 = ToInt16(data, 44) * 0.001;
  401. StrokeTorque2 = ToInt16(data, 46) * 0.001;
  402. StrokeTorque3 = ToInt16(data, 48) * 0.001;
  403. StrokeTorque4 = ToInt16(data, 50) * 0.001;
  404. StrokeTorque5 = ToInt16(data, 52) * 0.001;
  405. MaxTorque = ToInt16(data, 54) * 0.001;
  406. OverlockAngle = ToInt16(data, 56);
  407. OverlockTorque = ToInt16(data, 58) * 0.001;
  408. SlopeCheck = ToInt16(data, 60);
  409. ClampingAngle = ToInt16(data, 62);
  410. ClampingAngleCheck = ToInt16(data, 64);
  411. FitAngle = ToInt16(data, 66);
  412. FitAngleCheck = ToInt16(data, 68);
  413. ClampingTorque = ToInt16(data, 70) * 0.001;
  414. ClampingTorqueCheck = ToInt16(data, 72);
  415. ProcessMaxTorque = ToInt16(data, 74) * 0.001;
  416. ProcessMaxTorqueCheck = ToInt16(data, 76);
  417. FitPointCoord = ToInt16(data, 78);
  418. FitAngle1 = ToInt16(data, 80);
  419. FitTorque = ToInt16(data, 82) * 0.001;
  420. SectionTooth = ToInt16(data, 84);
  421. SectionStroke1 = ToInt16(data, 86);
  422. SectionStroke2 = ToInt16(data, 88);
  423. SectionStroke3 = ToInt16(data, 90);
  424. SectionStroke4 = ToInt16(data, 92);
  425. SectionStroke5 = ToInt16(data, 94);
  426. SectionLockAngle = ToInt16(data, 96);
  427. SectionLockFinish1 = ToInt16(data, 98);
  428. SectionOverLock = ToInt16(data, 100);
  429. SectionFinalEnd = ToInt16(data, 102);
  430. // 计算 TSPA 曲线数据段长度(协议: 在偏移 504/506 存有开始/结束索引或总数)
  431. int length = ToInt16(data, 506) - ToInt16(data, 504);
  432. if (length <= 0)
  433. {
  434. // 无曲线数据,清空集合并返回成功
  435. WaveDatas.Clear();
  436. return true;
  437. }
  438. int sectionBytes = length * 2;
  439. int expectedTotal = 508 + sectionBytes * 4;
  440. // 如果整体长度不足,则认为数据不完整,返回失败以触发重试
  441. if (data.Length < expectedTotal)
  442. return false;
  443. var torques = new byte[sectionBytes];
  444. var speeds = new byte[sectionBytes];
  445. var angles = new byte[sectionBytes];
  446. var slopes = new byte[sectionBytes];
  447. // 按顺序从数据中拷贝各段(扭矩、速度、角度、斜率)
  448. Array.Copy(data, 508, torques, 0, sectionBytes);
  449. Array.Copy(data, 508 + sectionBytes, speeds, 0, sectionBytes);
  450. Array.Copy(data, 508 + sectionBytes * 2, angles, 0, sectionBytes);
  451. Array.Copy(data, 508 + sectionBytes * 3, slopes, 0, sectionBytes);
  452. WaveDatas.Clear();
  453. // 每 2 字节为一个样本,使用 ToInt16 解析(注意字节序)
  454. for (int i = 0; i < sectionBytes; i += 2)
  455. {
  456. double angleVal = ToInt16(angles, i) / 360.0;
  457. double torqueVal = ToInt16(torques, i) * 0.001;
  458. double slopeVal = ToInt16(slopes, i);
  459. // 时间:按采样频率换算(单位:秒),注意 i 为字节索引,样本索引为 i/2
  460. double time = (Frequency * i) / 1000.0;
  461. WaveDatas.Add(new WaveData
  462. {
  463. LockAngle = angleVal,
  464. Torque = torqueVal,
  465. Slopes = slopeVal,
  466. Turns = angleVal,
  467. Time = time
  468. });
  469. }
  470. return true;
  471. }
  472. catch
  473. {
  474. // 任意解析或转换异常均视为解析失败
  475. return false;
  476. }
  477. }
  478. /// <summary>
  479. /// 将指定数组中从 startIndex 开始的两个字节按设备协议的字节序解析为有符号 16 位值。
  480. /// 协议采用“DCBA 风格(低字节在前,高字节在后)”,因此这里以小端方式合成。
  481. /// </summary>
  482. /// <param name="value">字节数组</param>
  483. /// <param name="startIndex">起始索引</param>
  484. /// <returns>解析出的 short 值,出错返回 0</returns>
  485. private short ToInt16(byte[] value, int startIndex)
  486. {
  487. if (value == null || startIndex < 0 || startIndex + 1 >= value.Length)
  488. return 0;
  489. // data is DCBA style (little-endian word swapped)
  490. return (short)((value[startIndex + 1] << 8) | value[startIndex]);
  491. }
  492. /// <summary>
  493. /// 将指定数组中从 startIndex 开始的 4 个字节按设备协议解析为 32 位整型(DCBA 顺序)。
  494. /// 注意字节顺序为设备特定格式,这里按原实现保持位移组合。
  495. /// </summary>
  496. /// <param name="value">字节数组</param>
  497. /// <param name="startIndex">起始索引</param>
  498. /// <returns>解析出的 int 值,出错返回 0</returns>
  499. private int ToInt32N(byte[] value, int startIndex)
  500. {
  501. if (value == null || startIndex < 0 || startIndex + 3 >= value.Length)
  502. return 0;
  503. // DCBA order -> 构造 32 位整数(高位在后面的索引)
  504. return (value[startIndex + 3] << 24) | (value[startIndex + 2] << 16) | (value[startIndex + 1] << 8) | value[startIndex];
  505. }
  506. /// <summary>
  507. /// 曲线数据结构,包含速度、扭矩、角度、圈数、斜率与时间。
  508. /// </summary>
  509. public struct WaveData
  510. {
  511. /// <summary>
  512. /// 速度
  513. /// </summary>
  514. public double Speed { get; set; }
  515. /// <summary>
  516. /// 扭矩
  517. /// </summary>
  518. public double Torque { get; set; }
  519. /// <summary>
  520. /// 角度
  521. /// </summary>
  522. public double LockAngle { get; set; }
  523. /// <summary>
  524. /// 圈数
  525. /// </summary>
  526. public double Turns { get; set; }
  527. /// <summary>
  528. /// 斜率
  529. /// </summary>
  530. public double Slopes { get; set; }
  531. /// <summary>
  532. /// 时间(秒)
  533. /// </summary>
  534. public double Time { get; set; }
  535. }
  536. }
  537. }