Scada.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using NewLife.IO;
  5. using OPC_Client;
  6. namespace ScadaTcpService
  7. {
  8. public class Scada
  9. {
  10. private readonly string _opcServerName;
  11. private readonly string _pointName;
  12. private readonly Client _client = new Client();
  13. public Scada(string serverName, string pointName)
  14. {
  15. _opcServerName = serverName;
  16. _pointName = pointName;
  17. }
  18. #region [Public]
  19. /// <summary>
  20. /// 开始
  21. /// </summary>
  22. public void Start()
  23. {
  24. using (var csv = new CsvFile(_pointName))
  25. {
  26. var headers = csv.ReadLine();
  27. var all = csv.ReadAll();
  28. if (headers?.Length != 3) return;
  29. foreach (var row in all)
  30. {
  31. _client.itemIDs.Add(row[0]);
  32. _client.descritions.Add(row[1]);
  33. _client.equipMentCodes.Add(row[2]);
  34. }
  35. }
  36. //建立连接
  37. _client._opcServerName = _opcServerName;
  38. _client.Connect();
  39. if (!_client.isConnected)
  40. {
  41. throw new Exception("连接失败");
  42. }
  43. _client.Data_Change += DataChange;
  44. }
  45. /// <summary>
  46. /// 停止
  47. /// </summary>
  48. public void Stop()
  49. {
  50. if (!_client.isConnected) return;
  51. _client.Disconnect();
  52. _client.Data_Change -= DataChange;
  53. }
  54. public List<Data> GetAllData()
  55. => _client.dataCenter.Select(c => c.Value).ToList();
  56. /// <summary>
  57. /// 改变事件
  58. /// </summary>
  59. public event Action<Dictionary<int, Data>, List<int>> ChangeEvent;
  60. #endregion
  61. #region [Event]
  62. /// <summary>
  63. /// 变更记录
  64. /// </summary>
  65. /// <param name="numItems"></param>
  66. /// <param name="clientHandles"></param>
  67. private void DataChange(int numItems, ref Array clientHandles)
  68. {
  69. var changeItems = clientHandles.Cast<int>().ToList();
  70. ChangeEvent?.Invoke(_client.dataCenter, changeItems);
  71. }
  72. #endregion
  73. }
  74. }