10 Commits

Author SHA1 Message Date
Adrian Zuercher
ede86b71ef repo name change
All checks were successful
Build ArtNet Driver / build (amd64, , linux) (push) Successful in 1m40s
Build ArtNet Driver / build (amd64, .exe, windows) (push) Successful in 1m41s
Build ArtNet Driver / build (arm, 6, , linux) (push) Successful in 1m39s
Build ArtNet Driver / build (arm64, , linux) (push) Successful in 1m38s
2025-08-06 22:41:34 +02:00
Adrian Zuercher
67f25c76ae rename folder .github t .gitea
Some checks failed
Build Go Binaries / build (arm, linux) (push) Has been cancelled
Build Go Binaries / build (arm64, linux) (push) Has been cancelled
Build Go Binaries / build (amd64, linux) (push) Has been cancelled
Build Go Binaries / build (amd64, windows) (push) Has been cancelled
2025-08-02 09:58:12 +02:00
Adrian Zuercher
7ef6e614cc update to newest json_data model 2025-07-31 12:27:53 +02:00
Adrian Zuercher
49dff4f609 update json_data and model so more than one address can be revieved from server 2025-07-30 17:16:50 +02:00
Adrian Zuercher
3704edebd5 fix wrong call and missing send set 2025-07-27 13:07:16 +02:00
Adrian Zuercher
a503b71fb6 add read write lock to dmx data 2025-07-26 07:18:26 +02:00
Adrian Zuercher
05409c2544 change send data to dmx as 23 millisecond ticker when new data 2025-07-25 22:37:35 +02:00
Adrian Zuercher
b484745ed1 increase timeout of ping from 10 to 40 2025-07-25 20:59:17 +02:00
Adrian Zuercher
04e306c6da update to latest json_data 2025-07-24 09:57:16 +02:00
Adrian Zuercher
239e0050a1 change ping pong handler and fix blocking channel 2025-07-23 08:56:43 +02:00
14 changed files with 226 additions and 159 deletions

View File

@@ -0,0 +1,89 @@
name: Build ArtNet Driver
on:
push:
tags:
- '*'
env:
APP_NAME: tecamino-driver-artNet
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- os: windows
arch: amd64
ext: .exe
- os: linux
arch: amd64
ext: ""
- os: linux
arch: arm64
ext: ""
- os: linux
arch: arm
arm_version: 6
ext: ""
steps:
- uses: actions/checkout@v4
- name: Ensure latest Go is installed in /data/go
run: |
export GOROOT=/data/go/go
export PATH=$GOROOT/bin:$PATH
export GOCACHE=/data/gocache
export GOMODCACHE=/data/gomodcache
mkdir -p $GOCACHE $GOMODCACHE
if [ ! -x "$GOROOT/bin/go" ]; then
echo "Go not found in $GOROOT, downloading latest stable..."
GO_VERSION=$(curl -s https://go.dev/VERSION?m=text | head -n1)
echo "Latest version is $GO_VERSION"
mkdir -p /data/go
curl -sSL "https://go.dev/dl/${GO_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz
tar -C /data/go -xzf /tmp/go.tar.gz
else
echo "Using cached Go from $GOROOT"
fi
go version
- name: Download Go dependencies
run: |
export GOROOT=/data/go/go
export PATH=$GOROOT/bin:$PATH
export GOCACHE=/data/gocache
export GOMODCACHE=/data/gomodcache
mkdir -p $GOCACHE $GOMODCACHE
go mod download
- name: Build binary
run: |
export GOROOT=/data/go/go
export PATH=$GOROOT/bin:$PATH
export GOCACHE=/data/gocache
export GOMODCACHE=/data/gomodcache
mkdir -p $GOCACHE $GOMODCACHE
OUTPUT="bin/${APP_NAME}-${{ matrix.os }}-${{ matrix.arch }}"
if [ -n "${{ matrix.arm_version }}" ]; then
OUTPUT="${OUTPUT}v${{ matrix.arm_version }}"
export GOARM=${{ matrix.arm_version }}
fi
OUTPUT="${OUTPUT}${{ matrix.ext }}"
echo "Building $OUTPUT"
GOOS=${{ matrix.os }} GOARCH=${{ matrix.arch }} go build -ldflags="-s -w" -trimpath -o "$OUTPUT"
shell: bash
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: ${{ env.APP_NAME }}-${{ matrix.os }}-${{ matrix.arch }}
path: bin/

View File

@@ -1,48 +0,0 @@
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/

View File

@@ -8,8 +8,8 @@ import (
"fmt" "fmt"
"path" "path"
json_data "github.com/tecamino/tecamino-json_data" json_data "gitea.tecamino.com/paadi/tecamino-json_data"
"github.com/tecamino/tecamino-logger/logging" "gitea.tecamino.com/paadi/tecamino-logger/logging"
) )
type ArtNetDriver struct { type ArtNetDriver struct {
@@ -78,10 +78,10 @@ func (d *ArtNetDriver) SetValue(bus string, address uint, value uint8) error {
if _, ok := d.Buses[bus]; !ok { if _, ok := d.Buses[bus]; !ok {
return fmt.Errorf("no bus '%s' found", bus) return fmt.Errorf("no bus '%s' found", bus)
} }
if d.Buses[bus].Data == nil { if d.Buses[bus].DMX.Data == nil {
return fmt.Errorf("no dmx data on bus '%s' found", bus) return fmt.Errorf("no dmx data on bus '%s' found", bus)
} }
d.Buses[bus].Data.SetValue(address, value) d.Buses[bus].SetDMXData(address, value)
return nil return nil
} }
@@ -102,15 +102,17 @@ func (d *ArtNetDriver) Connect(ip, id string, port uint) error {
} }
client.OnMessage = func(data []byte) { client.OnMessage = func(data []byte) {
request := json_data.NewResponse() request := json_data.NewResponse()
err = json.Unmarshal(data, &request) err = json.Unmarshal(data, &request)
if err != nil { if err != nil {
return return
} }
if request.Subscribe != nil { if request.Subscribe != nil {
d.Subscribe(request.Subscribe...) d.Subscribe(request.Subscribe...)
} }
if request.Publish != nil { if request.Publish != nil {
d.Publish(request.Publish...) d.Publish(request.Publish...)
} }
@@ -138,6 +140,6 @@ func (d *ArtNetDriver) Connect(ip, id string, port uint) error {
// send data to all buses that the send flage is true // send data to all buses that the send flage is true
func (d *ArtNetDriver) SendData() { func (d *ArtNetDriver) SendData() {
for _, bus := range d.Buses { for _, bus := range d.Buses {
bus.Send <- bus.Data bus.Send = bus.Reachable
} }
} }

View File

@@ -7,9 +7,9 @@ import (
"net" "net"
"net/http" "net/http"
json_data "gitea.tecamino.com/paadi/tecamino-json_data"
json_dataModels "gitea.tecamino.com/paadi/tecamino-json_data/models"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
json_data "github.com/tecamino/tecamino-json_data"
json_dataModels "github.com/tecamino/tecamino-json_data/models"
) )
// sends a list of all buses in the driver // sends a list of all buses in the driver

View File

@@ -1,7 +1,7 @@
package driver package driver
import ( import (
json_dataModels "github.com/tecamino/tecamino-json_data/models" json_dataModels "gitea.tecamino.com/paadi/tecamino-json_data/models"
) )
func (d *ArtNetDriver) Publish(pubs ...json_dataModels.Publish) error { func (d *ArtNetDriver) Publish(pubs ...json_dataModels.Publish) error {
@@ -10,8 +10,12 @@ func (d *ArtNetDriver) Publish(pubs ...json_dataModels.Publish) error {
} }
for _, pub := range pubs { for _, pub := range pubs {
if drv, ok := (d.Subscriptions)[pub.Uuid]; ok { if subs, ok := (d.Subscriptions)[pub.Uuid]; ok {
d.SetValue(drv.Bus, drv.Address, uint8(pub.Value.(float64))) for _, sub := range subs {
for _, address := range sub.Address {
d.SetValue(sub.Bus, address, uint8(pub.Value.(float64)))
}
}
} }
} }
d.SendData() d.SendData()

View File

@@ -3,7 +3,7 @@ package driver
import ( import (
"artNet/models" "artNet/models"
json_dataModels "github.com/tecamino/tecamino-json_data/models" json_dataModels "gitea.tecamino.com/paadi/tecamino-json_data/models"
) )
func (d *ArtNetDriver) Subscribe(subs ...json_dataModels.Subscription) { func (d *ArtNetDriver) Subscribe(subs ...json_dataModels.Subscription) {
@@ -14,7 +14,12 @@ func (d *ArtNetDriver) Subscribe(subs ...json_dataModels.Subscription) {
for _, sub := range subs { for _, sub := range subs {
if drv, ok := (*sub.Drivers)[sub.Driver]; ok { if drv, ok := (*sub.Drivers)[sub.Driver]; ok {
d.Subscriptions.AddSubscription(sub.Uuid, drv) 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() d.SendData()

4
go.mod
View File

@@ -5,12 +5,12 @@ go 1.23.0
toolchain go1.23.8 toolchain go1.23.8
require ( require (
gitea.tecamino.com/paadi/tecamino-json_data v0.1.0
gitea.tecamino.com/paadi/tecamino-logger v0.2.1
github.com/gin-gonic/gin v1.10.0 github.com/gin-gonic/gin v1.10.0
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3 github.com/gorilla/websocket v1.5.3
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e
github.com/tecamino/tecamino-json_data v0.0.16
github.com/tecamino/tecamino-logger v0.2.0
gopkg.in/yaml.v3 v3.0.1 gopkg.in/yaml.v3 v3.0.1
) )

8
go.sum
View File

@@ -1,3 +1,7 @@
gitea.tecamino.com/paadi/tecamino-json_data v0.1.0 h1:zp3L8qUvkVqzuesQdMh/SgZZZbX3pGD9NYa6jtz+JvA=
gitea.tecamino.com/paadi/tecamino-json_data v0.1.0/go.mod h1:/FKhbVYuhiNlQp4552rJJQIhynjLarDzfrgXpupkwZU=
gitea.tecamino.com/paadi/tecamino-logger v0.2.1 h1:sQTBKYPdzn9mmWX2JXZBtGBvNQH7cuXIwsl4TD0aMgE=
gitea.tecamino.com/paadi/tecamino-logger v0.2.1/go.mod h1:FkzRTldUBBOd/iy2upycArDftSZ5trbsX5Ira5OzJgM=
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
@@ -65,10 +69,6 @@ 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/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 h1:nt2877sKfojlHCTOBXbpWjBkuWKritFaGIfgQwbQUls=
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e/go.mod h1:B4+Kq1u5FlULTjFSM707Q6e/cOHFv0z/6QRoxubDIQ8= 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.16 h1:aZFxnhm4g6WMDPoqy4HosUk7vl0DB0iIcVs8bbT4MzU=
github.com/tecamino/tecamino-json_data v0.0.16/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= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=

View File

@@ -75,6 +75,7 @@ func main() {
if err := artNetDriver.Connect(*serverIp, DriverName, *serverPort); err != nil { if err := artNetDriver.Connect(*serverIp, DriverName, *serverPort); err != nil {
artNetDriver.Log.Error("main", err) artNetDriver.Log.Error("main", err)
} }
artNetDriver.Log.Info("main", "next reconnecting attempt in 10 seconds") artNetDriver.Log.Info("main", "next reconnecting attempt in 10 seconds")
time.Sleep(10 * time.Second) time.Sleep(10 * time.Second)
} }

View File

@@ -6,13 +6,14 @@ import (
"fmt" "fmt"
"net" "net"
"net/http" "net/http"
"sync"
"time" "time"
json_data "gitea.tecamino.com/paadi/tecamino-json_data"
json_dataModels "gitea.tecamino.com/paadi/tecamino-json_data/models"
"gitea.tecamino.com/paadi/tecamino-logger/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/tatsushid/go-fastping" "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"
) )
// Art-Net constants // Art-Net constants
@@ -25,11 +26,12 @@ type Bus struct {
Name string `yaml:"name" json:"name"` Name string `yaml:"name" json:"name"`
Ip string `yaml:"ip" json:"ip"` Ip string `yaml:"ip" json:"ip"`
Port *int `yaml:"port" json:"port,omitempty"` Port *int `yaml:"port" json:"port,omitempty"`
Data *DMX `yaml:"-" json:"-"` DMX *DMX `yaml:"-" json:"-"`
Resubscribe *[]json_dataModels.Subscription `yaml:"-" json:"resubscribe"` Resubscribe *[]json_dataModels.Subscription `yaml:"-" json:"resubscribe"`
Watchdog context.CancelFunc `yaml:"-" json:"-"` Watchdog context.CancelFunc `yaml:"-" json:"-"`
mu sync.Mutex `yaml:"-" json:"-"`
Reachable bool `yaml:"-" json:"-"` Reachable bool `yaml:"-" json:"-"`
Send chan *DMX `yaml:"-" json:"-"` Send bool `yaml:"-" json:"-"`
} }
// adds new Art-Net interface to driver port 0 = 6454 (default art-net) // adds new Art-Net interface to driver port 0 = 6454 (default art-net)
@@ -42,7 +44,7 @@ func NewBus(name, ip string, port int) *Bus {
Name: name, Name: name,
Ip: ip, Ip: ip,
Port: &port, Port: &port,
Data: NewDMXUniverse(), DMX: NewDMXUniverse(),
} }
return &i return &i
} }
@@ -90,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 { if err != nil {
return err return err
} }
@@ -107,8 +109,6 @@ func (b *Bus) Start(log *logging.Logger) error {
var ctx context.Context var ctx context.Context
ctx, b.Watchdog = context.WithCancel(context.Background()) ctx, b.Watchdog = context.WithCancel(context.Background())
b.Send = make(chan *DMX, 1024)
go func() { go func() {
var interval time.Duration = 10 * time.Second var interval time.Duration = 10 * time.Second
log.Info("bus.Start", fmt.Sprintf("device:%s ip:%s watchdog starting", b.Name, b.Ip)) log.Info("bus.Start", fmt.Sprintf("device:%s ip:%s watchdog starting", b.Name, b.Ip))
@@ -129,7 +129,7 @@ func (b *Bus) Start(log *logging.Logger) error {
} else { } else {
b.Reachable = true b.Reachable = true
// send data as a heartbeat for she ArtNet Protocol // send data as a heartbeat for she ArtNet Protocol
b.Send <- b.Data b.Send = true
log.Info("bus.Start", fmt.Sprintf("device:%s ip:%s watchdog running", b.Name, b.Ip)) log.Info("bus.Start", fmt.Sprintf("device:%s ip:%s watchdog running", b.Name, b.Ip))
interval = 30 * time.Second interval = 30 * time.Second
} }
@@ -148,18 +148,34 @@ func (b *Bus) Start(log *logging.Logger) error {
} }
go func() { go func() {
defer conn.Close() ticker := time.NewTicker(23 * time.Millisecond)
//close send channel
defer close(b.Send)
for send := range b.Send { defer func() {
_, err = conn.Write(NewArtNetPackage(send)) 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 { if err != nil {
log.Error("bus.Start", err) log.Error("bus.Start", err)
return return
} }
time.Sleep(23 * time.Millisecond)
} }
}() }()
return nil return nil
} }
@@ -169,8 +185,8 @@ func (b *Bus) Stop() {
if b.Watchdog != nil { if b.Watchdog != nil {
//cancels context //cancels context
b.Watchdog() b.Watchdog()
//close send channel
close(b.Send) b.Send = false
} }
} }
@@ -199,6 +215,13 @@ func (b *Bus) ParsePayload(c *gin.Context) error {
return nil 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) { func isUDPReachable(ip string) (recieved bool, err error) {
p := fastping.NewPinger() p := fastping.NewPinger()
ra, err := net.ResolveIPAddr("ip4:icmp", ip) ra, err := net.ResolveIPAddr("ip4:icmp", ip)

View File

@@ -1,12 +1,29 @@
package models package models
type DMX []byte import (
"sync"
)
type DMX struct {
Data []byte
mu sync.Mutex
}
func NewDMXUniverse() *DMX { 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) { func (d *DMX) SetValue(channel uint, value uint8) {
(*d)[channel] = value d.mu.Lock()
d.Data[channel] = value
d.mu.Unlock()
} }

View File

@@ -23,7 +23,7 @@ func NewArtNetPackage(data *DMX) Package {
packet.WriteByte(0x00) // Sequence packet.WriteByte(0x00) // Sequence
packet.WriteByte(0x00) // Physical packet.WriteByte(0x00) // Physical
binary.Write(packet, binary.BigEndian, uint16(0)) // Universe (net:subuni, usually 0) binary.Write(packet, binary.BigEndian, uint16(0)) // Universe (net:subuni, usually 0)
binary.Write(packet, binary.BigEndian, uint16(len(*data))) // Length binary.Write(packet, binary.BigEndian, uint16(len(data.Data))) // Length
packet.Write(*data) packet.Write(data.Data)
return packet.Bytes() return packet.Bytes()
} }

View File

@@ -1,15 +1,15 @@
package models package models
import ( import (
json_dataModels "gitea.tecamino.com/paadi/tecamino-json_data/models"
"github.com/google/uuid" "github.com/google/uuid"
json_dataModels "github.com/tecamino/tecamino-json_data/models"
) )
type Subscriptions map[uuid.UUID]Subscription type Subscriptions map[uuid.UUID][]Subscription
type Subscription struct { type Subscription struct {
Bus string Bus string
Address uint Address []uint
} }
func NewSubscriptions() Subscriptions { func NewSubscriptions() Subscriptions {
@@ -17,8 +17,11 @@ func NewSubscriptions() Subscriptions {
} }
func (s *Subscriptions) AddSubscription(uid uuid.UUID, drv *json_dataModels.Driver) { func (s *Subscriptions) AddSubscription(uid uuid.UUID, drv *json_dataModels.Driver) {
(*s)[uid] = Subscription{ subs := []Subscription{}
Bus: drv.Bus, for _, bus := range drv.Buses {
Address: drv.Address, sub := Subscription{Bus: bus.Name}
sub.Address = append(sub.Address, bus.Address...)
subs = append(subs, sub)
} }
(*s)[uid] = subs
} }

View File

@@ -6,19 +6,16 @@ import (
"log" "log"
"time" "time"
json_dataModels "gitea.tecamino.com/paadi/tecamino-json_data/models"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
json_dataModels "github.com/tecamino/tecamino-json_data/models"
) )
const ( const (
// Time allowed to write a message to the peer. // Time allowed to write a message to the peer.
writeWait = 10 * time.Second writeWait = 40 * time.Second
// Time allowed to read the next pong message from the peer. // Time allowed to read the next pong message from the peer.
pongWait = 10 * time.Second pongWait = 40 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
) )
type Client struct { type Client struct {
@@ -32,7 +29,6 @@ type Client struct {
OnError func(err error) OnError func(err error)
OnPing func() OnPing func()
OnPong func() OnPong func()
sendPong chan string
send chan []byte send chan []byte
unregister chan []byte unregister chan []byte
} }
@@ -45,9 +41,8 @@ func NewClient(ip, id string, port uint) (*Client, error) {
ip: ip, ip: ip,
port: port, port: port,
Connected: true, Connected: true,
sendPong: make(chan string), send: make(chan []byte, 256),
send: make(chan []byte), unregister: make(chan []byte, 256),
unregister: make(chan []byte),
} }
dialer := websocket.DefaultDialer dialer := websocket.DefaultDialer
@@ -65,13 +60,16 @@ func NewClient(ip, id string, port uint) (*Client, error) {
if c.OnPing != nil { if c.OnPing != nil {
c.OnPing() c.OnPing()
} }
conn.SetWriteDeadline(time.Now().Add(writeWait)) conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetReadDeadline(time.Now().Add(writeWait)) conn.SetWriteDeadline(time.Now().Add(pongWait))
c.sendPong <- appData if err := conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(2*pongWait)); err != nil {
c.OnError(err)
return err
}
return nil return nil
}) })
conn.SetPongHandler(func(string) error { conn.SetPongHandler(func(appData string) error {
conn.SetReadDeadline(time.Now().Add(pongWait)) conn.SetReadDeadline(time.Now().Add(pongWait))
if c.OnPong != nil { if c.OnPong != nil {
c.OnPong() c.OnPong()
@@ -79,17 +77,6 @@ func NewClient(ip, id string, port uint) (*Client, error) {
return nil return nil
}) })
conn.SetCloseHandler(func(code int, text string) error {
if c.OnClose != nil {
c.OnClose(code, text)
}
return nil
})
if c.OnOpen != nil {
c.OnOpen()
}
// Start reading messages from client // Start reading messages from client
go c.Read() go c.Read()
go c.Write() go c.Write()
@@ -101,13 +88,16 @@ func (c *Client) Read() {
c.OnOpen() c.OnOpen()
} }
c.conn.SetReadDeadline(time.Now().Add(writeWait)) c.conn.SetReadDeadline(time.Now().Add(pongWait))
for c.Connected { for c.Connected {
msgType, msg, err := c.conn.ReadMessage() msgType, msg, err := c.conn.ReadMessage()
c.conn.SetReadDeadline(time.Now().Add(pongWait))
if err != nil { if err != nil {
c.handleError(fmt.Errorf("read error (id:%s:%d): %w", c.ip, c.port, err)) c.handleError(fmt.Errorf("read error (ip:%s): %w", c.ip, err))
return return
} }
switch msgType { switch msgType {
case websocket.CloseMessage: case websocket.CloseMessage:
c.Close(websocket.CloseNormalClosure, "Client closed") c.Close(websocket.CloseNormalClosure, "Client closed")
@@ -116,32 +106,29 @@ func (c *Client) Read() {
if c.OnMessage != nil { if c.OnMessage != nil {
c.OnMessage(msg) c.OnMessage(msg)
} else { } else {
log.Printf("Received message but no handler set (id:%s:%d): %s", c.ip, c.port, string(msg)) log.Printf("Received message but no handler set (ip:%s): %s", c.ip, string(msg))
} }
default: default:
log.Printf("Unhandled message type %d (id:%s:%d)", msgType, c.ip, c.port) log.Printf("Unhandled message type %d (ip:%s)", msgType, c.ip)
} }
} }
} }
func (c *Client) Write() { func (c *Client) Write() {
ticker := time.NewTicker(pingPeriod) defer c.conn.Close()
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
for {
select { select {
case message, ok := <-c.send: case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok { if !ok {
// The hub closed the channel. // The hub closed the channel.
if err := c.conn.WriteMessage(websocket.CloseMessage, []byte{}); err != nil { if err := c.conn.WriteMessage(websocket.CloseMessage, []byte("ping")); err != nil {
c.handleError(err) c.handleError(err)
return return
} }
c.handleError(fmt.Errorf("server %s:%d closed channel", c.ip, c.port)) c.handleError(fmt.Errorf("server %s closed channel", c.ip))
return return
} else { } else {
if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil { if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil {
@@ -149,26 +136,10 @@ func (c *Client) Write() {
return return
} }
} }
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
c.handleError(err)
return
}
if c.OnPing != nil {
c.OnPing()
}
case message, ok := <-c.sendPong:
if ok {
c.conn.WriteMessage(websocket.PongMessage, []byte(message))
}
case message := <-c.unregister: case message := <-c.unregister:
c.conn.WriteMessage(websocket.CloseMessage, message) c.conn.WriteMessage(websocket.CloseMessage, message)
c.Connected = false c.Connected = false
close(c.send) close(c.send)
close(c.sendPong)
close(c.unregister) close(c.unregister)
return return
} }
@@ -217,7 +188,7 @@ func (c *Client) handleError(err error) {
if c.OnError != nil { if c.OnError != nil {
c.OnError(err) c.OnError(err)
} else { } else {
fmt.Println("error: ", err) log.Println("error:", err)
} }
} }
} }