MelsecA1EAsciiHsl.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using Curtain.Framework.Utils;
  7. using HslCommunication;
  8. using HslCommunication.Profinet.Melsec;
  9. namespace PCLCommunication
  10. {
  11. public class MelsecA1EAsciiHsl : IDisposable
  12. {
  13. private bool _always = false;
  14. //[NonSerialized]
  15. //public Socket _socket = null;
  16. //[NonSerialized]
  17. private StringBuilder _command = null;
  18. //[NonSerialized]
  19. private string _receive = null;
  20. [NonSerialized]
  21. public MelsecA1EAsciiNet _MelsecA1EAsciiNet = null;
  22. public string Command
  23. {
  24. get
  25. {
  26. return this._command?.ToString();
  27. }
  28. }
  29. public string Receive
  30. {
  31. get
  32. {
  33. return this._receive;
  34. }
  35. }
  36. /// <summary>
  37. /// 是:长连接;否:短连接
  38. /// </summary>
  39. public bool Always
  40. {
  41. get
  42. {
  43. return this._always;
  44. }
  45. set
  46. {
  47. this._always = value;
  48. if (!this._always)
  49. {
  50. this.CloseSocket();
  51. }
  52. else
  53. {
  54. this.ConnectSocket();
  55. }
  56. }
  57. }
  58. ///// <summary>
  59. ///// Socket
  60. ///// </summary>
  61. //[System.Xml.Serialization.XmlIgnore]
  62. //[System.Web.Script.Serialization.ScriptIgnore]
  63. //public Socket Socket
  64. //{
  65. // get
  66. // {
  67. // return this._socket;
  68. // }
  69. //}
  70. /// <summary>
  71. /// 通信超时(3s)
  72. /// </summary>
  73. public int Timeout
  74. {
  75. get;
  76. set;
  77. } = 10000;//3000;
  78. /// <summary>
  79. /// 关闭连接
  80. /// </summary>
  81. public void CloseSocket()
  82. {
  83. try
  84. {
  85. //_socket?.Close();
  86. this._MelsecA1EAsciiNet?.ConnectClose();
  87. }
  88. catch (Exception ex)
  89. {
  90. // TODO log
  91. string j = JsonUtil.FromObject(this);
  92. LogOut.Error(null, ex, j);
  93. //throw ex;
  94. }
  95. finally
  96. {
  97. //_socket = null;
  98. //this._MelsecA1EAsciiNet = null;
  99. }
  100. }
  101. /// <summary>
  102. /// 打开连接
  103. /// </summary>
  104. public void ConnectSocket()
  105. {
  106. try
  107. {
  108. //_socket?.Close();
  109. //this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  110. //this._socket.Connect(IPAddress.Parse(this.IP), this.Port);
  111. //this._socket.SendTimeout = this.Timeout;
  112. //this._socket.ReceiveTimeout = this.Timeout;
  113. this._MelsecA1EAsciiNet?.ConnectClose();
  114. if (this._MelsecA1EAsciiNet == null)
  115. {
  116. this._MelsecA1EAsciiNet = new MelsecA1EAsciiNet(this.IP, this.Port);
  117. }
  118. this._MelsecA1EAsciiNet.ConnectTimeOut = this.Timeout;
  119. this._MelsecA1EAsciiNet.ReceiveTimeOut = this.Timeout;
  120. this._MelsecA1EAsciiNet.ConnectServer();
  121. }
  122. catch (Exception ex)
  123. {
  124. // TODO log
  125. throw ex;
  126. }
  127. finally
  128. {
  129. if (!this._always)
  130. {
  131. CloseSocket();
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// PLC IP
  137. /// </summary>
  138. public string IP
  139. {
  140. get
  141. {
  142. return this._MelsecA1EAsciiNet.IpAddress;
  143. }
  144. set
  145. {
  146. this._MelsecA1EAsciiNet.IpAddress = value;
  147. }
  148. }
  149. /// <summary>
  150. /// PLC Port
  151. /// </summary>
  152. public int Port
  153. {
  154. get
  155. {
  156. return this._MelsecA1EAsciiNet.Port;
  157. }
  158. set
  159. {
  160. this._MelsecA1EAsciiNet.Port = value;
  161. }
  162. }
  163. public MelsecA1EAsciiHsl(string ip, int port)
  164. {
  165. this._MelsecA1EAsciiNet = new MelsecA1EAsciiNet(ip, port);
  166. this._MelsecA1EAsciiNet.ConnectTimeOut = this.Timeout;
  167. this._MelsecA1EAsciiNet.ReceiveTimeOut = this.Timeout;
  168. //this.IP = ip;
  169. //this.Port = port;
  170. }
  171. /// <summary>
  172. /// 读取PLC
  173. /// </summary>
  174. /// <param name="type"></param>
  175. /// <param name="begin"></param>
  176. /// <param name="length"></param>
  177. /// <returns></returns>
  178. public string GetHexData(string type, int begin, int length)
  179. {
  180. this._command = null;
  181. this._receive = null;
  182. string mm = "\r\ntype:" + type + "\r\nbegin:" + begin + "\r\nlength:" + length;
  183. try
  184. {
  185. //if (this._socket == null || !this._always)
  186. //{
  187. // this.CloseSocket();
  188. // this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  189. // this._socket.Connect(IPAddress.Parse(this.IP), this.Port);
  190. // this._socket.SendTimeout = this.Timeout;
  191. // this._socket.ReceiveTimeout = this.Timeout;
  192. //}
  193. // 副标题: 01 【命令:字单位读取】
  194. // PC号: FF 【固定】
  195. // 监视定时器:00 0C 【3秒(单位250毫秒)】
  196. this._command = new StringBuilder("01FF000C");
  197. // 起始软元件编码 D100 => 4420 0000 0064
  198. // 软元件代码
  199. if (type.Length == 1)
  200. {
  201. this._command.Append(MelsecA1EAscii.GetHexAscii(type) + "20");
  202. }
  203. else
  204. {
  205. this._command.Append(MelsecA1EAscii.GetHexAscii(type));
  206. }
  207. // 软元件编码
  208. this._command.Append(begin.ToString("X8"));
  209. // 软元件点数
  210. this._command.Append(length.ToString("X2"));
  211. // 命令结束
  212. this._command.Append("00");
  213. byte[] cmdBytes = Encoding.ASCII.GetBytes(this._command.ToString());
  214. //int cmdResult = this._socket.Send(cmdBytes);
  215. //byte[] receiveBytes = new byte[length * 4 + 4];
  216. //int receiveResult = this._socket.Receive(receiveBytes);
  217. //this._receive = Encoding.ASCII.GetString(receiveBytes, 0, receiveResult);
  218. //if (!this._receive.StartsWith("8100"))
  219. //{
  220. // // TODO log ip port command receive
  221. // string j = JsonUtil.FromObject(this) + mm;
  222. // LogOut.Error(null, null, j);
  223. // return null;
  224. //}
  225. OperateResult<byte[]> result = this._MelsecA1EAsciiNet.ReadFromCoreServer(cmdBytes);
  226. if (result.IsSuccess)
  227. {
  228. this._receive = Encoding.ASCII.GetString(result.Content);
  229. if (!this._receive.StartsWith("8100"))
  230. {
  231. // TODO log ip port command receive
  232. string j = JsonUtil.FromObject(this) + mm;
  233. LogOut.Error(null, null, j);
  234. return null;
  235. }
  236. }
  237. else
  238. {
  239. // TODO log ip port command receive
  240. string j = JsonUtil.FromObject(this) + mm + "\r\nError:" + result.ToMessageShowString();
  241. LogOut.Error(null, null, j);
  242. return null;
  243. }
  244. //return receive.Substring(4);
  245. return this._receive;
  246. }
  247. catch (Exception ex)
  248. {
  249. // TODO log
  250. string j = JsonUtil.FromObject(this) + mm;
  251. LogOut.Error(null, ex, j);
  252. return null;
  253. }
  254. finally
  255. {
  256. if (!this._always)
  257. {
  258. this.CloseSocket();
  259. }
  260. }
  261. }
  262. /// <summary>
  263. /// 读取PLC
  264. /// </summary>
  265. /// <param name="type"></param>
  266. /// <param name="begin"></param>
  267. /// <param name="length"></param>
  268. /// <returns></returns>
  269. public byte[] GetByteData(string type, int begin, int length)
  270. {
  271. string mm = "\r\ntype:" + type + "\r\nbegin:" + begin + "\r\nlength:" + length;
  272. try
  273. {
  274. string str = this.GetHexData(type, begin, length);
  275. if (string.IsNullOrEmpty(str))
  276. {
  277. return null;
  278. }
  279. List<byte> list = new List<byte>();
  280. for (int i = 4; i < str.Length; i = i + 2)
  281. {
  282. list.Add(Convert.ToByte(str.Substring(i, 2), 16));
  283. }
  284. return list.ToArray();
  285. }
  286. catch (Exception ex)
  287. {
  288. // TODO log
  289. string j = JsonUtil.FromObject(this) + mm;
  290. LogOut.Error(null, ex, j);
  291. return null;
  292. }
  293. finally
  294. {
  295. }
  296. }
  297. /// <summary>
  298. /// 写入PLC
  299. /// </summary>
  300. /// <param name="type"></param>
  301. /// <param name="begin"></param>
  302. /// <param name="length"></param>
  303. /// <returns></returns>
  304. public bool SetData(string type, int begin, int length, string hexData)
  305. {
  306. this._command = null;
  307. this._receive = null;
  308. string mm = "\r\ntype:" + type + "\r\nbegin:" + begin + "\r\nlength:" + length + "\r\nhexData:" + hexData;
  309. try
  310. {
  311. //if (this._socket == null || !this._always)
  312. //{
  313. // this.CloseSocket();
  314. // this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  315. // this._socket.Connect(IPAddress.Parse(this.IP), this.Port);
  316. // this._socket.SendTimeout = this.Timeout;
  317. // this._socket.ReceiveTimeout = this.Timeout;
  318. //}
  319. // 副标题: 03 【命令:字单位写入】
  320. // PC号: FF 【固定】
  321. // 监视定时器:00 0C 【3秒(单位250毫秒)】
  322. this._command = new StringBuilder("03FF000C");
  323. // 起始软元件编码 D100 => 4420 0000 0064
  324. // 软元件代码
  325. if (type.Length == 1)
  326. {
  327. this._command.Append(MelsecA1EAscii.GetHexAscii(type) + "20");
  328. }
  329. else
  330. {
  331. this._command.Append(MelsecA1EAscii.GetHexAscii(type));
  332. }
  333. // 软元件编码
  334. this._command.Append(begin.ToString("X8"));
  335. // 软元件点数
  336. this._command.Append(length.ToString("X2"));
  337. // 命令结束
  338. this._command.Append("00");
  339. // 写入补齐
  340. int count = length * 4;
  341. if (hexData.Length < count)
  342. {
  343. hexData = hexData.PadRight(count, '0');
  344. }
  345. //if (hexData.Length > count)
  346. //{
  347. // hexData = hexData.Substring(0, count);
  348. //}
  349. // 写入
  350. this._command.Append(hexData);
  351. byte[] cmdBytes = Encoding.ASCII.GetBytes(this._command.ToString());
  352. //int cmdResult = this._socket.Send(cmdBytes);
  353. //byte[] receiveBytes = new byte[1024];
  354. //int receiveResult = this._socket.Receive(receiveBytes);
  355. //this._receive = Encoding.ASCII.GetString(receiveBytes, 0, receiveResult);
  356. //if (!this._receive.StartsWith("8300"))
  357. //{
  358. // // TODO log ip port command receive
  359. // string j = JsonUtil.FromObject(this) + mm;
  360. // LogOut.Error(null, null, j);
  361. // return false;
  362. //}
  363. OperateResult<byte[]> result = this._MelsecA1EAsciiNet.ReadFromCoreServer(cmdBytes);
  364. if (result.IsSuccess)
  365. {
  366. this._receive = Encoding.ASCII.GetString(result.Content);
  367. if (!this._receive.StartsWith("8300"))
  368. {
  369. // TODO log ip port command receive
  370. string j = JsonUtil.FromObject(this) + mm;
  371. LogOut.Error(null, null, j);
  372. return false;
  373. }
  374. }
  375. else
  376. {
  377. // TODO log ip port command receive
  378. string j = JsonUtil.FromObject(this) + mm + "\r\nError:" + result.ToMessageShowString();
  379. LogOut.Error(null, null, j);
  380. return false;
  381. }
  382. return true;
  383. }
  384. catch (Exception ex)
  385. {
  386. // TODO log
  387. string j = JsonUtil.FromObject(this) + mm;
  388. LogOut.Error(null, ex, j);
  389. return false;
  390. }
  391. finally
  392. {
  393. if (!this._always)
  394. {
  395. this.CloseSocket();
  396. }
  397. }
  398. }
  399. /// <summary>
  400. /// 写入PLC
  401. /// </summary>
  402. /// <param name="type"></param>
  403. /// <param name="begin"></param>
  404. /// <param name="hexData"></param>
  405. /// <returns></returns>
  406. public bool SetData(string type, int begin, string hexData)
  407. {
  408. int length = (int)(hexData.Length / 4.0 + 0.5);
  409. return this.SetData(type, begin, length, hexData);
  410. }
  411. /// <summary>
  412. /// 写入PLC
  413. /// </summary>
  414. /// <param name="type"></param>
  415. /// <param name="begin"></param>
  416. /// <returns></returns>
  417. public bool SetData(string type, int begin, byte[] data)
  418. {
  419. try
  420. {
  421. StringBuilder sb = new StringBuilder();
  422. foreach (byte item in data)
  423. {
  424. sb.Append(item.ToString("X2"));
  425. }
  426. return SetData(type, begin, sb.ToString());
  427. }
  428. catch (Exception ex)
  429. {
  430. // TODO log
  431. LogOut.Error(null, ex);
  432. return false;
  433. }
  434. finally
  435. {
  436. }
  437. }
  438. /// <summary>
  439. /// 写入PLC
  440. /// </summary>
  441. /// <param name="type"></param>
  442. /// <param name="begin"></param>
  443. /// <param name="length"></param>
  444. /// <returns></returns>
  445. public bool SetData(string type, int begin, int length, byte[] data)
  446. {
  447. try
  448. {
  449. StringBuilder sb = new StringBuilder();
  450. foreach (byte item in data)
  451. {
  452. sb.Append(item.ToString("X2"));
  453. }
  454. return SetData(type, begin, length, sb.ToString());
  455. }
  456. catch (Exception ex)
  457. {
  458. // TODO log
  459. LogOut.Error(null, ex);
  460. return false;
  461. }
  462. finally
  463. {
  464. if (!this._always)
  465. {
  466. this.CloseSocket();
  467. }
  468. }
  469. }
  470. public void Do(string command)
  471. {
  472. this._command = null;
  473. this._receive = null;
  474. try
  475. {
  476. //if (this._socket == null || !this._always)
  477. //{
  478. // this.CloseSocket();
  479. // this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  480. // this._socket.Connect(IPAddress.Parse(this.IP), this.Port);
  481. // this._socket.SendTimeout = this.Timeout;
  482. // this._socket.ReceiveTimeout = this.Timeout;
  483. //}
  484. this._command = new StringBuilder(command);
  485. byte[] cmdBytes = Encoding.ASCII.GetBytes(command);
  486. //int cmdResult = this._socket.Send(cmdBytes);
  487. //byte[] receiveBytes = new byte[4096];
  488. //int receiveResult = this._socket.Receive(receiveBytes);
  489. //this._receive = Encoding.ASCII.GetString(receiveBytes, 0, receiveResult);
  490. OperateResult<byte[]> result = this._MelsecA1EAsciiNet.ReadFromCoreServer(cmdBytes);
  491. if (result.IsSuccess)
  492. {
  493. this._receive = Encoding.ASCII.GetString(result.Content);
  494. }
  495. else
  496. {
  497. // TODO log ip port command receive
  498. string j = JsonUtil.FromObject(this) + "\r\nError:" + result.ToMessageShowString();
  499. LogOut.Error(null, null, j);
  500. }
  501. }
  502. catch (Exception ex)
  503. {
  504. // TODO log
  505. string j = JsonUtil.FromObject(this);
  506. LogOut.Error(null, ex, j);
  507. }
  508. finally
  509. {
  510. if (!this._always)
  511. {
  512. this.CloseSocket();
  513. }
  514. }
  515. }
  516. /// <summary>
  517. /// 获取字符串对应的2进制Ascii码(字符=>命令)
  518. /// </summary>
  519. /// <param name="value"></param>
  520. /// <returns></returns>
  521. public static string GetHexAscii(string value)
  522. {
  523. if (string.IsNullOrEmpty(value))
  524. {
  525. return "";
  526. }
  527. byte[] bs = Encoding.ASCII.GetBytes(value);
  528. if (bs.Length > 1)
  529. {
  530. StringBuilder sb = new StringBuilder();
  531. foreach (byte item in bs)
  532. {
  533. sb.Append(item.ToString("X2"));
  534. }
  535. return sb.ToString();
  536. }
  537. else
  538. {
  539. return bs[0].ToString("X2");
  540. }
  541. }
  542. /// <summary>
  543. /// 获取2进制Ascii码对应的字符串(命令=>字符)
  544. /// </summary>
  545. /// <param name="value"></param>
  546. /// <returns></returns>
  547. public static string GetByHexAscii(string value)
  548. {
  549. if (string.IsNullOrWhiteSpace(value))
  550. {
  551. return null;
  552. }
  553. List<byte> list = new List<byte>();
  554. for (int i = 0; i < value.Length; i = i + 2)
  555. {
  556. list.Add(Convert.ToByte(value.Substring(i, 2), 16));
  557. }
  558. return Encoding.ASCII.GetString(list.ToArray());
  559. }
  560. /// <summary>
  561. /// 销毁
  562. /// </summary>
  563. public void Dispose()
  564. {
  565. try
  566. {
  567. this.CloseSocket();
  568. }
  569. catch
  570. {
  571. }
  572. }
  573. }
  574. }