Implements Gateway for car controls
This commit is contained in:
@@ -17,28 +17,31 @@ import (
|
||||
)
|
||||
|
||||
func New(publisher Publisher, addressSimulator string) *Gateway {
|
||||
log.Info("run camera camera")
|
||||
l := log.WithField("simulator", addressSimulator)
|
||||
l.Info("run camera from simulator")
|
||||
|
||||
return &Gateway{
|
||||
address: addressSimulator,
|
||||
publisher: publisher,
|
||||
address: addressSimulator,
|
||||
publisher: publisher,
|
||||
log: l,
|
||||
}
|
||||
}
|
||||
|
||||
/* Simulator interface to publish camera frames into mqtt topic */
|
||||
type Gateway struct {
|
||||
cancel chan interface{}
|
||||
cancel chan interface{}
|
||||
|
||||
address string
|
||||
conn io.ReadCloser
|
||||
|
||||
publisher Publisher
|
||||
log *log.Entry
|
||||
}
|
||||
|
||||
func (p *Gateway) Start() error {
|
||||
log.Info("connect to simulator")
|
||||
p.log.Info("connect to simulator")
|
||||
p.cancel = make(chan interface{})
|
||||
msgChan := make(chan *simulator.SimulatorMsg)
|
||||
msgChan := make(chan *simulator.TelemetryMsg)
|
||||
|
||||
go p.run(msgChan)
|
||||
|
||||
@@ -53,17 +56,17 @@ func (p *Gateway) Start() error {
|
||||
}
|
||||
|
||||
func (p *Gateway) Stop() {
|
||||
log.Info("close simulator gateway")
|
||||
p.log.Info("close simulator gateway")
|
||||
close(p.cancel)
|
||||
|
||||
if err := p.Close(); err != nil {
|
||||
log.Printf("unexpected error while simulator connection is closed: %v", err)
|
||||
p.log.Warnf("unexpected error while simulator connection is closed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Gateway) Close() error {
|
||||
if p.conn == nil {
|
||||
log.Warnln("no connection to close")
|
||||
p.log.Warn("no connection to close")
|
||||
return nil
|
||||
}
|
||||
if err := p.conn.Close(); err != nil {
|
||||
@@ -72,19 +75,21 @@ func (p *Gateway) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Gateway) run(msgChan chan<- *simulator.SimulatorMsg) {
|
||||
func (p *Gateway) run(msgChan chan<- *simulator.TelemetryMsg) {
|
||||
err := retry.Do(func() error {
|
||||
p.log.Info("connect to simulator")
|
||||
conn, err := connect(p.address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to connect to simulator at %v", p.address)
|
||||
}
|
||||
p.conn = conn
|
||||
p.log.Info("connection success")
|
||||
return nil
|
||||
},
|
||||
retry.Delay(1*time.Second),
|
||||
)
|
||||
if err != nil {
|
||||
log.Panicf("unable to connect to simulator: %v", err)
|
||||
p.log.Panicf("unable to connect to simulator: %v", err)
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(p.conn)
|
||||
@@ -93,25 +98,25 @@ func (p *Gateway) run(msgChan chan<- *simulator.SimulatorMsg) {
|
||||
func() error { return p.listen(msgChan, reader) },
|
||||
)
|
||||
if err != nil {
|
||||
log.Errorf("unable to connect to server: %v", err)
|
||||
p.log.Errorf("unable to connect to server: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Gateway) listen(msgChan chan<- *simulator.SimulatorMsg, reader *bufio.Reader) error {
|
||||
func (p *Gateway) listen(msgChan chan<- *simulator.TelemetryMsg, reader *bufio.Reader) error {
|
||||
for {
|
||||
rawLine, err := reader.ReadBytes('\n')
|
||||
if err == io.EOF {
|
||||
log.Info("Connection closed")
|
||||
p.log.Info("Connection closed")
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to read response: %v", err)
|
||||
}
|
||||
|
||||
var msg simulator.SimulatorMsg
|
||||
var msg simulator.TelemetryMsg
|
||||
err = json.Unmarshal(rawLine, &msg)
|
||||
if err != nil {
|
||||
log.Errorf("unable to unmarshal simulator msg: %v", err)
|
||||
p.log.Errorf("unable to unmarshal simulator msg: %v", err)
|
||||
}
|
||||
if "telemetry" != msg.MsgType {
|
||||
continue
|
||||
@@ -120,7 +125,7 @@ func (p *Gateway) listen(msgChan chan<- *simulator.SimulatorMsg, reader *bufio.R
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Gateway) publishFrame(msgSim *simulator.SimulatorMsg) {
|
||||
func (p *Gateway) publishFrame(msgSim *simulator.TelemetryMsg) {
|
||||
now := time.Now()
|
||||
msg := &events.FrameMessage{
|
||||
Id: &events.FrameRef{
|
||||
@@ -136,9 +141,9 @@ func (p *Gateway) publishFrame(msgSim *simulator.SimulatorMsg) {
|
||||
|
||||
payload, err := proto.Marshal(msg)
|
||||
if err != nil {
|
||||
log.Errorf("unable to marshal protobuf message: %v", err)
|
||||
p.log.Errorf("unable to marshal protobuf message: %v", err)
|
||||
}
|
||||
p.publisher.Publish(&payload)
|
||||
p.publisher.Publish(payload)
|
||||
}
|
||||
|
||||
var connect = func(address string) (io.ReadWriteCloser, error) {
|
||||
@@ -150,23 +155,23 @@ var connect = func(address string) (io.ReadWriteCloser, error) {
|
||||
}
|
||||
|
||||
type Publisher interface {
|
||||
Publish(payload *[]byte)
|
||||
Publish(payload []byte)
|
||||
}
|
||||
|
||||
func NewMqttPublisher(client mqtt.Client, topic string) Publisher {
|
||||
return &MqttPublisher{
|
||||
client: client,
|
||||
topic: topic,
|
||||
topic: topic,
|
||||
}
|
||||
}
|
||||
|
||||
type MqttPublisher struct {
|
||||
client mqtt.Client
|
||||
topic string
|
||||
topic string
|
||||
}
|
||||
|
||||
func (m *MqttPublisher) Publish(payload *[]byte) {
|
||||
token := m.client.Publish(m.topic, 0, false, *payload)
|
||||
func (m *MqttPublisher) Publish(payload []byte) {
|
||||
token := m.client.Publish(m.topic, 0, false, payload)
|
||||
token.WaitTimeout(10 * time.Millisecond)
|
||||
if err := token.Error(); err != nil {
|
||||
log.Errorf("unable to publish frame: %v", err)
|
||||
|
@@ -12,44 +12,44 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type MockPublisher struct {
|
||||
muPubEvents sync.Mutex
|
||||
publishedEvents []*[]byte
|
||||
notifyChan chan []byte
|
||||
initNotifyChan sync.Once
|
||||
}
|
||||
|
||||
func (p *MockPublisher) Publish(payload *[]byte) {
|
||||
p.muPubEvents.Lock()
|
||||
defer p.muPubEvents.Unlock()
|
||||
p.publishedEvents = append(p.publishedEvents, payload)
|
||||
func (p *MockPublisher) Close() error {
|
||||
if p.notifyChan != nil {
|
||||
close(p.notifyChan)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *MockPublisher) Events() []*[]byte {
|
||||
p.muPubEvents.Lock()
|
||||
defer p.muPubEvents.Unlock()
|
||||
eventsMsg := make([]*[]byte, len(p.publishedEvents), len(p.publishedEvents))
|
||||
copy(eventsMsg, p.publishedEvents)
|
||||
return eventsMsg
|
||||
func (p *MockPublisher) Publish(payload []byte) {
|
||||
p.notifyChan <- payload
|
||||
}
|
||||
|
||||
func (p *MockPublisher) Notify() <-chan []byte {
|
||||
p.initNotifyChan.Do(func() { p.notifyChan = make(chan []byte) })
|
||||
return p.notifyChan
|
||||
}
|
||||
|
||||
func TestPart_ListenEvents(t *testing.T) {
|
||||
connMock := ConnMock{}
|
||||
err := connMock.Listen()
|
||||
simulatorMock := SimulatorMock{}
|
||||
err := simulatorMock.Start()
|
||||
if err != nil {
|
||||
t.Errorf("unable to start mock server: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := connMock.Close(); err != nil {
|
||||
if err := simulatorMock.Close(); err != nil {
|
||||
t.Errorf("unable to close mock server: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
publisher := MockPublisher{}
|
||||
|
||||
publisher := MockPublisher{publishedEvents: make([]*[]byte, 0)}
|
||||
|
||||
part := New(&publisher, connMock.Addr())
|
||||
part := New(&publisher, simulatorMock.Addr())
|
||||
go func() {
|
||||
err := part.Start()
|
||||
if err != nil {
|
||||
@@ -62,25 +62,20 @@ func TestPart_ListenEvents(t *testing.T) {
|
||||
}
|
||||
}()
|
||||
|
||||
simulatorMock.WaitConnection()
|
||||
log.Trace("read test data")
|
||||
testContent, err := ioutil.ReadFile("testdata/msg.json")
|
||||
lines := strings.Split(string(testContent), "\n")
|
||||
|
||||
for idx, line := range lines {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
err = connMock.WriteMsg(line)
|
||||
err = simulatorMock.EmitMsg(line)
|
||||
if err != nil {
|
||||
t.Errorf("[line %v/%v] unable to write line: %v", idx+1, len(lines), err)
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
expectedFrames := 16
|
||||
if len(publisher.Events()) != expectedFrames {
|
||||
t.Errorf("invalid number of frame emmitted: %v, wants %v", len(publisher.Events()), expectedFrames)
|
||||
}
|
||||
for _, byteMsg := range publisher.Events() {
|
||||
byteMsg := <-publisher.Notify()
|
||||
var msg events.FrameMessage
|
||||
err = proto.Unmarshal(*byteMsg, &msg)
|
||||
err = proto.Unmarshal(byteMsg, &msg)
|
||||
if err != nil {
|
||||
t.Errorf("unable to unmarshal frame msg: %v", err)
|
||||
continue
|
||||
@@ -94,57 +89,80 @@ func TestPart_ListenEvents(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
type ConnMock struct {
|
||||
ln net.Listener
|
||||
conn net.Conn
|
||||
muWriter sync.Mutex
|
||||
writer *bufio.Writer
|
||||
type SimulatorMock struct {
|
||||
ln net.Listener
|
||||
muConn sync.Mutex
|
||||
conn net.Conn
|
||||
writer *bufio.Writer
|
||||
newConnection chan net.Conn
|
||||
logger *log.Entry
|
||||
}
|
||||
|
||||
func (c *ConnMock) WriteMsg(p string) (err error) {
|
||||
c.muWriter.Lock()
|
||||
defer c.muWriter.Unlock()
|
||||
func (c *SimulatorMock) EmitMsg(p string) (err error) {
|
||||
c.muConn.Lock()
|
||||
defer c.muConn.Unlock()
|
||||
_, err = c.writer.WriteString(p + "\n")
|
||||
if err != nil {
|
||||
log.Errorf("unable to write response: %v", err)
|
||||
c.logger.Errorf("unable to write response: %v", err)
|
||||
}
|
||||
if err == io.EOF {
|
||||
log.Info("Connection closed")
|
||||
c.logger.Info("Connection closed")
|
||||
return err
|
||||
}
|
||||
err = c.writer.Flush()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *ConnMock) Listen() error {
|
||||
c.muWriter.Lock()
|
||||
defer c.muWriter.Unlock()
|
||||
func (c *SimulatorMock) WaitConnection() {
|
||||
c.muConn.Lock()
|
||||
defer c.muConn.Unlock()
|
||||
c.logger.Debug("simulator waiting connection")
|
||||
if c.conn != nil {
|
||||
return
|
||||
}
|
||||
c.logger.Debug("new connection")
|
||||
conn := <-c.newConnection
|
||||
|
||||
c.conn = conn
|
||||
c.writer = bufio.NewWriter(conn)
|
||||
}
|
||||
|
||||
func (c *SimulatorMock) Start() error {
|
||||
c.logger = log.WithField("simulator", "mock")
|
||||
c.newConnection = make(chan net.Conn)
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:")
|
||||
c.ln = ln
|
||||
if err != nil {
|
||||
|
||||
return fmt.Errorf("unable to listen on port: %v", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
c.conn, err = c.ln.Accept()
|
||||
conn, err := c.ln.Accept()
|
||||
if err != nil && err == io.EOF {
|
||||
log.Infof("connection close: %v", err)
|
||||
c.logger.Errorf("connection close: %v", err)
|
||||
break
|
||||
}
|
||||
c.writer = bufio.NewWriter(c.conn)
|
||||
if c.newConnection == nil {
|
||||
break
|
||||
}
|
||||
c.newConnection <- conn
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ConnMock) Addr() string {
|
||||
func (c *SimulatorMock) Addr() string {
|
||||
return c.ln.Addr().String()
|
||||
}
|
||||
|
||||
func (c *ConnMock) Close() error {
|
||||
log.Infof("close mock server")
|
||||
func (c *SimulatorMock) Close() error {
|
||||
c.logger.Debug("close mock server")
|
||||
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
close(c.newConnection)
|
||||
c.newConnection = nil
|
||||
err := c.ln.Close()
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to close mock server: %v", err)
|
||||
|
4
camera/testdata/msg.json
vendored
4
camera/testdata/msg.json
vendored
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user