终端一体化运控平台
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

97 rindas
3.0 KiB

  1. using S7.Net;
  2. namespace BPASmartClient.S7Net
  3. {
  4. public class SiemensHelper
  5. {
  6. Plc myPlc;
  7. public bool IsConnected => myPlc is null ? false : myPlc.IsConnected;
  8. /// <summary>
  9. /// 打开连接
  10. /// </summary>
  11. /// <param name="cpuType">PLC CPU 类型</param>
  12. /// <param name="ip">plc ip 地址</param>
  13. /// <param name="port">plc 端口号</param>
  14. /// <param name="rack">PLC 机架号</param>
  15. /// <param name="solt"> PLC 插槽号</param>
  16. public void Connect(CpuType cpuType, string ip, int port = 102, short rack = 0, short solt = 0)
  17. {
  18. myPlc = new Plc(cpuType, ip, port, rack, solt);
  19. myPlc.Open();
  20. }
  21. /// <summary>
  22. /// 断开和PLC的连接
  23. /// </summary>
  24. public void Disconnect()
  25. {
  26. myPlc?.Close();
  27. }
  28. public object Read(string address)
  29. {
  30. if (!IsConnected) return default;
  31. return myPlc?.Read(address);
  32. }
  33. public bool[] ReadBools(int address, int count)
  34. {
  35. if (!IsConnected) return default;
  36. var res = Read(DataType.Memory, 0, address, VarType.Bit, count);
  37. if (res != null && res is bool[] bools) return bools;
  38. return default;
  39. }
  40. public ushort[] ReadMW(int address, int count)
  41. {
  42. if (!IsConnected) return default;
  43. var res = Read(DataType.Memory, 0, address, VarType.Word, count);
  44. if (res != null && res is ushort[] ReturnValue) return ReturnValue;
  45. return default;
  46. }
  47. public float[] ReadMD(int address, int count)
  48. {
  49. if (!IsConnected) return default;
  50. var res = Read(DataType.Memory, 0, address, VarType.Real, count);
  51. if (res != null && res is float[] ReturnValue) return ReturnValue;
  52. return default;
  53. }
  54. private object Read(DataType dataType, int db, int address, VarType varType, int count)
  55. {
  56. if (!IsConnected) return default;
  57. return myPlc?.Read(dataType, db, address, varType, count);
  58. }
  59. public void Write(string address, object value)
  60. {
  61. myPlc?.Write(address, value);
  62. }
  63. public ReadT ReadStruct<ReadT>(int db, int startAddress = 0)
  64. {
  65. if (!IsConnected) return default;
  66. return (ReadT)myPlc.ReadStruct(typeof(ReadT), db, startAddress);
  67. }
  68. public void WriteStruct(object structValue, int db, int startAddress = 0)
  69. {
  70. myPlc?.WriteStruct(structValue, db, startAddress);
  71. }
  72. public int ReadClass(object sourceClass, int db, int startAddress = 0)
  73. {
  74. if (!IsConnected) return -1;
  75. return myPlc.ReadClass(sourceClass, db, startAddress);
  76. }
  77. public void WriteClass(object sourceClass, int db, int startAddress = 0)
  78. {
  79. myPlc?.WriteClass(sourceClass, db, startAddress);
  80. }
  81. }
  82. }