Skip to content

Commit 8bc3c8a

Browse files
committed
[refactoring] Remove dependency to refbox in apiServer
1 parent 010a55f commit 8bc3c8a

File tree

4 files changed

+128
-108
lines changed

4 files changed

+128
-108
lines changed

cmd/ssl-game-controller/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@ import (
77

88
func main() {
99

10-
controller.RunRefBox()
10+
controller.RefBox.Run()
1111

1212
// serve the static resource of UI (for production use only)
1313
http.Handle("/", http.FileServer(http.Dir(".")))
1414
// serve the bidirectional web socket
15-
http.HandleFunc("/ws", controller.WsHandler)
15+
http.HandleFunc("/ws", controller.RefBox.ApiServer.WsHandler)
1616
http.ListenAndServe(":8081", nil)
1717
}

internal/app/controller/apiServer.go

Lines changed: 34 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,17 @@ import (
77
"net/http"
88
)
99

10+
type ApiServer struct {
11+
Consumer EventConsumer
12+
connections []*websocket.Conn
13+
}
14+
15+
type EventConsumer interface {
16+
OnNewEvent(event Event)
17+
}
18+
1019
// WsHandler handles incoming web socket connections
11-
func WsHandler(w http.ResponseWriter, r *http.Request) {
20+
func (a *ApiServer) WsHandler(w http.ResponseWriter, r *http.Request) {
1221
u := websocket.Upgrader{
1322
ReadBufferSize: 1024,
1423
WriteBufferSize: 1024,
@@ -20,60 +29,61 @@ func WsHandler(w http.ResponseWriter, r *http.Request) {
2029
log.Println(err)
2130
return
2231
}
23-
defer conn.Close()
24-
defer log.Println("Client disconnected")
32+
defer a.disconnect(conn)
2533

2634
log.Println("Client connected")
2735

28-
go listenForNewEvents(conn)
36+
a.connections = append(a.connections, conn)
2937

30-
publishState(conn)
38+
a.listenForNewEvents(conn)
3139
}
3240

33-
func publishState(conn *websocket.Conn) {
34-
for {
35-
b, err := json.Marshal(refBox.State)
36-
if err != nil {
37-
log.Println("Marshal error:", err)
38-
}
41+
func (a *ApiServer) PublishState(state State) {
42+
b, err := json.Marshal(state)
43+
if err != nil {
44+
log.Println("Marshal error:", err)
45+
}
3946

47+
for _, conn := range a.connections {
4048
err = conn.WriteMessage(websocket.TextMessage, b)
4149
if err != nil {
4250
log.Println("Could not write message.", err)
43-
return
4451
}
52+
}
53+
}
4554

46-
// wait to be notified
47-
<-refBox.notifyUpdateState
55+
func (a *ApiServer) disconnect(conn *websocket.Conn) {
56+
conn.Close()
57+
for i, c := range a.connections {
58+
if c == conn {
59+
a.connections = append(a.connections[:i], a.connections[i+1:]...)
60+
break
61+
}
4862
}
63+
log.Println("Client disconnected")
4964
}
5065

51-
func listenForNewEvents(conn *websocket.Conn) {
66+
func (a *ApiServer) listenForNewEvents(conn *websocket.Conn) {
5267
for {
5368
messageType, b, err := conn.ReadMessage()
5469
if err != nil || messageType != websocket.TextMessage {
5570
log.Println("Could not read message: ", err)
5671
return
5772
}
5873

59-
handleNewEventMessage(b)
74+
a.handleNewEventMessage(b)
6075
}
6176
}
6277

63-
func handleNewEventMessage(b []byte) {
78+
func (a *ApiServer) handleNewEventMessage(b []byte) {
6479
event := Event{}
6580
err := json.Unmarshal(b, &event)
6681
if err != nil {
6782
log.Println("Could not read event:", string(b), err)
6883
return
6984
}
7085

71-
err = processEvent(&event)
72-
if err != nil {
73-
log.Println("Could not process event:", string(b), err)
74-
return
86+
if a.Consumer != nil {
87+
a.Consumer.OnNewEvent(event)
7588
}
76-
77-
refBox.SaveState()
78-
refBox.Update(event.Command)
7989
}

internal/app/controller/engine.go

Lines changed: 39 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -26,44 +26,44 @@ func processEvent(event *Event) error {
2626
func processCommand(c *EventCommand) error {
2727
switch c.Type {
2828
case CommandHalt:
29-
refBox.State.GameState = GameStateHalted
30-
refBox.State.GameStateFor = nil
29+
RefBox.State.GameState = GameStateHalted
30+
RefBox.State.GameStateFor = nil
3131
case CommandStop:
32-
refBox.State.GameState = GameStateStopped
33-
refBox.State.GameStateFor = nil
32+
RefBox.State.GameState = GameStateStopped
33+
RefBox.State.GameStateFor = nil
3434
case CommandForceStart, CommandNormalStart, CommandDirect, CommandIndirect:
35-
refBox.State.GameState = GameStateRunning
36-
refBox.State.GameStateFor = nil
35+
RefBox.State.GameState = GameStateRunning
36+
RefBox.State.GameStateFor = nil
3737
case CommandKickoff:
3838
if c.ForTeam == nil {
3939
return errors.New("Team required for kickoff")
4040
}
41-
refBox.State.GameState = GameStatePreKickoff
42-
refBox.State.GameStateFor = c.ForTeam
41+
RefBox.State.GameState = GameStatePreKickoff
42+
RefBox.State.GameStateFor = c.ForTeam
4343
case CommandPenalty:
4444
if c.ForTeam == nil {
4545
return errors.New("Team required for penalty")
4646
}
47-
refBox.State.GameState = GameStatePrePenalty
48-
refBox.State.GameStateFor = c.ForTeam
47+
RefBox.State.GameState = GameStatePrePenalty
48+
RefBox.State.GameStateFor = c.ForTeam
4949
case CommandBallPlacement:
5050
if c.ForTeam == nil {
5151
return errors.New("Team required for ball placement")
5252
}
53-
refBox.State.GameState = GameStateBallPlacement
54-
refBox.State.GameStateFor = c.ForTeam
53+
RefBox.State.GameState = GameStateBallPlacement
54+
RefBox.State.GameStateFor = c.ForTeam
5555
case CommandGoal:
5656
if c.ForTeam == nil {
5757
return errors.New("Team required for goal")
5858
}
59-
refBox.State.TeamState[*c.ForTeam].Goals++
59+
RefBox.State.TeamState[*c.ForTeam].Goals++
6060
case CommandTimeout:
6161
if c.ForTeam == nil {
6262
return errors.New("Team required for timeout")
6363
}
64-
refBox.State.TeamState[*c.ForTeam].TimeoutsLeft--
65-
refBox.State.GameState = GameStateTimeout
66-
refBox.State.GameStateFor = c.ForTeam
64+
RefBox.State.TeamState[*c.ForTeam].TimeoutsLeft--
65+
RefBox.State.GameState = GameStateTimeout
66+
RefBox.State.GameStateFor = c.ForTeam
6767
default:
6868
return errors.Errorf("Unknown command: %v", c)
6969
}
@@ -76,7 +76,7 @@ func processModify(m *EventModifyValue) error {
7676
if m.ForTeam.Unknown() {
7777
return errors.Errorf("Unknown team: %v", m.ForTeam)
7878
}
79-
teamState := refBox.State.TeamState[m.ForTeam]
79+
teamState := RefBox.State.TeamState[m.ForTeam]
8080
if m.Goals != nil {
8181
teamState.Goals = *m.Goals
8282
} else if m.Goalie != nil {
@@ -91,7 +91,7 @@ func processModify(m *EventModifyValue) error {
9191
teamState.Name = *m.TeamName
9292
} else if m.OnPositiveHalf != nil {
9393
teamState.OnPositiveHalf = *m.OnPositiveHalf
94-
refBox.State.TeamState[m.ForTeam.Opposite()].OnPositiveHalf = !*m.OnPositiveHalf
94+
RefBox.State.TeamState[m.ForTeam.Opposite()].OnPositiveHalf = !*m.OnPositiveHalf
9595
} else if m.YellowCardTime != nil {
9696
cardId := m.YellowCardTime.CardID
9797
if cardId < 0 || cardId >= len(teamState.YellowCardTimes) {
@@ -114,11 +114,11 @@ func processModify(m *EventModifyValue) error {
114114
}
115115

116116
func processStage(s *EventStage) error {
117-
if refBox.State.GameState != GameStateHalted && refBox.State.GameState != GameStateStopped {
117+
if RefBox.State.GameState != GameStateHalted && RefBox.State.GameState != GameStateStopped {
118118
return errors.New("The game state must be halted or stopped to change the stage")
119119
}
120120

121-
index, err := refBox.State.Stage.index()
121+
index, err := RefBox.State.Stage.index()
122122
if err != nil {
123123
return err
124124
}
@@ -127,28 +127,28 @@ func processStage(s *EventStage) error {
127127
if nextIndex >= len(Stages) {
128128
return errors.New("No next stage")
129129
}
130-
refBox.State.Stage = Stages[nextIndex]
130+
RefBox.State.Stage = Stages[nextIndex]
131131
} else if s.StageOperation == StagePrevious {
132132
nextIndex := index - 1
133133
if nextIndex < 0 {
134134
return errors.New("No previous stage")
135135
}
136-
refBox.State.Stage = Stages[nextIndex]
136+
RefBox.State.Stage = Stages[nextIndex]
137137
} else {
138138
return errors.Errorf("Unknown stage operation: %v", s.StageOperation)
139139
}
140140

141-
refBox.State.StageTimeLeft = refBox.StageTimes[refBox.State.Stage]
142-
refBox.State.StageTimeElapsed = 0
141+
RefBox.State.StageTimeLeft = RefBox.StageTimes[RefBox.State.Stage]
142+
RefBox.State.StageTimeElapsed = 0
143143

144-
if refBox.State.Stage == StageFirstHalf {
145-
refBox.MatchTimeStart = time.Now()
144+
if RefBox.State.Stage == StageFirstHalf {
145+
RefBox.MatchTimeStart = time.Now()
146146
}
147-
if refBox.State.Stage == StageOvertimeFirstHalfPre {
148-
refBox.State.TeamState[TeamYellow].TimeoutsLeft = refBox.Config.Overtime.Timeouts
149-
refBox.State.TeamState[TeamYellow].TimeoutTimeLeft = refBox.Config.Overtime.TimeoutDuration
150-
refBox.State.TeamState[TeamBlue].TimeoutsLeft = refBox.Config.Overtime.Timeouts
151-
refBox.State.TeamState[TeamBlue].TimeoutTimeLeft = refBox.Config.Overtime.TimeoutDuration
147+
if RefBox.State.Stage == StageOvertimeFirstHalfPre {
148+
RefBox.State.TeamState[TeamYellow].TimeoutsLeft = RefBox.Config.Overtime.Timeouts
149+
RefBox.State.TeamState[TeamYellow].TimeoutTimeLeft = RefBox.Config.Overtime.TimeoutDuration
150+
RefBox.State.TeamState[TeamBlue].TimeoutsLeft = RefBox.Config.Overtime.Timeouts
151+
RefBox.State.TeamState[TeamBlue].TimeoutTimeLeft = RefBox.Config.Overtime.TimeoutDuration
152152
}
153153

154154
log.Printf("Processed stage %v", s.StageOperation)
@@ -163,7 +163,7 @@ func processCard(card *EventCard) error {
163163
if card.Type != CardTypeYellow && card.Type != CardTypeRed {
164164
return errors.Errorf("Unknown card type: %v", card.Type)
165165
}
166-
teamState := refBox.State.TeamState[card.ForTeam]
166+
teamState := RefBox.State.TeamState[card.ForTeam]
167167
if card.Operation == CardOperationAdd {
168168
return addCard(card, teamState)
169169
} else if card.Operation == CardOperationRevoke {
@@ -190,7 +190,7 @@ func addCard(card *EventCard, teamState *TeamInfo) error {
190190
if card.Type == CardTypeYellow {
191191
log.Printf("Add yellow card for team %v", card.ForTeam)
192192
teamState.YellowCards++
193-
teamState.YellowCardTimes = append(teamState.YellowCardTimes, refBox.Config.Global.YellowCardDuration)
193+
teamState.YellowCardTimes = append(teamState.YellowCardTimes, RefBox.Config.Global.YellowCardDuration)
194194
} else if card.Type == CardTypeRed {
195195
log.Printf("Add red card for team %v", card.ForTeam)
196196
teamState.RedCards++
@@ -200,14 +200,14 @@ func addCard(card *EventCard, teamState *TeamInfo) error {
200200

201201
func processTrigger(t *EventTrigger) error {
202202
if t.Type == TriggerResetMatch {
203-
refBox.State = NewState(refBox.Config)
204-
refBox.MatchTimeStart = time.Unix(0, 0)
203+
RefBox.State = NewState(RefBox.Config)
204+
RefBox.MatchTimeStart = time.Unix(0, 0)
205205
} else if t.Type == TriggerSwitchColor {
206-
yellow := refBox.State.TeamState[TeamYellow]
207-
refBox.State.TeamState[TeamYellow] = refBox.State.TeamState[TeamBlue]
208-
refBox.State.TeamState[TeamBlue] = yellow
206+
yellow := RefBox.State.TeamState[TeamYellow]
207+
RefBox.State.TeamState[TeamYellow] = RefBox.State.TeamState[TeamBlue]
208+
RefBox.State.TeamState[TeamBlue] = yellow
209209
} else if t.Type == TriggerUndo {
210-
refBox.UndoLastAction()
210+
RefBox.UndoLastAction()
211211
} else {
212212
return errors.Errorf("Unknown trigger: %v", t.Type)
213213
}

0 commit comments

Comments
 (0)