forked from tarm/can
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wait.go
51 lines (42 loc) · 962 Bytes
/
wait.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
package can
import (
"fmt"
"time"
)
// A WaitResponse encapsulates the response of waiting for a frame.
type WaitResponse struct {
Frame Frame
Err error
}
type waiter struct {
id uint32
wait chan WaitResponse
bus *Bus
filter Handler
}
// Wait returns a channel, which receives a frame or an error, if the
// frame with the expected id didn't arrive on time.
func Wait(bus *Bus, id uint32, timeout time.Duration) <-chan WaitResponse {
waiter := waiter{
id: id,
wait: make(chan WaitResponse),
bus: bus,
}
ch := make(chan WaitResponse)
go func() {
select {
case resp := <-waiter.wait:
ch <- resp
case <-time.After(timeout):
err := fmt.Errorf("Timeout error waiting for %X", id)
ch <- WaitResponse{Frame{}, err}
}
}()
waiter.filter = newFilter(id, &waiter)
bus.Subscribe(waiter.filter)
return ch
}
func (w *waiter) Handle(frame Frame) {
w.bus.Unsubscribe(w.filter)
w.wait <- WaitResponse{frame, nil}
}