implement new json_data model

This commit is contained in:
Adrian Zürcher
2025-04-29 08:34:51 +02:00
parent f5e66af3d8
commit 2839b615c3
9 changed files with 176 additions and 59 deletions

66
client/client.go Normal file
View File

@@ -0,0 +1,66 @@
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
}