FSM DSL in Kotlin

FSM DSL in Kotlin

F46a37b9f855c245f72a07b04045216a?s=128

Tomoya Miwa

June 27, 2018
Tweet

Transcript

  1. FSM DSL in Kotlin tomoya0x00 Kotlin Developers Meetup

  2. About me tomoya0x00 Twitter, GitHub, Qiita Android, Embedded system, BLE/BT,

    iOS DeNA Co., Ltd. Automotive Business Unit.
  3. Everyone

  4. You want to make DSL by yourself?

  5. I want to FSM DSL in Kotlin FSM is nite

    state machine.
  6. Why FSM? Avoid confusion caused by multiple ag management Easy

    to test
  7. And, I want to support composite states

  8. Example

  9. Simple smart lock for bike sharing

  10. I am developing a Proof-of-Concept

  11. DSL Example val sm = stateMachine(initial = MyState.NotLoaned) { state(MyState.NotLoaned)

    { edge(MyEvent.PressRental, next = MyState.Lock) } state(MyState.OnLoan, entry = { println("turnOnRentalLed") }, exit = { println("turnOffRentalLed") }) { state(MyState.Lock) { edge(MyEvent.PressReturn, next = MyState.NotLoaned) edge(MyEvent.PressUnLock, next = MyState.UnLock) } state(MyState.UnLock) { edge(MyEvent.PressLock, next = MyState.Lock) } } }
  12. Let's run! val next = sm.dispatch(MyEvent.PressRental) assert(next).isEqualTo(MyState.Lock) result: turnOnRentalLed next

    == MyState.Lock
  13. Internal

  14. Generate the tree of states DSL Tree of states

  15. DSL internal fun stateMachine( initial: BaseState, init: StateMachine.() -> Unit

    ): StateMachine = StateMachine(initial = initial) .apply(init)
  16. Problem

  17. Search processing is executed for each dispatch

  18. When press return in Lock state Find route to NotLoaned

    state from Lock state
  19. When press return in Lock state Find route to NotLoaned

    state from Lock state
  20. When press return in Lock state Find route to NotLoaned

    state from Lock state
  21. When press return in Lock state Find route to NotLoaned

    state from Lock state
  22. When press return in Lock state Find route to NotLoaned

    state from Lock state
  23. When press return in Lock state Execute entry/exit on route

  24. Solution

  25. StateMachine.Builder fun stateMachine( initial: BaseState, init: StateMachine.Builder.() -> Unit ):

    StateMachine = StateMachine.Builder(initial = initial) .apply(init).build()
  26. Generate transition map in build() state event actions next NotLoaned

    PressRental [OnLoan.entry] Lock Lock PressReturn [OnLoan.exit] NotLoaned Lock PressUnLock [] UnLock UnLock PressLock [] Lock
  27. But, not implemented yet... to be available soon!

  28. Any Idea? Tree search algorithm when creating transition map, if

    you have any good idea, please let me know!
  29. Waiting for your suggestions︕ https://github.com/tomoya0x00/fsm-dsl- kotlin-poc

  30. Thank you!