ComPortCommunicatorMock.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.IO.Ports;
  5. using System.Threading;
  6. using Edge.Core.Parser.BinaryParser.MessageEntity;
  7. using Edge.Core.Processor;
  8. using Edge.Core.IndustryStandardInterface.Pump;
  9. using Edge.Core.Parser;
  10. using System.Threading.Tasks;
  11. using Edge.Core.Processor.Communicator;
  12. namespace Mocks
  13. {
  14. public class ComPortCommunicatorMock<T> : ICommunicator<byte[], T> where T : MessageBase
  15. {
  16. private object syncObject = new object();
  17. private int isStarted = 0;
  18. public string Identity { get; set; }
  19. public event EventHandler OnConnected;
  20. public event EventHandler OnDisconnected;
  21. public event EventHandler<CommunicatorEventArg<byte[], T>> OnRawDataWriting;
  22. public event EventHandler<CommunicatorEventArg<byte[], T>> OnDataReceived;
  23. public event EventHandler<CommunicatorErrorMessageReadEventArg> OnErrorMessageRead;
  24. public bool Write(T message)
  25. {
  26. var safe = this.OnRawDataWriting;
  27. var arg = new CommunicatorEventArg<byte[], T>() { Message = message, Continue = true };
  28. safe?.Invoke(this, arg);
  29. return true;
  30. }
  31. public void Dispose()
  32. {
  33. this.isStarted = 0;
  34. }
  35. public async Task<bool> Start()
  36. {
  37. if (0 == Interlocked.CompareExchange(ref this.isStarted, 1, 0))
  38. {
  39. return true;
  40. }
  41. return false;
  42. }
  43. #region mock functions
  44. /// <summary>
  45. /// simulate a message was read and parsed from remote device, then push this message finally to Hanlder.
  46. /// </summary>
  47. /// <param name="message"></param>
  48. public void FireOnDataReceived(T message)
  49. {
  50. var safe = this.OnDataReceived;
  51. safe?.Invoke(this, new CommunicatorEventArg<byte[], T>() { Message = message });
  52. }
  53. public bool Write(T message, object extraControlParameter)
  54. {
  55. throw new NotImplementedException();
  56. }
  57. #endregion
  58. }
  59. }