8 Commits

Author SHA1 Message Date
Adrian Zuercher
de88b2773c lift version 2025-08-09 18:01:19 +02:00
Adrian Zuercher
1697a4dcfd add new lights, add login and role to it, add services page 2025-08-09 18:00:36 +02:00
Adrian Zuercher
7d2ab814da increment app version 2025-07-31 12:30:18 +02:00
Adrian Zuercher
d50bf9c058 implement driver add update remove and improve rename tree experience 2025-07-31 12:29:16 +02:00
Adrian Zuercher
dac7130544 remove dead file from pull 2025-07-25 18:47:01 +02:00
Adrian Zuercher
7434f02c30 move file 2025-07-25 18:41:13 +02:00
Adrian Zuercher
81b7f96abc make new folder for reuse ngLib add new features for datatree like change add remove rename datapoints improve pingpong 2025-07-25 18:37:18 +02:00
zuadi
8c506b9af3 Rename dataTable.vue to DataTable.vue
bug fix of file name
2025-07-12 23:33:59 +02:00
90 changed files with 3964 additions and 1181 deletions

View File

@@ -2,7 +2,7 @@ name: Build Quasar SPA and Go Backend for lightController
on:
push:
branches: [ main ]
branches: [main]
pull_request:
jobs:
@@ -57,9 +57,9 @@ jobs:
working-directory: ./backend
run: |
if [ "${{ matrix.goos }}" == "windows" ]; then
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -o ../server-${{ matrix.goos }}-${{ matrix.goarch }}.exe main.go
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -ldflags="-s -w" -trimpath -o ../server-${{ matrix.goos }}-${{ matrix.goarch }}.exe main.go
else
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -o ../server-${{ matrix.goos }}-${{ matrix.goarch }} main.go
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -ldflags="-s -w" -trimpath -o ../server-${{ matrix.goos }}-${{ matrix.goarch }} main.go
fi
- name: Upload build artifacts

View File

@@ -1,6 +1,7 @@
package dbRequest
import (
"backend/models"
"fmt"
"net/http"
@@ -10,25 +11,22 @@ import (
var DBCreate string = `CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
role TEXT NOT NULL,
password TEXT NOT NULL
);`
var DBNewUser string = `INSERT INTO users (username, password) VALUES (?, ?)`
var DBQueryPassword string = `SELECT password FROM users WHERE username = ?`
var DBNewUser string = `INSERT INTO users (username, role, password) VALUES (?, ?, ?)`
var DBQueryPassword string = `SELECT role, password FROM users WHERE username = ?`
var DBUserLookup string = `SELECT EXISTS(SELECT 1 FROM users WHERE username = ?)`
var DBRemoveUser string = `DELETE FROM users WHERE username = $1`
func CheckDBError(c *gin.Context, username string, err error) bool {
if err != nil {
if err.Error() == "sql: no rows in result set" {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("no user '%s' found", username),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorMessageResponse(fmt.Sprintf("no user '%s' found", username)))
return true
}
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return true
}
return false

Binary file not shown.

View File

@@ -0,0 +1,28 @@
{
"drivers":[{
"name":"ArtNet",
"description":"ArtNet Driver DMX over UDP/IP",
"executablePath":"bin/tecamino-driver-artNet-linux-arm64",
"workingDirectory":"bin",
"arguments":[
"-cfg './cfg'",
"-serverIp '127.0.0.1'",
"-serverPort 8100",
"-port 8200"
]
},
{
"name":"OSC Driver",
"description":"OSC Driver Music Mixer over UDP/IP",
"executablePath":"bin/tecamino-driver-osc-linux-arm64",
"workingDirectory":"bin",
"arguments":[
"-cfg './cfg'",
"-serverIp '127.0.0.1'",
"-serverPort 8100",
"-port 8300"
]
}
]
}

View File

@@ -0,0 +1,36 @@
package drivers
import (
"backend/models"
"encoding/json"
"net/http"
"os"
"github.com/gin-gonic/gin"
)
type DriverHandler struct {
driversConfig string
}
func NewDriverHandler(cfgDir string) *DriverHandler {
return &DriverHandler{driversConfig: cfgDir}
}
func (dH *DriverHandler) GetDriverList(c *gin.Context) {
content, err := os.ReadFile(dH.driversConfig)
if err != nil {
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
var data struct {
Drivers []models.Drivers `json:"drivers"`
}
err = json.Unmarshal(content, &data)
if err != nil {
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
c.JSON(http.StatusOK, data.Drivers)
}

View File

@@ -19,25 +19,19 @@ import (
func (lm *LoginManager) AddUser(c *gin.Context) {
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
user := models.User{}
err = json.Unmarshal(body, &user)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
if !user.IsValid() {
c.JSON(http.StatusBadRequest, gin.H{
"error": "user empty",
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorMessageResponse("user empty"))
return
}
@@ -54,20 +48,16 @@ func (lm *LoginManager) AddUser(c *gin.Context) {
}
if exists {
c.JSON(http.StatusOK, gin.H{
"error": fmt.Sprintf("user '%s' exists already", user.Name),
})
c.JSON(http.StatusOK, models.NewJsonErrorMessageResponse(fmt.Sprintf("user '%s' exists already", user.Name)))
return
}
hash, err := utils.HashPassword(user.Password)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
if _, err := db.Exec(dbRequest.DBNewUser, user.Name, hash); dbRequest.CheckDBError(c, user.Name, err) {
if _, err := db.Exec(dbRequest.DBNewUser, user.Role, user.Name, hash); dbRequest.CheckDBError(c, user.Name, err) {
return
}
@@ -79,25 +69,19 @@ func (lm *LoginManager) AddUser(c *gin.Context) {
func (lm *LoginManager) RemoveUser(c *gin.Context) {
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
user := models.User{}
err = json.Unmarshal(body, &user)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
if !user.IsValid() {
c.JSON(http.StatusBadRequest, gin.H{
"error": "user empty",
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorMessageResponse("user empty"))
return
}
@@ -108,14 +92,12 @@ func (lm *LoginManager) RemoveUser(c *gin.Context) {
defer db.Close()
var storedPassword string
if err := db.QueryRow(dbRequest.DBQueryPassword, user.Name).Scan(&storedPassword); dbRequest.CheckDBError(c, user.Name, err) {
if err := db.QueryRow(dbRequest.DBQueryPassword, user.Name).Scan(&storedPassword, &user.Role); dbRequest.CheckDBError(c, user.Name, err) {
return
}
if !utils.CheckPassword(user.Password, storedPassword) {
c.JSON(http.StatusBadRequest, gin.H{
"error": "wrong password",
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorMessageResponse("wrong password"))
return
}
@@ -131,27 +113,19 @@ func (lm *LoginManager) RemoveUser(c *gin.Context) {
func (lm *LoginManager) Login(c *gin.Context) {
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
user := models.User{}
err = json.Unmarshal(body, &user)
if err != nil {
fmt.Println(2)
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
if !user.IsValid() {
c.JSON(http.StatusBadRequest, gin.H{
"error": "user empty",
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorMessageResponse("user empty"))
return
}
@@ -162,41 +136,36 @@ func (lm *LoginManager) Login(c *gin.Context) {
defer db.Close()
var storedPassword string
if err := db.QueryRow(dbRequest.DBQueryPassword, user.Name).Scan(&storedPassword); dbRequest.CheckDBError(c, user.Name, err) {
if err := db.QueryRow(dbRequest.DBQueryPassword, user.Name).Scan(&user.Role, &storedPassword); dbRequest.CheckDBError(c, user.Name, err) {
return
}
if !utils.CheckPassword(user.Password, storedPassword) {
fmt.Println(2, user.Password)
c.JSON(http.StatusBadRequest, gin.H{
"error": "wrong password",
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorMessageResponse("wrong password"))
return
}
// Create token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Name,
"exp": time.Now().Add(time.Hour * 72).Unix(), // expires in 72h
"role": user.Role,
"exp": time.Now().Add(time.Minute * 60).Unix(), // expires in 72h
})
secret, err := utils.GenerateJWTSecret(32) // 32 bytes = 256 bits
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "error generate jwt token"})
c.JSON(http.StatusInternalServerError, models.NewJsonErrorMessageResponse("error generate jwt token"))
return
}
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString(secret)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Could not generate token"})
c.JSON(http.StatusInternalServerError, models.NewJsonErrorMessageResponse("Could not generate token"))
return
}
c.JSON(http.StatusOK, models.User{
Name: user.Name,
Token: tokenString,
})
}

View File

@@ -37,7 +37,7 @@ func NewLoginManager(dir string) (*LoginManager, error) {
if err != nil {
return nil, err
}
_, err = db.Exec(dbRequest.DBNewUser, "admin", hash)
_, err = db.Exec(dbRequest.DBNewUser, "admin", "admin", hash)
if err != nil {
return nil, err
}

View File

@@ -1,7 +1,9 @@
package main
import (
"backend/drivers"
"backend/login"
"backend/models"
secenes "backend/scenes"
"backend/server"
"backend/utils"
@@ -20,7 +22,14 @@ import (
)
func main() {
var allowOrigins models.StringSlice
flag.Var(&allowOrigins, "allowOrigin", "Allowed origin (can repeat this flag)")
spa := flag.String("spa", "./dist/spa", "quasar spa files")
cfgDir := flag.String("cfg", "./cfg", "config dir")
driversCfg := flag.String("drivers", "defaultConfigurations.json", "drivers config file name")
workingDir := flag.String("workingDirectory", ".", "quasar spa files")
ip := flag.String("ip", "0.0.0.0", "server listening ip")
port := flag.Uint("port", 9500, "server listening port")
@@ -32,7 +41,7 @@ func main() {
fmt.Println(1, *workingDir)
os.Chdir(*workingDir)
}
fmt.Println(1.1, *workingDir)
wd, err := os.Getwd()
if err != nil {
log.Fatalf("Could not get working directory: %v", err)
@@ -63,23 +72,24 @@ func main() {
//new scenes handler
scenesHandler := secenes.NewScenesHandler("")
//new scenes handler
driversHandler := drivers.NewDriverHandler(filepath.Join(*cfgDir, *driversCfg))
// new server
s := server.NewServer()
//get local ip
origins := []string{"http://localhost:9000"}
origins = append(origins, "http://localhost:9500")
allowOrigins = append(allowOrigins, "http://localhost:9000", "http://localhost:9500")
localIP, err := utils.GetLocalIP()
if err != nil {
logger.Error("main", fmt.Sprintf("get local ip : %s", err.Error()))
} else {
origins = append(origins, fmt.Sprintf("http://%s:9000", localIP))
origins = append(origins, fmt.Sprintf("http://%s:9500", localIP))
allowOrigins = append(allowOrigins, fmt.Sprintf("http://%s:9000", localIP), fmt.Sprintf("http://%s:9500", localIP))
}
fmt.Println(123, origins)
s.Routes.Use(cors.New(cors.Config{
AllowOrigins: origins,
AllowOrigins: allowOrigins,
AllowMethods: []string{"POST", "GET", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type"},
AllowCredentials: true,
@@ -88,6 +98,7 @@ func main() {
api := s.Routes.Group("/api")
//set routes
api.GET("/loadScenes", scenesHandler.LoadScenes)
api.GET("/allDrivers", driversHandler.GetDriverList)
api.POST("/login", loginManager.Login)
api.POST("/user/add", loginManager.AddUser)
api.POST("/saveScene", scenesHandler.SaveScene)
@@ -100,7 +111,7 @@ func main() {
s.Routes.NoRoute(func(c *gin.Context) {
// Disallow fallback for /api paths
if strings.HasPrefix(c.Request.URL.Path, "/api") {
c.JSON(http.StatusNotFound, gin.H{"error": "API endpoint not found"})
c.JSON(http.StatusNotFound, models.NewJsonErrorMessageResponse("API endpoint not found"))
return
}
// Try to serve file from SPA directory

View File

@@ -0,0 +1,9 @@
package models
type Drivers struct {
Name string `json:"name"`
Description string `json:"description"`
ExecutablePath string `json:"executablePath,omitempty"`
WorkingDirectory string `json:"workingDirectory,omitempty"`
Arguments []string `json:"arguments,omitempty"`
}

View File

@@ -0,0 +1,20 @@
package models
type JsonResponse struct {
Error bool `json:"error,omitempty"`
Message string `json:"message,omitempty"`
}
func NewJsonErrorMessageResponse(msg string) JsonResponse {
return JsonResponse{
Error: true,
Message: msg,
}
}
func NewJsonErrorResponse(err error) JsonResponse {
return JsonResponse{
Error: true,
Message: err.Error(),
}
}

View File

@@ -1,3 +0,0 @@
package models
type LightBar []Value

View File

@@ -1,3 +0,0 @@
package models
type MovingHead []Value

View 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
}

View File

@@ -2,6 +2,7 @@ package models
type User struct {
Name string `json:"user"`
Role string `json:"role"`
Password string `json:"password,omitempty"`
Token string `json:"token,omitempty"`
}

View File

@@ -1,7 +1,9 @@
package models
type Values struct {
MovingHead *MovingHead `json:"movingHead"`
LightBar *LightBar `json:"lightBar"`
Value any `json:"value"`
Stagelights []Value `json:"stageLights,omitempty"`
LightBar []Value `json:"lightBar,omitempty"`
FloogLights []Value `json:"floodLights,omitempty"`
MovingHead []Value `json:"movingHead,omitempty"`
Value any `json:"value"`
}

View File

@@ -31,45 +31,35 @@ func NewScenesHandler(dir string) *ScenesHandler {
func (sh *ScenesHandler) SaveScene(c *gin.Context) {
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
var scene models.Scene
err = json.Unmarshal(body, &scene)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
if _, err := os.Stat(path.Join(sh.dir)); err != nil {
err := os.MkdirAll(sh.dir, 0755)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
}
f, err := os.OpenFile(path.Join(sh.dir, scene.Name+".scene"), os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
defer f.Close()
_, err = f.Write(body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
@@ -81,26 +71,20 @@ func (sh *ScenesHandler) SaveScene(c *gin.Context) {
func (sh *ScenesHandler) DeleteScene(c *gin.Context) {
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
var scene models.Scene
err = json.Unmarshal(body, &scene)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
err = os.Remove(path.Join(sh.dir, scene.Name+".scene"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
@@ -114,26 +98,20 @@ func (sh *ScenesHandler) LoadScenes(c *gin.Context) {
files, err := utils.FindAllFiles("./scenes", ".scene")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
for _, f := range files {
content, err := os.ReadFile(f)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
var scene models.Scene
err = json.Unmarshal(content, &scene)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
sceneMap[scene.Name] = scene
@@ -160,9 +138,7 @@ func (sh *ScenesHandler) LoadScenes(c *gin.Context) {
func (sh *ScenesHandler) LoadScene(c *gin.Context) {
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
@@ -170,17 +146,13 @@ func (sh *ScenesHandler) LoadScene(c *gin.Context) {
err = json.Unmarshal(body, &scene)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
files, err := utils.FindAllFiles("./scenes", ".scene")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
@@ -190,26 +162,18 @@ func (sh *ScenesHandler) LoadScene(c *gin.Context) {
}
content, err := os.ReadFile(f)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
err = json.Unmarshal(content, &scene)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
c.JSON(http.StatusOK, scene)
break
}
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Errorf("scene '%s' not found", scene.Name),
})
return
}
c.JSON(http.StatusBadRequest, models.NewJsonErrorMessageResponse(fmt.Sprintf("scene '%s' not found", scene.Name)))
}

Binary file not shown.

150
package-lock.json generated
View File

@@ -1,16 +1,18 @@
{
"name": "lightcontrol",
"version": "0.0.14",
"version": "0.0.21",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "lightcontrol",
"version": "0.0.14",
"version": "0.0.21",
"hasInstallScript": true,
"dependencies": {
"@quasar/extras": "^1.16.4",
"axios": "^1.10.0",
"jwt-decode": "^4.0.0",
"pinia": "^3.0.3",
"quasar": "^2.16.0",
"vue": "^3.4.18",
"vue-router": "^4.0.12"
@@ -1939,6 +1941,30 @@
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
"license": "MIT"
},
"node_modules/@vue/devtools-kit": {
"version": "7.7.7",
"resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.7.tgz",
"integrity": "sha512-wgoZtxcTta65cnZ1Q6MbAfePVFxfM+gq0saaeytoph7nEa7yMXoi6sCPy4ufO111B9msnw0VOWjPEFCXuAKRHA==",
"license": "MIT",
"dependencies": {
"@vue/devtools-shared": "^7.7.7",
"birpc": "^2.3.0",
"hookable": "^5.5.3",
"mitt": "^3.0.1",
"perfect-debounce": "^1.0.0",
"speakingurl": "^14.0.1",
"superjson": "^2.2.2"
}
},
"node_modules/@vue/devtools-shared": {
"version": "7.7.7",
"resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.7.tgz",
"integrity": "sha512-+udSj47aRl5aKb0memBvcUG9koarqnxNM5yjuREvqwK6T3ap4mn3Zqqc17QrBFTqSMjr3HK1cvStEZpMDpfdyw==",
"license": "MIT",
"dependencies": {
"rfdc": "^1.4.1"
}
},
"node_modules/@vue/eslint-config-prettier": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/@vue/eslint-config-prettier/-/eslint-config-prettier-10.2.0.tgz",
@@ -2378,6 +2404,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/birpc": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/birpc/-/birpc-2.5.0.tgz",
"integrity": "sha512-VSWO/W6nNQdyP520F1mhf+Lc2f8pjGQOtoHHm7Ze8Go1kX7akpVIrtTa0fn+HB0QJEDVacl6aO08YE0PgXfdnQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/bl": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
@@ -2998,6 +3033,21 @@
"dev": true,
"license": "MIT"
},
"node_modules/copy-anything": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-3.0.5.tgz",
"integrity": "sha512-yCEafptTtb4bk7GLEQoM8KVJpxAfdBJYaXyzQEgQQQgYrZiDp8SJmGKlYza6CYjEDNstAdNdKA3UuoULlEbS6w==",
"license": "MIT",
"dependencies": {
"is-what": "^4.1.8"
},
"engines": {
"node": ">=12.13"
},
"funding": {
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
@@ -4398,6 +4448,12 @@
"he": "bin/he"
}
},
"node_modules/hookable": {
"version": "5.5.3",
"resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz",
"integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==",
"license": "MIT"
},
"node_modules/html-minifier-terser": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/html-minifier-terser/-/html-minifier-terser-7.2.0.tgz",
@@ -4696,6 +4752,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-what": {
"version": "4.1.16",
"resolved": "https://registry.npmjs.org/is-what/-/is-what-4.1.16.tgz",
"integrity": "sha512-ZhMwEosbFJkA0YhFnNDgTM4ZxDRsS6HqTo7qsZM08fehyRYIYa0yHu5R6mgo1n/8MgaPBXiPimPD77baVFYg+A==",
"license": "MIT",
"engines": {
"node": ">=12.13"
},
"funding": {
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/is-wsl": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.0.tgz",
@@ -4819,6 +4887,15 @@
"graceful-fs": "^4.1.6"
}
},
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -5132,6 +5209,12 @@
"node": ">=16 || 14 >=14.17"
}
},
"node_modules/mitt": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
"integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
"license": "MIT"
},
"node_modules/mlly": {
"version": "1.7.4",
"resolved": "https://registry.npmjs.org/mlly/-/mlly-1.7.4.tgz",
@@ -5560,6 +5643,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/perfect-debounce": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz",
"integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==",
"license": "MIT"
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -5579,6 +5668,36 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/pinia": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/pinia/-/pinia-3.0.3.tgz",
"integrity": "sha512-ttXO/InUULUXkMHpTdp9Fj4hLpD/2AoJdmAbAeW2yu1iy1k+pkFekQXw5VpC0/5p51IOR/jDaDRfRWRnMMsGOA==",
"license": "MIT",
"dependencies": {
"@vue/devtools-api": "^7.7.2"
},
"funding": {
"url": "https://github.com/sponsors/posva"
},
"peerDependencies": {
"typescript": ">=4.4.4",
"vue": "^2.7.0 || ^3.5.11"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/pinia/node_modules/@vue/devtools-api": {
"version": "7.7.7",
"resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.7.tgz",
"integrity": "sha512-lwOnNBH2e7x1fIIbVT7yF5D+YWhqELm55/4ZKf45R9T8r9dE2AIOy8HKjfqzGsoTHFbWbr337O4E0A0QADnjBg==",
"license": "MIT",
"dependencies": {
"@vue/devtools-kit": "^7.7.7"
}
},
"node_modules/pkg-types": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",
@@ -5954,6 +6073,12 @@
"node": ">=0.10.0"
}
},
"node_modules/rfdc": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
"integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
"license": "MIT"
},
"node_modules/rollup": {
"version": "4.40.1",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.40.1.tgz",
@@ -6865,6 +6990,15 @@
"source-map": "^0.6.0"
}
},
"node_modules/speakingurl": {
"version": "14.0.1",
"resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz",
"integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/stack-trace": {
"version": "1.0.0-pre2",
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-1.0.0-pre2.tgz",
@@ -6980,6 +7114,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/superjson": {
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.2.tgz",
"integrity": "sha512-5JRxVqC8I8NuOUjzBbvVJAKNM8qoVuH0O77h4WInc/qC2q5IreqKxYwgkga3PfA22OayK2ikceb/B26dztPl+Q==",
"license": "MIT",
"dependencies": {
"copy-anything": "^3.0.2"
},
"engines": {
"node": ">=16"
}
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "lightcontrol",
"version": "0.0.18",
"version": "0.0.22",
"description": "A Tecamino App",
"productName": "Light Control",
"author": "A. Zuercher",
@@ -17,6 +17,8 @@
"dependencies": {
"@quasar/extras": "^1.16.4",
"axios": "^1.10.0",
"jwt-decode": "^4.0.0",
"pinia": "^3.0.3",
"quasar": "^2.16.0",
"vue": "^3.4.18",
"vue-router": "^4.0.12"

View File

@@ -11,7 +11,7 @@ export default defineConfig((/* ctx */) => {
// app boot file (/src/boot)
// --> boot files are part of "main.js"
// https://v2.quasar.dev/quasar-cli-vite/boot-files
boot: ['websocket', 'axios'],
boot: ['websocket', 'axios', 'auth'],
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-file#css
css: ['app.scss'],

13
src/boot/auth.ts Normal file
View File

@@ -0,0 +1,13 @@
import { boot } from 'quasar/wrappers';
import { createPinia } from 'pinia';
import { useUserStore } from 'src/vueLib/login/userStore';
import type { QVueGlobals } from 'quasar';
export default boot(({ app }) => {
const $q = app.config.globalProperties.$q as QVueGlobals;
const pinia = createPinia();
app.use(pinia);
const useStore = useUserStore();
useStore.initStore($q);
useStore.loadFromStorage();
});

View File

@@ -2,11 +2,19 @@ import { boot } from 'quasar/wrappers';
import axios from 'axios';
const host = window.location.hostname;
const port = 8100;
const baseURL = `http://${host}:${port}`;
const portDbm = 8100;
const portApp = 9500;
const api = axios.create({
baseURL: baseURL,
const dbmApi = axios.create({
baseURL: `http://${host}:${portDbm}`,
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
});
const appApi = axios.create({
baseURL: `http://${host}:${portApp}/api`,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
@@ -15,7 +23,8 @@ const api = axios.create({
export default boot(({ app }) => {
app.config.globalProperties.$axios = axios;
app.config.globalProperties.$api = api;
app.config.globalProperties.$dbmApi = dbmApi;
app.config.globalProperties.$appApi = appApi;
});
export { axios, api };
export { axios, dbmApi, appApi };

View File

@@ -1,14 +1,11 @@
import { boot } from 'quasar/wrappers';
import type { QVueGlobals } from 'quasar';
import { initWebSocket } from 'src/services/websocket';
import { initWebSocket } from '../vueLib/services/websocket';
export default boot(({ app }) => {
const $q = app.config.globalProperties.$q as QVueGlobals;
const host = window.location.hostname;
const port = 8100;
const randomId = Math.floor(Math.random() * 10001); // random number from 0 to 10000
const ws = initWebSocket(`ws://${host}:${port}/ws?id=q${randomId}`, $q);
const ws = initWebSocket(window.location.hostname, 8100, $q);
app.config.globalProperties.$socket = ws;
ws.connect();

View File

@@ -1,180 +0,0 @@
<template>
<q-card>
<div class="row">
<q-card-section class="col-4 scroll tree-container">
<q-tree
class="text-blue text-bold"
dense
:nodes="dbmData"
node-key="key"
no-transition
:default-expand-all="false"
v-model:expanded="expanded"
@update:expanded="onExpandedChange"
@lazy-load="onLazyLoad"
>
<template v-slot:[`default-header`]="props">
<div
class="row items-center text-blue"
@contextmenu.prevent.stop="openSubMenu($event, props.node.key)"
>
<div class="row items-center text-blue"></div>
<div>{{ props.node.path }}</div>
</div>
</template>
</q-tree>
<!-- not implemented yet <sub-menu ref="subMenuRef"></sub-menu> -->
</q-card-section>
<dataTable class="col-8" :rows="getRows()" />
</div>
</q-card>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import {
type TreeNode,
buildTree,
dbmData,
removeSubtreeByParentKey,
} from 'src/composables/dbm/dbmTree';
import DataTable from './DataTable.vue';
import { useQuasar } from 'quasar';
import { NotifyResponse } from 'src/composables/notify';
import { QCard } from 'quasar';
import { subscribe, unsubscribe } from 'src/services/websocket';
import { onBeforeRouteLeave } from 'vue-router';
import { api } from 'boot/axios';
// not implemented yet import SubMenu from './SubMenu.vue';
import { type Subs, type RawSubs, convertToSubscribes } from 'src/models/Subscribe';
import { addSubscriptions, getRows, removeAllSubscriptions } from 'src/models/Subscriptions';
const $q = useQuasar();
const expanded = ref<string[]>([]);
const ZERO_UUID = '00000000-0000-0000-0000-000000000000';
let lastExpanded: string[] = [];
const postQuery = '/json_data';
onMounted(() => {
api
.post(postQuery, { get: [{ path: '.*', query: { depth: 1 } }] })
.then((res) => {
if (res.data.get) buildTree(convertToSubscribes(res.data.get as RawSubs));
})
.catch((err) => NotifyResponse($q, err, 'error'));
});
onBeforeRouteLeave(() => {
unsubscribe([{ path: '.*', depth: 0 }]).catch((err) => NotifyResponse($q, err, 'error'));
});
function onLazyLoad({
node,
done,
fail,
}: {
node: TreeNode;
done: (children: TreeNode[]) => void;
fail: () => void;
}): void {
api
.post(postQuery, { get: [{ uuid: node.key ?? ZERO_UUID, path: '', query: { depth: 2 } }] })
.then((resp) => {
if (resp?.data.get) done(buildTree(convertToSubscribes(resp?.data.get as RawSubs)));
else done([]); // no children returned
})
.catch((err) => {
NotifyResponse($q, err, 'error');
fail(); // trigger the fail handler
});
}
async function onExpandedChange(newExpanded: readonly string[]) {
const collapsed = lastExpanded.filter((k) => !newExpanded.includes(k));
const newlyExpanded = newExpanded.filter((k) => !lastExpanded.includes(k));
try {
await unsubscribe([{ path: '.*', depth: 0 }])
.then(() => {
removeAllSubscriptions();
})
.catch((err) => NotifyResponse($q, err, 'error'));
if (collapsed.length) {
collapsed.forEach((key) => {
removeSubtreeByParentKey(key);
api
.post(postQuery, { get: [{ uuid: key, path: '', query: { depth: 2 } }] })
.then((resp) => {
if (resp?.data.get) {
buildTree(resp?.data.get as Subs);
subscribe([{ uuid: key, path: '', depth: 2 }]).catch((err) =>
NotifyResponse($q, err, 'error'),
);
addSubscriptions(resp?.data.get as RawSubs);
}
})
.catch((err) => NotifyResponse($q, err, 'error'));
});
}
if (newlyExpanded.length) {
newlyExpanded.forEach((key) => {
api
.post(postQuery, { get: [{ uuid: key, path: '', query: { depth: 2 } }] })
.then((resp) => {
if (resp?.data.get) {
buildTree(resp?.data.get as Subs);
subscribe([{ uuid: key, path: '', depth: 2 }]).catch((err) =>
NotifyResponse($q, err, 'error'),
);
addSubscriptions(resp?.data.get as RawSubs);
}
})
.catch((err) => NotifyResponse($q, err, 'error'));
});
}
lastExpanded = [...newExpanded];
} catch {
console.error('error in expand function');
}
}
const subMenuRef = ref();
function openSubMenu(event: MouseEvent, uuid: string) {
subMenuRef.value?.open(event, uuid);
}
</script>
<style scoped>
.tree-container {
overflow-y: auto;
}
@media (max-width: 599px) {
.tree-container {
max-height: 50vh;
}
}
@media (min-width: 600px) and (max-width: 1023px) {
.tree-container {
max-height: 60vh;
}
}
@media (min-width: 1024px) and (max-width: 1439px) {
.tree-container {
max-height: 70vh;
}
}
@media (min-width: 1440px) and (max-width: 1919px) {
.tree-container {
max-height: 80vh;
}
}
@media (min-width: 1920px) {
.tree-container {
max-height: 90vh;
}
}
</style>

View File

@@ -1,52 +0,0 @@
<template>
<q-menu ref="contextMenuRef" context-menu>
<q-list>
<q-item clickable v-close-popup @click="handleAction('Add')">
<q-item-section>Add Datapoint</q-item-section>
</q-item>
<q-item
:class="disable ? 'text-grey-5' : ''"
:clickable="!disable"
v-close-popup
@click="handleAction('Delete')"
>
<q-item-section>Delete Datapoint</q-item-section>
</q-item>
</q-list>
</q-menu>
<AddDialog :dialogLabel="label" width="700px" button-ok-label="Add" ref="addDialog" />
</template>
<script setup lang="ts">
import AddDialog from 'src/components/dialog/AddDatapoint.vue';
import { ref } from 'vue';
const ZERO_UUID = '00000000-0000-0000-0000-000000000000';
const addDialog = ref();
const datapointUuid = ref('');
const contextMenuRef = ref();
const label = ref('');
const disable = ref(false);
function handleAction(action: string) {
switch (action) {
case 'Add':
label.value = 'Add New Datapoint';
addDialog.value?.open(datapointUuid.value);
break;
case 'Delete':
label.value = 'Remove Datapoint';
addDialog.value?.open(datapointUuid.value);
break;
}
}
const open = (event: MouseEvent, uuid: string) => {
if (uuid === ZERO_UUID) disable.value = true;
event.preventDefault();
datapointUuid.value = uuid;
contextMenuRef.value?.show(event);
};
defineExpose({ open });
</script>

View File

@@ -1,82 +0,0 @@
<template>
<div class="q-pa-md">
<q-table
v-if="tableRows.length > 0"
style="height: 600px"
flat
bordered
:title="props.rows[0]?.path"
:rows="rows"
:columns="columns"
row-key="path"
virtual-scroll
:rows-per-page-options="[0]"
>
<template v-slot:body-cell-value="props">
<q-td :props="props" @click="openDialog(props.row)">
<div :class="['cursor-pointer', 'q-mx-sm']">
{{ props.row.value }}
</div>
</q-td>
</template>
<template v-slot:body-cell-drivers="props">
<q-td :props="props" @click="openDialog(props.row, 'driver')">
<div v-if="props.row.type !== 'none'" :class="['cursor-pointer']">
<q-icon size="sm" name="cell_tower" :color="props.row.drivers ? 'blue-5' : 'grey-4'" />
</div>
</q-td>
</template>
</q-table>
<UpdateDialog
dialogLabel="Update Value"
width="400px"
button-ok-label="Write"
ref="updateDialog"
v-model:datapoint="dialogValue"
/>
</div>
</template>
<script setup lang="ts">
import UpdateDialog from 'src/components/dialog/UpdateValueDialog.vue';
import type { QTableProps } from 'quasar';
import type { Subscribe } from 'src/models/Subscribe';
import { computed, ref } from 'vue';
import type { Subs } from 'src/models/Subscribe';
const updateDialog = ref();
const dialogValue = ref();
const openDialog = (sub: Subscribe, type?: string) => {
updateDialog.value?.open(sub, type);
};
// we generate lots of rows here
const props = defineProps<{
rows: Subs;
}>();
const tableRows = computed(() => [...props.rows]);
const columns = [
{ name: 'path', label: 'Path', field: 'path', align: 'left' },
{
name: 'type',
label: 'Type',
field: 'type',
align: 'left',
},
{
name: 'value',
label: 'Value',
field: 'value',
align: 'left',
},
// {. not implemented yet
// name: 'drivers',
// label: 'Drivers',
// field: 'drivers',
// align: 'center',
// },
] as QTableProps['columns'];
</script>

View File

@@ -1,101 +0,0 @@
<template>
<DialogFrame ref="Dialog" :width="props.width">
<q-card-section
v-if="props.dialogLabel"
class="text-bold text-left q-mb-none q-pb-none"
:class="'text-' + props.labelColor"
>{{ props.dialogLabel }}
</q-card-section>
<q-form ref="addForm" @submit="onSubmit" class="q-gutter-md">
<q-input
class="q-pa-md"
filled
v-model="path"
label=""
:rules="[(val) => !!val || 'Path is required']"
>
<template #prepend>
<div class="column">
<span class="text-caption text-primary non-editable-prefix">Path *</span>
<span class="text-body2 text-grey-6 non-editable-prefix">{{ staticPrefix }}</span>
</div>
</template>
</q-input>
<DataTypes class="q-ma-md" flat></DataTypes>
<q-btn no-caps class="q-ma-lg" type="submit" color="primary">{{ props.buttonOkLabel }}</q-btn>
</q-form>
</DialogFrame>
</template>
<script setup lang="ts">
import { useQuasar } from 'quasar';
import { ref } from 'vue';
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import { api } from 'boot/axios';
import { NotifyResponse } from 'src/composables/notify';
import DataTypes from 'src/vueLib/buttons/DataTypes.vue';
//import datatype from 'src/vueLib/buttons/DataType.vue';
const $q = useQuasar();
const Dialog = ref();
const path = ref('');
const staticPrefix = ref('');
//const radio = ref('bool');
const addForm = ref();
const open = (uuid: string) => {
Dialog.value?.open();
getDatapoint(uuid);
};
function validate() {
addForm.value.validate().then((success: undefined) => {
if (success) {
console.log(909);
// yay, models are correct
} else {
console.log(910);
// oh no, user has filled in
// at least one invalid value
}
});
}
const props = defineProps({
buttonOkLabel: {
type: String,
default: 'OK',
},
labelColor: {
type: String,
default: 'primary',
},
dialogLabel: {
type: String,
default: '',
},
width: {
type: String,
default: '300px',
},
});
function onSubmit() {
validate();
console.log('submit', props);
}
function getDatapoint(uuid: string) {
api
.post('/json_data', { get: [{ uuid: uuid, query: { depth: 1 } }] })
.then((resp) => {
if (resp.data.get) {
staticPrefix.value = resp.data.get[0].path;
if (staticPrefix.value !== '') staticPrefix.value += ':';
}
})
.catch((err) => NotifyResponse($q, err, 'error'));
}
defineExpose({ open });
</script>

View File

@@ -66,18 +66,14 @@ const internalShowDialog = ref(props.showDialog);
watch(
() => props.showDialog,
(newValue) => {
console.log('watch showDialog', newValue);
internalShowDialog.value = newValue;
},
);
watch(internalShowDialog, (newValue) => {
console.log('watch internalShowDialog', newValue);
emit('update:showDialog', newValue);
if (!newValue) {
console.log('emit cancel');
emit('cancel');
} else {
console.log('emit confirmed');
emit('confirmed');
}
});

View File

@@ -1,126 +0,0 @@
<template>
<DialogFrame ref="Dialog" :width="props.width">
<q-card-section
v-if="props.dialogLabel"
class="text-bold text-left q-mb-none q-pb-none"
:class="'text-' + props.labelColor"
>{{ props.dialogLabel + ': ' + props.datapoint?.path }}</q-card-section
>
<q-card-section>
<q-input
class="q-px-md q-ma-sm"
label="current value"
dense
filled
readonly
v-model="inputValue as string | number"
></q-input>
<q-input
class="q-px-md q-mx-sm"
label="new value"
dense
filled
@keyup.enter="write"
v-model="writeValue as string | number"
></q-input>
</q-card-section>
<q-card-section v-if="props.text" class="text-center" style="white-space: pre-line">{{
props.text
}}</q-card-section>
<q-card-actions align="left" class="text-primary">
<q-btn v-if="props.buttonCancelLabel" flat :label="props.buttonCancelLabel" v-close-popup>
</q-btn>
<q-btn
class="q-mb-xl q-ml-lg q-mt-none"
v-if="props.buttonOkLabel"
color="primary"
:label="props.buttonOkLabel"
@click="write"
>
</q-btn>
</q-card-actions>
</DialogFrame>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import type { Subscribe } from 'src/models/Subscribe';
import type { PropType } from 'vue';
import { setValues } from 'src/services/websocket';
import { NotifyResponse } from 'src/composables/notify';
import { useQuasar } from 'quasar';
const $q = useQuasar();
const Dialog = ref();
const writeValue = ref();
const props = defineProps({
buttonOkLabel: {
type: String,
default: 'OK',
},
labelColor: {
type: String,
default: 'primary',
},
dialogLabel: {
type: String,
default: '',
},
text: {
type: String,
default: '',
},
buttonCancelLabel: {
type: String,
default: '',
},
width: {
type: String,
default: '300px',
},
datapoint: Object as PropType<Subscribe>,
});
const inputValue = ref(props.datapoint?.value);
const open = (sub: Subscribe, type?: string) => {
Dialog.value?.open();
switch (type) {
case 'driver':
console.log(9, sub.drivers);
writeValue.value = sub.drivers;
break;
default:
writeValue.value = sub.value;
}
};
watch(
() => props.datapoint?.value,
(newVal) => {
inputValue.value = newVal;
},
);
function write() {
setValues([{ uuid: props.datapoint?.uuid ?? '', value: writeValue.value ?? undefined }])
.then((resp) => {
if (resp?.set) {
resp.set.forEach((set) => {
inputValue.value = set.value;
});
}
})
.catch((err) => NotifyResponse($q, err));
}
defineExpose({ open });
</script>
<style scoped>
.outercard {
border-radius: 10px;
}
</style>

View File

@@ -105,14 +105,14 @@
</template>
<script setup lang="ts">
import { useQuasar } from 'quasar';
import { watch, reactive, ref } from 'vue';
import type { Light } from 'src/models/Light';
import { setValues } from 'src/services/websocket';
import { setValues } from 'src/vueLib/services/websocket';
import SettingDialog from 'src/components/lights/SettingDomeLight.vue';
import { NotifyResponse } from 'src/composables/notify';
import { useNotify } from 'src/vueLib/general/useNotify';
import { catchError } from 'src/vueLib/models/error';
const $q = useQuasar();
const { NotifyResponse } = useNotify();
const settings = ref(false);
const light = reactive<Light>({
@@ -154,10 +154,10 @@ watch(light, (newVal: Light) => {
},
])
.then((response) => {
NotifyResponse($q, response);
NotifyResponse(response);
})
.catch((err) => {
NotifyResponse($q, err, 'error');
NotifyResponse(catchError(err), 'error');
});
});
</script>

View File

@@ -109,8 +109,8 @@
<script lang="ts" setup>
import { addOne, substractOne } from 'src/utils/number-helpers';
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { updateValue } from 'src/composables/dbm/dbmTree';
import { useQuasar } from 'quasar';
import { updateValue } from 'src/vueLib/dbm/dbmTree';
import { useNotify } from 'src/vueLib/general/useNotify';
const props = defineProps({
reversePan: {
@@ -141,16 +141,15 @@ const props = defineProps({
},
});
const $q = useQuasar();
const { NotifyResponse } = useNotify();
const togglePan = ref(false);
const toggleTilt = ref(false);
const pad = ref<HTMLElement | null>(null);
const dragging = ref(false);
const containerSize = ref(0);
const pan = updateValue(props.panPath, $q, togglePan, props.panPath2);
const tilt = updateValue(props.tiltPath, $q, toggleTilt, props.tiltPath2);
const pan = updateValue(NotifyResponse, props.panPath, togglePan, props.panPath2);
const tilt = updateValue(NotifyResponse, props.tiltPath, toggleTilt, props.tiltPath2);
const scaleFactor = computed(() => containerSize.value / 255);
// 200px → 2, 400px → 4, etc.
@@ -202,7 +201,7 @@ function stopDrag() {
}
function startTouch(e: TouchEvent) {
e.preventDefault(); // ✅ block scroll
e.preventDefault();
const touch = e.touches[0];
if (!touch) return;
dragging.value = true;

View File

@@ -0,0 +1,98 @@
<template>
<div>
<q-card>
<div class="q-pt-md text-black text-bold text-center">{{ cardTitle }}</div>
<q-card-section class="row items-start">
<div class="column justify-center q-mr-xs" style="height: 200px">
<q-btn
@click="changeState"
round
:color="brightness > 0 ? 'yellow' : 'blue'"
icon="lightbulb"
style="position: relative"
/>
</div>
<LightSlider
mainTitle="Dimmer"
:dbm-path="props.path + ':Brightness'"
:opacity="0.5"
class="q-ma-sm"
></LightSlider>
<LightSlider
mainTitle="Red"
:dbm-path="props.path + ':Red'"
color="red"
:opacity="0.8"
class="q-ma-sm"
></LightSlider>
<LightSlider
mainTitle="Green"
:dbm-path="props.path + ':Green'"
:opacity="0.8"
color="green"
class="q-ma-sm"
></LightSlider>
<LightSlider
mainTitle="Blue"
:dbm-path="props.path + ':Blue'"
:opacity="0.8"
color="blue"
class="q-ma-sm"
></LightSlider>
</q-card-section>
</q-card>
</div>
</template>
<script setup lang="ts">
import LightSlider from './LightSlider.vue';
import { onMounted, onUnmounted } from 'vue';
import { unsubscribe, subscribeToPath } from 'src/vueLib/services/websocket';
import { useNotify } from 'src/vueLib/general/useNotify';
import { updateValue } from 'src/vueLib/dbm/dbmTree';
import { removeAllSubscriptions } from 'src/vueLib/models/Subscriptions';
import { catchError } from 'src/vueLib/models/error';
const props = defineProps({
cardTitle: {
type: String,
default: '',
},
path: {
type: String,
required: true,
},
});
const { NotifyResponse } = useNotify();
const brightness = updateValue(NotifyResponse, props.path + ':Brightness');
const state = updateValue(NotifyResponse, props.path + ':State');
onMounted(() => {
subscribeToPath(NotifyResponse, props.path + ':.*');
});
onUnmounted(() => {
unsubscribe([
{
path: props.path,
depth: 0,
},
]).catch((err) => {
NotifyResponse(catchError(err), 'error');
});
removeAllSubscriptions();
});
function changeState() {
if (brightness.value === 0) {
if (state.value === 0) {
brightness.value = 255;
return;
}
brightness.value = state.value;
return;
}
state.value = brightness.value;
brightness.value = 0;
}
</script>

View File

@@ -0,0 +1,18 @@
<template>
<div class="">
<q-card>
<div class="row items-start">
<q-card-section>
<FloodPanel card-title="Left" path="FloodPanels:001" />
</q-card-section>
<q-card-section>
<FloodPanel card-title="Right" path="FloodPanels:002" />
</q-card-section>
</div>
</q-card>
</div>
</template>
<script setup lang="ts">
import FloodPanel from './FloodPanel.vue';
</script>

View File

@@ -56,31 +56,25 @@
color="blue"
class="q-ma-sm"
></LightSlider>
<div class="colums q-ma-xl">
<q-btn color="secondary" @click="settings = !settings" icon="settings">Settings</q-btn>
<SettingDialog :settings-dialog="settings"></SettingDialog>
</div>
</q-card-section>
</q-card>
</div>
</template>
<script setup lang="ts">
import { useQuasar } from 'quasar';
import LightSlider from './LightSlider.vue';
import { ref, onMounted, onUnmounted } from 'vue';
import { unsubscribe, subscribeToPath } from 'src/services/websocket';
import SettingDialog from 'src/components/lights/SettingDomeLight.vue';
import { NotifyResponse } from 'src/composables/notify';
import { updateValue } from 'src/composables/dbm/dbmTree';
import { removeAllSubscriptions } from 'src/models/Subscriptions';
import { onMounted, onUnmounted } from 'vue';
import { unsubscribe, subscribeToPath } from 'src/vueLib/services/websocket';
import { useNotify } from 'src/vueLib/general/useNotify';
import { updateValue } from 'src/vueLib/dbm/dbmTree';
import { removeAllSubscriptions } from 'src/vueLib/models/Subscriptions';
import { catchError } from 'src/vueLib/models/error';
const $q = useQuasar();
const settings = ref(false);
const brightness = updateValue('LightBar:Brightness', $q);
const state = updateValue('LightBar:State', $q);
const { NotifyResponse } = useNotify();
const brightness = updateValue(NotifyResponse, 'LightBar:Brightness');
const state = updateValue(NotifyResponse, 'LightBar:State');
onMounted(() => {
subscribeToPath($q, 'LightBar:.*');
subscribeToPath(NotifyResponse, 'LightBar:.*');
});
onUnmounted(() => {
@@ -90,7 +84,7 @@ onUnmounted(() => {
depth: 0,
},
]).catch((err) => {
NotifyResponse($q, err, 'error');
NotifyResponse(catchError(err), 'error');
});
removeAllSubscriptions();
});

View File

@@ -45,11 +45,9 @@
<script setup lang="ts">
import { ref } from 'vue';
import { useQuasar } from 'quasar';
import { updateValue } from 'src/composables/dbm/dbmTree';
import { updateValue } from 'src/vueLib/dbm/dbmTree';
import { addOne, substractOne } from 'src/utils/number-helpers';
const $q = useQuasar();
import { useNotify } from 'src/vueLib/general/useNotify';
const props = defineProps({
toggleHighLow: {
@@ -123,10 +121,11 @@ const props = defineProps({
},
});
const { NotifyResponse } = useNotify();
const toggle = ref(false);
const localValue = updateValue(
NotifyResponse,
props.dbmPath,
$q,
toggle,
props.dbmPath2,
props.dbmPath3,

View File

@@ -26,7 +26,7 @@ select
:toggle-high-low="true"
dbm-path="MovingHead:Brightness"
dbm-path2="MovingHead:BrightnessFine"
dbm-path3="MovingHead:Strobe"
dbm-path3="MovingHead:Strobe'"
:dbm-value3="255"
:opacity="0.5"
class="q-ma-md"
@@ -101,36 +101,35 @@ select
</template>
<script setup lang="ts">
import { useQuasar } from 'quasar';
import LightSlider from './LightSlider.vue';
import { NotifyResponse } from 'src/composables/notify';
import { useNotify } from 'src/vueLib/general/useNotify';
import { onBeforeUpdate, computed, onMounted, onUnmounted, ref } from 'vue';
import { subscribeToPath, unsubscribe, setValues } from 'src/services/websocket';
import { subscribeToPath, unsubscribe, setValues } from 'src/vueLib/services/websocket';
import { LocalStorage } from 'quasar';
import { updateValue } from 'src/composables/dbm/dbmTree';
import { updateValue } from 'src/vueLib/dbm/dbmTree';
import DragPad from 'src/components/lights/DragPad.vue';
import SettingDialog from './SettingMovingHead.vue';
import type { Settings } from 'src/models/MovingHead';
import { findSubscriptionByPath, removeAllSubscriptions } from 'src/models/Subscriptions';
import { findSubscriptionByPath, removeAllSubscriptions } from 'src/vueLib/models/Subscriptions';
import { catchError } from 'src/vueLib/models/error';
const $q = useQuasar();
const brightness = updateBrightnessValue('MovingHead:Brightness');
const state = updateValue('MovingHead:State', $q);
const { NotifyResponse } = useNotify();
const settings = ref<Settings>({
show: false,
reversePan: false,
reverseTilt: false,
startAddress: 0,
});
const brightness = updateBrightnessValue('MovingHead:Brightness');
const state = updateValue(NotifyResponse, 'MovingHead:State');
onMounted(() => {
settings.value.reversePan = LocalStorage.getItem('reversePan') ?? false;
settings.value.reverseTilt = LocalStorage.getItem('reverseTilt') ?? false;
subscribeToPath($q, 'MovingHead:.*');
subscribeToPath(NotifyResponse, 'MovingHead:.*');
});
onBeforeUpdate(() => {
subscribeToPath($q, 'MovingHead:.*');
subscribeToPath(NotifyResponse, 'MovingHead:.*');
});
onUnmounted(() => {
@@ -140,7 +139,7 @@ onUnmounted(() => {
depth: 0,
},
]).catch((err) => {
NotifyResponse($q, err, 'error');
NotifyResponse(catchError(err), 'error');
});
removeAllSubscriptions();
});
@@ -172,7 +171,7 @@ function updateBrightnessValue(path: string) {
setPaths.push({ path: `MovingHead:Strobe`, value: 255 });
setValues(setPaths)
.then((response) => NotifyResponse($q, response))
.then((response) => NotifyResponse(response))
.catch((err) => console.error(`Failed to update ${path.split(':')[1]}:`, err));
},
});

View File

@@ -21,13 +21,6 @@
>{{ settings.reversePan ? 'Reversed Pan' : 'Normal Pan' }}</q-btn
>
</q-card-section>
<q-card-section>
<q-input
type="number"
label="Start Address"
v-model:model-value="settings.startAddress"
></q-input>
</q-card-section>
<q-card-actions align="right">
<q-btn flat label="Cancel" v-close-popup />
<q-btn flat label="Save" @click="saveSettings" />
@@ -45,7 +38,6 @@ const settings = defineModel<Settings>('settings', {
show: false,
reversePan: false,
reverseTilt: false,
startAddress: 0,
},
required: true,
});

View File

@@ -0,0 +1,117 @@
<template>
<div>
<q-card>
<div class="q-pt-md text-black text-bold text-center">{{ cardTitle }}</div>
<q-card-section class="row items-start">
<div class="column justify-center q-mr-xs" style="height: 200px">
<q-btn
@click="changeState"
round
:color="brightness > 0 ? 'yellow' : 'blue'"
icon="lightbulb"
style="position: relative"
/>
</div>
<LightSlider
mainTitle="Dimmer"
:dbm-path="props.path + ':Brightness'"
:opacity="0.5"
class="q-ma-sm"
></LightSlider>
<LightSlider
mainTitle="Strobe"
:dbm-path="props.path + ':Strobe'"
:opacity="0.5"
class="q-ma-sm"
></LightSlider>
<LightSlider
mainTitle="DimmerFade"
:dbm-path="props.path + ':DimmerFade'"
:opacity="0.5"
:step="50"
class="q-ma-sm"
></LightSlider>
<LightSlider
mainTitle="Red"
:dbm-path="props.path + ':Red'"
color="red"
:opacity="0.8"
class="q-ma-sm"
></LightSlider>
<LightSlider
mainTitle="Green"
:dbm-path="props.path + ':Green'"
:opacity="0.8"
color="green"
class="q-ma-sm"
></LightSlider>
<LightSlider
mainTitle="Blue"
:dbm-path="props.path + ':Blue'"
:opacity="0.8"
color="blue"
class="q-ma-sm"
></LightSlider>
<LightSlider
mainTitle="White"
:dbm-path="props.path + ':White'"
:opacity="0.5"
class="q-ma-sm"
></LightSlider>
</q-card-section>
</q-card>
</div>
</template>
<script setup lang="ts">
import LightSlider from './LightSlider.vue';
import { onMounted, onUnmounted } from 'vue';
import { unsubscribe, subscribeToPath } from 'src/vueLib/services/websocket';
import { useNotify } from 'src/vueLib/general/useNotify';
import { updateValue } from 'src/vueLib/dbm/dbmTree';
import { removeAllSubscriptions } from 'src/vueLib/models/Subscriptions';
import { catchError } from 'src/vueLib/models/error';
const props = defineProps({
cardTitle: {
type: String,
default: '',
},
path: {
type: String,
required: true,
},
});
const { NotifyResponse } = useNotify();
const brightness = updateValue(NotifyResponse, props.path + ':Brightness');
const state = updateValue(NotifyResponse, props.path + ':State');
onMounted(() => {
subscribeToPath(NotifyResponse, props.path + ':.*');
});
onUnmounted(() => {
unsubscribe([
{
path: props.path,
depth: 0,
},
]).catch((err) => {
NotifyResponse(catchError(err), 'error');
});
removeAllSubscriptions();
});
function changeState() {
if (brightness.value === 0) {
if (state.value === 0) {
brightness.value = 255;
return;
}
brightness.value = state.value;
return;
}
state.value = brightness.value;
brightness.value = 0;
}
</script>

View File

@@ -0,0 +1,18 @@
<template>
<div class="">
<q-card>
<div class="row items-start">
<q-card-section>
<StageLight card-title="Left" path="StageLights:001" />
</q-card-section>
<q-card-section>
<StageLight card-title="Right" path="StageLights:002" />
</q-card-section>
</div>
</q-card>
</div>
</template>
<script setup lang="ts">
import StageLight from './StageLight.vue';
</script>

View File

@@ -1,13 +1,14 @@
<template>
<!-- new edit scene dialog-->
<q-dialog v-model="showDialog" persistent>
<q-card style="min-width: 350px">
<DialogFrame ref="sceneDialog" width="350px">
<q-card>
<q-card-section>
<div class="text-primary text-h6">{{ dialogLabel }}</div>
</q-card-section>
<q-card-section class="q-pt-none">
<q-input
:readonly="dialog === 'load'"
class="q-mb-md"
dense
v-model="newScene.name"
@@ -17,6 +18,7 @@
@keyup.enter="saveScene"
/>
<q-input
:readonly="dialog === 'load'"
dense
v-model="newScene.description"
placeholder="Description"
@@ -25,18 +27,19 @@
/>
<div class="q-py-md">
<div class="q-gutter-sm">
<q-checkbox v-model="newScene.movingHead" label="Moving Head" />
<q-checkbox v-model="newScene.stageLights" label="Stage Lights" />
<q-checkbox v-model="newScene.lightBar" label="Light Bar" />
<q-checkbox v-model="newScene.floodPanels" label="Flood Panels" />
<q-checkbox v-model="newScene.movingHead" label="Moving Head" />
</div>
</div>
</q-card-section>
<q-card-actions align="right" class="text-primary">
<q-btn flat label="Cancel" v-close-popup />
<q-btn flat :label="dialogLabel" @click="saveScene()" />
<q-btn flat :label="dialogLabel" v-close-popup @click="saveScene()" />
</q-card-actions>
</q-card>
</q-dialog>
</DialogFrame>
<Dialog
dialogLabel="Duplicate Scene"
:text="`Scene '${newScene.name}' exists already`"
@@ -51,6 +54,7 @@
>
<q-btn
rounded
no-caps
color="primary"
:class="['q-ma-md', 'text-bold', 'text-white']"
@click="openDialog('add')"
@@ -101,6 +105,7 @@
<div>No scenes available</div>
<q-btn
rounded
no-caps
color="primary"
:class="['q-ma-md', 'text-bold', 'text-white']"
@click="openDialog('add')"
@@ -110,76 +115,67 @@
</template>
<script setup lang="ts">
import { NotifyDialog } from 'src/composables/notify';
import { onMounted, reactive, ref } from 'vue';
import { useQuasar } from 'quasar';
import type { Scene } from 'src/models/Scene';
import type { Set } from 'src/models/Set';
import axios from 'axios';
import { api } from 'boot/axios';
import { NotifyResponse } from 'src/composables/notify';
import type { Set } from 'src/vueLib/models/Set';
import { dbmApi } from 'src/boot/axios';
import { useNotify } from 'src/vueLib/general/useNotify';
import Dialog from 'src/components/dialog/OkDialog.vue';
import { setValues } from 'src/services/websocket';
const $q = useQuasar();
const showDialog = ref(false);
import { setValues } from 'src/vueLib/services/websocket';
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import { catchError } from 'src/vueLib/models/error';
import { appApi } from 'src/boot/axios';
const { NotifyResponse, NotifyDialog } = useNotify();
const sceneDialog = ref();
const dialog = ref('');
const existsAlready = ref(false);
const editIndex = ref(-1);
const dialogLabel = ref('');
const newScene = reactive<Scene>({
name: '',
movingHead: false,
stageLights: false,
lightBar: false,
floodPanels: false,
movingHead: false,
});
const scenes = ref<Scene[]>([]);
const host = window.location.hostname;
const port = 9500;
const baseURL = `http://${host}:${port}`;
const quasarApi = axios.create({
baseURL: baseURL,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
onMounted(() => {
quasarApi
.get('/api/loadScenes')
appApi
.get('/loadScenes')
.then((resp) => {
if (resp.data) {
scenes.value = resp.data;
}
})
.catch((err) => {
NotifyResponse($q, err.response.data.error, 'error');
NotifyResponse(catchError(err), 'error');
});
});
function removeScene(name: string) {
dialog.value = '';
NotifyDialog($q, 'Delete', 'Do you want to delete scene: ' + name, 'YES', 'NO')
NotifyDialog('Delete', 'Do you want to delete scene: ' + name, 'YES', 'NO')
.then((res) => {
if (res) {
scenes.value = scenes.value.filter((s) => s.name !== name);
quasarApi
.delete('/api/deleteScene', {
appApi
.delete('/deleteScene', {
data: { name },
})
.then((res) => {
if (res.data) {
NotifyResponse($q, res.data, 'warning');
NotifyResponse(res.data, 'warning');
}
})
.catch((err) => {
NotifyResponse($q, err.response.data.error, 'error');
NotifyResponse(catchError(err), 'error');
});
}
})
.catch((err) => NotifyResponse($q, err.resp, 'warning'));
.catch((err) => NotifyResponse(catchError(err), 'warning'));
}
function openDialog(dialogType: string, scene?: Scene, index?: number) {
@@ -188,9 +184,11 @@ function openDialog(dialogType: string, scene?: Scene, index?: number) {
dialog.value = 'add';
dialogLabel.value = 'Add Scene';
newScene.name = '';
newScene.movingHead = true;
newScene.stageLights = true;
newScene.lightBar = true;
showDialog.value = true;
newScene.floodPanels = true;
newScene.movingHead = true;
break;
case 'edit':
if (!scene) return;
@@ -199,26 +197,22 @@ function openDialog(dialogType: string, scene?: Scene, index?: number) {
dialogLabel.value = 'Update Scene';
editIndex.value = index;
Object.assign(newScene, JSON.parse(JSON.stringify(scene)));
showDialog.value = true;
break;
case 'load':
if (!scene) return;
dialog.value = 'load';
dialogLabel.value = 'Load Scene';
quasarApi
.post('/api/loadScene', scene)
appApi
.post('/loadScene', scene)
.then((res) => {
if (res.data) {
Object.assign(newScene, JSON.parse(JSON.stringify(res.data)));
showDialog.value = true;
}
})
.catch((err) => NotifyResponse($q, err.response.data.error, 'error'));
break;
default:
showDialog.value = false;
.catch((err) => NotifyResponse(catchError(err), 'error'));
break;
}
sceneDialog.value.open();
}
const saveScene = async () => {
@@ -239,9 +233,9 @@ const saveScene = async () => {
return;
}
if (newScene.movingHead) {
if (newScene.stageLights) {
sendValues.push({
path: 'MovingHead',
path: 'StageLights',
query: { depth: 0 },
});
}
@@ -253,12 +247,26 @@ const saveScene = async () => {
});
}
if (newScene.floodPanels) {
sendValues.push({
path: 'FloodPanels',
query: { depth: 0 },
});
}
if (newScene.movingHead) {
sendValues.push({
path: 'MovingHead',
query: { depth: 0 },
});
}
if (sendValues.length > 0) {
try {
const res = await api.post('/json_data', { get: sendValues });
const res = await dbmApi.post('/json_data', { get: sendValues });
newScene.values = res.data.get;
} catch (err) {
NotifyResponse($q, err as Error, 'error');
NotifyResponse(err as Error, 'error');
}
} else {
newScene.values = [];
@@ -269,27 +277,28 @@ const saveScene = async () => {
// Sort alphabetically by scene name
scenes.value.sort((a, b) => a.name.localeCompare(b.name));
quasarApi
.post('/api/saveScene', JSON.stringify(newScene))
appApi
.post('/saveScene', JSON.stringify(newScene))
.then((res) => {
if (res.data) {
NotifyResponse($q, res.data);
NotifyResponse(res.data);
}
})
.catch((err) => {
NotifyResponse($q, err.response.data.error, 'error');
NotifyResponse(catchError(err), 'error');
});
scenes.value = [...scenes.value];
break;
case 'edit':
if (exists) {
existsAlready.value = true;
return;
}
if (newScene.movingHead) {
if (newScene.stageLights) {
sendValues.push({
path: 'MovingHead',
path: 'StageLights',
query: { depth: 0 },
});
}
@@ -301,12 +310,26 @@ const saveScene = async () => {
});
}
if (newScene.floodPanels) {
sendValues.push({
path: 'FloodPanels',
query: { depth: 0 },
});
}
if (newScene.movingHead) {
sendValues.push({
path: 'MovingHead',
query: { depth: 0 },
});
}
if (sendValues.length > 0) {
try {
const res = await api.post('/json_data', { get: sendValues });
const res = await dbmApi.post('/json_data', { get: sendValues });
newScene.values = res.data.get;
} catch (err) {
NotifyResponse($q, err as Error, 'error');
NotifyResponse(err as Error, 'error');
}
} else {
newScene.values = [];
@@ -315,47 +338,51 @@ const saveScene = async () => {
scenes.value.sort((a, b) => a.name.localeCompare(b.name));
scenes.value = [...scenes.value];
quasarApi
.post('/api/saveScene', JSON.stringify(newScene))
appApi
.post('/saveScene', JSON.stringify(newScene))
.then((res) => {
if (res.data) {
NotifyResponse($q, res.data);
NotifyResponse(res.data);
}
})
.catch((err) => {
NotifyResponse($q, err.response.data.error, 'error');
NotifyResponse(catchError(err), 'error');
});
scenes.value = [...scenes.value];
break;
case 'load':
{
const setPaths = <Set[]>[];
if (newScene.movingHead) {
newScene.values?.forEach((element) => {
if (element.path && element.path.includes('MovingHead')) {
setPaths.push({ path: element.path, value: element.value });
}
});
}
newScene.values?.forEach((element) => {
if (!element.path) return;
if (newScene.stageLights && element.path.includes('StageLights'))
setPaths.push({ uuid: element.uuid, path: element.path, value: element.value });
if (newScene.lightBar && element.path.includes('LightBar'))
setPaths.push({ uuid: element.uuid, path: element.path, value: element.value });
if (newScene.floodPanels && element.path.includes('FloodPanels'))
setPaths.push({ uuid: element.uuid, path: element.path, value: element.value });
if (newScene.movingHead && element.path.includes('MovingHead'))
setPaths.push({ uuid: element.uuid, path: element.path, value: element.value });
});
if (newScene.lightBar) {
newScene.values?.forEach((element) => {
if (element.path && element.path.includes('LightBar')) {
setPaths.push({ path: element.path, value: element.value });
}
});
}
setValues(setPaths)
.then((response) => {
NotifyResponse($q, response);
NotifyResponse(response);
})
.catch((err) => console.error(`Failed to load scene ${newScene.name}`, err));
.catch((err) => {
NotifyResponse(`Failed to load scene ${newScene.name}`, 'warning');
NotifyResponse(catchError(err), 'error');
});
}
break;
}
dialog.value = '';
showDialog.value = false;
};
</script>

View File

@@ -1,131 +0,0 @@
import { reactive, computed, type Ref } from 'vue';
import type { QVueGlobals } from 'quasar';
import type { Subs } from 'src/models/Subscribe';
import { NotifyResponse } from '../notify';
import { setValues } from 'src/services/websocket';
import { findSubscriptionByPath } from 'src/models/Subscriptions';
export const dbmData = reactive<TreeNode[]>([]);
//export const reactiveValues = new Map<string, Ref<string | number | boolean | null>>();
export type TreeNode = {
path: string | undefined;
key?: string; // optional: useful for QTree's node-key
lazy: boolean;
children?: TreeNode[];
};
type TreeMap = {
[key: string]: {
__children: TreeMap;
uuid?: string;
value?: string | number | boolean | null;
lazy: boolean;
};
};
const root: TreeMap = {};
export function buildTree(subs: Subs): TreeNode[] {
for (const { path, uuid, value, hasChild } of subs) {
if (!path) continue;
const parts = path.split(':');
let current = root;
parts.forEach((part, idx) => {
if (!part) return;
if (!current[part]) {
current[part] = { __children: {}, lazy: true };
}
if (idx === parts.length - 1 && uuid) {
if (current[part].uuid === uuid) return;
current[part].uuid = uuid;
current[part].value = value?.value ?? null;
current[part].lazy = hasChild ?? false;
}
current = current[part].__children;
});
}
function mapToTree(map: TreeMap): TreeNode[] {
return Object.entries(map).map(([key, node]) => ({
path: key,
key: node.uuid ?? key,
value: node.value,
lazy: node.lazy,
children: mapToTree(node.__children),
}));
}
const newTree = [
{
path: 'DBM',
key: '00000000-0000-0000-0000-000000000000',
lazy: true,
children: mapToTree(root),
},
];
return dbmData.splice(0, dbmData.length, ...newTree);
}
export function removeSubtreeByParentKey(parentKey: string) {
function removeChildrenAndMarkLazy(nodes: TreeNode[], targetKey: string): boolean {
for (const node of nodes) {
if (node.key === targetKey) {
delete node.children;
node.lazy = true;
return true;
}
if (node.children) {
const found = removeChildrenAndMarkLazy(node.children, targetKey);
if (found) return true;
}
}
return false;
}
removeChildrenAndMarkLazy(dbmData, parentKey);
}
export function updateValue(
path1: string,
$q: QVueGlobals,
toggle?: Ref<boolean>,
path2?: string,
path3?: string,
value3?: number,
) {
return computed({
get() {
const sub = findSubscriptionByPath(toggle?.value && path2 ? path2 : path1);
return sub?.value ? Number(sub.value ?? 0) : 0;
},
set(val) {
const baseValue = val;
const setPaths = [];
if (toggle?.value && path2) {
setPaths.push({ path: path2, value: baseValue });
} else {
setPaths.push({ path: path1, value: baseValue });
}
if (path3) {
setPaths.push({ path: path3, value: value3 ? value3 : baseValue });
}
setValues(setPaths)
.then((response) => NotifyResponse($q, response))
.catch((err) => {
NotifyResponse(
$q,
`Failed to update [${path1 + ' ' + path2 + ' ' + path3}]: ${err}`,
'error',
);
});
},
});
}

View File

@@ -1,67 +0,0 @@
import type { Response } from 'src/models/Response';
import type { QVueGlobals } from 'quasar';
export function NotifyResponse(
$q: QVueGlobals,
response: Response | string | undefined,
type?: 'warning' | 'error',
timeout: number = 5000,
) {
let color = 'green';
let icon = 'check_circle';
switch (type) {
case 'warning':
color = 'orange';
icon = 'warning';
break;
case 'error':
color = 'red';
icon = 'error';
break;
}
if (response) {
const message = typeof response === 'string' ? response : (response.message ?? '');
if (message === '') {
return;
}
color = typeof response === 'string' ? color : response?.error ? 'red' : color;
icon = typeof response === 'string' ? icon : response?.error ? 'error' : icon;
$q?.notify({
message: message,
color: color,
position: 'bottom-right',
icon: icon,
timeout: timeout,
});
}
}
export function NotifyDialog(
$q: QVueGlobals,
title: string,
text: string,
okText?: string,
cancelText?: string,
) {
return new Promise((resolve) => {
$q.dialog({
title: title,
message: text,
persistent: true,
ok: okText ?? 'OK',
cancel: cancelText ?? 'CANCEL',
})
.onOk(() => {
resolve(true);
})
.onCancel(() => {
resolve(false);
})
.onDismiss(() => {
resolve(false);
});
});
}

View File

@@ -10,10 +10,11 @@
/>
<q-btn flat dense round icon="menu" aria-label="Menu" @click="toggleLeftDrawer" />
<q-toolbar-title> Light Control </q-toolbar-title>
<q-toolbar-title> {{ productName }} </q-toolbar-title>
<div>Version {{ version }}</div>
<q-btn dense icon="refresh" square class="q-px-md q-ml-md" @click="refresh" />
<LoginMenu />
</q-toolbar>
</q-header>
@@ -25,9 +26,12 @@
<q-item to="/scenes" clickable v-ripple @click="closeDrawer">
<q-item-section>Scenes</q-item-section>
</q-item>
<q-item to="/data" clickable v-ripple @click="closeDrawer">
<q-item v-if="autorized" to="/data" clickable v-ripple @click="closeDrawer">
<q-item-section>Data</q-item-section>
</q-item>
<q-item to="/services" clickable v-ripple @click="closeDrawer">
<q-item-section>Services</q-item-section>
</q-item>
</q-list>
</q-drawer>
<q-page-container>
@@ -38,10 +42,14 @@
<script setup lang="ts">
import logo from 'src/assets/LOGO_CF-ICON_color.svg';
import { ref } from 'vue';
import { version } from '../..//package.json';
import { computed, ref } from 'vue';
import { version, productName } from '../../package.json';
import LoginMenu from 'src/vueLib/login/LoginMenu.vue';
import { useUserStore } from 'src/vueLib/login/userStore';
const leftDrawerOpen = ref(false);
const user = useUserStore();
const autorized = computed(() => !!user.isAuthorizedAs(['admin']));
function toggleLeftDrawer() {
leftDrawerOpen.value = !leftDrawerOpen.value;

View File

@@ -14,5 +14,4 @@ export type Settings = {
show: boolean;
reversePan: boolean;
reverseTilt: boolean;
startAddress: number;
};

View File

@@ -1,16 +0,0 @@
export type Publish = {
event: string;
uuid: string;
path: string;
type: string;
value: string | number | boolean | null;
};
export type Pubs = Publish[];
import { updateSubscriptionValue } from './Subscriptions';
export function publishToSubscriptions(pubs: Pubs) {
pubs.forEach((pub) => {
updateSubscriptionValue(pub.uuid, pub.value);
});
}

View File

@@ -1,10 +0,0 @@
import type { Gets } from './Get';
import type { Sets } from './Set';
import type { Subs } from './Subscribe';
export type Request = {
get?: Gets;
set?: Sets;
subscribe?: Subs;
unsubscribe?: Subs;
};

View File

@@ -1,9 +1,11 @@
import type { Value } from './Value';
import type { Value } from '../vueLib/models/Value';
export interface Scene {
name: string;
description?: string;
movingHead: boolean;
stageLights: boolean;
lightBar: boolean;
floodPanels: boolean;
movingHead: boolean;
values?: Value[];
}

View File

@@ -4,17 +4,17 @@
</template>
<script setup lang="ts">
import DBMTree from 'src/components/dbm/DBMTree.vue';
import { api } from 'src/boot/axios';
import { NotifyResponse } from 'src/composables/notify';
import { useQuasar } from 'quasar';
import DBMTree from 'src/vueLib/dbm/DBMTree.vue';
import { dbmApi } from 'src/boot/axios';
import { useNotify } from 'src/vueLib/general/useNotify';
import { catchError } from 'src/vueLib/models/error';
const $q = useQuasar();
const { NotifyResponse } = useNotify();
function saveDBM() {
api
dbmApi
.get('saveData')
.then((resp) => NotifyResponse($q, resp.data))
.catch((err) => NotifyResponse($q, err));
.then((resp) => NotifyResponse(resp.data))
.catch((err) => NotifyResponse(catchError(err), 'error'));
}
</script>

View File

@@ -1,16 +1,24 @@
<template>
<q-page>
<q-tabs v-model="tab">
<q-tab name="movingHead" label="Moving Head" />
<q-tab name="lightBar" label="Light Bar" />
<q-tab no-caps name="stageLights" label="Stage Lights" />
<q-tab no-caps name="movingHead" label="Moving Head" />
<q-tab no-caps name="lightBar" label="Light Bar" />
<q-tab no-caps name="floodPanels" label="Flood Panels" />
</q-tabs>
<q-tab-panels v-model="tab" animated class="text-white">
<q-tab-panel name="movingHead">
<moving-head />
<q-tab-panel name="stageLights">
<stage-lights />
</q-tab-panel>
<q-tab-panel name="lightBar">
<LightBar />
</q-tab-panel>
<q-tab-panel name="floodPanels">
<FloodPanels />
</q-tab-panel>
<q-tab-panel name="movingHead">
<moving-head />
</q-tab-panel>
</q-tab-panels>
</q-page>
</template>
@@ -18,6 +26,8 @@
<script setup lang="ts">
import MovingHead from 'src/components/lights/MovingHead.vue';
import LightBar from 'src/components/lights/LightBarCBL.vue';
import FloodPanels from 'src/components/lights/FloodPanels.vue';
import StageLights from 'src/components/lights/StageLights.vue';
import { ref, onMounted, watch } from 'vue';
const tab = ref('movingHead');
const STORAGE_KEY = 'lastTabUsed';

View File

@@ -0,0 +1,60 @@
<template>
<q-card>
<q-card-section>
<div class="text-bold text-primary">Services</div>
</q-card-section>
<q-card-section>
<q-table v-if="driverRows?.length > 0" :rows="driverRows" :columns="columns"> </q-table>
<div v-else class="q-pa-md text-grey text-center">
<div>No services available</div>
<q-btn
no-caps
rounded
color="primary"
:class="['q-ma-md', 'text-bold', 'text-white']"
:disable="userStore.user?.role !== 'admin'"
@click="addNewDriver"
>Add First Service</q-btn
>
</div>
</q-card-section>
</q-card>
<service-dialog ref="refServiceDialog"></service-dialog>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { QTableProps } from 'quasar';
import { useUserStore } from 'src/vueLib/login/userStore';
import ServiceDialog from 'src/vueLib/services/dialog/ServiceDialog.vue';
const userStore = useUserStore();
const refServiceDialog = ref();
const driverRows = reactive([]);
const columns = [
{ name: 'path', label: 'Path', field: 'path', align: 'left' },
{
name: 'type',
label: 'Type',
field: 'type',
align: 'left',
},
{
name: 'value',
label: 'Value',
field: 'value',
align: 'left',
},
{
name: 'drivers',
label: 'Drivers',
field: 'drivers',
align: 'center',
},
] as QTableProps['columns'];
function addNewDriver() {
refServiceDialog.value.open();
}
</script>

View File

@@ -19,7 +19,9 @@ import routes from './routes';
export default defineRouter(function (/* { store, ssrContext } */) {
const createHistory = process.env.SERVER
? createMemoryHistory
: (process.env.VUE_ROUTER_MODE === 'history' ? createWebHistory : createWebHashHistory);
: process.env.VUE_ROUTER_MODE === 'history'
? createWebHistory
: createWebHashHistory;
const Router = createRouter({
scrollBehavior: () => ({ left: 0, top: 0 }),
@@ -30,6 +32,5 @@ export default defineRouter(function (/* { store, ssrContext } */) {
// quasar.conf.js -> build -> publicPath
history: createHistory(process.env.VUE_ROUTER_BASE),
});
return Router;
});

View File

@@ -6,8 +6,16 @@ const routes: RouteRecordRaw[] = [
component: () => import('layouts/MainLayout.vue'),
children: [
{ path: '', component: () => import('pages/MainPage.vue') },
{ path: '/data', component: () => import('pages/DataPage.vue') },
{
path: '/data',
component: () => import('pages/DataPage.vue'),
meta: { requiresAuth: true, requiresAdmin: true },
},
{ path: '/scenes', component: () => import('components/scenes/ScenesPage.vue') },
{
path: '/services',
component: () => import('pages/ServicesPage.vue'),
},
],
},

View File

@@ -3,22 +3,90 @@
<div class="text-primary q-ma-md">Datatypes *</div>
<div>
<div class="row q-gutter-sm q-ml-sm">
<q-card-section class="items-between">
<RadioButton class="q-ma-xs" v-model:opt="datatype" text="None" hint="none">
<div>
<div class="text-grey text-bold">General</div>
<RadioButton
class="q-my-xs q-px-lg q-mr-sm"
v-model:opt="datatype"
text="None"
hint="none"
>
</RadioButton>
<RadioButton class="q-ma-xs" v-model:opt="datatype" text="String" hint="Text">
<RadioButton
class="q-my-xs q-px-lg q-mr-sm"
v-model:opt="datatype"
text="String"
hint="Text"
>
</RadioButton>
<RadioButton class="q-ma-xs" v-model:opt="datatype" text="Bool" hint="On / Off">
<RadioButton class="q-my-xs q-px-lg" v-model:opt="datatype" text="Bool" hint="On / Off">
</RadioButton>
</q-card-section>
<RadioButton v-model:opt="datatype" text="Uint8" hint="0 - 255"> </RadioButton>
<RadioButton v-model:opt="datatype" text="Uint16" hint="0 - 65535"> </RadioButton>
<RadioButton v-model:opt="datatype" text="Uint32" hint="0 - 429496..."> </RadioButton>
<RadioButton v-model:opt="datatype" text="Int8" hint="-128 - 127"> </RadioButton>
<RadioButton v-model:opt="datatype" text="Int16" hint="-32768 - 3..."> </RadioButton>
<RadioButton v-model:opt="datatype" text="Int32" hint="-21474836..."> </RadioButton>
<RadioButton v-model:opt="datatype" text="Int32" hint="-2^63 - (2^...)"> </RadioButton>
<RadioButton v-model:opt="datatype" text="double" hint="1.7E 1/- 3..."> </RadioButton>
</div>
<div>
<div class="text-grey text-bold">Numbers</div>
<div>
<RadioButton
class="q-my-xs q-px-lg q-mr-sm"
v-model:opt="datatype"
text="Uint8"
hint="0 - 255"
>
</RadioButton>
<RadioButton
class="q-my-xs q-px-lg q-mr-sm"
v-model:opt="datatype"
text="Uint16"
hint="0 - 65535"
>
</RadioButton>
<RadioButton
class="q-my-xs q-px-sm"
v-model:opt="datatype"
text="Uint32"
hint="0 - 429496..."
>
</RadioButton>
</div>
<div>
<RadioButton
class="q-my-xs q-mr-sm"
v-model:opt="datatype"
text="Int8"
hint="-128 - 127"
>
</RadioButton>
<RadioButton
class="q-my-xs q-mr-sm"
v-model:opt="datatype"
text="Int16"
hint="-32768 - 3..."
>
</RadioButton>
<RadioButton
class="q-my-xs q-px-sm"
v-model:opt="datatype"
text="Int32"
hint="-21474836..."
>
</RadioButton>
</div>
<div>
<RadioButton
class="q-my-xs q-px-sm q-mr-sm"
v-model:opt="datatype"
text="Int"
hint="-2^63 - (2^...)"
>
</RadioButton>
<RadioButton
class="q-my-xs q-px-md"
v-model:opt="datatype"
text="Double"
hint="1.7E 1/- 3..."
>
</RadioButton>
</div>
</div>
</div>
</div>
</q-card>
@@ -26,7 +94,10 @@
<script setup lang="ts">
import RadioButton from './RadioButton.vue';
import { ref } from 'vue';
import { ref, watch } from 'vue';
const datatype = ref('none');
const emit = defineEmits(['update:datatype']);
const datatype = ref('None');
watch(datatype, (newVal) => emit('update:datatype', newVal));
</script>

View File

@@ -1,7 +1,7 @@
<template>
<q-btn style="border-radius: 8px" no-caps
><q-radio v-model="opt" :val="props.text"></q-radio>
<div class="column items-start q-mx-md">
<div class="column items-start q-mx-sm">
<div class="text-body1 text-black">{{ props.text }}</div>
<div class="text-caption text-grey">{{ props.hint }}</div>
</div>

125
src/vueLib/dbm/DBMTree.vue Normal file
View File

@@ -0,0 +1,125 @@
<template>
<q-card>
<div class="row">
<q-card-section class="col-4 scroll tree-container">
<q-tree
class="text-blue text-bold"
dense
:nodes="dbmData"
node-key="key"
no-transition
:default-expand-all="false"
v-model:expanded="expanded"
@update:expanded="onExpandedChange(expanded)"
@lazy-load="onLazyLoad"
>
<template v-slot:[`default-header`]="props">
<div
class="row items-center text-blue"
@contextmenu.prevent.stop="openSubMenu($event, props.node)"
>
<div class="row items-center text-blue"></div>
<div>{{ props.node.path }}</div>
</div>
</template>
</q-tree>
<sub-menu ref="subMenuRef"></sub-menu>
</q-card-section>
<dataTable class="col-8" />
</div>
</q-card>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import {
type TreeNode,
dbmData,
onExpandedChange,
expanded,
buildTree,
} from '../../vueLib/dbm/dbmTree';
import DataTable from './DataTable.vue';
import { useNotify } from '../general/useNotify';
import { QCard } from 'quasar';
import { unsubscribe } from '../services/websocket';
import { onBeforeRouteLeave } from 'vue-router';
import SubMenu from './SubMenu.vue';
import { convertToSubscribes, type RawSubs } from '../models/Subscribe';
import { getRequest } from '../models/Request';
import { catchError } from '../models/error';
const { NotifyResponse } = useNotify();
const ZERO_UUID = '00000000-0000-0000-0000-000000000000';
onMounted(() => {
getRequest('', '.*', 1)
.then((res) => {
const test = res;
if (res) buildTree(convertToSubscribes(test as RawSubs));
})
.catch((err) => NotifyResponse(catchError(err), 'error'));
});
onBeforeRouteLeave(() => {
unsubscribe([{ path: '.*', depth: 0 }]).catch((err) => NotifyResponse(catchError(err), 'error'));
});
function onLazyLoad({
node,
done,
fail,
}: {
node: TreeNode;
done: (children: TreeNode[]) => void;
fail: () => void;
}) {
getRequest(node.key ?? ZERO_UUID, '', 2)
.then((resp) => {
if (resp) done(buildTree(convertToSubscribes(resp as RawSubs)));
else done([]); // no children returned
})
.catch((err) => {
NotifyResponse(err, 'error');
fail(); // trigger the fail handler
});
}
const subMenuRef = ref();
function openSubMenu(event: MouseEvent, uuid: string) {
subMenuRef.value?.open(event, uuid);
}
</script>
<style scoped>
.tree-container {
overflow-y: auto;
}
@media (max-width: 599px) {
.tree-container {
max-height: 50vh;
}
}
@media (min-width: 600px) and (max-width: 1023px) {
.tree-container {
max-height: 60vh;
}
}
@media (min-width: 1024px) and (max-width: 1439px) {
.tree-container {
max-height: 70vh;
}
}
@media (min-width: 1440px) and (max-width: 1919px) {
.tree-container {
max-height: 80vh;
}
}
@media (min-width: 1920px) {
.tree-container {
max-height: 90vh;
}
}
</style>

View File

@@ -0,0 +1,139 @@
<template>
<div class="q-pa-md">
<q-table
v-if="tableRows.length > 0"
style="height: 600px"
flat
bordered
:title="tableRows[0]?.path"
:rows="tableRows"
:columns="columns"
row-key="path"
virtual-scroll
:rows-per-page-options="[0]"
>
<template v-slot:body-cell-path="props">
<q-td :props="props" @click="openDialog(props.row, 'rename')">
<div
:class="[
'text-left',
props.row.path?.split(':')[0] !== 'System' && props.row.path !== 'DBM'
? 'cursor-pointer'
: '',
'q-mx-sm',
]"
>
{{ props.row.path?.split(':').pop() ?? '' }}
</div>
</q-td>
</template>
<template v-slot:body-cell-type="props">
<q-td :props="props" @click="openDialog(props.row, 'type')">
<div
:class="[
'text-center',
props.row.path?.split(':')[0] !== 'System' && props.row.path !== 'DBM'
? 'cursor-pointer'
: '',
'q-mx-sm',
]"
>
{{ convertFromType(props.row.type) }}
</div>
</q-td>
</template>
<template v-slot:body-cell-value="props">
<q-td :props="props" @click="openDialog(props.row, 'value')">
<div :class="['text-center', 'cursor-pointer', 'q-mx-sm']">
{{ props.row.value }}
</div>
</q-td>
</template>
<template v-slot:body-cell-drivers="props">
<q-td :props="props" @click="openDialog(props.row, 'drivers')">
<div
v-if="props.row.type !== 'NONE' || props.row.path?.split(':')[0] !== 'System'"
:class="['cursor-pointer']"
>
<q-icon size="sm" name="cell_tower" :color="props.row.drivers ? 'blue-5' : 'grey-4'" />
</div>
</q-td>
</template>
</q-table>
<RenameDialog
dialogLabel="Rename Datapoint"
width="400px"
button-ok-label="Rename"
ref="renameDialog"
/>
<UpdateDialog width="400px" button-ok-label="Write" ref="updateDialog" />
<UpdateDriver width="400px" ref="updateDriverDialog" />
<UpdateDatatype
width="400px"
button-ok-label="Update"
ref="updateDatatype"
dialog-label="Update Datatype"
/>
</div>
</template>
<script setup lang="ts">
import UpdateDialog from './dialog/UpdateValueDialog.vue';
import RenameDialog from './dialog/RenameDatapoint.vue';
import UpdateDatatype from './dialog/UpdateDatatype.vue';
import UpdateDriver from './dialog/UpdateDriverDialog.vue';
import type { QTableProps } from 'quasar';
import type { Subscribe } from '../models/Subscribe';
import { computed, ref } from 'vue';
import { TableSubs } from '../dbm/updateTable';
import { convertFromType } from './Datapoint';
const renameDialog = ref();
const updateDialog = ref();
const updateDriverDialog = ref();
const updateDatatype = ref();
const openDialog = (sub: Subscribe, type?: string) => {
if (sub.path?.split(':')[0] === 'System' && sub.path !== 'DBM') return;
switch (type) {
case 'type':
updateDatatype.value.open(sub.uuid);
break;
case 'rename':
renameDialog.value.open(sub.uuid);
break;
case 'value':
if (sub.type === 'NONE') return;
updateDialog.value?.open(ref(sub), type);
break;
case 'drivers':
if (sub.path === 'DBM' || sub.type === 'NONE') return;
updateDriverDialog.value?.open(sub);
break;
}
};
const tableRows = computed(() => [...(TableSubs.value ?? [])]);
const columns = [
{ name: 'path', label: 'Path', field: 'path', align: 'left' },
{
name: 'type',
label: 'Type',
field: 'type',
align: 'left',
},
{
name: 'value',
label: 'Value',
field: 'value',
align: 'left',
},
{
name: 'drivers',
label: 'Drivers',
field: 'drivers',
align: 'center',
},
] as QTableProps['columns'];
</script>

View File

@@ -0,0 +1,72 @@
import type { Gets } from '../models/Get';
import type { Sets } from '../models/Set';
export function datapointRequestForCopy(response: Gets, oldPath: string, newPath: string): Sets {
const copySet = <Sets>[];
response.forEach((get) => {
copySet.push({
path: typeof get.path === 'string' ? get.path.replace(oldPath, newPath) : '',
type: get.type ? get.type : '',
value: get.value,
rights: get.rights ? get.rights : '',
});
});
return copySet;
}
export function convertFromType(type: string): string {
switch (type) {
case 'STR':
return 'string';
case 'BIT':
return 'bool';
case 'BYU':
return 'uint8';
case 'WOU':
return 'uint16';
case 'DWU':
return 'uint32';
case 'BYS':
return 'int8';
case 'WOS':
return 'int16';
case 'DWS':
return 'int32';
case 'LOU':
return 'uint64';
case 'LOS':
return 'int64';
case 'F64':
return 'double';
default:
return 'none';
}
}
export function convertToType(type: string): string {
switch (type) {
case 'String':
return 'STR';
case 'Bool':
return 'BIT';
case 'Uint8':
return 'BYU';
case 'Int8':
return 'BYS';
case 'Uint16':
return 'WOU';
case 'Int16':
return 'WOS';
case 'Uint32':
return 'DWU';
case 'Int32':
return 'DWS';
case 'Int':
return 'LOS';
case 'Double':
return 'F64';
default:
return 'NONE';
}
}

179
src/vueLib/dbm/SubMenu.vue Normal file
View File

@@ -0,0 +1,179 @@
<template>
<q-menu ref="contextMenuRef" context-menu>
<q-list>
<q-item :clickable="!disableAll" v-close-popup @click="handleAction('Add')">
<q-item-section>
<div class="row">
<div class="col-5">
<q-icon
:color="disableAll ? 'grey-5' : 'primary'"
class="q-pr-sm"
name="add"
size="xs"
left
/>
</div>
<div :class="['col-7', disableAll ? 'text-grey-5' : 'text-primary']">Add</div>
</div>
</q-item-section>
</q-item>
<q-item
:class="disable ? 'text-grey-5' : ''"
:clickable="!disable"
v-close-popup
@click="handleAction('Rename')"
><q-item-section>
<div class="row">
<div class="col-5">
<q-icon
:color="disable ? 'grey-5' : 'primary'"
class="q-pr-sm"
name="edit"
size="xs"
left
/>
</div>
<div :class="['col-7', disable ? 'text-grey-5' : 'text-primary']">Rename</div>
</div>
</q-item-section>
</q-item>
<q-item
:class="disable ? 'text-grey-5' : ''"
:clickable="!disable"
v-close-popup
@click="handleAction('Delete')"
><q-item-section>
<div class="row">
<div class="col-5">
<q-icon
:color="disable ? 'grey-5' : 'primary'"
class="q-pr-sm"
name="delete"
size="xs"
left
/>
</div>
<div :class="['col-7', disable ? 'text-grey-5' : 'text-primary']">Delete</div>
</div>
</q-item-section>
</q-item>
<q-item
:color="disable ? 'grey-5' : 'primary'"
:clickable="!disable"
v-close-popup
@click="handleAction('Copy')"
>
<q-item-section>
<div class="row">
<div class="col-5">
<q-icon
:color="disable ? 'grey-5' : 'primary'"
class="q-pr-sm"
name="content_copy"
size="xs"
left
/>
</div>
<div :class="['col-7', disable ? 'text-grey-5' : 'text-primary']">Copy</div>
</div>
</q-item-section>
</q-item>
<q-item
:color="disable ? 'grey-5' : 'primary'"
:clickable="!disable"
v-close-popup
@click="handleAction('Datatype')"
>
<q-item-section>
<div class="row">
<div class="col-5">
<q-icon
:color="disable ? 'grey-5' : 'primary'"
class="q-pr-sm"
name="text_fields"
size="xs"
left
/>
</div>
<div :class="['col-7', disable ? 'text-grey-5' : 'text-primary']">Datatype</div>
</div>
</q-item-section>
</q-item>
</q-list>
</q-menu>
<RenameDatapoint :dialogLabel="label" width="700px" button-ok-label="Rename" ref="renameDialog" />
<AddDialog :dialogLabel="label" width="750px" button-ok-label="Add" ref="addDialog" />
<RemoveDialog :dialogLabel="label" width="350px" button-ok-label="Remove" ref="removeDialog" />
<CopyDialog :dialogLabel="label" width="300px" button-ok-label="Copy" ref="copyDialog" />
<UpdateDatapoint
:dialogLabel="label"
width="300px"
button-ok-label="Update"
ref="datatypeDialog"
/>
</template>
<script setup lang="ts">
import AddDialog from './dialog/AddDatapoint.vue';
import RemoveDialog from './dialog/RemoveDatapoint.vue';
import CopyDialog from './dialog/CopyDatapoint.vue';
import UpdateDatapoint from './dialog/UpdateDatatype.vue';
import { ref } from 'vue';
import { type TreeNode } from '../dbm/dbmTree';
import { findSubscriptionByUuid } from '../models/Subscriptions';
import RenameDatapoint from './dialog/RenameDatapoint.vue';
const ZERO_UUID = '00000000-0000-0000-0000-000000000000';
const renameDialog = ref();
const addDialog = ref();
const removeDialog = ref();
const copyDialog = ref();
const datatypeDialog = ref();
const datapointUuid = ref('');
const contextMenuRef = ref();
const label = ref('');
const disable = ref(false);
const disableAll = ref(false);
function handleAction(action: string) {
switch (action) {
case 'Rename':
label.value = 'Rename Datapoint';
renameDialog.value?.open(datapointUuid.value);
break;
case 'Add':
label.value = 'Add New Datapoint';
addDialog.value?.open(datapointUuid.value);
break;
case 'Delete':
label.value = 'Remove Datapoint';
removeDialog.value.open(datapointUuid.value);
break;
case 'Copy':
label.value = 'Copy Datapoint';
copyDialog.value.open(datapointUuid.value);
break;
case 'Datatype':
label.value = 'Update Datatype';
datatypeDialog.value.open(datapointUuid.value);
break;
}
}
const open = (event: MouseEvent, sub: TreeNode) => {
disable.value = false;
disableAll.value = false;
if (findSubscriptionByUuid(sub.key ?? '')?.path?.includes('System')) {
disable.value = true;
disableAll.value = true;
}
if (sub.key === ZERO_UUID) disable.value = true;
event.preventDefault();
datapointUuid.value = sub.key ?? '';
contextMenuRef.value?.show(event);
};
defineExpose({ open });
</script>

264
src/vueLib/dbm/dbmTree.ts Normal file
View File

@@ -0,0 +1,264 @@
import { ref, computed, type Ref } from 'vue';
import { convertToSubscribes, type Subs } from '../models/Subscribe';
import { setValues, subscribe, unsubscribe } from '../services/websocket';
import {
findSubscriptionByPath,
addRawSubscriptions,
removeAllSubscriptions,
} from '../models/Subscriptions';
import { UpdateTable } from '..//dbm/updateTable';
import type { Response } from '..//models/Response';
import type { RawSubs } from '..//models/Subscribe';
import { getRequest } from '../models/Request';
import type { Pubs } from '../models/Publish';
const ZERO_UUID = '00000000-0000-0000-0000-000000000000';
export const dbmData = ref<TreeNode[]>([]);
export const expanded = ref<string[]>([]);
let lastExpanded: string[] = [];
export type TreeNode = {
path?: string;
key?: string;
lazy: boolean;
children?: TreeNode[];
};
type TreeMap = {
[key: string]: {
__children: TreeMap;
uuid?: string;
value?: string | number | boolean | null;
lazy: boolean;
};
};
const root: TreeMap = {};
export function buildTreeWithRawSubs(subs: RawSubs): TreeNode[] {
return buildTree(convertToSubscribes(subs));
}
export function buildTree(subs: Subs | null): TreeNode[] {
if (subs) {
for (const { path, uuid, value, hasChild } of subs) {
if (!path) continue;
const parts = path.split(':');
let current = root;
parts.forEach((part, idx) => {
if (!part) return;
if (!current[part]) current[part] = { __children: {}, lazy: true };
if (idx === parts.length - 1 && uuid) {
current[part].uuid = uuid;
current[part].value = value?.value ?? null;
current[part].lazy = !!hasChild;
}
current = current[part].__children;
});
}
}
const toTreeNodes = (map: TreeMap): TreeNode[] =>
Object.entries(map)
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, node]) => ({
path: key,
key: node.uuid ?? key,
value: node.value,
lazy: node.lazy,
children: toTreeNodes(node.__children),
}));
const newTree = [
{
path: 'DBM',
key: ZERO_UUID,
lazy: true,
children: toTreeNodes(root),
},
];
dbmData.value.splice(0, dbmData.value.length, ...newTree);
return newTree;
}
export function removeNodes(pubs: Pubs) {
pubs.forEach((pub) => {
removeNode(pub.uuid);
});
}
export function removeNode(uuid: string) {
removeFromTreeMap(root, uuid);
removeFromTree(dbmData.value, uuid);
collapseNode(uuid);
}
function removeFromTreeMap(tree: TreeMap, uuid: string): boolean {
for (const [key, node] of Object.entries(tree)) {
if (node.uuid === uuid) {
delete tree[key];
return true;
}
if (removeFromTreeMap(node.__children, uuid)) return true;
}
return false;
}
function removeFromTree(nodes: TreeNode[], uuid: string): boolean {
const index = nodes.findIndex((n) => n.key === uuid);
if (index !== -1) {
nodes.splice(index, 1);
return true;
}
for (const node of nodes) {
if (node.children && removeFromTree(node.children, uuid)) {
if (node.children.length === 0) {
delete node.children;
node.lazy = true;
}
return true;
}
}
return false;
}
export function removeSubtreeByParentKey(parentKey: string) {
const recurse = (nodes: TreeNode[]): boolean => {
for (const node of nodes) {
if (node.key === parentKey) {
delete node.children;
node.lazy = true;
return true;
}
if (node.children && recurse(node.children)) return true;
}
return false;
};
recurse(dbmData.value);
}
function collapseNode(uuid: string) {
const idx = expanded.value.indexOf(uuid);
if (idx !== -1) {
expanded.value.splice(idx, 1);
const lastIdx = lastExpanded.indexOf(uuid);
if (lastIdx !== -1) lastExpanded.splice(lastIdx, 1);
onExpandedChange([...expanded.value]).catch(console.error);
}
}
export function updateValue(
NotifyResponse: (
response: Response | string | undefined,
type?: 'warning' | 'error',
timeout?: 5000,
) => void,
path1: string,
toggle?: Ref<boolean>,
path2?: string,
path3?: string,
value3?: number,
) {
return computed({
get() {
const path = toggle?.value && path2 ? path2 : path1;
return Number(findSubscriptionByPath(path)?.value ?? 0);
},
set(val) {
const baseValue = val;
const updates = [
{ path: toggle?.value && path2 ? path2 : path1, value: baseValue },
...(path3 ? [{ path: path3, value: value3 ?? baseValue }] : []),
];
setValues(updates)
.then((response) => NotifyResponse(response))
.catch((err) =>
NotifyResponse(`Failed to update [${[path1, path2, path3].join(' ')}]: ${err}`, 'error'),
);
},
});
}
export async function onExpandedChange(newExpanded: readonly string[]) {
const collapsed = lastExpanded.filter((k) => !newExpanded.includes(k));
const newlyExpanded = newExpanded.filter((k) => !lastExpanded.includes(k));
try {
await unsubscribe([{ path: '.*', depth: 0 }]).then(removeAllSubscriptions);
for (const key of collapsed) {
removeSubtreeByParentKey(key);
fetchAndUpdateNode(key);
}
for (const key of newlyExpanded) {
fetchAndUpdateNode(key);
}
lastExpanded = [...newExpanded];
} catch (err) {
console.error('error in expand function', err);
}
}
function fetchAndUpdateNode(key: string) {
getRequest(key, '', 2)
.then((resp) => {
if (resp) {
buildTreeWithRawSubs(resp);
subscribe([{ uuid: key, path: '', depth: 2 }]).catch((err) => console.error(err));
addRawSubscriptions(resp);
}
UpdateTable(key);
})
.catch((err) => console.error(err));
}
export function findParentKey(
childKey: string,
parentKey: string | null = null,
nodes?: TreeNode[],
): string | null {
if (!nodes) nodes = dbmData.value;
for (const node of nodes) {
if (node.key === childKey) return parentKey;
if (node.children) {
const found = findParentKey(childKey, node.key ?? null, node.children);
if (found) return found;
}
}
return null;
}
function getNodeUuidByPath(path: string, nodes?: TreeNode[]): string {
if (!nodes) nodes = dbmData.value;
for (const node of nodes) {
if (node.path === path) return node.key ?? '';
if (node.children) {
const found = getNodeUuidByPath(path, node.children);
if (found !== '') return found;
}
}
return '';
}
export function pathIsExpanded(path: string): boolean {
if (!path.includes(':')) {
return true;
}
let p = path.replace(/:.+$/, '');
if (expanded.value.includes(getNodeUuidByPath(p))) {
return true;
}
p = path.replace(/:.+$/, '');
return expanded.value.includes(getNodeUuidByPath(p));
}

View File

@@ -0,0 +1,160 @@
<template>
<DialogFrame
ref="Dialog"
:width="props.width"
:height="props.height"
:header-title="props.dialogLabel"
>
<q-card-section
v-if="props.dialogLabel"
class="text-bold text-left q-mb-none q-pb-none"
:class="'text-' + props.labelColor"
>
</q-card-section>
<q-form ref="addForm" class="q-gutter-md">
<q-input
class="q-mt-lg q-mb-none q-pl-lg q-pr-xl"
filled
v-model="addingForm.path"
label=""
:rules="[(val) => !!val || 'Path is required']"
>
<template #prepend>
<div class="column">
<span class="text-caption text-primary non-editable-prefix">Path *</span>
<span class="text-body2 text-grey-6 non-editable-prefix"
>{{ addingForm.prefix }}{{ addingForm.staticPrefix }}</span
>
</div>
</template>
</q-input>
<DataTypes class="q-mt-lg q-pl-md q-pr-xl" flat v-model:datatype="datatype"></DataTypes>
<div class="q-pl-lg">
<div class="text-grey text-bold">Read Write Access</div>
<q-checkbox v-model="addingForm.read">Read</q-checkbox>
<q-checkbox v-model="addingForm.write">Write</q-checkbox>
</div>
<q-input
:type="valueType"
stack-label
label="Value"
class="q-pl-md q-pr-xl"
filled
v-model="addingForm.value"
></q-input>
<div class="row justify-end">
<q-btn no-caps class="q-mb-xl q-mx-xl q-px-lg" @click="onSubmit" color="primary">{{
props.buttonOkLabel
}}</q-btn>
</div>
</q-form>
</DialogFrame>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import { useNotify } from '../../general/useNotify';
import DataTypes from '../../buttons/DataTypes.vue';
import { addRawSubscription } from '../../models/Subscriptions';
import { UpdateTable } from '../../dbm/updateTable';
import { getRequest, setRequest } from 'src/vueLib/models/Request';
import { convertToType } from '../Datapoint';
import { catchError } from 'src/vueLib/models/error';
const { NotifyResponse } = useNotify();
const addingForm = reactive({
path: '',
value: '',
staticPrefix: '',
read: true,
write: true,
prefix: 'DBM:',
});
const Dialog = ref();
const valueType = ref<'text' | 'number'>('text');
const datatype = ref('None');
const addForm = ref();
const open = (uuid: string) => {
Dialog.value?.open();
getDatapoint(uuid);
};
watch(datatype, (newVal) => {
if (newVal === 'String') valueType.value = 'text';
else valueType.value = 'number';
});
function onSubmit() {
let type = 'NONE';
let access = '';
addForm.value.validate().then((success: undefined) => {
if (success) {
type = convertToType(datatype.value);
if (addingForm.read) access = 'R';
if (addingForm.write) access += 'W';
if (access == '') access = 'R';
setRequest(addingForm.staticPrefix + addingForm.path, type, addingForm.value, access)
.then((respond) => {
if (respond) {
respond.forEach((set) => {
NotifyResponse("Datapoint '" + addingForm.prefix + set.path + "' added");
});
addRawSubscription(respond[0]);
UpdateTable();
}
})
.catch((err) => {
NotifyResponse(catchError(err), 'error');
});
} else {
if (addingForm.path === '') {
NotifyResponse("Field 'Path' is requierd", 'error');
return;
} else NotifyResponse('Form not validated', 'error');
}
});
}
const props = defineProps({
buttonOkLabel: {
type: String,
default: 'OK',
},
labelColor: {
type: String,
default: 'primary',
},
dialogLabel: {
type: String,
default: '',
},
width: {
type: String,
default: '300px',
},
height: {
type: String,
default: '650px',
},
});
function getDatapoint(uuid: string) {
getRequest(uuid, '', 1)
.then((resp) => {
if (resp[0]) {
addingForm.staticPrefix = resp[0].path ?? '';
if (addingForm.staticPrefix !== '') addingForm.staticPrefix += ':';
}
})
.catch((err) => NotifyResponse(catchError(err), 'error'));
}
defineExpose({ open });
</script>

View File

@@ -0,0 +1,145 @@
<template>
<DialogFrame
ref="Dialog"
:width="props.width"
:height="props.height"
:header-title="props.dialogLabel"
>
<q-card-section
v-if="props.dialogLabel"
class="text-bold text-left q-mb-none q-pb-none"
:class="'text-' + props.labelColor"
>
</q-card-section>
<q-form ref="copyForm" class="q-gutter-md">
<q-input
class="q-mt-lg q-mb-none q-pl-md q-mx-lg"
filled
v-model="copyData.path"
label="Current Path"
label-color="primary"
readonly
>
</q-input>
<q-input
class="q-mt-lg q-mt-none q-pl-md q-mx-lg"
filled
v-model="copyData.copyPath"
label="New Path *"
label-color="primary"
@keyup.enter="onSubmit"
:rules="[(val) => !!val || 'Path is required']"
>
</q-input>
<div class="q-mx-sm">
<div class="row justify-end">
<q-btn no-caps class="q-mb-xl q-mr-md q-px-lg" @click="onSubmit" color="primary">{{
props.buttonOkLabel
}}</q-btn>
</div>
</div>
</q-form>
</DialogFrame>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import { useNotify } from '../../general/useNotify';
import { getRequest, setsRequest } from 'src/vueLib/models/Request';
import { datapointRequestForCopy } from '../Datapoint';
import { catchError } from 'src/vueLib/models/error';
const { NotifyResponse } = useNotify();
const copyData = reactive({
path: '',
copyPath: '',
prefix: 'DBM:',
});
const Dialog = ref();
const copyForm = ref();
const open = (uuid: string) => {
Dialog.value?.open();
getDatapoint(uuid);
};
function onSubmit() {
copyForm.value.validate().then((success: undefined) => {
if (success) {
if (copyData.copyPath === copyData.path) {
NotifyResponse('copy path can not be the same as current path', 'error');
return;
}
const absolutePath = copyData.path.slice(copyData.prefix.length);
const absolutecopyPath = copyData.copyPath.slice(copyData.prefix.length);
getRequest('', absolutecopyPath, 1)
.then((response) => {
if (response?.length > 0) {
NotifyResponse("path '" + copyData.copyPath + "' already exists", 'warning');
return;
}
})
.catch((err) => {
if (err instanceof Error && err.message === 'No data returned') {
getRequest('', absolutePath, 0)
.then((response) => {
setsRequest(
datapointRequestForCopy(response, absolutePath, absolutecopyPath),
).catch((err) => console.error(err));
NotifyResponse(copyData.copyPath + ' copied');
})
.catch((err) => NotifyResponse(catchError(err), 'error'));
} else {
NotifyResponse(catchError(err), 'error');
}
return;
});
} else {
if (copyData.copyPath === '') {
NotifyResponse("Field 'New Path' is requierd", 'error');
return;
} else NotifyResponse('Form not validated', 'error');
}
});
}
const props = defineProps({
buttonOkLabel: {
type: String,
default: 'OK',
},
labelColor: {
type: String,
default: 'primary',
},
dialogLabel: {
type: String,
default: '',
},
width: {
type: String,
default: '300px',
},
height: {
type: String,
default: '400px',
},
});
function getDatapoint(uuid: string) {
getRequest(uuid)
.then((resp) => {
if (resp[0]) {
copyData.path = copyData.prefix + resp[0].path;
copyData.copyPath = copyData.prefix + resp[0].path;
}
})
.catch((err) => NotifyResponse(catchError(err), 'error'));
}
defineExpose({ open });
</script>

View File

@@ -0,0 +1,258 @@
<template>
<DialogFrame
ref="Dialog"
:width="props.width"
:height="props.height"
:header-title="localDialogLabel"
>
<q-card-section
v-if="dialogLabel"
class="text-bold text-left q-mb-none q-pb-none"
:class="'text-' + props.labelColor"
>{{ dialogLabel }}
</q-card-section>
<q-card-section v-if="props.text" class="text-center" style="white-space: pre-line">{{
props.text
}}</q-card-section>
<q-form ref="form">
<q-card-section class="q-gutter-xs row q-col-gutter-xs q-ml-sm">
<div>
<q-select
filled
label="Driver Name"
type="text"
name="Type"
dense
:options="options"
:rules="[(val) => !!val || 'Name is required']"
v-model="driverForm.type"
/>
<q-input
filled
label="Bus"
type="text"
name="Bus"
dense
:rules="[(val) => !!val || 'Bus is required']"
v-model="driverForm.bus"
/>
<q-input
v-if="driverForm.isAddress"
filled
dense
label="Address"
type="number"
name="Address"
@keyup.enter="updateDriver"
v-model.number="driverForm.address"
/>
</div>
<div v-if="!driverForm.isAddress" class="q-gutter-xs row q-col-gutter-xs">
<q-input
filled
dense
label="Subscribe"
type="text"
name="Address"
v-model="driverForm.subscribe"
/>
<q-input
filled
dense
label="Publish"
type="text"
name="Address"
@keyup.enter="updateDriver"
v-model="driverForm.publish"
/>
</div>
</q-card-section>
</q-form>
<q-card-actions align="right" class="text-primary">
<q-btn v-if="props.buttonCancelLabel" flat :label="props.buttonCancelLabel" v-close-popup />
<q-btn
class="q-mb-xl q-mr-lg"
v-if="props.buttonOkLabel"
color="primary"
no-caps
:label="props.buttonOkLabel"
@click="updateDriver"
>
</q-btn>
</q-card-actions>
</DialogFrame>
</template>
<script setup lang="ts">
import { reactive, ref, watch, computed } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import type { Driver } from '../../models/Drivers';
import { deleteRequest, setRequest } from 'src/vueLib/models/Request';
import { addRawSubscriptions } from 'src/vueLib/models/Subscriptions';
import { convertToSubscribe, type RawSubs } from 'src/vueLib/models/Subscribe';
import { useNotify } from 'src/vueLib/general/useNotify';
import { UpdateTable } from '../updateTable';
import { updateDriverTable, type DriverTableRow } from 'src/vueLib/models/driverTable';
const { NotifyResponse } = useNotify();
const Dialog = ref();
const dialogLabel = computed(() => props.dialogLabel || localDialogLabel.value);
const options = ['ArtNetDriver', 'OSCDriver'];
const driverForm = reactive({
type: 'ArtNetDriver',
bus: '',
isAddress: true,
address: 0,
subscribe: '',
publish: '',
});
const props = defineProps({
buttonOkLabel: {
type: String,
default: 'OK',
},
labelColor: {
type: String,
default: 'primary',
},
dialogLabel: {
type: String,
default: '',
},
text: {
type: String,
default: '',
},
buttonCancelLabel: {
type: String,
default: '',
},
width: {
type: String,
default: '300px',
},
height: {
type: String,
default: '480px',
},
});
const localDialogLabel = ref('');
const driver = ref<Driver>();
let dpUuid = '';
const form = ref();
const address = ref();
const topic = ref();
const edit = ref(false);
watch(
() => driverForm.type,
(val) => {
driverForm.isAddress = val === options[0];
if (driverForm.isAddress) {
driverForm.subscribe = '';
driverForm.publish = '';
topic.value = undefined;
} else {
driverForm.address = -1;
address.value = undefined;
}
},
);
const open = (uuid: string, drvs: DriverTableRow, type: 'add' | 'edit') => {
switch (type) {
case 'add':
localDialogLabel.value = 'Add Driver';
edit.value = false;
Object.assign(driverForm, {
type: 'ArtNetDriver',
bus: '',
isAddress: true,
address: 0,
subscribe: '',
publish: '',
});
break;
case 'edit':
localDialogLabel.value = 'Edit Driver';
edit.value = true;
fillDriverFormFromRow(drvs);
}
dpUuid = uuid;
driver.value = drvs;
if (drvs.address) driverForm.address = drvs.address;
if (drvs.subscribe) driverForm.subscribe = drvs.subscribe;
if (drvs.publish) driverForm.publish = drvs.publish;
Dialog.value?.open();
};
async function updateDriver() {
const valid = await form.value?.validate();
if (!valid) {
NotifyResponse('Please fill in all required fields', 'warning');
return;
}
if (driverForm.address > -1) {
address.value = [driverForm.address];
}
if (driverForm.subscribe !== '' || driverForm.publish !== '') {
topic.value = { subscribe: [driverForm.subscribe], publish: [driverForm.publish] };
}
if (edit.value) {
deleteRequest(dpUuid, '', driver.value)
.then((resp) => {
resp.forEach((set) => {
updateDriverTable(convertToSubscribe(set));
});
})
.catch((err) => NotifyResponse(err, 'error'));
}
setRequest('', undefined, undefined, undefined, dpUuid, {
type: driverForm.type,
buses: [
{
name: driverForm.bus,
address: address.value,
topic: topic.value,
},
],
})
.then((resp) => {
addRawSubscriptions(resp as RawSubs);
resp.forEach((set) => {
updateDriverTable(convertToSubscribe(set));
});
UpdateTable();
Dialog.value.close();
})
.catch((err) => {
NotifyResponse(err, 'error');
});
}
function fillDriverFormFromRow(drvs: DriverTableRow) {
driverForm.type = drvs.type;
driverForm.bus = drvs.buses?.[0]?.name ?? '';
driverForm.address = drvs.buses?.[0]?.address?.[0] ?? -1;
driverForm.subscribe = drvs.topic?.subscribe?.[0] ?? '';
driverForm.publish = drvs.topic?.publish?.[0] ?? '';
}
defineExpose({ open });
</script>
<style scoped>
.outercard {
border-radius: 10px;
}
</style>

View File

@@ -0,0 +1,104 @@
<template>
<DialogFrame ref="Dialog" :width="props.width" :header-title="props.dialogLabel">
<q-card-section
v-if="props.dialogLabel"
class="text-bold text-left q-mb-none q-pb-none"
:class="'text-' + props.labelColor"
>
</q-card-section>
<div class="text-center text-bold text-primary">
Do you want to remove Datapoint
<br /><br />
'{{ datapoint.path ?? '' }}'
</div>
<div class="row justify-end">
<q-btn no-caps class="q-ma-lg q-mr-xl" filled color="negative" @click="remove">{{
props.buttonOkLabel
}}</q-btn>
</div>
</DialogFrame>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import { useNotify } from '../../general/useNotify';
import { subscribe } from '../../services/websocket';
import { findParentKey, buildTree } from '../../dbm/dbmTree';
import { addRawSubscriptions } from '../../models/Subscriptions';
import { UpdateTable } from '../../dbm/updateTable';
import { convertToSubscribes } from '../../models/Subscribe';
import { deleteRequest, getRequest } from 'src/vueLib/models/Request';
import { catchError } from 'src/vueLib/models/error';
const { NotifyResponse } = useNotify();
const Dialog = ref();
const datapoint = ref();
const prefix = 'DBM:';
const open = (uuid: string) => {
getDatapoint(uuid)
.then(() => Dialog.value?.open())
.catch((err) => NotifyResponse(catchError(err), 'error'));
};
function remove() {
deleteRequest(datapoint.value.uuid)
.then((respond) => {
const sub = respond[respond.length - 1];
if (sub) NotifyResponse("Datapoint '" + prefix + sub.path + "' removed", 'warning');
Dialog.value.close();
{
const parentKey = findParentKey(datapoint.value.uuid);
if (parentKey) {
subscribe([{ uuid: parentKey, path: '', depth: 2 }])
.then((res) => {
if (res?.subscribe) {
addRawSubscriptions(res.subscribe);
buildTree(convertToSubscribes(res.subscribe));
UpdateTable();
}
})
.catch((err) => NotifyResponse('Subscribe failed ' + catchError(err), 'error'));
}
}
})
.catch((err) => {
if (err.response) {
NotifyResponse(err.response.data.message, 'error');
} else console.error(err);
});
}
const props = defineProps({
buttonOkLabel: {
type: String,
default: 'OK',
},
labelColor: {
type: String,
default: 'primary',
},
dialogLabel: {
type: String,
default: '',
},
width: {
type: String,
default: '300px',
},
});
async function getDatapoint(uuid: string) {
await getRequest(uuid, '', 1)
.then((resp) => {
if (resp) {
datapoint.value = resp[0];
}
})
.catch((err) => NotifyResponse(catchError(err), 'error'));
}
defineExpose({ open, close });
</script>

View File

@@ -0,0 +1,153 @@
<template>
<DialogFrame
ref="Dialog"
:width="props.width"
:height="props.height"
:header-title="props.dialogLabel"
>
<q-card-section
v-if="props.dialogLabel"
class="text-bold text-left q-mb-none q-pb-none"
:class="'text-' + props.labelColor"
>
</q-card-section>
<q-form ref="copyForm" class="q-gutter-md">
<q-input
class="q-mt-lg q-mb-none q-pl-md q-mx-lg"
filled
v-model="removeData.path"
label="Current Path"
label-color="primary"
readonly
>
</q-input>
<q-input
class="q-mt-lg q-mt-none q-pl-md q-mx-lg"
filled
v-model="removeData.newPath"
label="New Path *"
label-color="primary"
@keyup.enter="onSubmit"
:rules="[(val) => !!val || 'Path is required']"
>
</q-input>
<div class="row justify-end q-mr-lg">
<q-btn no-caps class="q-mb-xl q-ml-lg q-px-lg" @click="onSubmit" color="primary">{{
props.buttonOkLabel
}}</q-btn>
</div>
</q-form>
</DialogFrame>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import { useNotify } from '../../general/useNotify';
import { getRequest, setRequest } from 'src/vueLib/models/Request';
import { catchError } from 'src/vueLib/models/error';
import { convertToSubscribes, type RawSubs } from 'src/vueLib/models/Subscribe';
import { UpdateTable } from '../updateTable';
import { addRawSubscriptions } from 'src/vueLib/models/Subscriptions';
import { buildTree } from '../dbmTree';
const { NotifyResponse } = useNotify();
const Dialog = ref();
const datapoint = ref();
const removeData = reactive({
path: '',
newPath: '',
prefix: 'DBM:',
});
const copyForm = ref();
const open = (uuid: string) => {
Dialog.value?.open();
getDatapoint(uuid);
};
function onSubmit() {
copyForm.value.validate().then((success: undefined) => {
if (success) {
if (removeData.newPath === removeData.path) {
NotifyResponse('same name', 'warning');
return;
}
getRequest('', removeData.newPath.slice(removeData.prefix.length), 1)
.then((response) => {
if (response?.length > 0) {
NotifyResponse("path '" + response[0]?.path + "' already exists", 'warning');
return;
}
})
.catch((err) => {
const error = catchError(err);
if (error !== 'No data returned') {
NotifyResponse(error, 'error');
return;
}
setRequest(
removeData.newPath.slice(removeData.prefix.length),
datapoint.value.type,
datapoint.value.value,
datapoint.value.rights,
datapoint.value.uuid,
undefined,
true,
)
.then((res) => {
addRawSubscriptions(res as RawSubs);
buildTree(convertToSubscribes(res as RawSubs));
UpdateTable();
})
.catch((err) => NotifyResponse(err, 'error'));
});
} else {
if (removeData.newPath === '') {
NotifyResponse("Field 'New Path' is requierd", 'error');
return;
} else NotifyResponse('Form not validated', 'error');
}
});
}
const props = defineProps({
buttonOkLabel: {
type: String,
default: 'OK',
},
labelColor: {
type: String,
default: 'primary',
},
dialogLabel: {
type: String,
default: '',
},
width: {
type: String,
default: '300px',
},
height: {
type: String,
default: '400px',
},
});
function getDatapoint(uuid: string) {
getRequest(uuid)
.then((resp) => {
if (resp[0]) {
datapoint.value = resp[0];
removeData.path = removeData.prefix + resp[0].path;
removeData.newPath = removeData.prefix + resp[0].path;
}
})
.catch((err) => NotifyResponse(catchError(err), 'error'));
}
defineExpose({ open });
</script>

View File

@@ -0,0 +1,152 @@
<template>
<DialogFrame
ref="Dialog"
:width="props.width"
:height="props.height"
:header-title="props.dialogLabel"
>
<q-card-section
v-if="props.dialogLabel"
class="text-bold text-left q-mb-none q-pb-none"
:class="'text-' + props.labelColor"
>{{
datapoint.uuid === '00000000-0000-0000-0000-000000000000' ? 'DBM' : 'DBM:' + datapoint.path
}}
</q-card-section>
<q-form ref="datatypeForm" class="q-gutter-md">
<q-input
class="q-mt-lg q-mb-none q-pl-md q-mx-lg"
filled
dense
v-model="currentDatatype"
label="Current Datatype"
label-color="primary"
readonly
>
</q-input>
<q-select
class="q-mt-lg q-mt-none q-pl-md q-mx-lg"
popup-content-class="small-dropdown"
label="New Datatype"
filled
dense
v-model="selectedDatatype"
:options="options"
option-label="label"
>
</q-select>
<div class="row justify-end q-mr-lg">
<q-btn no-caps class="q-mb-xl q-ml-lg q-px-lg" @click="onSubmit" color="primary">{{
props.buttonOkLabel
}}</q-btn>
</div>
</q-form>
</DialogFrame>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import { useNotify } from '../../general/useNotify';
import { getRequest, setRequest } from 'src/vueLib/models/Request';
import { UpdateTable } from '../updateTable';
import { updateSubscription } from 'src/vueLib/models/Subscriptions';
import { convertToSubscribe } from 'src/vueLib/models/Subscribe';
import { convertFromType } from '../Datapoint';
import { catchError } from 'src/vueLib/models/error';
const { NotifyResponse } = useNotify();
const Dialog = ref();
const datapoint = ref();
const currentDatatype = ref('');
const datatypeForm = ref();
const selectedDatatype = ref({ label: 'None', value: 'NONE' });
const options = [
{ label: 'None', value: 'NONE' },
{ label: 'String (Text)', value: 'STR' },
{ label: 'Bool (On/Off)', value: 'BIT' },
{ label: 'Uint8 (0 - 256)', value: 'BYU' },
{ label: 'Uint16 (0 - 65535)', value: 'WOU' },
{ label: 'Uint32 (0 - 429496...)', value: 'DWU' },
{ label: 'Int8 (-128 - 127)', value: 'BYS' },
{ label: 'Int16 (-32768 -3...)', value: 'WOS' },
{ label: 'Int32 (-21474836...)', value: 'DWS' },
{ label: 'Int64 (-2^63 -(2^...))', value: 'DWS' },
{ label: 'Double (1.7E 1/-3...)', value: 'F64' },
];
const open = async (uuid: string) => {
await getDatapoint(uuid);
Dialog.value?.open();
};
async function onSubmit() {
const success = await datatypeForm.value.validate();
if (!success) {
NotifyResponse('Form not validated', 'error');
return;
}
const datatype = options.find((s) => s.label === selectedDatatype.value.label)?.value;
if (datatype === undefined) return;
try {
const response = await setRequest(datapoint.value.path, datatype, datapoint.value.value);
if (response[0]) updateSubscription(convertToSubscribe(response[0]));
NotifyResponse(
'new datatype: ' +
convertFromType(response[0]?.type ?? '') +
' for datapoint :DBM:' +
response[0]?.path,
);
UpdateTable();
return;
} catch (err) {
console.error(err);
}
}
const props = defineProps({
buttonOkLabel: {
type: String,
default: 'OK',
},
labelColor: {
type: String,
default: 'primary',
},
dialogLabel: {
type: String,
default: '',
},
width: {
type: String,
default: '300px',
},
height: {
type: String,
default: '340px',
},
});
async function getDatapoint(uuid: string) {
await getRequest(uuid)
.then((resp) => {
if (resp[0]) {
datapoint.value = resp[0];
const type = options.find((s) => s.value === (resp[0]?.type ?? 'NONE'))?.label ?? 'None';
currentDatatype.value = type;
selectedDatatype.value.value = type;
}
})
.catch((err) => NotifyResponse(catchError(err), 'error'));
}
defineExpose({ open });
</script>
<style scope>
.small-dropdown .q-item {
min-height: 28px; /* default is 48px */
padding: 4px 8px;
}
</style>

View File

@@ -0,0 +1,212 @@
<template>
<DialogFrame
ref="Dialog"
:width="props.width"
:height="props.height"
:header-title="'DBM:' + datapoint?.path"
>
<q-card-section
v-if="props.dialogLabel || localDialogLabel"
class="text-bold text-left q-mb-none q-pb-none"
:class="'text-' + props.labelColor"
>{{ props.dialogLabel || localDialogLabel }}</q-card-section
>
<q-card-section>
<q-table
flat
dense
virtual-scroll
:rows-per-page-options="[0]"
:rows="drivers"
:columns="columns"
row-key="type"
>
<!-- add symbol on top right of table-->
<template v-slot:top-right>
<q-btn
size="sm"
ripple
rounded
color="primary"
icon="add"
round
dense
@click="handleRow(driver, 'add')"
/>
</template>
<template v-slot:body-cell-settings="props">
<q-td :props="props" class="cursor-pointer">
<q-btn
dense
flat
size="sm"
icon="more_vert"
@click="(evt) => openSubMenu(evt, props.row)"
></q-btn>
</q-td>
</template>
</q-table>
<q-menu ref="contextMenuRef" context-menu>
<q-list>
<q-item>
<q-item-section v-close-popup class="cursor-pointer" @click="handleRow(driver, 'edit')">
Edit
</q-item-section>
</q-item>
<q-item>
<q-item-section
v-close-popup
class="text-negative cursor-pointer"
@click="deleteDriver(driver)"
>
Delete
</q-item-section>
</q-item>
</q-list>
</q-menu>
</q-card-section>
<q-card-section v-if="props.text" class="text-center" style="white-space: pre-line">{{
props.text
}}</q-card-section>
<q-card-actions align="right" class="text-primary">
<q-btn v-if="props.buttonCancelLabel" flat :label="props.buttonCancelLabel" v-close-popup>
</q-btn>
<q-btn
class="q-mb-xl q-ml-lg q-mt-none"
v-if="props.buttonOkLabel"
color="primary"
no-caps
:label="props.buttonOkLabel"
v-close-popup
>
</q-btn>
</q-card-actions>
</DialogFrame>
<DriverDialog :button-ok-label="driverOkLabel" ref="driverDialog"></DriverDialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import DriverDialog from './DriverDialog.vue';
import { convertToSubscribe, type Subscribe } from '../../models/Subscribe';
import type { Driver } from '../../models/Drivers';
import { driverDefault } from '../../models/Drivers';
import type { DriverTableRow } from 'src/vueLib/models/driverTable';
import { updateDriverTable, useDriverTable } from 'src/vueLib/models/driverTable';
import { deleteRequest } from 'src/vueLib/models/Request';
import { useNotify } from 'src/vueLib/general/useNotify';
import type { Bus } from 'src/vueLib/models/Bus';
const { NotifyResponse } = useNotify();
const Dialog = ref();
const driverDialog = ref();
const writeValue = ref();
const onlyRead = ref(false);
const props = defineProps({
buttonOkLabel: {
type: String,
default: 'OK',
},
labelColor: {
type: String,
default: 'primary',
},
dialogLabel: {
type: String,
default: '',
},
text: {
type: String,
default: '',
},
buttonCancelLabel: {
type: String,
default: '',
},
width: {
type: String,
default: '300px',
},
height: {
type: String,
default: '500px',
},
});
const datapoint = ref();
const localDialogLabel = ref('');
const contextMenuRef = ref();
const table = useDriverTable();
const drivers = table.driverTable;
const driver: Driver = { type: '' };
const driverOkLabel = ref('');
const columns = table.columns;
const open = (sub: Subscribe) => {
datapoint.value = sub;
if (datapoint.value.rights == 'R') onlyRead.value = true;
table.emptyTable();
localDialogLabel.value = 'Update Drivers';
updateDriverTable(sub);
writeValue.value = sub.drivers;
Dialog.value?.open();
};
function openSubMenu(evt: Event, d: DriverTableRow) {
if (d) {
const bus: Bus = {
name: d.bus,
};
bus.name = d.bus;
if (d.address) bus.address = d.address !== undefined ? [d.address] : [];
if (d.subscribe || d.publish)
bus.topic = {
subscribe:
typeof d.subscribe === 'string' ? d.subscribe.split(',').map((s) => s.trim()) : [],
publish: typeof d.publish === 'string' ? d.publish.split(',').map((s) => s.trim()) : [],
};
driver.type = d.type;
driver.buses = [bus];
}
const mouseEvent = evt as MouseEvent;
contextMenuRef.value?.show(mouseEvent);
}
function handleRow(driver: Driver | undefined, type: 'add' | 'edit') {
driverOkLabel.value = 'Add';
switch (type) {
case 'add':
driver = driverDefault;
break;
case 'edit':
driverOkLabel.value = 'Update';
break;
}
driverDialog.value?.open(datapoint.value.uuid, driver, type);
}
function deleteDriver(driver: Driver | undefined) {
deleteRequest(datapoint.value.uuid, '', driver)
.then((resp) => {
resp.forEach((set) => {
updateDriverTable(convertToSubscribe(set));
});
})
.catch((err) => {
NotifyResponse(err, 'error');
});
}
defineExpose({ open });
</script>
<style scoped>
.outercard {
border-radius: 10px;
}
</style>

View File

@@ -0,0 +1,159 @@
<template>
<DialogFrame
ref="Dialog"
:width="props.width"
:height="props.height"
:header-title="datapoint?.path"
>
<q-card-section
v-if="props.dialogLabel || localDialogLabel"
class="text-bold text-left q-mb-none q-pb-none"
:class="'text-' + props.labelColor"
>{{ props.dialogLabel ? props.dialogLabel : localDialogLabel }}</q-card-section
>
<q-card-section v-if="datapoint.type !== 'BIT'">
<q-input
class="q-px-md q-ma-sm"
label="current value"
dense
filled
readonly
v-model="inputValue as string | number"
></q-input>
<q-input
class="q-px-md q-mx-sm"
label="new value"
dense
filled
:readonly="onlyRead"
@keyup.enter="write"
:type="writeType"
v-model="writeValue as string | number"
></q-input>
</q-card-section>
<q-card-section v-else>
<div class="column q-pr-xs q-ma-sm">
<div class="row items-center q-gutter-sm">
<div>current value</div>
<div class="row items-left">
<q-toggle class="readonly-toggle" left-label v-model="inputValue"></q-toggle>
</div>
</div>
<div class="row items-center q-gutter-lg">
<div>new value</div>
<div class="row items-left">
<q-toggle left-label v-model="writeValue"></q-toggle>
</div>
</div>
</div>
</q-card-section>
<q-card-section v-if="props.text" class="text-center" style="white-space: pre-line">{{
props.text
}}</q-card-section>
<q-card-actions align="right" class="text-primary">
<q-btn v-if="props.buttonCancelLabel" flat :label="props.buttonCancelLabel" v-close-popup>
</q-btn>
<q-btn
class="q-mb-xl q-mr-lg q-mt-none"
v-if="props.buttonOkLabel"
color="primary"
no-caps
:label="props.buttonOkLabel"
@click="write"
>
</q-btn>
</q-card-actions>
</DialogFrame>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import type { Subscribe } from '../../models/Subscribe';
import type { Ref } from 'vue';
import { setValues } from '../../services/websocket';
import { useNotify } from '../../general/useNotify';
import { catchError } from 'src/vueLib/models/error';
const { NotifyResponse } = useNotify();
const Dialog = ref();
const localDialogLabel = ref('');
const writeValue = ref();
const onlyRead = ref(false);
const writeType = ref<'text' | 'number'>('text');
const datapoint = ref();
const inputValue = ref(datapoint?.value);
const props = defineProps({
buttonOkLabel: {
type: String,
default: 'OK',
},
labelColor: {
type: String,
default: 'primary',
},
dialogLabel: {
type: String,
default: '',
},
text: {
type: String,
default: '',
},
buttonCancelLabel: {
type: String,
default: '',
},
width: {
type: String,
default: '300px',
},
height: {
type: String,
default: '350px',
},
});
const open = (sub: Ref<Subscribe>) => {
datapoint.value = sub.value;
if (datapoint.value.rights == 'R') onlyRead.value = true;
localDialogLabel.value = 'Update Value';
if (sub.value.type === 'STR') writeType.value = 'text';
else writeType.value = 'number';
writeValue.value = sub.value.value;
Dialog.value?.open();
};
watch(
() => datapoint.value?.value,
(newVal) => {
inputValue.value = newVal;
},
);
function write() {
setValues([{ uuid: datapoint.value?.uuid ?? '', value: writeValue.value ?? undefined }])
.then((resp) => {
if (resp?.set) {
resp.set.forEach((set) => {
inputValue.value = set.value;
});
}
})
.catch((err) => NotifyResponse(catchError(err), 'error'));
}
defineExpose({ open });
</script>
<style scoped>
.outercard {
border-radius: 10px;
}
.readonly-toggle {
pointer-events: none;
opacity: 0.7;
}
</style>

View File

@@ -0,0 +1,22 @@
import type { Subs } from '../models/Subscribe';
import { Subscriptions } from '../models/Subscriptions';
import { ref } from 'vue';
export const TableSubs = ref<Subs>();
export function UpdateTable(targetUuid?: string) {
TableSubs.value = Object.values(Subscriptions)
.map((sub) => {
sub.type = sub.type ?? 'none';
return sub;
})
.sort((a, b) => {
if (targetUuid) {
if (a.uuid === targetUuid) return -1; // move `a` to front
if (b.uuid === targetUuid) return 1; // move `b` to front
}
const aPath = a.path ?? '';
const bPath = b.path ?? '';
return aPath.localeCompare(bPath);
});
}

View File

@@ -7,13 +7,30 @@
:no-refocus="!minMaxState"
:seamless="!minMaxState"
>
<q-card class="layout" :style="cardStyle" v-touch-pan.mouse.prevent.stop="handlePan">
<div class="row justify-end q-mx-sm q-mt-xs">
<q-btn dense flat :icon="minMaxIcon" size="md" @click="minMax()"></q-btn>
<q-btn dense flat icon="close" size="md" v-close-popup></q-btn>
<q-card class="layout" :style="cardStyle">
<!-- Draggable Header -->
<div
class="dialog-header row items-center justify-between bg-grey-1"
v-touch-pan.mouse.prevent.stop="handlePan"
>
<div v-if="headerTitle" class="text-left text-bold text-caption q-mx-sm">
{{ headerTitle }}
</div>
<div class="row justify-end q-mx-sm">
<q-btn dense flat :icon="minMaxIcon" size="md" @click="minMax" />
<q-btn dense flat icon="close" size="md" v-close-popup />
</div>
</div>
<q-separator color="black" class="q-my-none" />
<slot />
<q-separator color="black" />
<!-- Content Slot -->
<div class="scrollArea">
<slot />
</div>
<!-- Resize Handle -->
<div v-if="!minMaxState" class="resize-handle" @mousedown.prevent="startResizing" />
</q-card>
</q-dialog>
</template>
@@ -23,43 +40,108 @@ import { ref, computed } from 'vue';
const dialogRef = ref();
const open = () => dialogRef.value?.show();
const close = () => dialogRef.value?.hide();
defineExpose({ open, close });
const props = defineProps({
headerTitle: { type: String, default: '' },
width: { type: String, default: '400' },
height: { type: String, default: '250' },
});
// Fullscreen toggle
const minMaxIcon = ref('fullscreen');
const minMaxState = ref(false);
function minMax() {
if (minMaxState.value) {
minMaxIcon.value = 'fullscreen';
} else {
minMaxIcon.value = 'fullscreen_exit';
}
minMaxState.value = !minMaxState.value;
minMaxIcon.value = minMaxState.value ? 'fullscreen_exit' : 'fullscreen';
}
const props = defineProps({
width: {
type: String,
default: '300px',
},
});
// Position and Size
const position = ref({ x: 0, y: 0 });
const width = ref(parseInt(props.width));
const height = ref(parseInt(props.height));
// This makes the dialog draggable
// Dragging (only from header)
const handlePan = (details: { delta: { x: number; y: number } }) => {
position.value.x += details.delta.x;
position.value.y += details.delta.y;
if (!minMaxState.value) {
position.value.x += details.delta.x;
position.value.y += details.delta.y;
}
};
const cardStyle = computed(() => ({
width: props.width,
transform: `translate(${position.value.x}px, ${position.value.y}px)`,
}));
// Resizing
const isResizing = ref(false);
function startResizing(e: MouseEvent) {
isResizing.value = true;
const startX = e.clientX;
const startY = e.clientY;
const startWidth = width.value;
const startHeight = height.value;
defineExpose({ open });
function onMouseMove(e: MouseEvent) {
width.value = Math.max(200, startWidth + e.clientX - startX);
height.value = Math.max(200, startHeight + e.clientY - startY);
}
function onMouseUp() {
isResizing.value = false;
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
}
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
}
// Styles
const cardStyle = computed(() => {
if (minMaxState.value) {
return {};
}
return {
width: `${width.value}px`,
height: `${height.value}px`,
transform: `translate(${position.value.x}px, ${position.value.y}px)`,
};
});
</script>
<style scoped>
.layout {
position: relative;
display: flex;
flex-direction: column;
border-radius: 10px;
background-color: white;
}
/* Draggable header */
.dialog-header {
padding: 8px 0;
background: #f5f5f5;
cursor: move;
user-select: none;
}
/* Scrollable content */
.scrollArea {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
padding: 16px;
}
/* Resize handle in bottom right */
.resize-handle {
position: absolute;
width: 16px;
height: 16px;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.1);
cursor: nwse-resize;
z-index: 10;
}
</style>

View File

@@ -0,0 +1,80 @@
import type { Response } from '../models/Response';
import { useQuasar } from 'quasar';
export function useNotify() {
const $q = useQuasar();
function NotifyResponse(
response: Response | string | undefined,
type?: 'warning' | 'error',
timeout: number = 5000,
) {
let color = 'green';
let icon = 'check_circle';
switch (type) {
case 'warning':
color = 'orange';
icon = 'warning';
break;
case 'error':
color = 'red';
icon = 'error';
break;
}
if (response instanceof Error) {
const resp = response as Response;
if (resp.response?.data?.error) {
$q?.notify({
message: resp.response.data.message as string,
color: color,
position: 'bottom-right',
icon: icon,
timeout: timeout,
});
return;
}
}
if (response) {
const message = typeof response === 'string' ? response : (response.message ?? '');
if (message === '') {
return;
}
color = typeof response === 'string' ? color : response?.error ? 'red' : color;
icon = typeof response === 'string' ? icon : response?.error ? 'error' : icon;
$q?.notify({
message: message,
color: color,
position: 'bottom-right',
icon: icon,
timeout: timeout,
});
}
}
function NotifyDialog(title: string, text: string, okText?: string, cancelText?: string) {
return new Promise((resolve) => {
$q.dialog({
title: title,
message: text,
persistent: true,
ok: okText ?? 'OK',
cancel: cancelText ?? 'CANCEL',
})
.onOk(() => {
resolve(true);
})
.onCancel(() => {
resolve(false);
})
.onDismiss(() => {
resolve(false);
});
});
}
return {
NotifyDialog,
NotifyResponse,
};
}

View File

@@ -0,0 +1,109 @@
<template>
<DialogFrame ref="Dialog" width="300px" height="380px" header-title="Login">
<div class="text-black"></div>
<q-form ref="refForm">
<q-item-section class="q-gutter-md q-pa-md">
<q-card :class="['q-gutter-xs q-items-center q-pa-lg', { shake: shake }]">
<div class="text-h5 text-primary text-center">{{ productName }}</div>
<q-input
ref="refUserInput"
dense
filled
type="text"
label="User"
v-model="user"
:rules="[(val) => !!val || 'User is required']"
></q-input>
<q-input
dense
filled
type="password"
label="Password"
v-model="password"
@keyup.enter="onSubmit"
:rules="[(val) => !!val || 'Password is required']"
></q-input>
<div class="q-pt-sm q-mr-md row justify-end">
<q-btn color="primary" label="Login" @click="onSubmit"></q-btn>
</div>
</q-card>
</q-item-section>
</q-form>
</DialogFrame>
</template>
<script setup lang="ts">
import { productName } from '../../../package.json';
import { ref, nextTick } from 'vue';
import DialogFrame from '../dialog/DialogFrame.vue';
import { useNotify } from '../general/useNotify';
import { useLogin } from './login';
const { NotifyResponse } = useNotify();
const Dialog = ref();
const refForm = ref();
const refUserInput = ref();
const user = ref('');
const password = ref('');
const { login } = useLogin();
const shake = ref(false);
const open = () => {
Dialog.value?.open();
nextTick(() => {
refUserInput.value?.focus();
}).catch((err) => console.error(err));
};
const onSubmit = () => {
refForm.value?.validate().then((success: boolean) => {
if (success) {
login(user.value, password.value)
.then(() => {
NotifyResponse("logged in as '" + user.value + "'");
Dialog.value.close();
})
.catch((err) => {
NotifyResponse(err, 'error');
shake.value = true;
setTimeout(() => {
shake.value = false;
}, 500);
});
} else {
NotifyResponse('error submitting login form', 'error');
}
});
};
defineExpose({ open });
</script>
<style scoped>
@keyframes shake {
0% {
transform: translateX(0);
}
20% {
transform: translateX(-8px);
}
40% {
transform: translateX(8px);
}
60% {
transform: translateX(-6px);
}
80% {
transform: translateX(6px);
}
100% {
transform: translateX(0);
}
}
.shake {
animation: shake 0.4s ease;
border: 2px solid #f44336;
}
</style>

View File

@@ -0,0 +1,43 @@
<template>
<div class="q-gutter-md">
<q-btn dense flat round icon="person" :color="userStore.user ? 'green' : ''">
<q-menu ref="refLoginMenu">
<q-list style="min-width: 100px">
<q-item v-if="userStore.user" class="text-primary">{{ userStore.user?.username }}</q-item>
<q-item clickable v-close-popup @click="openLogin">
<q-item-section class="text-primary">{{ loginText }}</q-item-section>
</q-item>
</q-list>
</q-menu>
</q-btn>
</div>
<LoginForm ref="refLoginForm"></LoginForm>
</template>
<script setup lang="ts">
import LoginForm from './LoginForm.vue';
import { computed, ref } from 'vue';
import { useLogin } from './login';
import { useUserStore } from './userStore';
import { useNotify } from '../general/useNotify';
const userStore = useUserStore();
const userLogin = useLogin();
const { NotifyResponse } = useNotify();
const loginText = computed(() => {
return userStore.user ? 'Logout' : 'Login';
});
const refLoginForm = ref();
function openLogin() {
if (userStore.user) {
const username = userStore.user.username;
userLogin.logout();
NotifyResponse("user '" + username + "' logged out", 'warning');
return;
}
refLoginForm.value?.open();
}
</script>

31
src/vueLib/login/login.ts Normal file
View File

@@ -0,0 +1,31 @@
import { appApi } from 'src/boot/axios';
import { useUserStore } from './userStore';
const useStore = useUserStore();
export function useLogin() {
async function login(user: string, password: string) {
await appApi
.post('/login', { user: user, password: password })
.then((resp) => {
useStore.setToken(resp.data.token);
})
.catch((err) => {
throw err;
});
}
function logout() {
useStore.logout();
}
function isTokenValid() {
const token = localStorage.getItem('token');
if (token === null) return false;
const payload = JSON.parse(atob(token.split('.')[1] ?? ''));
const currentTime = Math.floor(Date.now() / 1000);
return payload.exp > currentTime;
}
return { login, logout, isTokenValid };
}

View File

@@ -0,0 +1,80 @@
import { defineStore } from 'pinia';
import { jwtDecode } from 'jwt-decode';
import type { QVueGlobals } from 'quasar';
interface JwtPayload {
id: string;
role: string;
username: string;
exp?: number;
iat?: number;
}
interface UserState {
token: string | null;
user: JwtPayload | null;
}
let $q = <QVueGlobals>{};
export const useUserStore = defineStore('user', {
state: (): UserState => ({
token: null,
user: null,
}),
getters: {
isAuthenticated: (state): boolean => !!state.token && !!state.user,
},
actions: {
isAuthorizedAs(roles: string[]) {
return !!this.token && !!this.user && roles.includes(this.user.role);
},
setToken(token: string) {
try {
const decoded = jwtDecode<JwtPayload>(token);
this.token = token;
this.user = decoded;
localStorage.setItem('token', token);
if (decoded.exp) {
const timeUntilExpiry = decoded.exp * 1000 - Date.now();
if (timeUntilExpiry > 0) {
setTimeout(() => {
this.logout();
}, timeUntilExpiry);
} else {
this.logout();
}
}
} catch (err) {
console.error('Invalid token:', err);
this.logout();
}
},
logout() {
$q?.notify({
message: "user '" + this.user?.username + "' logged out",
color: 'orange',
position: 'bottom-right',
icon: 'warning',
timeout: 5000,
});
this.token = null;
this.user = null;
localStorage.removeItem('token');
setTimeout(() => {
window.location.href = '/';
}, 5000);
},
loadFromStorage() {
const token = localStorage.getItem('token');
if (token) {
this.setToken(token);
}
},
initStore(q: QVueGlobals) {
$q = q;
},
},
});

7
src/vueLib/models/Bus.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { Topic } from './Topic';
export interface Bus {
name: string;
address?: number[];
topic?: Topic;
}

View File

@@ -0,0 +1,9 @@
import type { Bus } from './Bus';
export interface Driver {
type: string;
buses?: Bus[];
}
export const driverDefault = <Driver>{
type: '',
};

View File

@@ -7,7 +7,7 @@ type Get = {
path?: string;
type?: string;
rights?: string;
value?: undefined;
value?: string | number | boolean | null;
query?: Query;
hasChild?: boolean;
};

View File

@@ -0,0 +1,62 @@
import type { Driver } from './Drivers';
export type Publish = {
event: string;
uuid: string;
path: string;
type: string;
drivers?: Record<string, Driver>;
value: string | number | boolean | null;
hasChild: boolean;
};
export type Pubs = Publish[];
import {
updateSubscriptionValue,
removeRawSubscriptions,
addRawSubscription,
removeRawSubscription,
} from './Subscriptions';
import { buildTree, buildTreeWithRawSubs, removeNodes } from '../dbm/dbmTree';
import type { RawSubs, RawSubscribe } from '../models/Subscribe';
import { ref } from 'vue';
import { UpdateTable } from '../dbm/updateTable';
import { pathIsExpanded } from '../dbm/dbmTree';
export function publishToSubscriptions(pubs: Pubs) {
let event = '';
const rawSubs = ref<RawSubs>([]);
pubs.forEach((pub) => {
switch (pub.event) {
case 'onCreate':
event = 'onCreate';
if (!pathIsExpanded(pub.path)) break;
pub.hasChild = pubs.length > 0;
rawSubs.value.push(pub as RawSubscribe);
break;
case 'onChange':
break;
case 'onDelete':
event = 'onDelete';
rawSubs.value.push(pub as RawSubscribe);
break;
}
if (pub.drivers) {
removeRawSubscription(pub as RawSubscribe);
addRawSubscription(pub as RawSubscribe);
UpdateTable();
}
updateSubscriptionValue(pub.uuid, pub.value);
});
switch (event) {
case 'onCreate':
buildTreeWithRawSubs(rawSubs.value);
break;
case 'onDelete':
buildTree(null);
removeRawSubscriptions(rawSubs.value);
UpdateTable();
removeNodes(pubs);
break;
}
}

View File

@@ -0,0 +1,128 @@
import type { Driver } from './Drivers';
import type { Gets } from './Get';
import type { Sets } from './Set';
import type { Subs } from './Subscribe';
import { dbmApi } from 'src/boot/axios';
export type Request = {
get?: Gets;
set?: Sets;
subscribe?: Subs;
unsubscribe?: Subs;
};
const query = '/json_data';
export async function getRequest(
uuid: string,
path: string = '',
depth: number = 1,
): Promise<Gets> {
let payload = {};
if (uuid !== '') {
payload = { uuid: uuid, path: path, query: { depth: depth } };
} else {
payload = { path: path, query: { depth: depth } };
}
const resp = await dbmApi.post(query, {
get: [payload],
});
if (resp.data.get && resp.data.get.length > 0) {
return resp.data.get;
} else {
throw new Error('No data returned');
}
}
export async function getRequests(gets: Gets): Promise<Gets> {
const resp = await dbmApi.post(query, {
get: gets,
});
if (resp.data.get && resp.data.get.length > 0) {
return resp.data.get;
} else {
throw new Error('No data returned');
}
}
export async function rawSetsRequest(sets: Sets): Promise<Sets> {
const resp = await dbmApi.post(query, {
set: sets,
});
if (resp.data.set && resp.data.set.length > 0) {
return resp.data.set;
} else {
throw new Error('No data returned');
}
}
export async function setRequest(
path: string,
type?: string,
value?: string | number | boolean,
rights?: string,
uuid?: string,
driver?: Driver,
rename?: boolean,
): Promise<Sets> {
const payload = {
path: path,
type: type,
value: value,
rights: rights,
uuid: uuid,
driver: driver,
rename: rename,
};
const resp = await dbmApi.post(query, {
set: [payload],
});
if (resp.data.set && resp.data.set.length > 0) {
return resp.data.set;
} else {
throw new Error('No data returned');
}
}
export async function setsRequest(sets: Sets): Promise<Sets> {
const resp = await dbmApi.post(query, {
set: sets,
});
if (resp.data.set && resp.data.set.length > 0) {
return resp.data.set;
} else {
throw new Error('No data returned');
}
}
export async function deleteRequest(
uuid?: string,
path?: string,
driver?: Driver,
rename?: boolean,
): Promise<Sets> {
let payload = {};
if (uuid) {
payload = { uuid: uuid, driver: driver, rename: rename };
} else if (path) {
payload = { path: path, driver: driver };
}
const resp = await dbmApi.delete('/json_data', {
data: {
set: [payload],
},
});
if (resp.data.set && resp.data.set.length > 0) {
return resp.data.set;
} else {
throw new Error('No data returned');
}
}

View File

@@ -11,4 +11,10 @@ export type Response = {
publish?: Pubs;
error?: boolean;
message?: string;
response?: {
data?: {
error?: boolean;
message?: string;
};
};
};

View File

@@ -2,8 +2,10 @@ export type Set = {
uuid?: string | undefined;
path?: string;
type?: string;
value: string | number | boolean | undefined;
value: string | number | boolean | null | undefined;
rights?: string;
create?: boolean;
hasChild?: boolean;
};
export type Sets = Set[];

View File

@@ -1,12 +1,14 @@
import { ref } from 'vue';
import type { Ref } from 'vue';
import type { Driver } from './Drivers';
import type { Set } from './Set';
export type Subscribe = {
uuid?: string;
path?: string;
depth?: number;
type?: string;
drivers?: object | undefined;
drivers?: Record<string, Driver>;
value?: Ref<string | number | boolean | null | undefined>;
hasChild?: boolean;
};
@@ -18,20 +20,27 @@ export type RawSubscribe = {
path?: string;
depth?: number;
value?: string | number | boolean | null;
drivers?: Record<string, Driver>;
rights?: string;
hasChild?: boolean;
};
export type RawSubs = RawSubscribe[];
export function convertToSubscribe(raw: RawSubscribe): Subscribe {
export function convertToSubscribe(raw: RawSubscribe | Set): Subscribe {
return {
...raw,
uuid: raw.uuid ?? '',
value: ref(raw.value ?? null),
};
}
export function convertToSubscribes(rawList: RawSubs): Subs {
const subs = rawList.map(convertToSubscribe);
const subs = rawList.map(convertToSubscribe).sort((a, b) => {
const aPath = a.path ?? '';
const bPath = b.path ?? '';
return aPath.localeCompare(bPath);
});
return subs as Subs;
}

View File

@@ -1,7 +1,8 @@
import type { Ref } from 'vue';
import { reactive, ref } from 'vue';
import { convertToSubscribe } from 'src/models/Subscribe';
import type { Subs, Subscribe, RawSubs } from 'src/models/Subscribe';
import { convertToSubscribe } from '../models/Subscribe';
import type { Subscribe, RawSubs, RawSubscribe } from '../models/Subscribe';
import type { Set } from './Set';
const EMPTYUUID = '00000000-0000-0000-0000-000000000000';
export const Subscriptions = reactive<Record<string, Subscribe>>({});
@@ -11,16 +12,12 @@ export type TableSubscription = {
value: Ref<string | number | boolean | null | undefined>;
};
export function getRows(): Subs {
return Object.values(Subscriptions).map((sub) => {
sub.path = sub.path?.split(':').pop() ?? '';
if (!sub.type) sub.type = 'None';
else sub.type = sub.type.toLowerCase();
return sub;
});
export function addRawSubscription(sub: RawSubscribe | Set | undefined) {
if (sub === undefined) return;
addSubscription(convertToSubscribe(sub as RawSubscribe));
}
export function addSubscriptions(subs: RawSubs) {
export function addRawSubscriptions(subs: RawSubs) {
subs.forEach((sub) => addSubscription(convertToSubscribe(sub)));
}
@@ -46,9 +43,13 @@ export function updateSubscriptionValue(
Subscriptions[uuid].value = ref(value);
}
export function removeSubscriptions(subs: RawSubs) {
export function removeRawSubscription(sub: RawSubscribe | string) {
removeSubscription(typeof sub === 'string' ? sub : sub.uuid);
}
export function removeRawSubscriptions(subs: RawSubs) {
subs.forEach((sub) => {
removeSubscription(sub.path);
removeSubscription(sub.uuid);
});
}
@@ -56,7 +57,7 @@ export function removeAllSubscriptions() {
Object.keys(Subscriptions).forEach((key) => delete Subscriptions[key]);
}
function removeSubscription(uuid: string | undefined) {
export function removeSubscription(uuid: string | undefined) {
if (uuid === undefined) return;
if (!Subscriptions || Subscriptions[uuid] === undefined) return;
delete Subscriptions[uuid];
@@ -65,3 +66,8 @@ function removeSubscription(uuid: string | undefined) {
export function findSubscriptionByPath(path: string): Subscribe | undefined {
return Object.values(Subscriptions).find((sub) => sub.path === path);
}
export function findSubscriptionByUuid(uuid: string): Subscribe | undefined {
if (!Subscriptions[uuid]) return;
return Subscriptions[uuid];
}

View File

@@ -0,0 +1,4 @@
export interface Topic {
subscribe: string[];
publish: string[];
}

View File

@@ -0,0 +1,87 @@
import { reactive, ref } from 'vue';
import type { QTableColumn } from 'quasar';
import type { Subscribe } from './Subscribe';
import type { Bus } from './Bus';
import type { Topic } from './Topic';
export type DriverTableRow = {
type: string;
buses?: Bus[];
topic?: Topic;
bus: string;
address?: number | undefined;
subscribe?: string;
publish?: string;
};
const driverTable = reactive<DriverTableRow[]>([]);
const columns = ref<QTableColumn[]>([]);
const baseColumns: QTableColumn[] = [
{ name: 'type', label: 'Driver Name', field: 'type', align: 'left' },
{ name: 'bus', label: 'Bus Name', field: 'bus', align: 'center' },
{ name: 'address', label: 'Address', field: 'address', align: 'center' },
{ name: 'settings', label: '', field: 'settings', align: 'center' },
];
export function updateDriverTable(sub: Subscribe) {
driverTable.length = 0;
let hasSubs = false;
let hasPubs = false;
if (sub.drivers)
Object.entries(sub.drivers).forEach(([driverName, driverData]) => {
driverData.buses?.forEach((bus) => {
hasSubs = bus.topic?.subscribe !== undefined || hasSubs;
hasPubs = bus.topic?.publish !== undefined || hasPubs;
const subscribeList = bus.topic?.subscribe ?? [];
const publishList = bus.topic?.publish ?? [];
const addresses = bus.address?.length ? bus.address : [undefined];
addresses.forEach((addr) => {
driverTable.push({
type: driverName,
bus: bus.name,
address: addr,
subscribe: subscribeList.join(', '),
publish: publishList.join(', '),
});
});
});
});
reloadColumns(hasSubs, hasPubs);
}
export function useDriverTable() {
function emptyTable() {
driverTable.length = 0;
}
return {
driverTable,
emptyTable,
columns,
};
}
function reloadColumns(hasSubs: boolean, hasPubs: boolean) {
columns.value = [...baseColumns];
const settingsIndex = columns?.value.findIndex((col) => col.name === 'settings');
if (hasSubs) {
columns.value?.splice(settingsIndex ?? -1, 0, {
name: 'subscribe',
label: 'subscribe',
field: 'subscribe',
align: 'left',
});
}
if (hasPubs) {
columns.value?.splice(settingsIndex ?? -1, 0, {
name: 'publish',
label: 'publish',
field: 'publish',
align: 'left',
});
}
}

View File

@@ -0,0 +1,13 @@
import type { Response } from './Response';
export function catchError(data: Error | Response): string {
if (data instanceof Response) {
if (data.message) return data.message;
else console.error(data);
} else if (data instanceof Error) {
return data.message;
} else {
console.error(data);
}
return '';
}

View File

@@ -0,0 +1,38 @@
<template>
<DialogFrame ref="refDialog" width="500px" header-title="Add new Service">
<div class="row justify-center">
<q-select class="col-4" :options="opts" v-model="option"></q-select>
</div>
<!-- <q-table :rows="driverRows"> </q-table> -->
</DialogFrame>
</template>
<script setup lang="ts">
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import { ref } from 'vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import { appApi } from 'src/boot/axios';
const { NotifyResponse } = useNotify();
const refDialog = ref();
const driverRows = ref([]);
const opts = ref();
const option = ref('Choose new service');
interface conf {
name: string;
}
function open() {
appApi
.get('/allDrivers')
.then((resp) => {
driverRows.value = resp.data;
opts.value = resp.data.map((item: conf) => item.name);
})
.catch((err) => NotifyResponse(err, 'error'));
refDialog.value.open();
}
defineExpose({ open });
</script>

View File

@@ -1,53 +1,28 @@
import type { Response } from 'src/models/Response';
import { publishToSubscriptions } from 'src/models/Publish';
import type { Request } from 'src/models/Request';
import type { Response } from '../models/Response';
import { publishToSubscriptions } from '../models/Publish';
import type { Request } from '../models/Request';
import type { QVueGlobals } from 'quasar';
import { ref } from 'vue';
import { NotifyResponse } from 'src/composables/notify';
import { type Subs } from 'src/models/Subscribe';
import type { Sets } from 'src/models/Set';
import type { PongMessage } from 'src/models/Pong';
import { addSubscriptions } from 'src/models/Subscriptions';
import { type Subs } from '../models/Subscribe';
import type { Sets } from '../models/Set';
import { addRawSubscriptions } from '../models/Subscriptions';
const pendingResponses = new Map<string, (data: Response | undefined) => void>();
//const lastKnownValues: Record<string, string> = reactive({});
export let socket: WebSocket | null = null;
const isConnected = ref(false);
let lastPongTime = Date.now();
function pingLoop(interval: number = 5000) {
// Start sending ping every 5 seconds
setInterval(() => {
if (!socket || socket.readyState !== WebSocket.OPEN) return;
export function initWebSocket(host: string, port: number = 8100, $q?: QVueGlobals) {
const randomId = Math.floor(Math.random() * 10001); // random number from 0 to 10000
// If no pong received in last 10 seconds, close
if (Date.now() - lastPongTime > interval + 10000) {
console.warn('No pong response, closing socket...');
socket.close();
return;
}
socket.send(JSON.stringify({ type: 'ping' }));
}, interval);
}
function isPong(msg: PongMessage | undefined | null) {
if (msg?.type === 'pong') {
lastPongTime = Date.now();
return true;
}
return false;
}
export function initWebSocket(url: string, $q?: QVueGlobals) {
const connect = () => {
socket = new WebSocket(url);
socket = new WebSocket(`ws://${host}:${port}/ws?id=q${randomId}`);
socket.onopen = () => {
console.log('WebSocket connected');
isConnected.value = true;
// Start sending ping every 5 seconds
pingLoop(5000);
};
socket.onclose = () => {
isConnected.value = false;
console.log('WebSocket disconnected');
@@ -74,9 +49,6 @@ export function initWebSocket(url: string, $q?: QVueGlobals) {
if (typeof event.data === 'string') {
const message = JSON.parse(event.data);
// Handle pong
if (isPong(message)) return;
const id = message.id;
if (id && pendingResponses.has(id)) {
pendingResponses.get(id)?.(message); // resolve the promise
@@ -127,7 +99,14 @@ function waitForSocketConnection(): Promise<void> {
});
}
export function subscribeToPath(q: QVueGlobals, path: string) {
export function subscribeToPath(
NotifyResponse: (
resp: Response | string | undefined,
type?: 'warning' | 'error',
timeout?: 5000,
) => void,
path: string,
) {
subscribe([
{
path: path,
@@ -136,13 +115,13 @@ export function subscribeToPath(q: QVueGlobals, path: string) {
])
.then((response) => {
if (response?.subscribe) {
addSubscriptions(response.subscribe);
addRawSubscriptions(response.subscribe);
} else {
NotifyResponse(q, response);
NotifyResponse(response);
}
})
.catch((err) => {
NotifyResponse(q, err, 'error');
NotifyResponse(err, 'error');
});
}