abstract write to websocket and add request id

This commit is contained in:
Adrian Zürcher
2025-05-01 12:51:35 +02:00
parent 8e6b39c8bf
commit 4b36598bd7
4 changed files with 107 additions and 27 deletions

View File

@@ -1,24 +1,18 @@
package dbm
import (
"github.com/coder/websocket/wsjson"
json_dataModels "github.com/tecamino/tecamino-json_data/models"
)
func (d *DBMHandler) Subscribe(subs []json_dataModels.Subscribe, id string) {
func (d *DBMHandler) Subscribe(subs []json_dataModels.Subscribe, id, id2 string) {
if subs == nil {
return
}
d.RLock()
defer d.RUnlock()
client, ok := d.Conns.Clients[id]
if !ok {
d.Log.Error("subscribe.Subscribe", "client not found for id "+id)
return
}
response := json_dataModels.NewResponse()
r := json_dataModels.NewResponse()
r.Id = id2
for _, sub := range subs {
for _, dp := range d.DB.QueryDatapoints(sub.Depth, sub.Path) {
@@ -28,7 +22,7 @@ func (d *DBMHandler) Subscribe(subs []json_dataModels.Subscribe, id string) {
}
}
dp.AddSubscribtion(id, sub)
response.AddSubscription(json_dataModels.Subscribe{
r.AddSubscription(json_dataModels.Subscribe{
Uuid: dp.Uuid,
Path: dp.Path,
Value: dp.Value,
@@ -37,7 +31,8 @@ func (d *DBMHandler) Subscribe(subs []json_dataModels.Subscribe, id string) {
})
}
}
if err := wsjson.Write(client.Ctx, client.Conn, response); err != nil {
if err := d.Conns.SendResponse(id, r); err != nil {
d.Log.Error("subscribe.Subscribe", err.Error())
}
}
@@ -49,13 +44,7 @@ func (d *DBMHandler) Unsubscribe(subs []json_dataModels.Subscribe, id string) {
d.RLock()
defer d.RUnlock()
client, ok := d.Conns.Clients[id]
if !ok {
d.Log.Error("subscribe.Subscribe", "client not found for id "+id)
return
}
response := json_dataModels.NewResponse()
r := json_dataModels.NewResponse()
for _, sub := range subs {
for _, dp := range d.DB.QueryDatapoints(sub.Depth, sub.Path) {
@@ -63,13 +52,14 @@ func (d *DBMHandler) Unsubscribe(subs []json_dataModels.Subscribe, id string) {
continue
}
dp.RemoveSubscribtion(id)
response.AddUnsubscription(json_dataModels.Subscribe{
r.AddUnsubscription(json_dataModels.Subscribe{
Uuid: dp.Uuid,
Path: dp.Path,
})
}
}
if err := wsjson.Write(client.Ctx, client.Conn, response); err != nil {
d.Log.Error("subscribe.Subscribe", err.Error())
if err := d.Conns.SendResponse(id, r); err != nil {
d.Log.Error("subscribe.Unsubscribe", err.Error())
}
}