9 Commits

Author SHA1 Message Date
Adrian Zürcher
33f7775800 .
Some checks failed
Build Quasar SPA and Go Backend for lightController / build (arm, 6, , linux, ubuntu-latest) (push) Successful in 6m30s
Build Quasar SPA and Go Backend for lightController / build (amd64, , linux, ubuntu-latest) (push) Successful in 6m39s
Build Quasar SPA and Go Backend for lightController / build (arm64, , linux, ubuntu-latest) (push) Successful in 4m30s
Build Quasar SPA and Go Backend for lightController / build (amd64, .exe, windows, windows-latest) (push) Has been cancelled
2025-08-11 10:52:31 +02:00
Adrian Zürcher
ac412bbffb fix npm for windows 2025-08-11 10:51:50 +02:00
Adrian Zürcher
6f532ef4b0 fix repo links
Some checks failed
Build Quasar SPA and Go Backend for lightController / build (amd64, .exe, windows) (push) Failing after 1m30s
Build Quasar SPA and Go Backend for lightController / build (amd64, , linux) (push) Successful in 6m1s
Build Quasar SPA and Go Backend for lightController / build (arm, 6, , linux) (push) Successful in 6m9s
Build Quasar SPA and Go Backend for lightController / build (arm64, , linux) (push) Successful in 4m45s
2025-08-11 10:37:48 +02:00
Adrian Zürcher
1155bafb30 lift version 2025-08-11 10:26:21 +02:00
Adrian Zürcher
0e3a14d69c change repo name
Some checks failed
Build Quasar SPA and Go Backend for lightController / build (amd64, , linux) (push) Failing after 5m18s
Build Quasar SPA and Go Backend for lightController / build (amd64, .exe, windows) (push) Failing after 5m23s
Build Quasar SPA and Go Backend for lightController / build (arm64, , linux) (push) Has been cancelled
Build Quasar SPA and Go Backend for lightController / build (arm, 6, , linux) (push) Has been cancelled
2025-08-11 10:25:25 +02:00
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
70 changed files with 2090 additions and 455 deletions

108
.gitea/workflows/build.yml Normal file
View File

@@ -0,0 +1,108 @@
name: Build Quasar SPA and Go Backend for lightController
on:
push:
tags:
- '*'
jobs:
build:
strategy:
matrix:
include:
- os: windows-latest
goos: windows
arch: amd64
ext: .exe
- os: ubuntu-latest
goos: linux
arch: amd64
ext: ""
- os: ubuntu-latest
goos: linux
arch: arm64
ext: ""
- os: ubuntu-latest
goos: linux
arch: arm
arm_version: 6
ext: ""
runs-on: ${{ matrix.os }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependecies
run: npm install
- name: Install Quasar CLI
run: |
npm cache clean --force
npm install -g @quasar/cli --force
- name: Build Quasar SPA
run: quasar build
- name: Ensure latest Go is installed in /data/go
run: |
export GOROOT=/data/go/go
export PATH=$GOROOT/bin:$PATH
export GOCACHE=/data/gocache
export GOMODCACHE=/data/gomodcache
mkdir -p $GOCACHE $GOMODCACHE
if [ ! -x "$GOROOT/bin/go" ]; then
echo "Go not found in $GOROOT, downloading latest stable..."
GO_VERSION=$(curl -s https://go.dev/VERSION?m=text | head -n1)
echo "Latest version is $GO_VERSION"
mkdir -p /data/go
curl -sSL "https://go.dev/dl/${GO_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz
tar -C /data/go -xzf /tmp/go.tar.gz
else
echo "Using cached Go from $GOROOT"
fi
go version
- name: Go Mod Tidy & Download
working-directory: ./backend
run: |
export GOROOT=/data/go/go
export PATH=$GOROOT/bin:$PATH
export GOCACHE=/data/gocache
export GOMODCACHE=/data/gomodcache
mkdir -p $GOCACHE $GOMODCACHE
go mod tidy -v
go mod download
- name: Build go backend binary
working-directory: ./backend
run: |
export GOROOT=/data/go/go
export PATH=$GOROOT/bin:$PATH
export GOCACHE=/data/gocache
export GOMODCACHE=/data/gomodcache
mkdir -p $GOCACHE $GOMODCACHE
OUTPUT="../server-${{ matrix.goos }}-${{ matrix.goarch }}"
if [ "${{ matrix.goos }}" == "windows" ]; then
OUTPUT="${OUTPUT}.exe"
fi
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -ldflags="-s -w" -trimpath -o "$OUTPUT" main.go
- name: Upload build artifacts
uses: actions/upload-artifact@v3
with:
name: lightcontroller-${{ matrix.goos }}-${{ matrix.goarch }}
path: |
./dist/spa
server-${{ matrix.goos }}-${{ matrix.goarch }}${{ (matrix.goos == 'windows' && '.exe') || '' }}

View File

@@ -1,71 +0,0 @@
name: Build Quasar SPA and Go Backend for lightController
on:
push:
branches: [main]
pull_request:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
goos: [linux, windows]
goarch: [amd64, arm, arm64]
exclude:
- goos: windows
goarch: arm
- goos: windows
goarch: arm64
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set ip Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependecies
run: npm install
- name: Install Quasar CLI
run: npm install -g @quasar/cli
- name: Build Quasar SPA
run: quasar build
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.24.0'
cache-dependency-path: backend/go.sum
- name: Set up Git credentials for private modules
run: |
git config --global url."https://oauth2:${{ secrets.GH_PAT }}@github.com".insteadOf "https://github.com"
env:
GH_PAT_FOR_MODULES: ${{ secrets.GH_PAT }}
- name: Go Mod Tidy & Download
working-directory: ./backend
run: go mod tidy -v
- name: Build go backend binary
working-directory: ./backend
run: |
if [ "${{ matrix.goos }}" == "windows" ]; then
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 -ldflags="-s -w" -trimpath -o ../server-${{ matrix.goos }}-${{ matrix.goarch }} main.go
fi
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: lightcontroller-${{ matrix.goos }}-${{ matrix.goarch }}
path: |
./dist/spa
server-${{ matrix.goos }}-${{ matrix.goarch }}${{ (matrix.goos == 'windows' && '.exe') || '' }}

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

@@ -5,12 +5,12 @@ go 1.24.0
toolchain go1.24.3
require (
gitea.tecamino.com/paadi/tecamino-dbm v0.1.1
gitea.tecamino.com/paadi/tecamino-logger v0.2.1
github.com/gin-contrib/cors v1.7.5
github.com/gin-gonic/gin v1.10.0
github.com/golang-jwt/jwt/v5 v5.2.2
github.com/google/uuid v1.6.0
github.com/tecamino/tecamino-dbm v0.0.10
github.com/tecamino/tecamino-logger v0.2.0
golang.org/x/crypto v0.36.0
modernc.org/sqlite v1.37.1
)

View File

@@ -1,3 +1,7 @@
gitea.tecamino.com/paadi/tecamino-dbm v0.1.1 h1:vAq7mwUxlxJuLzCQSDMrZCwo8ky5usWi9Qz+UP+WnkI=
gitea.tecamino.com/paadi/tecamino-dbm v0.1.1/go.mod h1:+tmf1rjPaKEoNeUcr1vdtoFIFweNG3aUGevDAl3NMBk=
gitea.tecamino.com/paadi/tecamino-logger v0.2.1 h1:sQTBKYPdzn9mmWX2JXZBtGBvNQH7cuXIwsl4TD0aMgE=
gitea.tecamino.com/paadi/tecamino-logger v0.2.1/go.mod h1:FkzRTldUBBOd/iy2upycArDftSZ5trbsX5Ira5OzJgM=
github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ=
github.com/bytedance/sonic v1.13.2/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
@@ -79,10 +83,6 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tecamino/tecamino-dbm v0.0.10 h1:+6OTl7yTsqLuYqE8QVB8ski3x0seI5yBFLnuHdVz99k=
github.com/tecamino/tecamino-dbm v0.0.10/go.mod h1:8YYOr/jQ9mGVmmNj2NE8HajDvlJAVY3iGOZNfMjd8kA=
github.com/tecamino/tecamino-logger v0.2.0 h1:NPH/Gg9qRhmVoW8b39i1eXu/LEftHc74nyISpcRG+XU=
github.com/tecamino/tecamino-logger v0.2.0/go.mod h1:0M1E9Uei/qw3e3WA1x3lBo1eP3H5oeYE7GjYrMahnj8=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=

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,6 +1,7 @@
package main
import (
"backend/drivers"
"backend/login"
"backend/models"
secenes "backend/scenes"
@@ -15,9 +16,9 @@ import (
"strings"
"time"
"gitea.tecamino.com/paadi/tecamino-logger/logging"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/tecamino/tecamino-logger/logging"
)
func main() {
@@ -27,6 +28,8 @@ func main() {
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")
@@ -69,6 +72,9 @@ func main() {
//new scenes handler
scenesHandler := secenes.NewScenesHandler("")
//new scenes handler
driversHandler := drivers.NewDriverHandler(filepath.Join(*cfgDir, *driversCfg))
// new server
s := server.NewServer()
@@ -92,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)
@@ -104,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

@@ -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"`
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,24 +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)
return
}
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Errorf("scene '%s' not found", scene.Name),
})
c.JSON(http.StatusBadRequest, models.NewJsonErrorMessageResponse(fmt.Sprintf("scene '%s' not found", scene.Name)))
}

View File

@@ -4,9 +4,9 @@ import (
"fmt"
"sync"
"gitea.tecamino.com/paadi/tecamino-dbm/cert"
"gitea.tecamino.com/paadi/tecamino-logger/logging"
"github.com/gin-gonic/gin"
"github.com/tecamino/tecamino-dbm/cert"
"github.com/tecamino/tecamino-logger/logging"
)
// server model for database manager websocket

Binary file not shown.

View File

@@ -8,7 +8,7 @@ import (
"path/filepath"
"runtime"
"github.com/tecamino/tecamino-logger/logging"
"gitea.tecamino.com/paadi/tecamino-logger/logging"
)
func OpenBrowser(url string, logger *logging.Logger) error {

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.20",
"version": "0.1.2",
"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,20 +2,29 @@ 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',
},
});
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

@@ -4,11 +4,8 @@ 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

@@ -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

@@ -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,10 +56,6 @@
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>
@@ -67,16 +63,14 @@
<script setup lang="ts">
import LightSlider from './LightSlider.vue';
import { ref, onMounted, onUnmounted } from 'vue';
import { onMounted, onUnmounted } from 'vue';
import { unsubscribe, subscribeToPath } from 'src/vueLib/services/websocket';
import SettingDialog from 'src/components/lights/SettingDomeLight.vue';
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 { NotifyResponse } = useNotify();
const settings = ref(false);
const brightness = updateValue(NotifyResponse, 'LightBar:Brightness');
const state = updateValue(NotifyResponse, 'LightBar:State');
onMounted(() => {

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"
@@ -114,14 +114,13 @@ import { findSubscriptionByPath, removeAllSubscriptions } from 'src/vueLib/model
import { catchError } from 'src/vueLib/models/error';
const { NotifyResponse } = useNotify();
const brightness = updateBrightnessValue('MovingHead:Brightness');
const state = updateValue(NotifyResponse, 'MovingHead:State');
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;

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

@@ -27,8 +27,10 @@
/>
<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>
@@ -52,6 +54,7 @@
>
<q-btn
rounded
no-caps
color="primary"
:class="['q-ma-md', 'text-bold', 'text-white']"
@click="openDialog('add')"
@@ -102,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')"
@@ -114,13 +118,13 @@
import { onMounted, reactive, ref } from 'vue';
import type { Scene } from 'src/models/Scene';
import type { Set } from 'src/vueLib/models/Set';
import axios from 'axios';
import { api } from 'src/boot/axios';
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/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();
@@ -130,26 +134,17 @@ 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;
@@ -166,9 +161,8 @@ function removeScene(name: string) {
.then((res) => {
if (res) {
scenes.value = scenes.value.filter((s) => s.name !== name);
quasarApi
.delete('/api/deleteScene', {
appApi
.delete('/deleteScene', {
data: { name },
})
.then((res) => {
@@ -190,8 +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;
newScene.floodPanels = true;
newScene.movingHead = true;
break;
case 'edit':
if (!scene) return;
@@ -205,8 +202,8 @@ function openDialog(dialogType: string, scene?: Scene, index?: number) {
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)));
@@ -236,9 +233,9 @@ const saveScene = async () => {
return;
}
if (newScene.movingHead) {
if (newScene.stageLights) {
sendValues.push({
path: 'MovingHead',
path: 'StageLights',
query: { depth: 0 },
});
}
@@ -250,9 +247,23 @@ 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(err as Error, 'error');
@@ -266,8 +277,8 @@ 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(res.data);
@@ -285,9 +296,9 @@ const saveScene = async () => {
return;
}
if (newScene.movingHead) {
if (newScene.stageLights) {
sendValues.push({
path: 'MovingHead',
path: 'StageLights',
query: { depth: 0 },
});
}
@@ -299,9 +310,23 @@ 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(err as Error, 'error');
@@ -313,8 +338,8 @@ 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(res.data);
@@ -333,11 +358,17 @@ const saveScene = async () => {
newScene.values?.forEach((element) => {
if (!element.path) return;
if (newScene.movingHead && element.path.includes('MovingHead'))
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 });
});
setValues(setPaths)

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

@@ -3,7 +3,9 @@ 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

@@ -5,14 +5,14 @@
<script setup lang="ts">
import DBMTree from 'src/vueLib/dbm/DBMTree.vue';
import { api } from 'src/boot/axios';
import { dbmApi } from 'src/boot/axios';
import { useNotify } from 'src/vueLib/general/useNotify';
import { catchError } from 'src/vueLib/models/error';
const { NotifyResponse } = useNotify();
function saveDBM() {
api
dbmApi
.get('saveData')
.then((resp) => NotifyResponse(resp.data))
.catch((err) => NotifyResponse(catchError(err), 'error'));

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

@@ -17,7 +17,7 @@
<div
:class="[
'text-left',
!props.row.path.includes('System') && props.row.path !== 'DBM'
props.row.path?.split(':')[0] !== 'System' && props.row.path !== 'DBM'
? 'cursor-pointer'
: '',
'q-mx-sm',
@@ -32,7 +32,7 @@
<div
:class="[
'text-center',
!props.row.path.includes('System') && props.row.path !== 'DBM'
props.row.path?.split(':')[0] !== 'System' && props.row.path !== 'DBM'
? 'cursor-pointer'
: '',
'q-mx-sm',
@@ -43,22 +43,31 @@
</q-td>
</template>
<template v-slot:body-cell-value="props">
<q-td :props="props" @click="openDialog(props.row)">
<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, 'driver')">
<div v-if="props.row.type !== 'none'" :class="['cursor-pointer']">
<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 width="400px" button-ok-label="Rename" ref="renameDialog" />
<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"
@@ -72,6 +81,7 @@
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';
@@ -80,10 +90,11 @@ 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?.includes('System') || sub.path === 'DBM') return;
if (sub.path?.split(':')[0] === 'System' && sub.path !== 'DBM') return;
switch (type) {
case 'type':
updateDatatype.value.open(sub.uuid);
@@ -91,10 +102,14 @@ const openDialog = (sub: Subscribe, type?: string) => {
case 'rename':
renameDialog.value.open(sub.uuid);
break;
default:
if (sub.type === 'none') return;
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;
}
};

View File

@@ -102,7 +102,7 @@
</q-list>
</q-menu>
<RenameDatapoint :dialogLabel="label" width="700px" button-ok-label="Rename" ref="renameDialog" />
<AddDialog :dialogLabel="label" width="700px" button-ok-label="Add" ref="addDialog" />
<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

View File

@@ -1,5 +1,10 @@
<template>
<DialogFrame ref="Dialog" :width="props.width" :header-title="props.dialogLabel">
<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"
@@ -10,7 +15,7 @@
<q-input
class="q-mt-lg q-mb-none q-pl-lg q-pr-xl"
filled
v-model="path"
v-model="addingForm.path"
label=""
:rules="[(val) => !!val || 'Path is required']"
>
@@ -18,7 +23,7 @@
<div class="column">
<span class="text-caption text-primary non-editable-prefix">Path *</span>
<span class="text-body2 text-grey-6 non-editable-prefix"
>{{ prefix }}{{ staticPrefix }}</span
>{{ addingForm.prefix }}{{ addingForm.staticPrefix }}</span
>
</div>
</template>
@@ -26,8 +31,8 @@
<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="read">Read</q-checkbox>
<q-checkbox v-model="write">Write</q-checkbox>
<q-checkbox v-model="addingForm.read">Read</q-checkbox>
<q-checkbox v-model="addingForm.write">Write</q-checkbox>
</div>
<q-input
:type="valueType"
@@ -35,17 +40,19 @@
label="Value"
class="q-pl-md q-pr-xl"
filled
v-model="value"
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 { ref, watch } from 'vue';
import { reactive, ref, watch } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import { useNotify } from '../../general/useNotify';
import DataTypes from '../../buttons/DataTypes.vue';
@@ -56,16 +63,21 @@ 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 path = ref('');
const staticPrefix = ref('');
const value = ref('');
const valueType = ref<'text' | 'number'>('text');
const read = ref(true);
const write = ref(true);
const datatype = ref('None');
const addForm = ref();
const prefix = 'DBM:';
const open = (uuid: string) => {
Dialog.value?.open();
@@ -84,15 +96,15 @@ function onSubmit() {
if (success) {
type = convertToType(datatype.value);
if (read.value) access = 'R';
if (write.value) access += 'W';
if (addingForm.read) access = 'R';
if (addingForm.write) access += 'W';
if (access == '') access = 'R';
setRequest(staticPrefix.value + path.value, type, value.value, access)
setRequest(addingForm.staticPrefix + addingForm.path, type, addingForm.value, access)
.then((respond) => {
if (respond) {
respond.forEach((set) => {
NotifyResponse("Datapoint '" + prefix + set.path + "' added");
NotifyResponse("Datapoint '" + addingForm.prefix + set.path + "' added");
});
addRawSubscription(respond[0]);
UpdateTable();
@@ -102,7 +114,7 @@ function onSubmit() {
NotifyResponse(catchError(err), 'error');
});
} else {
if (path.value === '') {
if (addingForm.path === '') {
NotifyResponse("Field 'Path' is requierd", 'error');
return;
} else NotifyResponse('Form not validated', 'error');
@@ -127,14 +139,18 @@ const props = defineProps({
type: String,
default: '300px',
},
height: {
type: String,
default: '650px',
},
});
function getDatapoint(uuid: string) {
getRequest(uuid, '', 1)
.then((resp) => {
if (resp[0]) {
staticPrefix.value = resp[0].path ?? '';
if (staticPrefix.value !== '') staticPrefix.value += ':';
addingForm.staticPrefix = resp[0].path ?? '';
if (addingForm.staticPrefix !== '') addingForm.staticPrefix += ':';
}
})
.catch((err) => NotifyResponse(catchError(err), 'error'));

View File

@@ -1,5 +1,10 @@
<template>
<DialogFrame ref="Dialog" :width="props.width" :header-title="props.dialogLabel">
<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"
@@ -10,7 +15,7 @@
<q-input
class="q-mt-lg q-mb-none q-pl-md q-mx-lg"
filled
v-model="path"
v-model="copyData.path"
label="Current Path"
label-color="primary"
readonly
@@ -19,7 +24,7 @@
<q-input
class="q-mt-lg q-mt-none q-pl-md q-mx-lg"
filled
v-model="copyPath"
v-model="copyData.copyPath"
label="New Path *"
label-color="primary"
@keyup.enter="onSubmit"
@@ -27,16 +32,18 @@
>
</q-input>
<div class="q-mx-sm">
<q-btn no-caps class="q-mb-xl q-ml-lg q-px-lg" @click="onSubmit" color="primary">{{
<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 { ref } from 'vue';
import { reactive, ref } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import { useNotify } from '../../general/useNotify';
import { getRequest, setsRequest } from 'src/vueLib/models/Request';
@@ -44,11 +51,14 @@ 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 path = ref('');
const copyPath = ref('');
const copyForm = ref();
const prefix = 'DBM:';
const open = (uuid: string) => {
Dialog.value?.open();
@@ -58,18 +68,18 @@ const open = (uuid: string) => {
function onSubmit() {
copyForm.value.validate().then((success: undefined) => {
if (success) {
if (copyPath.value === path.value) {
if (copyData.copyPath === copyData.path) {
NotifyResponse('copy path can not be the same as current path', 'error');
return;
}
const absolutePath = path.value.slice(prefix.length);
const absolutecopyPath = copyPath.value.slice(prefix.length);
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 '" + copyPath.value + "' already exists", 'warning');
NotifyResponse("path '" + copyData.copyPath + "' already exists", 'warning');
return;
}
})
@@ -80,7 +90,7 @@ function onSubmit() {
setsRequest(
datapointRequestForCopy(response, absolutePath, absolutecopyPath),
).catch((err) => console.error(err));
NotifyResponse(copyPath.value + ' copied');
NotifyResponse(copyData.copyPath + ' copied');
})
.catch((err) => NotifyResponse(catchError(err), 'error'));
} else {
@@ -89,7 +99,7 @@ function onSubmit() {
return;
});
} else {
if (copyPath.value === '') {
if (copyData.copyPath === '') {
NotifyResponse("Field 'New Path' is requierd", 'error');
return;
} else NotifyResponse('Form not validated', 'error');
@@ -114,14 +124,18 @@ const props = defineProps({
type: String,
default: '300px',
},
height: {
type: String,
default: '400px',
},
});
function getDatapoint(uuid: string) {
getRequest(uuid)
.then((resp) => {
if (resp[0]) {
path.value = prefix + resp[0].path;
copyPath.value = prefix + resp[0].path;
copyData.path = copyData.prefix + resp[0].path;
copyData.copyPath = copyData.prefix + resp[0].path;
}
})
.catch((err) => NotifyResponse(catchError(err), 'error'));

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

@@ -8,12 +8,14 @@
</q-card-section>
<div class="text-center text-bold text-primary">
Do you want to remove Datapoint
<br />
<br /><br />
'{{ datapoint.path ?? '' }}'
</div>
<q-btn no-caps class="q-ma-md" filled color="negative" @click="remove">{{
<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>

View File

@@ -1,5 +1,10 @@
<template>
<DialogFrame ref="Dialog" :width="props.width" :header-title="props.dialogLabel">
<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"
@@ -10,7 +15,7 @@
<q-input
class="q-mt-lg q-mb-none q-pl-md q-mx-lg"
filled
v-model="path"
v-model="removeData.path"
label="Current Path"
label-color="primary"
readonly
@@ -19,14 +24,14 @@
<q-input
class="q-mt-lg q-mt-none q-pl-md q-mx-lg"
filled
v-model="newPath"
v-model="removeData.newPath"
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-mr-lg">
<q-btn no-caps class="q-mb-xl q-ml-lg q-px-lg" @click="onSubmit" color="primary">{{
props.buttonOkLabel
}}</q-btn>
@@ -36,7 +41,7 @@
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { reactive, ref } from 'vue';
import DialogFrame from '../../dialog/DialogFrame.vue';
import { useNotify } from '../../general/useNotify';
import { getRequest, setRequest } from 'src/vueLib/models/Request';
@@ -49,10 +54,13 @@ import { buildTree } from '../dbmTree';
const { NotifyResponse } = useNotify();
const Dialog = ref();
const datapoint = ref();
const path = ref('');
const newPath = ref('');
const removeData = reactive({
path: '',
newPath: '',
prefix: 'DBM:',
});
const copyForm = ref();
const prefix = 'DBM:';
const open = (uuid: string) => {
Dialog.value?.open();
@@ -62,14 +70,13 @@ const open = (uuid: string) => {
function onSubmit() {
copyForm.value.validate().then((success: undefined) => {
if (success) {
if (newPath.value === path.value) {
if (removeData.newPath === removeData.path) {
NotifyResponse('same name', 'warning');
return;
}
getRequest('', newPath.value.slice(prefix.length), 1)
getRequest('', removeData.newPath.slice(removeData.prefix.length), 1)
.then((response) => {
console.log(10, response);
if (response?.length > 0) {
NotifyResponse("path '" + response[0]?.path + "' already exists", 'warning');
return;
@@ -83,11 +90,12 @@ function onSubmit() {
}
setRequest(
newPath.value.slice(prefix.length),
removeData.newPath.slice(removeData.prefix.length),
datapoint.value.type,
datapoint.value.value,
datapoint.value.rights,
datapoint.value.uuid,
undefined,
true,
)
.then((res) => {
@@ -98,7 +106,7 @@ function onSubmit() {
.catch((err) => NotifyResponse(err, 'error'));
});
} else {
if (newPath.value === '') {
if (removeData.newPath === '') {
NotifyResponse("Field 'New Path' is requierd", 'error');
return;
} else NotifyResponse('Form not validated', 'error');
@@ -123,6 +131,10 @@ const props = defineProps({
type: String,
default: '300px',
},
height: {
type: String,
default: '400px',
},
});
function getDatapoint(uuid: string) {
@@ -130,8 +142,8 @@ function getDatapoint(uuid: string) {
.then((resp) => {
if (resp[0]) {
datapoint.value = resp[0];
path.value = prefix + resp[0].path;
newPath.value = prefix + resp[0].path;
removeData.path = removeData.prefix + resp[0].path;
removeData.newPath = removeData.prefix + resp[0].path;
}
})
.catch((err) => NotifyResponse(catchError(err), 'error'));

View File

@@ -1,10 +1,17 @@
<template>
<DialogFrame ref="Dialog" :width="props.width" :header-title="props.dialogLabel">
<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"
>DBM:{{ datapoint.path }}
>{{
datapoint.uuid === '00000000-0000-0000-0000-000000000000' ? 'DBM' : 'DBM:' + datapoint.path
}}
</q-card-section>
<q-form ref="datatypeForm" class="q-gutter-md">
<q-input
@@ -12,7 +19,7 @@
filled
dense
v-model="currentDatatype"
label="Current Path"
label="Current Datatype"
label-color="primary"
readonly
>
@@ -20,6 +27,7 @@
<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"
@@ -27,7 +35,7 @@
option-label="label"
>
</q-select>
<div class="q-mx-sm">
<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>
@@ -114,6 +122,10 @@ const props = defineProps({
type: String,
default: '300px',
},
height: {
type: String,
default: '340px',
},
});
async function getDatapoint(uuid: string) {

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

@@ -1,12 +1,17 @@
<template>
<DialogFrame ref="Dialog" :width="props.width" :header-title="datapoint?.path">
<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="drivers && drivers.length == 0">
<q-card-section v-if="datapoint.type !== 'BIT'">
<q-input
class="q-px-md q-ma-sm"
label="current value"
@@ -27,24 +32,29 @@
></q-input>
</q-card-section>
<q-card-section v-else>
<q-table
flat
dense
virtual-scroll
:rows-per-page-options="[0]"
:rows="drivers"
:columns="columns"
>
</q-table>
<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="left" class="text-primary">
<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"
class="q-mb-xl q-mr-lg q-mt-none"
v-if="props.buttonOkLabel"
color="primary"
no-caps
@@ -63,15 +73,16 @@ import type { Subscribe } from '../../models/Subscribe';
import type { Ref } from 'vue';
import { setValues } from '../../services/websocket';
import { useNotify } from '../../general/useNotify';
import type { QTableProps } from 'quasar';
import type { Driver } from '../../models/Drivers';
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: {
@@ -98,35 +109,20 @@ const props = defineProps({
type: String,
default: '300px',
},
height: {
type: String,
default: '350px',
},
});
const datapoint = ref();
const inputValue = ref(datapoint?.value);
const localDialogLabel = ref('');
const drivers = ref<Driver[]>([]);
const columns = [
{ 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' },
] as QTableProps['columns'];
const open = (sub: Ref<Subscribe>, type?: string) => {
const open = (sub: Ref<Subscribe>) => {
datapoint.value = sub.value;
if (datapoint.value.rights == 'R') onlyRead.value = true;
drivers.value = [];
switch (type) {
case 'driver':
localDialogLabel.value = 'Update Drivers';
if (sub.value.drivers) drivers.value = Object.values(sub.value.drivers);
writeValue.value = sub.value.drivers;
break;
default:
localDialogLabel.value = 'Update Value';
if (sub.value.type === 'STR') writeType.value = 'text';
else if (sub.value.type === 'BIT') writeType.value = 'text';
else writeType.value = 'number';
writeValue.value = sub.value.value;
}
Dialog.value?.open();
};
@@ -156,4 +152,8 @@ defineExpose({ open });
.outercard {
border-radius: 10px;
}
.readonly-toggle {
pointer-events: none;
opacity: 0.7;
}
</style>

View File

@@ -7,18 +7,30 @@
:no-refocus="!minMaxState"
:seamless="!minMaxState"
>
<q-card class="layout" :style="cardStyle" v-touch-pan.mouse.prevent.stop="handlePan">
<div :class="props.headerTitle ? 'row items-center justify-between' : ''">
<div v-if="headerTitle" class="q-mx-sm q-mt-xs text-left text-bold text-caption">
{{ props.headerTitle }}
<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-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>
<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" />
<div class="scrollArea"><slot /></div>
<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>
@@ -29,54 +41,107 @@ 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({
headerTitle: {
type: String,
default: '',
},
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 } }) => {
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, close });
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 {
border-radius: 10px;
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 {
overflow-y: auto;
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

@@ -22,6 +22,19 @@ export function useNotify() {
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 === '') {

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

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

View File

@@ -1,14 +1,21 @@
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 } from './Subscriptions';
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';
@@ -33,6 +40,11 @@ export function publishToSubscriptions(pubs: Pubs) {
rawSubs.value.push(pub as RawSubscribe);
break;
}
if (pub.drivers) {
removeRawSubscription(pub as RawSubscribe);
addRawSubscription(pub as RawSubscribe);
UpdateTable();
}
updateSubscriptionValue(pub.uuid, pub.value);
});

View File

@@ -1,7 +1,8 @@
import type { Driver } from './Drivers';
import type { Gets } from './Get';
import type { Sets } from './Set';
import type { Subs } from './Subscribe';
import { api } from 'src/boot/axios';
import { dbmApi } from 'src/boot/axios';
export type Request = {
get?: Gets;
@@ -24,7 +25,7 @@ export async function getRequest(
payload = { path: path, query: { depth: depth } };
}
const resp = await api.post(query, {
const resp = await dbmApi.post(query, {
get: [payload],
});
@@ -36,7 +37,7 @@ export async function getRequest(
}
export async function getRequests(gets: Gets): Promise<Gets> {
const resp = await api.post(query, {
const resp = await dbmApi.post(query, {
get: gets,
});
@@ -48,7 +49,7 @@ export async function getRequests(gets: Gets): Promise<Gets> {
}
export async function rawSetsRequest(sets: Sets): Promise<Sets> {
const resp = await api.post(query, {
const resp = await dbmApi.post(query, {
set: sets,
});
@@ -61,10 +62,11 @@ export async function rawSetsRequest(sets: Sets): Promise<Sets> {
export async function setRequest(
path: string,
type: string,
value: string | number | boolean,
type?: string,
value?: string | number | boolean,
rights?: string,
uuid?: string,
driver?: Driver,
rename?: boolean,
): Promise<Sets> {
const payload = {
@@ -73,10 +75,11 @@ export async function setRequest(
value: value,
rights: rights,
uuid: uuid,
driver: driver,
rename: rename,
};
const resp = await api.post(query, {
const resp = await dbmApi.post(query, {
set: [payload],
});
@@ -88,7 +91,7 @@ export async function setRequest(
}
export async function setsRequest(sets: Sets): Promise<Sets> {
const resp = await api.post(query, {
const resp = await dbmApi.post(query, {
set: sets,
});
@@ -99,15 +102,19 @@ export async function setsRequest(sets: Sets): Promise<Sets> {
}
}
export async function deleteRequest(uuid?: string, path?: string, rename?: boolean): Promise<Sets> {
export async function deleteRequest(
uuid?: string,
path?: string,
driver?: Driver,
rename?: boolean,
): Promise<Sets> {
let payload = {};
if (uuid) {
payload = { uuid: uuid, rename: rename };
payload = { uuid: uuid, driver: driver, rename: rename };
} else if (path) {
payload = { path: path };
payload = { path: path, driver: driver };
}
const resp = await api.delete('/json_data', {
const resp = await dbmApi.delete('/json_data', {
data: {
set: [payload],
},

View File

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

View File

@@ -20,6 +20,7 @@ export type RawSubscribe = {
path?: string;
depth?: number;
value?: string | number | boolean | null;
drivers?: Record<string, Driver>;
rights?: string;
hasChild?: boolean;
};

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,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

@@ -12,9 +12,11 @@ export let socket: WebSocket | null = null;
const isConnected = ref(false);
export function initWebSocket(url: string, $q?: QVueGlobals) {
export function initWebSocket(host: string, port: number = 8100, $q?: QVueGlobals) {
const randomId = Math.floor(Math.random() * 10001); // random number from 0 to 10000
const connect = () => {
socket = new WebSocket(url);
socket = new WebSocket(`ws://${host}:${port}/ws?id=q${randomId}`);
socket.onopen = () => {
console.log('WebSocket connected');