-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpgetcommand.go
102 lines (84 loc) · 2.45 KB
/
tcpgetcommand.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package tcpgetcommand
import (
"context"
"strconv"
"time"
"github.com/Allenxuxu/gev"
"github.com/sirupsen/logrus"
"github.com/telemac/goutils/natsevents"
"github.com/telemac/goutils/natsservice"
)
type TcpGetCommandConfig struct {
ListenPort int `json:"listen_port"`
ListenAddress string `json:"listen_address"`
}
type TcpGetCommandService struct {
natsservice.NatsService
config TcpGetCommandConfig
}
type TcpGetCommandMessage struct {
Data []byte
RemoteAddr string
}
func NewTcpGetCommandService(config TcpGetCommandConfig) *TcpGetCommandService {
return &TcpGetCommandService{config: config}
}
func (svc *TcpGetCommandService) OnConnect(c *gev.Connection) {
svc.Logger().WithFields(logrus.Fields{
"peer_addr": c.PeerAddr(),
"read_buffer_length": c.ReadBufferLength(),
}).Debug("OnConnect")
//c.Set("name", "Alexandre")
}
func (svc *TcpGetCommandService) OnMessage(c *gev.Connection, ctx interface{}, data []byte) (out interface{}) {
// TODO : decode watchcomx message 000042<MESSAGE_TYPE>=WATCHDOG<MODULE>=WATCH_DC09
svc.Logger().WithFields(logrus.Fields{
"data": string(data),
"peer_addr": c.PeerAddr(),
"read_buffer_length": c.ReadBufferLength(),
}).Debug("OnMessage")
eventData := TcpGetCommandMessage{
Data: data,
RemoteAddr: c.PeerAddr(),
}
heartbeatEvent := natsevents.NewEvent("com.plugis.", "tcp-get-command.message", eventData)
topic := heartbeatEvent.Type()
err := svc.Transport().Send(context.TODO(), heartbeatEvent, topic)
if err != nil {
svc.Logger().WithFields(logrus.Fields{
"error": err,
"type": heartbeatEvent.Type(),
"data": string(data),
"peer_addr": c.PeerAddr(),
}).Error("send event")
}
name, ok := c.Get("name")
if ok {
svc.Logger().Println("name", name.(string))
}
// out = []byte("OK\r\n")
return
}
func (svc *TcpGetCommandService) OnClose(c *gev.Connection) {
c.UserBuffer()
svc.Logger().WithFields(logrus.Fields{
"peer_addr": c.PeerAddr(),
}).Debug("OnClose")
}
func (svc *TcpGetCommandService) Run(ctx context.Context, params ...interface{}) error {
log := svc.Logger()
log.Debug("tcp-get-command service started")
defer log.Debug("tcp-get-command service ended")
s, err := gev.NewServer(svc,
gev.Address(svc.config.ListenAddress+":"+strconv.Itoa(svc.config.ListenPort)),
gev.NumLoops(0),
gev.IdleTime(65*time.Second))
if err != nil {
panic(err)
}
go s.Start()
defer s.Stop()
<-ctx.Done()
s.Stop()
return nil
}