aboutsummaryrefslogtreecommitdiff
path: root/fsm.go
blob: 3e3cb6ee65b0ee9d3f1536a8d80521286ea108ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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 {
	f.command <- &Command{Direction: 90}
	return f.readDistance
}

func (f *FSM) readDistance() stateFn {
	ev := <-f.events
	log.Println(ev)
	if ev.Distance < 20 {
		return f.stop
	}
	return f.moveAhead
}

func (f *FSM) moveAhead() stateFn {
	f.command <- &Command{SpeedL: 200, SpeedR: 200}
	return f.readDistance
}

func (f *FSM) stop() stateFn {
	f.command <- &Command{Stop: true}
	return f.readDistance
}