In computation theory, the Finite State Machine (FSM) is those machines that can have a finite number of states at a given time. These machines are used in our daily life such as; vending machines, elevators, traffic lights, etc. Not only in hardware these machines are used in the software also.

在计算理论中,有限状态机(FSM)是在给定时间可以具有有限数量状态的机器。 这些机器用于我们的日常生活中,例如; 自动售货机,电梯,交通信号灯等。这些机器不仅用于硬件,而且还用于软件。

什么是FSM? What is FSM?

They are the process to model stateful, reactive systems i.e in behavior-driven development. FSM based programming is a powerful tool to model complicated state transitions, it could significantly simplify our programs.

它们是对有状态的React性系统进行建模的过程,即在行为驱动的开发中。 基于FSM的编程是建模复杂状态转换的强大工具,它可以大大简化我们的程序。

For a functional programming standpoint, FSM is a function that takes in four parameters; initial state, transition function, set of states, event, and then return the next state at which the machine can be.

从功能编程的角度来看,FSM是一个具有四个参数的函数。 初始状态,转换函数,状态集,事件,然后返回机器可以处于的下一个状态。

Image for post
Wikipedia 维基百科
lockedunlockedlockedcoinpush
lockedunlockedlockedcoinpush

With this, we can see how our state machine function can give out the next state when we provide it with the initial state, number of states, transition function (described by the table), and event.

这样,我们便可以了解到状态机功能如何向其提供初始状态,状态数,转换函数(由表描述)和事件,从而发出下一个状态。

In automata theory, there are different types of state machines and various other state-based concepts so, for simplicity, I am only talking about the basic finite state machine.

在自动机理论中,有不同类型的状态机和各种其他基于状态的概念,因此,为简单起见,我仅讨论基本的有限状态机。

状态说明图 FIGURE TO STATE DESCRIPTION

I know it would be better if we could directly send our diagram into the machine and it would change the state based on the diagram (like; BPMN which is also a kind of state machine built just for business process modeling)

我知道最好将图表直接发送到机器中,并且根据图表更改状态(例如BPMN,这也是一种仅用于业务流程建模的状态机),这样会更好。

Let’s define our struct that would be used to model our figure into code. (this description is inspired by xstate, a state charts library in JavaScript)

让我们定义将用于将图形建模为代码的结构。 (此描述的灵感来自xstate ,这是JavaScript中的状态图库)

// MachineTransition transition map
type MachineTransition struct {
	To      string
}


// TransitionMap map with transitions
type TransitionMap map[string]MachineTransition


// MachineState is State of machine
type MachineState struct {
	On TransitionMap
}


// StateMap maps state
type StateMap map[string]MachineState


// Machine datatype
type Machine struct {
	Initial     string
	current     string
	States      StateMap
}

Here, The struct machine describes all our parameters described previously.

在这里,struct机器描述了我们前面描述的所有参数。

MachineMachineStateMapStateMapTransitionMapTransitionMap
Image for post
https://xstate.js.org/viz/ https://xstate.js.org/viz/生成

The switch toggling from one state to another state as described in the figure above can be described as;

如上图所示,从一种状态切换到另一种状态的开关可以描述为:

machine := statemachine.Machine{
    Initial: "on",
    States: statemachine.StateMap{
        "on": statemachine.MachineState{
            On: statemachine.TransitionMap{
                "TOGGLE": statemachine.MachineTransition{
                    To: "off",
                },
            },
        },
        "off": statemachine.MachineState{
            On: statemachine.TransitionMap{
                "TOGGLE": statemachine.MachineTransition{
                    To: "on",
                },
            },
        },
    },
}
onTOGGLEoffoffTOGGLEon
onTOGGLEoffoffTOGGLEon

Now we have described the machine using our format but the engine that transitions the state from one to another is still not built.

现在,我们已经使用格式描述了机器,但是仍未构建将状态从一种转换为另一种的引擎。

过渡引擎 TRANSITION ENGINE
MachineTransitionCurrent
MachineTransitionCurrent
// IMachine machine interface
type IMachine interface {
	Transition() string
	Current() string
}


// Current returns current state
func (m *Machine) Current() string {
	if m.current == "" {
		return m.Initial
	}
	return m.current
}


// Transition transitions to next state
func (m *Machine) Transition(event string) string {
	current := m.Current()
	transitions := m.States[current].On
	for evt := range transitions {
		if evt == event {
			next := transitions[evt].To
			m.current = next
			return next
		}
	}
	return current
}

In the above code we can see that;

在上面的代码中我们可以看到;

eventevent

Now, let’s use the functions. The function can be used using;

现在,让我们使用这些功能。 该功能可以通过以下方式使用:

output := machine.Transition("TOGGLE")

and we can see that the machine has actually transitioned into another state.

我们可以看到机器实际上已经过渡到另一种状态。

最终密码 FINAL CODE

Final code of the machine description and toggling state will look like;

机器描述和切换状态的最终代码将如下所示;

package main


import (
	"fmt"


	"github.com/dipeshdulal/statemachine"
)


func main(){
  machine := statemachine.Machine{
      ID:      "machine-1",
      Initial: "on",
      States: statemachine.StateMap{
          "on": statemachine.MachineState{
              On: statemachine.TransitionMap{
                  "TOGGLE": statemachine.MachineTransition{
                      To: "off",
                  },
              },
          },
          "off": statemachine.MachineState{
              On: statemachine.TransitionMap{
                  "TOGGLE": statemachine.MachineTransition{
                      To: "on",
                  },
              },
          },
      },
  }
  output := machine.Transition("TOGGLE")
  fmt.Println(output)
  output := machine.Transition("TOGGLE")
  fmt.Println(output)
  output := machine.Transition("TOGGLE")
  fmt.Println(output)
}

We could add some other functionality into our little FSM library like;

我们可以在我们的小FSM库中添加其他功能,例如;

  • External condition for the transition 过渡的外部条件
  • State change listeners etc. 状态更改侦听器等

You can check out; https://github.com/dipeshdulal/statemachine for full code of the machine and some examples present in the repository.

您可以签出; https://github.com/dipeshdulal/statemachine ,其中包含机器的完整代码以及存储库中提供的一些示例。

The state description for the lock-unlock machine presented in the figure above is shown here

上图显示了上锁机器的状态说明