PLC.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Net.NetworkInformation;
  2. using System.Text;
  3. namespace WCS.Core
  4. {
  5. public class PLC : EntityEx<PLCInfo>
  6. {
  7. public bool Ping { get; private set; }
  8. public PLC(PLCInfo ent) : base(ent)
  9. {
  10. if (Configs.PLCAccessorCreater != null)
  11. {
  12. Accessor = Configs.PLCAccessorCreater.Create(ent);
  13. }
  14. else
  15. throw new Exception("Configs.PLCAccessorCreater未赋值");
  16. Task.Run(() =>
  17. {
  18. while (true)
  19. {
  20. Ping = ping();
  21. Task.Delay(1000);
  22. }
  23. });
  24. }
  25. public IPLCAccessor Accessor { get; private set; }
  26. private bool ping(int timeout = 100)
  27. {
  28. if (Entity.IP == "1") return false;
  29. try
  30. {
  31. var objPingSender = new Ping();
  32. var objPinOptions = new PingOptions
  33. {
  34. DontFragment = true
  35. };
  36. const string data = "";
  37. var buffer = Encoding.UTF8.GetBytes(data);
  38. var objPinReply = objPingSender.Send(Entity.IP, timeout, buffer, objPinOptions);
  39. var strInfo = objPinReply.Status.ToString();
  40. return strInfo == "Success";
  41. }
  42. catch (Exception)
  43. {
  44. return false;
  45. }
  46. //var p = new Ping();
  47. //var res = p.Send(Entity.IP, timeout);
  48. //return res.Status == IPStatus.Success;
  49. ////return true;
  50. }
  51. }
  52. public interface IPLCAccessorCreater
  53. {
  54. IPLCAccessor Create(PLCInfo data);
  55. }
  56. public interface IPLCAccessor
  57. {
  58. void WriteBytes(ushort db, ushort address, byte[] data);
  59. byte[] ReadBytes(ushort db, ushort address, ushort length);
  60. }
  61. }