Add arena status websocket API for clients that need realtime match signaling.

This commit is contained in:
Patrick Fairbank
2019-08-23 22:03:07 -07:00
parent 33378fe3eb
commit 6926aa42ad
4 changed files with 38 additions and 1 deletions

View File

@@ -9,6 +9,7 @@ import (
"encoding/json"
"github.com/Team254/cheesy-arena/game"
"github.com/Team254/cheesy-arena/model"
"github.com/Team254/cheesy-arena/websocket"
"github.com/gorilla/mux"
"net/http"
)
@@ -176,3 +177,20 @@ func (web *Web) alliancesApiHandler(w http.ResponseWriter, r *http.Request) {
return
}
}
// Websocket API for receiving arena status updates.
func (web *Web) arenaWebsocketApiHandler(w http.ResponseWriter, r *http.Request) {
if !web.userIsAdmin(w, r) {
return
}
ws, err := websocket.NewWebsocket(w, r)
if err != nil {
handleWebErr(w, err)
return
}
defer ws.Close()
// Subscribe the websocket to the notifiers whose messages will be passed on to the client.
ws.HandleNotifiers(web.arena.MatchTimingNotifier, web.arena.MatchLoadNotifier, web.arena.MatchTimeNotifier)
}

View File

@@ -7,6 +7,8 @@ import (
"encoding/json"
"github.com/Team254/cheesy-arena/game"
"github.com/Team254/cheesy-arena/model"
"github.com/Team254/cheesy-arena/websocket"
gorillawebsocket "github.com/gorilla/websocket"
"github.com/stretchr/testify/assert"
"testing"
"time"
@@ -123,3 +125,19 @@ func TestAlliancesApi(t *testing.T) {
}
}
}
func TestArenaWebsocketApi(t *testing.T) {
web := setupTestWeb(t)
server, wsUrl := web.startTestServer()
defer server.Close()
conn, _, err := gorillawebsocket.DefaultDialer.Dial(wsUrl+"/api/arena/websocket", nil)
assert.Nil(t, err)
defer conn.Close()
ws := websocket.NewTestWebsocket(conn)
// Should get a few status updates right after connection.
readWebsocketType(t, ws, "matchTiming")
readWebsocketType(t, ws, "matchLoad")
readWebsocketType(t, ws, "matchTime")
}

View File

@@ -49,6 +49,6 @@ func (web *Web) ledPlcWebsocketHandler(w http.ResponseWriter, r *http.Request) {
}
defer ws.Close()
// Subscribe the websocket to the notifiers whose messages will be passed on to the client, in a separate goroutine.
// Subscribe the websocket to the notifiers whose messages will be passed on to the client.
ws.HandleNotifiers(web.arena.Plc.IoChangeNotifier)
}

View File

@@ -102,6 +102,7 @@ func (web *Web) newHandler() http.Handler {
router.HandleFunc("/alliance_selection/reset", web.allianceSelectionResetHandler).Methods("POST")
router.HandleFunc("/alliance_selection/start", web.allianceSelectionStartHandler).Methods("POST")
router.HandleFunc("/api/alliances", web.alliancesApiHandler).Methods("GET")
router.HandleFunc("/api/arena/websocket", web.arenaWebsocketApiHandler).Methods("GET")
router.HandleFunc("/api/matches/{type}", web.matchesApiHandler).Methods("GET")
router.HandleFunc("/api/rankings", web.rankingsApiHandler).Methods("GET")
router.HandleFunc("/api/sponsor_slides", web.sponsorSlidesApiHandler).Methods("GET")