DeviceOPCUat.cs 24 KB

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