forked from lorenzodonini/ocpp-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallbackqueue.go
62 lines (47 loc) · 1.26 KB
/
callbackqueue.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package callbackqueue
import (
"sync"
"github.com/lorenzodonini/ocpp-go/ocpp"
)
type CallbackQueue struct {
callbacksMutex sync.RWMutex
callbacks map[string][]func(confirmation ocpp.Response, err error)
}
func New() CallbackQueue {
return CallbackQueue{
callbacks: make(map[string][]func(confirmation ocpp.Response, err error)),
}
}
func (cq *CallbackQueue) TryQueue(id string, try func() error, callback func(confirmation ocpp.Response, err error)) error {
cq.callbacksMutex.Lock()
defer cq.callbacksMutex.Unlock()
cq.callbacks[id] = append(cq.callbacks[id], callback)
if err := try(); err != nil {
// pop off last element
callbacks := cq.callbacks[id]
cq.callbacks[id] = callbacks[:len(callbacks)-1]
if len(cq.callbacks[id]) == 0 {
delete(cq.callbacks, id)
}
return err
}
return nil
}
func (cq *CallbackQueue) Dequeue(id string) (func(confirmation ocpp.Response, err error), bool) {
cq.callbacksMutex.Lock()
defer cq.callbacksMutex.Unlock()
callbacks, ok := cq.callbacks[id]
if !ok {
return nil, false
}
if len(callbacks) == 0 {
panic("Internal CallbackQueue inconsistency")
}
callback := callbacks[0]
if len(callbacks) == 1 {
delete(cq.callbacks, id)
} else {
cq.callbacks[id] = callbacks[1:]
}
return callback, ok
}