2018-05-21 23:00:36 -04:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/golang/protobuf/proto"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2018-05-23 14:53:41 -04:00
|
|
|
type Timer struct {
|
|
|
|
Id int32
|
|
|
|
Done bool
|
|
|
|
Cleared bool
|
|
|
|
Interval bool
|
|
|
|
Duration int32 // In milliseconds
|
|
|
|
}
|
|
|
|
|
|
|
|
var timers = make(map[int32]*Timer)
|
|
|
|
|
2018-05-21 23:00:36 -04:00
|
|
|
func InitTimers() {
|
|
|
|
Sub("timers", func(buf []byte) []byte {
|
|
|
|
msg := &Msg{}
|
|
|
|
check(proto.Unmarshal(buf, msg))
|
|
|
|
switch msg.Payload.(type) {
|
|
|
|
case *Msg_TimerStart:
|
|
|
|
payload := msg.GetTimerStart()
|
2018-05-23 14:53:41 -04:00
|
|
|
timers[*payload.Id] = &Timer{
|
|
|
|
Id: *payload.Id,
|
|
|
|
Done: false,
|
|
|
|
Interval: *payload.Interval,
|
|
|
|
Duration: *payload.Duration,
|
|
|
|
Cleared: false,
|
|
|
|
}
|
|
|
|
timers[*payload.Id].StartTimer()
|
|
|
|
return nil
|
|
|
|
case *Msg_TimerClear:
|
|
|
|
payload := msg.GetTimerClear()
|
|
|
|
// TODO maybe need mutex here.
|
|
|
|
timer := timers[*payload.Id]
|
|
|
|
timer.Clear()
|
|
|
|
return nil
|
2018-05-21 23:00:36 -04:00
|
|
|
default:
|
|
|
|
panic("[timers] Unexpected message " + string(buf))
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-05-23 14:53:41 -04:00
|
|
|
func (t *Timer) Clear() {
|
|
|
|
if !t.Cleared {
|
|
|
|
wg.Done()
|
|
|
|
t.Cleared = true
|
|
|
|
delete(timers, t.Id)
|
|
|
|
}
|
|
|
|
t.Done = true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Timer) StartTimer() {
|
2018-05-21 23:00:36 -04:00
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
2018-05-23 14:53:41 -04:00
|
|
|
defer t.Clear()
|
|
|
|
for {
|
|
|
|
time.Sleep(time.Duration(t.Duration) * time.Millisecond)
|
|
|
|
if !t.Interval {
|
|
|
|
t.Done = true
|
|
|
|
}
|
2018-05-23 17:23:50 -04:00
|
|
|
PubMsg("timers", &Msg{
|
2018-05-23 14:53:41 -04:00
|
|
|
Payload: &Msg_TimerReady{
|
|
|
|
TimerReady: &TimerReadyMsg{
|
|
|
|
Id: &t.Id,
|
|
|
|
Done: &t.Done,
|
|
|
|
},
|
2018-05-21 23:00:36 -04:00
|
|
|
},
|
2018-05-23 14:53:41 -04:00
|
|
|
})
|
|
|
|
if t.Done {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2018-05-21 23:00:36 -04:00
|
|
|
}()
|
2018-05-23 14:53:41 -04:00
|
|
|
}
|