Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc2e582203 | ||
|
|
21e4231e24 | ||
|
|
b21101958d | ||
|
|
c3a3060129 | ||
|
|
a23f82e9fe | ||
|
|
c37dd87a37 | ||
|
|
8be5c80a22 | ||
|
|
47a065aaf9 | ||
|
|
5e1e4b9daf | ||
|
|
0f06128ce8 | ||
|
|
be07dc8749 | ||
|
|
e75d7c8b03 | ||
|
|
59c7705ca1 | ||
|
|
91ea59ed6e | ||
|
|
659cbe4072 |
4
.github/workflows/build.yml
vendored
4
.github/workflows/build.yml
vendored
@@ -36,9 +36,9 @@ jobs:
|
||||
run: |
|
||||
mkdir -p build
|
||||
if [ "${{ matrix.goos }}" == "windows" ]; then
|
||||
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -o build/tecamino-dbm-${{ matrix.goos }}-${{ matrix.goarch }}.exe main.go
|
||||
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -ldflags="-s -w" -trimpath -o build/tecamino-dbm-${{ matrix.goos }}-${{ matrix.goarch }}.exe main.go
|
||||
else
|
||||
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -o build/tecamino-dbm-${{ matrix.goos }}-${{ matrix.goarch }} main.go
|
||||
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -ldflags="-s -w" -trimpath -o build/tecamino-dbm-${{ matrix.goos }}-${{ matrix.goarch }} main.go
|
||||
fi
|
||||
|
||||
- name: Upload artifacts
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,3 +1,6 @@
|
||||
.DS_Store
|
||||
*.dbm
|
||||
*.log
|
||||
|
||||
# local executables
|
||||
dbm-arm64
|
||||
|
||||
18
args/args.go
18
args/args.go
@@ -2,7 +2,6 @@ package args
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"strings"
|
||||
|
||||
"github.com/tecamino/tecamino-dbm/cert"
|
||||
"github.com/tecamino/tecamino-dbm/models"
|
||||
@@ -19,21 +18,10 @@ type Args struct {
|
||||
Debug bool
|
||||
}
|
||||
|
||||
type StringSlice []string
|
||||
|
||||
func (s *StringSlice) String() string {
|
||||
return strings.Join(*s, ",")
|
||||
}
|
||||
|
||||
func (s *StringSlice) Set(value string) error {
|
||||
*s = append(*s, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
// initialte cli arguments
|
||||
func Init() *Args {
|
||||
|
||||
var allowOrigins StringSlice
|
||||
var allowOrigins models.StringSlice
|
||||
|
||||
flag.Var(&allowOrigins, "allowOrigin", "Allowed origin (can repeat this flag)")
|
||||
|
||||
@@ -43,6 +31,7 @@ func Init() *Args {
|
||||
keyFile := flag.String("keyFile", "./cert/key.pem", "path of keyfile")
|
||||
portHttp := flag.Uint("http-port", 8100, "json server communication for http/ws")
|
||||
portHttps := flag.Uint("https-port", 8101, "json server communication for http/wss")
|
||||
remotePort := flag.Uint("remotePort", 9500, "remote Port of gui user interface")
|
||||
rootDir := flag.String("workingDir", "./", "working directory")
|
||||
dbmFile := flag.String("dbm", "/test/test", "dbm file name")
|
||||
debug := flag.Bool("debug", false, "debug flag")
|
||||
@@ -58,6 +47,7 @@ func Init() *Args {
|
||||
Port: models.Port{
|
||||
Http: *portHttp,
|
||||
Https: *portHttps,
|
||||
Remote: *remotePort,
|
||||
},
|
||||
RootDir: *rootDir,
|
||||
DBMFile: *dbmFile,
|
||||
@@ -65,7 +55,7 @@ func Init() *Args {
|
||||
}
|
||||
|
||||
if len(allowOrigins) == 0 {
|
||||
allowOrigins = StringSlice{"http://localhost:9500"}
|
||||
allowOrigins = models.StringSlice{"http://localhost:9500"}
|
||||
}
|
||||
|
||||
a.AllowOrigins = allowOrigins
|
||||
|
||||
@@ -11,13 +11,13 @@ import (
|
||||
|
||||
"github.com/tecamino/tecamino-dbm/args"
|
||||
"github.com/tecamino/tecamino-dbm/models"
|
||||
serverModels "github.com/tecamino/tecamino-dbm/server/models"
|
||||
ws "github.com/tecamino/tecamino-dbm/websocket"
|
||||
"github.com/tecamino/tecamino-logger/logging"
|
||||
)
|
||||
|
||||
type DBMHandler struct {
|
||||
DBM *models.DBM
|
||||
Conns *serverModels.Connections
|
||||
Conns *ws.ClientHandler
|
||||
sync.RWMutex
|
||||
Log *logging.Logger
|
||||
arg *args.Args
|
||||
@@ -43,7 +43,7 @@ func NewDbmHandler(a *args.Args) (*DBMHandler, error) {
|
||||
logger.Info("main", "start dma handler")
|
||||
|
||||
//initialize connection map
|
||||
conns := serverModels.NewConnections()
|
||||
conns := ws.NewConnectionHandler()
|
||||
|
||||
// Initialize dtabase manager handler
|
||||
dmaHandler := DBMHandler{
|
||||
@@ -74,8 +74,8 @@ func NewDbmHandler(a *args.Args) (*DBMHandler, error) {
|
||||
var line int
|
||||
for scanner.Scan() {
|
||||
line++
|
||||
dp := models.Datapoint{}
|
||||
if err = json.Unmarshal(scanner.Bytes(), &dp); err != nil {
|
||||
dp := &models.Datapoint{}
|
||||
if err = json.Unmarshal(scanner.Bytes(), dp); err != nil {
|
||||
dmaHandler.Log.Error("dmbHandler.NewDmbHandler", "error in line "+fmt.Sprint(line)+" "+scanner.Text())
|
||||
dmaHandler.Log.Error("dmbHandler.NewDmbHandler", err.Error())
|
||||
|
||||
|
||||
@@ -29,12 +29,14 @@ func (d *DBMHandler) Json_Data(c *gin.Context) {
|
||||
if get.Query != nil {
|
||||
depth = get.Query.Depth
|
||||
}
|
||||
|
||||
for _, res := range d.DBM.QueryDatapoints(depth, get.Uuid, get.Path) {
|
||||
resp.AddGet(json_dataModels.Get{
|
||||
Uuid: res.Uuid,
|
||||
Path: res.Path,
|
||||
Type: res.Type,
|
||||
Value: res.Value,
|
||||
Drivers: &res.Drivers,
|
||||
HasChild: res.Datapoints != nil,
|
||||
Rights: res.ReadWrite,
|
||||
})
|
||||
@@ -67,9 +69,7 @@ func (d *DBMHandler) Delete(c *gin.Context) {
|
||||
}
|
||||
|
||||
response := json_data.NewResponse()
|
||||
|
||||
if payload.Set != nil {
|
||||
|
||||
response.Set, err = d.DBM.RemoveDatapoint(payload.Set...)
|
||||
if err != nil {
|
||||
r := json_data.NewResponse()
|
||||
|
||||
@@ -20,6 +20,7 @@ func (d *DBMHandler) Set(req *json_dataModels.Request, id string) {
|
||||
|
||||
for _, set := range req.Set {
|
||||
dps := d.DBM.QueryDatapoints(1, set.Uuid, set.Path)
|
||||
|
||||
if len(dps) == 0 {
|
||||
resp.SetError()
|
||||
if resp.Message == "" {
|
||||
@@ -27,8 +28,10 @@ func (d *DBMHandler) Set(req *json_dataModels.Request, id string) {
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
for _, dp := range dps {
|
||||
dp.UpdateValue(d.Conns, set.Value)
|
||||
dp.UpdateValue(set.Value)
|
||||
|
||||
resp.AddSet(json_dataModels.Set{
|
||||
Uuid: dp.Uuid,
|
||||
Path: dp.Path,
|
||||
@@ -36,6 +39,7 @@ func (d *DBMHandler) Set(req *json_dataModels.Request, id string) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if err := d.Conns.SendResponse(id, resp); err != nil {
|
||||
d.Log.Error("get.Set", err.Error())
|
||||
}
|
||||
|
||||
@@ -36,18 +36,25 @@ func (d *DBMHandler) Subscribe(req *json_dataModels.Request, id string) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
dp.AddSubscribtion(id, sub)
|
||||
|
||||
client := d.DBM.Conns.GetClient(id)
|
||||
if client == nil {
|
||||
d.Log.Warning("subscribe", "id "+id+" not found")
|
||||
continue
|
||||
}
|
||||
|
||||
dp.AddSubscribtion(client, sub)
|
||||
resp.AddSubscription(json_dataModels.Subscription{
|
||||
Uuid: dp.Uuid,
|
||||
Path: dp.Path,
|
||||
Value: dp.Value,
|
||||
HasChild: dp.Datapoints != nil,
|
||||
Rights: dp.ReadWrite.GetRights(),
|
||||
Driver: sub.Driver,
|
||||
Drivers: &dp.Drivers,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if err := d.Conns.SendResponse(id, resp); err != nil {
|
||||
d.Log.Error("subscribe.Subscribe", err.Error())
|
||||
}
|
||||
@@ -68,10 +75,17 @@ func (d *DBMHandler) Unsubscribe(req *json_dataModels.Request, id string) {
|
||||
|
||||
for _, sub := range req.Unsubscribe {
|
||||
for _, dp := range d.DBM.QueryDatapoints(sub.Depth, sub.Uuid, sub.Path) {
|
||||
if _, ok := dp.Subscriptions[id]; !ok {
|
||||
|
||||
client := d.DBM.Conns.GetClient(id)
|
||||
if client == nil {
|
||||
d.Log.Warning("subscribe", "id "+id+" not found")
|
||||
continue
|
||||
}
|
||||
dp.RemoveSubscribtion(id)
|
||||
|
||||
if _, ok := dp.Subscriptions[client]; !ok {
|
||||
continue
|
||||
}
|
||||
dp.RemoveSubscribtion(client)
|
||||
resp.AddUnsubscription(json_dataModels.Subscription{
|
||||
Uuid: dp.Uuid,
|
||||
Path: dp.Path,
|
||||
|
||||
@@ -2,11 +2,7 @@ package dbm
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tecamino/tecamino-dbm/auth"
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
@@ -26,25 +22,19 @@ func (d *DBMHandler) WebSocket(c *gin.Context) {
|
||||
}
|
||||
d.Log.Debug("dbmHandler.webSocket.Websocket", "authorization id token: "+id)
|
||||
|
||||
err = d.Conns.ConnectRecievingWsConnection(id, c)
|
||||
defer d.Conns.RemoveClient(id)
|
||||
client, err := d.Conns.ConnectNewClient(id, c)
|
||||
if err != nil {
|
||||
d.Log.Error("dbmHandler.webSocket.Websocket", "error connecting recieving websocket conection: "+err.Error())
|
||||
d.Log.Error("dbmHandler.webSocket.Websocket", err)
|
||||
return
|
||||
}
|
||||
defer d.Conns.DisconnectWsConnection(id, websocket.StatusInternalError, "Internal error")
|
||||
|
||||
//Read loop
|
||||
for {
|
||||
|
||||
request, err := d.readJsonData(id)
|
||||
client.OnMessage = func(data []byte) {
|
||||
request, err := d.readJsonData(data)
|
||||
if err != nil {
|
||||
d.Log.Error("websocket.WebSocket", err.Error())
|
||||
break
|
||||
d.Log.Error("dbmHandler.webSocket.Websocket", "read json: "+err.Error())
|
||||
}
|
||||
|
||||
// Sets
|
||||
|
||||
d.Get(request, id)
|
||||
// Sets
|
||||
d.Set(request, id)
|
||||
@@ -54,48 +44,18 @@ func (d *DBMHandler) WebSocket(c *gin.Context) {
|
||||
|
||||
// Unsubscribe
|
||||
d.Unsubscribe(request, id)
|
||||
}
|
||||
|
||||
request.Get = make([]json_dataModels.Get, 0)
|
||||
request.Set = make([]json_dataModels.Set, 0)
|
||||
request.Subscribe = make([]json_dataModels.Subscription, 0)
|
||||
request.Unsubscribe = make([]json_dataModels.Subscription, 0)
|
||||
request = nil
|
||||
client.OnWarning = func(s string) {
|
||||
d.Log.Warning("dbmHandler.webSocket.Websocket", "warning on websocket connection: "+s)
|
||||
}
|
||||
|
||||
client.OnError = func(err error) {
|
||||
d.Log.Error("dbmHandler.webSocket.Websocket", "error on websocket connection: "+err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DBMHandler) readJsonData(id string) (request *json_dataModels.Request, err error) {
|
||||
|
||||
client, ok := d.Conns.Clients[id]
|
||||
if !ok {
|
||||
return request, errors.New("client id not found")
|
||||
}
|
||||
|
||||
_, reader, err := client.Conn.Reader(client.Ctx)
|
||||
if err != nil {
|
||||
d.Log.Info("webSocket.readJsonData", fmt.Sprintf("WebSocket reader: %v\n", err))
|
||||
return request, nil
|
||||
}
|
||||
|
||||
b, err := io.ReadAll(reader)
|
||||
|
||||
if err != nil {
|
||||
code := websocket.CloseStatus(err)
|
||||
|
||||
switch code {
|
||||
case websocket.StatusNormalClosure,
|
||||
websocket.StatusGoingAway,
|
||||
websocket.StatusNoStatusRcvd:
|
||||
d.Log.Info("webSocket.readJsonData", fmt.Sprintf("WebSocket closed: %v (code: %v)\n", err, code))
|
||||
return
|
||||
default:
|
||||
d.Log.Error("webSocket.readJsonData", fmt.Sprintf("WebSocket read error: %v (code: %v)\n", err, code))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(b, &request); err != nil {
|
||||
return request, err
|
||||
}
|
||||
|
||||
func (d *DBMHandler) readJsonData(data []byte) (request *json_dataModels.Request, err error) {
|
||||
err = json.Unmarshal(data, &request)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -3,5 +3,8 @@ package drivers
|
||||
type Drivers []Driver
|
||||
|
||||
type Driver interface {
|
||||
NewArtNetDriver(string)
|
||||
AddAddress()
|
||||
}
|
||||
|
||||
//func Add
|
||||
|
||||
4
go.mod
4
go.mod
@@ -3,11 +3,11 @@ module github.com/tecamino/tecamino-dbm
|
||||
go 1.24.0
|
||||
|
||||
require (
|
||||
github.com/coder/websocket v1.8.13
|
||||
github.com/gin-contrib/cors v1.7.5
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/tecamino/tecamino-json_data v0.0.15
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/tecamino/tecamino-json_data v0.0.31
|
||||
github.com/tecamino/tecamino-logger v0.2.0
|
||||
)
|
||||
|
||||
|
||||
8
go.sum
8
go.sum
@@ -6,8 +6,6 @@ github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFos
|
||||
github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
|
||||
github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
|
||||
github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
@@ -34,6 +32,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
@@ -71,8 +71,8 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/tecamino/tecamino-json_data v0.0.15 h1:r8S6Ls/MMKTdsqUWd3iVDW6Zm5I5H9UCqNAW9wid02E=
|
||||
github.com/tecamino/tecamino-json_data v0.0.15/go.mod h1:LLlyD7Wwqplb2BP4PeO86EokEcTRidlW5MwgPd1T2JY=
|
||||
github.com/tecamino/tecamino-json_data v0.0.31 h1:7zFbANj1Lihr64CCCh3O+9hxxsMcEPniRJZ5NgPrS5Y=
|
||||
github.com/tecamino/tecamino-json_data v0.0.31/go.mod h1:LLlyD7Wwqplb2BP4PeO86EokEcTRidlW5MwgPd1T2JY=
|
||||
github.com/tecamino/tecamino-logger v0.2.0 h1:NPH/Gg9qRhmVoW8b39i1eXu/LEftHc74nyISpcRG+XU=
|
||||
github.com/tecamino/tecamino-logger v0.2.0/go.mod h1:0M1E9Uei/qw3e3WA1x3lBo1eP3H5oeYE7GjYrMahnj8=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
|
||||
6
main.go
6
main.go
@@ -6,7 +6,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tecamino/tecamino-dbm/args"
|
||||
"github.com/tecamino/tecamino-dbm/dbm"
|
||||
"github.com/tecamino/tecamino-dbm/server"
|
||||
ws "github.com/tecamino/tecamino-dbm/websocket"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -18,12 +18,12 @@ func main() {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
//save database after exeutabe ends
|
||||
//save database after executabe ends
|
||||
defer dbmHandler.SaveDb()
|
||||
|
||||
//initialize new server
|
||||
dbmHandler.Log.Debug("main", "initialize new server instance")
|
||||
s := server.NewServer(a.AllowOrigins)
|
||||
s := ws.NewServer(a.AllowOrigins, a.Port.Remote)
|
||||
|
||||
//set routes
|
||||
dbmHandler.Log.Debug("main", "setting routes")
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
serverModels "github.com/tecamino/tecamino-dbm/server/models"
|
||||
"github.com/tecamino/tecamino-dbm/utils"
|
||||
ws "github.com/tecamino/tecamino-dbm/websocket"
|
||||
wsModels "github.com/tecamino/tecamino-dbm/websocket/models"
|
||||
json_data "github.com/tecamino/tecamino-json_data"
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
)
|
||||
@@ -21,16 +22,17 @@ const (
|
||||
)
|
||||
|
||||
type Datapoint struct {
|
||||
Datapoints map[string]*Datapoint `json:"-"`
|
||||
Uuid uuid.UUID `json:"uuid"`
|
||||
Path string `json:"path"`
|
||||
Value any `json:"value,omitempty"`
|
||||
Path string `json:"path"`
|
||||
CreateDateTime int64 `json:"createDateTime,omitempty"`
|
||||
UpdateDateTime int64 `json:"updateDateTime,omitempty"`
|
||||
Type json_dataModels.Type `json:"type"`
|
||||
ReadWrite json_dataModels.Rights `json:"readWrite"`
|
||||
Datapoints map[string]*Datapoint `json:"-"`
|
||||
Drivers json_dataModels.Drivers `json:"drivers,omitempty"`
|
||||
Subscriptions Subscriptions `json:"-"`
|
||||
Type json_dataModels.Type `json:"type"`
|
||||
ReadWrite json_dataModels.Rights `json:"readWrite"`
|
||||
HasChild bool `json:"-"`
|
||||
}
|
||||
|
||||
func (d *Datapoint) Set(path string, set json_dataModels.Set) (bool, error) {
|
||||
@@ -53,8 +55,8 @@ func (d *Datapoint) Set(path string, set json_dataModels.Set) (bool, error) {
|
||||
changed = true
|
||||
d.Value = d.Type.ConvertValue(set.Value)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if set.Rights != "" {
|
||||
changed = true
|
||||
d.ReadWrite = set.Rights.GetRights()
|
||||
@@ -67,17 +69,13 @@ func (d *Datapoint) Set(path string, set json_dataModels.Set) (bool, error) {
|
||||
if set.Driver == nil {
|
||||
return changed, nil
|
||||
}
|
||||
if set.Driver.Type == "" {
|
||||
return changed, errors.New("driver type missing")
|
||||
}
|
||||
if set.Driver.Bus == "" {
|
||||
return changed, errors.New("driver bus name missing")
|
||||
}
|
||||
|
||||
if d.Drivers == nil {
|
||||
d.Drivers = json_dataModels.NewDrivers()
|
||||
d.Drivers = json_dataModels.Drivers{}
|
||||
}
|
||||
d.Drivers.AddDriver(set.Driver.Type, set.Driver.Bus, set.Driver.Address)
|
||||
d.Drivers.AddDriver(set.Driver)
|
||||
|
||||
changed = true
|
||||
d.UpdateDateTime = time.Now().UnixMilli()
|
||||
|
||||
return changed, nil
|
||||
@@ -87,14 +85,36 @@ func (d *Datapoint) GetValueUint64() uint64 {
|
||||
return utils.Uint64From(d.Value)
|
||||
}
|
||||
|
||||
func (d *Datapoint) CreateDatapoints(conns *serverModels.Connections, sets ...json_dataModels.Set) (created []json_dataModels.Set, uuids Uuids, err error) {
|
||||
func (d *Datapoint) CreateDatapoints(uuids *Uuids, sets ...json_dataModels.Set) (created []json_dataModels.Set, err error) {
|
||||
if len(sets) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
uuids = make(Uuids, 1)
|
||||
publishes := []json_dataModels.Publish{}
|
||||
|
||||
for _, dp := range sets {
|
||||
|
||||
if dp.Path == "" && dp.Uuid != uuid.Nil {
|
||||
existing := uuids.GetDatapoint(dp.Uuid)
|
||||
_, err := existing.Set("", dp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
created = append(created, json_dataModels.Set{
|
||||
Uuid: existing.Uuid,
|
||||
Path: existing.Path,
|
||||
Type: existing.Type,
|
||||
Value: existing.Value,
|
||||
Rights: existing.ReadWrite,
|
||||
Drivers: &existing.Drivers,
|
||||
Updated: true,
|
||||
HasChild: existing.HasChild,
|
||||
})
|
||||
|
||||
existing.Publish(OnChange)
|
||||
continue
|
||||
}
|
||||
|
||||
parts := strings.Split(dp.Path, ":")
|
||||
|
||||
current := d
|
||||
@@ -106,9 +126,10 @@ func (d *Datapoint) CreateDatapoints(conns *serverModels.Connections, sets ...js
|
||||
if i == len(parts)-1 {
|
||||
// Leaf node: create or update datapoint
|
||||
if existing, ok := current.Datapoints[part]; ok {
|
||||
publish, err := existing.Set("", dp)
|
||||
|
||||
_, err := existing.Set("", dp)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, err
|
||||
}
|
||||
created = append(created, json_dataModels.Set{
|
||||
Uuid: existing.Uuid,
|
||||
@@ -118,23 +139,32 @@ func (d *Datapoint) CreateDatapoints(conns *serverModels.Connections, sets ...js
|
||||
Rights: existing.ReadWrite,
|
||||
Drivers: &existing.Drivers,
|
||||
Updated: true,
|
||||
HasChild: existing.HasChild,
|
||||
})
|
||||
|
||||
if publish {
|
||||
existing.Publish(conns, OnChange)
|
||||
}
|
||||
existing.Publish(OnChange)
|
||||
} else {
|
||||
ndp := Datapoint{
|
||||
Uuid: uuid.New(),
|
||||
var uid uuid.UUID = uuid.New()
|
||||
if dp.Uuid != uuid.Nil {
|
||||
uid = dp.Uuid
|
||||
}
|
||||
ndp := &Datapoint{
|
||||
Uuid: uid,
|
||||
CreateDateTime: time.Now().UnixMilli(),
|
||||
Subscriptions: InitSubscribtion(),
|
||||
}
|
||||
|
||||
// Create new
|
||||
current.Datapoints[part] = &ndp
|
||||
publish, err := ndp.Set(strings.Join(parts, ":"), dp)
|
||||
current.Datapoints[part] = ndp
|
||||
|
||||
_, err := ndp.Set(strings.Join(parts, ":"), dp)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//add uuid to flat map for faster lookup
|
||||
renamedDps := uuids.AddDatapoint(current, ndp)
|
||||
created = append(created, renamedDps...)
|
||||
created = append(created, json_dataModels.Set{
|
||||
Uuid: ndp.Uuid,
|
||||
Path: ndp.Path,
|
||||
@@ -142,12 +172,16 @@ func (d *Datapoint) CreateDatapoints(conns *serverModels.Connections, sets ...js
|
||||
Value: ndp.Value,
|
||||
Rights: ndp.ReadWrite,
|
||||
Driver: dp.Driver,
|
||||
HasChild: ndp.HasChild,
|
||||
})
|
||||
|
||||
publishes = append(publishes, json_dataModels.Publish{
|
||||
Event: OnCreate,
|
||||
Uuid: ndp.Uuid,
|
||||
Path: ndp.Path,
|
||||
Type: ndp.Type,
|
||||
Value: ndp.Value,
|
||||
})
|
||||
if publish {
|
||||
current.Publish(conns, OnChange)
|
||||
}
|
||||
//add uuid to flat map for faster lookuo
|
||||
uuids[ndp.Uuid] = &ndp
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,34 +198,51 @@ func (d *Datapoint) CreateDatapoints(conns *serverModels.Connections, sets ...js
|
||||
Subscriptions: InitSubscribtion(),
|
||||
}
|
||||
|
||||
//add uuid to flat map for faster lookup
|
||||
renamedDps := uuids.AddDatapoint(current, newDp)
|
||||
created = append(created, renamedDps...)
|
||||
created = append(created, json_dataModels.Set{
|
||||
Uuid: newDp.Uuid,
|
||||
Path: newDp.Path,
|
||||
Type: newDp.Type,
|
||||
Value: newDp.Value,
|
||||
Rights: newDp.ReadWrite,
|
||||
HasChild: newDp.HasChild,
|
||||
})
|
||||
|
||||
if dp.Rights != "" {
|
||||
newDp.ReadWrite = dp.Rights.GetRights()
|
||||
}
|
||||
|
||||
publishes = append(publishes, json_dataModels.Publish{
|
||||
Event: OnCreate,
|
||||
Uuid: newDp.Uuid,
|
||||
Path: newDp.Path,
|
||||
Type: newDp.Type,
|
||||
Value: newDp.Value,
|
||||
})
|
||||
|
||||
current.Datapoints[part] = newDp
|
||||
current = newDp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//add uuid to flat map for faster lookuo
|
||||
uuids[newDp.Uuid] = newDp
|
||||
}
|
||||
}
|
||||
r := json_data.NewResponse()
|
||||
r.Publish = append(r.Publish, publishes...)
|
||||
|
||||
b, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return created, err
|
||||
}
|
||||
ws.SendBroadcast(b)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (d *Datapoint) ImportDatapoint(conns *serverModels.Connections, dp Datapoint, path string) (uuids Uuids, err error) {
|
||||
func (d *Datapoint) ImportDatapoint(uuids *Uuids, dp *Datapoint, path string) (err error) {
|
||||
parts := strings.Split(dp.Path, ":")
|
||||
|
||||
uuids = make(Uuids, 1)
|
||||
|
||||
current := d
|
||||
for i, part := range parts {
|
||||
if current.Datapoints == nil {
|
||||
@@ -205,19 +256,20 @@ func (d *Datapoint) ImportDatapoint(conns *serverModels.Connections, dp Datapoin
|
||||
existing.Value = dp.Type.ConvertValue(dp.Value)
|
||||
existing.ReadWrite = dp.ReadWrite.GetRights()
|
||||
existing.UpdateDateTime = time.Now().UnixMilli()
|
||||
dp.Publish(conns, OnChange)
|
||||
dp.Publish(OnChange)
|
||||
} else {
|
||||
dp.Path = strings.Join(parts, ":")
|
||||
dp.ReadWrite = dp.ReadWrite.GetRights()
|
||||
dp.UpdateDateTime = time.Now().UnixMilli()
|
||||
dp.Subscriptions = InitSubscribtion()
|
||||
current.Datapoints[part] = &dp
|
||||
//add uuid to flat map for faster lookuo
|
||||
uuids[dp.Uuid] = &dp
|
||||
dp.Publish(conns, OnChange)
|
||||
current.Datapoints[part] = dp
|
||||
//add uuid to flat map for faster lookup
|
||||
uuids.AddDatapoint(current, dp)
|
||||
|
||||
dp.Publish(OnChange)
|
||||
}
|
||||
|
||||
return uuids, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// Traverse or create intermediate nodes
|
||||
@@ -233,14 +285,14 @@ func (d *Datapoint) ImportDatapoint(conns *serverModels.Connections, dp Datapoin
|
||||
newDp.ReadWrite = newDp.ReadWrite.GetRights()
|
||||
current.Datapoints[part] = newDp
|
||||
current = newDp
|
||||
//add uuid to flat map for faster lookuo
|
||||
uuids[newDp.Uuid] = newDp
|
||||
//add uuid to flat map for faster lookup
|
||||
uuids.AddDatapoint(current, newDp)
|
||||
}
|
||||
}
|
||||
return uuids, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Datapoint) UpdateDatapointValue(conns *serverModels.Connections, value any, path string) error {
|
||||
func (d *Datapoint) UpdateDatapointValue(value any, path string) error {
|
||||
|
||||
paths := strings.Split(path, ":")
|
||||
|
||||
@@ -253,7 +305,7 @@ func (d *Datapoint) UpdateDatapointValue(conns *serverModels.Connections, value
|
||||
if i == len(paths)-1 {
|
||||
dp.Value = dp.Type.ConvertValue(value)
|
||||
dp.UpdateDateTime = time.Now().UnixMilli()
|
||||
dp.Publish(conns, OnChange)
|
||||
dp.Publish(OnChange)
|
||||
return nil
|
||||
}
|
||||
current = dp
|
||||
@@ -261,57 +313,110 @@ func (d *Datapoint) UpdateDatapointValue(conns *serverModels.Connections, value
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Datapoint) UpdateValue(conns *serverModels.Connections, value any) error {
|
||||
func (d *Datapoint) UpdateValue(value any) error {
|
||||
d.Value = d.Type.ConvertValue(value)
|
||||
d.UpdateDateTime = time.Now().UnixMilli()
|
||||
d.Publish(conns, OnChange)
|
||||
d.Publish(OnChange)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Datapoint) RemoveDatapoint(conns *serverModels.Connections, set json_dataModels.Set) (json_dataModels.Set, error) {
|
||||
// removes datapoint and its children if path is given
|
||||
// if path and
|
||||
func (d *Datapoint) RemoveDatapoint(set json_dataModels.Set) (sets []json_dataModels.Set, err error) {
|
||||
parts := strings.Split(set.Path, ":")
|
||||
|
||||
if len(parts) < 1 {
|
||||
return json_dataModels.Set{}, fmt.Errorf("invalid path: '%s'", set.Path)
|
||||
return sets, fmt.Errorf("invalid path: '%s'", set.Path)
|
||||
}
|
||||
|
||||
publishes := []json_dataModels.Publish{}
|
||||
|
||||
current := d
|
||||
for i := range len(parts) - 1 {
|
||||
for i := 0; i < len(parts)-1; i++ {
|
||||
next, ok := current.Datapoints[parts[i]]
|
||||
if !ok {
|
||||
return json_dataModels.Set{}, fmt.Errorf("path not found: '%s'", strings.Join(parts[:i+1], ":"))
|
||||
return sets, fmt.Errorf("path not found: '%s'", strings.Join(parts[:i+1], ":"))
|
||||
}
|
||||
current = next
|
||||
}
|
||||
|
||||
toDelete := parts[len(parts)-1]
|
||||
if dp, ok := current.Datapoints[toDelete]; ok {
|
||||
dp.Publish(conns, OnDelete)
|
||||
//if driver information found, remoove only driver information
|
||||
if set.Driver != nil {
|
||||
dp.RemoveDriver(set.Driver)
|
||||
publishes = append(publishes, json_dataModels.Publish{
|
||||
Event: OnChange,
|
||||
Uuid: dp.Uuid,
|
||||
Path: dp.Path,
|
||||
Value: dp.Value,
|
||||
Drivers: &dp.Drivers,
|
||||
})
|
||||
sets = append(sets, json_dataModels.Set{
|
||||
Uuid: dp.Uuid,
|
||||
Path: dp.Path,
|
||||
Drivers: &dp.Drivers,
|
||||
Value: dp.Value,
|
||||
})
|
||||
} else {
|
||||
s, pubs := removeChildren(dp)
|
||||
sets = append(sets, s...)
|
||||
publishes = append(publishes, pubs...)
|
||||
publishes = append(publishes, json_dataModels.Publish{
|
||||
Event: OnDelete,
|
||||
Uuid: dp.Uuid,
|
||||
Path: dp.Path,
|
||||
})
|
||||
sets = append(sets, json_dataModels.Set{
|
||||
Uuid: dp.Uuid,
|
||||
Path: dp.Path,
|
||||
})
|
||||
delete(current.Datapoints, toDelete)
|
||||
return json_dataModels.Set{
|
||||
Uuid: set.Uuid,
|
||||
Path: set.Path,
|
||||
}, nil
|
||||
}
|
||||
return json_dataModels.Set{}, fmt.Errorf("datapoint '%s' not found", set.Path)
|
||||
r := json_data.NewResponse()
|
||||
r.Publish = append(r.Publish, publishes...)
|
||||
|
||||
b, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return sets, err
|
||||
}
|
||||
ws.SendBroadcast(b)
|
||||
|
||||
return sets, nil
|
||||
}
|
||||
return sets, fmt.Errorf("datapoint '%s' not found", set.Path)
|
||||
}
|
||||
|
||||
// removes all children and grandchlidren of datapoint
|
||||
func removeChildren(dp *Datapoint) (sets []json_dataModels.Set, pubs []json_dataModels.Publish) {
|
||||
for name, d := range dp.Datapoints {
|
||||
s, p := removeChildren(d)
|
||||
sets = append(sets, s...)
|
||||
pubs = append(pubs, p...)
|
||||
|
||||
sets = append(sets, json_dataModels.Set{
|
||||
Uuid: d.Uuid,
|
||||
Path: d.Path,
|
||||
})
|
||||
delete(d.Datapoints, name)
|
||||
}
|
||||
return sets, pubs
|
||||
}
|
||||
|
||||
func (d *Datapoint) GetAllDatapoints(depth uint) (dps Datapoints) {
|
||||
|
||||
var dfs func(dp *Datapoint, currentDepth uint)
|
||||
dfs = func(dp *Datapoint, currentDepth uint) {
|
||||
dps = append(dps, d)
|
||||
if depth == 1 {
|
||||
return
|
||||
} else if depth == 0 {
|
||||
} else if depth > 0 {
|
||||
depth--
|
||||
}
|
||||
var dfs func(dp *Datapoint, currentDepth uint)
|
||||
dfs = func(dp *Datapoint, currentDepth uint) {
|
||||
switch depth {
|
||||
case 0:
|
||||
// Return all descendants
|
||||
for _, child := range dp.Datapoints {
|
||||
dps = append(dps, child)
|
||||
dfs(child, currentDepth+1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if currentDepth == depth-1 {
|
||||
case currentDepth:
|
||||
return
|
||||
}
|
||||
|
||||
@@ -320,7 +425,7 @@ func (d *Datapoint) GetAllDatapoints(depth uint) (dps Datapoints) {
|
||||
dfs(child, currentDepth+1)
|
||||
}
|
||||
}
|
||||
dps = append(dps, d)
|
||||
|
||||
dfs(d, 0)
|
||||
dps.SortSlice()
|
||||
return
|
||||
@@ -354,17 +459,17 @@ func (d *Datapoint) QueryDatapoints(depth uint, path string) (dps Datapoints) {
|
||||
return
|
||||
}
|
||||
|
||||
func (d *Datapoint) AddSubscribtion(id string, sub json_dataModels.Subscription) {
|
||||
func (d *Datapoint) AddSubscribtion(conn *wsModels.Client, sub json_dataModels.Subscription) {
|
||||
if d.Subscriptions == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if s, ok := d.Subscriptions[id]; ok {
|
||||
if s, ok := d.Subscriptions[conn]; ok {
|
||||
s.OnCreate = sub.OnCreate
|
||||
s.OnChange = sub.OnChange
|
||||
s.OnDelete = sub.OnDelete
|
||||
} else {
|
||||
d.Subscriptions[id] = &Subscription{
|
||||
d.Subscriptions[conn] = &Subscription{
|
||||
OnCreate: sub.OnCreate,
|
||||
OnChange: sub.OnChange,
|
||||
OnDelete: sub.OnDelete,
|
||||
@@ -372,35 +477,85 @@ func (d *Datapoint) AddSubscribtion(id string, sub json_dataModels.Subscription)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Datapoint) RemoveSubscribtion(id string) {
|
||||
if _, ok := d.Subscriptions[id]; !ok {
|
||||
func (d *Datapoint) RenamePaths(oldPath string) (renamed []json_dataModels.Set) {
|
||||
visited := make(map[*Datapoint]bool)
|
||||
|
||||
if len(d.Datapoints) == 0 {
|
||||
return
|
||||
}
|
||||
delete(d.Subscriptions, id)
|
||||
|
||||
for _, dp := range d.Datapoints {
|
||||
dp.Path = strings.Replace(dp.Path, oldPath, d.Path, 1)
|
||||
renamedDps := dp.renameSubPaths(oldPath, d.Path, visited)
|
||||
renamed = append(renamed, renamedDps...)
|
||||
renamed = append(renamed, json_dataModels.Set{
|
||||
Uuid: dp.Uuid,
|
||||
Path: dp.Path,
|
||||
Type: dp.Type,
|
||||
Value: dp.Value,
|
||||
Rights: dp.ReadWrite,
|
||||
Drivers: &dp.Drivers,
|
||||
HasChild: dp.HasChild,
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (d *Datapoint) Publish(conns *serverModels.Connections, eventType string) error {
|
||||
if conns.Clients == nil {
|
||||
return nil
|
||||
func (d *Datapoint) renameSubPaths(oldPath, newPath string, visited map[*Datapoint]bool) (renamed []json_dataModels.Set) {
|
||||
if visited[d] {
|
||||
return
|
||||
}
|
||||
conns.RLock()
|
||||
defer conns.RUnlock()
|
||||
visited[d] = true
|
||||
|
||||
for id := range d.Subscriptions {
|
||||
if _, ok := conns.Clients[id]; !ok {
|
||||
delete(d.Subscriptions, id)
|
||||
} else {
|
||||
if len(d.Datapoints) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for _, dp := range d.Datapoints {
|
||||
dp.Path = strings.Replace(dp.Path, oldPath, newPath, 1)
|
||||
renamedDps := dp.renameSubPaths(oldPath, newPath, visited)
|
||||
renamed = append(renamed, renamedDps...)
|
||||
renamed = append(renamed, json_dataModels.Set{
|
||||
Uuid: dp.Uuid,
|
||||
Path: dp.Path,
|
||||
Type: dp.Type,
|
||||
Value: dp.Value,
|
||||
Rights: dp.ReadWrite,
|
||||
Drivers: &dp.Drivers,
|
||||
HasChild: dp.HasChild,
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (d *Datapoint) RemoveSubscribtion(client *wsModels.Client) {
|
||||
delete(d.Subscriptions, client)
|
||||
}
|
||||
|
||||
func (d *Datapoint) RemoveDriver(driver *json_dataModels.Driver) {
|
||||
d.Drivers.RemoveDriver(driver)
|
||||
}
|
||||
|
||||
func (d *Datapoint) Publish(eventType string) error {
|
||||
r := json_data.NewResponse()
|
||||
r.AddUPublish(json_dataModels.Publish{
|
||||
r.AddPublish(json_dataModels.Publish{
|
||||
Event: eventType,
|
||||
Uuid: d.Uuid,
|
||||
Path: d.Path,
|
||||
Type: d.Type,
|
||||
Value: d.Value,
|
||||
})
|
||||
|
||||
if err := conns.SendResponse(id, r); err != nil {
|
||||
b, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch eventType {
|
||||
case OnCreate, OnDelete:
|
||||
ws.SendBroadcast(b)
|
||||
default:
|
||||
for client := range d.Subscriptions {
|
||||
client.SendResponse(b)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -5,27 +5,25 @@ import (
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"maps"
|
||||
|
||||
"github.com/google/uuid"
|
||||
serverModels "github.com/tecamino/tecamino-dbm/server/models"
|
||||
"github.com/tecamino/tecamino-dbm/utils"
|
||||
ws "github.com/tecamino/tecamino-dbm/websocket"
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
"github.com/tecamino/tecamino-logger/logging"
|
||||
)
|
||||
|
||||
type DBM struct {
|
||||
Datapoints Datapoint
|
||||
Uuids Uuids
|
||||
Conns *serverModels.Connections
|
||||
Uuids *Uuids
|
||||
Conns *ws.ClientHandler
|
||||
Log *logging.Logger
|
||||
}
|
||||
|
||||
var SystemDatapoints uuid.UUID
|
||||
|
||||
func NewDBM(conns *serverModels.Connections, log *logging.Logger) *DBM {
|
||||
func NewDBM(conns *ws.ClientHandler, log *logging.Logger) *DBM {
|
||||
return &DBM{
|
||||
Uuids: make(Uuids),
|
||||
Uuids: &Uuids{},
|
||||
Conns: conns,
|
||||
Log: log,
|
||||
}
|
||||
@@ -36,11 +34,7 @@ func (d *DBM) CreateDatapoints(sets ...json_dataModels.Set) ([]json_dataModels.S
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
dps, uuids, err := d.Datapoints.CreateDatapoints(d.Conns, sets...)
|
||||
|
||||
//save uuid in seperate map for fast look up
|
||||
maps.Copy(d.Uuids, uuids)
|
||||
|
||||
dps, err := d.Datapoints.CreateDatapoints(d.Uuids, sets...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -56,13 +50,12 @@ func (d *DBM) CreateDatapoints(sets ...json_dataModels.Set) ([]json_dataModels.S
|
||||
return dps, nil
|
||||
}
|
||||
|
||||
func (d *DBM) ImportDatapoints(dps ...Datapoint) error {
|
||||
func (d *DBM) ImportDatapoints(dps ...*Datapoint) error {
|
||||
for _, dp := range dps {
|
||||
uuids, err := d.Datapoints.ImportDatapoint(d.Conns, dp, dp.Path)
|
||||
err := d.Datapoints.ImportDatapoint(d.Uuids, dp, dp.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
maps.Copy(d.Uuids, uuids)
|
||||
|
||||
d.ModifyCountedDatapoints(1, false)
|
||||
}
|
||||
@@ -71,43 +64,45 @@ func (d *DBM) ImportDatapoints(dps ...Datapoint) error {
|
||||
|
||||
func (d *DBM) UpdateDatapointValue(value any, uid uuid.UUID, path ...string) error {
|
||||
if uid != uuid.Nil {
|
||||
if _, ok := d.Uuids[uid]; !ok {
|
||||
dp := d.Uuids.GetDatapoint(uid)
|
||||
if dp == nil {
|
||||
return fmt.Errorf("uuid %s not found", uid.String())
|
||||
}
|
||||
dp := d.Uuids[uid]
|
||||
dp.Value = dp.Type.ConvertValue(value)
|
||||
dp.UpdateDateTime = time.Now().UnixMilli()
|
||||
dp.Publish(d.Conns, OnChange)
|
||||
dp.Publish(OnChange)
|
||||
}
|
||||
|
||||
if len(path) > 1 {
|
||||
return fmt.Errorf("only one path allowed")
|
||||
}
|
||||
|
||||
return d.Datapoints.UpdateDatapointValue(d.Conns, value, path[0])
|
||||
return d.Datapoints.UpdateDatapointValue(value, path[0])
|
||||
}
|
||||
|
||||
func (d *DBM) RemoveDatapoint(sets ...json_dataModels.Set) ([]json_dataModels.Set, error) {
|
||||
var lsRemoved []json_dataModels.Set
|
||||
func (d *DBM) RemoveDatapoint(sets ...json_dataModels.Set) (lsRemoved []json_dataModels.Set, err error) {
|
||||
for _, set := range sets {
|
||||
removed, err := d.Datapoints.RemoveDatapoint(d.Conns, set)
|
||||
if err != nil {
|
||||
return lsRemoved, err
|
||||
if set.Path == "" {
|
||||
if dp := d.Uuids.GetDatapoint(set.Uuid); dp != nil {
|
||||
set.Path = dp.Path
|
||||
}
|
||||
lsRemoved = append(lsRemoved, removed)
|
||||
d.ModifyCountedDatapoints(1, true)
|
||||
}
|
||||
|
||||
return lsRemoved, nil
|
||||
lsRemoved, err = d.Datapoints.RemoveDatapoint(set)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
d.ModifyCountedDatapoints(uint64(len(lsRemoved)), true)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (d *DBM) QueryDatapoints(depth uint, uid uuid.UUID, key ...string) []*Datapoint {
|
||||
if uid != uuid.Nil {
|
||||
if _, ok := d.Uuids[uid]; !ok {
|
||||
dp := d.Uuids.GetDatapoint(uid)
|
||||
if dp == nil {
|
||||
return nil
|
||||
}
|
||||
dp := d.Uuids[uid]
|
||||
if depth == 1 {
|
||||
} else if depth == 1 {
|
||||
return []*Datapoint{dp}
|
||||
}
|
||||
return append([]*Datapoint{}, dp.QueryDatapoints(depth, key[0])...)
|
||||
@@ -136,7 +131,6 @@ func (d *DBM) ModifyCountedDatapoints(count uint64, countDown bool) {
|
||||
|
||||
func (d *DBM) GoSystemTime() error {
|
||||
path := "System:Time"
|
||||
var tOld int64
|
||||
|
||||
typ := json_dataModels.STR
|
||||
rights := json_dataModels.Read
|
||||
@@ -147,15 +141,12 @@ func (d *DBM) GoSystemTime() error {
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
t := time.Now().UnixMilli()
|
||||
if tOld != t {
|
||||
if er := d.UpdateDatapointValue(time.UnixMilli(t).Format("2006-01-02 15:04:05"), uuid.Nil, path); er != nil {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
for range ticker.C {
|
||||
if er := d.UpdateDatapointValue(time.Now().Format("2006-01-02 15:04:05"), uuid.Nil, path); er != nil {
|
||||
d.Log.Error("dmb.Handler.AddSystemDps.UpdateDatapointValue", er.Error())
|
||||
}
|
||||
tOld = t
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
@@ -163,8 +154,6 @@ func (d *DBM) GoSystemTime() error {
|
||||
|
||||
func (d *DBM) GoSystemMemory() error {
|
||||
path := "System:UsedMemory"
|
||||
var m runtime.MemStats
|
||||
var mOld uint64
|
||||
|
||||
typ := json_dataModels.STR
|
||||
rights := json_dataModels.Read
|
||||
@@ -176,14 +165,12 @@ func (d *DBM) GoSystemMemory() error {
|
||||
|
||||
go func() {
|
||||
for {
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
if m.Sys != mOld {
|
||||
mem := fmt.Sprintf("%.2f MB", float64(m.Sys)/1024/1024)
|
||||
mem := fmt.Sprintf("%.2f MB", float64(m.Alloc)/1024/1024)
|
||||
if er := d.UpdateDatapointValue(mem, uuid.Nil, path); er != nil {
|
||||
d.Log.Error("dmb.Handler.AddSystemDps.UpdateDatapointValue", er.Error())
|
||||
}
|
||||
mOld = m.Sys
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -3,4 +3,5 @@ package models
|
||||
type Port struct {
|
||||
Http uint
|
||||
Https uint
|
||||
Remote uint
|
||||
}
|
||||
|
||||
14
models/stringSlices.go
Normal file
14
models/stringSlices.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package models
|
||||
|
||||
import "strings"
|
||||
|
||||
type StringSlice []string
|
||||
|
||||
func (s *StringSlice) String() string {
|
||||
return strings.Join(*s, ",")
|
||||
}
|
||||
|
||||
func (s *StringSlice) Set(value string) error {
|
||||
*s = append(*s, value)
|
||||
return nil
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package models
|
||||
|
||||
type Subscriptions map[string]*Subscription
|
||||
import wsModels "github.com/tecamino/tecamino-dbm/websocket/models"
|
||||
|
||||
type Subscriptions map[*wsModels.Client]*Subscription
|
||||
|
||||
type Subscription struct {
|
||||
OnCreate bool
|
||||
|
||||
@@ -1,5 +1,50 @@
|
||||
package models
|
||||
|
||||
import "github.com/google/uuid"
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
)
|
||||
|
||||
type Uuids map[uuid.UUID]*Datapoint
|
||||
|
||||
func NewUuids() *Uuids {
|
||||
return &Uuids{}
|
||||
}
|
||||
|
||||
func (u *Uuids) AddDatapoint(parentDp, newDp *Datapoint) (renamed []json_dataModels.Set) {
|
||||
if odp, ok := (*u)[newDp.Uuid]; ok {
|
||||
if odp.Path == newDp.Path {
|
||||
return
|
||||
}
|
||||
newDp.Datapoints = odp.Datapoints
|
||||
newDp.HasChild = len(odp.Datapoints) > 0
|
||||
odp.Datapoints = map[string]*Datapoint{}
|
||||
renamed = newDp.RenamePaths(odp.Path)
|
||||
rmDps, _ := parentDp.RemoveDatapoint(json_dataModels.Set{Path: odp.Path})
|
||||
datapoints := u.GetDatapointByPath("System:Datapoints")
|
||||
datapoints.UpdateValue(datapoints.Value.(uint64) - uint64(len(rmDps)))
|
||||
}
|
||||
|
||||
(*u)[newDp.Uuid] = newDp
|
||||
return
|
||||
}
|
||||
|
||||
func (u *Uuids) GetDatapoint(uuid uuid.UUID) *Datapoint {
|
||||
if dp, ok := (*u)[uuid]; ok {
|
||||
return dp
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *Uuids) GetDatapointByPath(path string) *Datapoint {
|
||||
for _, dp := range *u {
|
||||
if dp.Path == path {
|
||||
return dp
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *Uuids) RemoveDatapoint(uuid uuid.UUID) {
|
||||
delete(*u, uuid)
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var Origins []string = []string{"*"}
|
||||
|
||||
type Clients map[string]*Client
|
||||
|
||||
type Client struct {
|
||||
Ctx context.Context `json:"-"`
|
||||
Cancel context.CancelFunc `json:"-"`
|
||||
Connected bool `json:"connected"`
|
||||
Conn *websocket.Conn `json:"-"`
|
||||
}
|
||||
|
||||
func NewClients() Clients {
|
||||
return make(Clients)
|
||||
}
|
||||
|
||||
// Connect a recieving websocket connection
|
||||
func (cl *Clients) ConnectRecievingWsConnection(id string, c *gin.Context) error {
|
||||
if _, exists := (*cl)[id]; exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
conn, err := websocket.Accept(c.Writer, c.Request, &websocket.AcceptOptions{
|
||||
OriginPatterns: Origins,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("error accept websocket client: %s", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
(*cl)[id] = &Client{
|
||||
Connected: true,
|
||||
Ctx: ctx,
|
||||
Cancel: cancel,
|
||||
Conn: conn,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Clients) RemoveClient(id string) {
|
||||
delete(*c, id)
|
||||
}
|
||||
|
||||
func (c *Clients) DisconnectWsConnection(id string, code websocket.StatusCode, reason string) {
|
||||
(*c)[id].Connected = false
|
||||
(*c)[id].Conn.Close(code, reason)
|
||||
(*c)[id].Cancel()
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/gin-gonic/gin"
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
)
|
||||
|
||||
// serves as connection handler of websocket
|
||||
type Connections struct {
|
||||
sync.RWMutex
|
||||
Clients Clients
|
||||
}
|
||||
|
||||
// initaiates new conections with client map
|
||||
func NewConnections() *Connections {
|
||||
return &Connections{
|
||||
Clients: NewClients(),
|
||||
}
|
||||
}
|
||||
|
||||
// Connect a recieving websocket connection
|
||||
func (c *Connections) ConnectRecievingWsConnection(id string, ctx *gin.Context) error {
|
||||
return c.Clients.ConnectRecievingWsConnection(id, ctx)
|
||||
}
|
||||
|
||||
func (c *Connections) RemoveClient(id string) {
|
||||
c.Clients.RemoveClient(id)
|
||||
}
|
||||
|
||||
func (c *Connections) DisconnectWsConnection(id string, code websocket.StatusCode, reason string) {
|
||||
c.Clients.DisconnectWsConnection(id, code, reason)
|
||||
}
|
||||
|
||||
// sends json response to client
|
||||
func (c *Connections) SendResponse(id string, r *json_dataModels.Response) error {
|
||||
client, ok := c.Clients[id]
|
||||
if !ok {
|
||||
return fmt.Errorf("client not found for id %s", id)
|
||||
|
||||
}
|
||||
b, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
w, err := client.Conn.Writer(ctx, websocket.MessageText)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer w.Close()
|
||||
|
||||
_, err = w.Write(b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
"github.com/tecamino/tecamino-dbm/cert"
|
||||
"github.com/tecamino/tecamino-dbm/dbm"
|
||||
"github.com/tecamino/tecamino-dbm/models"
|
||||
"github.com/tecamino/tecamino-dbm/server"
|
||||
"github.com/tecamino/tecamino-dbm/utils"
|
||||
ws "github.com/tecamino/tecamino-dbm/websocket"
|
||||
)
|
||||
|
||||
func TestCreateDps(t *testing.T) {
|
||||
@@ -142,7 +142,7 @@ func TestUpdateDps(t *testing.T) {
|
||||
|
||||
func TestServer(t *testing.T) {
|
||||
fmt.Println("start")
|
||||
server := server.NewServer([]string{".*"})
|
||||
server := ws.NewServer([]string{".*"}, 9500)
|
||||
|
||||
t.Fatal(server.ServeHttp("http://localhost", 8100))
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
func ListofA2ZZ() (list []string) {
|
||||
for i := 'A'; i <= 'Z'; i++ {
|
||||
list = append(list, string(i))
|
||||
@@ -9,12 +14,21 @@ func ListofA2ZZ() (list []string) {
|
||||
list = append(list, string(i)+string(j))
|
||||
}
|
||||
}
|
||||
// for i := 'A'; i <= 'Z'; i++ {
|
||||
// for j := 'A'; j <= 'Z'; j++ {
|
||||
// for k := 'A'; k <= 'Z'; k++ {
|
||||
// list = append(list, string(i)+string(j)+string(k))
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
return
|
||||
}
|
||||
|
||||
func GetLocalIP() (string, error) {
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
for _, addr := range addrs {
|
||||
if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
|
||||
if ipNet.IP.To4() != nil {
|
||||
return ipNet.IP.String(), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no local IP address found")
|
||||
}
|
||||
|
||||
76
websocket/clientHandler.go
Normal file
76
websocket/clientHandler.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tecamino/tecamino-dbm/websocket/models"
|
||||
wsModels "github.com/tecamino/tecamino-dbm/websocket/models"
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
)
|
||||
|
||||
// serves as connection handler of websocket
|
||||
type ClientHandler struct {
|
||||
sync.RWMutex
|
||||
Clients models.Clients
|
||||
}
|
||||
|
||||
func SendBroadcast(msg []byte) {
|
||||
for _, c := range models.Broadcast {
|
||||
c.SendResponse(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// initaiates new conections with client map
|
||||
func NewConnectionHandler() *ClientHandler {
|
||||
return &ClientHandler{
|
||||
Clients: make(models.Clients),
|
||||
}
|
||||
}
|
||||
|
||||
// Connect a recieving websocket connection
|
||||
func (cH *ClientHandler) ConnectNewClient(id string, c *gin.Context) (client *models.Client, err error) {
|
||||
if _, exists := cH.Clients[id]; exists {
|
||||
return cH.Clients[id], nil
|
||||
}
|
||||
|
||||
client, err = models.ConnectNewClient(id, c)
|
||||
client.OnClose = func(code int, reason string) {
|
||||
delete(cH.Clients, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cH.Lock()
|
||||
cH.Clients[id] = client
|
||||
cH.Unlock()
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// get client client
|
||||
func (c *ClientHandler) GetClient(id string) *wsModels.Client {
|
||||
if client, ok := c.Clients[id]; ok {
|
||||
return client
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sends json response to client
|
||||
func (c *ClientHandler) SendResponse(id string, r *json_dataModels.Response) error {
|
||||
client, ok := c.Clients[id]
|
||||
if !ok {
|
||||
return fmt.Errorf("client not found for id %s", id)
|
||||
|
||||
}
|
||||
|
||||
b, err := json.Marshal(*r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client.SendResponse(b)
|
||||
|
||||
return nil
|
||||
}
|
||||
226
websocket/models/client.go
Normal file
226
websocket/models/client.go
Normal file
@@ -0,0 +1,226 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var Origins []string = []string{"*"}
|
||||
|
||||
var Broadcast Clients = make(Clients)
|
||||
|
||||
const (
|
||||
// Time allowed to write a message to the peer.
|
||||
writeWait = 10 * time.Second
|
||||
|
||||
// Time allowed to read the next pong message from the peer.
|
||||
pongWait = 30 * time.Second
|
||||
|
||||
// Send pings to peer with this period. Must be less than pongWait.
|
||||
pingPeriod = (pongWait * 9) / 10
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
Id string
|
||||
Connected bool `json:"connected"`
|
||||
conn *websocket.Conn `json:"-"`
|
||||
OnOpen func()
|
||||
OnMessage func(data []byte)
|
||||
OnClose func(code int, reason string)
|
||||
OnError func(err error)
|
||||
OnWarning func(warn string)
|
||||
OnPing func()
|
||||
OnPong func()
|
||||
send chan []byte
|
||||
unregister chan []byte
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
if len(Origins) == 0 {
|
||||
return false
|
||||
} else if Origins[0] == "*" {
|
||||
return true
|
||||
}
|
||||
return slices.Contains(Origins, r.Header.Get("Origin"))
|
||||
},
|
||||
EnableCompression: false,
|
||||
}
|
||||
|
||||
func ConnectNewClient(id string, c *gin.Context) (*Client, error) {
|
||||
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("websocket upgrade error: %w", err)
|
||||
}
|
||||
|
||||
client := &Client{
|
||||
Id: id,
|
||||
Connected: true,
|
||||
conn: conn,
|
||||
send: make(chan []byte, 512),
|
||||
unregister: make(chan []byte, 256),
|
||||
}
|
||||
|
||||
Broadcast[client.Id] = client
|
||||
|
||||
conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
|
||||
conn.SetPingHandler(func(appData string) error {
|
||||
if client.OnPing != nil {
|
||||
client.OnPing()
|
||||
}
|
||||
|
||||
conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if err := client.conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(pongWait)); err != nil {
|
||||
client.OnError(err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
conn.SetPongHandler(func(appData string) error {
|
||||
conn.SetReadDeadline(time.Now().Add(pongWait))
|
||||
if client.OnPong != nil {
|
||||
client.OnPong()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
// Start reading messages from client
|
||||
go client.Read()
|
||||
go client.Write()
|
||||
go client.PingInterval(pingPeriod)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *Client) Read() {
|
||||
if c.OnOpen != nil {
|
||||
c.OnOpen()
|
||||
}
|
||||
|
||||
c.conn.SetReadDeadline(time.Now().Add(writeWait))
|
||||
for c.Connected {
|
||||
msgType, msg, err := c.conn.ReadMessage()
|
||||
|
||||
if err != nil {
|
||||
c.handleError(fmt.Errorf("read error (id:%s): %w", c.Id, err))
|
||||
return
|
||||
}
|
||||
switch msgType {
|
||||
case websocket.CloseMessage:
|
||||
c.Close(websocket.CloseNormalClosure, "Client closed")
|
||||
return
|
||||
case websocket.TextMessage:
|
||||
if c.OnMessage != nil {
|
||||
c.OnMessage(msg)
|
||||
} else {
|
||||
log.Printf("Received message but no handler set (id:%s): %s", c.Id, string(msg))
|
||||
}
|
||||
default:
|
||||
log.Printf("Unhandled message type %d (id:%s)", msgType, c.Id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Write() {
|
||||
defer c.conn.Close()
|
||||
|
||||
for {
|
||||
select {
|
||||
case message, ok := <-c.send:
|
||||
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if !ok {
|
||||
// The hub closed the channel.
|
||||
if err := c.conn.WriteMessage(websocket.CloseMessage, []byte("ping")); err != nil {
|
||||
c.handleError(err)
|
||||
return
|
||||
}
|
||||
c.handleError(fmt.Errorf("server %s closed channel", c.Id))
|
||||
return
|
||||
} else {
|
||||
if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil {
|
||||
c.handleError(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
case message := <-c.unregister:
|
||||
c.conn.WriteMessage(websocket.CloseMessage, message)
|
||||
c.Connected = false
|
||||
close(c.send)
|
||||
delete(Broadcast, c.Id)
|
||||
close(c.unregister)
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) PingInterval(interval time.Duration) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
if err := c.conn.WriteControl(websocket.PingMessage, []byte("ping"), time.Now().Add(pongWait)); err != nil {
|
||||
c.OnError(err)
|
||||
return
|
||||
}
|
||||
|
||||
for range ticker.C {
|
||||
if c.OnPing != nil {
|
||||
c.OnPing()
|
||||
}
|
||||
|
||||
if err := c.conn.WriteControl(websocket.PingMessage, []byte("ping"), time.Now().Add(pongWait)); err != nil {
|
||||
c.OnError(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) SendResponse(data []byte) {
|
||||
if !c.Connected {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case c.send <- data:
|
||||
// sent successfully
|
||||
default:
|
||||
// channel full, drop or log
|
||||
if c.OnWarning != nil {
|
||||
c.OnWarning("Dropping message: channel full")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Close(code int, reason string) error {
|
||||
closeMsg := websocket.FormatCloseMessage(code, reason)
|
||||
|
||||
select {
|
||||
case c.unregister <- closeMsg: // Attempt to send
|
||||
default: // If the channel is full, this runs
|
||||
return fmt.Errorf("attempt close client socket failed")
|
||||
}
|
||||
if c.OnClose != nil {
|
||||
c.OnClose(code, reason)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) handleError(err error) {
|
||||
if c.OnError != nil {
|
||||
c.OnError(err)
|
||||
}
|
||||
|
||||
if err := c.Close(websocket.CloseInternalServerErr, err.Error()); err != nil {
|
||||
if c.OnError != nil {
|
||||
c.OnError(err)
|
||||
} else {
|
||||
fmt.Println("error: ", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
3
websocket/models/clients.go
Normal file
3
websocket/models/clients.go
Normal file
@@ -0,0 +1,3 @@
|
||||
package models
|
||||
|
||||
type Clients map[string]*Client
|
||||
21
websocket/models/wsMessage.go
Normal file
21
websocket/models/wsMessage.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package models
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type WSMessage struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
func GetPongByteSlice() []byte {
|
||||
b, err := json.Marshal(WSMessage{
|
||||
Type: "pong",
|
||||
})
|
||||
if err != nil {
|
||||
return []byte{}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (w WSMessage) IsPing() bool {
|
||||
return w.Type == "ping"
|
||||
}
|
||||
@@ -1,13 +1,15 @@
|
||||
package server
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tecamino/tecamino-dbm/cert"
|
||||
"github.com/tecamino/tecamino-dbm/utils"
|
||||
"github.com/tecamino/tecamino-logger/logging"
|
||||
)
|
||||
|
||||
@@ -19,8 +21,17 @@ type Server struct {
|
||||
}
|
||||
|
||||
// initalizes new dbm server
|
||||
func NewServer(allowOrigins []string) *Server {
|
||||
func NewServer(allowOrigins []string, port uint) *Server {
|
||||
r := gin.Default()
|
||||
|
||||
allowOrigins = append(allowOrigins, fmt.Sprintf("http://localhost:%d", port))
|
||||
|
||||
localIP, err := utils.GetLocalIP()
|
||||
if err != nil {
|
||||
log.Printf("get local ip : %s", err.Error())
|
||||
} else {
|
||||
allowOrigins = append(allowOrigins, fmt.Sprintf("http://%s:%d", localIP, port))
|
||||
}
|
||||
r.Use(cors.New(cors.Config{
|
||||
AllowOrigins: allowOrigins,
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
Reference in New Issue
Block a user