PlcCommunManager.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //PLC参数管理类
  2. using MvvmScaffoldFrame48.DLL.AlarmTools;
  3. using MvvmScaffoldFrame48.DLL.LogTools;
  4. using MvvmScaffoldFrame48.Model.StorageModel.PlcParameter;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace MvvmScaffoldFrame48.DLL.CommunicationTools
  11. {
  12. public class PlcCommunManager
  13. {
  14. private static readonly Dictionary<int, ushort> BitMasks = new Dictionary<int, ushort>
  15. {
  16. // 寄存器位掩码
  17. {0, (ushort)(1 << 0)},
  18. {1, (ushort)(1 << 1)},
  19. {2, (ushort)(1 << 2)},
  20. {3, (ushort)(1 << 3)},
  21. {4, (ushort)(1 << 4)},
  22. {5, (ushort)(1 << 5)},
  23. {6, (ushort)(1 << 6)},
  24. {7, (ushort)(1 << 7)},
  25. {8, (ushort)(1 << 8)},
  26. {9, (ushort)(1 << 9)},
  27. {10, (ushort)(1 << 10)},
  28. {11, (ushort)(1 << 11)},
  29. {12, (ushort)(1 << 12)},
  30. {13, (ushort)(1 << 13)},
  31. {14, (ushort)(1 << 14)},
  32. {15, (ushort)(1 << 15)},
  33. };
  34. private static readonly Dictionary<string, PlcParameterModel> RegisterMap = new Dictionary<string, PlcParameterModel>
  35. {
  36. {"test1",new PlcValueBitParameterModel(0,0) }
  37. };
  38. private bool isConnect = false;
  39. public bool IsConnect
  40. {
  41. get
  42. {
  43. return isConnect ? modbusTcpClient.IsTcpClientConnected() : isConnect;
  44. }
  45. }
  46. public ModbusTcpClient modbusTcpClient = new ModbusTcpClient();
  47. public PlcCommunManager(string IpAddress)
  48. {
  49. ConnectModbus(IpAddress);
  50. }
  51. public void ConnectModbus(string ipAddress)
  52. {
  53. int i = 10;
  54. while (!modbusTcpClient.Connect(ipAddress) && i > 0)
  55. {
  56. isConnect = false;
  57. //SystemAlarm.AlarmAlert(AlarmMessageList.PLC通讯连接失败, $"Modbus通讯连接失败,目标IP:{ipAddress}", "DLL:MainThreadClass-ConnectModbus");
  58. SystemAlarm.AlarmAlert(AlarmMessageList.PLC通讯连接失败,
  59. $"PLC communication connection failed, target IP:{ipAddress}",
  60. $"PLC通讯连接失败, IP地址:{ipAddress}",
  61. "DLL:MainThreadClass-ConnectModbus");
  62. i--;
  63. Task.Delay(1000);
  64. }
  65. if (modbusTcpClient.Connect(ipAddress))
  66. {
  67. SystemAlarm.AlarmCancel(AlarmMessageList.PLC通讯连接失败);
  68. TxtLog.log("PLC通讯成功", 6);
  69. //FaultLog.RecordLogMessage($"Modbus通讯连接成功,目标IP:{ipAddress}", 6);
  70. isConnect = true;
  71. }
  72. }
  73. }
  74. }