-
Notifications
You must be signed in to change notification settings - Fork 1
/
component.go
91 lines (81 loc) · 2.03 KB
/
component.go
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package gosm
import (
"time"
)
const receiveTimeout time.Duration = time.Millisecond * 100
type Component struct {
ports *portMultiplexer
stateCharts []State
timer *time.Timer
active bool
stopped bool
Runtime *Runtime
}
func (c *Component) loop() {
// The actual event loop that handles incoming messages
for sc := range c.stateCharts {
c.stateCharts[sc].OnEntry()
}
for {
// The activity flag indicates if anything has happened since the last receive timeout
active := false
// Process empty events until nothing happens
handled := true
for handled {
handled = false
for sc := range c.stateCharts {
scHandled, _, _, action := c.stateCharts[sc].Handle(0, nil)
if scHandled && action != nil {
action()
}
handled = handled || scHandled
active = active || scHandled
}
}
// Handle incoming messages
c.timer.Reset(receiveTimeout)
p, m := c.ports.receive(c, c.timer)
for sc := range c.stateCharts {
scHandled, _, _, action := c.stateCharts[sc].Handle(p, m)
if scHandled && action != nil {
action()
}
active = active || scHandled
}
c.active = active
// Check if we have been stopped
if c.stopped {
break
}
}
for sc := range c.stateCharts {
c.stateCharts[sc].OnExit()
}
c.active = false
c.Runtime.wg.Done()
}
func MakeComponent(portsBufferLen int, stateCharts ...State) *Component {
component := &Component{
stateCharts: stateCharts,
timer: time.NewTimer(receiveTimeout),
stopped: false,
active: true,
}
component.ports = newPortMultiplexer(portsBufferLen, component)
return component
}
func (c *Component) Send(port Port, message interface{}) {
c.ports.send(port, message)
}
func (c *Component) Stop() {
c.stopped = true
}
func (c *Component) Active() bool {
return c.active || len(c.ports.In) > 0
}
func Connector(client, server *Component, required, provided Port) {
portConnector(client.ports, server.ports, required, provided)
}
func InternalPort(client *Component, port Port) {
portInternal(client.ports, port)
}