Files
tecamino-driver-artNet/client/client.go
Adrian Zürcher b5d9d96c52 add resubscribe (in progress)
fix crash when no bus found in map
2025-05-28 22:00:04 +02:00

72 lines
1.7 KiB
Go

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
}
// Connect to websocket server
// ip: ip address of server
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
}
// Close connection to websocket server
func (c *Client) Disconnect() {
c.cancel()
}
// Subscribe to websocket server
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
}