OpcUaUtils.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using Newtonsoft.Json;
  2. using Opc.Ua;
  3. using OpcUaHelper;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using Kede;
  11. using Newtonsoft.Json.Linq;
  12. namespace TestAgreement.utils
  13. {
  14. internal class OpcUaUtils
  15. {
  16. public static ResponseBody OpcCaiji(string url,string userName,string password,List<string> list)
  17. {
  18. Console.WriteLine("===============科德机床OPCUa数据采集start================");
  19. ResponseBody responseBody = new ResponseBody();
  20. responseBody.code = 1;
  21. try
  22. {
  23. /*string url = "opc.tcp://192.168.11.63:12686";
  24. string userName = "";
  25. string password = "";*/
  26. OpcUaClient opcUaClient = new OpcUaClient();
  27. // 创建连接
  28. if (!string.IsNullOrEmpty(url) && string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password))
  29. {
  30. opcUaClient.ConnectServer(url);
  31. }
  32. else if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
  33. {
  34. opcUaClient.UserIdentity = new UserIdentity(userName, password);
  35. opcUaClient.ConnectServer(url);
  36. }
  37. // 批量获取值
  38. List<NodeId> nodeIdList = new List<NodeId>();
  39. list.ForEach(vo =>
  40. {
  41. nodeIdList.Add(vo);
  42. });
  43. //nodeIdList.Add("ns=2;s=cncVariablesInfo/variables-var1");//主轴负载
  44. //nodeIdList.Add("ns=2;s=cncVariablesInfo/variables-var1");//进给倍率
  45. List<DataValue> values = opcUaClient.ReadNodes(nodeIdList.ToArray());
  46. List<string> valuesList = new List<string>();
  47. for (int i = 0; i < values.Count; i++)
  48. {
  49. valuesList.Add(values[i].ToString());
  50. }
  51. responseBody.values = valuesList;
  52. // 关闭连接
  53. if (opcUaClient != null)
  54. {
  55. opcUaClient.Disconnect();
  56. }
  57. }
  58. catch (Exception ex)
  59. {
  60. Console.WriteLine("连接失败报错:" + ex);
  61. responseBody.code=0;
  62. responseBody.msg = ex.Message;
  63. }
  64. return responseBody;
  65. }
  66. }
  67. }