Start cameradar server to communicate with GUI
This commit is contained in:
committed by
Brendan Le Glaunec
parent
3ef48a97cf
commit
4e922a2a48
@@ -0,0 +1,20 @@
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package adaptor
|
||||
|
||||
// WebSocket is an interface that represents an authenticated websocket connection
|
||||
type WebSocket interface {
|
||||
AccessToken() string
|
||||
Read() <-chan interface{}
|
||||
Write() chan<- interface{}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/EtixLabs/cameradar/server/adaptor"
|
||||
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// FactoryMock mocks a websocket factory
|
||||
type FactoryMock struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// NewIncomingWebSocket mocks the creation of a websocket adaptor
|
||||
func (m *FactoryMock) NewIncomingWebSocket(
|
||||
w http.ResponseWriter,
|
||||
req *http.Request,
|
||||
) (adaptor.WebSocket, error) {
|
||||
args := m.Called(w, req)
|
||||
return args.Get(0).(adaptor.WebSocket), args.Error(1)
|
||||
}
|
||||
|
||||
// NewWebSocket mocks the creation of a websocket adaptor
|
||||
func (m *FactoryMock) NewWebSocket(url string) (adaptor.WebSocket, error) {
|
||||
args := m.Called(url)
|
||||
ws := args.Get(0)
|
||||
if ws != nil {
|
||||
return ws.(adaptor.WebSocket), args.Error(1)
|
||||
}
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
gorilla "github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// Gorilla implements WebSocket interface using Gorilla library
|
||||
type Gorilla struct {
|
||||
conn *gorilla.Conn
|
||||
accessToken string
|
||||
|
||||
input chan interface{}
|
||||
output chan interface{}
|
||||
}
|
||||
|
||||
// AccessToken returns the user authentication token
|
||||
func (g *Gorilla) AccessToken() string {
|
||||
return g.accessToken
|
||||
}
|
||||
|
||||
// Write return a chan to retrieve websocket inputs
|
||||
func (g *Gorilla) Read() <-chan interface{} {
|
||||
return g.input
|
||||
}
|
||||
|
||||
// Write returns a chan to write on websocket
|
||||
func (g *Gorilla) Write() chan<- interface{} {
|
||||
return g.output
|
||||
}
|
||||
|
||||
func (g *Gorilla) read(readLimit int64, pongWait time.Duration) {
|
||||
defer (func() {
|
||||
g.conn.Close()
|
||||
close(g.input)
|
||||
})()
|
||||
|
||||
// setup read to timeout if no pong is received after `pongWait`
|
||||
g.conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
g.conn.SetPongHandler(func(string) error {
|
||||
g.conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
return nil
|
||||
})
|
||||
|
||||
g.conn.SetReadLimit(readLimit)
|
||||
for {
|
||||
messageType, message, err := g.conn.ReadMessage()
|
||||
if err != nil {
|
||||
if _, ok := err.(*gorilla.CloseError); ok {
|
||||
fmt.Printf("ws connection closed from %v (%v)\n", g.conn.RemoteAddr(), err)
|
||||
} else {
|
||||
// most of the time, a read error is not an error (connection closed, ...)
|
||||
fmt.Printf("ws read error: %v\n", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
switch messageType {
|
||||
case gorilla.TextMessage:
|
||||
g.input <- string(message)
|
||||
case gorilla.BinaryMessage:
|
||||
g.input <- message
|
||||
default:
|
||||
fmt.Printf("received invalid message type: %v\n", messageType)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gorilla) pingAndWrite(pingInterval time.Duration) {
|
||||
defer g.conn.Close()
|
||||
|
||||
pinger := time.NewTicker(pingInterval)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-pinger.C:
|
||||
if err := g.conn.WriteMessage(gorilla.PingMessage, []byte{}); err != nil {
|
||||
fmt.Printf("ping write error: %v\n", err)
|
||||
return
|
||||
}
|
||||
case message, ok := <-g.output:
|
||||
if !ok {
|
||||
// chan closed, stop write routine
|
||||
return
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
switch msg := message.(type) {
|
||||
case []byte:
|
||||
err = g.conn.WriteMessage(gorilla.BinaryMessage, msg)
|
||||
case string:
|
||||
err = g.conn.WriteMessage(gorilla.TextMessage, []byte(msg))
|
||||
default:
|
||||
err = fmt.Errorf("invalid message type: %T", msg)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Printf("write error: %v\n", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/EtixLabs/cameradar/server/adaptor"
|
||||
|
||||
gorilla "github.com/gorilla/websocket"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// GorillaFactory is a websocket Factory using Gorilla websocket client
|
||||
type GorillaFactory struct {
|
||||
readLimit int64
|
||||
pingInterval time.Duration
|
||||
pongWait time.Duration
|
||||
writeChanBufferSize uint
|
||||
upgrader gorilla.Upgrader
|
||||
}
|
||||
|
||||
// NewGorillaFactory instantiates and returns a Gorilla Factory
|
||||
func NewGorillaFactory(options ...func(*GorillaFactory)) *GorillaFactory {
|
||||
gf := &GorillaFactory{
|
||||
// readLimit: default to 1MB
|
||||
readLimit: 1024 * 1024,
|
||||
pingInterval: 5 * time.Second,
|
||||
pongWait: 10 * time.Second,
|
||||
|
||||
// allow about 1 frame per grid cell to be buffered (grids contain about ~16 cameras)
|
||||
// NOTE: this should be about the same size as the number of subcriptions the client has
|
||||
writeChanBufferSize: 20,
|
||||
|
||||
// default upgrader: don't check requests origin
|
||||
upgrader: gorilla.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
},
|
||||
}
|
||||
// apply the options to the struct
|
||||
for _, option := range options {
|
||||
option(gf)
|
||||
}
|
||||
return gf
|
||||
}
|
||||
|
||||
// NewIncomingWebSocket instantiates a Gorilla websocket from an http incoming connection
|
||||
func (gf *GorillaFactory) NewIncomingWebSocket(w http.ResponseWriter, req *http.Request) (adaptor.WebSocket, error) {
|
||||
fmt.Printf("new ws connection from %v\n", req.RemoteAddr)
|
||||
|
||||
// create WS connection
|
||||
conn, err := gf.upgrader.Upgrade(w, req, nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "cannot upgrade ws connection")
|
||||
}
|
||||
|
||||
g := &Gorilla{
|
||||
conn: conn,
|
||||
accessToken: req.Header.Get("Sec-WebSocket-Protocol"),
|
||||
|
||||
input: make(chan interface{}),
|
||||
output: make(chan interface{}, gf.writeChanBufferSize),
|
||||
}
|
||||
|
||||
go g.pingAndWrite(gf.pingInterval)
|
||||
go g.read(gf.readLimit, gf.pongWait)
|
||||
|
||||
return g, nil
|
||||
}
|
||||
|
||||
// NewWebSocket attemps to connect to a ws server using Gorilla library
|
||||
func (gf *GorillaFactory) NewWebSocket(url string) (adaptor.WebSocket, error) {
|
||||
fmt.Printf("opening new ws connection to %v\n", url)
|
||||
|
||||
// create WS connection
|
||||
conn, _, err := gorilla.DefaultDialer.Dial(url, nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "cannot open ws connection")
|
||||
}
|
||||
|
||||
g := &Gorilla{
|
||||
conn: conn,
|
||||
|
||||
input: make(chan interface{}),
|
||||
output: make(chan interface{}, gf.writeChanBufferSize),
|
||||
}
|
||||
|
||||
go g.pingAndWrite(gf.pingInterval)
|
||||
go g.read(gf.readLimit, gf.pongWait)
|
||||
|
||||
return g, nil
|
||||
}
|
||||
|
||||
// SetReadLimit sets the maximum size read from an incoming message
|
||||
func SetReadLimit(limit int64) func(gf *GorillaFactory) {
|
||||
return func(gf *GorillaFactory) {
|
||||
gf.readLimit = limit
|
||||
}
|
||||
}
|
||||
|
||||
// SetPingInterval sets the interval between pings
|
||||
func SetPingInterval(interval time.Duration) func(gf *GorillaFactory) {
|
||||
return func(gf *GorillaFactory) {
|
||||
gf.pingInterval = interval
|
||||
}
|
||||
}
|
||||
|
||||
// SetPongWait sets the time before read should timeout if no pong is received
|
||||
func SetPongWait(pongWait time.Duration) func(gf *GorillaFactory) {
|
||||
return func(gf *GorillaFactory) {
|
||||
gf.pongWait = pongWait
|
||||
}
|
||||
}
|
||||
|
||||
// SetWriteChanBufferSize sets the buffer size of the write channel
|
||||
func SetWriteChanBufferSize(size uint) func(gf *GorillaFactory) {
|
||||
return func(gf *GorillaFactory) {
|
||||
gf.writeChanBufferSize = size
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// Mock mocks a websocket adaptor
|
||||
type Mock struct {
|
||||
mock.Mock
|
||||
|
||||
Token string
|
||||
ReadChan chan interface{}
|
||||
WriteChan chan interface{}
|
||||
}
|
||||
|
||||
// NewMock create a new websocket adaptor mock, with helper read/write
|
||||
// chans already created
|
||||
func NewMock(accessToken string, writeChanBuffer uint) *Mock {
|
||||
return &Mock{
|
||||
Token: accessToken,
|
||||
ReadChan: make(chan interface{}),
|
||||
WriteChan: make(chan interface{}, writeChanBuffer),
|
||||
}
|
||||
}
|
||||
|
||||
// AccessToken mocks token getter
|
||||
func (m *Mock) AccessToken() string {
|
||||
args := m.Called()
|
||||
return args.String(0)
|
||||
}
|
||||
|
||||
// OnAccessToken is a helper method to setup an "AccessToken()" handler
|
||||
// with the mock accessToken
|
||||
func (m *Mock) OnAccessToken() *mock.Call {
|
||||
return m.On("AccessToken").Return(m.Token)
|
||||
}
|
||||
|
||||
// Read mocks read channel getter
|
||||
func (m *Mock) Read() <-chan interface{} {
|
||||
args := m.Called()
|
||||
return args.Get(0).(<-chan interface{})
|
||||
}
|
||||
|
||||
// OnRead is a helper method to setup a "Read()" handler
|
||||
// with the mock readChan
|
||||
func (m *Mock) OnRead() *mock.Call {
|
||||
var readOnlyChan <-chan interface{} = m.ReadChan
|
||||
return m.On("Read").Return(readOnlyChan)
|
||||
}
|
||||
|
||||
// Write mocks write channel getter
|
||||
func (m *Mock) Write() chan<- interface{} {
|
||||
args := m.Called()
|
||||
return args.Get(0).(chan<- interface{})
|
||||
}
|
||||
|
||||
// OnWrite is a helper method to setup a "Write()" handler
|
||||
// with the mock writeChan
|
||||
func (m *Mock) OnWrite() *mock.Call {
|
||||
var writeOnlyChan chan<- interface{} = m.WriteChan
|
||||
return m.On("Write").Return(writeOnlyChan)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package adaptor
|
||||
|
||||
import "net/http"
|
||||
|
||||
// WebSocketFactory is an interface for creating generic websocket connections
|
||||
type WebSocketFactory interface {
|
||||
NewIncomingWebSocket(w http.ResponseWriter, req *http.Request) (WebSocket, error)
|
||||
NewWebSocket(url string) (WebSocket, error)
|
||||
}
|
||||
Reference in New Issue
Block a user