Publish camera frame

This commit is contained in:
2020-09-20 23:16:06 +02:00
parent 5908978ddd
commit b2ca7423ea
545 changed files with 201593 additions and 0 deletions

174
camera/camera.go Normal file
View File

@@ -0,0 +1,174 @@
package camera
import (
"bufio"
"encoding/json"
"fmt"
"github.com/avast/retry-go"
"github.com/cyrilix/robocar-protobuf/go/events"
"github.com/cyrilix/robocar-simulator/simulator"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/timestamp"
log "github.com/sirupsen/logrus"
"io"
"net"
"time"
)
func New(publisher Publisher, addressSimulator string) *Gateway {
log.Info("run camera camera")
return &Gateway{
address: addressSimulator,
publisher: publisher,
}
}
/* Simulator interface to publish camera frames into mqtt topic */
type Gateway struct {
cancel chan interface{}
address string
conn io.ReadCloser
publisher Publisher
}
func (p *Gateway) Start() error {
log.Info("connect to simulator")
p.cancel = make(chan interface{})
msgChan := make(chan *simulator.SimulatorMsg)
go p.run(msgChan)
for {
select {
case msg := <-msgChan:
go p.publishFrame(msg)
case <-p.cancel:
return nil
}
}
}
func (p *Gateway) Stop() {
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)
}
}
func (p *Gateway) Close() error {
if p.conn == nil {
log.Warnln("no connection to close")
return nil
}
if err := p.conn.Close(); err != nil {
return fmt.Errorf("unable to close connection to simulator: %v", err)
}
return nil
}
func (p *Gateway) run(msgChan chan<- *simulator.SimulatorMsg) {
err := retry.Do(func() error {
conn, err := connect(p.address)
if err != nil {
return fmt.Errorf("unable to connect to simulator at %v", p.address)
}
p.conn = conn
return nil
},
retry.Delay(1*time.Second),
)
if err != nil {
log.Panicf("unable to connect to simulator: %v", err)
}
reader := bufio.NewReader(p.conn)
err = retry.Do(
func() error { return p.listen(msgChan, reader) },
)
if err != nil {
log.Errorf("unable to connect to server: %v", err)
}
}
func (p *Gateway) listen(msgChan chan<- *simulator.SimulatorMsg, reader *bufio.Reader) error {
for {
rawLine, err := reader.ReadBytes('\n')
if err == io.EOF {
log.Info("Connection closed")
return err
}
if err != nil {
return fmt.Errorf("unable to read response: %v", err)
}
var msg simulator.SimulatorMsg
err = json.Unmarshal(rawLine, &msg)
if err != nil {
log.Errorf("unable to unmarshal simulator msg: %v", err)
}
if "telemetry" != msg.MsgType {
continue
}
msgChan <- &msg
}
}
func (p *Gateway) publishFrame(msgSim *simulator.SimulatorMsg) {
now := time.Now()
msg := &events.FrameMessage{
Id: &events.FrameRef{
Name: "camera",
Id: fmt.Sprintf("%d%03d", now.Unix(), now.Nanosecond()/1000/1000),
CreatedAt: &timestamp.Timestamp{
Seconds: now.Unix(),
Nanos: int32(now.Nanosecond()),
},
},
Frame: msgSim.Image,
}
payload, err := proto.Marshal(msg)
if err != nil {
log.Errorf("unable to marshal protobuf message: %v", err)
}
p.publisher.Publish(&payload)
}
var connect = func(address string) (io.ReadWriteCloser, error) {
conn, err := net.Dial("tcp", address)
if err != nil {
return nil, fmt.Errorf("unable to connect to %v", address)
}
return conn, nil
}
type Publisher interface {
Publish(payload *[]byte)
}
func NewMqttPublisher(client mqtt.Client, topic string) Publisher {
return &MqttPublisher{
client: client,
topic: topic,
}
}
type MqttPublisher struct {
client mqtt.Client
topic string
}
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)
}
}

153
camera/camera_test.go Normal file
View File

@@ -0,0 +1,153 @@
package camera
import (
"bufio"
"fmt"
"github.com/cyrilix/robocar-protobuf/go/events"
"github.com/golang/protobuf/proto"
log "github.com/sirupsen/logrus"
"io"
"io/ioutil"
"net"
"strings"
"sync"
"testing"
"time"
)
type MockPublisher struct {
muPubEvents sync.Mutex
publishedEvents []*[]byte
}
func (p *MockPublisher) Publish(payload *[]byte) {
p.muPubEvents.Lock()
defer p.muPubEvents.Unlock()
p.publishedEvents = append(p.publishedEvents, payload)
}
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 TestPart_ListenEvents(t *testing.T) {
connMock := ConnMock{}
err := connMock.Listen()
if err != nil {
t.Errorf("unable to start mock server: %v", err)
}
defer func() {
if err := connMock.Close(); err != nil {
t.Errorf("unable to close mock server: %v", err)
}
}()
publisher := MockPublisher{publishedEvents: make([]*[]byte, 0)}
part := New(&publisher, connMock.Addr())
go func() {
err := part.Start()
if err != nil {
t.Fatalf("unable to start camera simulator: %v", err)
}
}()
defer func() {
if err := part.Close(); err != nil {
t.Errorf("unable to close camera simulator: %v", err)
}
}()
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)
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() {
var msg events.FrameMessage
err = proto.Unmarshal(*byteMsg, &msg)
if err != nil {
t.Errorf("unable to unmarshal frame msg: %v", err)
continue
}
if msg.GetId() == nil {
t.Error("frame msg has not Id")
}
if len(msg.Frame) < 10 {
t.Errorf("[%v] invalid frame image: %v", msg.Id, msg.GetFrame())
}
}
}
type ConnMock struct {
ln net.Listener
conn net.Conn
muWriter sync.Mutex
writer *bufio.Writer
}
func (c *ConnMock) WriteMsg(p string) (err error) {
c.muWriter.Lock()
defer c.muWriter.Unlock()
_, err = c.writer.WriteString(p + "\n")
if err != nil {
log.Errorf("unable to write response: %v", err)
}
if err == io.EOF {
log.Info("Connection closed")
return err
}
err = c.writer.Flush()
return err
}
func (c *ConnMock) Listen() error {
c.muWriter.Lock()
defer c.muWriter.Unlock()
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()
if err != nil && err == io.EOF {
log.Infof("connection close: %v", err)
break
}
c.writer = bufio.NewWriter(c.conn)
}
}()
return nil
}
func (c *ConnMock) Addr() string {
return c.ln.Addr().String()
}
func (c *ConnMock) Close() error {
log.Infof("close mock server")
err := c.ln.Close()
if err != nil {
return fmt.Errorf("unable to close mock server: %v", err)
}
return nil
}

18
camera/testdata/msg.json vendored Normal file

File diff suppressed because one or more lines are too long