diff options
Diffstat (limited to 'src/state.go')
-rw-r--r-- | src/state.go | 54 |
1 files changed, 53 insertions, 1 deletions
diff --git a/src/state.go b/src/state.go index 9c6ab66..9a08738 100644 --- a/src/state.go +++ b/src/state.go @@ -13,6 +13,7 @@ type Machine struct { current string states StateMap api chan string + state_listeners []*(chan string) } type StateMap map[string]MachineState @@ -34,6 +35,49 @@ func (m Machine) GetState() string { return m.current } +func (m *Machine) GetStateOnChange(known string) string { + listener := make(chan string) + var current string + m.RegisterListener(&listener) + for { + if m.GetState() != known { + current = m.GetState() + break + } + current = <-listener + if current != known { + break + } + } + m.DeregisterListener(&listener) + return current +} + +func (m *Machine) RegisterListener(listener *(chan string)) { + m.state_listeners = append(m.state_listeners, listener) +} + +func (m *Machine) DeregisterListener(listener *(chan string)) { + wasRemoved := false + if len(m.state_listeners) == 0 { + log.Println("Not able to unregister listener from empty state_listener slice") + } + for index,item := range(m.state_listeners) { + if item == listener { + if index == len(m.state_listeners) - 1 { + m.state_listeners = m.state_listeners[: len(m.state_listeners) - 1] + } else { + m.state_listeners[index] = m.state_listeners[len(m.state_listeners) - 1] + m.state_listeners = m.state_listeners[: len(m.state_listeners) - 1] + } + wasRemoved = true + } + } + if !wasRemoved { + log.Println("Could not find listener in slice state_listeners") + } +} + func (m *Machine) processEvent(event string) string { current := m.GetState() next := m.states[current].on[event].to @@ -59,7 +103,14 @@ func (m *Machine) run() { } func (m *Machine) runHooks(last string, next string) { - if next == "single_picture" { + + log.Println("Send state to listeners ...") + for _,listener := range(m.state_listeners) { + *listener <- next + } + log.Println("State sent to listeners") + + if last == "idle" && next == "single_picture" { // TODO implement launch of python subprocess here go func() { time.Sleep(1 * time.Second) @@ -89,6 +140,7 @@ func newCamStateMachine() Machine { }, }, api: make(chan string), + state_listeners: make([]*(chan string), 0), } } |