DeviceOPCUat.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. using Opc.Ua;
  2. using Opc.Ua.Client;
  3. using SinumerikOpcUaAPI;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace YG.Device
  10. {
  11. public class DeviceOPCUat
  12. {
  13. Server opcserver;
  14. EndpointDescription endpointDescription;
  15. public bool IsOn { get; set; } = false;
  16. public DeviceOPCUat(string url, string username = "OpcUaClient", string pwd = "12345678")
  17. {
  18. if (opcserver == null || !opcserver.Session.Connected)
  19. {
  20. IsOn = OpcUa_Connection(url, username, pwd);
  21. YG.Log.Instance.WriteLogAdd("OPCUA 连接是否成功===>>" + IsOn);
  22. }
  23. }
  24. public bool IsConnection { get; set; } = false;
  25. private void Notification_KeepAlive(Session sender, KeepAliveEventArgs e)
  26. {
  27. try
  28. {
  29. if (sender != this.opcserver.Session || !ServiceResult.IsBad(e.Status))
  30. return;
  31. this.opcserver.Session.Reconnect();
  32. YG.Log.Instance.WriteLogAdd($"35----->>----->>----->>----->>----->>----->>----->>----->>----->>----->>----->>Notification_KeepAlive");
  33. IsConnection = true;
  34. }
  35. catch (Exception ex)
  36. {
  37. IsConnection = false;
  38. YG.Log.Instance.WriteLogAdd($"41-->>{ex.Message}");
  39. }
  40. }
  41. /// <summary>
  42. /// 获取NC下边的文件列表
  43. /// </summary>
  44. /// <returns></returns>
  45. public ReferenceDescriptionCollection OpcUa_BrowseNode()
  46. {
  47. return opcserver.BrowseNode(new NodeId("Sinumerik/FileSystem/NCExtend/webApiMESFILE/", (ushort)2).ToString());
  48. }
  49. #region 终止连接
  50. public void OpcUa_Close()
  51. {
  52. if (OpcUa_ConState())
  53. {
  54. opcserver.Disconnect();
  55. }
  56. }
  57. private bool OpcUa_ConState()
  58. {
  59. if (opcserver != null && opcserver.Session.Connected)
  60. {
  61. return true;
  62. }
  63. else
  64. {
  65. YG.Log.Instance.WriteLogAdd("OPC没有连接");
  66. }
  67. return false;
  68. }
  69. #endregion
  70. #region 写入
  71. public bool OpcUa_Write(string address, object value)
  72. {
  73. try
  74. {
  75. if (OpcUa_ConState())
  76. {
  77. opcserver.WriteValues(new List<string>() { value.ToString() }, new List<string>() { address });
  78. return true;
  79. }
  80. return false;
  81. }
  82. catch (Exception ex)
  83. {
  84. YG.Log.Instance.WriteLogAdd($"92-->{ex.Message}");
  85. return false;
  86. }
  87. }
  88. public bool OpcUa_WriteValue(string address, object value)
  89. {
  90. try
  91. {
  92. string str = new NodeId(address, (ushort)2).ToString();
  93. if (OpcUa_ConState())
  94. {
  95. opcserver.WriteValues(new List<string>() { value.ToString() }, new List<string>() { str });
  96. return true;
  97. }
  98. return false;
  99. }
  100. catch (Exception ex)
  101. {
  102. YG.Log.Instance.WriteLogAdd($"110->{ex.Message}");
  103. return false;
  104. }
  105. }
  106. public bool OpcUa_WriteValue(List<string> addresses, List<string> values)
  107. {
  108. try
  109. {
  110. if (OpcUa_ConState())
  111. {
  112. opcserver.WriteValues(addresses, values);
  113. return true;
  114. }
  115. return false;
  116. }
  117. catch (Exception ex)
  118. {
  119. YG.Log.Instance.WriteLogAdd($"110->{ex.Message}");
  120. return false;
  121. }
  122. }
  123. #endregion
  124. #region 选中
  125. public bool OpcUa_Select(string filename)
  126. {
  127. bool result = false;
  128. try
  129. {
  130. if (OpcUa_ConState())
  131. {
  132. string extension = System.IO.Path.GetExtension(filename);
  133. if (string.IsNullOrWhiteSpace(extension) || !extension.ToUpper().Equals(".MPF"))
  134. {
  135. // System.Windows.Forms.MessageBox.Show("请选择要上传的文件");
  136. return false;
  137. }
  138. try
  139. {
  140. string value = opcserver.MethodCallSelectProgram(filename, Convert.ToUInt32(1)).status;
  141. if (value.Equals("Good"))
  142. {
  143. result = true;
  144. }
  145. }
  146. catch (Exception ex)
  147. {
  148. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  149. //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
  150. }
  151. }
  152. return result;
  153. }
  154. catch (Exception ex)
  155. {
  156. YG.Log.Instance.WriteLogAdd($"154--->{ex.Message}");
  157. return false;
  158. }
  159. }
  160. public bool OpcUa_Select(string path, string filename)
  161. {
  162. bool result = false;
  163. try
  164. {
  165. if (OpcUa_ConState())
  166. {
  167. string extension = System.IO.Path.GetExtension(filename);
  168. if (string.IsNullOrWhiteSpace(extension) || !extension.ToUpper().Equals(".MPF"))
  169. {
  170. //System.Windows.Forms.MessageBox.Show("请选择要上传的文件");
  171. return false;
  172. }
  173. try
  174. {
  175. string value = opcserver.MethodCallSelectProgram(path + filename, Convert.ToUInt32(1)).status;
  176. if (value.Equals("Good"))
  177. {
  178. result = true;
  179. }
  180. }
  181. catch (Exception ex)
  182. {
  183. YG.Log.Instance.WriteLogAdd($"182-->{ex.Message}");
  184. //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
  185. }
  186. }
  187. return result;
  188. }
  189. catch (Exception ex)
  190. {
  191. YG.Log.Instance.WriteLogAdd($"192-->{ex.Message}");
  192. return false;
  193. }
  194. }
  195. #endregion
  196. #region 读取
  197. public bool OpcUa_Read(string address, out string value)
  198. {
  199. bool result = false;
  200. value = "";
  201. if (OpcUa_ConState())
  202. {
  203. try
  204. {
  205. string itemaddress = $"/Plc/{address}";
  206. string str = new NodeId(itemaddress, (ushort)2).ToString();
  207. if (opcserver != null && opcserver.Session.Connected)
  208. {
  209. value = opcserver.ReadValues(new List<string>() { str })[0];
  210. }
  211. result = true;
  212. }
  213. catch (Exception ex)
  214. {
  215. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  216. //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
  217. }
  218. }
  219. return result;
  220. }
  221. /// <summary>
  222. ///
  223. /// </summary>
  224. /// <param name="address">list里边的地址格式为I2.0,I2.1,DB2.DBX35.0等格式</param>
  225. /// <param name="value">查询出来的值和上面的值是一一对应的关系</param>
  226. /// <returns></returns>
  227. public bool OpcUa_Read(List<string> address, out List<string> value)
  228. {
  229. value = new List<string>();
  230. try
  231. {
  232. List<string> nodeIdStrings = new List<string>();
  233. foreach (string s in address)
  234. {
  235. nodeIdStrings.Add(new NodeId($"/Plc/{s}", (ushort)2).ToString());
  236. }
  237. if (opcserver != null && opcserver.Session.Connected)
  238. {
  239. value = opcserver.ReadValues(nodeIdStrings);
  240. }
  241. return true;
  242. }
  243. catch (Exception ex)
  244. {
  245. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  246. //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
  247. return false;
  248. }
  249. }
  250. public List<string> OpcUa_Read(List<string> address)
  251. {
  252. List<string> value = new List<string>();
  253. try
  254. {
  255. List<string> nodeIdStrings = new List<string>();
  256. if (opcserver != null && opcserver.Session != null && opcserver.Session.Connected)
  257. {
  258. value = opcserver.ReadValues(nodeIdStrings);
  259. }
  260. return value;
  261. }
  262. catch (Exception ex)
  263. {
  264. try
  265. {
  266. OpcUa_Connection(opcserver.Session.ConfiguredEndpoint.ToString());
  267. }
  268. catch (Exception esx)
  269. {
  270. YG.Log.Instance.WriteLogAdd($"284------->>esx---->{esx.Message} {ex.Message}--->>>");
  271. }
  272. return value;
  273. }
  274. }
  275. public bool OpcUa_Read(List<string> address, out Dictionary<string, string> value)
  276. {
  277. value = new Dictionary<string, string>();
  278. try
  279. {
  280. List<string> nodeIdStrings = new List<string>();
  281. foreach (string s in address)
  282. {
  283. nodeIdStrings.Add(new NodeId($"/Plc/{s}", (ushort)2).ToString());
  284. value.Add(s, "");
  285. }
  286. if (opcserver != null && opcserver.Session.Connected)
  287. {
  288. List<string> Keys = value.Keys.ToList();
  289. List<string> items = opcserver.ReadValues(nodeIdStrings);
  290. for (int i = 0; i < items.Count; i++)
  291. {
  292. value[Keys[i]] = items[i];
  293. }
  294. }
  295. return true;
  296. }
  297. catch (Exception ex)
  298. {
  299. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  300. //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
  301. return false;
  302. }
  303. }
  304. #endregion
  305. #region OPCUA连接
  306. /// <summary>
  307. /// 连接opcua
  308. /// </summary>
  309. /// <param name="url"></param>
  310. /// <param name="username"></param>
  311. /// <param name="pwd"></param>
  312. public bool OpcUa_Connection(string url, string username = "OpcUaClient", string pwd = "12345678")
  313. {
  314. bool result = false;
  315. try
  316. {
  317. opcserver = new Server();
  318. ApplicationDescriptionCollection applicationDescriptions = opcserver.FindServers(url);
  319. if (applicationDescriptions.Count == 0)
  320. {
  321. YG.Log.Instance.WriteLogAdd("没有找到服务!");
  322. }
  323. else if (applicationDescriptions.Count == 1)
  324. {
  325. applicationDescriptions[0].DiscoveryUrls.Where(m => m.Equals(url)).FirstOrDefault().FirstOrDefaultYG(
  326. (t) =>
  327. {
  328. try
  329. {
  330. var cc = opcserver.GetEndpoints(t);
  331. opcserver.GetEndpoints(t).Where(n => n.EndpointUrl.Equals(url)).FirstOrDefault().FirstOrDefaultYG((tt) =>
  332. {
  333. try
  334. {
  335. endpointDescription = tt;
  336. opcserver.KeepAliveNotification += new KeepAliveEventHandler(this.Notification_KeepAlive);
  337. opcserver.Connect(tt, true, username, pwd);
  338. if (opcserver.Session.Connected)
  339. {
  340. IsConnection = true;
  341. result = true;
  342. }
  343. else
  344. {
  345. result = false;
  346. }
  347. }
  348. catch (Exception ex)
  349. {
  350. YG.Log.Instance.WriteLogAdd($"355-->{ex.Message}");
  351. result = false;
  352. }
  353. });
  354. }
  355. catch (Exception ext)
  356. {
  357. YG.Log.Instance.WriteLogAdd($"362-->{ext.Message}");
  358. }
  359. });
  360. }
  361. }
  362. catch (Exception eex) { YG.Log.Instance.WriteLogAdd($"368-->{eex.Message}-->{url}"); }
  363. return result;
  364. }
  365. /// <summary>
  366. /// 连接opcua
  367. /// </summary>
  368. /// <param name="url"></param>
  369. /// <param name="username"></param>
  370. /// <param name="pwd"></param>
  371. public static Server OpcUa_Connection1(string url, string username = "OpcUaClient", string pwd = "12345678")
  372. {
  373. Server serverOpcUa = new Server();
  374. try
  375. {
  376. ApplicationDescriptionCollection applicationDescriptions = serverOpcUa.FindServers(url);
  377. if (applicationDescriptions.Count == 0)
  378. {
  379. YG.Log.Instance.WriteLogAdd("没有找到服务!");
  380. }
  381. else if (applicationDescriptions.Count == 1)
  382. {
  383. applicationDescriptions[0].DiscoveryUrls.Where(m => m.Equals(url)).FirstOrDefault().FirstOrDefaultYG(
  384. (t) =>
  385. {
  386. try
  387. {
  388. var cc = serverOpcUa.GetEndpoints(t);
  389. serverOpcUa.GetEndpoints(t).Where(n => n.EndpointUrl.Equals(url)).FirstOrDefault().FirstOrDefaultYG((tt) =>
  390. {
  391. try
  392. {
  393. serverOpcUa.Connect(tt, true, username, pwd);
  394. }
  395. catch (Exception ex)
  396. {
  397. YG.Log.Instance.WriteLogAdd($"355-->{ex.Message}");
  398. }
  399. });
  400. }
  401. catch (Exception ext)
  402. {
  403. YG.Log.Instance.WriteLogAdd($"362-->{ext.Message}");
  404. }
  405. });
  406. }
  407. }
  408. catch (Exception eex) { YG.Log.Instance.WriteLogAdd($"368-->{eex.Message}-->{url}"); }
  409. return serverOpcUa;
  410. }
  411. #endregion
  412. #region 添加用户权限
  413. /// <summary>
  414. /// 添加用户权限
  415. /// </summary>
  416. /// <param name="username"></param>
  417. public bool OpcUa_Access(string username = "OpcUaClient")
  418. {
  419. bool resultb = true;
  420. if (OpcUa_ConState())
  421. {
  422. try
  423. {
  424. string result = "";
  425. string strValue = "StateRead,StateWrite,FrameRead,FrameWrite,SeaRead,SeaWrite,TeaRead,TeaWrite,ToolRead,ToolWrite,DriveRead,DriveWrite,GudRead,GudWrite,PlcRead,PlcWrite,AlarmRead,FsRead,FsWrite,ApWrite,CsomReadx,CsomWritex,PlcReadDBx,PlcWriteDBx,SinuReadAll,SinuWriteAll";
  426. {
  427. string[] vs = strValue.Split(new string[] { "," }, StringSplitOptions.None);
  428. foreach (string s in vs)
  429. {
  430. Server.MethodCallResult methodCallResult = opcserver.MethodCall("/Methods/GiveUserAccess", username, s);
  431. if (methodCallResult != null && !methodCallResult.status.Equals("Good"))
  432. {
  433. result += s + methodCallResult.status;
  434. }
  435. }
  436. }
  437. if (result.Length > 0)
  438. {
  439. resultb = false;
  440. YG.Log.Instance.WriteLogAdd($"执行权限添加是出现异常:{result}");
  441. }
  442. }
  443. catch (Exception ex)
  444. {
  445. resultb = false;
  446. YG.Log.Instance.WriteLogAdd($"409-->{ex.Message}");
  447. }
  448. }
  449. return resultb;
  450. }
  451. #endregion
  452. #region 上传文件
  453. /// <summary>
  454. /// 上传文件,不能是文件夹,只能是一个文件,已经默认了一个文件位置, 如果有其他需求后期做调整
  455. /// </summary>
  456. /// <param name="file">需要上传的文件的名字,这个名字是有后缀的,</param>
  457. public void OpcUa_UpLoadFile(string file)
  458. {
  459. try
  460. {
  461. string extension = System.IO.Path.GetExtension(file);
  462. if (string.IsNullOrWhiteSpace(extension))
  463. {
  464. //System.Windows.Forms.MessageBox.Show("请选择要上传的文件");
  465. return;
  466. }
  467. try
  468. {
  469. opcserver.MethodCallCreateNewFile("Sinumerik/FileSystem/NCExtend/webApiMESFILE/", System.IO.Path.GetFileName(file), true);
  470. byte[] data = opcserver.ReadFile(file);
  471. int copylen = 5000;
  472. bool isover = true;
  473. byte[] bt = new byte[copylen];
  474. if (data.Length > copylen)
  475. {
  476. int runcount = data.Length / copylen;
  477. for (int i = 0; i < runcount; i++)
  478. {
  479. Array.Copy(data, i * copylen, bt, 0, copylen);
  480. if (i > 0)
  481. {
  482. isover = false;
  483. }
  484. var cc = opcserver.MethodCallCopyFileToServer($"/Methods/CopyFileToServer", $"Sinumerik/FileSystem/NCExtend/webApiMESFILE/{System.IO.Path.GetFileName(file)}", data, isover);
  485. System.Console.WriteLine($"当前循环到的位置:{i}-->>{cc.status}");
  486. }
  487. int lastleng = data.Length % copylen;
  488. bt = new byte[lastleng];
  489. Array.Copy(data, runcount * copylen, bt, 0, lastleng);
  490. Server.MethodCallResult methodCallResult = opcserver.MethodCallCopyFileToServer($"/Methods/CopyFileToServer", $"Sinumerik/FileSystem/NCExtend/webApiMESFILE/{System.IO.Path.GetFileName(file)}", data, isover);
  491. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  492. {
  493. YG.Log.Instance.WriteLogAdd("上传文件成功");
  494. }
  495. else
  496. {
  497. YG.Log.Instance.WriteLogAdd("上传文件失败");
  498. }
  499. }
  500. else
  501. {
  502. Server.MethodCallResult methodCallResult = opcserver.MethodCallCopyFileToServer($"/Methods/CopyFileToServer", $"Sinumerik/FileSystem/NCExtend/webApiMESFILE/{System.IO.Path.GetFileName(file)}", data, isover);
  503. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  504. {
  505. YG.Log.Instance.WriteLogAdd("上传文件成功");
  506. }
  507. else
  508. {
  509. YG.Log.Instance.WriteLogAdd("上传文件失败");
  510. }
  511. }
  512. }
  513. catch (Exception ex)
  514. {
  515. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  516. //System.Windows.Forms.MessageBox.Show($"{ex.Message}");
  517. }
  518. }
  519. catch (Exception ex)
  520. {
  521. YG.Log.Instance.WriteLogAdd($"493-->{ex.Message}");
  522. }
  523. }
  524. #endregion
  525. #region 删除文件
  526. /// <summary>
  527. /// 删除文件,只能是一个文件,已经默认了一个文件位置, 如果有其他需求后期做调整
  528. /// </summary>
  529. /// <param name="file">需要删除的文件的名字,这个名字是有后缀的</param>
  530. public void OpcUa_DeleteFile(string file)
  531. {
  532. try
  533. {
  534. Server.MethodCallResult methodCallResult = opcserver.MethodCallDeleteFile($"Sinumerik/FileSystem/NCExtend/webApiMESFILE/{file}");
  535. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  536. {
  537. YG.Log.Instance.WriteLogAdd("删除文件成功");
  538. }
  539. else
  540. {
  541. YG.Log.Instance.WriteLogAdd("删除文件失败");
  542. }
  543. }
  544. catch (Exception ex)
  545. {
  546. YG.Log.Instance.WriteLogAdd($"519-->{ex.Message}");
  547. }
  548. }
  549. public string OpcUa_DeleteFile(string path, string file)
  550. {
  551. string status = "";
  552. try
  553. {
  554. status = opcserver.MethodCallDeleteFile(path + file).status;
  555. if (status.ToUpper().Equals("GOOD"))
  556. {
  557. YG.Log.Instance.WriteLogAdd("删除文件成功");
  558. }
  559. else
  560. {
  561. YG.Log.Instance.WriteLogAdd("删除文件失败");
  562. }
  563. }
  564. catch (Exception ex)
  565. {
  566. YG.Log.Instance.WriteLogAdd($"539-->{ex.Message}");
  567. }
  568. return status;
  569. }
  570. #endregion
  571. #region 创建文件目录
  572. /// <summary>
  573. /// 创建文件目录,,
  574. /// </summary>
  575. /// <param name="file">类似于文件夹名称</param>
  576. public void OpcUa_CreateNewFile(string file = "webApiMESFILE")
  577. {
  578. try
  579. {
  580. Server.MethodCallResult methodCallResult = opcserver.MethodCallCreateNewDir($"Sinumerik/FileSystem/NCExtend", file);
  581. if (methodCallResult.status.ToUpper().Equals("GOOD"))
  582. {
  583. YG.Log.Instance.WriteLogAdd("删除文件成功");
  584. }
  585. else
  586. {
  587. YG.Log.Instance.WriteLogAdd("删除文件失败");
  588. }
  589. }
  590. catch (Exception ex)
  591. {
  592. YG.Log.Instance.WriteLogAdd($"565-->{ex.Message}");
  593. }
  594. }
  595. #endregion
  596. public void disConnect()
  597. {
  598. if (opcserver.Session.Connected)
  599. {
  600. opcserver.Disconnect();
  601. }
  602. }
  603. }
  604. }