Exemplo n.º 1
2
        private StateMachine<string, char> CreateMachine()
        {
            var machine = new StateMachine<string, char>(off);

            Action log = () =>
            {
                C.WriteLine(this.color, "switched pre {1}: {0}", machine.Id, machine.State);
                //Thread.Sleep(1000);
                C.WriteLine(this.color, "switched post {1}: {0}", machine.Id, machine.State);
            };

            machine
                .Configure(off)
                .Permit(space, on)
                .OnEntry(log);
            machine
                .Configure(on)
                .Permit(space, off)
                .OnEntry(log);
            return machine;
        }
        private StateMachine<ImportFinancialGuaranteeStatus, Trigger> CreateStateMachine()
        {
            var stateMachine = new StateMachine<ImportFinancialGuaranteeStatus, Trigger>(() => Status, s => Status = s);

            stateMachine.OnTransitioned(OnTransitionAction);

            completeTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.Complete);

            stateMachine.Configure(ImportFinancialGuaranteeStatus.ApplicationReceived)
                .Permit(Trigger.Complete, ImportFinancialGuaranteeStatus.ApplicationComplete);

            stateMachine.Configure(ImportFinancialGuaranteeStatus.ApplicationComplete)
                .OnEntryFrom(completeTrigger, OnComplete)
                .Permit(Trigger.Approve, ImportFinancialGuaranteeStatus.Approved)
                .Permit(Trigger.Refuse, ImportFinancialGuaranteeStatus.Refused);

            stateMachine.Configure(ImportFinancialGuaranteeStatus.Approved)
                .Permit(Trigger.Release, ImportFinancialGuaranteeStatus.Released);
                
            return stateMachine;
        }
		public Download ()
		{

			State = Bo.State.Waiting;
			_machine = new StateMachine<State, Transition>(() => State, s => State = s);

			_machine.Configure (Bo.State.Waiting)
				.Permit (Transition.Cancel, Bo.State.Finished)
				.Permit (Transition.Fail, Bo.State.Error)
				.Permit (Transition.Resume, Bo.State.Downloading);

			_machine.Configure (Bo.State.Downloading)
				.Permit (Transition.Pause, Bo.State.Waiting)
				.PermitReentry (Transition.Progress)
				.Permit (Transition.Cancel, Bo.State.Finished)
				.Permit (Transition.Finish, Bo.State.Finished)
				.Permit (Transition.Fail, Bo.State.Error);

			_machine.Configure (Bo.State.Finished);

			_machine.Configure (Bo.State.Error)
				.Permit (Transition.Retry, Bo.State.Waiting)
				.Permit (Transition.Cancel, Bo.State.Finished)
				.Permit (Transition.Fail, Bo.State.Finished);
		}
Exemplo n.º 4
0
        private static StateMachine<ProductStatus, ProductStatus> InitializeStateMachine(ProductStatus initialState)
        {
            StateMachine<ProductStatus, ProductStatus> productStateMachine =
                new StateMachine<ProductStatus, ProductStatus>(initialState);

            productStateMachine.Configure(ProductStatus.Draft)
                .Permit(ProductStatus.WaitingForApproval, ProductStatus.WaitingForApproval);

            productStateMachine.Configure(ProductStatus.WaitingForApproval)
                .Permit(ProductStatus.Approved, ProductStatus.Approved)
                .Permit(ProductStatus.Cancelled, ProductStatus.Cancelled);

            productStateMachine.Configure(ProductStatus.Approved)
                .Permit(ProductStatus.Active, ProductStatus.Active)
                .Permit(ProductStatus.Passive, ProductStatus.Passive)
                .Permit(ProductStatus.Cancelled, ProductStatus.Cancelled);

            productStateMachine.Configure(ProductStatus.Active)
                .Permit(ProductStatus.Passive, ProductStatus.Passive)
                .Permit(ProductStatus.Cancelled, ProductStatus.Cancelled);

            productStateMachine.Configure(ProductStatus.Passive)
                .Permit(ProductStatus.Active, ProductStatus.Active)
                .Permit(ProductStatus.Cancelled, ProductStatus.Cancelled);

            // Allow none of the options for AccommodationPropertyStatus.Cancelled;

            return productStateMachine;
        }
Exemplo n.º 5
0
        public MainLogicProcessor()
        {
            VisionData = new VisionData();
            SensorData = new SensorData();

            stateMachine = new StateMachine<State, Trigger>(State.LookingForBall);

            stateMachine.Configure(State.LookingForBall)
                .Permit(Trigger.CameraLockedOnBall, State.ClosingInOnBall)
                .Permit(Trigger.BallCaught, State.FindingGoal)
                .OnEntry(StopTimer);

            stateMachine.Configure(State.ClosingInOnBall)
                .Permit(Trigger.CameraLostBall, State.LookingForBall)
                .Permit(Trigger.BallCaught, State.FindingGoal)
                .Permit(Trigger.Timeout, State.LookingForBall)
                .OnEntry(() => StartTimer(10000, Trigger.Timeout))
                .OnExit(StopTimer);

            stateMachine.Configure(State.FindingGoal)
                .Permit(Trigger.CoilgunLaunched, State.LookingForBall)
                .Permit(Trigger.BallLost, State.LookingForBall)
                .Permit(Trigger.Timeout, State.LookingForBall)
                .OnEntry(() => StartTimer(5000, Trigger.Timeout))
                .OnExit(StopTimer);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            try
            {
                string on = "On", off = "Off";
                var space = ' ';

                var onOffSwitch = new StateMachine<string, char>(off);

                onOffSwitch.Configure(off).Permit(space, on);
                onOffSwitch.Configure(on).Permit(space, off);

                Console.WriteLine("Press <space> to toggle the switch. Any other key will raise an error.");

                while (true)
                {
                    Console.WriteLine("Switch is in state: " + onOffSwitch.State);
                    var pressed = Console.ReadKey(true).KeyChar;
                    onOffSwitch.Fire(pressed);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey(true);
            }
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            var phoneCall = new StateMachine<State, Trigger>(State.OffHook);
            setVolumeTrigger = phoneCall.SetTriggerParameters<int>(Trigger.SetVolume);

            phoneCall.Configure(State.OffHook)
                .Permit(Trigger.CallDialed, State.Ringing);

            phoneCall.Configure(State.Ringing)
                .Permit(Trigger.HungUp, State.OffHook)
                .Permit(Trigger.CallConnected, State.Connected);

            phoneCall.Configure(State.Connected)
                .OnEntry(t => StartCallTimer())
                .OnExit(t => StopCallTimer())
                .InternalTransition(Trigger.MuteMicrophone, t => OnMute())
                .InternalTransition(Trigger.UnmuteMicrophone, t => OnUnmute())
                .InternalTransition<int>(setVolumeTrigger, (volume, t) => OnSetVolume(volume))
                .Permit(Trigger.LeftMessage, State.OffHook)
                .Permit(Trigger.HungUp, State.OffHook)
                .Permit(Trigger.PlacedOnHold, State.OnHold);

            phoneCall.Configure(State.OnHold)
                .SubstateOf(State.Connected)
                .Permit(Trigger.TakenOffHold, State.Connected)
                .Permit(Trigger.HungUp, State.OffHook)
                .Permit(Trigger.PhoneHurledAgainstWall, State.PhoneDestroyed);

            Print(phoneCall);
            Fire(phoneCall, Trigger.CallDialed);
            Print(phoneCall);
            Fire(phoneCall, Trigger.CallConnected);
            Print(phoneCall);
            SetVolume(phoneCall, 2);
            Print(phoneCall);
            Fire(phoneCall, Trigger.PlacedOnHold);
            Print(phoneCall);
            Fire(phoneCall, Trigger.MuteMicrophone);
            Print(phoneCall);
            Fire(phoneCall, Trigger.UnmuteMicrophone);
            Print(phoneCall);
            Fire(phoneCall, Trigger.TakenOffHold);
            Print(phoneCall);
            SetVolume(phoneCall, 11);
            Print(phoneCall);
            Fire(phoneCall, Trigger.HungUp);
            Print(phoneCall);

            Console.WriteLine("Press any key...");
            Console.ReadKey(true);
        }
Exemplo n.º 8
0
        internal static StateMachine<State, Trigger> GetStateMachine()
        {
            var machine = new StateMachine<State, Trigger>(State.WaitingForStart);

            machine.Configure(State.WaitingForStart)
                .Permit(Trigger.DataLinkEscapeRead, State.Started);

            machine.Configure(State.Started)
                .Permit(Trigger.StartOfTextRead, State.ReadingMessageType)
                .Permit(Trigger.UnexpectedCharacter, State.WaitingForStart);

            machine.Configure(State.ReadingMessageType)
                .Permit(Trigger.MessageTypeRead, State.ReadingMessageLength)
                .Permit(Trigger.UnexpectedCharacter, State.WaitingForStart);

            machine.Configure(State.ReadingMessageLength)
                .Permit(Trigger.MessageLengthRead, State.BuildingMessage);

            machine.Configure(State.BuildingMessage)
                .Permit(Trigger.MessageTextRead, State.ReadingCheckSum);

            machine.Configure(State.ReadingCheckSum)
                .Permit(Trigger.CheckSumPassed, State.CheckSumRead)
                .Permit(Trigger.CheckSumFailed, State.WaitingForStart);

            machine.Configure(State.CheckSumRead)
                .Permit(Trigger.DataLinkEscapeRead, State.MessageDone)
                .Permit(Trigger.UnexpectedCharacter, State.WaitingForStart);

            machine.Configure(State.MessageDone)
                .Permit(Trigger.MessageFinished, State.WaitingForStart)
                .Permit(Trigger.UnexpectedCharacter, State.WaitingForStart);

            return machine;
        }
Exemplo n.º 9
0
        public void ConfigureStates(StateMachine<StoryUpdateFunction, string> state)
        {
            state.Configure(Master)
                .Permit(Triggers.Start, Intro);

            state.Configure(Intro)
                .SubstateOf(Master)
                .Permit(Story.Triggers.NextScene, Tutorial);

            state.Configure(Tutorial)
                .SubstateOf(Master)
                .Permit(Story.Triggers.NextScene, AlienInvasionIntro);

            state.Configure(AlienInvasionIntro)
                .SubstateOf(Master)
                .Permit(Story.Triggers.NextScene, AlienInvasionGameplay);
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            //var wf1 = new Workflow1();
            //wf1.InputValue = 0;
            //wf1.

            var phoneCall = new StateMachine<State, Trigger>(State.OffHook);

            phoneCall.Configure(State.OffHook)
                .Permit(Trigger.CallDialed, State.Ringing);

            phoneCall.Configure(State.Ringing)
                .Permit(Trigger.HungUp, State.OffHook)
                .Permit(Trigger.CallConnected, State.Connected);

            phoneCall.Configure(State.Connected)
                .OnEntry(t => StartCallTimer())
                .OnExit(t => StopCallTimer())
                .Permit(Trigger.LeftMessage, State.OffHook)
                .Permit(Trigger.HungUp, State.OffHook)
                .Permit(Trigger.PlacedOnHold, State.OnHold);

            phoneCall.Configure(State.OnHold)
                .SubstateOf(State.Connected)
                .Permit(Trigger.TakenOffHold, State.Connected)
                .Permit(Trigger.HungUp, State.OffHook)
                .Permit(Trigger.PhoneHurledAgainstWall, State.PhoneDestroyed);

            Print(phoneCall);
            Fire(phoneCall, Trigger.CallDialed);
            Print(phoneCall);
            Fire(phoneCall, Trigger.CallConnected);
            Print(phoneCall);
            Fire(phoneCall, Trigger.PlacedOnHold);
            Print(phoneCall);
            Fire(phoneCall, Trigger.TakenOffHold);
            Print(phoneCall);
            Fire(phoneCall, Trigger.HungUp);
            Print(phoneCall);

            Console.WriteLine("Press any key...");
            Console.ReadKey(true);
        }
        public static StateMachine<RequestState, RequestAction> ForRequest(int requestId)
        {
            //use request id to get the current state of the request and initialize
            var persistedState = GetRequestState(requestId);

            var workflow = new StateMachine<RequestState, RequestAction>(persistedState);

            //configure requested status
            workflow.Configure(RequestState.Created)
                .Permit(RequestAction.Suspend, RequestState.Suspended)
                .Permit(RequestAction.Cancel, RequestState.Cancelled)
                .Permit(RequestAction.Process, RequestState.Assigned);

            workflow.Configure(RequestState.Assigned)
                    .OnEntry(OnBeginHandleAssigned)
                    .OnExit(OnExitHandleAssigned);

            return workflow;
        }
Exemplo n.º 12
0
        public ConnectionContext()
        {
            State = new StateMachine<HostState, HostCommand>(HostState.Disconnected);

            State.Configure(HostState.Disconnected)
                .Permit(HostCommand.ConnectionRequested, HostState.Connecting);

            State.Configure(HostState.Connecting)
                .Permit(HostCommand.ConnectionEstablished, HostState.Connected)
                .Permit(HostCommand.ConnectionFailed, HostState.Disconnected);

            State.Configure(HostState.Connected)
                .Permit(HostCommand.MessageReceived, HostState.Processing);

            State.Configure(HostState.Processing)
                .Permit(HostCommand.ResponseSent, HostState.Connected);

            LastActivity = DateTime.Now;
        }
Exemplo n.º 13
0
        protected Bug()
        {
            Machine = new StateMachine<States, Triggers>(() => State, s => State = s);
            AssignTrigger = Machine.SetTriggerParameters<string>(Triggers.Assign);

            Machine.Configure(States.Open)
               .Permit(Triggers.Assign, States.Assigned);

            Machine.Configure(States.Assigned)
                .SubstateOf(States.Open)
                .OnEntryFrom(AssignTrigger, OnAssigned)
                .PermitReentry(Triggers.Assign)
                .Permit(Triggers.Close, States.Closed)
                .Permit(Triggers.Defer, States.Deferred)
                .OnExit(OnDeassigned);

            Machine.Configure(States.Deferred)
                .OnEntry(() => Assignee = null)
                .Permit(Triggers.Assign, States.Assigned);
        }
Exemplo n.º 14
0
        static void Main()
        {
            var sm = new StateMachine<State, Trigger>(State.A);

            sm.Configure(State.A)
              .Permit(Trigger.GoToB, State.B)
              .OnEntry(OnEnterA); // This never gets called.

            sm.Configure(State.B)
              .OnEntry(OnEnterB)
              .Permit(Trigger.GoToC, State.C);

            var goToCTrigger = sm.SetTriggerParameters<string>(Trigger.GoToC);

            sm.Configure(State.C)
              .OnEntryFrom(goToCTrigger, OnEnterC);

            Console.WriteLine(sm);
            sm.Fire(Trigger.GoToB);
            Console.WriteLine(sm);
            sm.Fire(goToCTrigger, "foo"); // Using Trigger.GoToC will throw an exception.
            Console.WriteLine(sm);
        }
Exemplo n.º 15
0
        private static Lazy<IStateStepConfiguration, IStateStepConfigurationMetadata> ConfigureStateMachine(StateMachine<WorkflowStep, WorkflowTrigger> stateMachine, 
            Lazy<IStateStepConfiguration, IStateStepConfigurationMetadata> stepConfiguration)
        {
            var stateConfig = stateMachine.Configure(stepConfiguration.Metadata.WorkflowStep);

            foreach (var permission in stepConfiguration.Value.Permissions)
                stateConfig.Permit(permission.Key, permission.Value);

            stateConfig.OnEntry(
                () => Console.WriteLine("Entering {0} Step at {1}", stepConfiguration.Metadata.WorkflowStep,
                                        DateTime.Now.ToLongTimeString()));

            return stepConfiguration;
        }
Exemplo n.º 16
0
        public Bug(string title)
        {
            _title = title;

            _machine = new StateMachine<State, Trigger>(() => _state, s => _state = s);

            _assignTrigger = _machine.SetTriggerParameters<string>(Trigger.Assign);

            _machine.Configure(State.Open)
                .Permit(Trigger.Assign, State.Assigned);

            _machine.Configure(State.Assigned)
                .SubstateOf(State.Open)
                .OnEntryFrom(_assignTrigger, assignee => OnAssigned(assignee))
                .PermitReentry(Trigger.Assign)
                .Permit(Trigger.Close, State.Closed)
                .Permit(Trigger.Defer, State.Deferred)
                .OnExit(() => OnDeassigned());

            _machine.Configure(State.Deferred)
                .OnEntry(() => _assignee = null)
                .Permit(Trigger.Assign, State.Assigned);
        }
Exemplo n.º 17
0
        public Story(EntityWorld world)
        {
            Acts = new List<IStoryAct>(new[] { new ActOne() });
            State = new StateMachine<StoryUpdateFunction, string>(Acts[0].Master);
            State.OnTransitioned(OnTransition);

            for (int i = 0; i < Acts.Count; i++)
            {
                var act = Acts[i];
                act.ConfigureStates(State);

                State.Configure(act.Master)
                    .Permit(Triggers.NextAct, i < Acts.Count - 1 ? (StoryUpdateFunction)Acts[i + 1].Master : EndOfStory);
            }
            World = world;
            State.Fire(ActOne.Triggers.Start);
        }
Exemplo n.º 18
0
 public SMWorkflowMachine()
 {
     stateMachine = new StateMachine<State, Trigger>(State.Idle);
       stateMachine.Configure(State.Idle)
     .OnEntry(() => { if (OnIdleEntry != null) OnIdleEntry(); })
     .OnExit(() => { if (OnIdleExit != null) OnIdleExit(); })
     .PermitIf(Trigger.Select, State.SelectDrink , () => { if (GuardClauseFromIdleToSelectDrinkUsingTriggerSelect != null) return GuardClauseFromIdleToSelectDrinkUsingTriggerSelect(); return true; } )
     .PermitIf(Trigger.Insert, State.CoinBox , () => { if (GuardClauseFromIdleToCoinBoxUsingTriggerInsert != null) return GuardClauseFromIdleToCoinBoxUsingTriggerInsert(); return true; } )
       ;
       stateMachine.Configure(State.SelectDrink)
     .OnEntry(() => { if (OnSelectDrinkEntry != null) OnSelectDrinkEntry(); })
     .OnExit(() => { if (OnSelectDrinkExit != null) OnSelectDrinkExit(); })
     .PermitIf(Trigger.SelectedDrink, State.SelectedDrink , () => { if (GuardClauseFromSelectDrinkToSelectedDrinkUsingTriggerSelectedDrink != null) return GuardClauseFromSelectDrinkToSelectedDrinkUsingTriggerSelectedDrink(); return true; } )
       ;
       stateMachine.Configure(State.CoinBox)
     .OnEntry(() => { if (OnCoinBoxEntry != null) OnCoinBoxEntry(); })
     .OnExit(() => { if (OnCoinBoxExit != null) OnCoinBoxExit(); })
     .PermitIf(Trigger.RefundMoney, State.MoneyRefunded , () => { if (GuardClauseFromCoinBoxToMoneyRefundedUsingTriggerRefundMoney != null) return GuardClauseFromCoinBoxToMoneyRefundedUsingTriggerRefundMoney(); return true; } )
     .PermitIf(Trigger.CheckMoney, State.ControlMoney , () => { if (GuardClauseFromCoinBoxToControlMoneyUsingTriggerCheckMoney != null) return GuardClauseFromCoinBoxToControlMoneyUsingTriggerCheckMoney(); return true; } )
       ;
       stateMachine.Configure(State.ControlMoney)
     .OnEntry(() => { if (OnControlMoneyEntry != null) OnControlMoneyEntry(); })
     .OnExit(() => { if (OnControlMoneyExit != null) OnControlMoneyExit(); })
     .PermitIf(Trigger.Rejected, State.CoinBox , () => { if (GuardClauseFromControlMoneyToCoinBoxUsingTriggerRejected != null) return GuardClauseFromControlMoneyToCoinBoxUsingTriggerRejected(); return true; } )
     .PermitIf(Trigger.EnoughMoney, State.ServingDrink , () => { if (GuardClauseFromControlMoneyToServingDrinkUsingTriggerEnoughMoney != null) return GuardClauseFromControlMoneyToServingDrinkUsingTriggerEnoughMoney(); return true; } )
       ;
       stateMachine.Configure(State.SelectedDrink)
     .OnEntry(() => { if (OnSelectedDrinkEntry != null) OnSelectedDrinkEntry(); })
     .OnExit(() => { if (OnSelectedDrinkExit != null) OnSelectedDrinkExit(); })
     .PermitIf(Trigger.DeSelectDrink, State.SelectDrink , () => { if (GuardClauseFromSelectedDrinkToSelectDrinkUsingTriggerDeSelectDrink != null) return GuardClauseFromSelectedDrinkToSelectDrinkUsingTriggerDeSelectDrink(); return true; } )
     .PermitIf(Trigger.FoundDrink, State.ServingDrink , () => { if (GuardClauseFromSelectedDrinkToServingDrinkUsingTriggerFoundDrink != null) return GuardClauseFromSelectedDrinkToServingDrinkUsingTriggerFoundDrink(); return true; } )
       ;
       stateMachine.Configure(State.ServingDrink)
     .OnEntry(() => { if (OnServingDrinkEntry != null) OnServingDrinkEntry(); })
     .OnExit(() => { if (OnServingDrinkExit != null) OnServingDrinkExit(); })
     .PermitIf(Trigger.TakeDrink, State.DrinkReady , () => { if (GuardClauseFromServingDrinkToDrinkReadyUsingTriggerTakeDrink != null) return GuardClauseFromServingDrinkToDrinkReadyUsingTriggerTakeDrink(); return true; } )
       ;
       stateMachine.Configure(State.DrinkReady)
     .OnEntry(() => { if (OnDrinkReadyEntry != null) OnDrinkReadyEntry(); })
     .OnExit(() => { if (OnDrinkReadyExit != null) OnDrinkReadyExit(); })
     .PermitIf(Trigger.TakeChange, State.MoneyRefunded , () => { if (GuardClauseFromDrinkReadyToMoneyRefundedUsingTriggerTakeChange != null) return GuardClauseFromDrinkReadyToMoneyRefundedUsingTriggerTakeChange(); return true; } )
       ;
       stateMachine.Configure(State.MoneyRefunded)
     .OnEntry(() => { if (OnMoneyRefundedEntry != null) OnMoneyRefundedEntry(); })
     .OnExit(() => { if (OnMoneyRefundedExit != null) OnMoneyRefundedExit(); })
     .PermitIf(Trigger.RefundMoney, State.Idle , () => { if (GuardClauseFromMoneyRefundedToIdleUsingTriggerRefundMoney != null) return GuardClauseFromMoneyRefundedToIdleUsingTriggerRefundMoney(); return true; } )
       ;
       stateMachine.OnUnhandledTrigger((state, trigger) => { if (OnUnhandledTrigger != null) OnUnhandledTrigger(state, trigger); });
 }
Exemplo n.º 19
0
        /// <summary>
        ///     Main client thread.
        /// </summary>
        private void ClientThread()
        {
            _gameState.Reset();

            _connection = DotaGameConnection.CreateWith(_details);
            _handshake = new DotaHandshake(_details, _gameState, _connection);
            _signon = new DotaSignon(_gameState, _connection, _details);
            _game = new DotaGame(_gameState, _connection);
            _commandGenerator = new UserCmdGenerator(_gameState, _connection);

            foreach (var cont in Controllers)
                cont.Initialize(_details.SteamId, _gameState, _commandGenerator);

            long handshake_requested = 0;
            long handshake_giveup = new TimeSpan(0, 0, 0, 10).Ticks;

            // Map states in the StateMachine to handlers
            var metastates = new Dictionary<States, Metastates>() {
                { States.HANDSHAKE_REQUEST, Metastates.HANDSHAKE },
                { States.HANDSHAKE_CONNECT, Metastates.HANDSHAKE },
                { States.CONNECTED, Metastates.SIGNON },
                { States.LOADING, Metastates.SIGNON },
                { States.PRESPAWN, Metastates.SIGNON },
                { States.SPAWN, Metastates.SIGNON },
                { States.PLAY, Metastates.GAME },
            };

            var processors = new Dictionary<Metastates, IHandler>() {
                { Metastates.HANDSHAKE, _handshake },
                { Metastates.SIGNON, _signon },
                { Metastates.GAME, _game }
            };


            _stateMachine = new StateMachine<States, Events>(States.DISCONNECTED);
            //temporary shit
            _stateMachine.OnTransitioned(transition =>
            {
                if (transition.Source == transition.Destination) return;
                Callback?.Invoke(this, new CallbackEventArgs(new DotaGameClient.SessionStateTransition(transition.Source, transition.Destination)));
            });

            _stateMachine.OnUnhandledTrigger((states, events) =>
            {
                Console.WriteLine("Unhandled trigger: " + events.ToString("G"));

            });

            var disconnected = new Action(() =>
            {
                if (_connection == null) return;
                Running = true;
                Stop();
            });

            _stateMachine.Configure(States.DISCONNECTED)
                .Ignore(Events.TICK)
                .Ignore(Events.DISCONNECTED)
                .OnEntry(disconnected)
                .Permit(Events.REQUEST_CONNECT, States.HANDSHAKE_REQUEST);
            _stateMachine.Configure(States.HANDSHAKE_REJECTED)
                .Permit(Events.DISCONNECTED, States.DISCONNECTED)
                .OnEntry(() =>
                {
                    Callback?.Invoke(this, new CallbackEventArgs(new DotaGameClient.HandshakeRejected(_handshake.rejected_reason)));
                    _stateMachine.Fire(Events.DISCONNECTED);
                });
            _stateMachine.Configure(States.HANDSHAKE_REQUEST)
                .OnEntry(() => handshake_requested = DateTime.Now.Ticks)
                .OnEntry(_handshake.RequestHandshake)
                .Ignore(Events.TICK)
                .Permit(Events.HANDSHAKE_CHALLENGE, States.HANDSHAKE_CONNECT)
                .Permit(Events.REJECTED, States.HANDSHAKE_REJECTED)
                .Permit(Events.DISCONNECTED, States.DISCONNECTED);
            _stateMachine.Configure(States.HANDSHAKE_CONNECT)
                .OnEntry(_handshake.RespondHandshake)
                .Ignore(Events.TICK)
                .PermitReentry(Events.HANDSHAKE_CHALLENGE) // possibly re-enter?
                .Permit(Events.HANDSHAKE_COMPLETE, States.CONNECTED)
                .Permit(Events.REJECTED, States.HANDSHAKE_REJECTED)
                .Permit(Events.DISCONNECTED, States.DISCONNECTED);
            _stateMachine.Configure(States.CONNECTED)
                .OnEntry(_signon.EnterConnected)
                .Ignore(Events.TICK)
                .Permit(Events.LOADING_START, States.LOADING)
                .Permit(Events.DISCONNECTED, States.DISCONNECTED);
            _stateMachine.Configure(States.LOADING)
                .OnEntry(_signon.EnterNew)
                .Ignore(Events.TICK)
                .Permit(Events.CONNECTED, States.CONNECTED)
                .Permit(Events.PRESPAWN_START, States.PRESPAWN)
                .Permit(Events.DISCONNECTED, States.DISCONNECTED);
            _stateMachine.Configure(States.PRESPAWN)
                .OnEntry(_signon.EnterPrespawn)
                .Ignore(Events.TICK)
                .Permit(Events.SPAWNED, States.SPAWN)
                .Permit(Events.DISCONNECTED, States.DISCONNECTED);
            _stateMachine.Configure(States.SPAWN)
                .OnEntry(_signon.EnterSpawn)
                .Ignore(Events.TICK)
                .Permit(Events.BASELINE, States.PLAY)
                .Permit(Events.DISCONNECTED, States.DISCONNECTED);
            _stateMachine.Configure(States.PLAY)
                .OnEntryFrom(Events.BASELINE, () =>
                {
                    _game.EnterGame();
                    _commandGenerator.Reset();
                })
                .OnEntryFrom(Events.TICK, () =>
                {
                    _gameState.Update();
                    foreach(var cont in Controllers) cont.Tick();
                    _commandGenerator.Tick();
                    _gameState.Created.Clear();
                    _gameState.Deleted.Clear();
                })
                .PermitReentry(Events.TICK)
                .Permit(Events.DISCONNECTED, States.DISCONNECTED);

            _stateMachine.Fire(Events.REQUEST_CONNECT);

            long next_tick = DateTime.Now.Ticks;
            while (Running && _stateMachine.State != States.DISCONNECTED && _stateMachine.State != States.HANDSHAKE_REJECTED)
            {
                try
                {
                    if (next_tick > DateTime.Now.Ticks)
                    {
                        Thread.Sleep(1);
                        continue;
                    }

                    if (_stateMachine == null) break;

                    if (_stateMachine.State == States.HANDSHAKE_REQUEST &&
                        (DateTime.Now.Ticks - handshake_requested) > handshake_giveup)
                    {
                        _stateMachine.Fire(Events.DISCONNECTED);
                        continue;
                    }

                    if (_connection.state == DotaGameConnection.State.Closed)
                    {
                        _stateMachine.Fire(Events.DISCONNECTED);
                        continue;
                    }

                    if (_connection == null) break;

                    List<byte[]> outBand = _connection.GetOutOfBand();
                    List<DotaGameConnection.Message> inBand = _connection.GetInBand();

                    foreach (byte[] message in outBand)
                    {
                        Nullable<Events> e = processors[metastates[_stateMachine.State]].Handle(message);
                        if (e.HasValue)
                        {
                            _stateMachine.Fire(e.Value);
                        }
                    }

                    foreach (DotaGameConnection.Message message in inBand)
                    {
                        Nullable<Events> e = processors[metastates[_stateMachine.State]].Handle(message);
                        if (e.HasValue)
                        {
                            _stateMachine.Fire(e.Value);
                        }
                    }

                    _stateMachine.Fire(Events.TICK);

                    if (_gameState.TickInterval > 0)
                    {
                        next_tick += (uint)(_gameState.TickInterval * 1000 * 10000 /* ticks per ms */);
                    }
                    else
                    {
                        next_tick += 50 * 1000;
                    }
                    int remain = (int)(next_tick - DateTime.Now.Ticks) / 10000;
                    if (remain > 0)
                    {
                        Thread.Sleep(1);
                    }
                    else if (remain < 0)
                    {
                        next_tick = DateTime.Now.Ticks;
                    }
                }
                catch (Exception ex)
                {
                    Callback?.Invoke(this, new CallbackEventArgs(new DotaGameClient.LogMessage("Ignored error in session loop, " + ex.Message)));
                }
            }

            if (Running) Stop();
        }
        private StateMachine<ImportNotificationStatus, Trigger> CreateStateMachine()
        {
            var stateMachine = new StateMachine<ImportNotificationStatus, Trigger>(() => Status, s => Status = s);

            stateMachine.OnTransitioned(OnTransition);

            receivedTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.Receive);
            fullyPaidTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.FullyPaid);
            beginAssessmentTrigger = stateMachine.SetTriggerParameters<DateTime, string>(Trigger.BeginAssessment);
            completeNotificationTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.CompleteNotification);
            acknowledgeTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.Acknowledge);
            consentedTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.Consent);
            withdrawConsentTrigger = stateMachine.SetTriggerParameters<DateTime, string>(Trigger.WithdrawConsent);
            fileClosedTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.FileClosed);

            stateMachine.Configure(ImportNotificationStatus.New)
                .Permit(Trigger.Receive, ImportNotificationStatus.NotificationReceived);

            stateMachine.Configure(ImportNotificationStatus.NotificationReceived)
                .OnEntryFrom(receivedTrigger, OnReceived)
                .Permit(Trigger.Submit, ImportNotificationStatus.AwaitingPayment)
                .Permit(Trigger.Withdraw, ImportNotificationStatus.Withdrawn)
                .Permit(Trigger.Object, ImportNotificationStatus.Objected)
                .Permit(Trigger.FileClosed, ImportNotificationStatus.FileClosed);

            stateMachine.Configure(ImportNotificationStatus.AwaitingPayment)
                .SubstateOf(ImportNotificationStatus.Submitted)
                .Permit(Trigger.FullyPaid, ImportNotificationStatus.AwaitingAssessment)
                .Permit(Trigger.Withdraw, ImportNotificationStatus.Withdrawn)
                .Permit(Trigger.Object, ImportNotificationStatus.Objected)
                .Permit(Trigger.FileClosed, ImportNotificationStatus.FileClosed);

            stateMachine.Configure(ImportNotificationStatus.AwaitingAssessment)
                .SubstateOf(ImportNotificationStatus.Submitted)
                .OnEntryFrom(fullyPaidTrigger, OnFullyPaid)
                .Permit(Trigger.BeginAssessment, ImportNotificationStatus.InAssessment)
                .Permit(Trigger.Withdraw, ImportNotificationStatus.Withdrawn)
                .Permit(Trigger.Object, ImportNotificationStatus.Objected)
                .Permit(Trigger.FileClosed, ImportNotificationStatus.FileClosed);
            
            stateMachine.Configure(ImportNotificationStatus.InAssessment)
                .OnEntryFrom(beginAssessmentTrigger, OnAssessmentStarted)
                .Permit(Trigger.CompleteNotification, ImportNotificationStatus.ReadyToAcknowledge)
                .Permit(Trigger.Object, ImportNotificationStatus.Objected)
                .Permit(Trigger.Withdraw, ImportNotificationStatus.Withdrawn)
                .Permit(Trigger.FileClosed, ImportNotificationStatus.FileClosed);

            stateMachine.Configure(ImportNotificationStatus.ReadyToAcknowledge)
                .OnEntryFrom(completeNotificationTrigger, OnNotificationCompleted)
                .Permit(Trigger.Acknowledge, ImportNotificationStatus.DecisionRequiredBy)
                .Permit(Trigger.Withdraw, ImportNotificationStatus.Withdrawn)
                .Permit(Trigger.Object, ImportNotificationStatus.Objected)
                .Permit(Trigger.FileClosed, ImportNotificationStatus.FileClosed);

            stateMachine.Configure(ImportNotificationStatus.DecisionRequiredBy)
                .OnEntryFrom(acknowledgeTrigger, OnAcknowledged)
                .Permit(Trigger.Consent, ImportNotificationStatus.Consented)
                .Permit(Trigger.Object, ImportNotificationStatus.Objected)
                .Permit(Trigger.Withdraw, ImportNotificationStatus.Withdrawn)
                .Permit(Trigger.FileClosed, ImportNotificationStatus.FileClosed);

            stateMachine.Configure(ImportNotificationStatus.Consented)
                .OnEntryFrom(consentedTrigger, OnConsented)
                .Permit(Trigger.WithdrawConsent, ImportNotificationStatus.ConsentWithdrawn)
                .Permit(Trigger.FileClosed, ImportNotificationStatus.FileClosed);

            stateMachine.Configure(ImportNotificationStatus.ConsentWithdrawn)
                .OnEntryFrom(withdrawConsentTrigger, OnConsentWithdrawn)
                .Permit(Trigger.FileClosed, ImportNotificationStatus.FileClosed);

            stateMachine.Configure(ImportNotificationStatus.Objected)
                .Permit(Trigger.FileClosed, ImportNotificationStatus.FileClosed);

            stateMachine.Configure(ImportNotificationStatus.Withdrawn)
                .Permit(Trigger.FileClosed, ImportNotificationStatus.FileClosed);

            stateMachine.Configure(ImportNotificationStatus.FileClosed)
                .OnEntryFrom(fileClosedTrigger, OnFileClosed);

            return stateMachine;
        }
Exemplo n.º 21
0
        private void ConfigureStateMachine()
        {
            _fsm = new StateMachine<State, Trigger>(State.Unmonitored);

            _fsm.OnTransitioned(OnStateMachineTransitioned);

            _fsm.Configure(State.Unmonitored)
                .Permit(Trigger.Watch, State.Connecting)
                .OnEntry(OnUnmonitoredState);

            _fsm.Configure(State.Monitored)
                .Permit(Trigger.Unwatch, State.Unmonitored)
                .OnEntry(OnMonitoredState);

            _fsm.Configure(State.Disconnected)
                .SubstateOf(State.Monitored)
                .PermitReentry(Trigger.Disconnect)
                .Permit(Trigger.Connect, State.Connecting)
                .OnEntry(OnDisconnectedState);

            _fsm.Configure(State.Connecting)
                .SubstateOf(State.Disconnected)
                .Permit(Trigger.Connected, State.Connected)
                .OnEntry(OnConnectingState);

            _fsm.Configure(State.Restarting)
                .SubstateOf(State.Disconnected)
                .Permit(Trigger.Connected, State.Connected);

            _fsm.Configure(State.Upgrading)
                .SubstateOf(State.Disconnected)
                .Permit(Trigger.Connected, State.Connected);

            _fsm.Configure(State.Connected)
                .SubstateOf(State.Monitored)
                .Permit(Trigger.Restart, State.Restarting)
                .Permit(Trigger.Upgrade, State.Upgrading)
                .Permit(Trigger.Disconnect, State.Disconnected)
                .Permit(Trigger.Disconnected, State.Disconnected)
                .OnEntry(OnConnectedState)
                .OnExit(OnConnectedStateExit);
        }
Exemplo n.º 22
0
        private StateMachine<MovementStatus, Trigger> CreateStateMachine()
        {
            var stateMachine = new StateMachine<MovementStatus, Trigger>(() => Status, s => Status = s);

            submittedTrigger = stateMachine.SetTriggerParameters<Guid>(Trigger.Submit);
            internallySubmittedTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.SubmitInternal);
            completedTrigger = stateMachine.SetTriggerParameters<DateTime, Guid, Guid>(Trigger.Complete);
            internallyCompletedTrigger = stateMachine.SetTriggerParameters<DateTime, Guid>(Trigger.CompleteInternal);

            acceptedTrigger = stateMachine.SetTriggerParameters<AcceptedTriggerParameters>(Trigger.Receive);
            internallyAcceptedTrigger = stateMachine.SetTriggerParameters<InternallyAcceptedTriggerParameters>(Trigger.ReceiveInternal);

            stateMachine.OnTransitioned(OnTransitionAction);

            stateMachine.Configure(MovementStatus.New)
                .Permit(Trigger.Submit, MovementStatus.Submitted);

            stateMachine.Configure(MovementStatus.Submitted)
                .OnEntryFrom(submittedTrigger, OnSubmitted)
                .OnEntryFrom(internallySubmittedTrigger, OnInternallySubmitted)
                .Permit(Trigger.Receive, MovementStatus.Received)
                .Permit(Trigger.ReceiveInternal, MovementStatus.Received)
                .Permit(Trigger.Reject, MovementStatus.Rejected)
                .Permit(Trigger.Cancel, MovementStatus.Cancelled);

            stateMachine.Configure(MovementStatus.Received)
                .OnEntryFrom(acceptedTrigger, OnReceived)
                .OnEntryFrom(internallyAcceptedTrigger, OnInternallyReceived)
                .Permit(Trigger.Complete, MovementStatus.Completed)
                .Permit(Trigger.CompleteInternal, MovementStatus.Completed);

            stateMachine.Configure(MovementStatus.Completed)
                .OnEntryFrom(completedTrigger, OnCompleted)
                .OnEntryFrom(internallyCompletedTrigger, OnInternallyCompleted);

            stateMachine.Configure(MovementStatus.Captured)
                .Permit(Trigger.ReceiveInternal, MovementStatus.Received)
                .Permit(Trigger.Reject, MovementStatus.Rejected)
                .Permit(Trigger.SubmitInternal, MovementStatus.Submitted);

            return stateMachine;
        }
        private StateMachine<NotificationStatus, Trigger> CreateStateMachine()
        {
            var stateMachine = new StateMachine<NotificationStatus, Trigger>(() => Status, s => Status = s);

            receivedTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.NotificationReceived);
            commencedTrigger = stateMachine.SetTriggerParameters<DateTime, string>(Trigger.AssessmentCommenced);
            completeTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.NotificationComplete);
            transmitTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.Transmit);
            acknowledgedTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.Acknowledged);
            withdrawTrigger = stateMachine.SetTriggerParameters<DateTime, string>(Trigger.Withdraw);
            objectTrigger = stateMachine.SetTriggerParameters<DateTime, string>(Trigger.Object);
            withdrawConsentTrigger = stateMachine.SetTriggerParameters<DateTime, string>(Trigger.WithdrawConsent);
            consentedTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.Consent);
            archiveTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.Archive);

            stateMachine.OnTransitioned(OnTransitionAction);

            stateMachine.Configure(NotificationStatus.NotSubmitted)
                .Permit(Trigger.Submit, NotificationStatus.Submitted)
                .Permit(Trigger.Archive, NotificationStatus.FileClosed);

            stateMachine.Configure(NotificationStatus.Submitted)
                .SubstateOf(NotificationStatus.InDetermination)
                .OnEntryFrom(Trigger.Submit, OnSubmit)
                .Permit(Trigger.NotificationReceived, NotificationStatus.NotificationReceived);

            stateMachine.Configure(NotificationStatus.NotificationReceived)
                .SubstateOf(NotificationStatus.InDetermination)
                .OnEntryFrom(receivedTrigger, OnReceived)
                .PermitIf(Trigger.AssessmentCommenced, NotificationStatus.InAssessment, () => Dates.PaymentReceivedDate.HasValue)
                .Permit(Trigger.Object, NotificationStatus.Objected);

            stateMachine.Configure(NotificationStatus.InAssessment)
                .SubstateOf(NotificationStatus.InDetermination)
                .OnEntryFrom(commencedTrigger, OnInAssessment)
                .Permit(Trigger.NotificationComplete, NotificationStatus.ReadyToTransmit)
                .Permit(Trigger.Object, NotificationStatus.Objected);

            stateMachine.Configure(NotificationStatus.ReadyToTransmit)
                .SubstateOf(NotificationStatus.InDetermination)
                .OnEntryFrom(completeTrigger, OnCompleted)
                .Permit(Trigger.Transmit, NotificationStatus.Transmitted)
                .Permit(Trigger.Object, NotificationStatus.Objected);

            stateMachine.Configure(NotificationStatus.Transmitted)
                .SubstateOf(NotificationStatus.InDetermination)
                .OnEntryFrom(transmitTrigger, OnTransmitted)
                .Permit(Trigger.Acknowledged, NotificationStatus.DecisionRequiredBy)
                .Permit(Trigger.Object, NotificationStatus.Objected);

            stateMachine.Configure(NotificationStatus.DecisionRequiredBy)
                .OnEntryFrom(acknowledgedTrigger, OnAcknowledged)
                .Permit(Trigger.Unlock, NotificationStatus.Unlocked)
                .Permit(Trigger.Consent, NotificationStatus.Consented)
                .Permit(Trigger.Object, NotificationStatus.Objected)
                .Permit(Trigger.Withdraw, NotificationStatus.Withdrawn)
                .Permit(Trigger.Archive, NotificationStatus.FileClosed);

            stateMachine.Configure(NotificationStatus.InDetermination)
                .Permit(Trigger.Withdraw, NotificationStatus.Withdrawn)
                .Permit(Trigger.Archive, NotificationStatus.FileClosed);

            stateMachine.Configure(NotificationStatus.Withdrawn)
                .OnEntryFrom(withdrawTrigger, OnWithdrawn)
                .Permit(Trigger.Archive, NotificationStatus.FileClosed);

            stateMachine.Configure(NotificationStatus.Objected)
                .OnEntryFrom(objectTrigger, OnObjected)
                .Permit(Trigger.Archive, NotificationStatus.FileClosed);

            stateMachine.Configure(NotificationStatus.Consented)
                .OnEntryFrom(consentedTrigger, OnConsented)
                .Permit(Trigger.WithdrawConsent, NotificationStatus.ConsentWithdrawn)
                .Permit(Trigger.Archive, NotificationStatus.FileClosed);

            stateMachine.Configure(NotificationStatus.ConsentWithdrawn)
                .OnEntryFrom(withdrawConsentTrigger, OnConsentWithdrawn)
                .Permit(Trigger.Archive, NotificationStatus.FileClosed);

            stateMachine.Configure(NotificationStatus.Unlocked)
                .SubstateOf(NotificationStatus.InDetermination)
                .Permit(Trigger.Resubmit, NotificationStatus.Reassessment);

            stateMachine.Configure(NotificationStatus.Reassessment)
                .SubstateOf(NotificationStatus.InDetermination)
                .Permit(Trigger.AcceptChanges, NotificationStatus.DecisionRequiredBy)
                .Permit(Trigger.RejectChanges, NotificationStatus.Unlocked);

            stateMachine.Configure(NotificationStatus.FileClosed)
                .OnEntryFrom(archiveTrigger, OnFileClosed);

            return stateMachine;
        }
Exemplo n.º 24
0
        public override void OnUpdateInit(long msec)
        {
            Animation.AddClip (walkUp);
            Animation.AddClip (walkDown);
            Animation.AddClip (walkRight);
            Animation.AddClip (walkLeft);

            sm = new StateMachine<State, Trigger> (State.Down);
            walkDown.Play ();

            sm.Configure (State.Down)
                .Ignore (Trigger.Down)
                .Permit (Trigger.Up, State.Up)
                .Permit (Trigger.Right, State.Right)
                .Permit (Trigger.Left, State.Left)
                .OnExit (x => walkDown.Stop ())
                .OnEntry (x => walkDown.Play ());

            sm.Configure (State.Up)
                .Permit (Trigger.Down, State.Down)
                .Ignore (Trigger.Up)
                .Permit (Trigger.Right, State.Right)
                .Permit (Trigger.Left, State.Left)
                .OnExit (x => walkUp.Stop ())
                .OnEntry (x => walkUp.Play ());

            sm.Configure (State.Right)
                .Permit (Trigger.Down, State.Down)
                .Permit (Trigger.Up, State.Up)
                .Ignore (Trigger.Right)
                .Permit (Trigger.Left, State.Left)
                .OnExit (x => walkRight.Stop ())
                .OnEntry (x => walkRight.Play ());

            sm.Configure (State.Left)
                .Permit (Trigger.Down, State.Down)
                .Permit (Trigger.Up, State.Up)
                .Permit (Trigger.Right, State.Right)
                .Ignore (Trigger.Left)
                .OnExit (x => walkLeft.Stop ())
                .OnEntry (x => walkLeft.Play ());
        }
Exemplo n.º 25
0
        public MainLogicProcessor()
        {
            VisionData = new VisionData();
            SensorData = new SensorData();
            LogicState = new LogicState();

            stateMachine = new StateMachine<State, Trigger>(State.Idle);

            stateMachine.OnUnhandledTrigger((state, trigger) => { });

            stateMachine.Configure(State.Idle)
                .Permit(Trigger.PoweredUp, State.Starting)
                .OnEntry(() => Commander.SetColors(Colors.Yellow));

            stateMachine.Configure(State.Starting)
                .Permit(Trigger.Finished, State.LookingForBall)
                .Permit(Trigger.BallCaught, State.FindingGoal)
                .OnEntry(() =>
                {
                    stopwatchTime = stopwatch.ElapsedMilliseconds;
                    SoundClipPlayer.PlayIntro();
                    Commander.SetColors(Colors.Cyan);
                });

            stateMachine.Configure(State.LookingForBall)
                .Permit(Trigger.CameraLockedOnBall, State.ClosingInOnBall)
                .Permit(Trigger.BallCaught, State.FindingGoal)
                .OnEntry(
                () =>
                {
                    Commander.SetColors(Colors.Blue);
                    stopwatchTime = stopwatch.ElapsedMilliseconds;
                });

            stateMachine.Configure(State.ClosingInOnBall)
                .Permit(Trigger.CameraLostBall, State.LookingForBall)
                .Permit(Trigger.BallCaught, State.FindingGoal)
                .Permit(Trigger.Timeout, State.LookingForBall)
                .OnEntry(() =>
                {
                    StartTimer(10000, Trigger.Timeout);
                    Commander.SetColors(Colors.Red);
                })
                .OnExit(StopTimer);

            stateMachine.Configure(State.FindingGoal)
                .Permit(Trigger.CoilgunLaunched, State.LookingForBall)
                .Permit(Trigger.BallLost, State.LookingForBall)
                .Permit(Trigger.Timeout, State.LookingForBall)
                .OnEntry(() =>
                {
                    LogicState.FindingGoal = true;
                    StartTimer(5000, LaunchBall);
                    Commander.SetColors(Colors.Magenta);
                })
                .OnExit(
                () =>
                {
                    LogicState.FindingGoal = false;
                    StopTimer();
                });

            stopwatch.Start();
        }
        private StateMachine<FinancialGuaranteeStatus, Trigger> CreateStateMachine()
        {
            var stateMachine = new StateMachine<FinancialGuaranteeStatus, Trigger>(() => Status, s => Status = s);

            completedTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.Completed);
            approvedTrigger = stateMachine.SetTriggerParameters<ApprovalData>(Trigger.Approved);
            refusedTrigger = stateMachine.SetTriggerParameters<DateTime, string>(Trigger.Refused);
            releasedTrigger = stateMachine.SetTriggerParameters<DateTime>(Trigger.Released);

            stateMachine.Configure(FinancialGuaranteeStatus.ApplicationReceived)
                .Permit(Trigger.Completed, FinancialGuaranteeStatus.ApplicationComplete);

            stateMachine.Configure(FinancialGuaranteeStatus.ApplicationComplete)
                .OnEntryFrom(completedTrigger, OnCompleted)
                .PermitIf(Trigger.Approved, FinancialGuaranteeStatus.Approved, () => CompletedDate.HasValue)
                .PermitIf(Trigger.Refused, FinancialGuaranteeStatus.Refused, () => CompletedDate.HasValue);

            stateMachine.Configure(FinancialGuaranteeStatus.Approved)
                .OnEntryFrom(approvedTrigger, OnApproved)
                .Permit(Trigger.Released, FinancialGuaranteeStatus.Released)
                .Permit(Trigger.Superseded, FinancialGuaranteeStatus.Superseded);

            stateMachine.Configure(FinancialGuaranteeStatus.Refused)
                .OnEntryFrom(refusedTrigger, OnRefused);

            stateMachine.Configure(FinancialGuaranteeStatus.Released)
                .OnEntryFrom(releasedTrigger, OnReleased);

            stateMachine.OnTransitioned(OnTransitionAction);

            return stateMachine;
        }
Exemplo n.º 27
0
        private void ConfigStateMachine(States initState)
        {
            MyStateMachine = new StateMachine<States, Triggers>(initState);

            MyStateMachine.Configure(States.Start)
                .OnExit(s => PrintState())
                .PermitIf(Triggers.DD_Trigger, States.DD, () => IsDD, "Dynamic to Dynamic")
                .PermitIf(Triggers.DS_Trigger, States.DS, () => IsDS, "Dynamic to Static")
                .PermitIf(Triggers.SD_Trigger, States.SD, () => IsSD, "Static to Dynamic")
                .PermitIf(Triggers.SS_Trigger, States.SS, () => IsSS, "Static to Static");

            MyStateMachine.Configure(States.DD)
                .OnExit(s => PrintState())
                .Permit(Triggers.CSP_Trigger, States.Carrier_CSP, "change Carrier CSP");

            MyStateMachine.Configure(States.DS)
                .OnExit(s => PrintState())
                .Permit(Triggers.Reserve_IP_Trigger, States.Reserve_IP, "reserve IP");

            MyStateMachine.Configure(States.Reserve_IP)
                .OnEntry(ReserveIP)
                .OnExit(s => PrintState())
                .Permit(Triggers.CSP_Trigger, States.Carrier_CSP, "change Carrier CSP");

            MyStateMachine.Configure(States.Carrier_CSP)
                .OnEntry(CSPChange)
                .OnExit(s => PrintState())
                .PermitIf(Triggers.Kore_Update_Trigger, States.Kore_Update, () => IsDD && result == Result.Success, "Carrier CSP changed")
                .PermitIf(Triggers.Update_Carrier_Static_IP_Trigger, States.Update_Carrier_Static_IP, () => IsDS && result == Result.Success, "update carrier static IP")
                .PermitReentryIf(Triggers.CSP_Trigger, () => result == Result.Pending, "Carrier CSP change is pending")
                .PermitIf(Triggers.Error_Trigger, States.Error, () => result == Result.Failed, "Carrier CSP change failed");

            MyStateMachine.Configure(States.Update_Carrier_Static_IP)
                .OnEntry(UpdateCarrierStaticIP)
                .OnExit(s => PrintState())
                .PermitIf(Triggers.Kore_Update_Trigger, States.Kore_Update,()=>result == Result.Success, "update Kore");

            MyStateMachine.Configure(States.Kore_Update)
                .OnEntry(KoreProfileChange)
                .OnExit(s => PrintState())
                .PermitIf(Triggers.Complete_Trigger, States.Complete, () => result == Result.Success, "Kore update succeed")
                .PermitIf(Triggers.Error_Trigger, States.Error, () => result == Result.Failed, "kore update failed");

            MyStateMachine.Configure(States.Complete)
                .OnEntry(s => PrintState());

            MyStateMachine.Configure(States.Error)
                .OnEntry(s => PrintState());
        }
Exemplo n.º 28
0
        private StateMachine<MediaPlayerState, Triggers> BuildStateMachine()
        {
            var stateMachine = new StateMachine<MediaPlayerState, Triggers>(MediaPlayerState.Closed);
            stateMachine.Configure(MediaPlayerState.Closed)
                .Permit(Triggers.SetMediaPlaybackList, MediaPlayerState.PlaybackListSet);
            stateMachine.Configure(MediaPlayerState.PlaybackListSet)
                .PermitReentry(Triggers.SetMediaPlaybackList)
                .Permit(Triggers.RaiseOpening, MediaPlayerState.MediaOpening);
            stateMachine.Configure(MediaPlayerState.MediaOpening)
                .Permit(Triggers.RaisePaused, MediaPlayerState.Paused)
                .Permit(Triggers.RaiseMediaOpened, MediaPlayerState.MediaOpened)
                .Permit(Triggers.RaiseError, MediaPlayerState.Error);
            stateMachine.Configure(MediaPlayerState.MediaOpened)
                .Permit(Triggers.RaisePaused, MediaPlayerState.Paused)
                .Permit(Triggers.Play, MediaPlayerState.StartPlaying);
            stateMachine.Configure(MediaPlayerState.StartPlaying)
                .Permit(Triggers.RaisePlaying, MediaPlayerState.Playing)
                .Permit(Triggers.RaiseBuffering, MediaPlayerState.Buffering)
                .Permit(Triggers.RaiseError, MediaPlayerState.Error);
            stateMachine.Configure(MediaPlayerState.Playing)
                .Permit(Triggers.Pause, MediaPlayerState.Pausing)
                .Permit(Triggers.RaisePaused, MediaPlayerState.Paused)
                .Permit(Triggers.RaiseEnded, MediaPlayerState.Ended)
                .Permit(Triggers.SetMediaPlaybackList, MediaPlayerState.PlaybackListSet)
                .Permit(Triggers.RaiseError, MediaPlayerState.Error);
            stateMachine.Configure(MediaPlayerState.Pausing)
                .Permit(Triggers.RaisePaused, MediaPlayerState.Paused)
                .Permit(Triggers.SetMediaPlaybackList, MediaPlayerState.PlaybackListSet)
                .Permit(Triggers.RaiseError, MediaPlayerState.Error);
            stateMachine.Configure(MediaPlayerState.Paused)
                .Permit(Triggers.RaiseEnded, MediaPlayerState.Ended)
                .Permit(Triggers.RaiseMediaOpened, MediaPlayerState.MediaOpened)
                .Permit(Triggers.Play, MediaPlayerState.StartPlaying)
                .Permit(Triggers.SetMediaPlaybackList, MediaPlayerState.PlaybackListSet);
            stateMachine.Configure(MediaPlayerState.Ended)
                .Permit(Triggers.Play, MediaPlayerState.StartPlaying)
                .Permit(Triggers.SetMediaPlaybackList, MediaPlayerState.MediaOpening);
            stateMachine.Configure(MediaPlayerState.Error)
                .Permit(Triggers.SetMediaPlaybackList, MediaPlayerState.MediaOpening);

            return stateMachine;
        }
Exemplo n.º 29
0
        public UIController(IUIProvider uiProvider, IRepositoryHosts hosts, IExportFactoryProvider factory,
            IConnectionManager connectionManager, Lazy<ITwoFactorChallengeHandler> lazyTwoFactorChallengeHandler)
        {
            this.factory = factory;
            this.uiProvider = uiProvider;
            this.hosts = hosts;
            this.connectionManager = connectionManager;
            this.lazyTwoFactorChallengeHandler = lazyTwoFactorChallengeHandler;

#if DEBUG
            if (Application.Current != null && !Splat.ModeDetector.InUnitTestRunner())
            {
                var waitDispatcher = RxApp.MainThreadScheduler as WaitForDispatcherScheduler;
                if (waitDispatcher != null)
                {
                    Debug.Assert(DispatcherScheduler.Current.Dispatcher == Application.Current.Dispatcher,
                       "DispatcherScheduler is set correctly");
                }
                else
                {
                    Debug.Assert(((DispatcherScheduler)RxApp.MainThreadScheduler).Dispatcher == Application.Current.Dispatcher,
                        "The MainThreadScheduler is using the wrong dispatcher");
                }
            }
#endif
            machine = new StateMachine<UIViewType, Trigger>(UIViewType.None);

            machine.Configure(UIViewType.Login)
                .OnEntry(() =>
                {
                    RunView(UIViewType.Login);
                })
                .Permit(Trigger.Next, UIViewType.TwoFactor)
                // Added the following line to make it easy to login to both GitHub and GitHub Enterprise 
                // in DesignTimeStyleHelper in order to test Publish.
                .Permit(Trigger.Cancel, UIViewType.End)
                .PermitIf(Trigger.Finish, UIViewType.End, () => currentFlow == UIControllerFlow.Authentication)
                .PermitIf(Trigger.Finish, UIViewType.Create, () => currentFlow == UIControllerFlow.Create)
                .PermitIf(Trigger.Finish, UIViewType.Clone, () => currentFlow == UIControllerFlow.Clone)
                .PermitIf(Trigger.Finish, UIViewType.Publish, () => currentFlow == UIControllerFlow.Publish);

            machine.Configure(UIViewType.TwoFactor)
                .SubstateOf(UIViewType.Login)
                .OnEntry(() =>
                {
                    RunView(UIViewType.TwoFactor);
                })
                .Permit(Trigger.Cancel, UIViewType.End)
                .PermitIf(Trigger.Next, UIViewType.End, () => currentFlow == UIControllerFlow.Authentication)
                .PermitIf(Trigger.Next, UIViewType.Create, () => currentFlow == UIControllerFlow.Create)
                .PermitIf(Trigger.Next, UIViewType.Clone, () => currentFlow == UIControllerFlow.Clone)
                .PermitIf(Trigger.Next, UIViewType.Publish, () => currentFlow == UIControllerFlow.Publish);

            machine.Configure(UIViewType.Create)
                .OnEntry(() =>
                {
                    RunView(UIViewType.Create);
                })
                .Permit(Trigger.Cancel, UIViewType.End)
                .Permit(Trigger.Next, UIViewType.End);

            machine.Configure(UIViewType.Clone)
                .OnEntry(() =>
                {
                    RunView(UIViewType.Clone);
                })
                .Permit(Trigger.Cancel, UIViewType.End)
                .Permit(Trigger.Next, UIViewType.End);

            machine.Configure(UIViewType.Publish)
                .OnEntry(() =>
                {
                    RunView(UIViewType.Publish);
                })
                .Permit(Trigger.Cancel, UIViewType.End)
                .Permit(Trigger.Next, UIViewType.End);

            machine.Configure(UIViewType.End)
                .OnEntry(() =>
                {
                    uiProvider.RemoveService(typeof(IConnection));
                    transition.OnCompleted();
                })
                .Permit(Trigger.Next, UIViewType.Finished);

            // it might be useful later to check which triggered
            // made us enter here (Cancel or Next) and set a final
            // result accordingly, which is why UIViewType.End only
            // allows a Next trigger
            machine.Configure(UIViewType.Finished);
        }
Exemplo n.º 30
0
        private void ConfigureMachine()
        {
            m_GameMachine = new StateMachine<State, Trigger>(() => m_CurrentState, newState => m_CurrentState = newState);
            ProcessMessages();

            #region WaitingForPlayers
            m_GameMachine.Configure(State.WaitingForPlayers)
                .Permit(Trigger.AllPlayersReady, State.AllPlayersReady)
                .OnEntryFrom(Trigger.PlayerNotReady, x =>
                {
                    GenericClientMessage waiting = new GenericClientMessage() { MessageEnum = ClientMessage.ClientMessageEnum.PlayerNotReady };
                    LookupPlayerById(m_GameCreatorClientId).Callback.SendMessage(waiting.ToXml());
                })
                .OnEntryFrom(Trigger.PlayerLeft, x =>
                {
                    SendUpdatedGameInfo();
                })
                .PermitReentry(Trigger.PlayerLeft)
                .Ignore(Trigger.PlayerNotReady)
                .Ignore(Trigger.CreatorPressedStart);
            #endregion

            #region AllPlayersReady
            m_GameMachine.Configure(State.AllPlayersReady)
                .OnEntry(x =>
                {
                    GenericClientMessage ready = new GenericClientMessage() { MessageEnum = ClientMessage.ClientMessageEnum.AllPlayersReady };
                    LookupPlayerById(m_GameCreatorClientId).Callback.SendMessage(ready.ToXml());
                })
                .Permit(Trigger.PlayerNotReady, State.WaitingForPlayers)
                .Permit(Trigger.PlayerLeft, State.WaitingForPlayers)
                .Permit(Trigger.CreatorPressedStart, State.GameStarted);
            #endregion

            #region GameStarted
            m_GameMachine.Configure(State.GameStarted)
                .OnEntry(x =>
                {
                    List<KeyValuePair<string, Army.ArmyTypeEnum>> PlayerInfos = new List<KeyValuePair<string, Army.ArmyTypeEnum>>();
                    foreach (Player player in Players)
                    {
                        PlayerInfos.Add(new KeyValuePair<string, Army.ArmyTypeEnum>(player.ClientId, player.ArmyType));
                        m_PlayerTurnOrder.Enqueue(player.ClientId);
                    }
                    GameState = new GameState(PlayerInfos);
                    pathFinder = new PathFinder(GameState);
                    ConsoleLogger.Push(String.Format("Game {0} has been started", Name));
                    NotifyAllPlayers(new GenericClientMessage() { MessageEnum = ClientMessage.ClientMessageEnum.TransitionToLoadingState }.ToXml()); // switch all the players to loading while we send the gamestate
                    ClientGameStateMessage gamestate = new ClientGameStateMessage() { State = GameState };
                    GenericClientMessage start = new GenericClientMessage() { MessageEnum = ClientMessage.ClientMessageEnum.StartGame };
                    AggregateMessage aggregate = new AggregateMessage();
                    aggregate.MessageList.Add(gamestate);
                    aggregate.MessageList.Add(start);
                    NotifyAllPlayers(aggregate.ToXml());
                    m_GameMachine.Fire(Trigger.GameStarted);
                })
                .Permit(Trigger.GameStarted, State.PlayerTurn)
                .Ignore(Trigger.PlayerNotReady);
            #endregion

            #region PlayerTurn
            m_GameMachine.Configure(State.PlayerTurn)
                .PermitReentry(Trigger.PlayerTurn)
                .Permit(Trigger.PlayerLeft, State.Reconfigure)
                .Permit(Trigger.StartBattlePhase, State.BattlePhase)
                .Permit(Trigger.Cheatcode, State.EndGame)
                .OnEntry(x =>
                {
                    // notify the current player that its their turn
                    m_CurrentPlayerId = m_PlayerTurnOrder.Dequeue();
                    LookupPlayerById(m_CurrentPlayerId).Callback.SendMessage((new GenericClientMessage() { MessageEnum = ClientMessage.ClientMessageEnum.ActiveTurn }).ToXml());

                    // notify all other players that they have to wait
                    foreach (string playerId in m_PlayerTurnOrder)
                    {
                        LookupPlayerById(playerId).Callback.SendMessage((new WaitingForTurnMessage() { ActivePlayerName = LookupPlayerById(m_CurrentPlayerId).Name }).ToXml());
                    }

                    // add the current player back on the queue
                    m_PlayerTurnOrder.Enqueue(m_CurrentPlayerId);
                });
            #endregion

            m_GameMachine.Configure(State.BattlePhase)
                .OnEntry(x =>
                {

                });

            #region EndGame
            m_GameMachine.Configure(State.EndGame)
                .OnEntry(x =>
                {
                    var winner = LookupPlayerById(m_WinnerId);
                    var gameOverMessage = new GameOverMessage() { WinnerId = m_WinnerId, WinnerName = winner.Name };
                    NotifyAllPlayers(gameOverMessage.ToXml());
                });
            #endregion

            #region Reconfigure
            m_GameMachine.Configure(State.Reconfigure)
                .OnEntry(x =>
                {
                    // this state allows us to reconfigure the players involved in the game in case someone leaves or is defeated
                    Queue<string> tempPlayers = new Queue<string>();
                    foreach (string playerId in m_PlayerTurnOrder)
                    {
                        if (Players.FirstOrDefault(p => p.ClientId == playerId) != null)
                        {
                            tempPlayers.Enqueue(playerId);
                        }
                    }
                    if (tempPlayers.Count > 0)
                    {
                        m_PlayerTurnOrder.Clear();
                        m_PlayerTurnOrder = tempPlayers;
                        m_GameMachine.Fire(Trigger.PlayerTurn);
                    }
                })
                .Permit(Trigger.PlayerTurn, State.PlayerTurn);
            #endregion
        }