Compare commits
24 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
67f25c76ae | ||
![]() |
7ef6e614cc | ||
![]() |
49dff4f609 | ||
![]() |
3704edebd5 | ||
![]() |
a503b71fb6 | ||
![]() |
05409c2544 | ||
![]() |
b484745ed1 | ||
![]() |
04e306c6da | ||
![]() |
239e0050a1 | ||
![]() |
de4758c563 | ||
![]() |
a85c9ccd66 | ||
![]() |
da78a00446 | ||
![]() |
ba3c55dc34 | ||
![]() |
e0950b44ee | ||
![]() |
76a036707f | ||
![]() |
258323f5b7 | ||
![]() |
473eb22b97 | ||
![]() |
64ad4e8b3e | ||
![]() |
b29e7a97b8 | ||
![]() |
c85590e5a5 | ||
![]() |
b5d9d96c52 | ||
![]() |
dc64d08e9d | ||
![]() |
a92995d766 | ||
![]() |
348a6f7622 |
48
.gitea/workflows/build.yml
Normal file
48
.gitea/workflows/build.yml
Normal file
@@ -0,0 +1,48 @@
|
||||
name: Build Go Binaries
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
goos: [linux, windows]
|
||||
goarch: [amd64, arm, arm64]
|
||||
exclude:
|
||||
- goos: windows
|
||||
goarch: arm
|
||||
- goos: windows
|
||||
goarch: arm64
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '1.24.0'
|
||||
|
||||
- name: Set up Git credentials for private modules
|
||||
run: |
|
||||
git config --global url."https://${{ secrets.GH_PAT }}@github.com/".insteadOf "https://github.com/"
|
||||
echo "GOPRIVATE=github.com/tecamino/*" >> $GITHUB_ENV
|
||||
|
||||
- name: Build binary
|
||||
run: |
|
||||
mkdir -p build
|
||||
if [ "${{ matrix.goos }}" == "windows" ]; then
|
||||
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -ldflags="-s -w" -trimpath -o build/tecamino-driver-artNet-${{ matrix.goos }}-${{ matrix.goarch }}.exe main.go
|
||||
else
|
||||
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -ldflags="-s -w" -trimpath -o build/tecamino-driver-artNet-${{ matrix.goos }}-${{ matrix.goarch }} main.go
|
||||
fi
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: binaries-${{ matrix.goos }}-${{ matrix.goarch }}
|
||||
path: build/
|
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,2 +1,5 @@
|
||||
.DS_Store
|
||||
*.cfg
|
||||
*.log
|
||||
artNetDriver-arm64
|
||||
tecamino-driver-artNet-linux-arm64
|
||||
|
@@ -1,66 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
json_data "github.com/tecamino/tecamino-json_data"
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
"github.com/tecamino/tecamino-logger/logging"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
conn *websocket.Conn
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
log *logging.Logger
|
||||
}
|
||||
|
||||
// Initialize new websocket server
|
||||
func NewClient(log *logging.Logger) *Client {
|
||||
c := Client{
|
||||
log: log,
|
||||
}
|
||||
c.ctx, c.cancel = context.WithCancel(context.Background())
|
||||
return &c
|
||||
}
|
||||
|
||||
func (c *Client) Connect(ip, id string, port uint) (err error) {
|
||||
c.conn, _, err = websocket.Dial(c.ctx, fmt.Sprintf("ws://%s:%d/ws?id=%s", ip, port, id), nil)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Client) Disconnect() {
|
||||
c.cancel()
|
||||
}
|
||||
func (c *Client) Subscribe(id string) error {
|
||||
|
||||
req := json_data.NewRequest()
|
||||
req.AddDriverSubscription(".*", id, 0, true, false, false)
|
||||
if err := wsjson.Write(c.ctx, c.conn, req); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) ReadJsonData() (response json_dataModels.Response, err error) {
|
||||
|
||||
err = wsjson.Read(c.ctx, c.conn, &response)
|
||||
if err != nil {
|
||||
code := websocket.CloseStatus(err)
|
||||
|
||||
switch code {
|
||||
case websocket.StatusNormalClosure,
|
||||
websocket.StatusGoingAway,
|
||||
websocket.StatusNoStatusRcvd:
|
||||
c.log.Info("webSocket.readJsonData", fmt.Sprintf("WebSocket closed: %v (code: %v)\n", err, code))
|
||||
return
|
||||
default:
|
||||
c.log.Error("webSocket.readJsonData", fmt.Sprintf("WebSocket read error: %v (code: %v)\n", err, code))
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
@@ -2,11 +2,13 @@ package driver
|
||||
|
||||
import (
|
||||
"artNet/cfg"
|
||||
"artNet/client"
|
||||
"artNet/models"
|
||||
ws "artNet/websocket"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path"
|
||||
|
||||
json_data "github.com/tecamino/tecamino-json_data"
|
||||
"github.com/tecamino/tecamino-logger/logging"
|
||||
)
|
||||
|
||||
@@ -14,7 +16,6 @@ type ArtNetDriver struct {
|
||||
Name string `yaml:"driver" json:"driver"`
|
||||
Buses map[string]*models.Bus `yaml:"buses,omitempty" json:"buses,omitempty"`
|
||||
cfgHandler *cfg.Cfg `yaml:"-" json:"-"`
|
||||
Conn *client.Client `yaml:"-" json:"-"`
|
||||
Subscriptions models.Subscriptions `yaml:"-" json:"-"`
|
||||
Log *logging.Logger `yaml:"-" json:"-"`
|
||||
}
|
||||
@@ -50,9 +51,6 @@ func NewDriver(cfgDir, name string, debug bool) (*ArtNetDriver, error) {
|
||||
logger.Error("artNet.NewDriver.LoadCfg", "error load driver configuration: "+err.Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d.Conn = client.NewClient(logger)
|
||||
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
@@ -63,8 +61,8 @@ func (d *ArtNetDriver) LoadCfg() error {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, b := range d.Buses {
|
||||
d.NewBus(b.Name, b.Ip, *b.Port)
|
||||
for name, b := range d.Buses {
|
||||
d.NewBus(name, b.Ip, *b.Port)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -80,35 +78,68 @@ func (d *ArtNetDriver) SetValue(bus string, address uint, value uint8) error {
|
||||
if _, ok := d.Buses[bus]; !ok {
|
||||
return fmt.Errorf("no bus '%s' found", bus)
|
||||
}
|
||||
d.Buses[bus].Data.SetValue(address, value)
|
||||
|
||||
return d.Buses[bus].SendData()
|
||||
if d.Buses[bus].DMX.Data == nil {
|
||||
return fmt.Errorf("no dmx data on bus '%s' found", bus)
|
||||
}
|
||||
d.Buses[bus].SetDMXData(address, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
// connect to websocket server and listen to subscriptions
|
||||
// ip: ip address of server
|
||||
// id: id of driver
|
||||
// port: port of server
|
||||
func (d *ArtNetDriver) Connect(ip, id string, port uint) error {
|
||||
if err := d.Conn.Connect(ip, id, port); err != nil {
|
||||
return err
|
||||
}
|
||||
defer d.Conn.Disconnect()
|
||||
|
||||
if err := d.Conn.Subscribe(id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
respond, err := d.Conn.ReadJsonData()
|
||||
errChan := make(chan error)
|
||||
client, err := ws.NewClient(ip, id, port)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
d.Subscribe(respond.Subscribe...)
|
||||
client.OnError = func(err error) {
|
||||
d.Log.Error("websocket connection", err)
|
||||
errChan <- err
|
||||
}
|
||||
|
||||
for _, pub := range respond.Publish {
|
||||
if sub, ok := d.Subscriptions[pub.Uuid]; ok {
|
||||
if err := d.SetValue(sub.Bus, sub.Address, uint8(pub.Value.(float64))); err != nil {
|
||||
d.Log.Info("artNet.Connect", err.Error())
|
||||
}
|
||||
client.OnMessage = func(data []byte) {
|
||||
request := json_data.NewResponse()
|
||||
|
||||
err = json.Unmarshal(data, &request)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if request.Subscribe != nil {
|
||||
d.Subscribe(request.Subscribe...)
|
||||
}
|
||||
|
||||
if request.Publish != nil {
|
||||
d.Publish(request.Publish...)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
d.Log.Error("artNet.Connect", err)
|
||||
return err
|
||||
}
|
||||
|
||||
req := json_data.NewRequest()
|
||||
req.AddDriverSubscription(".*", id, 0, true, false, false)
|
||||
|
||||
if err := client.SendRequest(req); err != nil {
|
||||
errChan <- err
|
||||
d.Log.Error("websocket send data", err)
|
||||
}
|
||||
|
||||
for err := range errChan {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// send data to all buses that the send flage is true
|
||||
func (d *ArtNetDriver) SendData() {
|
||||
for _, bus := range d.Buses {
|
||||
bus.Send = bus.Reachable
|
||||
}
|
||||
}
|
||||
|
@@ -30,7 +30,8 @@ func (d *ArtNetDriver) CreateBus(c *gin.Context) {
|
||||
_, err := auth.GetIDFromQuery(c)
|
||||
if err != nil {
|
||||
r := json_data.NewResponse()
|
||||
r.SendError(err.Error())
|
||||
r.SetError()
|
||||
r.SetMessage(err.Error())
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return
|
||||
}
|
||||
@@ -42,14 +43,16 @@ func (d *ArtNetDriver) CreateBus(c *gin.Context) {
|
||||
|
||||
if addr := net.ParseIP(busPayload.Ip); addr == nil {
|
||||
r := json_data.NewResponse()
|
||||
r.SendError("wrong ip '" + busPayload.Ip + "'")
|
||||
r.SetError()
|
||||
r.SetMessage("wrong ip '" + busPayload.Ip + "'")
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return
|
||||
}
|
||||
|
||||
if _, ok := d.Buses[busPayload.Name]; ok {
|
||||
r := json_data.NewResponse()
|
||||
r.SendError("bus " + busPayload.Name + " exists already")
|
||||
r.SetError()
|
||||
r.SetMessage("bus " + busPayload.Name + " exists already")
|
||||
c.JSON(http.StatusOK, r)
|
||||
return
|
||||
}
|
||||
@@ -57,7 +60,7 @@ func (d *ArtNetDriver) CreateBus(c *gin.Context) {
|
||||
bus := d.NewBus(busPayload.Name, busPayload.Ip, busPayload.GetPort())
|
||||
|
||||
r := json_data.NewResponse()
|
||||
r.SendMessage(fmt.Sprintf("bus '%s' successfully created with ip: %s and on port: %d", bus.Name, bus.Ip, bus.GetPort()))
|
||||
r.SetMessage(fmt.Sprintf("bus '%s' successfully created with ip: %s and on port: %d", bus.Name, bus.Ip, bus.GetPort()))
|
||||
c.JSON(http.StatusOK, r)
|
||||
d.cfgHandler.SaveCfg(*d)
|
||||
}
|
||||
@@ -66,7 +69,8 @@ func (d *ArtNetDriver) RemoveBus(c *gin.Context) {
|
||||
_, err := auth.GetIDFromQuery(c)
|
||||
if err != nil {
|
||||
r := json_data.NewResponse()
|
||||
r.SendError("id: " + err.Error())
|
||||
r.SetError()
|
||||
r.SetMessage("id: " + err.Error())
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return
|
||||
}
|
||||
@@ -78,14 +82,14 @@ func (d *ArtNetDriver) RemoveBus(c *gin.Context) {
|
||||
|
||||
if _, ok := d.Buses[busPayload.Name]; !ok {
|
||||
r := json_dataModels.NewResponse()
|
||||
r.SendMessage("bus " + busPayload.Name + " not found")
|
||||
c.JSON(http.StatusOK, r)
|
||||
r.SetMessage("bus " + busPayload.Name + " not found")
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return
|
||||
} else {
|
||||
delete(d.Buses, busPayload.Name)
|
||||
}
|
||||
r := json_dataModels.NewResponse()
|
||||
r.SendMessage(fmt.Sprintf("bus '%s' successfully removed", busPayload.Name))
|
||||
r.SetMessage(fmt.Sprintf("bus '%s' successfully removed", busPayload.Name))
|
||||
c.JSON(http.StatusOK, r)
|
||||
d.cfgHandler.SaveCfg(*d)
|
||||
}
|
||||
@@ -94,29 +98,30 @@ func (d *ArtNetDriver) Start(c *gin.Context) {
|
||||
_, err := auth.GetIDFromQuery(c)
|
||||
if err != nil {
|
||||
r := json_data.NewResponse()
|
||||
r.SendError("id: " + err.Error())
|
||||
r.SetError()
|
||||
r.SetMessage("id: " + err.Error())
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return
|
||||
}
|
||||
|
||||
busPayload := models.Bus{}
|
||||
if busPayload.ParsePayload(c); err != nil {
|
||||
if err := busPayload.ParsePayload(c); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
d.Buses[busPayload.Name].Start(d.Log)
|
||||
|
||||
r := json_dataModels.NewResponse()
|
||||
r.SendMessage(fmt.Sprintf("bus '%s' running", busPayload.Name))
|
||||
r.SetMessage(fmt.Sprintf("bus '%s' running", busPayload.Name))
|
||||
c.JSON(http.StatusOK, r)
|
||||
d.cfgHandler.SaveCfg(*d)
|
||||
}
|
||||
|
||||
func (d *ArtNetDriver) Stop(c *gin.Context) {
|
||||
_, err := auth.GetIDFromQuery(c)
|
||||
if err != nil {
|
||||
r := json_data.NewResponse()
|
||||
r.SendError("id: " + err.Error())
|
||||
r.SetError()
|
||||
r.SetMessage("id: " + err.Error())
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return
|
||||
}
|
||||
@@ -129,16 +134,49 @@ func (d *ArtNetDriver) Stop(c *gin.Context) {
|
||||
d.Buses[busPayload.Name].Stop()
|
||||
|
||||
r := json_dataModels.NewResponse()
|
||||
r.SendMessage(fmt.Sprintf("bus '%s' stopped", busPayload.Name))
|
||||
r.SetMessage(fmt.Sprintf("bus '%s' stopped", busPayload.Name))
|
||||
c.JSON(http.StatusOK, r)
|
||||
d.cfgHandler.SaveCfg(*d)
|
||||
}
|
||||
|
||||
func (d *ArtNetDriver) Resubscribe(c *gin.Context) {
|
||||
_, err := auth.GetIDFromQuery(c)
|
||||
|
||||
if err != nil {
|
||||
r := json_data.NewResponse()
|
||||
r.SetError()
|
||||
r.SetMessage("id: " + err.Error())
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return
|
||||
}
|
||||
|
||||
busPayload := models.Bus{}
|
||||
if err := busPayload.ParsePayload(c); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if _, ok := d.Buses[busPayload.Name]; !ok {
|
||||
r := json_dataModels.NewResponse()
|
||||
r.SetMessage("bus " + busPayload.Name + " not found")
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return
|
||||
}
|
||||
|
||||
if busPayload.Resubscribe == nil {
|
||||
r := json_dataModels.NewResponse()
|
||||
r.SetMessage("no resubscriptions in request")
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return
|
||||
}
|
||||
|
||||
d.Subscribe(*busPayload.Resubscribe...)
|
||||
}
|
||||
|
||||
func (d *ArtNetDriver) Status(c *gin.Context) {
|
||||
_, err := auth.GetIDFromQuery(c)
|
||||
if err != nil {
|
||||
r := json_data.NewResponse()
|
||||
r.SendError("id: " + err.Error())
|
||||
r.SetError()
|
||||
r.SetMessage("id: " + err.Error())
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return
|
||||
}
|
||||
@@ -153,6 +191,6 @@ func (d *ArtNetDriver) Status(c *gin.Context) {
|
||||
if d.Buses[busPayload.Name].Status() {
|
||||
state = "running"
|
||||
}
|
||||
r.SendMessage(fmt.Sprintf("bus '%s' %s", busPayload.Name, state))
|
||||
r.SetMessage(fmt.Sprintf("bus '%s' %s", busPayload.Name, state))
|
||||
c.JSON(http.StatusOK, r)
|
||||
}
|
||||
|
23
driver/publish.go
Normal file
23
driver/publish.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package driver
|
||||
|
||||
import (
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
)
|
||||
|
||||
func (d *ArtNetDriver) Publish(pubs ...json_dataModels.Publish) error {
|
||||
if d.Subscriptions == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, pub := range pubs {
|
||||
if subs, ok := (d.Subscriptions)[pub.Uuid]; ok {
|
||||
for _, sub := range subs {
|
||||
for _, address := range sub.Address {
|
||||
d.SetValue(sub.Bus, address, uint8(pub.Value.(float64)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
d.SendData()
|
||||
return nil
|
||||
}
|
@@ -6,7 +6,7 @@ import (
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
)
|
||||
|
||||
func (d *ArtNetDriver) Subscribe(subs ...json_dataModels.Subscribe) {
|
||||
func (d *ArtNetDriver) Subscribe(subs ...json_dataModels.Subscription) {
|
||||
if d.Subscriptions == nil {
|
||||
d.Subscriptions = models.NewSubscriptions()
|
||||
}
|
||||
@@ -14,7 +14,13 @@ func (d *ArtNetDriver) Subscribe(subs ...json_dataModels.Subscribe) {
|
||||
for _, sub := range subs {
|
||||
if drv, ok := (*sub.Drivers)[sub.Driver]; ok {
|
||||
d.Subscriptions.AddSubscription(sub.Uuid, drv)
|
||||
d.SetValue(drv.Bus, drv.Address, uint8(sub.Value.(float64)))
|
||||
for _, bus := range drv.Buses {
|
||||
for _, address := range bus.Address {
|
||||
d.SetValue(bus.Name, address, uint8(sub.Value.(float64)))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
d.SendData()
|
||||
}
|
||||
|
@@ -1,49 +0,0 @@
|
||||
package driver
|
||||
|
||||
const (
|
||||
OnCreate = "onCreate"
|
||||
OnChange = "onChange"
|
||||
OnDelete = "onDelete"
|
||||
)
|
||||
|
||||
//func (d *ArtNetDriver) Websocket(c *gin.Context) {
|
||||
// id, err := auth.GetIDFromQuery(c)
|
||||
// if err != nil {
|
||||
// d.Log.Error("artNet.webSocket.Websocket", "error GetIDFromAuth: "+err.Error())
|
||||
// return
|
||||
// }
|
||||
// d.Log.Debug("artNet.webSocket.Websocket", "authorization id token: "+id)
|
||||
|
||||
// ctx, cancel := context.WithTimeout(c.Request.Context(), 10*time.Minute)
|
||||
// defer cancel()
|
||||
// conn, err := d.Connections.ConnectRecievingWsConnection(id, c)
|
||||
// if err != nil {
|
||||
// d.Log.Error("artNet.webSocket.Websocket", "error connecting recieving websocket conection: "+err.Error())
|
||||
// return
|
||||
// }
|
||||
// defer d.Connections.DisconnectRecievingWsConnection(id, websocket.StatusInternalError, "Internal error")
|
||||
|
||||
// var request any
|
||||
// //Read loop
|
||||
// for {
|
||||
|
||||
// err := wsjson.Read(ctx, conn, &request)
|
||||
// if err != nil {
|
||||
// d.Log.Error("artNet.webSocket.Websocket", "read error:"+err.Error())
|
||||
// log.Println("WebSocket read error:", err)
|
||||
// break
|
||||
// }
|
||||
// fmt.Println(request)
|
||||
// Set
|
||||
// if request.Set != nil {
|
||||
// for _, set := range *request.Set {
|
||||
// if err = d.SetValue(set); err != nil {
|
||||
// d.Log.Error("artNet.webSocket.Websocket", "set value error"+err.Error())
|
||||
// log.Println(err)
|
||||
// continue
|
||||
// }
|
||||
// time.Sleep(23 * time.Millisecond)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
4
go.mod
4
go.mod
@@ -5,11 +5,11 @@ go 1.23.0
|
||||
toolchain go1.23.8
|
||||
|
||||
require (
|
||||
github.com/coder/websocket v1.8.13
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e
|
||||
github.com/tecamino/tecamino-json_data v0.0.11
|
||||
github.com/tecamino/tecamino-json_data v0.0.31
|
||||
github.com/tecamino/tecamino-logger v0.2.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
8
go.sum
8
go.sum
@@ -6,8 +6,6 @@ github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/
|
||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
|
||||
github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
@@ -32,6 +30,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
@@ -65,8 +65,8 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e h1:nt2877sKfojlHCTOBXbpWjBkuWKritFaGIfgQwbQUls=
|
||||
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e/go.mod h1:B4+Kq1u5FlULTjFSM707Q6e/cOHFv0z/6QRoxubDIQ8=
|
||||
github.com/tecamino/tecamino-json_data v0.0.11 h1:WVcF0tj+ElM9hRM1PccbSnY8DHJnLPauqzY0o0ib9O0=
|
||||
github.com/tecamino/tecamino-json_data v0.0.11/go.mod h1:LLlyD7Wwqplb2BP4PeO86EokEcTRidlW5MwgPd1T2JY=
|
||||
github.com/tecamino/tecamino-json_data v0.0.31 h1:7zFbANj1Lihr64CCCh3O+9hxxsMcEPniRJZ5NgPrS5Y=
|
||||
github.com/tecamino/tecamino-json_data v0.0.31/go.mod h1:LLlyD7Wwqplb2BP4PeO86EokEcTRidlW5MwgPd1T2JY=
|
||||
github.com/tecamino/tecamino-logger v0.2.0 h1:NPH/Gg9qRhmVoW8b39i1eXu/LEftHc74nyISpcRG+XU=
|
||||
github.com/tecamino/tecamino-logger v0.2.0/go.mod h1:0M1E9Uei/qw3e3WA1x3lBo1eP3H5oeYE7GjYrMahnj8=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
|
21
main.go
21
main.go
@@ -21,6 +21,7 @@ func main() {
|
||||
serverPort := flag.Uint("serverPort", 8100, "port of server")
|
||||
wsPort := flag.Uint("port", 8200, "websocket port")
|
||||
debug := flag.Bool("debug", false, "debug logging")
|
||||
start := flag.Bool("start", false, "starts all buses on startup")
|
||||
flag.Parse()
|
||||
|
||||
//change working directory only if value is given
|
||||
@@ -47,6 +48,7 @@ func main() {
|
||||
s.Routes.POST("/buses/start", artNetDriver.Start)
|
||||
s.Routes.POST("/buses/status", artNetDriver.Status)
|
||||
s.Routes.POST("/buses/stop", artNetDriver.Stop)
|
||||
s.Routes.POST("/buses/resubscribe", artNetDriver.Resubscribe)
|
||||
|
||||
s.Routes.GET("/", func(c *gin.Context) {
|
||||
c.String(200, "ArtNet Driver WebSocket Server is running!")
|
||||
@@ -54,14 +56,27 @@ func main() {
|
||||
|
||||
go func() {
|
||||
if err := s.ServeHttp(*wsPort); err != nil {
|
||||
artNetDriver.Log.Error("main", err.Error())
|
||||
artNetDriver.Log.Error("main", err)
|
||||
}
|
||||
}()
|
||||
|
||||
artNetDriver.Log.Info("main", fmt.Sprintf("connect to server ws://%s:%d with id %s", *serverIp, serverPort, DriverName))
|
||||
artNetDriver.Log.Info("main", fmt.Sprintf("connect to server ws://%s:%d with id %s", *serverIp, *serverPort, DriverName))
|
||||
|
||||
if *start {
|
||||
for busName, bus := range artNetDriver.Buses {
|
||||
artNetDriver.Log.Info("main", fmt.Sprintf("starting bus %s", busName))
|
||||
// start bus and listen to subscriptions
|
||||
bus.Start(artNetDriver.Log)
|
||||
}
|
||||
}
|
||||
|
||||
// connect to server
|
||||
for {
|
||||
artNetDriver.Log.Error("main", artNetDriver.Connect(*serverIp, DriverName, *serverPort))
|
||||
if err := artNetDriver.Connect(*serverIp, DriverName, *serverPort); err != nil {
|
||||
artNetDriver.Log.Error("main", err)
|
||||
}
|
||||
|
||||
artNetDriver.Log.Info("main", "next reconnecting attempt in 10 seconds")
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
|
||||
|
@@ -6,11 +6,13 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tatsushid/go-fastping"
|
||||
json_data "github.com/tecamino/tecamino-json_data"
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
"github.com/tecamino/tecamino-logger/logging"
|
||||
)
|
||||
|
||||
@@ -24,9 +26,12 @@ type Bus struct {
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Ip string `yaml:"ip" json:"ip"`
|
||||
Port *int `yaml:"port" json:"port,omitempty"`
|
||||
Data *DMX `yaml:"-" json:"-"`
|
||||
DMX *DMX `yaml:"-" json:"-"`
|
||||
Resubscribe *[]json_dataModels.Subscription `yaml:"-" json:"resubscribe"`
|
||||
Watchdog context.CancelFunc `yaml:"-" json:"-"`
|
||||
mu sync.Mutex `yaml:"-" json:"-"`
|
||||
Reachable bool `yaml:"-" json:"-"`
|
||||
Send bool `yaml:"-" json:"-"`
|
||||
}
|
||||
|
||||
// adds new Art-Net interface to driver port 0 = 6454 (default art-net)
|
||||
@@ -39,7 +44,7 @@ func NewBus(name, ip string, port int) *Bus {
|
||||
Name: name,
|
||||
Ip: ip,
|
||||
Port: &port,
|
||||
Data: NewDMXUniverse(),
|
||||
DMX: NewDMXUniverse(),
|
||||
}
|
||||
return &i
|
||||
}
|
||||
@@ -87,7 +92,7 @@ func (b *Bus) Poll(interval time.Duration) error {
|
||||
}
|
||||
}()
|
||||
|
||||
_, err = conn.Write(NewArtNetPackage(b.Data))
|
||||
_, err = conn.Write(NewArtNetPackage(b.DMX))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -100,13 +105,13 @@ func (b *Bus) Poll(interval time.Duration) error {
|
||||
}
|
||||
|
||||
// start bus
|
||||
func (b *Bus) Start(log *logging.Logger) {
|
||||
func (b *Bus) Start(log *logging.Logger) error {
|
||||
var ctx context.Context
|
||||
ctx, b.Watchdog = context.WithCancel(context.Background())
|
||||
|
||||
go func() {
|
||||
var interval time.Duration = 10 * time.Second
|
||||
log.Info("bus.Start", fmt.Sprintf("device:%s ip:%s watchdog stopped", b.Name, b.Ip))
|
||||
log.Info("bus.Start", fmt.Sprintf("device:%s ip:%s watchdog starting", b.Name, b.Ip))
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -123,6 +128,8 @@ func (b *Bus) Start(log *logging.Logger) {
|
||||
interval = 5 * time.Second
|
||||
} else {
|
||||
b.Reachable = true
|
||||
// send data as a heartbeat for she ArtNet Protocol
|
||||
b.Send = true
|
||||
log.Info("bus.Start", fmt.Sprintf("device:%s ip:%s watchdog running", b.Name, b.Ip))
|
||||
interval = 30 * time.Second
|
||||
}
|
||||
@@ -130,26 +137,7 @@ func (b *Bus) Start(log *logging.Logger) {
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// stop bus
|
||||
func (b *Bus) Stop() {
|
||||
if b.Watchdog != nil {
|
||||
b.Watchdog()
|
||||
}
|
||||
}
|
||||
|
||||
// status bus
|
||||
func (b *Bus) Status() bool {
|
||||
return b.Watchdog != nil
|
||||
}
|
||||
|
||||
// send dmx data
|
||||
func (b *Bus) SendData() error {
|
||||
if !b.Reachable {
|
||||
return nil
|
||||
}
|
||||
// Send packet over UDP
|
||||
conn, err := net.DialUDP("udp", nil, &net.UDPAddr{
|
||||
IP: net.ParseIP(b.Ip),
|
||||
Port: *b.Port,
|
||||
@@ -158,31 +146,82 @@ func (b *Bus) SendData() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
_, err = conn.Write(NewArtNetPackage(b.Data))
|
||||
go func() {
|
||||
ticker := time.NewTicker(23 * time.Millisecond)
|
||||
|
||||
return err
|
||||
defer func() {
|
||||
b.Send = false
|
||||
conn.Close()
|
||||
ticker.Stop()
|
||||
}()
|
||||
|
||||
for range ticker.C {
|
||||
|
||||
if !b.Send {
|
||||
continue
|
||||
}
|
||||
|
||||
b.Send = false
|
||||
|
||||
b.mu.Lock()
|
||||
data := NewDMXUniverse()
|
||||
copy(data.Data, b.DMX.GetDMXData())
|
||||
b.mu.Unlock()
|
||||
|
||||
_, err = conn.Write(NewArtNetPackage(data))
|
||||
if err != nil {
|
||||
log.Error("bus.Start", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// stop bus
|
||||
func (b *Bus) Stop() {
|
||||
if b.Watchdog != nil {
|
||||
//cancels context
|
||||
b.Watchdog()
|
||||
|
||||
b.Send = false
|
||||
}
|
||||
}
|
||||
|
||||
// status bus
|
||||
func (b *Bus) Status() bool {
|
||||
return b.Watchdog != nil
|
||||
}
|
||||
|
||||
func (b *Bus) ParsePayload(c *gin.Context) error {
|
||||
|
||||
if err := c.BindJSON(b); err != nil {
|
||||
r := json_data.NewResponse()
|
||||
r.SendError("json: " + err.Error())
|
||||
r.SetError()
|
||||
r.SetMessage("json: " + err.Error())
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return err
|
||||
}
|
||||
|
||||
if b.Name == "" {
|
||||
r := json_data.NewResponse()
|
||||
r.SendError("bus name missing")
|
||||
r.SetError()
|
||||
r.SetMessage("bus name missing")
|
||||
c.JSON(http.StatusBadRequest, r)
|
||||
return errors.New("bus name missing")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Bus) SetDMXData(channel uint, value uint8) error {
|
||||
fmt.Println(100, channel, value)
|
||||
b.DMX.SetValue(channel, value)
|
||||
b.Send = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func isUDPReachable(ip string) (recieved bool, err error) {
|
||||
p := fastping.NewPinger()
|
||||
ra, err := net.ResolveIPAddr("ip4:icmp", ip)
|
||||
|
@@ -1,12 +1,29 @@
|
||||
package models
|
||||
|
||||
type DMX []byte
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type DMX struct {
|
||||
Data []byte
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewDMXUniverse() *DMX {
|
||||
dmx := make(DMX, 512)
|
||||
return &dmx
|
||||
return &DMX{
|
||||
Data: make([]byte, 512),
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DMX) GetDMXData() (data []byte) {
|
||||
d.mu.Lock()
|
||||
data = d.Data
|
||||
d.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
func (d *DMX) SetValue(channel uint, value uint8) {
|
||||
(*d)[channel] = value
|
||||
d.mu.Lock()
|
||||
d.Data[channel] = value
|
||||
d.mu.Unlock()
|
||||
}
|
||||
|
@@ -23,7 +23,7 @@ func NewArtNetPackage(data *DMX) Package {
|
||||
packet.WriteByte(0x00) // Sequence
|
||||
packet.WriteByte(0x00) // Physical
|
||||
binary.Write(packet, binary.BigEndian, uint16(0)) // Universe (net:subuni, usually 0)
|
||||
binary.Write(packet, binary.BigEndian, uint16(len(*data))) // Length
|
||||
packet.Write(*data)
|
||||
binary.Write(packet, binary.BigEndian, uint16(len(data.Data))) // Length
|
||||
packet.Write(data.Data)
|
||||
return packet.Bytes()
|
||||
}
|
||||
|
@@ -5,11 +5,11 @@ import (
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
)
|
||||
|
||||
type Subscriptions map[uuid.UUID]Subscription
|
||||
type Subscriptions map[uuid.UUID][]Subscription
|
||||
|
||||
type Subscription struct {
|
||||
Bus string
|
||||
Address uint
|
||||
Address []uint
|
||||
}
|
||||
|
||||
func NewSubscriptions() Subscriptions {
|
||||
@@ -17,9 +17,11 @@ func NewSubscriptions() Subscriptions {
|
||||
}
|
||||
|
||||
func (s *Subscriptions) AddSubscription(uid uuid.UUID, drv *json_dataModels.Driver) {
|
||||
sub := Subscription{
|
||||
Bus: drv.Bus,
|
||||
Address: drv.Address,
|
||||
subs := []Subscription{}
|
||||
for _, bus := range drv.Buses {
|
||||
sub := Subscription{Bus: bus.Name}
|
||||
sub.Address = append(sub.Address, bus.Address...)
|
||||
subs = append(subs, sub)
|
||||
}
|
||||
(*s)[uid] = sub
|
||||
(*s)[uid] = subs
|
||||
}
|
||||
|
@@ -1,44 +0,0 @@
|
||||
package models
|
||||
|
||||
// type Clients map[string]Client
|
||||
|
||||
// type Client struct {
|
||||
// Connected *bool `json:"connected"`
|
||||
// SndConn *websocket.Conn `json:"-"` //sending connection
|
||||
// RvcConn *websocket.Conn `json:"-"` // revieving connection
|
||||
// }
|
||||
|
||||
// func NewClients() Clients {
|
||||
// return make(Clients)
|
||||
// }
|
||||
|
||||
// // Connect a recieving websocket connection
|
||||
// func (c *Clients) ConnectRecievingWsConnection(id string, ctx *gin.Context) (*websocket.Conn, error) {
|
||||
// conn, err := websocket.Accept(ctx.Writer, ctx.Request, &websocket.AcceptOptions{
|
||||
// OriginPatterns: []string{"*"},
|
||||
// })
|
||||
|
||||
// if err != nil {
|
||||
// return nil, fmt.Errorf("error accept websocket client: %s", err)
|
||||
// }
|
||||
|
||||
// b := true
|
||||
// (*c)[id] = Client{
|
||||
// Connected: &b,
|
||||
// RvcConn: conn,
|
||||
// }
|
||||
// return conn, nil
|
||||
// }
|
||||
|
||||
// func (c *Clients) RemoveClient(id string) {
|
||||
// delete(*c, id)
|
||||
// }
|
||||
|
||||
// func (c *Clients) GetClientPointer(id string) *bool {
|
||||
// return (*c)[id].Connected
|
||||
// }
|
||||
|
||||
// func (c *Clients) DisconnectRecievingWsConnection(id string, code websocket.StatusCode, reason string) {
|
||||
// *(*c)[id].Connected = false
|
||||
// (*c)[id].RvcConn.Close(code, reason)
|
||||
// }
|
194
websocket/client.go
Normal file
194
websocket/client.go
Normal file
@@ -0,0 +1,194 @@
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
)
|
||||
|
||||
const (
|
||||
// Time allowed to write a message to the peer.
|
||||
writeWait = 40 * time.Second
|
||||
|
||||
// Time allowed to read the next pong message from the peer.
|
||||
pongWait = 40 * time.Second
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
ip string
|
||||
port uint
|
||||
Connected bool
|
||||
conn *websocket.Conn
|
||||
OnOpen func()
|
||||
OnMessage func(data []byte)
|
||||
OnClose func(code int, reason string)
|
||||
OnError func(err error)
|
||||
OnPing func()
|
||||
OnPong func()
|
||||
send chan []byte
|
||||
unregister chan []byte
|
||||
}
|
||||
|
||||
// Connect to websocket server
|
||||
// ip: ip address of server
|
||||
func NewClient(ip, id string, port uint) (*Client, error) {
|
||||
url := fmt.Sprintf("ws://%s:%d/ws?id=%s", ip, port, id)
|
||||
c := &Client{
|
||||
ip: ip,
|
||||
port: port,
|
||||
Connected: true,
|
||||
send: make(chan []byte, 256),
|
||||
unregister: make(chan []byte, 256),
|
||||
}
|
||||
|
||||
dialer := websocket.DefaultDialer
|
||||
conn, resp, err := dialer.Dial(url, nil)
|
||||
if err != nil {
|
||||
if c.OnError != nil {
|
||||
c.OnError(err)
|
||||
}
|
||||
return nil, fmt.Errorf("dial error %v (status %v)", err, resp)
|
||||
}
|
||||
c.conn = conn
|
||||
|
||||
//Setup control handlers
|
||||
conn.SetPingHandler(func(appData string) error {
|
||||
if c.OnPing != nil {
|
||||
c.OnPing()
|
||||
}
|
||||
conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
conn.SetWriteDeadline(time.Now().Add(pongWait))
|
||||
if err := conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(2*pongWait)); err != nil {
|
||||
c.OnError(err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
conn.SetPongHandler(func(appData string) error {
|
||||
conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
if c.OnPong != nil {
|
||||
c.OnPong()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
// Start reading messages from client
|
||||
go c.Read()
|
||||
go c.Write()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *Client) Read() {
|
||||
if c.OnOpen != nil {
|
||||
c.OnOpen()
|
||||
}
|
||||
|
||||
c.conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
|
||||
for c.Connected {
|
||||
msgType, msg, err := c.conn.ReadMessage()
|
||||
c.conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
if err != nil {
|
||||
c.handleError(fmt.Errorf("read error (ip:%s): %w", c.ip, err))
|
||||
return
|
||||
}
|
||||
|
||||
switch msgType {
|
||||
case websocket.CloseMessage:
|
||||
c.Close(websocket.CloseNormalClosure, "Client closed")
|
||||
return
|
||||
case websocket.TextMessage:
|
||||
if c.OnMessage != nil {
|
||||
c.OnMessage(msg)
|
||||
} else {
|
||||
log.Printf("Received message but no handler set (ip:%s): %s", c.ip, string(msg))
|
||||
}
|
||||
default:
|
||||
log.Printf("Unhandled message type %d (ip:%s)", msgType, c.ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Write() {
|
||||
defer c.conn.Close()
|
||||
|
||||
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
for {
|
||||
select {
|
||||
case message, ok := <-c.send:
|
||||
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if !ok {
|
||||
// The hub closed the channel.
|
||||
if err := c.conn.WriteMessage(websocket.CloseMessage, []byte("ping")); err != nil {
|
||||
c.handleError(err)
|
||||
return
|
||||
}
|
||||
c.handleError(fmt.Errorf("server %s closed channel", c.ip))
|
||||
return
|
||||
} else {
|
||||
if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil {
|
||||
c.handleError(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
case message := <-c.unregister:
|
||||
c.conn.WriteMessage(websocket.CloseMessage, message)
|
||||
c.Connected = false
|
||||
close(c.send)
|
||||
close(c.unregister)
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) SendRequest(req *json_dataModels.Request) error {
|
||||
if !c.Connected {
|
||||
return nil
|
||||
}
|
||||
|
||||
data, err := json.Marshal(*req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.send <- data
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) ReadJsonData(data []byte) (json_dataModels.Response, error) {
|
||||
var resp json_dataModels.Response
|
||||
err := json.Unmarshal(data, &resp)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// Close connection to websocket server
|
||||
func (c *Client) Close(code int, reason string) error {
|
||||
closeMsg := websocket.FormatCloseMessage(code, reason)
|
||||
select {
|
||||
case c.unregister <- closeMsg: // Attempt to send
|
||||
default: // If the channel is full, this runs
|
||||
return fmt.Errorf("attempt close client socket failed")
|
||||
}
|
||||
if c.OnClose != nil {
|
||||
c.OnClose(code, reason)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) handleError(err error) {
|
||||
if c.OnError != nil {
|
||||
c.OnError(err)
|
||||
}
|
||||
if err := c.Close(websocket.CloseInternalServerErr, err.Error()); err != nil {
|
||||
if c.OnError != nil {
|
||||
c.OnError(err)
|
||||
} else {
|
||||
log.Println("error:", err)
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user