You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
2.0 KiB
Go
92 lines
2.0 KiB
Go
package common
|
|
|
|
import (
|
|
"bufio"
|
|
"encoding/binary"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"test/common/tmkind"
|
|
)
|
|
|
|
type TerminalClient struct {
|
|
address string
|
|
conn net.Conn
|
|
netWriter *bufio.Writer
|
|
netReader *bufio.Reader
|
|
GroupConfig []GroupConfig
|
|
|
|
HandlerMap map[uint32]chan any
|
|
|
|
RX chan *TerminalMessageResponse
|
|
}
|
|
|
|
func NewTerminalClient(address string) (tc *TerminalClient) {
|
|
return &TerminalClient{
|
|
address: address,
|
|
RX: make(chan *TerminalMessageResponse),
|
|
}
|
|
}
|
|
func (tc *TerminalClient) Connect() (err error) {
|
|
tc.conn, err = net.Dial("tcp", tc.address)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tc.netWriter = bufio.NewWriter(tc.conn)
|
|
tc.netReader = bufio.NewReader(tc.conn)
|
|
go tc.rxLoop()
|
|
|
|
return nil
|
|
}
|
|
func (tc *TerminalClient) Send(message *TerminalMessage) (err error) {
|
|
_, err = tc.netWriter.Write(message.Encode())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = tc.netWriter.Flush()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
func (tc *TerminalClient) rxLoop() {
|
|
var err error
|
|
for {
|
|
dataHeader := make([]byte, 2) //2 bytes for uint16
|
|
_, err = io.ReadFull(tc.netReader, dataHeader)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
payloadLength := binary.LittleEndian.Uint16(dataHeader)
|
|
fmt.Printf("length: %d bytes\n", payloadLength)
|
|
|
|
kindData := make([]byte, 2) //2 bytes for uint16
|
|
_, err = io.ReadFull(tc.netReader, kindData)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
messageKind := binary.LittleEndian.Uint16(kindData)
|
|
fmt.Printf("kind: %d\n", messageKind)
|
|
|
|
handlerData := make([]byte, 4) //4 bytes for uint32
|
|
_, err = io.ReadFull(tc.netReader, handlerData)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
messageHandler := binary.LittleEndian.Uint32(handlerData)
|
|
fmt.Printf("handler: %d\n", messageHandler)
|
|
|
|
dataPayload := make([]byte, payloadLength-(2+2+4)) //8 bytes for header
|
|
_, err = io.ReadFull(tc.netReader, dataPayload)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
parsedResp, err := NewTerminalMessageResponse(payloadLength, tmkind.TetraFlexTerminalMessageKinds(messageKind), messageHandler, dataPayload)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
tc.RX <- parsedResp
|
|
|
|
}
|
|
}
|