PLC.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.NetworkInformation;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace WCS.Core
  8. {
  9. public class PLC : EntityEx<PLCInfo>
  10. {
  11. public bool Ping { get; private set; }
  12. public PLC(PLCInfo ent, World world) : base(ent)
  13. {
  14. if (Configs.PLCAccessorCreater != null)
  15. {
  16. Accessor = Configs.PLCAccessorCreater.Create(ent);
  17. }
  18. else
  19. throw new Exception("Configs.PLCAccessorCreater未赋值");
  20. Task.Run(() =>
  21. {
  22. while (true)
  23. {
  24. Ping = ping();
  25. Task.Delay(1000).Wait();
  26. }
  27. // ReSharper disable once FunctionNeverReturns
  28. });
  29. }
  30. public PLC(PLCInfo ent) : base(ent)
  31. {
  32. if (Configs.PLCAccessorCreater != null)
  33. {
  34. Accessor = Configs.PLCAccessorCreater.Create(ent);
  35. }
  36. else
  37. throw new Exception("Configs.PLCAccessorCreater未赋值");
  38. Task.Run(() =>
  39. {
  40. while (true)
  41. {
  42. Ping = ping();
  43. Task.Delay(1000).Wait();
  44. }
  45. // ReSharper disable once FunctionNeverReturns
  46. });
  47. }
  48. public IPLCAccessor Accessor { get; private set; }
  49. private bool ping(int timeout = 300)
  50. {
  51. var p = new Ping();
  52. if (Entity.IP == "1") return false;
  53. var res = p.Send(Entity.IP, timeout);
  54. return res.Status == IPStatus.Success;
  55. }
  56. }
  57. public interface IPLCAccessorCreater
  58. {
  59. IPLCAccessor Create(PLCInfo data);
  60. }
  61. public interface IPLCAccessor
  62. {
  63. void WriteBytes(ushort db, ushort address, byte[] data);
  64. byte[] ReadBytes(ushort db, ushort address, ushort length);
  65. }
  66. }