aboutsummaryrefslogtreecommitdiff
path: root/fsm.go
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2017-09-03 00:54:03 +0200
committerDimitri Sokolyuk <demon@dim13.org>2017-09-03 00:54:03 +0200
commit528d38d82ff62aaa282812ae8b7a9fcc30691213 (patch)
tree2b7cf33df29aa80b2a4811b9a0f0603e4058f64f /fsm.go
parent3ee2c48a1d5599c4e6754636d1755b1e1e897301 (diff)
Add fsm
Diffstat (limited to 'fsm.go')
-rw-r--r--fsm.go57
1 files changed, 57 insertions, 0 deletions
diff --git a/fsm.go b/fsm.go
new file mode 100644
index 0000000..772a73d
--- /dev/null
+++ b/fsm.go
@@ -0,0 +1,57 @@
+package main
+
+import (
+ "bufio"
+ "io"
+ "log"
+)
+
+type stateFn func() stateFn
+
+type FSM struct {
+ events chan *Events
+ command chan *Command
+}
+
+func NewFSM(rw io.ReadWriter) *FSM {
+ events := make(chan *Events)
+ command := make(chan *Command)
+ go readEvents(rw, events)
+ go writeCommands(rw, command)
+ return &FSM{events: events, command: command}
+}
+
+func readEvents(r io.Reader, ch chan<- *Events) {
+ buf := bufio.NewReader(r)
+ for {
+ event := new(Events)
+ if err := Recv(buf, event); err != nil {
+ if err == io.ErrUnexpectedEOF {
+ continue
+ }
+ log.Println(err)
+ continue
+ }
+ ch <- event
+ }
+}
+
+func writeCommands(w io.Writer, ch <-chan *Command) {
+ for command := range ch {
+ if err := Send(w, command); err != nil {
+ if err == io.ErrUnexpectedEOF {
+ continue
+ }
+ log.Println(err)
+ }
+ }
+}
+
+func (f *FSM) Start() {
+ for state := f.initalState; state != nil; state = state() {
+ }
+}
+
+func (f *FSM) initalState() stateFn {
+ return nil
+}