Event handing improvements.

Corrected the Event struct to match it's new state based on Discord docs
and started tracking sequence number and sending it with heatbeats.
Also, move cleanup and comment improvements.
This commit is contained in:
Bruce Marriner 2016-04-28 16:59:45 -05:00
parent 2ac4665a4e
commit 94770635a9
3 changed files with 18 additions and 14 deletions

View file

@ -94,12 +94,6 @@ func (v *VoiceConnection) log(msgL int, format string, a ...interface{}) {
msglog(msgL, 2, format, a...)
}
// printEvent prints out a WSAPI event.
func printEvent(e *Event) {
log.Println(fmt.Sprintf("Event. Type: %s, State: %d Operation: %d Direction: %d", e.Type, e.State, e.Operation, e.Direction))
printJSON(e.RawData)
}
// printJSON is a helper function to display JSON data in a easy to read format.
func printJSON(body []byte) {
var prettyJSON bytes.Buffer

View file

@ -80,6 +80,9 @@ type Session struct {
// may switch to slices later
// TODO: performance test map vs slices
rateLimit rateLimitMutex
// sequence tracks the current gateway api websocket sequence number
sequence int
}
type rateLimitMutex struct {
@ -284,10 +287,9 @@ type FriendSourceFlags struct {
// An Event provides a basic initial struct for all websocket event.
type Event struct {
Type string `json:"t"`
State int `json:"s"`
Operation int `json:"op"`
Direction int `json:"dir"`
Sequence int `json:"s"`
Type string `json:"t"`
RawData json.RawMessage `json:"d"`
Struct interface{} `json:"-"`
}

View file

@ -196,7 +196,7 @@ func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}
var err error
ticker := time.NewTicker(i * time.Millisecond)
for {
err = wsConn.WriteJSON(heartbeatOp{1, int(time.Now().Unix())})
err = wsConn.WriteJSON(heartbeatOp{1, s.sequence})
if err != nil {
log.Println("Error sending heartbeat:", err)
return
@ -291,10 +291,19 @@ func (s *Session) onEvent(messageType int, message []byte) {
return
}
if s.Debug { // TODO: refactor using s.log()
printEvent(e)
if s.Debug {
s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
}
// Do not try to Dispatch a non-Dispatch Message
if e.Operation != 0 {
// But we probably should be doing something with them.
return
}
// Store the message sequence
s.sequence = e.Sequence
// Map event to registered event handlers and pass it along
// to any registered functions
i := eventToInterface[e.Type]
@ -318,8 +327,7 @@ func (s *Session) onEvent(messageType int, message []byte) {
s.handle(i)
} else {
s.log(LogWarning, "unknown event type %s", e.Type)
printEvent(e)
s.log(LogWarning, "unknown event, %#v", e)
}
// Emit event to the OnEvent handler