aboutsummaryrefslogtreecommitdiff
path: root/fsm.go
blob: 768e566b82b28b964d35f6da38cb81d1d3b503fd (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
package elegoo

import (
	"io"
	"log"
)

type stateFn func() stateFn

type FSM struct {
	events   chan *Event
	commands chan *Command
}

func NewFSM(rw io.ReadWriter) *FSM {
	events := make(chan *Event)
	commands := make(chan *Command)
	comm := NewComm(rw)
	go readEvents(comm, events)
	go writeCommands(comm, commands)
	return &FSM{events: events, commands: commands}
}

func readEvents(c ProtoComm, ch chan<- *Event) {
	for {
		event := new(Event)
		if err := c.Recv(event); err != nil {
			if err == io.ErrUnexpectedEOF {
				continue
			}
			log.Println(err)
			continue
		}
		ch <- event
	}
}

func writeCommands(c ProtoComm, ch <-chan *Command) {
	for command := range ch {
		if err := c.Send(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.commands <- &Command{Look: 0}
	return f.readDistance
}

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

func (f *FSM) moveAhead() stateFn {
	f.commands <- &Command{Speed: &Speed{L: 200, R: 200}}
	return f.readDistance
}

func (f *FSM) stop() stateFn {
	f.commands <- &Command{}
	return f.readDistance
}