Skip to content

Instantly share code, notes, and snippets.

@momania
Created November 25, 2010 13:15
Show Gist options
  • Save momania/715371 to your computer and use it in GitHub Desktop.
Save momania/715371 to your computer and use it in GitHub Desktop.
Simple FSM Lock
package samples.fsm.lock
import java.util.concurrent.TimeUnit
import TimeUnit._
import akka.actor.{ActorRegistry, FSM, Actor}
sealed trait LockState
case object Locked extends LockState
case object Open extends LockState
class Lock(code: String) extends Actor with FSM[LockState, String] {
val emptyCode = ""
when(Locked) {
case Event(digit: Char, soFar) => {
soFar + digit match {
case incomplete if incomplete.length < code.length =>
stay using incomplete
case `code` =>
log.info("Unlocked")
goto(Open) using emptyCode forMax (1, SECONDS)
case wrong =>
log.error("Wrong code " + wrong)
stay using emptyCode
}
}
}
when(Open) {
case Event(StateTimeout, _) => {
log.info("Locked")
goto(Locked)
}
}
startWith(Locked, emptyCode)
}
object Lock {
def main(args: Array[String]) {
val lock = Actor.actorOf(new Lock("1234")).start
lock ! '1'
lock ! '2'
lock ! '3'
lock ! '4'
ActorRegistry.shutdownAll
exit
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment