Files
tecamino-dbm/dbm/subscribe.go
2025-04-29 08:31:06 +02:00

76 lines
1.7 KiB
Go

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) {
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()
for _, sub := range subs {
for _, dp := range d.DB.QueryDatapoints(sub.Depth, sub.Path) {
if sub.Driver != "" {
if dp.Drivers == nil || dp.Drivers[sub.Driver] == nil {
continue
}
}
dp.AddSubscribtion(id, sub)
response.AddSubscription(json_dataModels.Subscribe{
Uuid: dp.Uuid,
Path: dp.Path,
Value: dp.Value,
Driver: sub.Driver,
Drivers: &dp.Drivers,
})
}
}
if err := wsjson.Write(client.Ctx, client.Conn, response); err != nil {
d.Log.Error("subscribe.Subscribe", err.Error())
}
}
func (d *DBMHandler) Unsubscribe(subs []json_dataModels.Subscribe, id 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()
for _, sub := range subs {
for _, dp := range d.DB.QueryDatapoints(sub.Depth, sub.Path) {
if _, ok := dp.Subscriptions[id]; !ok {
continue
}
dp.RemoveSubscribtion(id)
response.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())
}
}