SignalStateService.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using Appccelerate.StateMachine;
  5. using Appccelerate.StateMachine.AsyncMachine;
  6. using StatementMachineService.Events;
  7. using StatementMachineService.Model;
  8. namespace StatementMachineService.Service
  9. {
  10. internal class SignalStateService:ISignalStateService
  11. {
  12. private AsyncPassiveStateMachine<SignalState,SingalEvent> _machine;
  13. public event StateEventHandler UpExecuteEvent;
  14. public event StateEventHandler DownExecuteEvent;
  15. public SignalStateService()
  16. {
  17. }
  18. private void OnUpEvent()
  19. {
  20. UpExecuteEvent?.Invoke(this, new StateEventArgs(_id));
  21. }
  22. private void OnDownEvent()
  23. {
  24. DownExecuteEvent?.Invoke(this, new StateEventArgs(_id));
  25. }
  26. private static readonly List<int> SignalList=new List<int>();
  27. private int _id;
  28. public void CreateService(int id)
  29. {
  30. _id = id;
  31. if (SignalList.Exists(p=>p==id))
  32. {
  33. throw new Exception("已经存在");
  34. }
  35. var signal1=new SignalState(Guid.NewGuid().ToString());
  36. var signal2= new SignalState(Guid.NewGuid().ToString());
  37. var builder = new StateMachineDefinitionBuilder<SignalState, SingalEvent>();
  38. builder.In(signal1)
  39. .On(new SingalEvent(1))
  40. .Goto(signal2).Execute(OnUpEvent);
  41. builder.In(signal2).On(new SingalEvent(0)).Goto(signal1).Execute(OnDownEvent);
  42. _machine = builder.WithInitialState(signal1)
  43. .Build().CreatePassiveStateMachine();
  44. _machine.Start();
  45. SignalList.Add(id);
  46. }
  47. /// <summary>
  48. ///
  49. /// </summary>
  50. /// <param name="state">
  51. /// <状态></状态>
  52. /// </param>
  53. public void ExecuteSate(ushort state)
  54. {
  55. _machine.Fire(new SingalEvent(Convert.ToInt32(state)));
  56. }
  57. }
  58. [ComVisible(true)]
  59. [Serializable]
  60. public delegate void StateEventHandler(object sender, StateEventArgs e);
  61. }