XYD_ScrewDriver.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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 || data.Length==0)
  189. {
  190. return false;
  191. }
  192. //if (data == null || !DataAnalysis(data))
  193. //{
  194. // UpdateConnectState(true);
  195. // return true;
  196. //}
  197. UpdateConnectState(true);
  198. return true;
  199. }
  200. catch (Exception)
  201. {
  202. UpdateConnectState(false);
  203. return false;
  204. }
  205. }
  206. /// <summary>
  207. /// 异步版本的 Connect。
  208. /// </summary>
  209. public Task<bool> ConnectAsync()
  210. {
  211. return Task.Run(() => Connect());
  212. }
  213. /// <summary>
  214. /// 向设备请求数据并解析,最多尝试若干次(容错网络丢包)。
  215. /// </summary>
  216. public bool GetData()
  217. {
  218. if (_socket == null)
  219. {
  220. EnsureSocket();
  221. }
  222. // 允许多次重试以应对 UDP 丢包/超时
  223. for (int i = 0; i < 10; i++)
  224. {
  225. try
  226. {
  227. if (!SendGetTspc())
  228. continue;
  229. byte[] data = ReceiveOnce();
  230. if (data == null)
  231. continue;
  232. if (!DataAnalysis(data))
  233. continue;
  234. UpdateConnectState(true);
  235. return true;
  236. }
  237. catch (Exception)
  238. {
  239. UpdateConnectState(false);
  240. }
  241. }
  242. return false;
  243. }
  244. /// <summary>
  245. /// 异步版本的 GetData。
  246. /// </summary>
  247. public Task<bool> GetDataAsync()
  248. {
  249. return Task.Run(() => GetData());
  250. }
  251. /// <summary>
  252. /// 发送协议探测命令 "GET_TSPC" 到设备。
  253. /// 返回是否发送成功。
  254. /// </summary>
  255. private bool SendGetTspc()
  256. {
  257. try
  258. {
  259. var cmd = "GET_TSPC";
  260. var bytes = Encoding.ASCII.GetBytes(cmd);
  261. _socket.SendTo(bytes, _endPoint);
  262. return true;
  263. }
  264. catch
  265. {
  266. // 发送失败通常来自网络/Socket 状态,调用方会做重试或断开处理
  267. return false;
  268. }
  269. }
  270. /// <summary>
  271. /// 从 Socket 接收一次数据(单次 ReceiveFrom),并返回实际接收到的字节数组。
  272. /// 超时或异常返回 null。
  273. /// </summary>
  274. private byte[] ReceiveOnce()
  275. {
  276. try
  277. {
  278. EndPoint remote = new IPEndPoint(System.Net.IPAddress.Any, 0);
  279. byte[] buf = new byte[_socket.ReceiveBufferSize];
  280. int len = _socket.ReceiveFrom(buf, ref remote);
  281. if (len <= 0) return null;
  282. var data = new byte[len];
  283. Array.Copy(buf, 0, data, 0, len);
  284. return data;
  285. }
  286. catch
  287. {
  288. // 接收异常(例如超时),返回 null 以触发上层重试逻辑
  289. return null;
  290. }
  291. }
  292. /// <summary>
  293. /// 更新连接状态并触发事件。
  294. /// </summary>
  295. /// <param name="connected">新的连接状态</param>
  296. private void UpdateConnectState(bool connected)
  297. {
  298. _isConnected = connected;
  299. ConnectStateChangedEvent?.Invoke(this, connected);
  300. }
  301. /// <summary>
  302. /// 释放资源实现(受保护,可由派生类覆盖)。
  303. /// </summary>
  304. /// <param name="disposing">是否为显式释放</param>
  305. protected virtual void Dispose(bool disposing)
  306. {
  307. if (disposing)
  308. {
  309. if (_socket != null)
  310. {
  311. try
  312. {
  313. _socket.Shutdown(SocketShutdown.Both);
  314. }
  315. catch { }
  316. _socket.Close();
  317. _socket.Dispose();
  318. _socket = null;
  319. }
  320. }
  321. }
  322. /// <summary>
  323. /// 释放所有托管资源并抑制终结化。
  324. /// </summary>
  325. public void Dispose()
  326. {
  327. Dispose(true);
  328. GC.SuppressFinalize(this);
  329. }
  330. /// <summary>
  331. /// 解析设备返回的字节数据(TSPB + 可选的 TSPA 曲线数据)。
  332. /// 对协议字段按固定偏移解析并进行单位转换。
  333. /// 返回解析是否成功(数据完整且符合长度要求)。
  334. /// </summary>
  335. /// <param name="data">原始字节数据</param>
  336. /// <returns>是否解析成功</returns>
  337. private bool DataAnalysis(byte[] data)
  338. {
  339. if (data == null || data.Length < MinDataLength)
  340. return false;
  341. try
  342. {
  343. #region 注释(协议字段说明)
  344. // 协议字节说明(基于设备文档):
  345. // 1 - 4 “TSPB”
  346. // 5 - 8 螺丝编号 (4 bytes, DCBA order)
  347. // 9 - 10 曲线采样频率 (2 bytes)
  348. // 11 - 22 结果日期 - 年 月 日 时 分 秒 (每项 2 bytes)
  349. // 23 - 24 程序编号
  350. // 25 - 26 总圈数 (单位:度)
  351. // 27 锁止角度 (2 bytes)
  352. // 29 结果扭矩 (2 bytes)
  353. // 31 结果时间 (2 bytes)
  354. // 33 锁附结果 (2 bytes)
  355. // 35 ... 94 各阶段角度/扭矩等(按文档固定偏移)
  356. // 205 TSPA 数据起始坐标(协议中以 1-base 或 0-base 可能不同)
  357. // 207 TSPA 数据总数(样本点数)
  358. // 随后按扭矩/速度/角度/斜率分别存放(每项为 2 bytes,sectionBytes = length * 2)
  359. #endregion
  360. // 基本字段解析
  361. ScrewNum = ToInt32N(data, 4);
  362. Frequency = ToInt16(data, 8);
  363. int year = ToInt16(data, 10);
  364. int month = ToInt16(data, 12);
  365. int day = ToInt16(data, 14);
  366. int hour = ToInt16(data, 16);
  367. int minute = ToInt16(data, 18);
  368. int second = ToInt16(data, 20);
  369. ResultDateTime = new DateTime(year, month, day, hour, minute, second);
  370. ProgramNumber = ToInt16(data, 22);
  371. // 设备返回的总圈数字段以度为单位,转换为圈
  372. Truns = ToInt16(data, 24) / 360.0;
  373. LockAngel = ToInt16(data, 26);
  374. // 扭矩值以 mN·m(或协议指定单位)返回,乘以 0.001 转换为 N·m
  375. TorqueValue = ToInt16(data, 28) * 0.001;
  376. FinalTime = ToInt16(data, 30);
  377. int finalResult = ToInt16(data, 32);
  378. switch (finalResult)
  379. {
  380. case 1: ErrorInfo = "圈数异常"; break;
  381. case 2: ErrorInfo = "区段行程NG"; break;
  382. case 3: ErrorInfo = "超时"; break;
  383. case 4: ErrorInfo = string.Empty; break;
  384. case 5: ErrorInfo = "中断"; break;
  385. case 6: ErrorInfo = "转矩过大"; break;
  386. case 7: ErrorInfo = "反转"; break;
  387. case 8: ErrorInfo = "锁止角不合格"; break;
  388. case 9: ErrorInfo = "过锁异常"; break;
  389. case 10: ErrorInfo = "斜率异常"; break;
  390. case 11: ErrorInfo = "夹角异常"; break;
  391. case 12: ErrorInfo = "贴合角异常"; break;
  392. case 13: ErrorInfo = "夹紧力异常"; break;
  393. case 14: ErrorInfo = "过程力异常"; break;
  394. default: ErrorInfo = finalResult.ToString(); break;
  395. }
  396. Success = finalResult == 4;
  397. // 阶段行程角度:协议中以度为单位,代码将其转换为圈(度/360)
  398. StrokeAngle1 = ToInt16(data, 34) / 360.0;
  399. StrokeAngle2 = ToInt16(data, 36) / 360.0;
  400. StrokeAngle3 = ToInt16(data, 38) / 360.0;
  401. StrokeAngle4 = ToInt16(data, 40) / 360.0;
  402. StrokeAngle5 = ToInt16(data, 42) / 360.0;
  403. // 阶段扭矩转换(单位缩放)
  404. StrokeTorque1 = ToInt16(data, 44) * 0.001;
  405. StrokeTorque2 = ToInt16(data, 46) * 0.001;
  406. StrokeTorque3 = ToInt16(data, 48) * 0.001;
  407. StrokeTorque4 = ToInt16(data, 50) * 0.001;
  408. StrokeTorque5 = ToInt16(data, 52) * 0.001;
  409. MaxTorque = ToInt16(data, 54) * 0.001;
  410. OverlockAngle = ToInt16(data, 56);
  411. OverlockTorque = ToInt16(data, 58) * 0.001;
  412. SlopeCheck = ToInt16(data, 60);
  413. ClampingAngle = ToInt16(data, 62);
  414. ClampingAngleCheck = ToInt16(data, 64);
  415. FitAngle = ToInt16(data, 66);
  416. FitAngleCheck = ToInt16(data, 68);
  417. ClampingTorque = ToInt16(data, 70) * 0.001;
  418. ClampingTorqueCheck = ToInt16(data, 72);
  419. ProcessMaxTorque = ToInt16(data, 74) * 0.001;
  420. ProcessMaxTorqueCheck = ToInt16(data, 76);
  421. FitPointCoord = ToInt16(data, 78);
  422. FitAngle1 = ToInt16(data, 80);
  423. FitTorque = ToInt16(data, 82) * 0.001;
  424. SectionTooth = ToInt16(data, 84);
  425. SectionStroke1 = ToInt16(data, 86);
  426. SectionStroke2 = ToInt16(data, 88);
  427. SectionStroke3 = ToInt16(data, 90);
  428. SectionStroke4 = ToInt16(data, 92);
  429. SectionStroke5 = ToInt16(data, 94);
  430. SectionLockAngle = ToInt16(data, 96);
  431. SectionLockFinish1 = ToInt16(data, 98);
  432. SectionOverLock = ToInt16(data, 100);
  433. SectionFinalEnd = ToInt16(data, 102);
  434. // 计算 TSPA 曲线数据段长度(协议: 在偏移 504/506 存有开始/结束索引或总数)
  435. int length = ToInt16(data, 506) - ToInt16(data, 504);
  436. if (length <= 0)
  437. {
  438. // 无曲线数据,清空集合并返回成功
  439. WaveDatas.Clear();
  440. return true;
  441. }
  442. int sectionBytes = length * 2;
  443. int expectedTotal = 508 + sectionBytes * 4;
  444. // 如果整体长度不足,则认为数据不完整,返回失败以触发重试
  445. if (data.Length < expectedTotal)
  446. return false;
  447. var torques = new byte[sectionBytes];
  448. var speeds = new byte[sectionBytes];
  449. var angles = new byte[sectionBytes];
  450. var slopes = new byte[sectionBytes];
  451. // 按顺序从数据中拷贝各段(扭矩、速度、角度、斜率)
  452. Array.Copy(data, 508, torques, 0, sectionBytes);
  453. Array.Copy(data, 508 + sectionBytes, speeds, 0, sectionBytes);
  454. Array.Copy(data, 508 + sectionBytes * 2, angles, 0, sectionBytes);
  455. Array.Copy(data, 508 + sectionBytes * 3, slopes, 0, sectionBytes);
  456. WaveDatas.Clear();
  457. // 每 2 字节为一个样本,使用 ToInt16 解析(注意字节序)
  458. for (int i = 0; i < sectionBytes; i += 2)
  459. {
  460. double angleVal = ToInt16(angles, i) / 360.0;
  461. double torqueVal = ToInt16(torques, i) * 0.001;
  462. double slopeVal = ToInt16(slopes, i);
  463. // 时间:按采样频率换算(单位:秒),注意 i 为字节索引,样本索引为 i/2
  464. double time = (Frequency * i) / 1000.0;
  465. WaveDatas.Add(new WaveData
  466. {
  467. LockAngle = angleVal,
  468. Torque = torqueVal,
  469. Slopes = slopeVal,
  470. Turns = angleVal,
  471. Time = time
  472. });
  473. }
  474. return true;
  475. }
  476. catch
  477. {
  478. // 任意解析或转换异常均视为解析失败
  479. return false;
  480. }
  481. }
  482. /// <summary>
  483. /// 将指定数组中从 startIndex 开始的两个字节按设备协议的字节序解析为有符号 16 位值。
  484. /// 协议采用“DCBA 风格(低字节在前,高字节在后)”,因此这里以小端方式合成。
  485. /// </summary>
  486. /// <param name="value">字节数组</param>
  487. /// <param name="startIndex">起始索引</param>
  488. /// <returns>解析出的 short 值,出错返回 0</returns>
  489. private short ToInt16(byte[] value, int startIndex)
  490. {
  491. if (value == null || startIndex < 0 || startIndex + 1 >= value.Length)
  492. return 0;
  493. // data is DCBA style (little-endian word swapped)
  494. return (short)((value[startIndex + 1] << 8) | value[startIndex]);
  495. }
  496. /// <summary>
  497. /// 将指定数组中从 startIndex 开始的 4 个字节按设备协议解析为 32 位整型(DCBA 顺序)。
  498. /// 注意字节顺序为设备特定格式,这里按原实现保持位移组合。
  499. /// </summary>
  500. /// <param name="value">字节数组</param>
  501. /// <param name="startIndex">起始索引</param>
  502. /// <returns>解析出的 int 值,出错返回 0</returns>
  503. private int ToInt32N(byte[] value, int startIndex)
  504. {
  505. if (value == null || startIndex < 0 || startIndex + 3 >= value.Length)
  506. return 0;
  507. // DCBA order -> 构造 32 位整数(高位在后面的索引)
  508. return (value[startIndex + 3] << 24) | (value[startIndex + 2] << 16) | (value[startIndex + 1] << 8) | value[startIndex];
  509. }
  510. /// <summary>
  511. /// 曲线数据结构,包含速度、扭矩、角度、圈数、斜率与时间。
  512. /// </summary>
  513. public struct WaveData
  514. {
  515. /// <summary>
  516. /// 速度
  517. /// </summary>
  518. public double Speed { get; set; }
  519. /// <summary>
  520. /// 扭矩
  521. /// </summary>
  522. public double Torque { get; set; }
  523. /// <summary>
  524. /// 角度
  525. /// </summary>
  526. public double LockAngle { get; set; }
  527. /// <summary>
  528. /// 圈数
  529. /// </summary>
  530. public double Turns { get; set; }
  531. /// <summary>
  532. /// 斜率
  533. /// </summary>
  534. public double Slopes { get; set; }
  535. /// <summary>
  536. /// 时间(秒)
  537. /// </summary>
  538. public double Time { get; set; }
  539. }
  540. }
  541. }