summaryrefslogtreecommitdiff
path: root/src/rhctl/switch_control.go
blob: 56063f4d76328d854e62154b1190ccd101866775 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//
//  rhctl
//
//  Copyright (C) 2009-2016 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of rhctl.
//
//  rhctl is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  rhctl is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with rhctl. If not, see <http://www.gnu.org/licenses/>.
//

package main

import (
	"errors"
	"fmt"
	"time"

	"github.com/btittelbach/pubsub"
)

type Mood uint

const (
	MoodAwakening Mood = iota
	MoodSad
	MoodNervous
	MoodHappy
)

func (m Mood) String() string {
	switch m {
	case MoodAwakening:
		return "awakening"
	case MoodSad:
		return "sad"
	case MoodNervous:
		return "nervous"
	case MoodHappy:
		return "happy"
	}
	return "unknown"
}

func (m Mood) MarshalText() (data []byte, err error) {
	data = []byte(m.String())
	return
}

type State struct {
	Mood         Mood
	Switch       SwitchState
	ActiveServer string
	Server       map[string]ServerState
	Settled      bool
}

type CommandType uint8

const (
	CmdState CommandType = iota
	CmdServer
	CmdChannel
	CmdSwitch
)

func (c CommandType) String() string {
	switch c {
	case CmdState:
		return "state"
	case CmdServer:
		return "server"
	case CmdChannel:
		return "channel"
	case CmdSwitch:
		return "switch"
	}
	return "unknown"
}

func (c CommandType) MarshalText() (data []byte, err error) {
	data = []byte(c.String())
	return
}

type Command struct {
	Type     CommandType
	Args     []string
	Response chan<- interface{}
}

type SwitchControl struct {
	sw                       *AudioSwitch
	servers                  []*PlayoutServer
	state                    State
	settling                 *time.Timer
	Updates                  *pubsub.PubSub
	Commands                 chan *Command
	AwakeningSettlingTime    time.Duration
	SelectServerSettlingTime time.Duration
	UpdateStatesSettlingTime time.Duration
	StaleStatesCheckInterval time.Duration
	StatesMaxAge             time.Duration
}

func (ctrl *SwitchControl) handleCommand(cmd *Command) {
	switch cmd.Type {
	case CmdState:
		if cmd.Response != nil {
			cmd.Response <- ctrl.state
		}
	case CmdServer:
		if len(cmd.Args) == 0 {
			if cmd.Response != nil {
				cmd.Response <- fmt.Errorf("no server specified")
			}
			return
		}
		result := ctrl.reconcile(cmd.Args[0])
		if cmd.Response != nil {
			cmd.Response <- result
		}
	case CmdChannel:
		if len(cmd.Args) != 2 {
			if cmd.Response != nil {
				cmd.Response <- fmt.Errorf("no server and or channel specified")
			}
			return
		}
		if ctrl.state.Mood == MoodAwakening || ctrl.state.ActiveServer != cmd.Args[0] {
			return
		}
		result := ctrl.selectServerChannel(cmd.Args[0], cmd.Args[1])
		if cmd.Response != nil {
			cmd.Response <- result
		}
	case CmdSwitch:
		if len(cmd.Args) == 0 {
			if cmd.Response != nil {
				cmd.Response <- fmt.Errorf("no command specified")
			}
			return
		}
		c, err := NewSwitchCommandFromStrings(cmd.Args[0], cmd.Args[1:]...)
		if err != nil {
			if cmd.Response != nil {
				cmd.Response <- fmt.Errorf("switch command syntax error: %s", err.Error())
			}
			return
		}
		c.Response = cmd.Response
		ctrl.sw.Commands <- c
	}
}

func handleServer(sin <-chan ServerState, sout chan<- ServerState, cin <-chan Command, cout chan<- *Command) {
	for {
		select {
		case update := <-sin:
			sout <- update
		case cmd := <-cin:
			cout <- &cmd
		}
	}
}

func (ctrl *SwitchControl) checkMissingOrStaleStates(maxAge time.Duration) (isStale bool) {
	if time.Since(ctrl.state.Switch.AudioInputsUpdated) > maxAge {
		ctrl.sw.Commands <- &SwitchCommand{SwitchCmdStateAudio, nil, nil}
		isStale = true
	}
	if time.Since(ctrl.state.Switch.AudioSilenceUpdated) > maxAge {
		ctrl.sw.Commands <- &SwitchCommand{SwitchCmdStateSilence, nil, nil}
		isStale = true
	}
	if time.Since(ctrl.state.Switch.GPIUpdated) > maxAge {
		ctrl.sw.Commands <- &SwitchCommand{SwitchCmdStateGPIAll, nil, nil}
		isStale = true
	}
	if time.Since(ctrl.state.Switch.RelayUpdated) > maxAge {
		ctrl.sw.Commands <- &SwitchCommand{SwitchCmdStateRelay, nil, nil}
		isStale = true
	}
	if time.Since(ctrl.state.Switch.OCUpdated) > maxAge {
		ctrl.sw.Commands <- &SwitchCommand{SwitchCmdStateOC, nil, nil}
		isStale = true
	}

	for _, server := range ctrl.servers {
		s, exists := ctrl.state.Server[server.name]
		if !exists || time.Since(s.Updated) > maxAge {
			server.UpdateRequest <- true
			isStale = true
		}
	}
	return
}

func (ctrl *SwitchControl) getSwitchServerAssignment() (swsrv, swch string, err error) {
	activeInput := SwitchInputNum(0)
	cnt := 0
	for idx, in := range ctrl.state.Switch.Audio[0].Inputs {
		if in {
			activeInput = SwitchInputNum(idx + 1)
			cnt++
		}
	}
	if cnt != 1 || activeInput == SwitchInputNum(0) {
		return "", "", errors.New("no or more than one input is active")
	}

	return ctrl.sw.Inputs.GetServerAndChannel(activeInput)
}

func (ctrl *SwitchControl) selectServerChannel(server, channel string) bool {
	newIn, err := ctrl.sw.Inputs.GetNumber(server, channel)
	if err != nil {
		rhdl.Printf("SwitchCTRL: no audio input configured for server/channel: '%s/%s'", server, channel)
		return false
	}

	for idx, in := range ctrl.state.Switch.Audio[0].Inputs {
		if in && SwitchInputNum(idx+1) != newIn {
			ctrl.sw.Commands <- &SwitchCommand{SwitchCmdAudioFadeDownInput, []interface{}{SwitchInputNum(idx + 1)}, nil}
		}
	}
	ctrl.sw.Commands <- &SwitchCommand{SwitchCmdAudioFadeUpInput, []interface{}{newIn}, nil}
	ctrl.settling.Reset(ctrl.SelectServerSettlingTime)
	ctrl.state.Settled = false
	rhl.Printf("SwitchCTRL: selecting server/channel: '%s/%s'", server, channel)
	return true
}

func (ctrl *SwitchControl) selectServer(server string) bool {
	return ctrl.selectServerChannel(server, ctrl.state.Server[server].Channel)
}

func (ctrl *SwitchControl) checkAndSelectServer(server string) bool {
	if state, exists := ctrl.state.Server[server]; exists {
		if state.Health == ServerAlive && state.Channel != "" {
			return ctrl.selectServer(server)
		}
	}
	return false
}

func (ctrl *SwitchControl) selectNextValidServer() {
	for name, state := range ctrl.state.Server {
		if state.Health == ServerAlive && state.Channel != "" {
			if !ctrl.selectServer(name) {
				continue
			}
			ctrl.state.Mood = MoodNervous
			rhl.Printf("SwitchCTRL: found another valid server '%s' -> now in mood: %s", name, ctrl.state.Mood)
			return
		}
	}
	ctrl.state.Mood = MoodSad
	rhl.Printf("SwitchCTRL: found no alive/valid server -> now in mood: %s", ctrl.state.Mood)
}

func (ctrl *SwitchControl) reconcile(requestedServer string) (result bool) {
	if !ctrl.state.Settled {
		if requestedServer != "" {
			rhl.Printf("SwitchCTRL: ignoreing preferred server requests while settling")
		}
		return
	}
	if len(ctrl.servers) < 1 {
		ctrl.state.Mood = MoodHappy
		rhdl.Printf("SwitchCTRL: there are no servers configured -> now in mood: %s", ctrl.state.Mood)
		return
	}

	if ctrl.state.Mood == MoodAwakening && requestedServer != "" {
		rhl.Printf("SwitchCTRL: ignoreing preferred server requests while waking-up")
		return
	}
	reqSrvSuffix := ""
	if requestedServer != "" {
		reqSrvSuffix = " (requested server: '" + requestedServer + "')"
	}
	rhdl.Printf("SwitchCTRL: reconciling state...%s", reqSrvSuffix)

	swsrv, swch, err := ctrl.getSwitchServerAssignment()
	if err != nil {
		ctrl.state.Mood = MoodSad
		rhl.Printf("SwitchCTRL: switch input assignments are ambigious -> now in mood: %s", ctrl.state.Mood)
		return
	}
	rhl.Printf("SwitchCTRL: switch is set to server/channel: '%s/%s'", swsrv, swch)

	s, exists := ctrl.state.Server[swsrv]
	if !exists || s.Health != ServerAlive || s.Channel == "" {
		rhl.Printf("SwitchCTRL: server '%s' is unknown, dead or has invalid channel!", swsrv)
		if requestedServer != "" {
			if ctrl.checkAndSelectServer(requestedServer) {
				rhl.Printf("SwitchCTRL: switching to requested server '%s' ...", requestedServer)
				return true
			}
			rhl.Printf("SwitchCTRL: requested server '%s' is not selectable, ignoring request", requestedServer)
		}
		ctrl.selectNextValidServer()
		return
	}
	ctrl.state.ActiveServer = swsrv

	if requestedServer != "" {
		if ctrl.state.ActiveServer != requestedServer {
			if ctrl.checkAndSelectServer(requestedServer) {
				rhl.Printf("SwitchCTRL: switching to requested server '%s' ...", requestedServer)
				result = true
			} else {
				rhl.Printf("SwitchCTRL: requested server '%s' is not selectable, ignoring request", requestedServer)
			}
		} else {
			result = true
		}
	} else {
		if s.Channel != swch {
			rhl.Printf("SwitchCTRL: switch and server channel mismatch: '%s' != '%s' -> switching...", swch, s.Channel)
			if !ctrl.selectServer(ctrl.state.ActiveServer) {
				ctrl.selectNextValidServer()
			}
		}
	}

	for _, s := range ctrl.state.Server {
		if s.Health != ServerAlive {
			ctrl.state.Mood = MoodNervous
			rhl.Printf("SwitchCTRL: at least one configured server is dead -> now in mood: %s", ctrl.state.Mood)
			return
		}
	}
	ctrl.state.Mood = MoodHappy
	rhl.Printf("SwitchCTRL: all servers are alive -> now in mood: %s", ctrl.state.Mood)
	return
}

func (ctrl *SwitchControl) Run() {
	rhl.Printf("SwitchCTRL: starting up -> now in mood: %s", ctrl.state.Mood)

	ctrl.settling = time.NewTimer(ctrl.AwakeningSettlingTime)
	ctrl.state.Settled = false

	serverStateChanges := make(chan ServerState, 8)
	for _, srv := range ctrl.servers {
		go handleServer(srv.StateChanges, serverStateChanges, srv.Commands, ctrl.Commands)
	}

	// send out commands to switch and/or server to get missing infos
	ctrl.checkMissingOrStaleStates(0)
	staleTicker := time.NewTicker(ctrl.StaleStatesCheckInterval)

	ctrl.reconcile("")
	for {
		select {
		case <-staleTicker.C:
			if ctrl.state.Settled { // better don't interfere with changes in progress
				if ctrl.checkMissingOrStaleStates(ctrl.StatesMaxAge) {
					rhl.Printf("updateting stale states...")
					ctrl.settling.Reset(ctrl.UpdateStatesSettlingTime)
					ctrl.state.Settled = false
				}
			}
		case <-ctrl.settling.C:
			ctrl.state.Settled = true
			ctrl.reconcile("")
			ctrl.Updates.Pub(ctrl.state, "state")
		case update := <-ctrl.sw.Updates:
			rhdl.Printf("got update from switch: %+v", update)
			for _, srv := range ctrl.servers {
				srv.SwitchUpdates <- update
			}
			ctrl.Updates.Pub(update, "switch:"+update.Type.String())
		case state := <-ctrl.sw.StateChanges:
			// rhdl.Printf("got switch state update: %+v", state)
			ctrl.Updates.Pub(state, "switch:state")
			ctrl.state.Switch = state
			ctrl.reconcile("")
			ctrl.Updates.Pub(ctrl.state, "state")
		case state := <-serverStateChanges:
			rhdl.Printf("got server state update: %+v", state)
			ctrl.Updates.Pub(state, "server:state")
			ctrl.state.Server[state.Name] = state
			ctrl.reconcile("")
			ctrl.Updates.Pub(ctrl.state, "state")
		case cmd := <-ctrl.Commands:
			ctrl.handleCommand(cmd)
		}
	}
}

func SwitchControlInit(conf *Config, sw *AudioSwitch, servers []*PlayoutServer) (ctrl *SwitchControl) {
	ctrl = &SwitchControl{}
	ctrl.sw = sw
	ctrl.servers = servers
	ctrl.state.Mood = MoodAwakening
	ctrl.state.Server = make(map[string]ServerState)
	ctrl.Updates = pubsub.NewNonBlocking(32)
	ctrl.Commands = make(chan *Command, 8)

	ctrl.AwakeningSettlingTime = 30 * time.Second
	if conf.Timing.Settling.Awakening.Duration > time.Duration(0) {
		ctrl.AwakeningSettlingTime = conf.Timing.Settling.Awakening.Duration
	}

	ctrl.SelectServerSettlingTime = 10 * time.Second
	if conf.Timing.Settling.SelectServer.Duration > time.Duration(0) {
		ctrl.SelectServerSettlingTime = conf.Timing.Settling.SelectServer.Duration
	}

	ctrl.UpdateStatesSettlingTime = 3 * time.Second
	if conf.Timing.Settling.UpdateStates.Duration > time.Duration(0) {
		ctrl.UpdateStatesSettlingTime = conf.Timing.Settling.UpdateStates.Duration
	}

	ctrl.StaleStatesCheckInterval = 1 * time.Minute
	if conf.Timing.StaleStates.CheckInterval.Duration > time.Duration(0) {
		ctrl.StaleStatesCheckInterval = conf.Timing.StaleStates.CheckInterval.Duration
	}

	ctrl.StatesMaxAge = 2 * time.Hour
	if conf.Timing.StaleStates.MaxAge.Duration > time.Duration(0) {
		ctrl.StatesMaxAge = conf.Timing.StaleStates.MaxAge.Duration
	}

	return
}