SimpleSocketDeviceSimulator.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using MECF.Framework.Common.Communications;
  2. using MECF.Framework.Simulator.Core.Driver;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO.Ports;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace MECF.Framework.Simulator.Core.Commons
  10. {
  11. public class SimpleSocketDeviceSimulator : DeviceSimulator
  12. {
  13. public override bool IsEnabled
  14. {
  15. get { return _socket != null && _socket.IsConnected; }
  16. }
  17. public override bool IsConnected
  18. {
  19. get { return IsEnabled; }
  20. }
  21. public string PortName
  22. {
  23. get { return _port.ToString(); }
  24. set { _port = int.Parse(value); }
  25. }
  26. public int LocalPort
  27. {
  28. get { return _port; }
  29. set
  30. {
  31. {
  32. _port = value;
  33. }
  34. }
  35. }
  36. private AsynSocketServer _socket;
  37. int _port;
  38. public SimpleSocketDeviceSimulator(int port, int commandIndex, string lineDelimiter, char msgDelimiter, bool isAscii = true)
  39. : base(commandIndex, lineDelimiter, msgDelimiter)
  40. {
  41. _port = port;
  42. _socket = new AsynSocketServer("127.0.0.1" , port, isAscii, lineDelimiter);
  43. _socket.OnDataChanged += OnReadMessage;
  44. _socket.OnBinaryDataChanged += OnReadMessage;
  45. _socket.OnErrorHappened += OnErrorMessage;
  46. }
  47. public void Enable()
  48. {
  49. _socket.Start();
  50. }
  51. public void Disable()
  52. {
  53. _socket.Dispose();
  54. }
  55. protected override void ProcessWriteMessage(string msg)
  56. {
  57. _socket.Write(msg);
  58. }
  59. protected override void ProcessWriteMessage(byte[] msg)
  60. {
  61. _socket.Write(msg);
  62. }
  63. }
  64. }