summaryrefslogtreecommitdiff
path: root/cmd
diff options
context:
space:
mode:
Diffstat (limited to 'cmd')
-rw-r--r--cmd/dolmetschctl/dolmetschctl.go61
1 files changed, 55 insertions, 6 deletions
diff --git a/cmd/dolmetschctl/dolmetschctl.go b/cmd/dolmetschctl/dolmetschctl.go
index 1d8c6ad..fb8cdf3 100644
--- a/cmd/dolmetschctl/dolmetschctl.go
+++ b/cmd/dolmetschctl/dolmetschctl.go
@@ -23,23 +23,73 @@
package main
import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
"log"
"os"
"time"
"github.com/gorilla/websocket"
"spreadspace.org/dolmetschctl/pkg/controller"
- // "spreadspace.org/dolmetschctl/pkg/types"
+ "spreadspace.org/dolmetschctl/pkg/types"
)
-func run(c *controller.Controller, ws *websocket.Conn) error {
- ch := make(chan controller.Event, 100)
- c.Subscribe(ch)
+func wsReader(ws *websocket.Conn, ch chan<- types.WebSocketResponseFull) {
+ defer close(ch)
+
+ for {
+ t, r, err := ws.NextReader()
+ if err != nil {
+ log.Println("websocket disconnected:", err)
+ return
+ }
+
+ switch t {
+ case websocket.TextMessage:
+ var msg types.WebSocketResponseFull
+ dec := json.NewDecoder(r)
+ dec.DisallowUnknownFields()
+ if err := dec.Decode(&msg); err != nil {
+ if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ }
+ log.Println("webclient response parse error:", err)
+ return
+ }
+
+ ch <- msg
+ case websocket.BinaryMessage:
+ io.Copy(ioutil.Discard, r) // consume all the data
+ }
+ }
+ return
+}
+
+func run(ctrl *controller.Controller, ws *websocket.Conn) error {
+ ctrlCh := make(chan controller.Event, 100)
+ ctrl.Subscribe(ctrlCh)
+
+ wsCh := make(chan types.WebSocketResponseFull)
+ go wsReader(ws, wsCh)
+
+ if err := ws.WriteJSON(types.WebSocketRequest{Command: "subscribe"}); err != nil {
+ return err
+ }
for {
select {
- case ev := <-ch:
+ case ev, ok := <-ctrlCh:
+ if !ok {
+ return fmt.Errorf("controller channel was closed.")
+ }
log.Printf("got controller event: %v", ev)
+ case msg, ok := <-wsCh:
+ if !ok {
+ return fmt.Errorf("websocket channel was closed.")
+ }
+ log.Printf("got message from websocket: %v", msg)
}
}
return nil
@@ -66,7 +116,6 @@ func main() {
if err != nil {
log.Printf("Error connecting to daemon: %v", err)
} else {
-
err := run(c, ws)
log.Printf("run() returned: %v", err)
}