Skip to end of metadata
Go to start of metadata

A finite-state machine can be implemented in a few minutes on the command line or in a bash script using csv-join.

Assume we have the following state machine:

moore-finite-state-machine

It has the following events and states:

events:

  1. close
  2. open
  3. sensor closed
  4. sensor opened

states:

  1. opened
  2. closing
  3. closed
  4. opening

The state transition table can be expressed in a csv file state-transition.csv:

# event,state,next_state
$ cat state-transition.csv
close,opened,closing
close,opening,closing
open,closing,opening
open,closed,opening
sensor_closed,closing,closed
sensor_opened,opening,opened

With the state transition table, csv-join can read in events, output the next state and keep track of this new state. Here is an example usage (input is marked '<', output '>'):

$ csv-join --fields event "state-transition.csv;fields=event,state,next_state" --string --initial-state "closed"
< open
> open,open,closed,opening
< sensor_opened
> sensor_opened,sensor_opened,opening,opened
< close
> close,close,opened,closing
< sensor_closed
> sensor_closed,sensor_closed,closing,closed
< open
> open,open,closed,opening
< close
> close,close,opening,closing
< sensor_closed
> sensor_closed,sensor_closed,closing,closed

The input field and joining key in this case is a single field event. As usual with csv-join any number of fields can be used to represent an event. The following example has the event represented by two fields: operation and result.

csv-join --fields operation,result "state-transition.csv;fields=operation,result,state,next_state" --string --initial-state 1

csv-join expects the state transition table to contain unique matches only (as per csv-join --unique).

The finite-state machine is only activated when the file/stream fields contain both 'state' and 'next_state'.


Related articles

 Finite-state machine

  • No labels