mirror of
https://github.com/jwetzell/showbridge-go.git
synced 2026-04-27 05:15:47 +00:00
Compare commits
120 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6c1c5c600 | ||
|
|
b6ec615e40 | ||
|
|
216775c9c6 | ||
|
|
1bfee2186b | ||
|
|
fa612231fb | ||
|
|
c1161c5aa9 | ||
|
|
b1076ce1e4 | ||
|
|
7f5204aca0 | ||
|
|
f3d87e92f8 | ||
|
|
e50e269697 | ||
|
|
ca6aebadef | ||
|
|
818ddc18f4 | ||
|
|
3e7b245536 | ||
|
|
e996d84234 | ||
|
|
04c8ebbe06 | ||
|
|
0f57e123ce | ||
|
|
82ba1d5d10 | ||
|
|
20c53e4996 | ||
|
|
8132faaba6 | ||
|
|
5a0f21bd64 | ||
|
|
fd0f78733c | ||
|
|
65476d5ecc | ||
|
|
536bc2af4e | ||
|
|
b89d907759 | ||
|
|
a3c48de2ad | ||
|
|
8ca9d9940f | ||
|
|
53d0648774 | ||
|
|
cf2881e5c3 | ||
|
|
f437438dca | ||
|
|
6b3c470534 | ||
|
|
3bdff5309f | ||
|
|
3792d40bb1 | ||
|
|
0cca2e3be9 | ||
|
|
5447781232 | ||
|
|
c760b220c0 | ||
|
|
cb71b5c5b8 | ||
|
|
84fd7c1028 | ||
|
|
7bdf6e01b3 | ||
|
|
1b607f64cd | ||
|
|
28e9141cbc | ||
|
|
3b38110ffb | ||
|
|
25e8563cd1 | ||
|
|
80969ac1ff | ||
|
|
beb3664e3b | ||
|
|
6e53cbe8fd | ||
|
|
4ebaa48f93 | ||
|
|
79d535c283 | ||
|
|
85349f8540 | ||
|
|
e49900a3a7 | ||
|
|
1f706becdc | ||
|
|
13a494239e | ||
|
|
153de944a2 | ||
|
|
42c75074fe | ||
|
|
361b07ec00 | ||
|
|
8c4f0591e1 | ||
|
|
09ddc40f1f | ||
|
|
6382cf6944 | ||
|
|
0732113a02 | ||
|
|
e5db9a48a9 | ||
|
|
9502201261 | ||
|
|
9859aa8fd4 | ||
|
|
b7b05cbb77 | ||
|
|
7b1fe47039 | ||
|
|
0848d8ab6e | ||
|
|
c1bb2ff4cb | ||
|
|
50898b9130 | ||
|
|
05e68e90af | ||
|
|
cd4c3f59f2 | ||
|
|
50399fa811 | ||
|
|
2dd44a11fd | ||
|
|
b7a8b04a72 | ||
|
|
078e6ec68c | ||
|
|
b58187d6a9 | ||
|
|
38b8e44f04 | ||
|
|
dff33f722d | ||
|
|
572a54d3b2 | ||
|
|
6a21cc2639 | ||
|
|
0d4ec24a9b | ||
|
|
10c6e84682 | ||
|
|
7ac0ec7582 | ||
|
|
c25a36f09c | ||
|
|
8d2c022baf | ||
|
|
76318b4e10 | ||
|
|
633eaba0ec | ||
|
|
00b6f3660d | ||
|
|
a275cd2b78 | ||
|
|
5cb2f845a1 | ||
|
|
8f769f0a4a | ||
|
|
fdd4b341cb | ||
|
|
9a9bf10078 | ||
|
|
ea46885f70 | ||
|
|
fa8f0b7cfc | ||
|
|
d316147411 | ||
|
|
30564523d7 | ||
|
|
f7231e54c2 | ||
|
|
14de829e7a | ||
|
|
33a54eb24c | ||
|
|
3c6c50c914 | ||
|
|
da516f5102 | ||
|
|
1f88819428 | ||
|
|
df4f0f745d | ||
|
|
d86bff30cd | ||
|
|
22d8bbf88d | ||
|
|
925873a124 | ||
|
|
08308c1891 | ||
|
|
f68312ee84 | ||
|
|
cd1b5e1437 | ||
|
|
34af7d7aec | ||
|
|
df14024012 | ||
|
|
af39c16f30 | ||
|
|
7d2a3225a7 | ||
|
|
b5ffee022a | ||
|
|
cd264d9ed4 | ||
|
|
9d14e5929f | ||
|
|
8fe1463198 | ||
|
|
28a5d1ea90 | ||
|
|
e9d5931e9d | ||
|
|
d90f103d00 | ||
|
|
05b0de1dfd | ||
|
|
0d8dbab743 |
8
.github/dependabot.yml
vendored
8
.github/dependabot.yml
vendored
@@ -1,10 +1,10 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: 'github-actions'
|
||||
directory: '/'
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: 'weekly'
|
||||
interval: "weekly"
|
||||
- package-ecosystem: gomod
|
||||
directory: /
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
interval: "weekly"
|
||||
|
||||
18
.github/labeler.yml
vendored
18
.github/labeler.yml
vendored
@@ -1,27 +1,27 @@
|
||||
config:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/config/**'
|
||||
- any-glob-to-any-file: "internal/config/**"
|
||||
|
||||
framer:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/framer/**'
|
||||
- any-glob-to-any-file: "internal/framer/**"
|
||||
|
||||
module:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/module/**'
|
||||
- any-glob-to-any-file: "internal/module/**"
|
||||
|
||||
processor:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/processor/**'
|
||||
- any-glob-to-any-file: "internal/processor/**"
|
||||
|
||||
router:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'router*'
|
||||
|
||||
- any-glob-to-any-file: "router*"
|
||||
|
||||
route:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/route/**'
|
||||
|
||||
- any-glob-to-any-file: "internal/route/**"
|
||||
|
||||
cli:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'cmd/showbridge/**'
|
||||
- any-glob-to-any-file: "cmd/showbridge/**"
|
||||
|
||||
2
.github/release.yml
vendored
2
.github/release.yml
vendored
@@ -26,4 +26,4 @@ changelog:
|
||||
- cli
|
||||
- title: Other Changes
|
||||
labels:
|
||||
- '*'
|
||||
- "*"
|
||||
|
||||
2
.github/workflows/label-pr.yaml
vendored
2
.github/workflows/label-pr.yaml
vendored
@@ -15,4 +15,4 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/labeler@634933edcd8ababfe52f92936142cc22ac488b1b # v6.0.1
|
||||
with:
|
||||
sync-labels: true
|
||||
sync-labels: true
|
||||
|
||||
12
.github/workflows/release-showbridge.yaml
vendored
12
.github/workflows/release-showbridge.yaml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
go-version-file: "go.mod"
|
||||
- name: release
|
||||
uses: goreleaser/goreleaser-action@v7
|
||||
with:
|
||||
@@ -37,26 +37,26 @@ jobs:
|
||||
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
|
||||
uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4.0.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
|
||||
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
|
||||
uses: docker/login-action@b45d80f862d83dbcd57f89517bcf500b2ab88fb2 # v4.0.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Setup Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6.0.0
|
||||
with:
|
||||
images: |
|
||||
jwetzell/showbridge
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
|
||||
uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0
|
||||
with:
|
||||
push: true
|
||||
context: ./
|
||||
|
||||
20
.github/workflows/test-showbridge.yaml
vendored
20
.github/workflows/test-showbridge.yaml
vendored
@@ -5,16 +5,16 @@ on:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- '**/*.go'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- "**/*.go"
|
||||
- "go.mod"
|
||||
- "go.sum"
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- '**/*.go'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- "**/*.go"
|
||||
- "go.mod"
|
||||
- "go.sum"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -29,15 +29,15 @@ jobs:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
go-version-file: "go.mod"
|
||||
- name: mod tidy
|
||||
run: go mod tidy
|
||||
|
||||
- name: run tests
|
||||
run: go test ./... -coverpkg "github.com/jwetzell/showbridge-go/..." -coverprofile coverage.out
|
||||
run: go test ./... -count=1 -coverpkg "github.com/jwetzell/showbridge-go/..." -coverprofile coverage.out
|
||||
|
||||
- name: clean up coverage report
|
||||
run: cat coverage.out | grep -v "github.com/jwetzell/showbridge-go/cmd" > coverage.nocmd.out
|
||||
run: cat coverage.out | grep -v "github.com/jwetzell/showbridge-go/cmd" > coverage.nocmd.out
|
||||
- name: Update coverage report
|
||||
uses: ncruces/go-coverage-report@v0.3.2
|
||||
with:
|
||||
@@ -45,5 +45,5 @@ jobs:
|
||||
report: true
|
||||
chart: true
|
||||
amend: true
|
||||
if: github.event_name == 'push'
|
||||
if: github.event_name == 'push'
|
||||
continue-on-error: true
|
||||
|
||||
33
.vscode/launch.json
vendored
33
.vscode/launch.json
vendored
@@ -1,18 +1,17 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
|
||||
{
|
||||
"name": "Launch showbridge",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "cmd/showbridge",
|
||||
"args": ["--log-level", "debug"],
|
||||
"cwd": "./"
|
||||
}
|
||||
]
|
||||
}
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch showbridge",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "cmd/showbridge",
|
||||
"args": ["--log-level", "debug"],
|
||||
"cwd": "./"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
ARG GO_VERSION=1.25.5
|
||||
ARG GO_VERSION=1.26.0
|
||||
FROM golang:${GO_VERSION}-alpine AS build
|
||||
RUN apk --no-cache add ca-certificates tzdata
|
||||
WORKDIR /build
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
# showbridge (go edition)
|
||||
|
||||
[](https://raw.githack.com/wiki/jwetzell/showbridge-go/coverage.html)
|
||||
|
||||
Simple protocol router _/s_
|
||||
|
||||
</div>
|
||||
@@ -14,6 +13,7 @@ Simple protocol router _/s_
|
||||
</p>
|
||||
|
||||
### Supported Protocols
|
||||
|
||||
- HTTP
|
||||
- UDP
|
||||
- TCP
|
||||
@@ -25,7 +25,7 @@ Simple protocol router _/s_
|
||||
- [OSC](https://opensoundcontrol.stanford.edu/spec-1_0.html)
|
||||
- [FreeD](https://ptzoptics.com/freed/)
|
||||
- [SIP](https://en.wikipedia.org/wiki/Session_Initiation_Protocol)
|
||||
|
||||
|
||||
### CLI Usage
|
||||
|
||||
```
|
||||
|
||||
146
api.go
Normal file
146
api.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
func (r *Router) startAPIServer(config config.ApiConfig) {
|
||||
r.logger.Debug("starting API server", "port", config.Port)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/ws", r.handleWebsocket)
|
||||
mux.HandleFunc("/health", r.handleHealthHTTP)
|
||||
mux.HandleFunc("/schema/{schema}", r.handleSchemaHTTP)
|
||||
mux.HandleFunc("/api/v1/config", r.handleConfigHTTP)
|
||||
|
||||
r.apiServerMu.Lock()
|
||||
defer r.apiServerMu.Unlock()
|
||||
r.apiServer = &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", config.Port),
|
||||
Handler: mux,
|
||||
}
|
||||
|
||||
go func() {
|
||||
r.apiServer.ListenAndServe()
|
||||
r.apiServerShutdown()
|
||||
}()
|
||||
}
|
||||
|
||||
func (r *Router) stopAPIServer() {
|
||||
r.logger.Debug("stopping API server")
|
||||
r.apiServerMu.Lock()
|
||||
defer r.apiServerMu.Unlock()
|
||||
if r.apiServer != nil {
|
||||
apiShutdownCtx, apiShutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
r.apiServerShutdown = apiShutdownCancel
|
||||
r.apiServer.Shutdown(apiShutdownCtx)
|
||||
<-apiShutdownCtx.Done()
|
||||
r.apiServer = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) handleHealthHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case http.MethodOptions:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) handleConfigHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
configJSON, err := json.Marshal(r.runningConfig)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(configJSON)
|
||||
case http.MethodPut:
|
||||
var newConfig config.Config
|
||||
err := json.NewDecoder(req.Body).Decode(&newConfig)
|
||||
if err != nil {
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
moduleErrors, routeErrors := r.UpdateConfig(newConfig)
|
||||
if len(moduleErrors) > 0 || len(routeErrors) > 0 {
|
||||
errorResponse := struct {
|
||||
ModuleErrors []module.ModuleError `json:"moduleErrors,omitempty"`
|
||||
RouteErrors []route.RouteError `json:"routeErrors,omitempty"`
|
||||
}{
|
||||
ModuleErrors: moduleErrors,
|
||||
RouteErrors: routeErrors,
|
||||
}
|
||||
errorResponseJSON, err := json.Marshal(errorResponse)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write(errorResponseJSON)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
r.ConfigChange <- newConfig
|
||||
case http.MethodOptions:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//go:embed schema
|
||||
var schema embed.FS
|
||||
|
||||
func (r *Router) handleSchemaHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
schemaName := req.PathValue("schema")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
configSchema, err := schema.ReadFile(fmt.Sprintf("schema/%s.schema.json", schemaName))
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Write(configSchema)
|
||||
case http.MethodOptions:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ builds:
|
||||
- "amd64"
|
||||
- "arm64"
|
||||
ldflags:
|
||||
- '-s -w -X main.version={{.RawVersion}}-{{.ShortCommit}}'
|
||||
- "-s -w -X main.version={{.RawVersion}}-{{.ShortCommit}}"
|
||||
|
||||
archives:
|
||||
- formats: [tar.gz]
|
||||
|
||||
@@ -13,12 +13,14 @@ import (
|
||||
|
||||
"github.com/jwetzell/showbridge-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"github.com/urfave/cli/v3"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.39.0"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
@@ -109,6 +111,20 @@ func readConfig(configPath string) (config.Config, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func writeConfig(configPath string, newConfig config.Config) error {
|
||||
configBytes, err := yaml.Marshal(newConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = os.WriteFile(configPath, configBytes, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func run(ctx context.Context, c *cli.Command) error {
|
||||
configPath := c.String("config")
|
||||
if configPath == "" {
|
||||
@@ -173,7 +189,19 @@ func run(ctx context.Context, c *cli.Command) error {
|
||||
routerRunner: &sync.WaitGroup{},
|
||||
}
|
||||
|
||||
router, err := showbridgeApp.getNewRouter()
|
||||
config, err := readConfig(showbridgeApp.configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
router, moduleErrors, routeErrors := showbridge.NewRouter(config)
|
||||
|
||||
showbridgeApp.logConfigErrors(moduleErrors, routeErrors)
|
||||
|
||||
if moduleErrors != nil || routeErrors != nil {
|
||||
return fmt.Errorf("errors initializing modules or routes")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize router: %w", err)
|
||||
}
|
||||
@@ -185,7 +213,7 @@ func run(ctx context.Context, c *cli.Command) error {
|
||||
})
|
||||
showbridgeApp.routerMutex.Unlock()
|
||||
|
||||
go showbridgeApp.handleHangup()
|
||||
go showbridgeApp.handleChannels()
|
||||
|
||||
<-showbridgeApp.ctx.Done()
|
||||
showbridgeApp.logger.Debug("shutting down router")
|
||||
@@ -195,40 +223,37 @@ func run(ctx context.Context, c *cli.Command) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (app *showbridgeApp) handleHangup() {
|
||||
func (app *showbridgeApp) handleChannels() {
|
||||
for {
|
||||
select {
|
||||
case <-sigHangup:
|
||||
app.logger.Info("received SIGHUP, reloading configuration")
|
||||
newRouter, err := app.getNewRouter()
|
||||
app.routerMutex.Lock()
|
||||
config, err := readConfig(app.configPath)
|
||||
if err != nil {
|
||||
app.logger.Error("failed to reload configuration", "error", err)
|
||||
app.logger.Error("failed to read config file", "error", err)
|
||||
app.routerMutex.Unlock()
|
||||
continue
|
||||
}
|
||||
app.routerMutex.Lock()
|
||||
app.router.Stop()
|
||||
app.routerRunner.Wait()
|
||||
app.router = newRouter
|
||||
app.routerRunner.Go(func() {
|
||||
app.router.Start(context.Background())
|
||||
})
|
||||
moduleErrors, routeErrors := app.router.UpdateConfig(config)
|
||||
app.logConfigErrors(moduleErrors, routeErrors)
|
||||
app.logger.Info("configuration reloaded successfully")
|
||||
app.routerMutex.Unlock()
|
||||
case config := <-app.router.ConfigChange:
|
||||
app.logger.Info("router config changed updating config file")
|
||||
err := writeConfig(app.configPath, config)
|
||||
if err != nil {
|
||||
app.logger.Error("failed to write config file", "error", err)
|
||||
continue
|
||||
}
|
||||
app.logger.Info("config file updated successfully")
|
||||
case <-app.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (app *showbridgeApp) getNewRouter() (*showbridge.Router, error) {
|
||||
// TODO(jwetzell): what should happen when the config file is unchanged?
|
||||
config, err := readConfig(app.configPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
router, moduleErrors, routeErrors := showbridge.NewRouter(config)
|
||||
|
||||
func (app *showbridgeApp) logConfigErrors(moduleErrors []module.ModuleError, routeErrors []route.RouteError) {
|
||||
for _, moduleError := range moduleErrors {
|
||||
app.logger.Error("problem initializing module", "index", moduleError.Index, "error", moduleError.Error)
|
||||
}
|
||||
@@ -236,12 +261,6 @@ func (app *showbridgeApp) getNewRouter() (*showbridge.Router, error) {
|
||||
for _, routeError := range routeErrors {
|
||||
app.logger.Error("problem initializing route", "index", routeError.Index, "error", routeError.Error)
|
||||
}
|
||||
|
||||
if moduleErrors != nil || routeErrors != nil {
|
||||
return nil, fmt.Errorf("errors initializing modules or routes")
|
||||
}
|
||||
|
||||
return router, nil
|
||||
}
|
||||
|
||||
func newTracerProvider(exp sdktrace.SpanExporter) *sdktrace.TracerProvider {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
api:
|
||||
port: 8080
|
||||
modules:
|
||||
- id: http
|
||||
type: http.server
|
||||
@@ -13,6 +15,8 @@ routes:
|
||||
processors:
|
||||
- type: osc.message.create
|
||||
params:
|
||||
address: "{{.URL.Path}}"
|
||||
address: "{{.Payload.URL.Path}}"
|
||||
- type: osc.message.encode
|
||||
output: udp
|
||||
- type: router.output
|
||||
params:
|
||||
module: udp
|
||||
|
||||
64
events.go
Normal file
64
events.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type Event struct {
|
||||
Type string `json:"type"`
|
||||
Data any `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (e Event) toJSON() ([]byte, error) {
|
||||
return json.Marshal(e)
|
||||
}
|
||||
|
||||
func (r *Router) handleEvent(event Event, sender *websocket.Conn) {
|
||||
switch event.Type {
|
||||
case "ping":
|
||||
r.unicastEvent(Event{Type: "pong"}, sender)
|
||||
default:
|
||||
r.logger.Warn("unknown event type", "eventType", event.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) unicastEvent(event Event, conn *websocket.Conn) {
|
||||
eventJSON, err := event.toJSON()
|
||||
if err != nil {
|
||||
r.logger.Error("failed to marshal event to JSON", "error", err)
|
||||
return
|
||||
}
|
||||
err = conn.WriteMessage(websocket.TextMessage, eventJSON)
|
||||
if err != nil {
|
||||
r.logger.Error("failed to write message to websocket connection", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) broadcastEvent(event Event, excluded ...*websocket.Conn) {
|
||||
eventJSON, err := event.toJSON()
|
||||
if err != nil {
|
||||
r.logger.Error("failed to marshal event to JSON", "error", err)
|
||||
return
|
||||
}
|
||||
r.wsConnsMu.Lock()
|
||||
defer r.wsConnsMu.Unlock()
|
||||
for _, conn := range r.wsConns {
|
||||
exclude := false
|
||||
for _, excludedConn := range excluded {
|
||||
if conn == excludedConn {
|
||||
exclude = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if exclude {
|
||||
continue
|
||||
}
|
||||
err := conn.WriteMessage(websocket.TextMessage, eventJSON)
|
||||
if err != nil {
|
||||
r.logger.Error("failed to write message to websocket connection", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
50
go.mod
50
go.mod
@@ -1,32 +1,33 @@
|
||||
module github.com/jwetzell/showbridge-go
|
||||
|
||||
go 1.25.5
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/emiago/diago v0.27.0
|
||||
github.com/emiago/sipgo v1.2.0
|
||||
github.com/emiago/sipgo v1.2.1
|
||||
github.com/expr-lang/expr v1.17.8
|
||||
github.com/extism/go-sdk v1.7.1
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/jwetzell/artnet-go v0.2.1
|
||||
github.com/jwetzell/free-d-go v0.1.0
|
||||
github.com/jwetzell/osc-go v0.1.0
|
||||
github.com/jwetzell/osc-go v0.2.0
|
||||
github.com/jwetzell/psn-go v0.3.0
|
||||
github.com/nats-io/nats-server/v2 v2.12.4
|
||||
github.com/nats-io/nats-server/v2 v2.12.5
|
||||
github.com/nats-io/nats.go v1.49.0
|
||||
github.com/urfave/cli/v3 v3.6.2
|
||||
gitlab.com/gomidi/midi/v2 v2.3.22
|
||||
github.com/urfave/cli/v3 v3.7.0
|
||||
gitlab.com/gomidi/midi/v2 v2.3.23
|
||||
go.bug.st/serial v1.6.4
|
||||
go.opentelemetry.io/otel v1.40.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0
|
||||
go.opentelemetry.io/otel/sdk v1.40.0
|
||||
go.opentelemetry.io/otel/trace v1.40.0
|
||||
go.opentelemetry.io/otel v1.42.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0
|
||||
go.opentelemetry.io/otel/sdk v1.42.0
|
||||
go.opentelemetry.io/otel/trace v1.42.0
|
||||
modernc.org/quickjs v0.17.1
|
||||
sigs.k8s.io/yaml v1.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op // indirect
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/creack/goselect v0.1.2 // indirect
|
||||
@@ -42,15 +43,14 @@ require (
|
||||
github.com/gobwas/ws v1.4.0 // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.7 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca // indirect
|
||||
github.com/icholy/digest v1.1.0 // indirect
|
||||
github.com/klauspost/compress v1.18.3 // indirect
|
||||
github.com/klauspost/compress v1.18.4 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76 // indirect
|
||||
github.com/nats-io/jwt/v2 v2.8.0 // indirect
|
||||
github.com/nats-io/nkeys v0.4.12 // indirect
|
||||
github.com/nats-io/nkeys v0.4.15 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/pion/logging v0.2.4 // indirect
|
||||
@@ -65,20 +65,20 @@ require (
|
||||
github.com/tetratelabs/wazero v1.9.0 // indirect
|
||||
github.com/zaf/g711 v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.40.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.42.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
golang.org/x/crypto v0.47.0 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
|
||||
golang.org/x/net v0.49.0 // indirect
|
||||
golang.org/x/net v0.51.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.40.0 // indirect
|
||||
golang.org/x/text v0.33.0 // indirect
|
||||
golang.org/x/time v0.14.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409 // indirect
|
||||
google.golang.org/grpc v1.78.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 // indirect
|
||||
google.golang.org/grpc v1.79.2 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/hraban/opus.v2 v2.0.0-20230925203106-0188a62cb302 // indirect
|
||||
modernc.org/libc v1.67.1 // indirect
|
||||
|
||||
104
go.sum
104
go.sum
@@ -1,5 +1,5 @@
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op h1:Ucf+QxEKMbPogRO5guBNe5cgd9uZgfoJLOYs8WWhtjM=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op h1:kpBdlEPbRvff0mDD1gk7o9BhI16b9p5yYAXRlidpqJE=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
@@ -18,8 +18,8 @@ github.com/emiago/diago v0.27.0 h1:5SQBbcLR9ooxhSMlTkU9QSuDv/2nhMO9lxuWJTd/7rE=
|
||||
github.com/emiago/diago v0.27.0/go.mod h1:8hUxCDPJY2p32hh+4ed7vHW/3yTMmEa3BjNctUPeGD0=
|
||||
github.com/emiago/dtls/v3 v3.0.0-20260122183559-8b8d23e359c0 h1:o4LxpUnZ1zxiQ+Qjc9kLwXcjz31NGAHmnZ7xoJto3VM=
|
||||
github.com/emiago/dtls/v3 v3.0.0-20260122183559-8b8d23e359c0/go.mod h1:ydcZ977eS1I6uOWodzMuw30BwvNAzT9su/xcNYSJqjA=
|
||||
github.com/emiago/sipgo v1.2.0 h1:rmHFdCu9zu2Cabfd8+/eC9HQWyooqk8x+ti550z5lBw=
|
||||
github.com/emiago/sipgo v1.2.0/go.mod h1:DuwAxBZhKMqIzQFPGZb1MVAGU6Wuxj64oTOhd5dx/FY=
|
||||
github.com/emiago/sipgo v1.2.1 h1:5JTwogbe3yQFA3sjBVueN2Q4WTU350tGeBwPYT8HMv0=
|
||||
github.com/emiago/sipgo v1.2.1/go.mod h1:DuwAxBZhKMqIzQFPGZb1MVAGU6Wuxj64oTOhd5dx/FY=
|
||||
github.com/expr-lang/expr v1.17.8 h1:W1loDTT+0PQf5YteHSTpju2qfUfNoBt4yw9+wOEU9VM=
|
||||
github.com/expr-lang/expr v1.17.8/go.mod h1:8/vRC7+7HBzESEqt5kKpYXxrxkr31SaO8r40VO/1IT4=
|
||||
github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
|
||||
@@ -49,8 +49,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.7 h1:X+2YciYSxvMQK0UZ7sg45ZVabVZBeBuvMkmuI2V3Fak=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.7/go.mod h1:lW34nIZuQ8UDPdkon5fmfp2l3+ZkQ2me/+oecHYLOII=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca h1:T54Ema1DU8ngI+aef9ZhAhNGQhcRTrWxVeG07F+c/Rw=
|
||||
@@ -61,12 +61,12 @@ github.com/jwetzell/artnet-go v0.2.1 h1:iYTKWcwYrF5kBkYfkw2UbWvoueeA23iKEn7fR27m
|
||||
github.com/jwetzell/artnet-go v0.2.1/go.mod h1:gli97Z32a0kMkZ6taoTiK7/lqHcF/dhiGjGJdx/PxqA=
|
||||
github.com/jwetzell/free-d-go v0.1.0 h1:xHt6dvyit98X+OC3jVzV0aLidxbyzi3vI9QiYkteEtA=
|
||||
github.com/jwetzell/free-d-go v0.1.0/go.mod h1:KmrkooRARRaxJTBSPvwt/6IMAIaHH1R8bSA8cwbbELw=
|
||||
github.com/jwetzell/osc-go v0.1.0 h1:EXxup5VWBErHot2Ri4MFToPf6KCzLDTbCt2x6GLfw8I=
|
||||
github.com/jwetzell/osc-go v0.1.0/go.mod h1:xLz0jTwebSxtx1TkKN1YVdeRqvpFNweDhTut5TE393A=
|
||||
github.com/jwetzell/osc-go v0.2.0 h1:4as+BYCeZhEddFczGveP5yZZxvY728Uavz+ZSLZfOII=
|
||||
github.com/jwetzell/osc-go v0.2.0/go.mod h1:D3ZIXYB12bt4S35lKFUqgCFbF1Y+9Ld0sOhHA9mGZZM=
|
||||
github.com/jwetzell/psn-go v0.3.0 h1:WVpCEmExYE8a+I5hQak5jNJJp2x35VdGX/VuMUKPmhY=
|
||||
github.com/jwetzell/psn-go v0.3.0/go.mod h1:bcEAeti4sQM375buujb3mIfmUstD4Aby18gq3ENb6+o=
|
||||
github.com/klauspost/compress v1.18.3 h1:9PJRvfbmTabkOX8moIpXPbMMbYN60bWImDDU7L+/6zw=
|
||||
github.com/klauspost/compress v1.18.3/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=
|
||||
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
@@ -77,12 +77,12 @@ github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76 h1:KGuD/pM2JpL
|
||||
github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
|
||||
github.com/nats-io/jwt/v2 v2.8.0 h1:K7uzyz50+yGZDO5o772eRE7atlcSEENpL7P+b74JV1g=
|
||||
github.com/nats-io/jwt/v2 v2.8.0/go.mod h1:me11pOkwObtcBNR8AiMrUbtVOUGkqYjMQZ6jnSdVUIA=
|
||||
github.com/nats-io/nats-server/v2 v2.12.4 h1:ZnT10v2LU2Xcoiy8ek9X6Se4YG8EuMfIfvAEuFVx1Ts=
|
||||
github.com/nats-io/nats-server/v2 v2.12.4/go.mod h1:5MCp/pqm5SEfsvVZ31ll1088ZTwEUdvRX1Hmh/mTTDg=
|
||||
github.com/nats-io/nats-server/v2 v2.12.5 h1:EOHLbsLJgUHUwzkj9gBTOlubkX+dmSs0EYWMdBiHivU=
|
||||
github.com/nats-io/nats-server/v2 v2.12.5/go.mod h1:JQDAKcwdXs0NRhvYO31dzsXkzCyDkOBS7SKU3Nozu14=
|
||||
github.com/nats-io/nats.go v1.49.0 h1:yh/WvY59gXqYpgl33ZI+XoVPKyut/IcEaqtsiuTJpoE=
|
||||
github.com/nats-io/nats.go v1.49.0/go.mod h1:fDCn3mN5cY8HooHwE2ukiLb4p4G4ImmzvXyJt+tGwdw=
|
||||
github.com/nats-io/nkeys v0.4.12 h1:nssm7JKOG9/x4J8II47VWCL1Ds29avyiQDRn0ckMvDc=
|
||||
github.com/nats-io/nkeys v0.4.12/go.mod h1:MT59A1HYcjIcyQDJStTfaOY6vhy9XTUjOFo+SVsvpBg=
|
||||
github.com/nats-io/nkeys v0.4.15 h1:JACV5jRVO9V856KOapQ7x+EY8Jo3qw1vJt/9Jpwzkk4=
|
||||
github.com/nats-io/nkeys v0.4.15/go.mod h1:CpMchTXC9fxA5zrMo4KpySxNjiDVvr8ANOSZdiNfUrs=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
@@ -113,30 +113,30 @@ github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZ
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk=
|
||||
github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=
|
||||
github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM=
|
||||
github.com/urfave/cli/v3 v3.6.2 h1:lQuqiPrZ1cIz8hz+HcrG0TNZFxU70dPZ3Yl+pSrH9A8=
|
||||
github.com/urfave/cli/v3 v3.6.2/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso=
|
||||
github.com/urfave/cli/v3 v3.7.0 h1:AGSnbUyjtLiM+WJUb4dzXKldl/gL+F8OwmRDtVr6g2U=
|
||||
github.com/urfave/cli/v3 v3.7.0/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso=
|
||||
github.com/zaf/g711 v1.4.0 h1:XZYkjjiAg9QTBnHqEg37m2I9q3IIDv5JRYXs2N8ma7c=
|
||||
github.com/zaf/g711 v1.4.0/go.mod h1:eCDXt3dSp/kYYAoooba7ukD/Q75jvAaS4WOMr0l1Roo=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.22 h1:4Q20o6q4BDo7i/KGvnwASeytOlrPI7MwsS7F2hA7fOM=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.22/go.mod h1:jDpP4O4skYi+7iVwt6Zyp18bd2M4hkjtMuw2cmgKgfw=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.23 h1:P8NxV4EzV9c+BjpwTeB+G/qa+Xdq/UTazS2fKxY0O0g=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.23/go.mod h1:jDpP4O4skYi+7iVwt6Zyp18bd2M4hkjtMuw2cmgKgfw=
|
||||
go.bug.st/serial v1.6.4 h1:7FmqNPgVp3pu2Jz5PoPtbZ9jJO5gnEnZIvnI1lzve8A=
|
||||
go.bug.st/serial v1.6.4/go.mod h1:nofMJxTeNVny/m6+KaafC6vJGj3miwQZ6vW4BZUGJPI=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms=
|
||||
go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0 h1:QKdN8ly8zEMrByybbQgv8cWBcdAarwmIPZ6FThrWXJs=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0/go.mod h1:bTdK1nhqF76qiPoCCdyFIV+N/sRHYXYCTQc+3VCi3MI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0 h1:wVZXIWjQSeSmMoxF74LzAnpVQOAFDo3pPji9Y4SOFKc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0/go.mod h1:khvBS2IggMFNwZK/6lEeHg/W57h/IX6J4URh57fuI40=
|
||||
go.opentelemetry.io/otel/metric v1.40.0 h1:rcZe317KPftE2rstWIBitCdVp89A2HqjkxR3c11+p9g=
|
||||
go.opentelemetry.io/otel/metric v1.40.0/go.mod h1:ib/crwQH7N3r5kfiBZQbwrTge743UDc7DTFVZrrXnqc=
|
||||
go.opentelemetry.io/otel/sdk v1.40.0 h1:KHW/jUzgo6wsPh9At46+h4upjtccTmuZCFAc9OJ71f8=
|
||||
go.opentelemetry.io/otel/sdk v1.40.0/go.mod h1:Ph7EFdYvxq72Y8Li9q8KebuYUr2KoeyHx0DRMKrYBUE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.40.0 h1:mtmdVqgQkeRxHgRv4qhyJduP3fYJRMX4AtAlbuWdCYw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.40.0/go.mod h1:4Z2bGMf0KSK3uRjlczMOeMhKU2rhUqdWNoKcYrtcBPg=
|
||||
go.opentelemetry.io/otel/trace v1.40.0 h1:WA4etStDttCSYuhwvEa8OP8I5EWu24lkOzp+ZYblVjw=
|
||||
go.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqQ5RgdEJcawiA=
|
||||
go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=
|
||||
go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc=
|
||||
go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=
|
||||
go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=
|
||||
go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=
|
||||
go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
@@ -145,34 +145,34 @@ go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
|
||||
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
|
||||
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
|
||||
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
|
||||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
||||
golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c=
|
||||
golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
||||
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
|
||||
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
|
||||
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409 h1:merA0rdPeUV3YIIfHHcH4qBkiQAc1nfCKSI7lB4cV2M=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409/go.mod h1:fl8J1IvUjCilwZzQowmw2b7HQB2eAuYBabMXzWurF+I=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409 h1:H86B94AW+VfJWDqFeEbBPhEtHzJwJfTbgE2lZa54ZAQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
|
||||
google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
|
||||
google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 h1:JLQynH/LBHfCTSbDWl+py8C+Rg/k1OVH3xfcaiANuF0=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:kSJwQxqmFXeo79zOmbrALdflXQeAYcUbgS7PbpMknCY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 h1:mWPCjDEyshlQYzBpMNHaEof6UX1PmHcaUODUywQ0uac=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
|
||||
google.golang.org/grpc v1.79.2 h1:fRMD94s2tITpyJGtBBn7MkMseNpOZU8ZxgC3MMBaXRU=
|
||||
google.golang.org/grpc v1.79.2/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
179
internal/common/common.go
Normal file
179
internal/common/common.go
Normal file
@@ -0,0 +1,179 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"math"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
func GetAnyAs[T any](value any) (T, bool) {
|
||||
typed, ok := value.(T)
|
||||
return typed, ok
|
||||
}
|
||||
|
||||
func GetAnyAsInt(value any) (int, bool) {
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return intValue, true
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return int(uintValue), true
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return int(byteValue), true
|
||||
}
|
||||
|
||||
floatValue, ok := value.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return 0, false
|
||||
}
|
||||
return int(floatValue), true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func GetAnyAsByteSlice(value any) ([]byte, bool) {
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
result := make([]byte, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
byteValue, ok := elem.(byte)
|
||||
if ok {
|
||||
result[i] = byteValue
|
||||
continue
|
||||
}
|
||||
uintValue, ok := elem.(uint)
|
||||
if ok {
|
||||
if uintValue > 255 {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = byte(uintValue)
|
||||
continue
|
||||
}
|
||||
intValue, ok := elem.(int)
|
||||
if ok {
|
||||
if intValue < 0 || intValue > 255 {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = byte(intValue)
|
||||
continue
|
||||
}
|
||||
floatValue, ok := elem.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return nil, false
|
||||
}
|
||||
if floatValue < 0 || floatValue > 255 {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = byte(floatValue)
|
||||
continue
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
|
||||
func GetAnyAsIntSlice(value any) ([]int, bool) {
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
result := make([]int, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
byteValue, ok := elem.(byte)
|
||||
if ok {
|
||||
result[i] = int(byteValue)
|
||||
continue
|
||||
}
|
||||
uintValue, ok := elem.(uint)
|
||||
if ok {
|
||||
result[i] = int(uintValue)
|
||||
continue
|
||||
}
|
||||
intValue, ok := elem.(int)
|
||||
if ok {
|
||||
result[i] = int(intValue)
|
||||
continue
|
||||
}
|
||||
floatValue, ok := elem.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = int(floatValue)
|
||||
continue
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
|
||||
func GetAnyAsFloat32(value any) (float32, bool) {
|
||||
float32Value, ok := value.(float32)
|
||||
if ok {
|
||||
return float32Value, true
|
||||
}
|
||||
|
||||
float64Value, ok := value.(float64)
|
||||
if ok {
|
||||
return float32(float64Value), true
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return float32(intValue), true
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return float32(uintValue), true
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return float32(byteValue), true
|
||||
}
|
||||
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func GetAnyAsFloat64(value any) (float64, bool) {
|
||||
float64Value, ok := value.(float64)
|
||||
if ok {
|
||||
return float64Value, true
|
||||
}
|
||||
|
||||
float32Value, ok := value.(float32)
|
||||
if ok {
|
||||
return float64(float32Value), true
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return float64(intValue), true
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return float64(uintValue), true
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return float64(byteValue), true
|
||||
}
|
||||
|
||||
return 0, false
|
||||
}
|
||||
8
internal/common/context.go
Normal file
8
internal/common/context.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package common
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RouterContextKey contextKey = contextKey("router")
|
||||
const SourceContextKey contextKey = contextKey("source")
|
||||
const ModulesContextKey contextKey = contextKey("modules")
|
||||
const SenderContextKey contextKey = contextKey("sender")
|
||||
15
internal/common/routing.go
Normal file
15
internal/common/routing.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package common
|
||||
|
||||
import "context"
|
||||
|
||||
type RouteIO interface {
|
||||
HandleInput(ctx context.Context, sourceId string, payload any) (bool, []RouteIOError)
|
||||
HandleOutput(ctx context.Context, destinationId string, payload any) error
|
||||
}
|
||||
|
||||
type RouteIOError struct {
|
||||
Index int `json:"index"`
|
||||
OutputError error `json:"outputError"`
|
||||
ProcessError error `json:"processError"`
|
||||
InputError error `json:"inputError"`
|
||||
}
|
||||
@@ -1,78 +1,26 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Api ApiConfig `json:"api"`
|
||||
Modules []ModuleConfig `json:"modules"`
|
||||
Routes []RouteConfig `json:"routes"`
|
||||
}
|
||||
|
||||
type Params map[string]any
|
||||
|
||||
var (
|
||||
ErrParamNotFound = errors.New("not found")
|
||||
ErrParamNotString = errors.New("not a string")
|
||||
ErrParamNotNumber = errors.New("not a number")
|
||||
)
|
||||
|
||||
func (p Params) GetString(key string) (string, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return "", ErrParamNotFound
|
||||
}
|
||||
|
||||
stringValue, ok := value.(string)
|
||||
if !ok {
|
||||
return "", ErrParamNotString
|
||||
}
|
||||
return stringValue, nil
|
||||
type ApiConfig struct {
|
||||
Port int `json:"port"`
|
||||
}
|
||||
|
||||
func (p Params) GetInt(key string) (int, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if !ok {
|
||||
floatValue, ok := value.(float64)
|
||||
if !ok {
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
intValue = int(floatValue)
|
||||
}
|
||||
return intValue, nil
|
||||
}
|
||||
|
||||
func (p Params) GetBool(key string) (bool, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return false, ErrParamNotFound
|
||||
}
|
||||
|
||||
boolValue, ok := value.(bool)
|
||||
if !ok {
|
||||
return false, errors.New("not a boolean")
|
||||
}
|
||||
return boolValue, nil
|
||||
}
|
||||
|
||||
type ModuleConfig struct {
|
||||
Id string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params"`
|
||||
Params Params `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
type RouteConfig struct {
|
||||
Input string `json:"input"`
|
||||
Processors []ProcessorConfig `json:"processors"`
|
||||
Output string `json:"output"`
|
||||
}
|
||||
|
||||
type ProcessorConfig struct {
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params"`
|
||||
Params Params `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
297
internal/config/config_test.go
Normal file
297
internal/config/config_test.go
Normal file
@@ -0,0 +1,297 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func TestGoodStringParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "string param",
|
||||
paramsJSON: `{"key": "value"}`,
|
||||
key: "key",
|
||||
expected: "value",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetString(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetString returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetString got %s, expected %s", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodIntParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected int
|
||||
}{
|
||||
{
|
||||
name: "int param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetInt(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetInt returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetInt got %d, expected %d", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodFloat32ParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected float32
|
||||
}{
|
||||
{
|
||||
name: "no decimal param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "float param",
|
||||
paramsJSON: `{"key": 1.23}`,
|
||||
key: "key",
|
||||
expected: 1.23,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetFloat32(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFloat32 returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetFloat32 got %f, expected %f", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodFloat64ParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected float64
|
||||
}{
|
||||
{
|
||||
name: "no decimal param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "float param",
|
||||
paramsJSON: `{"key": 1.23}`,
|
||||
key: "key",
|
||||
expected: 1.23,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetFloat64(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFloat64 returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetFloat64 got %f, expected %f", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodBoolParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "bool param",
|
||||
paramsJSON: `{"key": true}`,
|
||||
key: "key",
|
||||
expected: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetBool(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBool returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetBool got %t, expected %t", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodStringSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "string array",
|
||||
paramsJSON: `{"key": ["value1", "value2"]}`,
|
||||
key: "key",
|
||||
expected: []string{"value1", "value2"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetStringSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetStringSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetStringSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodIntSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []int
|
||||
}{
|
||||
{
|
||||
name: "int array",
|
||||
paramsJSON: `{"key": [1, 2, 3]}`,
|
||||
key: "key",
|
||||
expected: []int{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "int array with floats",
|
||||
paramsJSON: `{"key": [1.0, 2.0, 3.0]}`,
|
||||
key: "key",
|
||||
expected: []int{1, 2, 3},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetIntSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIntSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetIntSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodByteSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []byte
|
||||
}{
|
||||
{
|
||||
name: "byte array",
|
||||
paramsJSON: `{"key": [1,2,3,4]}`,
|
||||
key: "key",
|
||||
expected: []byte{1, 2, 3, 4},
|
||||
},
|
||||
{
|
||||
name: "byte array with floats",
|
||||
paramsJSON: `{"key": [1.0,2.0,3.0,4.0]}`,
|
||||
key: "key",
|
||||
expected: []byte{1, 2, 3, 4},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetByteSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByteSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetByteSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
140
internal/config/params.go
Normal file
140
internal/config/params.go
Normal file
@@ -0,0 +1,140 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
)
|
||||
|
||||
type Params map[string]any
|
||||
|
||||
var (
|
||||
ErrParamNotFound = errors.New("not found")
|
||||
ErrParamNotString = errors.New("not a string")
|
||||
ErrParamNotNumber = errors.New("not a number")
|
||||
ErrParamNotInteger = errors.New("not an integer")
|
||||
ErrParamNotBool = errors.New("not a boolean")
|
||||
ErrParamNotSlice = errors.New("not a slice")
|
||||
ErrParamNotByteSlice = errors.New("not a byte slice")
|
||||
ErrParamNotIntSlice = errors.New("not an int slice")
|
||||
)
|
||||
|
||||
func (p Params) GetString(key string) (string, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return "", ErrParamNotFound
|
||||
}
|
||||
|
||||
stringValue, ok := value.(string)
|
||||
if !ok {
|
||||
return "", ErrParamNotString
|
||||
}
|
||||
return stringValue, nil
|
||||
}
|
||||
|
||||
func (p Params) GetInt(key string) (int, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
intValue, ok := common.GetAnyAsInt(value)
|
||||
if ok {
|
||||
return intValue, nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetFloat32(key string) (float32, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
floatValue, ok := common.GetAnyAsFloat32(value)
|
||||
if ok {
|
||||
return floatValue, nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetFloat64(key string) (float64, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
floatValue, ok := common.GetAnyAsFloat64(value)
|
||||
if ok {
|
||||
return floatValue, nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetBool(key string) (bool, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return false, ErrParamNotFound
|
||||
}
|
||||
|
||||
boolValue, ok := value.(bool)
|
||||
if !ok {
|
||||
return false, ErrParamNotBool
|
||||
}
|
||||
return boolValue, nil
|
||||
}
|
||||
|
||||
func (p Params) GetStringSlice(key string) ([]string, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
interfaceSlice, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil, ErrParamNotSlice
|
||||
}
|
||||
|
||||
stringSlice := make([]string, len(interfaceSlice))
|
||||
for i, v := range interfaceSlice {
|
||||
str, ok := v.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("element at index %d is not a string", i)
|
||||
}
|
||||
stringSlice[i] = str
|
||||
}
|
||||
return stringSlice, nil
|
||||
}
|
||||
|
||||
func (p Params) GetIntSlice(key string) ([]int, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
intSlice, ok := common.GetAnyAsIntSlice(value)
|
||||
if !ok {
|
||||
return nil, ErrParamNotIntSlice
|
||||
}
|
||||
|
||||
return intSlice, nil
|
||||
}
|
||||
|
||||
func (p Params) GetByteSlice(key string) ([]byte, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
byteSlice, ok := common.GetAnyAsByteSlice(value)
|
||||
|
||||
if !ok {
|
||||
return nil, ErrParamNotByteSlice
|
||||
}
|
||||
|
||||
return byteSlice, nil
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type HTTPClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
client *http.Client
|
||||
router route.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "http.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
|
||||
return &HTTPClient{config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Id() string {
|
||||
return hc.config.Id
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Type() string {
|
||||
return hc.config.Type
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Start(ctx context.Context) error {
|
||||
hc.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.client unable to get router from context")
|
||||
}
|
||||
hc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
hc.ctx = moduleContext
|
||||
hc.cancel = cancel
|
||||
|
||||
hc.client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
<-hc.ctx.Done()
|
||||
hc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadRequest, ok := payload.(*http.Request)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.client is only able to output an http.Request")
|
||||
}
|
||||
|
||||
if hc.client == nil {
|
||||
return errors.New("http.client client is nil")
|
||||
}
|
||||
|
||||
response, err := hc.client.Do(payloadRequest)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if hc.router != nil {
|
||||
hc.router.HandleInput(hc.ctx, hc.Id(), response)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Stop() {
|
||||
hc.cancel()
|
||||
}
|
||||
@@ -6,18 +6,19 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type HTTPServer struct {
|
||||
config config.ModuleConfig
|
||||
Port uint16
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
@@ -83,6 +84,10 @@ func (hs *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if hs.router != nil {
|
||||
inputContext := context.WithValue(hs.ctx, httpServerContextKey("responseWriter"), &responseWriter)
|
||||
senderAddr, err := net.ResolveTCPAddr("tcp", r.RemoteAddr)
|
||||
if err == nil {
|
||||
inputContext = context.WithValue(inputContext, common.SenderContextKey, senderAddr)
|
||||
}
|
||||
aRouteFound, routingErrors := hs.router.HandleInput(inputContext, hs.Id(), r)
|
||||
if !responseWriter.done {
|
||||
if aRouteFound {
|
||||
@@ -142,7 +147,7 @@ func (hs *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (hs *HTTPServer) Start(ctx context.Context) error {
|
||||
hs.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.server unable to get router from context")
|
||||
@@ -182,7 +187,7 @@ func (hs *HTTPServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("http.server output must originate from an http.server input")
|
||||
}
|
||||
|
||||
payloadResponse, ok := payload.(processor.HTTPResponse)
|
||||
payloadResponse, ok := common.GetAnyAs[processor.HTTPResponse](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.server is only able to output HTTPResponse")
|
||||
@@ -200,3 +205,7 @@ func (hs *HTTPServer) Output(ctx context.Context, payload any) error {
|
||||
func (hs *HTTPServer) Stop() {
|
||||
hs.cancel()
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("http.server does not support Get")
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
_ "gitlab.com/gomidi/midi/v2/drivers/rtmididrv"
|
||||
)
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
type MIDIInput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
Port string
|
||||
SendFunc func(midi.Message) error
|
||||
logger *slog.Logger
|
||||
@@ -50,7 +50,7 @@ func (mi *MIDIInput) Type() string {
|
||||
func (mi *MIDIInput) Start(ctx context.Context) error {
|
||||
mi.logger.Debug("running")
|
||||
defer midi.CloseDriver()
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.input unable to get router from context")
|
||||
@@ -89,3 +89,12 @@ func (mi *MIDIInput) Output(ctx context.Context, payload any) error {
|
||||
func (mi *MIDIInput) Stop() {
|
||||
mi.cancel()
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "port":
|
||||
return mi.Port, nil
|
||||
default:
|
||||
return nil, errors.New("midi.input key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
_ "gitlab.com/gomidi/midi/v2/drivers/rtmididrv"
|
||||
)
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
type MIDIOutput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
Port string
|
||||
SendFunc func(midi.Message) error
|
||||
logger *slog.Logger
|
||||
@@ -51,7 +51,7 @@ func (mo *MIDIOutput) Type() string {
|
||||
func (mo *MIDIOutput) Start(ctx context.Context) error {
|
||||
mo.logger.Debug("running")
|
||||
defer midi.CloseDriver()
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.output unable to get router from context")
|
||||
@@ -84,7 +84,7 @@ func (mo *MIDIOutput) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("midi.output output is not setup")
|
||||
}
|
||||
|
||||
payloadMessage, ok := payload.(midi.Message)
|
||||
payloadMessage, ok := common.GetAnyAs[midi.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.output can only ouptut midi.Message")
|
||||
@@ -96,3 +96,12 @@ func (mo *MIDIOutput) Output(ctx context.Context, payload any) error {
|
||||
func (mo *MIDIOutput) Stop() {
|
||||
mo.cancel()
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "port":
|
||||
return mo.Port, nil
|
||||
default:
|
||||
return nil, errors.New("midi.output key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
)
|
||||
|
||||
type ModuleError struct {
|
||||
Index int
|
||||
Config config.ModuleConfig
|
||||
Error error
|
||||
Index int `json:"index"`
|
||||
Config config.ModuleConfig `json:"config"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type Module interface {
|
||||
@@ -21,6 +21,7 @@ type Module interface {
|
||||
Start(context.Context) error
|
||||
Stop()
|
||||
Output(context.Context, any) error
|
||||
Get(key string) (any, error)
|
||||
}
|
||||
|
||||
type ModuleRegistration struct {
|
||||
|
||||
@@ -7,14 +7,14 @@ import (
|
||||
"log/slog"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type MQTTClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
Broker string
|
||||
ClientID string
|
||||
Topic string
|
||||
@@ -61,7 +61,7 @@ func (mc *MQTTClient) Type() string {
|
||||
|
||||
func (mc *MQTTClient) Start(ctx context.Context) error {
|
||||
mc.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("mqtt.client unable to get router from context")
|
||||
@@ -101,7 +101,7 @@ func (mc *MQTTClient) Start(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Output(ctx context.Context, payload any) error {
|
||||
payloadMessage, ok := payload.(mqtt.Message)
|
||||
payloadMessage, ok := common.GetAnyAs[mqtt.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("mqtt.client is only able to output a MQTTMessage")
|
||||
@@ -125,3 +125,7 @@ func (mc *MQTTClient) Output(ctx context.Context, payload any) error {
|
||||
func (mc *MQTTClient) Stop() {
|
||||
mc.cancel()
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Get(key string) (any, error) {
|
||||
return nil, errors.New("mqtt.client does not support Get")
|
||||
}
|
||||
|
||||
@@ -5,16 +5,16 @@ import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
type NATSClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
URL string
|
||||
Subject string
|
||||
client *nats.Conn
|
||||
@@ -53,7 +53,7 @@ func (nc *NATSClient) Type() string {
|
||||
|
||||
func (nc *NATSClient) Start(ctx context.Context) error {
|
||||
nc.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("nats.client unable to get router from context")
|
||||
@@ -94,7 +94,7 @@ func (nc *NATSClient) Start(ctx context.Context) error {
|
||||
|
||||
func (nc *NATSClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadMessage, ok := payload.(processor.NATSMessage)
|
||||
payloadMessage, ok := common.GetAnyAs[processor.NATSMessage](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("nats.client is only able to output NATSMessage")
|
||||
@@ -116,3 +116,7 @@ func (nc *NATSClient) Output(ctx context.Context, payload any) error {
|
||||
func (nc *NATSClient) Stop() {
|
||||
nc.cancel()
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Get(key string) (any, error) {
|
||||
return nil, errors.New("nats.client does not support Get")
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
)
|
||||
|
||||
@@ -18,7 +18,7 @@ type NATSServer struct {
|
||||
ctx context.Context
|
||||
Ip string
|
||||
Port int
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
server *server.Server
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
@@ -66,7 +66,7 @@ func (ns *NATSServer) Type() string {
|
||||
|
||||
func (ns *NATSServer) Start(ctx context.Context) error {
|
||||
ns.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("nats.server unable to get router from context")
|
||||
@@ -103,7 +103,7 @@ func (ns *NATSServer) Start(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.ErrUnsupported
|
||||
return errors.New("nats.server does not support output")
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Stop() {
|
||||
@@ -112,3 +112,7 @@ func (ns *NATSServer) Stop() {
|
||||
ns.server.Shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("nats.server does not support Get")
|
||||
}
|
||||
|
||||
@@ -9,15 +9,15 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/psn-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type PSNClient struct {
|
||||
config config.ModuleConfig
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
decoder *psn.Decoder
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
@@ -43,7 +43,7 @@ func (pc *PSNClient) Type() string {
|
||||
|
||||
func (pc *PSNClient) Start(ctx context.Context) error {
|
||||
pc.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("psn.client unable to get router from context")
|
||||
@@ -112,3 +112,14 @@ func (pc *PSNClient) Output(ctx context.Context, payload any) error {
|
||||
func (pc *PSNClient) Stop() {
|
||||
pc.cancel()
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "trackers":
|
||||
return pc.decoder.Trackers, nil
|
||||
case "name":
|
||||
return pc.decoder.SystemName, nil
|
||||
default:
|
||||
return nil, errors.New("psn.client key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,16 +9,16 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"go.bug.st/serial"
|
||||
)
|
||||
|
||||
type SerialClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
Port string
|
||||
Framer framer.Framer
|
||||
Mode *serial.Mode
|
||||
@@ -84,7 +84,7 @@ func (sc *SerialClient) SetupPort() error {
|
||||
|
||||
func (sc *SerialClient) Start(ctx context.Context) error {
|
||||
sc.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("serial.client unable to get router from context")
|
||||
@@ -156,7 +156,7 @@ func (sc *SerialClient) Start(ctx context.Context) error {
|
||||
|
||||
func (sc *SerialClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("serial.client can only ouptut bytes")
|
||||
@@ -169,3 +169,12 @@ func (sc *SerialClient) Output(ctx context.Context, payload any) error {
|
||||
func (sc *SerialClient) Stop() {
|
||||
sc.cancel()
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "port":
|
||||
return sc.Port, nil
|
||||
default:
|
||||
return nil, errors.New("serial.client key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,15 +14,15 @@ import (
|
||||
"github.com/emiago/diago/media"
|
||||
"github.com/emiago/sipgo"
|
||||
"github.com/emiago/sipgo/sip"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type SIPCallServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
IP string
|
||||
Port int
|
||||
Transport string
|
||||
@@ -100,7 +100,7 @@ func (scs *SIPCallServer) Type() string {
|
||||
|
||||
func (scs *SIPCallServer) Start(ctx context.Context) error {
|
||||
scs.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("sip.call.server unable to get router from context")
|
||||
@@ -173,7 +173,7 @@ func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("sip.call.server inDialog already ended")
|
||||
}
|
||||
|
||||
payloadDTMFResponse, ok := payload.(processor.SipDTMFResponse)
|
||||
payloadDTMFResponse, ok := common.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
|
||||
if ok {
|
||||
dtmfWriter := call.inDialog.AudioWriterDTMF()
|
||||
@@ -189,7 +189,7 @@ func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
payloadAudioFileResponse, ok := payload.(processor.SipAudioFileResponse)
|
||||
payloadAudioFileResponse, ok := common.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
|
||||
if ok {
|
||||
audioFile, err := os.Open(payloadAudioFileResponse.AudioFile)
|
||||
@@ -221,3 +221,7 @@ func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
func (scs *SIPCallServer) Stop() {
|
||||
scs.cancel()
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("sip.call.server does not support Get")
|
||||
}
|
||||
|
||||
@@ -15,15 +15,15 @@ import (
|
||||
"github.com/emiago/diago/media"
|
||||
"github.com/emiago/sipgo"
|
||||
"github.com/emiago/sipgo/sip"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type SIPDTMFServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
IP string
|
||||
Port int
|
||||
Transport string
|
||||
@@ -113,7 +113,7 @@ func (sds *SIPDTMFServer) Type() string {
|
||||
|
||||
func (sds *SIPDTMFServer) Start(ctx context.Context) error {
|
||||
sds.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("sip.dtmf.server unable to get router from context")
|
||||
@@ -199,7 +199,7 @@ func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("sip.dtmf.server inDialog already ended")
|
||||
}
|
||||
|
||||
payloadDTMFResponse, ok := payload.(processor.SipDTMFResponse)
|
||||
payloadDTMFResponse, ok := common.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
|
||||
if ok {
|
||||
dtmfWriter := call.inDialog.AudioWriterDTMF()
|
||||
@@ -216,7 +216,7 @@ func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
payloadAudioFileResponse, ok := payload.(processor.SipAudioFileResponse)
|
||||
payloadAudioFileResponse, ok := common.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
|
||||
if ok {
|
||||
audioFile, err := os.Open(payloadAudioFileResponse.AudioFile)
|
||||
@@ -249,3 +249,7 @@ func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||
func (sds *SIPDTMFServer) Stop() {
|
||||
sds.cancel()
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("sip.dtmf.server does not support Get")
|
||||
}
|
||||
|
||||
@@ -8,9 +8,9 @@ import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type TCPClient struct {
|
||||
@@ -18,7 +18,7 @@ type TCPClient struct {
|
||||
framer framer.Framer
|
||||
conn *net.TCPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
Addr *net.TCPAddr
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
@@ -69,7 +69,7 @@ func (tc *TCPClient) Type() string {
|
||||
|
||||
func (tc *TCPClient) Start(ctx context.Context) error {
|
||||
tc.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client unable to get router from context")
|
||||
@@ -152,7 +152,7 @@ func (tc *TCPClient) Output(ctx context.Context, payload any) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client is only able to output bytes")
|
||||
}
|
||||
@@ -163,3 +163,20 @@ func (tc *TCPClient) Output(ctx context.Context, payload any) error {
|
||||
func (tc *TCPClient) Stop() {
|
||||
tc.cancel()
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "host":
|
||||
host, err := tc.config.Params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.client host error: %w", err)
|
||||
}
|
||||
return host, nil
|
||||
case "ip":
|
||||
return tc.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return tc.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.tcp.client key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,9 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type TCPServer struct {
|
||||
@@ -21,7 +21,7 @@ type TCPServer struct {
|
||||
Addr *net.TCPAddr
|
||||
Framer framer.Framer
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
quit chan interface{}
|
||||
wg sync.WaitGroup
|
||||
connections []*net.TCPConn
|
||||
@@ -140,7 +140,13 @@ ClientRead:
|
||||
messages := ts.Framer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if ts.router != nil {
|
||||
ts.router.HandleInput(ts.ctx, ts.Id(), message)
|
||||
senderAddr, ok := client.RemoteAddr().(*net.TCPAddr)
|
||||
if ok {
|
||||
senderCtx := context.WithValue(ts.ctx, common.SenderContextKey, senderAddr)
|
||||
ts.router.HandleInput(senderCtx, ts.Id(), message)
|
||||
} else {
|
||||
ts.router.HandleInput(ts.ctx, ts.Id(), message)
|
||||
}
|
||||
} else {
|
||||
ts.logger.Error("input received but no router is configured")
|
||||
}
|
||||
@@ -153,7 +159,7 @@ ClientRead:
|
||||
|
||||
func (ts *TCPServer) Start(ctx context.Context) error {
|
||||
ts.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.server unable to get router from context")
|
||||
@@ -200,7 +206,7 @@ AcceptLoop:
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Output(ctx context.Context, payload any) error {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.server is only able to output bytes")
|
||||
@@ -226,3 +232,14 @@ func (ts *TCPServer) Stop() {
|
||||
ts.cancel()
|
||||
ts.wg.Wait()
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "ip":
|
||||
return ts.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return ts.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.tcp.server key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestHTTPClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["http.client"]
|
||||
if !ok {
|
||||
t.Fatalf("http.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "http.client",
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create http.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("http.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "http.client" {
|
||||
t.Fatalf("http.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadHTTPClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["http.client"]
|
||||
if !ok {
|
||||
t.Fatalf("http.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "http.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("http.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("http.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("http.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ func TestHTTPServerFromRegistry(t *testing.T) {
|
||||
Id: "test",
|
||||
Type: "http.server",
|
||||
Params: map[string]any{
|
||||
"port": 3000.0,
|
||||
"port": 3000,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -30,6 +30,10 @@ func (m *TestModule) Id() string {
|
||||
return "test"
|
||||
}
|
||||
|
||||
func (m *TestModule) Get(key string) (any, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestModuleBadRegistrationNoType(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestSerialClientFromRegistry(t *testing.T) {
|
||||
Params: map[string]any{
|
||||
"port": "/dev/ttyUSB0",
|
||||
"framing": "LF",
|
||||
"baudRate": 9600.0,
|
||||
"baudRate": 9600,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ func TestTCPClientFromRegistry(t *testing.T) {
|
||||
Type: "net.tcp.client",
|
||||
Params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
})
|
||||
@@ -60,7 +60,7 @@ func TestBadTCPClient(t *testing.T) {
|
||||
{
|
||||
name: "no host param",
|
||||
params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.tcp.client host error: not found",
|
||||
},
|
||||
@@ -68,7 +68,7 @@ func TestBadTCPClient(t *testing.T) {
|
||||
name: "non-string host param",
|
||||
params: map[string]any{
|
||||
"host": 123,
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.tcp.client host error: not a string",
|
||||
},
|
||||
|
||||
@@ -17,7 +17,7 @@ func TestTCPServerFromRegistry(t *testing.T) {
|
||||
Id: "test",
|
||||
Type: "net.tcp.server",
|
||||
Params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
})
|
||||
@@ -59,14 +59,14 @@ func TestBadTCPServer(t *testing.T) {
|
||||
{
|
||||
name: "no framing param",
|
||||
params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.tcp.server framing error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string framing param",
|
||||
params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
"framing": 1,
|
||||
},
|
||||
errorString: "net.tcp.server framing error: not a string",
|
||||
@@ -74,7 +74,7 @@ func TestBadTCPServer(t *testing.T) {
|
||||
{
|
||||
name: "unkown framing method",
|
||||
params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
"framing": "asdfasdfasdfasdflkj",
|
||||
},
|
||||
errorString: "net.tcp.server unknown framing method: asdfasdfasdfasdflkj",
|
||||
@@ -82,7 +82,7 @@ func TestBadTCPServer(t *testing.T) {
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
"ip": 123,
|
||||
},
|
||||
@@ -92,7 +92,7 @@ func TestBadTCPServer(t *testing.T) {
|
||||
name: "invalid addr",
|
||||
params: map[string]any{
|
||||
"ip": "127.0.0.",
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "lookup 127.0.0.: no such host",
|
||||
|
||||
@@ -17,7 +17,7 @@ func TestTimeIntervalFromRegistry(t *testing.T) {
|
||||
Id: "test",
|
||||
Type: "time.interval",
|
||||
Params: map[string]any{
|
||||
"duration": 1000.0,
|
||||
"duration": 1000,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ func TestTimeTimerFromRegistry(t *testing.T) {
|
||||
Id: "test",
|
||||
Type: "time.timer",
|
||||
Params: map[string]any{
|
||||
"duration": 1000.0,
|
||||
"duration": 1000,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ func TestUDPClientFromRegistry(t *testing.T) {
|
||||
Type: "net.udp.client",
|
||||
Params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
})
|
||||
@@ -60,7 +60,7 @@ func TestBadUDPClient(t *testing.T) {
|
||||
{
|
||||
name: "no host param",
|
||||
params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.client host error: not found",
|
||||
},
|
||||
@@ -68,7 +68,7 @@ func TestBadUDPClient(t *testing.T) {
|
||||
name: "non-string host param",
|
||||
params: map[string]any{
|
||||
"host": 123,
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.client host error: not a string",
|
||||
},
|
||||
|
||||
@@ -18,7 +18,7 @@ func TestUDPMulticastFromRegistry(t *testing.T) {
|
||||
Type: "net.udp.multicast",
|
||||
Params: map[string]any{
|
||||
"ip": "236.10.10.10",
|
||||
"port": 56565.0,
|
||||
"port": 56565,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -59,7 +59,7 @@ func TestBadUDPMulticast(t *testing.T) {
|
||||
{
|
||||
name: "no ip param",
|
||||
params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.multicast ip error: not found",
|
||||
},
|
||||
@@ -67,7 +67,7 @@ func TestBadUDPMulticast(t *testing.T) {
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"ip": 123,
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.multicast ip error: not a string",
|
||||
},
|
||||
@@ -75,7 +75,7 @@ func TestBadUDPMulticast(t *testing.T) {
|
||||
name: "invalid addr",
|
||||
params: map[string]any{
|
||||
"ip": "127.0.0.",
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "lookup 127.0.0.: no such host",
|
||||
},
|
||||
|
||||
@@ -17,7 +17,7 @@ func TestUDPServerFromRegistry(t *testing.T) {
|
||||
Id: "test",
|
||||
Type: "net.udp.server",
|
||||
Params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -55,7 +55,7 @@ func TestBadUDPServer(t *testing.T) {
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "net.udp.server ip error: not a string",
|
||||
@@ -63,7 +63,7 @@ func TestBadUDPServer(t *testing.T) {
|
||||
{
|
||||
name: "non-number bufferSize param",
|
||||
params: map[string]any{
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
"bufferSize": "1024",
|
||||
},
|
||||
errorString: "net.udp.server bufferSize error: not a number",
|
||||
@@ -72,7 +72,7 @@ func TestBadUDPServer(t *testing.T) {
|
||||
name: "invalid addr",
|
||||
params: map[string]any{
|
||||
"ip": "127.0.0.",
|
||||
"port": 8000.0,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "lookup 127.0.0.: no such host",
|
||||
},
|
||||
|
||||
@@ -7,15 +7,15 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type TimeInterval struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
ticker *time.Ticker
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
@@ -46,7 +46,7 @@ func (i *TimeInterval) Type() string {
|
||||
|
||||
func (i *TimeInterval) Start(ctx context.Context) error {
|
||||
i.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("time.interval unable to get router from context")
|
||||
@@ -82,3 +82,12 @@ func (i *TimeInterval) Output(ctx context.Context, payload any) error {
|
||||
func (i *TimeInterval) Stop() {
|
||||
i.cancel()
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "duration":
|
||||
return i.Duration, nil
|
||||
default:
|
||||
return nil, errors.New("time.interval key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,15 +7,15 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type TimeTimer struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
timer *time.Timer
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
@@ -47,7 +47,7 @@ func (t *TimeTimer) Type() string {
|
||||
|
||||
func (t *TimeTimer) Start(ctx context.Context) error {
|
||||
t.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client unable to get router from context")
|
||||
@@ -81,3 +81,12 @@ func (t *TimeTimer) Output(ctx context.Context, payload any) error {
|
||||
func (t *TimeTimer) Stop() {
|
||||
t.cancel()
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "duration":
|
||||
return t.Duration, nil
|
||||
default:
|
||||
return nil, errors.New("time.timer key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"log/slog"
|
||||
"net"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type UDPClient struct {
|
||||
@@ -17,7 +17,7 @@ type UDPClient struct {
|
||||
Port uint16
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
@@ -62,7 +62,7 @@ func (uc *UDPClient) SetupConn() error {
|
||||
|
||||
func (uc *UDPClient) Start(ctx context.Context) error {
|
||||
uc.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.udp.client unable to get router from context")
|
||||
@@ -87,7 +87,7 @@ func (uc *UDPClient) Start(ctx context.Context) error {
|
||||
|
||||
func (uc *UDPClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.udp.client is only able to output bytes")
|
||||
}
|
||||
@@ -106,3 +106,20 @@ func (uc *UDPClient) Output(ctx context.Context, payload any) error {
|
||||
func (uc *UDPClient) Stop() {
|
||||
uc.cancel()
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "host":
|
||||
host, err := uc.config.Params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.client host error: %w", err)
|
||||
}
|
||||
return host, nil
|
||||
case "ip":
|
||||
return uc.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return uc.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.udp.client key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,15 +8,15 @@ import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type UDPMulticast struct {
|
||||
config config.ModuleConfig
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
Addr *net.UDPAddr
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
@@ -56,7 +56,7 @@ func (um *UDPMulticast) Type() string {
|
||||
|
||||
func (um *UDPMulticast) Start(ctx context.Context) error {
|
||||
um.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.udp.multicast unable to get router from context")
|
||||
@@ -108,7 +108,7 @@ func (um *UDPMulticast) Start(ctx context.Context) error {
|
||||
|
||||
func (um *UDPMulticast) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.udp.multicast can only output bytes")
|
||||
}
|
||||
@@ -124,3 +124,14 @@ func (um *UDPMulticast) Output(ctx context.Context, payload any) error {
|
||||
func (um *UDPMulticast) Stop() {
|
||||
um.cancel()
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "ip":
|
||||
return um.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return um.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.udp.multicast key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type UDPServer struct {
|
||||
@@ -17,7 +17,7 @@ type UDPServer struct {
|
||||
BufferSize int
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
@@ -69,7 +69,7 @@ func (us *UDPServer) Type() string {
|
||||
|
||||
func (us *UDPServer) Start(ctx context.Context) error {
|
||||
us.logger.Debug("running")
|
||||
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.udp.server unable to get router from context")
|
||||
@@ -96,7 +96,7 @@ func (us *UDPServer) Start(ctx context.Context) error {
|
||||
default:
|
||||
listener.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
|
||||
numBytes, _, err := listener.ReadFromUDP(buffer)
|
||||
numBytes, senderAddr, err := listener.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
|
||||
@@ -106,7 +106,8 @@ func (us *UDPServer) Start(ctx context.Context) error {
|
||||
}
|
||||
message := buffer[:numBytes]
|
||||
if us.router != nil {
|
||||
us.router.HandleInput(us.ctx, us.Id(), message)
|
||||
senderCtx := context.WithValue(us.ctx, common.SenderContextKey, senderAddr)
|
||||
us.router.HandleInput(senderCtx, us.Id(), message)
|
||||
} else {
|
||||
us.logger.Error("input received but no router is configured")
|
||||
}
|
||||
@@ -122,3 +123,14 @@ func (us *UDPServer) Output(ctx context.Context, payload any) error {
|
||||
func (us *UDPServer) Stop() {
|
||||
us.cancel()
|
||||
}
|
||||
|
||||
func (us *UDPServer) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "ip":
|
||||
return us.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return us.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.udp.server key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,7 +14,7 @@ type ArtNetPacketDecode struct {
|
||||
}
|
||||
|
||||
func (apd *ArtNetPacketDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("artnet.packet.decode processor only accepts a []byte")
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,7 +14,7 @@ type ArtNetPacketEncode struct {
|
||||
}
|
||||
|
||||
func (ape *ArtNetPacketEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPacket, ok := payload.(artnet.ArtNetPacket)
|
||||
payloadPacket, ok := common.GetAnyAs[artnet.ArtNetPacket](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("artnet.packet.encode processor only accepts an ArtNetPacket")
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type ArtNetPacketFilter struct {
|
||||
config config.ProcessorConfig
|
||||
OpCode uint16
|
||||
}
|
||||
|
||||
func (apf *ArtNetPacketFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPacket, ok := payload.(artnet.ArtNetPacket)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("artnet.packet.filter processor only accepts an ArtNetPacket")
|
||||
}
|
||||
|
||||
if payloadPacket.GetOpCode() != apf.OpCode {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadPacket, nil
|
||||
}
|
||||
|
||||
func (apf *ArtNetPacketFilter) Type() string {
|
||||
return apf.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "artnet.packet.filter",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
opCodeNum, err := params.GetInt("opCode")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("artnet.packet.filter opCode error: %w", err)
|
||||
}
|
||||
|
||||
return &ArtNetPacketFilter{config: config, OpCode: uint16(opCodeNum)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
61
internal/processor/filter-expr.go
Normal file
61
internal/processor/filter-expr.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/expr-lang/expr"
|
||||
"github.com/expr-lang/expr/vm"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
// NOTE(jwetzell): see language definition https://expr-lang.org/docs/language-definition
|
||||
type FilterExpr struct {
|
||||
config config.ProcessorConfig
|
||||
Program *vm.Program
|
||||
}
|
||||
|
||||
func (fe *FilterExpr) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
exprEnv := GetEnvData(ctx, payload)
|
||||
|
||||
output, err := expr.Run(fe.Program, exprEnv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputBool, ok := output.(bool)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("filter.expr expression did not return a boolean")
|
||||
}
|
||||
if !outputBool {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (fe *FilterExpr) Type() string {
|
||||
return fe.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "filter.expr",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
expressionString, err := params.GetString("expression")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("filter.expr expression error: %w", err)
|
||||
}
|
||||
|
||||
program, err := expr.Compile(expressionString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &FilterExpr{config: config, Program: program}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -6,41 +6,42 @@ import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type StringFilter struct {
|
||||
type FilterRegex struct {
|
||||
config config.ProcessorConfig
|
||||
Pattern *regexp.Regexp
|
||||
}
|
||||
|
||||
func (sf *StringFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := payload.(string)
|
||||
func (fr *FilterRegex) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("string.filter processor only accepts a string")
|
||||
return nil, errors.New("filter.regex processor only accepts a string")
|
||||
}
|
||||
|
||||
if !sf.Pattern.MatchString(payloadString) {
|
||||
if !fr.Pattern.MatchString(payloadString) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadString, nil
|
||||
}
|
||||
|
||||
func (sf *StringFilter) Type() string {
|
||||
return sf.config.Type
|
||||
func (fr *FilterRegex) Type() string {
|
||||
return fr.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "string.filter",
|
||||
Type: "filter.regex",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
patternString, err := params.GetString("pattern")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("string.filter pattern error: %w", err)
|
||||
return nil, fmt.Errorf("filter.regex pattern error: %w", err)
|
||||
}
|
||||
|
||||
patternRegexp, err := regexp.Compile(patternString)
|
||||
@@ -49,7 +50,7 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &StringFilter{config: config, Pattern: patternRegexp}, nil
|
||||
return &FilterRegex{config: config, Pattern: patternRegexp}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -15,7 +16,7 @@ type FloatParse struct {
|
||||
}
|
||||
|
||||
func (fp *FloatParse) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := payload.(string)
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("float.parse processor only accepts a string")
|
||||
|
||||
71
internal/processor/float-random.go
Normal file
71
internal/processor/float-random.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type FloatRandom struct {
|
||||
BitSize int
|
||||
Min float64
|
||||
Max float64
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fr *FloatRandom) Process(ctx context.Context, payload any) (any, error) {
|
||||
if fr.BitSize == 32 {
|
||||
payloadFloat := rand.Float32()*(float32(fr.Max)-float32(fr.Min)) + float32(fr.Min)
|
||||
return payloadFloat, nil
|
||||
}
|
||||
if fr.BitSize == 64 {
|
||||
payloadFloat := rand.Float64()*(fr.Max-fr.Min) + fr.Min
|
||||
return payloadFloat, nil
|
||||
}
|
||||
return nil, errors.New("float.random bitSize error: must be 32 or 64")
|
||||
}
|
||||
|
||||
func (fr *FloatRandom) Type() string {
|
||||
return fr.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "float.random",
|
||||
New: func(processorConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := processorConfig.Params
|
||||
|
||||
bitSizeInt, err := params.GetInt("bitSize")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
bitSizeInt = 32
|
||||
} else {
|
||||
return nil, fmt.Errorf("float.random bitSize error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if bitSizeInt != 32 && bitSizeInt != 64 {
|
||||
return nil, errors.New("float.random bitSize error: must be 32 or 64")
|
||||
}
|
||||
|
||||
minFloat, err := params.GetFloat64("min")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("float.random min error: %w", err)
|
||||
}
|
||||
|
||||
maxFloat, err := params.GetFloat64("max")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("float.random max error: %w", err)
|
||||
}
|
||||
|
||||
if maxFloat < minFloat {
|
||||
return nil, errors.New("float.random max must be greater than min")
|
||||
}
|
||||
|
||||
return &FloatRandom{config: processorConfig, Min: minFloat, Max: maxFloat, BitSize: bitSizeInt}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -26,8 +26,10 @@ type FreeDCreate struct {
|
||||
|
||||
func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var idBuffer bytes.Buffer
|
||||
err := fc.Id.Execute(&idBuffer, payload)
|
||||
err := fc.Id.Execute(&idBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -42,7 +44,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var panBuffer bytes.Buffer
|
||||
err = fc.Pan.Execute(&panBuffer, payload)
|
||||
err = fc.Pan.Execute(&panBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -57,7 +59,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var tiltBuffer bytes.Buffer
|
||||
err = fc.Tilt.Execute(&tiltBuffer, payload)
|
||||
err = fc.Tilt.Execute(&tiltBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -72,7 +74,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var rollBuffer bytes.Buffer
|
||||
err = fc.Tilt.Execute(&rollBuffer, payload)
|
||||
err = fc.Tilt.Execute(&rollBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -87,7 +89,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var posXBuffer bytes.Buffer
|
||||
err = fc.PosX.Execute(&posXBuffer, payload)
|
||||
err = fc.PosX.Execute(&posXBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -102,7 +104,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var posYBuffer bytes.Buffer
|
||||
err = fc.PosY.Execute(&posYBuffer, payload)
|
||||
err = fc.PosY.Execute(&posYBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -117,7 +119,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var posZBuffer bytes.Buffer
|
||||
err = fc.PosZ.Execute(&posZBuffer, payload)
|
||||
err = fc.PosZ.Execute(&posZBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -132,7 +134,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var zoomBuffer bytes.Buffer
|
||||
err = fc.Zoom.Execute(&zoomBuffer, payload)
|
||||
err = fc.Zoom.Execute(&zoomBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -147,7 +149,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var focusBuffer bytes.Buffer
|
||||
err = fc.Zoom.Execute(&focusBuffer, payload)
|
||||
err = fc.Focus.Execute(&focusBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -12,8 +13,8 @@ type FreeDDecode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fdd *FreeDDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
func (fd *FreeDDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.decode processor only accepts a []byte")
|
||||
@@ -26,8 +27,8 @@ func (fdd *FreeDDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
return payloadMessage, nil
|
||||
}
|
||||
|
||||
func (fdd *FreeDDecode) Type() string {
|
||||
return fdd.config.Type
|
||||
func (fd *FreeDDecode) Type() string {
|
||||
return fd.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -12,8 +13,8 @@ type FreeDEncode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fde *FreeDEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPosition, ok := payload.(freeD.FreeDPosition)
|
||||
func (fe *FreeDEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPosition, ok := common.GetAnyAs[freeD.FreeDPosition](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.decode processor only accepts a FreeDEncode")
|
||||
@@ -23,8 +24,8 @@ func (fde *FreeDEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
return payloadBytes, nil
|
||||
}
|
||||
|
||||
func (fde *FreeDEncode) Type() string {
|
||||
return fde.config.Type
|
||||
func (fe *FreeDEncode) Type() string {
|
||||
return fe.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"text/template"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPRequestCreate struct {
|
||||
config config.ProcessorConfig
|
||||
Method string
|
||||
URL *template.Template
|
||||
}
|
||||
|
||||
func (hrc *HTTPRequestCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
var urlBuffer bytes.Buffer
|
||||
err := hrc.URL.Execute(&urlBuffer, payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
urlString := urlBuffer.String()
|
||||
|
||||
//TODO(jwetzell): support body
|
||||
request, err := http.NewRequest(hrc.Method, urlString, bytes.NewBuffer([]byte{}))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return request, nil
|
||||
}
|
||||
|
||||
func (hrc *HTTPRequestCreate) Type() string {
|
||||
return hrc.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.create",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
methodString, err := params.GetString("method")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.request.create method error: %w", err)
|
||||
}
|
||||
|
||||
urlString, err := params.GetString("url")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.request.create url error: %w", err)
|
||||
}
|
||||
|
||||
urlTemplate, err := template.New("url").Parse(urlString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &HTTPRequestCreate{config: config, URL: urlTemplate, Method: methodString}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
93
internal/processor/http-request-do.go
Normal file
93
internal/processor/http-request-do.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPRequestDo struct {
|
||||
config config.ProcessorConfig
|
||||
client *http.Client
|
||||
Method string
|
||||
URL *template.Template
|
||||
}
|
||||
|
||||
func (hrd *HTTPRequestDo) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var urlBuffer bytes.Buffer
|
||||
err := hrd.URL.Execute(&urlBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
urlString := urlBuffer.String()
|
||||
|
||||
//TODO(jwetzell): support body
|
||||
request, err := http.NewRequest(hrd.Method, urlString, bytes.NewBuffer([]byte{}))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
response, err := hrd.client.Do(request)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(response.Body)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//TODO(jwetzell): support headers, etc
|
||||
return HTTPResponse{
|
||||
Status: response.StatusCode,
|
||||
Body: body,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (hrd *HTTPRequestDo) Type() string {
|
||||
return hrd.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.do",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
methodString, err := params.GetString("method")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.request.do method error: %w", err)
|
||||
}
|
||||
|
||||
urlString, err := params.GetString("url")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.request.do url error: %w", err)
|
||||
}
|
||||
|
||||
urlTemplate, err := template.New("url").Parse(urlString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
return &HTTPRequestDo{config: config, URL: urlTemplate, Method: methodString, client: client}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPRequestEncode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (hre *HTTPRequestEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadRequest, ok := payload.(*http.Request)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.encode processor only accepts an http.Request")
|
||||
}
|
||||
|
||||
bytes, err := io.ReadAll(payloadRequest.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return bytes, nil
|
||||
}
|
||||
|
||||
func (hre *HTTPRequestEncode) Type() string {
|
||||
return hre.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.encode",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &HTTPRequestEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPRequestFilter struct {
|
||||
config config.ProcessorConfig
|
||||
Path *regexp.Regexp
|
||||
Method string
|
||||
}
|
||||
|
||||
func (hrf *HTTPRequestFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
payloadRequest, ok := payload.(*http.Request)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.filter can only operate on http.Request payloads")
|
||||
}
|
||||
|
||||
if hrf.Method != "" {
|
||||
if payloadRequest.Method != hrf.Method {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
if !hrf.Path.MatchString(payloadRequest.URL.Path) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadRequest, nil
|
||||
}
|
||||
|
||||
func (hrf *HTTPRequestFilter) Type() string {
|
||||
return hrf.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.filter",
|
||||
New: func(moduleConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := moduleConfig.Params
|
||||
pathString, err := params.GetString("path")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.request.filter path error: %w", err)
|
||||
}
|
||||
|
||||
pathRegexp, err := regexp.Compile(fmt.Sprintf("^%s$", pathString))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
methodString, err := params.GetString("method")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
return &HTTPRequestFilter{config: moduleConfig, Path: pathRegexp}, nil
|
||||
} else {
|
||||
return nil, fmt.Errorf("http.request.filter method error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &HTTPRequestFilter{config: moduleConfig, Path: pathRegexp, Method: methodString}, nil
|
||||
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -20,22 +20,24 @@ type HTTPResponse struct {
|
||||
Body []byte
|
||||
}
|
||||
|
||||
func (hre *HTTPResponseCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
func (hrc *HTTPResponseCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var bodyBuffer bytes.Buffer
|
||||
err := hre.BodyTmpl.Execute(&bodyBuffer, payload)
|
||||
err := hrc.BodyTmpl.Execute(&bodyBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return HTTPResponse{
|
||||
Status: hre.Status,
|
||||
Status: hrc.Status,
|
||||
Body: bodyBuffer.Bytes(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (hre *HTTPResponseCreate) Type() string {
|
||||
return hre.config.Type
|
||||
func (hrc *HTTPResponseCreate) Type() string {
|
||||
return hrc.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPResponseEncode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (hre *HTTPResponseEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadResponse, ok := payload.(*http.Response)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.response.encode processor only accepts an http.Response")
|
||||
}
|
||||
defer payloadResponse.Body.Close()
|
||||
|
||||
bytes, err := io.ReadAll(payloadResponse.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return bytes, nil
|
||||
}
|
||||
|
||||
func (hre *HTTPResponseEncode) Type() string {
|
||||
return hre.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.response.encode",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &HTTPResponseEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -16,7 +17,7 @@ type IntParse struct {
|
||||
}
|
||||
|
||||
func (ip *IntParse) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := payload.(string)
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("int.parse processor only accepts a string")
|
||||
|
||||
@@ -15,13 +15,13 @@ type IntRandom struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (up *IntRandom) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadInt := rand.IntN(up.Max-up.Min+1) + up.Min
|
||||
func (ir *IntRandom) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadInt := rand.IntN(ir.Max-ir.Min+1) + ir.Min
|
||||
return payloadInt, nil
|
||||
}
|
||||
|
||||
func (up *IntRandom) Type() string {
|
||||
return up.config.Type
|
||||
func (ir *IntRandom) Type() string {
|
||||
return ir.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
71
internal/processor/int-scale.go
Normal file
71
internal/processor/int-scale.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type IntScale struct {
|
||||
OutMin int
|
||||
OutMax int
|
||||
InMin int
|
||||
InMax int
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (ir *IntScale) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadInt, ok := common.GetAnyAs[int](payload)
|
||||
if !ok {
|
||||
return nil, errors.New("int.scale can only process an int")
|
||||
}
|
||||
|
||||
payloadInt = (payloadInt-ir.InMin)*(ir.OutMax-ir.OutMin)/(ir.InMax-ir.InMin) + ir.OutMin
|
||||
return payloadInt, nil
|
||||
}
|
||||
|
||||
func (ir *IntScale) Type() string {
|
||||
return ir.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "int.scale",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
inMinInt, err := params.GetInt("inMin")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("int.scale inMin error: %w", err)
|
||||
}
|
||||
|
||||
inMaxInt, err := params.GetInt("inMax")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("int.scale inMax error: %w", err)
|
||||
}
|
||||
|
||||
if inMaxInt < inMinInt {
|
||||
return nil, errors.New("int.scale inMax must be greater than inMin")
|
||||
}
|
||||
|
||||
outMinInt, err := params.GetInt("outMin")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("int.scale outMin error: %w", err)
|
||||
}
|
||||
|
||||
outMaxInt, err := params.GetInt("outMax")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("int.scale outMax error: %w", err)
|
||||
}
|
||||
|
||||
if outMaxInt < outMinInt {
|
||||
return nil, errors.New("int.scale outMax must be greater than outMin")
|
||||
}
|
||||
|
||||
return &IntScale{config: config, InMin: inMinInt, InMax: inMaxInt, OutMin: outMinInt, OutMax: outMaxInt}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,15 +14,20 @@ type JsonDecode struct {
|
||||
}
|
||||
|
||||
func (jd *JsonDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := payload.(string)
|
||||
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("json.decode processor only accepts a string")
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
if !ok {
|
||||
return nil, errors.New("json.decode can only process a string or []byte")
|
||||
}
|
||||
payloadBytes = []byte(payloadString)
|
||||
}
|
||||
|
||||
payloadJson := make(map[string]any)
|
||||
|
||||
err := json.Unmarshal([]byte(payloadString), &payloadJson)
|
||||
err := json.Unmarshal(payloadBytes, &payloadJson)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -65,9 +65,10 @@ func newMidiNoteOnCreate(config config.ProcessorConfig) (Processor, error) {
|
||||
}
|
||||
|
||||
return &MIDIMessageCreate{config: config, ProcessFunc: func(ctx context.Context, payload any) (any, error) {
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var channelBuffer bytes.Buffer
|
||||
err := channelTemplate.Execute(&channelBuffer, payload)
|
||||
err := channelTemplate.Execute(&channelBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -76,7 +77,7 @@ func newMidiNoteOnCreate(config config.ProcessorConfig) (Processor, error) {
|
||||
channelValue, err := strconv.ParseUint(channelBuffer.String(), 10, 8)
|
||||
|
||||
var noteBuffer bytes.Buffer
|
||||
err = noteTemplate.Execute(¬eBuffer, payload)
|
||||
err = noteTemplate.Execute(¬eBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -85,7 +86,7 @@ func newMidiNoteOnCreate(config config.ProcessorConfig) (Processor, error) {
|
||||
noteValue, err := strconv.ParseUint(noteBuffer.String(), 10, 8)
|
||||
|
||||
var velocityBuffer bytes.Buffer
|
||||
err = velocityTemplate.Execute(&velocityBuffer, payload)
|
||||
err = velocityTemplate.Execute(&velocityBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -136,8 +137,10 @@ func newMidiNoteOffCreate(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
return &MIDIMessageCreate{config: config, ProcessFunc: func(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var channelBuffer bytes.Buffer
|
||||
err := channelTemplate.Execute(&channelBuffer, payload)
|
||||
err := channelTemplate.Execute(&channelBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -146,7 +149,7 @@ func newMidiNoteOffCreate(config config.ProcessorConfig) (Processor, error) {
|
||||
channelValue, err := strconv.ParseUint(channelBuffer.String(), 10, 8)
|
||||
|
||||
var noteBuffer bytes.Buffer
|
||||
err = noteTemplate.Execute(¬eBuffer, payload)
|
||||
err = noteTemplate.Execute(¬eBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -155,7 +158,7 @@ func newMidiNoteOffCreate(config config.ProcessorConfig) (Processor, error) {
|
||||
noteValue, err := strconv.ParseUint(noteBuffer.String(), 10, 8)
|
||||
|
||||
var velocityBuffer bytes.Buffer
|
||||
err = velocityTemplate.Execute(&velocityBuffer, payload)
|
||||
err = velocityTemplate.Execute(&velocityBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -207,8 +210,10 @@ func newMidiControlChangeCreate(config config.ProcessorConfig) (Processor, error
|
||||
|
||||
return &MIDIMessageCreate{config: config, ProcessFunc: func(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var channelBuffer bytes.Buffer
|
||||
err := channelTemplate.Execute(&channelBuffer, payload)
|
||||
err := channelTemplate.Execute(&channelBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -217,7 +222,7 @@ func newMidiControlChangeCreate(config config.ProcessorConfig) (Processor, error
|
||||
channelValue, err := strconv.ParseUint(channelBuffer.String(), 10, 8)
|
||||
|
||||
var controlBuffer bytes.Buffer
|
||||
err = controlTemplate.Execute(&controlBuffer, payload)
|
||||
err = controlTemplate.Execute(&controlBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -226,7 +231,7 @@ func newMidiControlChangeCreate(config config.ProcessorConfig) (Processor, error
|
||||
controlValue, err := strconv.ParseUint(controlBuffer.String(), 10, 8)
|
||||
|
||||
var valueBuffer bytes.Buffer
|
||||
err = valueTemplate.Execute(&valueBuffer, payload)
|
||||
err = valueTemplate.Execute(&valueBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -266,9 +271,10 @@ func newMidiProgramChangeCreate(config config.ProcessorConfig) (Processor, error
|
||||
}
|
||||
|
||||
return &MIDIMessageCreate{config: config, ProcessFunc: func(ctx context.Context, payload any) (any, error) {
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var channelBuffer bytes.Buffer
|
||||
err := channelTemplate.Execute(&channelBuffer, payload)
|
||||
err := channelTemplate.Execute(&channelBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -277,7 +283,7 @@ func newMidiProgramChangeCreate(config config.ProcessorConfig) (Processor, error
|
||||
channelValue, err := strconv.ParseUint(channelBuffer.String(), 10, 8)
|
||||
|
||||
var programBuffer bytes.Buffer
|
||||
err = programTemplate.Execute(&programBuffer, payload)
|
||||
err = programTemplate.Execute(&programBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
)
|
||||
@@ -15,7 +16,7 @@ type MIDIMessageDecode struct {
|
||||
}
|
||||
|
||||
func (mmd *MIDIMessageDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.message.decode processor only accepts a []byte")
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
)
|
||||
@@ -15,7 +16,7 @@ type MIDIMessageEncode struct {
|
||||
}
|
||||
|
||||
func (mme *MIDIMessageEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMessage, ok := payload.(midi.Message)
|
||||
payloadMessage, ok := common.GetAnyAs[midi.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.message.encode processor only accepts a midi.Message")
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
//go:build cgo
|
||||
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
)
|
||||
|
||||
type MIDIMessageFilter struct {
|
||||
config config.ProcessorConfig
|
||||
MIDIType string
|
||||
}
|
||||
|
||||
func (mmf *MIDIMessageFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMessage, ok := payload.(midi.Message)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.message.filter processor only accepts a midi.Message")
|
||||
}
|
||||
|
||||
if payloadMessage.Type().String() != mmf.MIDIType {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadMessage, nil
|
||||
}
|
||||
|
||||
func (mmf *MIDIMessageFilter) Type() string {
|
||||
return mmf.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "midi.message.filter",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
msgTypeString, err := params.GetString("type")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.filter type error: %w", err)
|
||||
}
|
||||
|
||||
return &MIDIMessageFilter{config: config, MIDIType: msgTypeString}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
)
|
||||
@@ -45,7 +46,7 @@ type MIDIPitchBend struct {
|
||||
}
|
||||
|
||||
func (mmu *MIDIMessageUnpack) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMidi, ok := payload.(midi.Message)
|
||||
payloadMidi, ok := common.GetAnyAs[midi.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.message.unpack processor only accepts a midi.Message")
|
||||
|
||||
@@ -80,8 +80,8 @@ func (mmc *MQTTMessageCreate) Type() string {
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "mqtt.message.create",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
New: func(processorConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := processorConfig.Params
|
||||
topicString, err := params.GetString("topic")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mqtt.message.create topic error: %w", err)
|
||||
@@ -98,25 +98,22 @@ func init() {
|
||||
}
|
||||
|
||||
//TODO(jwetzell): convert payload into []byte or string for sending
|
||||
payload, ok := params["payload"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("mqtt.message.create payload error: not found")
|
||||
}
|
||||
|
||||
if payloadBytes, ok := payload.([]byte); ok {
|
||||
return &MQTTMessageCreate{config: config, Topic: topicString, QoS: byte(qosByte), Retained: retainedBool, Payload: payloadBytes}, nil
|
||||
}
|
||||
|
||||
payloadString, ok := payload.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("mqtt.message.create payload error: not a string or byte array")
|
||||
payloadString, err := params.GetString("payload")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotString) {
|
||||
payloadBytes, err := params.GetByteSlice("payload")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mqtt.message.create payload error: %w", err)
|
||||
}
|
||||
return &MQTTMessageCreate{config: processorConfig, Topic: topicString, QoS: byte(qosByte), Retained: retainedBool, Payload: payloadBytes}, nil
|
||||
} else {
|
||||
return nil, fmt.Errorf("mqtt.message.create payload error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
payloadBytes := []byte(payloadString)
|
||||
|
||||
return &MQTTMessageCreate{config: config, Topic: topicString, QoS: byte(qosByte), Retained: retainedBool, Payload: payloadBytes}, nil
|
||||
return &MQTTMessageCreate{config: processorConfig, Topic: topicString, QoS: byte(qosByte), Retained: retainedBool, Payload: payloadBytes}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,7 +14,7 @@ type MQTTMessageEncode struct {
|
||||
}
|
||||
|
||||
func (mme *MQTTMessageEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMessage, ok := payload.(mqtt.Message)
|
||||
payloadMessage, ok := common.GetAnyAs[mqtt.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("mqtt.message.encode processor only accepts an mqtt.Message")
|
||||
|
||||
@@ -21,9 +21,10 @@ type NATSMessageCreate struct {
|
||||
}
|
||||
|
||||
func (nmc *NATSMessageCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var payloadBuffer bytes.Buffer
|
||||
err := nmc.Payload.Execute(&payloadBuffer, payload)
|
||||
err := nmc.Payload.Execute(&payloadBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -32,7 +33,7 @@ func (nmc *NATSMessageCreate) Process(ctx context.Context, payload any) (any, er
|
||||
payloadString := payloadBuffer.String()
|
||||
|
||||
var subjectBuffer bytes.Buffer
|
||||
err = nmc.Subject.Execute(&subjectBuffer, payload)
|
||||
err = nmc.Subject.Execute(&subjectBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -22,8 +22,10 @@ type OSCMessageCreate struct {
|
||||
|
||||
func (omc *OSCMessageCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var addressBuffer bytes.Buffer
|
||||
err := omc.Address.Execute(&addressBuffer, payload)
|
||||
err := omc.Address.Execute(&addressBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -39,7 +41,7 @@ func (omc *OSCMessageCreate) Process(ctx context.Context, payload any) (any, err
|
||||
return nil, errors.New("osc.message.create address must start with '/'")
|
||||
}
|
||||
|
||||
payloadMessage := osc.OSCMessage{
|
||||
payloadMessage := &osc.OSCMessage{
|
||||
Address: addressString,
|
||||
}
|
||||
|
||||
@@ -47,7 +49,7 @@ func (omc *OSCMessageCreate) Process(ctx context.Context, payload any) (any, err
|
||||
|
||||
for argIndex, argTemplate := range omc.Args {
|
||||
var argBuffer bytes.Buffer
|
||||
err := argTemplate.Execute(&argBuffer, payload)
|
||||
err := argTemplate.Execute(&argBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -78,8 +80,8 @@ func (omc *OSCMessageCreate) Type() string {
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "osc.message.create",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
New: func(processorConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := processorConfig.Params
|
||||
addressString, err := params.GetString("address")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("osc.message.create address error: %w", err)
|
||||
@@ -91,43 +93,36 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
args, ok := params["args"]
|
||||
|
||||
if ok {
|
||||
rawArgs, ok := args.([]interface{})
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("osc.message.create address must be an array found %T", args)
|
||||
argStrings, err := params.GetStringSlice("args")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
return &OSCMessageCreate{config: processorConfig, Address: addressTemplate}, nil
|
||||
} else {
|
||||
return nil, fmt.Errorf("osc.message.create args error: %w", err)
|
||||
}
|
||||
|
||||
typesString, err := params.GetString("types")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("osc.message.create types error: %w", err)
|
||||
}
|
||||
|
||||
if len(rawArgs) != len(typesString) {
|
||||
return nil, errors.New("osc.message.create args and types must be the same length")
|
||||
}
|
||||
|
||||
argTemplates := []*template.Template{}
|
||||
|
||||
for _, rawArg := range rawArgs {
|
||||
argString, ok := rawArg.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("osc.message.create arg error: not a string")
|
||||
}
|
||||
|
||||
argTemplate, err := template.New("arg").Parse(argString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
argTemplates = append(argTemplates, argTemplate)
|
||||
}
|
||||
return &OSCMessageCreate{config: config, Address: addressTemplate, Args: argTemplates, Types: typesString}, nil
|
||||
}
|
||||
return &OSCMessageCreate{config: config, Address: addressTemplate}, nil
|
||||
|
||||
typesString, err := params.GetString("types")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("osc.message.create types error: %w", err)
|
||||
}
|
||||
|
||||
if len(argStrings) != len(typesString) {
|
||||
return nil, errors.New("osc.message.create args and types must be the same length")
|
||||
}
|
||||
|
||||
argTemplates := []*template.Template{}
|
||||
|
||||
for _, argString := range argStrings {
|
||||
|
||||
argTemplate, err := template.New("arg").Parse(argString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
argTemplates = append(argTemplates, argTemplate)
|
||||
}
|
||||
return &OSCMessageCreate{config: processorConfig, Address: addressTemplate, Args: argTemplates, Types: typesString}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@ package processor
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
osc "github.com/jwetzell/osc-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,7 +15,7 @@ type OSCMessageDecode struct {
|
||||
}
|
||||
|
||||
func (omd *OSCMessageDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("osc.message.decode processor only accepts a []byte payload")
|
||||
@@ -29,7 +31,7 @@ func (omd *OSCMessageDecode) Process(ctx context.Context, payload any) (any, err
|
||||
|
||||
message, err := osc.MessageFromBytes(payloadBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("osc.message.decode processor failed to decode OSC message: %w", err)
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
osc "github.com/jwetzell/osc-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,10 +14,10 @@ type OSCMessageEncode struct {
|
||||
}
|
||||
|
||||
func (ome *OSCMessageEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMessage, ok := payload.(osc.OSCMessage)
|
||||
payloadMessage, ok := common.GetAnyAs[*osc.OSCMessage](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("osc.message.encode processor only accepts an OSCMessage")
|
||||
return nil, errors.New("osc.message.encode processor only accepts an *OSCMessage")
|
||||
}
|
||||
|
||||
bytes := payloadMessage.ToBytes()
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/jwetzell/osc-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type OSCMessageFilter struct {
|
||||
config config.ProcessorConfig
|
||||
Address *regexp.Regexp
|
||||
}
|
||||
|
||||
func (omf *OSCMessageFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
payloadMessage, ok := payload.(osc.OSCMessage)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("osc.message.filter can only operate on OSCMessage payloads")
|
||||
}
|
||||
|
||||
if !omf.Address.MatchString(payloadMessage.Address) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadMessage, nil
|
||||
}
|
||||
|
||||
func (omf *OSCMessageFilter) Type() string {
|
||||
return omf.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "osc.message.filter",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
addressString, err := params.GetString("address")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("osc.message.filter address error: %w", err)
|
||||
}
|
||||
|
||||
addressPattern := strings.ReplaceAll(addressString, "?", ".")
|
||||
addressPattern = strings.ReplaceAll(addressPattern, "*", "[^/]*")
|
||||
addressPattern = strings.ReplaceAll(addressPattern, "[!", "[^")
|
||||
addressPattern = strings.ReplaceAll(addressPattern, "{", "(")
|
||||
addressPattern = strings.ReplaceAll(addressPattern, "}", ")")
|
||||
addressPattern = strings.ReplaceAll(addressPattern, ",", "|")
|
||||
|
||||
addressPatternRegexp, err := regexp.Compile(fmt.Sprintf("^%s$", addressPattern))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &OSCMessageFilter{config: config, Address: addressPatternRegexp}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -40,3 +41,38 @@ var (
|
||||
processorRegistryMu sync.RWMutex
|
||||
ProcessorRegistry = make(map[string]ProcessorRegistration)
|
||||
)
|
||||
|
||||
type TemplateData struct {
|
||||
Payload any
|
||||
Modules any
|
||||
Sender any
|
||||
}
|
||||
|
||||
type EnvData struct {
|
||||
Payload any
|
||||
Sender any
|
||||
}
|
||||
|
||||
func GetTemplateData(ctx context.Context, payload any) TemplateData {
|
||||
templateData := TemplateData{Payload: payload}
|
||||
modules := ctx.Value(common.ModulesContextKey)
|
||||
if modules != nil {
|
||||
templateData.Modules = modules
|
||||
}
|
||||
|
||||
sender := ctx.Value(common.SenderContextKey)
|
||||
if sender != nil {
|
||||
templateData.Sender = sender
|
||||
}
|
||||
return templateData
|
||||
}
|
||||
|
||||
func GetEnvData(ctx context.Context, payload any) EnvData {
|
||||
envData := EnvData{Payload: payload}
|
||||
|
||||
sender := ctx.Value(common.SenderContextKey)
|
||||
if sender != nil {
|
||||
envData.Sender = sender
|
||||
}
|
||||
return envData
|
||||
}
|
||||
|
||||
55
internal/processor/router-input.go
Normal file
55
internal/processor/router-input.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type RouterInput struct {
|
||||
config config.ProcessorConfig
|
||||
SourceId string
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func (ro *RouterInput) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
if !ok {
|
||||
return nil, errors.New("router.input no router found")
|
||||
}
|
||||
|
||||
_, err := router.HandleInput(ctx, ro.SourceId, payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.New("router.input failed to send input")
|
||||
}
|
||||
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (ro *RouterInput) Type() string {
|
||||
return ro.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "router.input",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
params := config.Params
|
||||
|
||||
sourceId, err := params.GetString("source")
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("router.input source error: %w", err)
|
||||
}
|
||||
|
||||
return &RouterInput{config: config, SourceId: sourceId, logger: slog.Default().With("component", "processor", "type", config.Type)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
55
internal/processor/router-output.go
Normal file
55
internal/processor/router-output.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type RouterOutput struct {
|
||||
config config.ProcessorConfig
|
||||
ModuleId string
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func (ro *RouterOutput) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
if !ok {
|
||||
return nil, errors.New("router.output no router found")
|
||||
}
|
||||
|
||||
err := router.HandleOutput(ctx, ro.ModuleId, payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("router.output failed to send output: %w", err)
|
||||
}
|
||||
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (ro *RouterOutput) Type() string {
|
||||
return ro.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "router.output",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
params := config.Params
|
||||
|
||||
moduleId, err := params.GetString("module")
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("router.output module error: %w", err)
|
||||
}
|
||||
|
||||
return &RouterOutput{config: config, ModuleId: moduleId, logger: slog.Default().With("component", "processor", "type", config.Type)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -17,7 +17,9 @@ type ScriptExpr struct {
|
||||
|
||||
func (se *ScriptExpr) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
output, err := expr.Run(se.Program, payload)
|
||||
exprEnv := GetEnvData(ctx, payload)
|
||||
|
||||
output, err := expr.Run(se.Program, exprEnv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -5,38 +5,45 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"modernc.org/quickjs"
|
||||
)
|
||||
|
||||
type ScriptJS struct {
|
||||
config config.ProcessorConfig
|
||||
Program string
|
||||
config config.ProcessorConfig
|
||||
vm *quickjs.VM
|
||||
payloadAtom quickjs.Atom
|
||||
senderAtom quickjs.Atom
|
||||
Program string
|
||||
}
|
||||
|
||||
func (sj *ScriptJS) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
vm, err := quickjs.NewVM()
|
||||
//NOTE(jwetzell): some weird conversion going on with these types
|
||||
_, isUint8Slice := common.GetAnyAs[[]uint8](payload)
|
||||
_, isbyteSlice := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if isUint8Slice || isbyteSlice {
|
||||
intSlice, ok := common.GetAnyAsIntSlice(payload)
|
||||
|
||||
if ok {
|
||||
payload = intSlice
|
||||
}
|
||||
}
|
||||
defer vm.Close()
|
||||
payloadAtom, err := vm.NewAtom("payload")
|
||||
|
||||
sj.vm.SetProperty(sj.vm.GlobalObject(), sj.payloadAtom, payload)
|
||||
|
||||
sender := ctx.Value(common.SenderContextKey)
|
||||
sj.vm.SetProperty(sj.vm.GlobalObject(), sj.senderAtom, sender)
|
||||
|
||||
_, err := sj.vm.Eval(sj.Program, quickjs.EvalGlobal)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
vm.SetProperty(vm.GlobalObject(), payloadAtom, payload)
|
||||
|
||||
_, err = vm.Eval(sj.Program, quickjs.EvalGlobal)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
output, err := vm.GetProperty(vm.GlobalObject(), payloadAtom)
|
||||
output, err := sj.vm.GetProperty(sj.vm.GlobalObject(), sj.payloadAtom)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -54,6 +61,7 @@ func (sj *ScriptJS) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
if ok {
|
||||
var outputMap map[string]interface{}
|
||||
fmt.Println(outputObject.String())
|
||||
err := json.Unmarshal([]byte(outputObject.String()), &outputMap)
|
||||
return outputMap, err
|
||||
}
|
||||
@@ -76,7 +84,23 @@ func init() {
|
||||
return nil, fmt.Errorf("script.js program error: %w", err)
|
||||
}
|
||||
|
||||
return &ScriptJS{config: config, Program: programString}, nil
|
||||
vm, err := quickjs.NewVM()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
payloadAtom, err := vm.NewAtom("payload")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
senderAtom, err := vm.NewAtom("sender")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &ScriptJS{config: config, Program: programString, vm: vm, payloadAtom: payloadAtom, senderAtom: senderAtom}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
extism "github.com/extism/go-sdk"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -15,21 +16,21 @@ type ScriptWASM struct {
|
||||
Function string
|
||||
}
|
||||
|
||||
func (se *ScriptWASM) Process(ctx context.Context, payload any) (any, error) {
|
||||
func (sw *ScriptWASM) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("script.wasm can only operator on byte array")
|
||||
return nil, fmt.Errorf("script.wasm can only process a byte array")
|
||||
}
|
||||
|
||||
program, err := se.Program.Instance(ctx, extism.PluginInstanceConfig{})
|
||||
program, err := sw.Program.Instance(ctx, extism.PluginInstanceConfig{})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, output, err := program.Call(se.Function, payloadBytes)
|
||||
_, output, err := program.Call(sw.Function, payloadBytes)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -38,8 +39,8 @@ func (se *ScriptWASM) Process(ctx context.Context, payload any) (any, error) {
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func (se *ScriptWASM) Type() string {
|
||||
return se.config.Type
|
||||
func (sw *ScriptWASM) Type() string {
|
||||
return sw.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -22,10 +22,12 @@ type SipAudioFileResponse struct {
|
||||
AudioFile string
|
||||
}
|
||||
|
||||
func (scc *SipResponseAudioCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
func (srac *SipResponseAudioCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var audioFileBuffer bytes.Buffer
|
||||
err := scc.AudioFile.Execute(&audioFileBuffer, payload)
|
||||
err := srac.AudioFile.Execute(&audioFileBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -34,14 +36,14 @@ func (scc *SipResponseAudioCreate) Process(ctx context.Context, payload any) (an
|
||||
audioFileString := audioFileBuffer.String()
|
||||
|
||||
return SipAudioFileResponse{
|
||||
PreWait: scc.PreWait,
|
||||
PostWait: scc.PostWait,
|
||||
PreWait: srac.PreWait,
|
||||
PostWait: srac.PostWait,
|
||||
AudioFile: audioFileString,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (scc *SipResponseAudioCreate) Type() string {
|
||||
return scc.config.Type
|
||||
func (srac *SipResponseAudioCreate) Type() string {
|
||||
return srac.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -25,10 +25,12 @@ type SipDTMFResponse struct {
|
||||
Digits string
|
||||
}
|
||||
|
||||
func (scc *SipResponseDTMFCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
func (srdc *SipResponseDTMFCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var digitsBuffer bytes.Buffer
|
||||
err := scc.Digits.Execute(&digitsBuffer, payload)
|
||||
err := srdc.Digits.Execute(&digitsBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -36,19 +38,19 @@ func (scc *SipResponseDTMFCreate) Process(ctx context.Context, payload any) (any
|
||||
|
||||
digitsString := digitsBuffer.String()
|
||||
|
||||
if !scc.validDTMF.MatchString(digitsString) {
|
||||
if !srdc.validDTMF.MatchString(digitsString) {
|
||||
return nil, errors.New("sip.response.dtmf.create result of digits template contains invalid characters")
|
||||
}
|
||||
|
||||
return SipDTMFResponse{
|
||||
PreWait: scc.PreWait,
|
||||
PostWait: scc.PostWait,
|
||||
PreWait: srdc.PreWait,
|
||||
PostWait: srdc.PostWait,
|
||||
Digits: digitsString,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (scc *SipResponseDTMFCreate) Type() string {
|
||||
return scc.config.Type
|
||||
func (srdc *SipResponseDTMFCreate) Type() string {
|
||||
return srdc.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -15,8 +15,10 @@ type StringCreate struct {
|
||||
}
|
||||
|
||||
func (sc *StringCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var templateBuffer bytes.Buffer
|
||||
err := sc.Template.Execute(&templateBuffer, payload)
|
||||
err := sc.Template.Execute(&templateBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -12,7 +13,7 @@ type StringDecode struct {
|
||||
}
|
||||
|
||||
func (sd *StringDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("string.decode processor only accepts a []byte")
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -12,7 +13,7 @@ type StringEncode struct {
|
||||
}
|
||||
|
||||
func (se *StringEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := payload.(string)
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("string.encode processor only accepts a string")
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -15,7 +16,7 @@ type StringSplit struct {
|
||||
}
|
||||
|
||||
func (ss *StringSplit) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := payload.(string)
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("string.split only accepts a string")
|
||||
|
||||
@@ -18,7 +18,11 @@ func (sf *StructFieldGet) Process(ctx context.Context, payload any) (any, error)
|
||||
s := reflect.ValueOf(payload)
|
||||
|
||||
if s.Kind() != reflect.Struct {
|
||||
return nil, errors.New("struct.field.get processor only accepts a struct payload")
|
||||
if s.Kind() == reflect.Pointer && s.Elem().Kind() == reflect.Struct {
|
||||
s = s.Elem()
|
||||
} else {
|
||||
return nil, errors.New("struct.field.get processor only accepts a struct payload")
|
||||
}
|
||||
}
|
||||
|
||||
field := s.FieldByName(sf.Name)
|
||||
|
||||
@@ -18,7 +18,11 @@ func (sm *StructMethodGet) Process(ctx context.Context, payload any) (any, error
|
||||
s := reflect.ValueOf(payload)
|
||||
|
||||
if s.Kind() != reflect.Struct {
|
||||
return nil, errors.New("struct.method.get processor only accepts a struct payload")
|
||||
if s.Kind() == reflect.Pointer && s.Elem().Kind() == reflect.Struct {
|
||||
s = s.Elem()
|
||||
} else {
|
||||
return nil, errors.New("struct.method.get processor only accepts a struct payload")
|
||||
}
|
||||
}
|
||||
|
||||
method := s.MethodByName(sm.Name)
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
package processor_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
func TestArtnetPacketCreateFromRegistry(t *testing.T) {
|
||||
func TestArtnetPacketDecodeFromRegistry(t *testing.T) {
|
||||
registration, ok := processor.ProcessorRegistry["artnet.packet.decode"]
|
||||
if !ok {
|
||||
t.Fatalf("artnet.packet.decode processor not registered")
|
||||
@@ -25,3 +27,81 @@ func TestArtnetPacketCreateFromRegistry(t *testing.T) {
|
||||
t.Fatalf("artnet.packet.decode processor has wrong type: %s", processorInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodArtnetPacketDecode(t *testing.T) {
|
||||
packetDecoder := processor.ArtNetPacketDecode{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
payload any
|
||||
expected artnet.ArtNetPacket
|
||||
}{
|
||||
{
|
||||
name: "number",
|
||||
payload: []byte{65, 114, 116, 45, 78, 101, 116, 0, 0, 80, 0, 14, 237, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
|
||||
expected: &artnet.ArtDmx{
|
||||
ID: []byte{'A', 'r', 't', '-', 'N', 'e', 't', 0x00},
|
||||
OpCode: artnet.OpDmx,
|
||||
ProtVerHi: 0,
|
||||
ProtVerLo: 14,
|
||||
Sequence: 237,
|
||||
Physical: 0,
|
||||
SubUni: 1,
|
||||
Net: 0,
|
||||
Length: 512,
|
||||
Data: make([]uint8, 512),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
got, err := packetDecoder.Process(t.Context(), test.payload)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("artnet.packet.decode processing failed: %s", err)
|
||||
}
|
||||
|
||||
//TODO(jwetzell): work out better way to compare the any/any
|
||||
if !reflect.DeepEqual(got, test.expected) {
|
||||
t.Fatalf("artnet.packet.decode got %+v (%T), expected %+v (%T)", got, got, test.expected, test.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadArtnetPacketDecode(t *testing.T) {
|
||||
packetDecoder := processor.ArtNetPacketDecode{}
|
||||
tests := []struct {
|
||||
name string
|
||||
payload any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "not a byte slice",
|
||||
payload: "not a byte slice",
|
||||
errorString: "artnet.packet.decode processor only accepts a []byte",
|
||||
},
|
||||
{
|
||||
name: "not enough bytes",
|
||||
payload: []byte{1, 2, 3},
|
||||
errorString: "ArtNet packet must be at least 12 bytes",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
got, err := packetDecoder.Process(t.Context(), test.payload)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("artnet.packet.decode expected to fail but succeeded, got: %v", got)
|
||||
|
||||
}
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("artnet.packet.decode got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package processor_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
@@ -25,3 +27,76 @@ func TestArtnetPacketEncodeFromRegistry(t *testing.T) {
|
||||
t.Fatalf("artnet.packet.encode processor has wrong type: %s", processorInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodArtnetPacketEncode(t *testing.T) {
|
||||
packetEncoder := processor.ArtNetPacketEncode{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
expected []byte
|
||||
payload any
|
||||
}{
|
||||
{
|
||||
name: "number",
|
||||
expected: []byte{65, 114, 116, 45, 78, 101, 116, 0, 0, 80, 0, 14, 237, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
|
||||
payload: &artnet.ArtDmx{
|
||||
ID: []byte{'A', 'r', 't', '-', 'N', 'e', 't', 0x00},
|
||||
OpCode: artnet.OpDmx,
|
||||
ProtVerHi: 0,
|
||||
ProtVerLo: 14,
|
||||
Sequence: 237,
|
||||
Physical: 0,
|
||||
SubUni: 1,
|
||||
Net: 0,
|
||||
Length: 512,
|
||||
Data: make([]uint8, 512),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
got, err := packetEncoder.Process(t.Context(), test.payload)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("artnet.packet.encode processing failed: %s", err)
|
||||
}
|
||||
|
||||
//TODO(jwetzell): work out better way to compare the any/any
|
||||
if !reflect.DeepEqual(got, test.expected) {
|
||||
t.Fatalf("artnet.packet.encode got %+v (%T), expected %+v (%T)", got, got, test.expected, test.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadArtnetPacketEncode(t *testing.T) {
|
||||
packetEncoder := processor.ArtNetPacketEncode{}
|
||||
tests := []struct {
|
||||
name string
|
||||
payload any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "not an ArtNet packet",
|
||||
payload: "test",
|
||||
errorString: "artnet.packet.encode processor only accepts an ArtNetPacket",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
got, err := packetEncoder.Process(t.Context(), test.payload)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("artnet.packet.encode expected to fail but succeeded, got: %v", got)
|
||||
|
||||
}
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("artnet.packet.encode got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user