blob: 366fb857f047f748057d46461b485e27e5d969f0 [file] [log] [blame]
// Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package fsm_test
import (
"android.googlesource.com/platform/tools/gpu/framework/fsm"
"android.googlesource.com/platform/tools/gpu/framework/log"
)
// This example shows how to use hooks to detect specific transitions.
func ExampleHook() {
ctx := log.Background().PreFilter(log.NoLimit).Filter(log.Pass).Handler(log.Stdout(log.Normal))
ctx = ctx.Enter("Example")
count := 0
err := fsm.Run(ctx, fsm.MustCompile(fsm.FSM{
States: []fsm.State{
{Name: "Init"},
fsm.Do("Ping", func(ctx log.Context) error {
count++
ctx.Printf("Pinging %d", count)
if count > 2 {
fsm.Get(ctx).Trigger(ctx, "stop")
}
return nil
}),
fsm.Do("Pong", func(ctx log.Context) error {
ctx.Print("Ponged")
return nil
}),
fsm.Exit("Done"),
},
Transitions: []fsm.Transition{
{From: "Init", To: "Ping"},
{From: "Ping", To: "Pong"},
{From: "Pong", To: "Ping"},
{From: "Ping", Event: "stop", To: "Done"},
},
Hooks: []fsm.Hook{
fsm.OnExit("Ping", func(ctx log.Context, fsm *fsm.Instance, from fsm.StateID, event fsm.Event) {
ctx.Printf("Leaving %s to %s because %s", from, fsm.State(), event)
}),
fsm.OnEnter("Ping", func(ctx log.Context, fsm *fsm.Instance, from fsm.StateID, event fsm.Event) {
ctx.Printf("Entering %s from %s because %s", fsm.State(), from, event)
}),
fsm.OnEvent("stop", func(ctx log.Context, fsm *fsm.Instance, from fsm.StateID, event fsm.Event) {
ctx.Printf("%s in %s goes to %s", event, from, fsm.State())
}),
},
}))
if err != nil {
ctx.Fail(err, "FSM failed")
return
}
// Output:
//Info:Example:Entering Ping from Init because next
//Info:Example->Ping:Pinging 1
//Info:Example:Leaving Ping to Pong because next
//Info:Example->Pong:Ponged
//Info:Example:Entering Ping from Pong because next
//Info:Example->Ping:Pinging 2
//Info:Example:Leaving Ping to Pong because next
//Info:Example->Pong:Ponged
//Info:Example:Entering Ping from Pong because next
//Info:Example->Ping:Pinging 3
//Info:Example:Leaving Ping to Done because stop
//Info:Example:stop in Ping goes to Done
}