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 }