summaryrefslogtreecommitdiff
path: root/src/rhctl/telnet.go
blob: e4044efbbee40fb398720ed1c6ef2bbe310cda05 (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
//
//  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 (
	"sort"

	"github.com/spreadspace/telgo"
)

type TelnetInterface struct {
	server *telgo.Server
}

func telnetCmdState(c *telgo.Client, args []string, ctrl *SwitchControl) bool {
	resp := make(chan interface{})
	ctrl.Commands <- &Command{Type: CmdState, Response: resp}

	r := <-resp
	switch r.(type) {
	case error:
		c.Sayln("%v", r)
	case State:
		s := r.(State)
		c.Sayln("Mood: %v", s.Mood)

		c.Sayln("Switch:")
		c.Sayln(" audio:")                     //
		c.Sayln("   output 1: ? (silence!!)?") //
		c.Sayln("   output 2: ? (silence!!)?") // TODO: fill this with actual data
		c.Sayln(" relays: ?")                  //
		c.Sayln(" oc: ?")                      //

		c.Sayln("Server:")
		var names []string
		for n, _ := range s.Server {
			names = append(names, n)
		}
		sort.Strings(names)
		for _, name := range names {
			if name == s.ActiveServer {
				c.Say(" * ")
			} else {
				c.Say("   ")
			}
			c.Sayln("%s(%s): '%s'", name, s.Server[name].Health, s.Server[name].Channel)
		}
	default:
		c.Sayln("invalid response of type %T: %+v", r, r)
	}
	return false
}

func telnetUpdateListener(c *telgo.Client, ctrl *SwitchControl) {
	ch := c.UserData.(chan interface{})
	for {
		data, ok := <-ch
		if !ok {
			return
		}
		switch data.(type) {
		case SwitchUpdate:
			update := data.(SwitchUpdate)
			if !c.Sayln("audio-switch update(%v): %s", update.Type, update.Data) {
				ctrl.Updates.Unsub(ch)
				return
			}
		case ServerState:
			state := data.(ServerState)
			if !c.Sayln("playout-server(%s): health=%s, channel=%s", state.Name, state.Health, state.Channel) {
				ctrl.Updates.Unsub(ch)
				return
			}
		default:
			if !c.Sayln("unknown update of type: %T", data) {
				ctrl.Updates.Unsub(ch)
				return
			}
		}
	}
}

func telnetCmdListen(c *telgo.Client, args []string, ctrl *SwitchControl) bool {
	if len(args) <= 1 {
		c.Sayln("missing argument: <type>")
		return false
	}

	var ch chan interface{}
	if c.UserData == nil {
		ch = ctrl.Updates.Sub()
		c.UserData = ch
	} else {
		ch = c.UserData.(chan interface{})
	}

	switch args[1] {
	case "state":
		ctrl.Updates.AddSub(ch, "state")
	case "server":
		ctrl.Updates.AddSub(ch, "server:state")
	case "switch":
		ctrl.Updates.AddSub(ch, "switch:state")
	case "audio":
		fallthrough
	case "gpi":
		fallthrough
	case "oc":
		fallthrough
	case "relay":
		fallthrough
	case "silence":
		ctrl.Updates.AddSub(ch, "switch:"+args[1])
	default:
		c.Sayln("unknown message type")
		return false
	}
	go telnetUpdateListener(c, ctrl)
	return false
}

func telnetCmdServer(c *telgo.Client, args []string, ctrl *SwitchControl) bool {
	ctrl.Commands <- &Command{Type: CmdServer}
	// TODO: implement this
	return false
}

func telnetCmdSwitch(c *telgo.Client, args []string, ctrl *SwitchControl) bool {
	if len(args) < 2 {
		c.Sayln("missing switch command")
		return false
	}
	resp := make(chan interface{})
	ctrl.Commands <- &Command{Type: CmdSwitch, Args: args[1:], Response: resp}
	r := <-resp
	switch r.(type) {
	case error:
		c.Sayln("%v", r)
	case SwitchResponse:
		if r.(SwitchResponse).Result != SwitchOK {
			c.Sayln("%v: %s", r.(SwitchResponse).Result, r.(SwitchResponse).Message)
		}
	default:
		c.Sayln("invalid response of type %T: %+v", r, r)
	}
	return false
}

func telnetHelp(c *telgo.Client, args []string) bool {
	switch len(args) {
	case 2:
		switch args[1] {
		case "quit":
			c.Sayln("usage: quit")
			c.Sayln("   terminates the client connection. You may also use Ctrl-D to do this.")
			return false
		case "help":
			c.Sayln("usage: help [ <cmd> ]")
			c.Sayln("   prints command overview or detailed info to <cmd>.")
			return false
		case "state":
			c.Sayln("usage: state")
			c.Sayln("   show the state of the switch and servers")
			return false
		case "listen":
			c.Sayln("usage: listen <type>")
			c.Sayln("   subscribe to messages of type <type>. The following types are allowed:")
			c.Sayln("    - state     overall state changes")
			c.Sayln("    - server    state/health of the playout server")
			c.Sayln("    - switch    state/health of switch")
			c.Sayln("    - audio     audio input/output mapping changes")
			c.Sayln("    - gpi       general purpose input state messages")
			c.Sayln("    - oc        open-collector state messages")
			c.Sayln("    - relay     relay state messages")
			c.Sayln("    - silence   state of the silence detector")
			return false
		case "server":
			c.Sayln("usage: server <name>")
			c.Sayln("   switch to the server of name <name>. If the given server name does not")
			c.Sayln("   exist or is dead, the switch-over will be denied")
			return false
		case "switch":
			c.Sayln("usage: switch <cmd> [ [ <arg1> ] ... ]")
			c.Sayln("   send commands to tha audio switch directley.")
			return false
		}
		fallthrough
	default:
		c.Sayln("usage: <cmd> [ [ <arg1> ] ... ]")
		c.Sayln("  available commands:")
		c.Sayln("    quit                             close connection (or use Ctrl-D)")
		c.Sayln("    help [ <cmd> ]                   print this, or help for specific command")
		c.Sayln("    state                            show state of switch and all servers")
		c.Sayln("    listen <type>                    add listener for messages of type <type>")
		c.Sayln("    server <name>                    switch to server <name>")
		c.Sayln("    switch <cmd> [ [ <arg1> ] ... ]  send command to switch")
	}
	return false
}

func telnetQuit(c *telgo.Client, args []string) bool {
	return true
}

func (telnet *TelnetInterface) Run() {
	rhdl.Printf("Telnet: handler running...")
	if err := telnet.server.Run(); err != nil {
		rhl.Printf("Telnet: server returned: %s", err)
	}
}

func TelnetInit(conf *Config, ctrl *SwitchControl) (telnet *TelnetInterface) {
	telnet = &TelnetInterface{}

	cmdlist := make(telgo.CmdList)
	cmdlist["state"] = func(c *telgo.Client, args []string) bool { return telnetCmdState(c, args, ctrl) }
	cmdlist["listen"] = func(c *telgo.Client, args []string) bool { return telnetCmdListen(c, args, ctrl) }
	cmdlist["server"] = func(c *telgo.Client, args []string) bool { return telnetCmdServer(c, args, ctrl) }
	cmdlist["switch"] = func(c *telgo.Client, args []string) bool { return telnetCmdSwitch(c, args, ctrl) }
	cmdlist["help"] = telnetHelp
	cmdlist["quit"] = telnetQuit

	telnet.server = telgo.NewServer(conf.Clients.Telnet.Address, "rhctl> ", cmdlist, nil)

	return
}