-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransceiver.go
78 lines (63 loc) · 1.52 KB
/
transceiver.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package helvargo
import (
"bufio"
"net"
"time"
"github.com/nuqz/chanfan"
"github.com/nuqz/helvar-go/message"
"github.com/pkg/errors"
)
const KeepAliveDuration = 120 * time.Second
type Transceiver struct {
*chanfan.Transceiver[*message.Message, *message.Message]
conn net.Conn
r *bufio.Reader
}
var terminatorByte = message.Terminator.Byte()
func NewTransceiver(
conn net.Conn,
in <-chan *chanfan.IO[*message.Message, *message.Message],
) *Transceiver {
t := chanfan.NewTransceiver(in)
t.KeepAliveDuration = KeepAliveDuration
t.Terminate = func() error {
if err := conn.Close(); err != nil {
return errors.Wrap(err,
"failed to close transceiver connection properly")
}
return nil
}
return &Transceiver{
Transceiver: t,
conn: conn,
r: bufio.NewReader(conn),
}
}
func (t *Transceiver) transceive(
msg *message.Message,
) (*message.Message, error) {
out := msg.Bytes()
if n, err := t.conn.Write(out); err != nil {
return nil, errors.Wrapf(err,
"failed to sent message: %s", msg)
} else if n != len(out) {
return nil, errors.Wrapf(err,
"message was sent partially: %s", msg)
}
if message.NeedResponse(msg) {
resp, err := t.r.ReadString(terminatorByte)
if err != nil {
return nil, errors.Wrapf(err,
"failed to receive response for: %s", msg)
}
return message.ParsePartial(resp)
}
return nil, nil
}
func (t *Transceiver) Go() <-chan error {
t.KeepAlive = func() error {
_, err := t.transceive(message.NewQueryTime())
return err
}
return t.Transceiver.Go(t.transceive)
}