mirror of
https://github.com/jwetzell/showbridge-go.git
synced 2026-04-30 06:45:30 +00:00
Compare commits
46 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b639a5c786 | ||
|
|
d170958d9b | ||
|
|
ed4c14e82b | ||
|
|
fcb1378784 | ||
|
|
97f4cbeace | ||
|
|
8ffc7d02a5 | ||
|
|
3458b52206 | ||
|
|
e12b6e098e | ||
|
|
58cb7766fe | ||
|
|
407f1f3618 | ||
|
|
3c0f555a6f | ||
|
|
6c6e50e0eb | ||
|
|
0ed4d6669f | ||
|
|
cc37559bde | ||
|
|
18b307bca1 | ||
|
|
17106b5096 | ||
|
|
df9ffdda9e | ||
|
|
479cf41ea0 | ||
|
|
af833cb212 | ||
|
|
a6a8e275ee | ||
|
|
6968539c59 | ||
|
|
e96913230b | ||
|
|
f1dff33704 | ||
|
|
ff426994e4 | ||
|
|
a1275b3b69 | ||
|
|
227d042feb | ||
|
|
e53515267e | ||
|
|
502586dec6 | ||
|
|
cad3714664 | ||
|
|
cf6519b594 | ||
|
|
7dcac9470a | ||
|
|
e5268f42f8 | ||
|
|
ccff105e37 | ||
|
|
6611821155 | ||
|
|
7cde1c244a | ||
|
|
70878e6df6 | ||
|
|
bd005da358 | ||
|
|
25f2ec30c2 | ||
|
|
e679bf2b46 | ||
|
|
460d2f051d | ||
|
|
efdcbae5c4 | ||
|
|
076a13f48a | ||
|
|
971eea6e41 | ||
|
|
1172159455 | ||
|
|
ecb415f321 | ||
|
|
b552672011 |
34
README.md
34
README.md
@@ -6,29 +6,37 @@ Simple protocol router _/s_
|
|||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://github.com/jwetzell/showbridge-go/releases">Releases</a> ·
|
||||||
|
<a href="https://docs.showbridge.io">Documentation</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
### Supported Protocols
|
### Supported Protocols
|
||||||
- HTTP
|
- HTTP
|
||||||
- client
|
|
||||||
- server
|
|
||||||
- UDP
|
- UDP
|
||||||
- client
|
|
||||||
- server
|
|
||||||
- TCP
|
- TCP
|
||||||
- client
|
|
||||||
- server
|
|
||||||
- [MQTT](https://mqtt.org/)
|
- [MQTT](https://mqtt.org/)
|
||||||
- client
|
|
||||||
- [NATS](https://nats.io/)
|
- [NATS](https://nats.io/)
|
||||||
- client
|
|
||||||
- [PosiStageNet](https://posistage.net/)
|
- [PosiStageNet](https://posistage.net/)
|
||||||
- client
|
|
||||||
- MIDI (not included in pre-built binaries yet)
|
- MIDI (not included in pre-built binaries yet)
|
||||||
- input
|
- Serial (not included in pre-built binaries yet)
|
||||||
- output
|
- [OSC](https://opensoundcontrol.stanford.edu/spec-1_0.html)
|
||||||
|
- [FreeD](https://ptzoptics.com/freed/)
|
||||||
- [SIP](https://en.wikipedia.org/wiki/Session_Initiation_Protocol)
|
- [SIP](https://en.wikipedia.org/wiki/Session_Initiation_Protocol)
|
||||||
- call server
|
|
||||||
- [DTMF](https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling) server
|
|
||||||
|
|
||||||
|
### CLI Usage
|
||||||
|
|
||||||
|
```
|
||||||
|
NAME:
|
||||||
|
showbridge - Simple protocol router /s
|
||||||
|
|
||||||
|
USAGE:
|
||||||
|
showbridge [global options]
|
||||||
|
|
||||||
|
GLOBAL OPTIONS:
|
||||||
|
--config string path to config file (default: "./config.yaml")
|
||||||
|
--debug set log level to DEBUG
|
||||||
|
--json log using JSON
|
||||||
|
--help, -h show help
|
||||||
|
--version, -v print the version
|
||||||
|
```
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/jwetzell/showbridge-go"
|
"github.com/jwetzell/showbridge-go"
|
||||||
"github.com/jwetzell/showbridge-go/internal/config"
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
@@ -39,7 +40,37 @@ func main() {
|
|||||||
Usage: "log using JSON",
|
Usage: "log using JSON",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Action: func(ctx context.Context, c *cli.Command) error {
|
Action: run,
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||||
|
defer cancel()
|
||||||
|
err := cmd.Run(ctx, os.Args)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func readConfig(configPath string) (config.Config, error) {
|
||||||
|
cfg := config.Config{}
|
||||||
|
|
||||||
|
configBytes, err := os.ReadFile(configPath)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return config.Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = yaml.Unmarshal(configBytes, &cfg)
|
||||||
|
if err != nil {
|
||||||
|
return config.Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(ctx context.Context, c *cli.Command) error {
|
||||||
configPath := c.String("config")
|
configPath := c.String("config")
|
||||||
if configPath == "" {
|
if configPath == "" {
|
||||||
return errors.New("config value cannot be empty")
|
return errors.New("config value cannot be empty")
|
||||||
@@ -68,47 +99,30 @@ func main() {
|
|||||||
logHandler = slog.NewJSONHandler(logOutput, logHandlerOptions)
|
logHandler = slog.NewJSONHandler(logOutput, logHandlerOptions)
|
||||||
}
|
}
|
||||||
|
|
||||||
logger := slog.New(logHandler)
|
slog.SetDefault(slog.New(logHandler))
|
||||||
|
|
||||||
slog.SetDefault(logger)
|
commandLogger := slog.Default().With("component", "cmd")
|
||||||
|
|
||||||
router, moduleErrors, routeErrors := showbridge.NewRouter(ctx, config)
|
router, moduleErrors, routeErrors := showbridge.NewRouter(context.Background(), config)
|
||||||
|
|
||||||
for _, moduleError := range moduleErrors {
|
for _, moduleError := range moduleErrors {
|
||||||
logger.Error("problem initializing module", "index", moduleError.Index, "error", moduleError.Error)
|
commandLogger.Error("problem initializing module", "index", moduleError.Index, "error", moduleError.Error)
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, routeError := range routeErrors {
|
for _, routeError := range routeErrors {
|
||||||
logger.Error("problem initializing route", "index", routeError.Index, "error", routeError.Error)
|
commandLogger.Error("problem initializing route", "index", routeError.Index, "error", routeError.Error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
routerRunner := sync.WaitGroup{}
|
||||||
|
|
||||||
|
routerRunner.Go(func() {
|
||||||
router.Run()
|
router.Run()
|
||||||
|
})
|
||||||
|
|
||||||
|
<-ctx.Done()
|
||||||
|
commandLogger.Debug("shutting down router")
|
||||||
|
router.Stop()
|
||||||
|
commandLogger.Debug("waiting for router to exit")
|
||||||
|
routerRunner.Wait()
|
||||||
return nil
|
return nil
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Interrupt)
|
|
||||||
defer cancel()
|
|
||||||
err := cmd.Run(ctx, os.Args)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func readConfig(configPath string) (config.Config, error) {
|
|
||||||
cfg := config.Config{}
|
|
||||||
|
|
||||||
configBytes, err := os.ReadFile(configPath)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return config.Config{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = yaml.Unmarshal(configBytes, &cfg)
|
|
||||||
if err != nil {
|
|
||||||
return config.Config{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return cfg, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
3
go.mod
3
go.mod
@@ -1,12 +1,13 @@
|
|||||||
module github.com/jwetzell/showbridge-go
|
module github.com/jwetzell/showbridge-go
|
||||||
|
|
||||||
go 1.25.3
|
go 1.25.5
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||||
github.com/emiago/diago v0.23.1-0.20251211215055-e1d875617111
|
github.com/emiago/diago v0.23.1-0.20251211215055-e1d875617111
|
||||||
github.com/emiago/sipgo v1.0.1
|
github.com/emiago/sipgo v1.0.1
|
||||||
github.com/expr-lang/expr v1.17.7
|
github.com/expr-lang/expr v1.17.7
|
||||||
|
github.com/jwetzell/artnet-go v0.0.0-20251223201031-5097901aa9db
|
||||||
github.com/jwetzell/free-d-go v0.1.0
|
github.com/jwetzell/free-d-go v0.1.0
|
||||||
github.com/jwetzell/osc-go v0.1.0
|
github.com/jwetzell/osc-go v0.1.0
|
||||||
github.com/jwetzell/psn-go v0.3.0
|
github.com/jwetzell/psn-go v0.3.0
|
||||||
|
|||||||
2
go.sum
2
go.sum
@@ -30,6 +30,8 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs
|
|||||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||||
github.com/icholy/digest v1.1.0 h1:HfGg9Irj7i+IX1o1QAmPfIBNu/Q5A5Tu3n/MED9k9H4=
|
github.com/icholy/digest v1.1.0 h1:HfGg9Irj7i+IX1o1QAmPfIBNu/Q5A5Tu3n/MED9k9H4=
|
||||||
github.com/icholy/digest v1.1.0/go.mod h1:QNrsSGQ5v7v9cReDI0+eyjsXGUoRSUZQHeQ5C4XLa0Y=
|
github.com/icholy/digest v1.1.0/go.mod h1:QNrsSGQ5v7v9cReDI0+eyjsXGUoRSUZQHeQ5C4XLa0Y=
|
||||||
|
github.com/jwetzell/artnet-go v0.0.0-20251223201031-5097901aa9db h1:PR9sdDEWBufi8/3yiQHRXncLNKUHBMKiEBDtdNWsK/E=
|
||||||
|
github.com/jwetzell/artnet-go v0.0.0-20251223201031-5097901aa9db/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 h1:xHt6dvyit98X+OC3jVzV0aLidxbyzi3vI9QiYkteEtA=
|
||||||
github.com/jwetzell/free-d-go v0.1.0/go.mod h1:KmrkooRARRaxJTBSPvwt/6IMAIaHH1R8bSA8cwbbELw=
|
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 h1:EXxup5VWBErHot2Ri4MFToPf6KCzLDTbCt2x6GLfw8I=
|
||||||
|
|||||||
@@ -1,9 +1,5 @@
|
|||||||
package framer
|
package framer
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Framer interface {
|
type Framer interface {
|
||||||
Decode([]byte) [][]byte
|
Decode([]byte) [][]byte
|
||||||
Encode([]byte) []byte
|
Encode([]byte) []byte
|
||||||
@@ -11,19 +7,19 @@ type Framer interface {
|
|||||||
Buffer() []byte
|
Buffer() []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetFramer(framingType string) (Framer, error) {
|
func GetFramer(framingType string) Framer {
|
||||||
switch framingType {
|
switch framingType {
|
||||||
case "CR":
|
case "CR":
|
||||||
return NewByteSeparatorFramer([]byte{'\r'}), nil
|
return NewByteSeparatorFramer([]byte{'\r'})
|
||||||
case "LF":
|
case "LF":
|
||||||
return NewByteSeparatorFramer([]byte{'\n'}), nil
|
return NewByteSeparatorFramer([]byte{'\n'})
|
||||||
case "CRLF":
|
case "CRLF":
|
||||||
return NewByteSeparatorFramer([]byte{'\r', '\n'}), nil
|
return NewByteSeparatorFramer([]byte{'\r', '\n'})
|
||||||
case "SLIP":
|
case "SLIP":
|
||||||
return NewSlipFramer(), nil
|
return NewSlipFramer()
|
||||||
case "RAW":
|
case "RAW":
|
||||||
return NewRawFramer(), nil
|
return NewRawFramer()
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unknown framing method: %s", framingType)
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
15
internal/framer/framer_test.go
Normal file
15
internal/framer/framer_test.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package framer_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNilGetFramer(t *testing.T) {
|
||||||
|
nilFramer := framer.GetFramer("asldfiudchuehrkbjbkjrbb")
|
||||||
|
|
||||||
|
if nilFramer != nil {
|
||||||
|
t.Fatalf("Expected nil framer, got %v", nilFramer)
|
||||||
|
}
|
||||||
|
}
|
||||||
78
internal/framer/raw_test.go
Normal file
78
internal/framer/raw_test.go
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
package framer_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGoodRawFramerDecode(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
framer framer.Framer
|
||||||
|
input []byte
|
||||||
|
expected [][]byte
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "basic raw framer",
|
||||||
|
framer: framer.GetFramer("RAW"),
|
||||||
|
input: []byte("Hello\nWorld\nThis is a test\n"),
|
||||||
|
expected: [][]byte{
|
||||||
|
[]byte("Hello\nWorld\nThis is a test\n"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
frames := test.framer.Decode(test.input)
|
||||||
|
if len(frames) != len(test.expected) {
|
||||||
|
t.Fatalf("raw framer got %d frames, expected %d", len(frames), len(test.expected))
|
||||||
|
}
|
||||||
|
for i, frame := range frames {
|
||||||
|
if !slices.Equal(frame, test.expected[i]) {
|
||||||
|
t.Errorf("raw framer frame %d got %s, expected %s", i, frame, test.expected[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGoodRawFramerEncode(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
framer framer.Framer
|
||||||
|
expected []byte
|
||||||
|
input []byte
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "basic raw framer",
|
||||||
|
framer: framer.GetFramer("RAW"),
|
||||||
|
expected: []byte("Hello\nWorld\nThis is a test\n"),
|
||||||
|
input: []byte("Hello\nWorld\nThis is a test\n"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
frame := test.framer.Encode(test.input)
|
||||||
|
if !slices.Equal(frame, test.expected) {
|
||||||
|
t.Fatalf("raw frame encode got %s, expected %s", frame, test.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRawFramerBuffer(t *testing.T) {
|
||||||
|
framer := framer.GetFramer("RAW")
|
||||||
|
framer.Decode([]byte("Hello, World!"))
|
||||||
|
|
||||||
|
if !slices.Equal(framer.Buffer(), []byte{}) {
|
||||||
|
t.Fatalf("raw framer buffer got %s, expected empty", framer.Buffer())
|
||||||
|
}
|
||||||
|
framer.Clear()
|
||||||
|
if !slices.Equal(framer.Buffer(), []byte{}) {
|
||||||
|
t.Fatalf("raw framer buffer got %s, expected empty after clear", framer.Buffer())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGoodSeparatorFramer(t *testing.T) {
|
func TestGoodSeparatorFramerDecode(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
framer framer.Framer
|
framer framer.Framer
|
||||||
@@ -17,7 +17,7 @@ func TestGoodSeparatorFramer(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "new line separator",
|
name: "new line separator",
|
||||||
framer: framer.NewByteSeparatorFramer([]byte{0x0a}),
|
framer: framer.GetFramer("LF"),
|
||||||
input: []byte("Hello\nWorld\nThis is a test\n"),
|
input: []byte("Hello\nWorld\nThis is a test\n"),
|
||||||
expected: [][]byte{
|
expected: [][]byte{
|
||||||
[]byte("Hello"),
|
[]byte("Hello"),
|
||||||
@@ -26,9 +26,20 @@ func TestGoodSeparatorFramer(t *testing.T) {
|
|||||||
},
|
},
|
||||||
buffer: []byte{},
|
buffer: []byte{},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "CR separator",
|
||||||
|
framer: framer.GetFramer("CR"),
|
||||||
|
input: []byte("Hello\rWorld\rThis is a test\r"),
|
||||||
|
expected: [][]byte{
|
||||||
|
[]byte("Hello"),
|
||||||
|
[]byte("World"),
|
||||||
|
[]byte("This is a test"),
|
||||||
|
},
|
||||||
|
buffer: []byte{},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "CRLF separator",
|
name: "CRLF separator",
|
||||||
framer: framer.NewByteSeparatorFramer([]byte{0x0d, 0x0a}),
|
framer: framer.GetFramer("CRLF"),
|
||||||
input: []byte("Hello\r\nWorld\r\nThis is a test\r\n"),
|
input: []byte("Hello\r\nWorld\r\nThis is a test\r\n"),
|
||||||
expected: [][]byte{
|
expected: [][]byte{
|
||||||
[]byte("Hello"),
|
[]byte("Hello"),
|
||||||
@@ -39,7 +50,7 @@ func TestGoodSeparatorFramer(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "extra data after separator",
|
name: "extra data after separator",
|
||||||
framer: framer.NewByteSeparatorFramer([]byte{0x0d, 0x0a}),
|
framer: framer.GetFramer("CRLF"),
|
||||||
input: []byte("Hello\r\nWorld\r\nThis is a test\r\nextra"),
|
input: []byte("Hello\r\nWorld\r\nThis is a test\r\nextra"),
|
||||||
expected: [][]byte{
|
expected: [][]byte{
|
||||||
[]byte("Hello"),
|
[]byte("Hello"),
|
||||||
@@ -54,7 +65,7 @@ func TestGoodSeparatorFramer(t *testing.T) {
|
|||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
frames := test.framer.Decode(test.input)
|
frames := test.framer.Decode(test.input)
|
||||||
if len(frames) != len(test.expected) {
|
if len(frames) != len(test.expected) {
|
||||||
t.Errorf("separator framer got %d frames, expected %d", len(frames), len(test.expected))
|
t.Fatalf("separator framer got %d frames, expected %d", len(frames), len(test.expected))
|
||||||
}
|
}
|
||||||
for i, frame := range frames {
|
for i, frame := range frames {
|
||||||
if !slices.Equal(frame, test.expected[i]) {
|
if !slices.Equal(frame, test.expected[i]) {
|
||||||
@@ -62,8 +73,58 @@ func TestGoodSeparatorFramer(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !slices.Equal(test.framer.Buffer(), test.buffer) {
|
if !slices.Equal(test.framer.Buffer(), test.buffer) {
|
||||||
t.Errorf("separator framer buffer got %s, expected %s", test.framer.Buffer(), test.buffer)
|
t.Fatalf("separator framer buffer got %s, expected %s", test.framer.Buffer(), test.buffer)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGoodSeparatorFramerEncode(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
framer framer.Framer
|
||||||
|
input []byte
|
||||||
|
expected []byte
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "new line separator",
|
||||||
|
framer: framer.GetFramer("LF"),
|
||||||
|
input: []byte("Hello"),
|
||||||
|
expected: []byte("Hello\n"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "CR separator",
|
||||||
|
framer: framer.GetFramer("CR"),
|
||||||
|
input: []byte("Hello"),
|
||||||
|
expected: []byte("Hello\r"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "CRLF separator",
|
||||||
|
framer: framer.GetFramer("CRLF"),
|
||||||
|
input: []byte("Hello"),
|
||||||
|
expected: []byte("Hello\r\n"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
frame := test.framer.Encode(test.input)
|
||||||
|
if !slices.Equal(frame, test.expected) {
|
||||||
|
t.Fatalf("separator framer got %s, expected %s", frame, test.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSeparatorFrameBuffer(t *testing.T) {
|
||||||
|
framer := framer.GetFramer("LF")
|
||||||
|
framer.Decode([]byte("Hello\nWorld\nThis is a test\nextra"))
|
||||||
|
if !slices.Equal(framer.Buffer(), []byte("extra")) {
|
||||||
|
t.Fatalf("separator framer buffer got %s, expected %s", framer.Buffer(), []byte("extra"))
|
||||||
|
}
|
||||||
|
|
||||||
|
framer.Clear()
|
||||||
|
if !slices.Equal(framer.Buffer(), []byte{}) {
|
||||||
|
t.Fatalf("separator framer buffer got %s, expected empty slice", framer.Buffer())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -59,9 +59,9 @@ func (sf *SlipFramer) Encode(data []byte) []byte {
|
|||||||
for _, byteToEncode := range data {
|
for _, byteToEncode := range data {
|
||||||
switch byteToEncode {
|
switch byteToEncode {
|
||||||
case END:
|
case END:
|
||||||
encodedBytes = append(encodedBytes, ESC_END)
|
encodedBytes = append(encodedBytes, ESC, ESC_END)
|
||||||
case ESC:
|
case ESC:
|
||||||
encodedBytes = append(encodedBytes, ESC_ESC)
|
encodedBytes = append(encodedBytes, ESC, ESC_ESC)
|
||||||
default:
|
default:
|
||||||
encodedBytes = append(encodedBytes, byteToEncode)
|
encodedBytes = append(encodedBytes, byteToEncode)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGoodSLIPFramer(t *testing.T) {
|
func TestGoodSLIPFramerDecode(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
framer framer.Framer
|
framer framer.Framer
|
||||||
@@ -17,20 +17,34 @@ func TestGoodSLIPFramer(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "OSC SLIP messages",
|
name: "OSC SLIP messages",
|
||||||
framer: framer.NewSlipFramer(),
|
framer: framer.GetFramer("SLIP"),
|
||||||
input: []byte{0xc0, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0xc0},
|
input: []byte{0xc0, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0xc0},
|
||||||
expected: [][]byte{
|
expected: [][]byte{
|
||||||
{0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00},
|
{0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00},
|
||||||
},
|
},
|
||||||
buffer: []byte{},
|
buffer: []byte{},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "SLIP decode escaped end",
|
||||||
|
framer: framer.GetFramer("SLIP"),
|
||||||
|
expected: [][]byte{{0xc0}},
|
||||||
|
input: []byte{0xc0, 0xdb, 0xdc, 0xc0},
|
||||||
|
buffer: []byte{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "SLIP decode escaped escape",
|
||||||
|
framer: framer.GetFramer("SLIP"),
|
||||||
|
expected: [][]byte{{0xdb}},
|
||||||
|
input: []byte{0xc0, 0xdb, 0xdd, 0xc0},
|
||||||
|
buffer: []byte{},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
frames := test.framer.Decode(test.input)
|
frames := test.framer.Decode(test.input)
|
||||||
if len(frames) != len(test.expected) {
|
if len(frames) != len(test.expected) {
|
||||||
t.Errorf("SLIP framer got %d frames, expected %d", len(frames), len(test.expected))
|
t.Fatalf("SLIP framer got %d frames, expected %d", len(frames), len(test.expected))
|
||||||
}
|
}
|
||||||
for i, frame := range frames {
|
for i, frame := range frames {
|
||||||
if !slices.Equal(frame, test.expected[i]) {
|
if !slices.Equal(frame, test.expected[i]) {
|
||||||
@@ -38,8 +52,59 @@ func TestGoodSLIPFramer(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !slices.Equal(test.framer.Buffer(), test.buffer) {
|
if !slices.Equal(test.framer.Buffer(), test.buffer) {
|
||||||
t.Errorf("SLIP framer buffer got %s, expected %s", test.framer.Buffer(), test.buffer)
|
t.Fatalf("SLIP framer buffer got %s, expected %s", test.framer.Buffer(), test.buffer)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGoodSLIPFramerEncode(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
framer framer.Framer
|
||||||
|
input []byte
|
||||||
|
expected []byte
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "OSC SLIP messages",
|
||||||
|
framer: framer.GetFramer("SLIP"),
|
||||||
|
input: []byte{
|
||||||
|
0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00,
|
||||||
|
},
|
||||||
|
expected: []byte{0xc0, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0xc0},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "SLIP encode end",
|
||||||
|
framer: framer.GetFramer("SLIP"),
|
||||||
|
input: []byte{0xc0},
|
||||||
|
expected: []byte{0xc0, 0xdb, 0xdc, 0xc0},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "SLIP encode esc",
|
||||||
|
framer: framer.GetFramer("SLIP"),
|
||||||
|
input: []byte{0xdb},
|
||||||
|
expected: []byte{0xc0, 0xdb, 0xdd, 0xc0},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
frame := test.framer.Encode(test.input)
|
||||||
|
if !slices.Equal(frame, test.expected) {
|
||||||
|
t.Fatalf("SLIP framer frame got %s, expected %s", frame, test.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSlipFramerBuffer(t *testing.T) {
|
||||||
|
framer := framer.GetFramer("SLIP")
|
||||||
|
framer.Decode([]byte{0xc0, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0xc0, 0xc0, 0x45})
|
||||||
|
if !slices.Equal(framer.Buffer(), []byte{0x45}) {
|
||||||
|
t.Fatalf("SLIP framer buffer got %s, expected %s", framer.Buffer(), []byte{0x45})
|
||||||
|
}
|
||||||
|
framer.Clear()
|
||||||
|
if !slices.Equal(framer.Buffer(), []byte{}) {
|
||||||
|
t.Fatalf("SLIP framer buffer got %s, expected empty slice", framer.Buffer())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -22,9 +22,15 @@ type HTTPClient struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "http.client",
|
Type: "http.client",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
|
|
||||||
return &HTTPClient{config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("http.client unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &HTTPClient{config: config, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -44,11 +50,11 @@ func (hc *HTTPClient) Run() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
<-hc.ctx.Done()
|
<-hc.ctx.Done()
|
||||||
hc.logger.Debug("router context done in module")
|
hc.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HTTPClient) Output(payload any) error {
|
func (hc *HTTPClient) Output(ctx context.Context, payload any) error {
|
||||||
|
|
||||||
payloadRequest, ok := payload.(*http.Request)
|
payloadRequest, ok := payload.(*http.Request)
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ type ResponseData struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "http.server",
|
Type: "http.server",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
port, ok := params["port"]
|
port, ok := params["port"]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -41,7 +41,13 @@ func init() {
|
|||||||
return nil, errors.New("http.server port must be uint16")
|
return nil, errors.New("http.server port must be uint16")
|
||||||
}
|
}
|
||||||
|
|
||||||
return &HTTPServer{Port: uint16(portNum), config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("http.server unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &HTTPServer{Port: uint16(portNum), config: config, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -54,7 +60,7 @@ func (hs *HTTPServer) Type() string {
|
|||||||
return hs.config.Type
|
return hs.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hs *HTTPServer) HandleDefault(w http.ResponseWriter, r *http.Request) {
|
func (hs *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
response := ResponseData{
|
response := ResponseData{
|
||||||
@@ -82,29 +88,29 @@ func (hs *HTTPServer) HandleDefault(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hs *HTTPServer) Run() error {
|
func (hs *HTTPServer) Run() error {
|
||||||
http.HandleFunc("/", hs.HandleDefault)
|
|
||||||
|
|
||||||
httpServer := &http.Server{
|
httpServer := &http.Server{
|
||||||
Addr: fmt.Sprintf(":%d", hs.Port),
|
Addr: fmt.Sprintf(":%d", hs.Port),
|
||||||
Handler: http.DefaultServeMux,
|
Handler: hs,
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
<-hs.ctx.Done()
|
<-hs.ctx.Done()
|
||||||
hs.logger.Debug("router context done in module")
|
|
||||||
httpServer.Close()
|
httpServer.Close()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
err := httpServer.ListenAndServe()
|
err := httpServer.ListenAndServe()
|
||||||
// TODO(jwetzell): handle server closed error differently
|
// TODO(jwetzell): handle server closed error differently
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if err.Error() != "http: Server closed" {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
<-hs.ctx.Done()
|
<-hs.ctx.Done()
|
||||||
|
hs.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hs *HTTPServer) Output(payload any) error {
|
func (hs *HTTPServer) Output(ctx context.Context, payload any) error {
|
||||||
return errors.New("http.server output is not implemented")
|
return errors.New("http.server output is not implemented")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ type MIDIInput struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "midi.input",
|
Type: "midi.input",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
port, ok := params["port"]
|
port, ok := params["port"]
|
||||||
|
|
||||||
@@ -40,7 +40,13 @@ func init() {
|
|||||||
return nil, errors.New("midi.input port must be a string")
|
return nil, errors.New("midi.input port must be a string")
|
||||||
}
|
}
|
||||||
|
|
||||||
return &MIDIInput{config: config, Port: portString, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("midi.input unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &MIDIInput{config: config, Port: portString, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -74,10 +80,10 @@ func (mi *MIDIInput) Run() error {
|
|||||||
defer stop()
|
defer stop()
|
||||||
|
|
||||||
<-mi.ctx.Done()
|
<-mi.ctx.Done()
|
||||||
mi.logger.Debug("router context done in module")
|
mi.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mi *MIDIInput) Output(payload any) error {
|
func (mi *MIDIInput) Output(ctx context.Context, payload any) error {
|
||||||
return errors.New("midi.input output is not implemented")
|
return errors.New("midi.input output is not implemented")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ type MIDIOutput struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "midi.output",
|
Type: "midi.output",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
|
|
||||||
port, ok := params["port"]
|
port, ok := params["port"]
|
||||||
@@ -41,7 +41,13 @@ func init() {
|
|||||||
return nil, errors.New("midi.output port must be a string")
|
return nil, errors.New("midi.output port must be a string")
|
||||||
}
|
}
|
||||||
|
|
||||||
return &MIDIOutput{config: config, Port: portString, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("midi.output unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &MIDIOutput{config: config, Port: portString, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -71,11 +77,11 @@ func (mo *MIDIOutput) Run() error {
|
|||||||
mo.SendFunc = send
|
mo.SendFunc = send
|
||||||
|
|
||||||
<-mo.ctx.Done()
|
<-mo.ctx.Done()
|
||||||
mo.logger.Debug("router context done in module")
|
mo.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mo *MIDIOutput) Output(payload any) error {
|
func (mo *MIDIOutput) Output(ctx context.Context, payload any) error {
|
||||||
if mo.SendFunc == nil {
|
if mo.SendFunc == nil {
|
||||||
return errors.New("midi.output output is not setup")
|
return errors.New("midi.output output is not setup")
|
||||||
}
|
}
|
||||||
@@ -3,10 +3,10 @@ package module
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/jwetzell/showbridge-go/internal/config"
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
"github.com/jwetzell/showbridge-go/internal/route"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type ModuleError struct {
|
type ModuleError struct {
|
||||||
@@ -19,12 +19,12 @@ type Module interface {
|
|||||||
Id() string
|
Id() string
|
||||||
Type() string
|
Type() string
|
||||||
Run() error
|
Run() error
|
||||||
Output(any) error
|
Output(context.Context, any) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type ModuleRegistration struct {
|
type ModuleRegistration struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
New func(context.Context, config.ModuleConfig, route.RouteIO) (Module, error)
|
New func(context.Context, config.ModuleConfig) (Module, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func RegisterModule(mod ModuleRegistration) {
|
func RegisterModule(mod ModuleRegistration) {
|
||||||
@@ -49,3 +49,7 @@ var (
|
|||||||
moduleRegistryMu sync.RWMutex
|
moduleRegistryMu sync.RWMutex
|
||||||
ModuleRegistry = make(map[string]ModuleRegistration)
|
ModuleRegistry = make(map[string]ModuleRegistration)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func CreateLogger(config config.ModuleConfig) *slog.Logger {
|
||||||
|
return slog.Default().With("component", "module", "id", config.Id, "type", config.Type)
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package module
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
|
||||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||||
@@ -25,7 +24,7 @@ type MQTTClient struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "mqtt.client",
|
Type: "mqtt.client",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
broker, ok := params["broker"]
|
broker, ok := params["broker"]
|
||||||
|
|
||||||
@@ -63,7 +62,13 @@ func init() {
|
|||||||
return nil, errors.New("mqtt.client clientId must be string")
|
return nil, errors.New("mqtt.client clientId must be string")
|
||||||
}
|
}
|
||||||
|
|
||||||
return &MQTTClient{config: config, Broker: brokerString, Topic: topicString, ClientID: clientIdString, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("mqtt.client unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &MQTTClient{config: config, Broker: brokerString, Topic: topicString, ClientID: clientIdString, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -101,15 +106,13 @@ func (mc *MQTTClient) Run() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
<-mc.ctx.Done()
|
<-mc.ctx.Done()
|
||||||
mc.logger.Debug("router context done in module")
|
mc.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mc *MQTTClient) Output(payload any) error {
|
func (mc *MQTTClient) Output(ctx context.Context, payload any) error {
|
||||||
payloadMessage, ok := payload.(mqtt.Message)
|
payloadMessage, ok := payload.(mqtt.Message)
|
||||||
|
|
||||||
fmt.Printf("payload type: %T\n", payload)
|
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
return errors.New("mqtt.client is only able to output a MQTTMessage")
|
return errors.New("mqtt.client is only able to output a MQTTMessage")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ type NATSClient struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "nats.client",
|
Type: "nats.client",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
url, ok := params["url"]
|
url, ok := params["url"]
|
||||||
|
|
||||||
@@ -50,7 +50,13 @@ func init() {
|
|||||||
return nil, errors.New("nats.client subject must be string")
|
return nil, errors.New("nats.client subject must be string")
|
||||||
}
|
}
|
||||||
|
|
||||||
return &NATSClient{config: config, URL: urlString, Subject: subjectString, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("nats.client unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &NATSClient{config: config, URL: urlString, Subject: subjectString, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -88,11 +94,11 @@ func (nc *NATSClient) Run() error {
|
|||||||
defer sub.Unsubscribe()
|
defer sub.Unsubscribe()
|
||||||
|
|
||||||
<-nc.ctx.Done()
|
<-nc.ctx.Done()
|
||||||
nc.logger.Debug("router context done in module")
|
nc.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (nc *NATSClient) Output(payload any) error {
|
func (nc *NATSClient) Output(ctx context.Context, payload any) error {
|
||||||
|
|
||||||
payloadMessage, ok := payload.(processor.NATSMessage)
|
payloadMessage, ok := payload.(processor.NATSMessage)
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package module
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
@@ -24,9 +25,13 @@ type PSNClient struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "psn.client",
|
Type: "psn.client",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
return &PSNClient{config: config, decoder: psn.NewDecoder(), ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
if !ok {
|
||||||
|
return nil, errors.New("psn.client unable to get router from context")
|
||||||
|
}
|
||||||
|
return &PSNClient{config: config, decoder: psn.NewDecoder(), ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -59,7 +64,7 @@ func (pc *PSNClient) Run() error {
|
|||||||
select {
|
select {
|
||||||
case <-pc.ctx.Done():
|
case <-pc.ctx.Done():
|
||||||
// TODO(jwetzell): cleanup?
|
// TODO(jwetzell): cleanup?
|
||||||
pc.logger.Debug("router context done in module")
|
pc.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
default:
|
default:
|
||||||
pc.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
pc.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||||
@@ -77,7 +82,7 @@ func (pc *PSNClient) Run() error {
|
|||||||
message := buffer[:numBytes]
|
message := buffer[:numBytes]
|
||||||
err := pc.decoder.Decode(message)
|
err := pc.decoder.Decode(message)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pc.logger.Error("psn.client problem decoding psn traffic", "error", err)
|
pc.logger.Error("problem decoding psn traffic", "error", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if pc.router != nil {
|
if pc.router != nil {
|
||||||
@@ -85,13 +90,13 @@ func (pc *PSNClient) Run() error {
|
|||||||
pc.router.HandleInput(pc.Id(), tracker)
|
pc.router.HandleInput(pc.Id(), tracker)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
pc.logger.Error("psn.client has no router")
|
pc.logger.Error("has no router")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pc *PSNClient) Output(payload any) error {
|
func (pc *PSNClient) Output(ctx context.Context, payload any) error {
|
||||||
return fmt.Errorf("psn.client output is not implemented")
|
return fmt.Errorf("psn.client output is not implemented")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ type SerialClient struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "serial.client",
|
Type: "serial.client",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
port, ok := params["port"]
|
port, ok := params["port"]
|
||||||
|
|
||||||
@@ -56,10 +56,10 @@ func init() {
|
|||||||
framingMethod = framingMethodString
|
framingMethod = framingMethodString
|
||||||
}
|
}
|
||||||
|
|
||||||
framer, err := framer.GetFramer(framingMethod)
|
framer := framer.GetFramer(framingMethod)
|
||||||
|
|
||||||
if err != nil {
|
if framer == nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("serial.client unknown framing method: %s", framingMethod)
|
||||||
}
|
}
|
||||||
|
|
||||||
buadRate, ok := params["baudRate"]
|
buadRate, ok := params["baudRate"]
|
||||||
@@ -76,7 +76,13 @@ func init() {
|
|||||||
BaudRate: int(baudRateNum),
|
BaudRate: int(baudRateNum),
|
||||||
}
|
}
|
||||||
|
|
||||||
return &SerialClient{config: config, Port: portString, Framer: framer, Mode: &mode, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("serial.client unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &SerialClient{config: config, Port: portString, Framer: framer, Mode: &mode, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -106,7 +112,7 @@ func (sc *SerialClient) Run() error {
|
|||||||
// TODO(jwetzell): shutdown with router.Context properly
|
// TODO(jwetzell): shutdown with router.Context properly
|
||||||
go func() {
|
go func() {
|
||||||
<-sc.ctx.Done()
|
<-sc.ctx.Done()
|
||||||
sc.logger.Debug("router context done in module")
|
sc.logger.Debug("done")
|
||||||
if sc.port != nil {
|
if sc.port != nil {
|
||||||
sc.port.Close()
|
sc.port.Close()
|
||||||
}
|
}
|
||||||
@@ -116,10 +122,10 @@ func (sc *SerialClient) Run() error {
|
|||||||
err := sc.SetupPort()
|
err := sc.SetupPort()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if sc.ctx.Err() != nil {
|
if sc.ctx.Err() != nil {
|
||||||
sc.logger.Debug("router context done in module")
|
sc.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
sc.logger.Error("serial.client", "error", err.Error())
|
sc.logger.Error("port setup error", "error", err.Error())
|
||||||
time.Sleep(time.Second * 2)
|
time.Sleep(time.Second * 2)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -127,14 +133,14 @@ func (sc *SerialClient) Run() error {
|
|||||||
buffer := make([]byte, 1024)
|
buffer := make([]byte, 1024)
|
||||||
select {
|
select {
|
||||||
case <-sc.ctx.Done():
|
case <-sc.ctx.Done():
|
||||||
sc.logger.Debug("router context done in module")
|
sc.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
default:
|
default:
|
||||||
READ:
|
READ:
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-sc.ctx.Done():
|
case <-sc.ctx.Done():
|
||||||
sc.logger.Debug("router context done in module")
|
sc.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
default:
|
default:
|
||||||
byteCount, err := sc.port.Read(buffer)
|
byteCount, err := sc.port.Read(buffer)
|
||||||
@@ -151,7 +157,7 @@ func (sc *SerialClient) Run() error {
|
|||||||
if sc.router != nil {
|
if sc.router != nil {
|
||||||
sc.router.HandleInput(sc.Id(), message)
|
sc.router.HandleInput(sc.Id(), message)
|
||||||
} else {
|
} else {
|
||||||
sc.logger.Error("serial.client has no router")
|
sc.logger.Error("input received but no router is configured")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -162,7 +168,7 @@ func (sc *SerialClient) Run() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sc *SerialClient) Output(payload any) error {
|
func (sc *SerialClient) Output(ctx context.Context, payload any) error {
|
||||||
|
|
||||||
payloadBytes, ok := payload.([]byte)
|
payloadBytes, ok := payload.([]byte)
|
||||||
|
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ type SIPCallMessage struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "sip.call.server",
|
Type: "sip.call.server",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
portNum := 5060
|
portNum := 5060
|
||||||
|
|
||||||
@@ -87,7 +87,13 @@ func init() {
|
|||||||
}
|
}
|
||||||
userAgentString = specificTransportString
|
userAgentString = specificTransportString
|
||||||
}
|
}
|
||||||
return &SIPCallServer{config: config, ctx: ctx, router: router, IP: ipString, Port: int(portNum), Transport: transportString, UserAgent: userAgentString, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
|
||||||
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("sip.call.server unable to get router from context")
|
||||||
|
}
|
||||||
|
return &SIPCallServer{config: config, ctx: ctx, router: router, IP: ipString, Port: int(portNum), Transport: transportString, UserAgent: userAgentString, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -129,7 +135,7 @@ func (scs *SIPCallServer) Run() error {
|
|||||||
scs.dg = dg
|
scs.dg = dg
|
||||||
|
|
||||||
<-scs.ctx.Done()
|
<-scs.ctx.Done()
|
||||||
scs.logger.Debug("router context done in module")
|
scs.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,7 +149,7 @@ func (scs *SIPCallServer) HandleCall(inDialog *diago.DialogServerSession) {
|
|||||||
<-inDialog.Context().Done()
|
<-inDialog.Context().Done()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (scs *SIPCallServer) Output(payload any) error {
|
func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||||
|
|
||||||
payloadMsg, ok := payload.(string)
|
payloadMsg, ok := payload.(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ type SIPDTMFMessage struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "sip.dtmf.server",
|
Type: "sip.dtmf.server",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
portNum := 5060
|
portNum := 5060
|
||||||
|
|
||||||
@@ -91,7 +91,12 @@ func init() {
|
|||||||
if !strings.ContainsRune("0123456789*#ABCD", rune(separatorString[0])) {
|
if !strings.ContainsRune("0123456789*#ABCD", rune(separatorString[0])) {
|
||||||
return nil, errors.New("sip.dtmf.server separator must be a valid DTMF character")
|
return nil, errors.New("sip.dtmf.server separator must be a valid DTMF character")
|
||||||
}
|
}
|
||||||
return &SIPDTMFServer{config: config, ctx: ctx, router: router, IP: ipString, Port: int(portNum), Transport: transportString, Separator: separatorString, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("sip.dtmf.server unable to get router from context")
|
||||||
|
}
|
||||||
|
return &SIPDTMFServer{config: config, ctx: ctx, router: router, IP: ipString, Port: int(portNum), Transport: transportString, Separator: separatorString, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -132,7 +137,7 @@ func (sds *SIPDTMFServer) Run() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
<-sds.ctx.Done()
|
<-sds.ctx.Done()
|
||||||
sds.logger.Debug("router context done in module")
|
sds.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,6 +164,6 @@ func (sds *SIPDTMFServer) HandleCall(inDialog *diago.DialogServerSession) error
|
|||||||
}, 5*time.Second)
|
}, 5*time.Second)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sds *SIPDTMFServer) Output(payload any) error {
|
func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||||
return errors.New("sip.dtmf.server output is not implemented")
|
return errors.New("sip.dtmf.server output is not implemented")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ type TCPClient struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "net.tcp.client",
|
Type: "net.tcp.client",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
host, ok := params["host"]
|
host, ok := params["host"]
|
||||||
|
|
||||||
@@ -64,18 +64,24 @@ func init() {
|
|||||||
framingMethodString, ok := framingMethodRaw.(string)
|
framingMethodString, ok := framingMethodRaw.(string)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("misc.serial.client framing method must be a string")
|
return nil, errors.New("net.tcp.client framing method must be a string")
|
||||||
}
|
}
|
||||||
framingMethod = framingMethodString
|
framingMethod = framingMethodString
|
||||||
}
|
}
|
||||||
|
|
||||||
framer, err := framer.GetFramer(framingMethod)
|
framer := framer.GetFramer(framingMethod)
|
||||||
|
|
||||||
if err != nil {
|
if framer == nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("net.tcp.client unknown framing method: %s", framingMethod)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &TCPClient{framer: framer, Addr: addr, config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("net.tcp.client unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &TCPClient{framer: framer, Addr: addr, config: config, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -93,7 +99,7 @@ func (tc *TCPClient) Run() error {
|
|||||||
// TODO(jwetzell): shutdown with router.Context properly
|
// TODO(jwetzell): shutdown with router.Context properly
|
||||||
go func() {
|
go func() {
|
||||||
<-tc.ctx.Done()
|
<-tc.ctx.Done()
|
||||||
tc.logger.Debug("router context done in module")
|
tc.logger.Debug("done")
|
||||||
if tc.conn != nil {
|
if tc.conn != nil {
|
||||||
tc.conn.Close()
|
tc.conn.Close()
|
||||||
}
|
}
|
||||||
@@ -103,10 +109,10 @@ func (tc *TCPClient) Run() error {
|
|||||||
err := tc.SetupConn()
|
err := tc.SetupConn()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if tc.ctx.Err() != nil {
|
if tc.ctx.Err() != nil {
|
||||||
tc.logger.Debug("router context done in module")
|
tc.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
tc.logger.Error("net.tcp.client", "error", err.Error())
|
tc.logger.Error("connection error", "error", err.Error())
|
||||||
time.Sleep(time.Second * 2)
|
time.Sleep(time.Second * 2)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -114,14 +120,14 @@ func (tc *TCPClient) Run() error {
|
|||||||
buffer := make([]byte, 1024)
|
buffer := make([]byte, 1024)
|
||||||
select {
|
select {
|
||||||
case <-tc.ctx.Done():
|
case <-tc.ctx.Done():
|
||||||
tc.logger.Debug("router context done in module")
|
tc.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
default:
|
default:
|
||||||
READ:
|
READ:
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-tc.ctx.Done():
|
case <-tc.ctx.Done():
|
||||||
tc.logger.Debug("router context done in module")
|
tc.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
default:
|
default:
|
||||||
byteCount, err := tc.conn.Read(buffer)
|
byteCount, err := tc.conn.Read(buffer)
|
||||||
@@ -138,7 +144,7 @@ func (tc *TCPClient) Run() error {
|
|||||||
if tc.router != nil {
|
if tc.router != nil {
|
||||||
tc.router.HandleInput(tc.Id(), message)
|
tc.router.HandleInput(tc.Id(), message)
|
||||||
} else {
|
} else {
|
||||||
tc.logger.Error("net.tcp.client has no router")
|
tc.logger.Error("input received but no router is configured")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -155,7 +161,7 @@ func (tc *TCPClient) SetupConn() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tc *TCPClient) Output(payload any) error {
|
func (tc *TCPClient) Output(ctx context.Context, payload any) error {
|
||||||
// NOTE(jwetzell): not sure how this would occur but
|
// NOTE(jwetzell): not sure how this would occur but
|
||||||
if tc.conn == nil {
|
if tc.conn == nil {
|
||||||
err := tc.SetupConn()
|
err := tc.SetupConn()
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ type TCPServer struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "net.tcp.server",
|
Type: "net.tcp.server",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
port, ok := params["port"]
|
port, ok := params["port"]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -53,15 +53,15 @@ func init() {
|
|||||||
framingMethodString, ok := framingMethodRaw.(string)
|
framingMethodString, ok := framingMethodRaw.(string)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("misc.serial.client framing method must be a string")
|
return nil, errors.New("net.tcp.server framing method must be a string")
|
||||||
}
|
}
|
||||||
framingMethod = framingMethodString
|
framingMethod = framingMethodString
|
||||||
}
|
}
|
||||||
|
|
||||||
framer, err := framer.GetFramer(framingMethod)
|
framer := framer.GetFramer(framingMethod)
|
||||||
|
|
||||||
if err != nil {
|
if framer == nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("net.tcp.server unknown framing method: %s", framingMethod)
|
||||||
}
|
}
|
||||||
|
|
||||||
ipString := "0.0.0.0"
|
ipString := "0.0.0.0"
|
||||||
@@ -82,7 +82,13 @@ func init() {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &TCPServer{Framer: framer, Addr: addr, config: config, quit: make(chan interface{}), ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("net.tcp.server unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &TCPServer{Framer: framer, Addr: addr, config: config, quit: make(chan interface{}), ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -126,7 +132,7 @@ ClientRead:
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ts.logger.Debug("net.tcp.server connection reset", "remoteAddr", client.RemoteAddr().String())
|
ts.logger.Debug("connection reset", "remoteAddr", client.RemoteAddr().String())
|
||||||
ts.connectionsMu.Unlock()
|
ts.connectionsMu.Unlock()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -139,7 +145,7 @@ ClientRead:
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ts.logger.Debug("net.tcp.server stream ended", "remoteAddr", client.RemoteAddr().String())
|
ts.logger.Debug("stream ended", "remoteAddr", client.RemoteAddr().String())
|
||||||
ts.connectionsMu.Unlock()
|
ts.connectionsMu.Unlock()
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
@@ -151,7 +157,7 @@ ClientRead:
|
|||||||
if ts.router != nil {
|
if ts.router != nil {
|
||||||
ts.router.HandleInput(ts.Id(), message)
|
ts.router.HandleInput(ts.Id(), message)
|
||||||
} else {
|
} else {
|
||||||
ts.logger.Error("net.tcp.server has no router")
|
ts.logger.Error("input received but no router is configured")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -171,7 +177,7 @@ func (ts *TCPServer) Run() error {
|
|||||||
<-ts.ctx.Done()
|
<-ts.ctx.Done()
|
||||||
close(ts.quit)
|
close(ts.quit)
|
||||||
listener.Close()
|
listener.Close()
|
||||||
ts.logger.Debug("router context done in module")
|
ts.logger.Debug("done")
|
||||||
}()
|
}()
|
||||||
|
|
||||||
AcceptLoop:
|
AcceptLoop:
|
||||||
@@ -182,7 +188,7 @@ AcceptLoop:
|
|||||||
case <-ts.quit:
|
case <-ts.quit:
|
||||||
break AcceptLoop
|
break AcceptLoop
|
||||||
default:
|
default:
|
||||||
ts.logger.Debug("net.tcp.server problem with listener", "error", err)
|
ts.logger.Debug("problem with listener", "error", err)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
ts.wg.Add(1)
|
ts.wg.Add(1)
|
||||||
@@ -197,7 +203,7 @@ AcceptLoop:
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ts *TCPServer) Output(payload any) error {
|
func (ts *TCPServer) Output(ctx context.Context, payload any) error {
|
||||||
payloadBytes, ok := payload.([]byte)
|
payloadBytes, ok := payload.([]byte)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
"github.com/jwetzell/showbridge-go/internal/route"
|
"github.com/jwetzell/showbridge-go/internal/route"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Interval struct {
|
type TimeInterval struct {
|
||||||
config config.ModuleConfig
|
config config.ModuleConfig
|
||||||
Duration uint32
|
Duration uint32
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
@@ -21,35 +21,41 @@ type Interval struct {
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "gen.interval",
|
Type: "time.interval",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
|
|
||||||
duration, ok := params["duration"]
|
duration, ok := params["duration"]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("gen.interval requires a duration parameter")
|
return nil, errors.New("time.interval requires a duration parameter")
|
||||||
}
|
}
|
||||||
|
|
||||||
durationNum, ok := duration.(float64)
|
durationNum, ok := duration.(float64)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("gen.interval duration must be number")
|
return nil, errors.New("time.interval duration must be number")
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Interval{Duration: uint32(durationNum), config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("time.interval unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &TimeInterval{Duration: uint32(durationNum), config: config, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Interval) Id() string {
|
func (i *TimeInterval) Id() string {
|
||||||
return i.config.Id
|
return i.config.Id
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Interval) Type() string {
|
func (i *TimeInterval) Type() string {
|
||||||
return i.config.Type
|
return i.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Interval) Run() error {
|
func (i *TimeInterval) Run() error {
|
||||||
ticker := time.NewTicker(time.Millisecond * time.Duration(i.Duration))
|
ticker := time.NewTicker(time.Millisecond * time.Duration(i.Duration))
|
||||||
i.ticker = ticker
|
i.ticker = ticker
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
@@ -57,7 +63,7 @@ func (i *Interval) Run() error {
|
|||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-i.ctx.Done():
|
case <-i.ctx.Done():
|
||||||
i.logger.Debug("router context done in module")
|
i.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
if i.router != nil {
|
if i.router != nil {
|
||||||
@@ -68,7 +74,7 @@ func (i *Interval) Run() error {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Interval) Output(payload any) error {
|
func (i *TimeInterval) Output(ctx context.Context, payload any) error {
|
||||||
i.ticker.Reset(time.Millisecond * time.Duration(i.Duration))
|
i.ticker.Reset(time.Millisecond * time.Duration(i.Duration))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
"github.com/jwetzell/showbridge-go/internal/route"
|
"github.com/jwetzell/showbridge-go/internal/route"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Timer struct {
|
type TimeTimer struct {
|
||||||
config config.ModuleConfig
|
config config.ModuleConfig
|
||||||
Duration uint32
|
Duration uint32
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
@@ -21,42 +21,48 @@ type Timer struct {
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "gen.timer",
|
Type: "time.timer",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
|
|
||||||
duration, ok := params["duration"]
|
duration, ok := params["duration"]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("gen.timer requires a duration parameter")
|
return nil, errors.New("time.timer requires a duration parameter")
|
||||||
}
|
}
|
||||||
|
|
||||||
durationNum, ok := duration.(float64)
|
durationNum, ok := duration.(float64)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("gen.timer duration must be a number")
|
return nil, errors.New("time.timer duration must be a number")
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Timer{Duration: uint32(durationNum), config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("net.tcp.client unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &TimeTimer{Duration: uint32(durationNum), config: config, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Timer) Id() string {
|
func (t *TimeTimer) Id() string {
|
||||||
return t.config.Id
|
return t.config.Id
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Timer) Type() string {
|
func (t *TimeTimer) Type() string {
|
||||||
return t.config.Type
|
return t.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Timer) Run() error {
|
func (t *TimeTimer) Run() error {
|
||||||
t.timer = time.NewTimer(time.Millisecond * time.Duration(t.Duration))
|
t.timer = time.NewTimer(time.Millisecond * time.Duration(t.Duration))
|
||||||
defer t.timer.Stop()
|
defer t.timer.Stop()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-t.ctx.Done():
|
case <-t.ctx.Done():
|
||||||
t.timer.Stop()
|
t.timer.Stop()
|
||||||
t.logger.Debug("router context done in module")
|
t.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
case time := <-t.timer.C:
|
case time := <-t.timer.C:
|
||||||
if t.router != nil {
|
if t.router != nil {
|
||||||
@@ -66,7 +72,7 @@ func (t *Timer) Run() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Timer) Output(payload any) error {
|
func (t *TimeTimer) Output(ctx context.Context, payload any) error {
|
||||||
t.timer.Reset(time.Millisecond * time.Duration(t.Duration))
|
t.timer.Reset(time.Millisecond * time.Duration(t.Duration))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@ type UDPClient struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "net.udp.client",
|
Type: "net.udp.client",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
host, ok := params["host"]
|
host, ok := params["host"]
|
||||||
|
|
||||||
@@ -54,7 +54,13 @@ func init() {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &UDPClient{Addr: addr, config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("net.udp.client unable to get router from context")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &UDPClient{Addr: addr, config: config, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -81,14 +87,14 @@ func (uc *UDPClient) Run() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
<-uc.ctx.Done()
|
<-uc.ctx.Done()
|
||||||
uc.logger.Debug("router context done in module")
|
uc.logger.Debug("done")
|
||||||
if uc.conn != nil {
|
if uc.conn != nil {
|
||||||
uc.conn.Close()
|
uc.conn.Close()
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (uc *UDPClient) Output(payload any) error {
|
func (uc *UDPClient) Output(ctx context.Context, payload any) error {
|
||||||
|
|
||||||
payloadBytes, ok := payload.([]byte)
|
payloadBytes, ok := payload.([]byte)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ type UDPMulticast struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "net.udp.multicast",
|
Type: "net.udp.multicast",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
ip, ok := params["ip"]
|
ip, ok := params["ip"]
|
||||||
|
|
||||||
@@ -53,7 +53,13 @@ func init() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &UDPMulticast{config: config, Addr: addr, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
|
||||||
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("net.udp.multicast unable to get router from context")
|
||||||
|
}
|
||||||
|
return &UDPMulticast{config: config, Addr: addr, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -81,7 +87,7 @@ func (um *UDPMulticast) Run() error {
|
|||||||
select {
|
select {
|
||||||
case <-um.ctx.Done():
|
case <-um.ctx.Done():
|
||||||
// TODO(jwetzell): cleanup?
|
// TODO(jwetzell): cleanup?
|
||||||
um.logger.Debug("router context done in module")
|
um.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
default:
|
default:
|
||||||
um.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
um.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||||
@@ -101,14 +107,14 @@ func (um *UDPMulticast) Run() error {
|
|||||||
if um.router != nil {
|
if um.router != nil {
|
||||||
um.router.HandleInput(um.Id(), message)
|
um.router.HandleInput(um.Id(), message)
|
||||||
} else {
|
} else {
|
||||||
um.logger.Error("net.udp.multicast has no router")
|
um.logger.Error("input received but no router is configured")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (um *UDPMulticast) Output(payload any) error {
|
func (um *UDPMulticast) Output(ctx context.Context, payload any) error {
|
||||||
|
|
||||||
payloadBytes, ok := payload.([]byte)
|
payloadBytes, ok := payload.([]byte)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ type UDPServer struct {
|
|||||||
func init() {
|
func init() {
|
||||||
RegisterModule(ModuleRegistration{
|
RegisterModule(ModuleRegistration{
|
||||||
Type: "net.udp.server",
|
Type: "net.udp.server",
|
||||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
New: func(ctx context.Context, config config.ModuleConfig) (Module, error) {
|
||||||
params := config.Params
|
params := config.Params
|
||||||
port, ok := params["port"]
|
port, ok := params["port"]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -68,7 +68,12 @@ func init() {
|
|||||||
bufferSizeNum = int(bufferSizeFloat)
|
bufferSizeNum = int(bufferSizeFloat)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &UDPServer{Addr: addr, BufferSize: bufferSizeNum, config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
router, ok := ctx.Value(route.RouterContextKey).(route.RouteIO)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("net.udp.server unable to get router from context")
|
||||||
|
}
|
||||||
|
return &UDPServer{Addr: addr, BufferSize: bufferSizeNum, config: config, ctx: ctx, router: router, logger: CreateLogger(config)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -95,7 +100,7 @@ func (us *UDPServer) Run() error {
|
|||||||
select {
|
select {
|
||||||
case <-us.ctx.Done():
|
case <-us.ctx.Done():
|
||||||
// TODO(jwetzell): cleanup?
|
// TODO(jwetzell): cleanup?
|
||||||
us.logger.Debug("router context done in module")
|
us.logger.Debug("done")
|
||||||
return nil
|
return nil
|
||||||
default:
|
default:
|
||||||
listener.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
listener.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||||
@@ -112,13 +117,13 @@ func (us *UDPServer) Run() error {
|
|||||||
if us.router != nil {
|
if us.router != nil {
|
||||||
us.router.HandleInput(us.Id(), message)
|
us.router.HandleInput(us.Id(), message)
|
||||||
} else {
|
} else {
|
||||||
us.logger.Error("net.udp.server has no router")
|
us.logger.Error("input received but no router is configured")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (us *UDPServer) Output(payload any) error {
|
func (us *UDPServer) Output(ctx context.Context, payload any) error {
|
||||||
return errors.New("net.udp.server output is not implemented")
|
return errors.New("net.udp.server output is not implemented")
|
||||||
}
|
}
|
||||||
|
|||||||
42
internal/processor/artnet-packet-decode.go
Normal file
42
internal/processor/artnet-packet-decode.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jwetzell/artnet-go"
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ArtNetPacketDecode struct {
|
||||||
|
config config.ProcessorConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (apd *ArtNetPacketDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||||
|
payloadBytes, ok := payload.([]byte)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("artnet.packet.decode processor only accepts a []byte")
|
||||||
|
}
|
||||||
|
|
||||||
|
payloadMessage, err := artnet.Decode(payloadBytes)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return payloadMessage, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (apd *ArtNetPacketDecode) Type() string {
|
||||||
|
return apd.config.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RegisterProcessor(ProcessorRegistration{
|
||||||
|
Type: "artnet.packet.decode",
|
||||||
|
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||||
|
return &ArtNetPacketDecode{config: config}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
41
internal/processor/artnet-packet-encode.go
Normal file
41
internal/processor/artnet-packet-encode.go
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jwetzell/artnet-go"
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ArtNetPacketEncode struct {
|
||||||
|
config config.ProcessorConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ape *ArtNetPacketEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||||
|
payloadPacket, ok := payload.(artnet.ArtNetPacket)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("artnet.packet.encode processor only accepts an ArtNetPacket")
|
||||||
|
}
|
||||||
|
|
||||||
|
payloadBytes, err := payloadPacket.MarshalBinary()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return payloadBytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ape *ArtNetPacketEncode) Type() string {
|
||||||
|
return ape.config.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RegisterProcessor(ProcessorRegistration{
|
||||||
|
Type: "artnet.packet.encode",
|
||||||
|
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||||
|
return &ArtNetPacketEncode{config: config}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
52
internal/processor/artnet-packet-filter.go
Normal file
52
internal/processor/artnet-packet-filter.go
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
opCode, ok := params["opCode"]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("artnet.packet.filter requires an opCode parameter")
|
||||||
|
}
|
||||||
|
opCodeNum, ok := opCode.(float64)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("artnet.packet.filter opCode must be a number")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ArtNetPacketFilter{config: config, OpCode: uint16(opCodeNum)}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ type DebugLog struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (dl *DebugLog) Process(ctx context.Context, payload any) (any, error) {
|
func (dl *DebugLog) Process(ctx context.Context, payload any) (any, error) {
|
||||||
dl.logger.Debug("debug.log", "payload", payload, "payloadType", fmt.Sprintf("%T", payload))
|
dl.logger.Debug("", "payload", payload, "payloadType", fmt.Sprintf("%T", payload))
|
||||||
return payload, nil
|
return payload, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ func init() {
|
|||||||
RegisterProcessor(ProcessorRegistration{
|
RegisterProcessor(ProcessorRegistration{
|
||||||
Type: "debug.log",
|
Type: "debug.log",
|
||||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||||
return &DebugLog{config: config, logger: slog.Default().With("component", "processor")}, nil
|
return &DebugLog{config: config, logger: slog.Default().With("component", "processor", "type", config.Type)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
39
internal/processor/debug-log_test.go
Normal file
39
internal/processor/debug-log_test.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package processor_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDebugLogFromRegistry(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["debug.log"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("debug.log processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "debug.log",
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create debug.log processor: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if processorInstance.Type() != "debug.log" {
|
||||||
|
t.Fatalf("debug.log processor has wrong type: %s", processorInstance.Type())
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := "test"
|
||||||
|
expected := "test"
|
||||||
|
|
||||||
|
got, err := processorInstance.Process(t.Context(), payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("debug.log processing failed: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got != expected {
|
||||||
|
t.Fatalf("debug.log got %+v, expected %+v", got, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,30 +3,107 @@ package processor_test
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestFloatParseFromRegistry(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["float.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("float.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "float.parse",
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create float.parse processor: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if processorInstance.Type() != "float.parse" {
|
||||||
|
t.Fatalf("float.parse processor has wrong type: %s", processorInstance.Type())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFloatParseBadConfigBitSizeString(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["float.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("float.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "float.parse",
|
||||||
|
Params: map[string]any{
|
||||||
|
"bitSize": "64",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("float.parse should have returned an error for bad bitSize config")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFloatParseGoodConfig(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["float.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("float.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "float.parse",
|
||||||
|
Params: map[string]any{
|
||||||
|
"bitSize": 64.0,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("float.parse should have created processor but got error: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := "12345.0"
|
||||||
|
expected := float64(12345.0)
|
||||||
|
|
||||||
|
got, err := processorInstance.Process(t.Context(), payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("float.parse processing failed: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
gotFloat, ok := got.(float64)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("float.parse returned a %T payload: %s", got, got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if gotFloat != expected {
|
||||||
|
t.Fatalf("float.parse got %f, expected %f", gotFloat, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGoodFloatParse(t *testing.T) {
|
func TestGoodFloatParse(t *testing.T) {
|
||||||
floatParser := processor.FloatParse{}
|
floatParser := processor.FloatParse{}
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
processor processor.Processor
|
processor processor.Processor
|
||||||
name string
|
name string
|
||||||
payload any
|
payload any
|
||||||
|
bitSize int
|
||||||
expected float64
|
expected float64
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "positive number",
|
name: "positive number",
|
||||||
payload: "12345.67",
|
payload: "12345.67",
|
||||||
|
bitSize: 64,
|
||||||
expected: 12345.67,
|
expected: 12345.67,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "negative number",
|
name: "negative number",
|
||||||
payload: "-12345.67",
|
payload: "-12345.67",
|
||||||
|
bitSize: 64,
|
||||||
expected: -12345.67,
|
expected: -12345.67,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "zero",
|
name: "zero",
|
||||||
payload: "0",
|
payload: "0",
|
||||||
|
bitSize: 64,
|
||||||
expected: 0,
|
expected: 0,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -37,48 +114,59 @@ func TestGoodFloatParse(t *testing.T) {
|
|||||||
|
|
||||||
gotFloat, ok := got.(float64)
|
gotFloat, ok := got.(float64)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Errorf("float.parse returned a %T payload: %s", got, got)
|
t.Fatalf("float.parse returned a %T payload: %s", got, got)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("float.parse failed: %s", err)
|
t.Fatalf("float.parse failed: %s", err)
|
||||||
}
|
}
|
||||||
if gotFloat != test.expected {
|
if gotFloat != test.expected {
|
||||||
t.Errorf("float.parse got %f, expected %f", gotFloat, test.expected)
|
t.Fatalf("float.parse got %f, expected %f", gotFloat, test.expected)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBadFloatParse(t *testing.T) {
|
func TestBadFloatParse(t *testing.T) {
|
||||||
floatParser := processor.FloatParse{}
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
processor processor.Processor
|
processor processor.Processor
|
||||||
name string
|
name string
|
||||||
payload any
|
payload any
|
||||||
|
bitSize int
|
||||||
errorString string
|
errorString string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "non-string input",
|
name: "non-string input",
|
||||||
payload: []byte{0x01},
|
payload: []byte{0x01},
|
||||||
|
bitSize: 64,
|
||||||
errorString: "float.parse processor only accepts a string",
|
errorString: "float.parse processor only accepts a string",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "not float string",
|
name: "not float string",
|
||||||
payload: "abcd",
|
payload: "abcd",
|
||||||
|
bitSize: 64,
|
||||||
errorString: "strconv.ParseFloat: parsing \"abcd\": invalid syntax",
|
errorString: "strconv.ParseFloat: parsing \"abcd\": invalid syntax",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "bit size overflow",
|
||||||
|
payload: "1.79e+64",
|
||||||
|
bitSize: 32,
|
||||||
|
errorString: "strconv.ParseFloat: parsing \"1.79e+64\": value out of range",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
floatParser := processor.FloatParse{
|
||||||
|
BitSize: test.bitSize,
|
||||||
|
}
|
||||||
got, err := floatParser.Process(t.Context(), test.payload)
|
got, err := floatParser.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("float.parse expected to fail but succeeded, got: %v", got)
|
t.Fatalf("float.parse expected to fail but succeeded, got: %v", got)
|
||||||
|
|
||||||
}
|
}
|
||||||
if err.Error() != test.errorString {
|
if err.Error() != test.errorString {
|
||||||
t.Errorf("float.parse got error '%s', expected '%s'", err.Error(), test.errorString)
|
t.Fatalf("float.parse got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,82 +3,216 @@ package processor_test
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestIntParseFromRegistry(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["int.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("int.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "int.parse",
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create int.parse processor: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if processorInstance.Type() != "int.parse" {
|
||||||
|
t.Fatalf("int.parse processor has wrong type: %s", processorInstance.Type())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIntParseBadConfigBaseString(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["int.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("int.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "int.parse",
|
||||||
|
Params: map[string]any{
|
||||||
|
"base": "10",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("int.parse should have returned an error for bad base config")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIntParseBadConfigBitSizeString(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["int.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("int.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "int.parse",
|
||||||
|
Params: map[string]any{
|
||||||
|
"bitSize": "64",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("int.parse should have returned an error for bad bitSize config")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIntParseGoodConfig(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["int.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("int.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "int.parse",
|
||||||
|
Params: map[string]any{
|
||||||
|
"base": 10.0,
|
||||||
|
"bitSize": 64.0,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("int.parse should have created processor but got error: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := "12345"
|
||||||
|
expected := int64(12345)
|
||||||
|
|
||||||
|
got, err := processorInstance.Process(t.Context(), payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("int.parse processing failed: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
gotInt, ok := got.(int64)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("int.parse returned a %T payload: %s", got, got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if gotInt != expected {
|
||||||
|
t.Fatalf("int.parse got %d, expected %d", gotInt, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGoodIntParse(t *testing.T) {
|
func TestGoodIntParse(t *testing.T) {
|
||||||
intParser := processor.IntParse{}
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
processor processor.Processor
|
processor processor.Processor
|
||||||
name string
|
name string
|
||||||
payload any
|
payload any
|
||||||
expected int64
|
expected int64
|
||||||
|
base int
|
||||||
|
bitSize int
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "positive number",
|
name: "positive number",
|
||||||
payload: "12345",
|
payload: "12345",
|
||||||
expected: 12345,
|
expected: 12345,
|
||||||
|
base: 10,
|
||||||
|
bitSize: 64,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "negative number",
|
name: "negative number",
|
||||||
payload: "-12345",
|
payload: "-12345",
|
||||||
expected: -12345,
|
expected: -12345,
|
||||||
|
base: 10,
|
||||||
|
bitSize: 64,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "zero",
|
name: "zero",
|
||||||
payload: "0",
|
payload: "0",
|
||||||
expected: 0,
|
expected: 0,
|
||||||
|
base: 10,
|
||||||
|
bitSize: 64,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "binary",
|
||||||
|
payload: "1010101",
|
||||||
|
expected: 85,
|
||||||
|
base: 2,
|
||||||
|
bitSize: 64,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "hex",
|
||||||
|
payload: "15F",
|
||||||
|
expected: 351,
|
||||||
|
base: 16,
|
||||||
|
bitSize: 64,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
intParser := processor.IntParse{
|
||||||
|
Base: test.base,
|
||||||
|
BitSize: test.bitSize,
|
||||||
|
}
|
||||||
|
|
||||||
got, err := intParser.Process(t.Context(), test.payload)
|
got, err := intParser.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
gotInt, ok := got.(int64)
|
gotInt, ok := got.(int64)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Errorf("int.parse returned a %T payload: %s", got, got)
|
t.Fatalf("int.parse returned a %T payload: %s", got, got)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("int.parse failed: %s", err)
|
t.Fatalf("int.parse failed: %s", err)
|
||||||
}
|
}
|
||||||
if gotInt != test.expected {
|
if gotInt != test.expected {
|
||||||
t.Errorf("int.parse got %d, expected %d", gotInt, test.expected)
|
t.Fatalf("int.parse got %d, expected %d", gotInt, test.expected)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBadIntParse(t *testing.T) {
|
func TestBadIntParse(t *testing.T) {
|
||||||
intParser := processor.IntParse{}
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
processor processor.Processor
|
processor processor.Processor
|
||||||
name string
|
name string
|
||||||
payload any
|
payload any
|
||||||
|
base int
|
||||||
|
bitSize int
|
||||||
errorString string
|
errorString string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "non-string input",
|
name: "non-string input",
|
||||||
payload: []byte{0x01},
|
payload: []byte{0x01},
|
||||||
|
base: 10,
|
||||||
|
bitSize: 64,
|
||||||
errorString: "int.parse processor only accepts a string",
|
errorString: "int.parse processor only accepts a string",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "not int string",
|
name: "not int string",
|
||||||
payload: "123.46",
|
payload: "123.46",
|
||||||
|
base: 10,
|
||||||
|
bitSize: 64,
|
||||||
errorString: "strconv.ParseInt: parsing \"123.46\": invalid syntax",
|
errorString: "strconv.ParseInt: parsing \"123.46\": invalid syntax",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "bit overflow",
|
||||||
|
payload: "12345678901234567890",
|
||||||
|
base: 10,
|
||||||
|
bitSize: 32,
|
||||||
|
errorString: "strconv.ParseInt: parsing \"12345678901234567890\": value out of range",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
intParser := processor.IntParse{
|
||||||
|
Base: test.base,
|
||||||
|
BitSize: test.bitSize,
|
||||||
|
}
|
||||||
got, err := intParser.Process(t.Context(), test.payload)
|
got, err := intParser.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("int.parse expected to fail but succeeded, got: %v", got)
|
t.Fatalf("int.parse expected to fail but succeeded, got: %v", got)
|
||||||
|
|
||||||
}
|
}
|
||||||
if err.Error() != test.errorString {
|
if err.Error() != test.errorString {
|
||||||
t.Errorf("int.parse got error '%s', expected '%s'", err.Error(), test.errorString)
|
t.Fatalf("int.parse got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
61
internal/processor/int-random.go
Normal file
61
internal/processor/int-random.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"math/rand/v2"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type IntRandom struct {
|
||||||
|
Min int
|
||||||
|
Max int
|
||||||
|
config config.ProcessorConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (up *IntRandom) Process(ctx context.Context, payload any) (any, error) {
|
||||||
|
payloadInt := rand.IntN(up.Max-up.Min+1) + up.Min
|
||||||
|
return payloadInt, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (up *IntRandom) Type() string {
|
||||||
|
return up.config.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RegisterProcessor(ProcessorRegistration{
|
||||||
|
Type: "int.random",
|
||||||
|
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||||
|
params := config.Params
|
||||||
|
|
||||||
|
min, ok := params["min"]
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("int.random requires a min parameter")
|
||||||
|
}
|
||||||
|
|
||||||
|
minFloat, ok := min.(float64)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("int.random min must be a number")
|
||||||
|
}
|
||||||
|
|
||||||
|
max, ok := params["max"]
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("int.random requires a max parameter")
|
||||||
|
}
|
||||||
|
|
||||||
|
maxFloat, ok := max.(float64)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("int.random max must be a number")
|
||||||
|
}
|
||||||
|
|
||||||
|
if maxFloat < minFloat {
|
||||||
|
return nil, errors.New("int.random max must be greater than min")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &IntRandom{config: config, Min: int(minFloat), Max: int(maxFloat)}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -20,12 +20,12 @@ type MIDIMessageCreate struct {
|
|||||||
ProcessFunc func(ctx context.Context, payload any) (any, error)
|
ProcessFunc func(ctx context.Context, payload any) (any, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mmd *MIDIMessageCreate) Process(ctx context.Context, payload any) (any, error) {
|
func (mmc *MIDIMessageCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||||
return mmd.ProcessFunc(ctx, payload)
|
return mmc.ProcessFunc(ctx, payload)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mmd *MIDIMessageCreate) Type() string {
|
func (mmc *MIDIMessageCreate) Type() string {
|
||||||
return mmd.config.Type
|
return mmc.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func newMidiNoteOnCreate(config config.ProcessorConfig) (Processor, error) {
|
func newMidiNoteOnCreate(config config.ProcessorConfig) (Processor, error) {
|
||||||
|
|||||||
@@ -20,10 +20,10 @@ type OSCMessageCreate struct {
|
|||||||
Types string
|
Types string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OSCMessageCreate) Process(ctx context.Context, payload any) (any, error) {
|
func (omc *OSCMessageCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||||
|
|
||||||
var addressBuffer bytes.Buffer
|
var addressBuffer bytes.Buffer
|
||||||
err := o.Address.Execute(&addressBuffer, payload)
|
err := omc.Address.Execute(&addressBuffer, payload)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -45,7 +45,7 @@ func (o *OSCMessageCreate) Process(ctx context.Context, payload any) (any, error
|
|||||||
|
|
||||||
args := []osc.OSCArg{}
|
args := []osc.OSCArg{}
|
||||||
|
|
||||||
for argIndex, argTemplate := range o.Args {
|
for argIndex, argTemplate := range omc.Args {
|
||||||
var argBuffer bytes.Buffer
|
var argBuffer bytes.Buffer
|
||||||
err := argTemplate.Execute(&argBuffer, payload)
|
err := argTemplate.Execute(&argBuffer, payload)
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ func (o *OSCMessageCreate) Process(ctx context.Context, payload any) (any, error
|
|||||||
|
|
||||||
argString := argBuffer.String()
|
argString := argBuffer.String()
|
||||||
|
|
||||||
typedArg, err := argToTypedArg(argString, o.Types[argIndex])
|
typedArg, err := argToTypedArg(argString, omc.Types[argIndex])
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -71,8 +71,8 @@ func (o *OSCMessageCreate) Process(ctx context.Context, payload any) (any, error
|
|||||||
return payloadMessage, nil
|
return payloadMessage, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OSCMessageCreate) Type() string {
|
func (omc *OSCMessageCreate) Type() string {
|
||||||
return o.config.Type
|
return omc.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ type OSCMessageDecode struct {
|
|||||||
config config.ProcessorConfig
|
config config.ProcessorConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OSCMessageDecode) Process(ctx context.Context, payload any) (any, error) {
|
func (omd *OSCMessageDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||||
payloadBytes, ok := payload.([]byte)
|
payloadBytes, ok := payload.([]byte)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -34,8 +34,8 @@ func (o *OSCMessageDecode) Process(ctx context.Context, payload any) (any, error
|
|||||||
return message, nil
|
return message, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OSCMessageDecode) Type() string {
|
func (omd *OSCMessageDecode) Type() string {
|
||||||
return o.config.Type
|
return omd.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ type OSCMessageEncode struct {
|
|||||||
config config.ProcessorConfig
|
config config.ProcessorConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OSCMessageEncode) Process(ctx context.Context, payload any) (any, error) {
|
func (ome *OSCMessageEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||||
payloadMessage, ok := payload.(osc.OSCMessage)
|
payloadMessage, ok := payload.(osc.OSCMessage)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -23,8 +23,8 @@ func (o *OSCMessageEncode) Process(ctx context.Context, payload any) (any, error
|
|||||||
return bytes, nil
|
return bytes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OSCMessageEncode) Type() string {
|
func (ome *OSCMessageEncode) Type() string {
|
||||||
return o.config.Type
|
return ome.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ type OSCMessageFilter struct {
|
|||||||
Address *regexp.Regexp
|
Address *regexp.Regexp
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OSCMessageFilter) Process(ctx context.Context, payload any) (any, error) {
|
func (omf *OSCMessageFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||||
|
|
||||||
payloadMessage, ok := payload.(osc.OSCMessage)
|
payloadMessage, ok := payload.(osc.OSCMessage)
|
||||||
|
|
||||||
@@ -24,15 +24,15 @@ func (o *OSCMessageFilter) Process(ctx context.Context, payload any) (any, error
|
|||||||
return nil, errors.New("osc.message.filter can only operate on OSCMessage payloads")
|
return nil, errors.New("osc.message.filter can only operate on OSCMessage payloads")
|
||||||
}
|
}
|
||||||
|
|
||||||
if !o.Address.MatchString(payloadMessage.Address) {
|
if !omf.Address.MatchString(payloadMessage.Address) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return payloadMessage, nil
|
return payloadMessage, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OSCMessageFilter) Type() string {
|
func (omf *OSCMessageFilter) Type() string {
|
||||||
return o.config.Type
|
return omf.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ type OSCMessageTransform struct {
|
|||||||
Address *template.Template
|
Address *template.Template
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OSCMessageTransform) Process(ctx context.Context, payload any) (any, error) {
|
func (omt *OSCMessageTransform) Process(ctx context.Context, payload any) (any, error) {
|
||||||
payloadMessage, ok := payload.(osc.OSCMessage)
|
payloadMessage, ok := payload.(osc.OSCMessage)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -23,7 +23,7 @@ func (o *OSCMessageTransform) Process(ctx context.Context, payload any) (any, er
|
|||||||
}
|
}
|
||||||
|
|
||||||
var addressBuffer bytes.Buffer
|
var addressBuffer bytes.Buffer
|
||||||
err := o.Address.Execute(&addressBuffer, payloadMessage)
|
err := omt.Address.Execute(&addressBuffer, payloadMessage)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -44,8 +44,8 @@ func (o *OSCMessageTransform) Process(ctx context.Context, payload any) (any, er
|
|||||||
return payloadMessage, nil
|
return payloadMessage, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *OSCMessageTransform) Type() string {
|
func (omt *OSCMessageTransform) Type() string {
|
||||||
return o.config.Type
|
return omt.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
62
internal/processor/processor_test.go
Normal file
62
internal/processor/processor_test.go
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
package processor_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TestProcessor struct {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *TestProcessor) Type() string {
|
||||||
|
return "test"
|
||||||
|
}
|
||||||
|
func (p *TestProcessor) Process(ctx context.Context, input any) (any, error) {
|
||||||
|
return input, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProcessorBadRegistrationNoType(t *testing.T) {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r == nil {
|
||||||
|
t.Fatalf("processor registration should have panicked but did not")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
processor.RegisterProcessor(processor.ProcessorRegistration{
|
||||||
|
Type: "",
|
||||||
|
New: func(config config.ProcessorConfig) (processor.Processor, error) {
|
||||||
|
return &TestProcessor{}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProcessorBadRegistrationNoNew(t *testing.T) {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r == nil {
|
||||||
|
t.Fatalf("processor registration should have panicked but did not")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
processor.RegisterProcessor(processor.ProcessorRegistration{
|
||||||
|
Type: "test",
|
||||||
|
New: nil,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProcessorBadRegistrationExistingType(t *testing.T) {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r == nil {
|
||||||
|
t.Fatalf("processor registration should have panicked but did not")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
processor.RegisterProcessor(processor.ProcessorRegistration{
|
||||||
|
Type: "string.create",
|
||||||
|
New: func(config config.ProcessorConfig) (processor.Processor, error) {
|
||||||
|
return &TestProcessor{}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -4,9 +4,83 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/expr-lang/expr"
|
"github.com/expr-lang/expr"
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestScriptExprFromRegistry(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["script.expr"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("script.expr processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "script.expr",
|
||||||
|
Params: map[string]any{
|
||||||
|
"expression": "foo + bar",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create script.expr processor: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if processorInstance.Type() != "script.expr" {
|
||||||
|
t.Fatalf("script.expr processor has wrong type: %s", processorInstance.Type())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScriptExprNoProgram(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["script.expr"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("script.expr processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "script.expr",
|
||||||
|
Params: map[string]any{},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("script.expr processor should have thrown an error when creating")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScriptExprBadConfigWrongExpressionType(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["script.expr"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("script.expr processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "script.expr",
|
||||||
|
Params: map[string]any{
|
||||||
|
"expression": 12345,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("script.expr processor should have thrown an error when creating with non-string expression")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScriptExprBadConfigNonCompilingExpression(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["script.expr"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("script.expr processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "script.expr",
|
||||||
|
Params: map[string]any{
|
||||||
|
"expression": "foo + ",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("script.expr processor should have thrown an error when creating with non-compiling expression")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGoodScriptExpr(t *testing.T) {
|
func TestGoodScriptExpr(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
program string
|
program string
|
||||||
@@ -38,7 +112,7 @@ func TestGoodScriptExpr(t *testing.T) {
|
|||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
program, err := expr.Compile(test.program)
|
program, err := expr.Compile(test.program)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("script.expr failed to compile program: %s", err)
|
t.Fatalf("script.expr failed to compile program: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
exprProcessor := &processor.ScriptExpr{Program: program}
|
exprProcessor := &processor.ScriptExpr{Program: program}
|
||||||
@@ -46,12 +120,51 @@ func TestGoodScriptExpr(t *testing.T) {
|
|||||||
got, err := exprProcessor.Process(t.Context(), test.payload)
|
got, err := exprProcessor.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("script.expr failed: %s", err)
|
t.Fatalf("script.expr failed: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO(jwetzell): work out better way to compare the any/any
|
//TODO(jwetzell): work out better way to compare the any/any
|
||||||
if got != test.expected {
|
if got != test.expected {
|
||||||
t.Errorf("script.expr got %+v (%T), expected %+v (%T)", got, got, test.expected, test.expected)
|
t.Fatalf("script.expr got %+v (%T), expected %+v (%T)", got, got, test.expected, test.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBadScriptExpr(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
program string
|
||||||
|
name string
|
||||||
|
payload map[string]any
|
||||||
|
errorString string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "accessing missing field",
|
||||||
|
program: "foo + bar",
|
||||||
|
payload: map[string]any{
|
||||||
|
"foo": 1,
|
||||||
|
},
|
||||||
|
errorString: "invalid operation: int + <nil> (1:5)\n | foo + bar\n | ....^",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
program, err := expr.Compile(test.program)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("script.expr failed to compile program: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
exprProcessor := &processor.ScriptExpr{Program: program}
|
||||||
|
|
||||||
|
got, err := exprProcessor.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("script.expr expected to fail but succeeded, got: %v", got)
|
||||||
|
|
||||||
|
}
|
||||||
|
if err.Error() != test.errorString {
|
||||||
|
t.Fatalf("script.expr got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,82 @@
|
|||||||
package processor_test
|
package processor_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"maps"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestScriptJSFromRegistry(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["script.js"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("script.js processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "script.js",
|
||||||
|
Params: map[string]any{
|
||||||
|
"program": `
|
||||||
|
payload = payload + 1
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create script.js processor: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if processorInstance.Type() != "script.js" {
|
||||||
|
t.Fatalf("script.js processor has wrong type: %s", processorInstance.Type())
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := 1
|
||||||
|
expected := 2
|
||||||
|
|
||||||
|
got, err := processorInstance.Process(t.Context(), payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("script.js processing failed: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got != expected {
|
||||||
|
t.Fatalf("script.js got %+v, expected %+v", got, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScriptJSNoProgram(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["script.js"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("script.js processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "script.js",
|
||||||
|
Params: map[string]any{},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("script.js processor should have thrown an error when creating")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScriptJSBadConfigWrongProgramType(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["script.js"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("script.js processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "script.js",
|
||||||
|
Params: map[string]any{
|
||||||
|
"program": 12345,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("script.js processor should have thrown an error when creating with non-string program")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGoodScriptJS(t *testing.T) {
|
func TestGoodScriptJS(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
processor processor.Processor
|
processor processor.Processor
|
||||||
@@ -14,21 +85,37 @@ func TestGoodScriptJS(t *testing.T) {
|
|||||||
expected any
|
expected any
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
|
name: "number",
|
||||||
processor: &processor.ScriptJS{Program: `
|
processor: &processor.ScriptJS{Program: `
|
||||||
payload = payload + 1
|
payload = payload + 1
|
||||||
`},
|
`},
|
||||||
name: "number",
|
|
||||||
payload: 1,
|
payload: 1,
|
||||||
expected: 2,
|
expected: 2,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
name: "string",
|
||||||
processor: &processor.ScriptJS{Program: `
|
processor: &processor.ScriptJS{Program: `
|
||||||
payload = payload + "1"
|
payload = payload + "1"
|
||||||
`},
|
`},
|
||||||
name: "string",
|
|
||||||
payload: "1",
|
payload: "1",
|
||||||
expected: "11",
|
expected: "11",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "object",
|
||||||
|
processor: &processor.ScriptJS{Program: `
|
||||||
|
payload = { key: payload }
|
||||||
|
`},
|
||||||
|
payload: "1",
|
||||||
|
expected: map[string]any{"key": "1"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nil",
|
||||||
|
processor: &processor.ScriptJS{Program: `
|
||||||
|
payload = undefined
|
||||||
|
`},
|
||||||
|
payload: "1",
|
||||||
|
expected: nil,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
@@ -36,12 +123,56 @@ func TestGoodScriptJS(t *testing.T) {
|
|||||||
got, err := test.processor.Process(t.Context(), test.payload)
|
got, err := test.processor.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("script.js failed: %s", err)
|
t.Fatalf("script.js process failed: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO(jwetzell): work out better way to compare the any/any
|
//TODO(jwetzell): work out better way to compare the any/any
|
||||||
|
|
||||||
|
gotMap, ok := got.(map[string]interface{})
|
||||||
|
if ok {
|
||||||
|
// got a map
|
||||||
|
expectedMap, ok := test.expected.(map[string]interface{})
|
||||||
|
if ok {
|
||||||
|
if !maps.Equal(gotMap, expectedMap) {
|
||||||
|
t.Fatalf("script.js got %+v, expected %+v", got, test.expected)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
t.Fatalf("script.js got %+v, expected %+v", got, test.expected)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
if got != test.expected {
|
if got != test.expected {
|
||||||
t.Errorf("script.js got %+v, expected %+v", got, test.expected)
|
t.Fatalf("script.js got %+v, expected %+v", got, test.expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBadScriptJS(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
processor processor.Processor
|
||||||
|
payload any
|
||||||
|
errorString string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "accessing not defined variable",
|
||||||
|
processor: &processor.ScriptJS{Program: `paylod = foo`},
|
||||||
|
payload: 0,
|
||||||
|
errorString: "ReferenceError: 'foo' is not defined",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
got, err := test.processor.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("script.js expected to fail but succeeded, got: %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err.Error() != test.errorString {
|
||||||
|
t.Fatalf("script.js got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
81
internal/processor/string-create_test.go
Normal file
81
internal/processor/string-create_test.go
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
package processor_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"text/template"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TestStruct struct {
|
||||||
|
Data string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t TestStruct) GetData() string {
|
||||||
|
return t.Data
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGoodStringCreate(t *testing.T) {
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
template string
|
||||||
|
payload any
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "string payload",
|
||||||
|
template: "{{.}}",
|
||||||
|
payload: "hello",
|
||||||
|
expected: "hello",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "number payload",
|
||||||
|
template: "{{.}}",
|
||||||
|
payload: 4,
|
||||||
|
expected: "4",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "boolean payload",
|
||||||
|
template: "{{.}}",
|
||||||
|
payload: true,
|
||||||
|
expected: "true",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "struct payload - field",
|
||||||
|
template: "{{.Data}}",
|
||||||
|
payload: TestStruct{Data: "test"},
|
||||||
|
expected: "test",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "struct payload - method",
|
||||||
|
template: "{{.GetData}}",
|
||||||
|
payload: TestStruct{Data: "test"},
|
||||||
|
expected: "test",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
template, err := template.New("template").Parse(test.template)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("string.create template parsing failed: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
processor := &processor.StringCreate{Template: template}
|
||||||
|
|
||||||
|
got, err := processor.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
|
gotStrings, ok := got.(string)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("string.create returned a %T payload: %s", got, got)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("string.create failed: %s", err)
|
||||||
|
}
|
||||||
|
if gotStrings != test.expected {
|
||||||
|
t.Fatalf("string.create got %s, expected %s", got, test.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,13 +28,13 @@ func TestGoodStringDecode(t *testing.T) {
|
|||||||
|
|
||||||
gotString, ok := got.(string)
|
gotString, ok := got.(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Errorf("string.decode returned a %T payload: %s", got, got)
|
t.Fatalf("string.decode returned a %T payload: %s", got, got)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("string.decode failed: %s", err)
|
t.Fatalf("string.decode failed: %s", err)
|
||||||
}
|
}
|
||||||
if gotString != test.expected {
|
if gotString != test.expected {
|
||||||
t.Errorf("string.decode got %s, expected %s", got, test.expected)
|
t.Fatalf("string.decode got %s, expected %s", got, test.expected)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -61,10 +61,10 @@ func TestBadStringDecode(t *testing.T) {
|
|||||||
got, err := test.processor.Process(t.Context(), test.payload)
|
got, err := test.processor.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("string.decode expected to fail but got payload: %s", got)
|
t.Fatalf("string.decode expected to fail but got payload: %s", got)
|
||||||
}
|
}
|
||||||
if err.Error() != test.errorString {
|
if err.Error() != test.errorString {
|
||||||
t.Errorf("string.decode got error '%s', expected '%s'", err.Error(), test.errorString)
|
t.Fatalf("string.decode got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,13 +29,13 @@ func TestGoodStringEncode(t *testing.T) {
|
|||||||
|
|
||||||
gotBytes, ok := got.([]byte)
|
gotBytes, ok := got.([]byte)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Errorf("string.encode returned a %T payload: %s", got, got)
|
t.Fatalf("string.encode returned a %T payload: %s", got, got)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("string.encode failed: %s", err)
|
t.Fatalf("string.encode failed: %s", err)
|
||||||
}
|
}
|
||||||
if !slices.Equal(gotBytes, test.expected) {
|
if !slices.Equal(gotBytes, test.expected) {
|
||||||
t.Errorf("string.encode got %s, expected %s", got, test.expected)
|
t.Fatalf("string.encode got %s, expected %s", got, test.expected)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -62,10 +62,10 @@ func TestBadStringEncode(t *testing.T) {
|
|||||||
got, err := test.processor.Process(t.Context(), test.payload)
|
got, err := test.processor.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("string.encode expected to fail but got payload: %s", got)
|
t.Fatalf("string.encode expected to fail but got payload: %s", got)
|
||||||
}
|
}
|
||||||
if err.Error() != test.errorString {
|
if err.Error() != test.errorString {
|
||||||
t.Errorf("string.encode got error '%s', expected '%s'", err.Error(), test.errorString)
|
t.Fatalf("string.encode got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,22 +13,22 @@ type StringFilter struct {
|
|||||||
Pattern *regexp.Regexp
|
Pattern *regexp.Regexp
|
||||||
}
|
}
|
||||||
|
|
||||||
func (se *StringFilter) Process(ctx context.Context, payload any) (any, error) {
|
func (sf *StringFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||||
payloadString, ok := payload.(string)
|
payloadString, ok := payload.(string)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("string.filter processor only accepts a string")
|
return nil, errors.New("string.filter processor only accepts a string")
|
||||||
}
|
}
|
||||||
|
|
||||||
if !se.Pattern.MatchString(payloadString) {
|
if !sf.Pattern.MatchString(payloadString) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return payloadString, nil
|
return payloadString, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (se *StringFilter) Type() string {
|
func (sf *StringFilter) Type() string {
|
||||||
return se.config.Type
|
return sf.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
@@ -13,20 +13,20 @@ type StringSplit struct {
|
|||||||
Separator string
|
Separator string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (se *StringSplit) Process(ctx context.Context, payload any) (any, error) {
|
func (ss *StringSplit) Process(ctx context.Context, payload any) (any, error) {
|
||||||
payloadString, ok := payload.(string)
|
payloadString, ok := payload.(string)
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("string.split only accepts a string")
|
return nil, errors.New("string.split only accepts a string")
|
||||||
}
|
}
|
||||||
|
|
||||||
payloadParts := strings.Split(payloadString, se.Separator)
|
payloadParts := strings.Split(payloadString, ss.Separator)
|
||||||
|
|
||||||
return payloadParts, nil
|
return payloadParts, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (se *StringSplit) Type() string {
|
func (ss *StringSplit) Type() string {
|
||||||
return se.config.Type
|
return ss.config.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
@@ -28,13 +28,13 @@ func TestGoodStringSplit(t *testing.T) {
|
|||||||
|
|
||||||
gotStrings, ok := got.([]string)
|
gotStrings, ok := got.([]string)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Errorf("string.split returned a %T payload: %s", got, got)
|
t.Fatalf("string.split returned a %T payload: %s", got, got)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("string.split failed: %s", err)
|
t.Fatalf("string.split failed: %s", err)
|
||||||
}
|
}
|
||||||
if !slices.Equal(gotStrings, test.expected) {
|
if !slices.Equal(gotStrings, test.expected) {
|
||||||
t.Errorf("string.split got %s, expected %s", got, test.expected)
|
t.Fatalf("string.split got %s, expected %s", got, test.expected)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -60,10 +60,10 @@ func TestBadStringSplit(t *testing.T) {
|
|||||||
got, err := test.processor.Process(t.Context(), test.payload)
|
got, err := test.processor.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("string.split expected error but got none, payload: %s", got)
|
t.Fatalf("string.split expected error but got none, payload: %s", got)
|
||||||
}
|
}
|
||||||
if err.Error() != test.errorString {
|
if err.Error() != test.errorString {
|
||||||
t.Errorf("string.split got error '%s', expected '%s'", err.Error(), test.errorString)
|
t.Fatalf("string.split got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
45
internal/processor/time-sleep.go
Normal file
45
internal/processor/time-sleep.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MetaDelay struct {
|
||||||
|
config config.ProcessorConfig
|
||||||
|
Duration time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (md *MetaDelay) Process(ctx context.Context, payload any) (any, error) {
|
||||||
|
time.Sleep(md.Duration)
|
||||||
|
return payload, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (md *MetaDelay) Type() string {
|
||||||
|
return md.config.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RegisterProcessor(ProcessorRegistration{
|
||||||
|
Type: "time.sleep",
|
||||||
|
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||||
|
params := config.Params
|
||||||
|
|
||||||
|
duration, ok := params["duration"]
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("time.sleep requires a duration parameter")
|
||||||
|
}
|
||||||
|
|
||||||
|
durationNum, ok := duration.(float64)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("time.sleep duration must be number")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &MetaDelay{config: config, Duration: time.Millisecond * time.Duration(durationNum)}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -3,42 +3,158 @@ package processor_test
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestUintParseFromRegistry(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["uint.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("uint.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "uint.parse",
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create uint.parse processor: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if processorInstance.Type() != "uint.parse" {
|
||||||
|
t.Fatalf("uint.parse processor has wrong type: %s", processorInstance.Type())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUintParseBadConfigBaseString(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["uint.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("uint.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "uint.parse",
|
||||||
|
Params: map[string]any{
|
||||||
|
"base": "10",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("uint.parse should have returned an error for bad base config")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUintParseBadConfigBitSizeString(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["uint.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("uint.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "uint.parse",
|
||||||
|
Params: map[string]any{
|
||||||
|
"bitSize": "64",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("uint.parse should have returned an error for bad bitSize config")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUintParseGoodConfig(t *testing.T) {
|
||||||
|
registration, ok := processor.ProcessorRegistry["uint.parse"]
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("uint.parse processor not registered")
|
||||||
|
}
|
||||||
|
|
||||||
|
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||||
|
Type: "uint.parse",
|
||||||
|
Params: map[string]any{
|
||||||
|
"base": 10.0,
|
||||||
|
"bitSize": 64.0,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("uint.parse should have created processor but got error: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := "12345"
|
||||||
|
expected := uint64(12345)
|
||||||
|
|
||||||
|
got, err := processorInstance.Process(t.Context(), payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("uint.parse processing failed: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
gotUint, ok := got.(uint64)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("uint.parse returned a %T payload: %s", got, got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if gotUint != expected {
|
||||||
|
t.Fatalf("uint.parse got %d, expected %d", gotUint, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGoodUintParse(t *testing.T) {
|
func TestGoodUintParse(t *testing.T) {
|
||||||
uintParser := processor.UintParse{}
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
processor processor.Processor
|
processor processor.Processor
|
||||||
name string
|
name string
|
||||||
payload any
|
payload any
|
||||||
expected uint64
|
expected uint64
|
||||||
|
base int
|
||||||
|
bitSize int
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "positive number",
|
name: "positive number",
|
||||||
payload: "12345",
|
payload: "12345",
|
||||||
expected: 12345,
|
expected: 12345,
|
||||||
|
base: 10,
|
||||||
|
bitSize: 64,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "zero",
|
name: "zero",
|
||||||
payload: "0",
|
payload: "0",
|
||||||
expected: 0,
|
expected: 0,
|
||||||
|
base: 10,
|
||||||
|
bitSize: 64,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "binary",
|
||||||
|
payload: "1010101",
|
||||||
|
expected: 85,
|
||||||
|
base: 2,
|
||||||
|
bitSize: 64,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "hex",
|
||||||
|
payload: "15F",
|
||||||
|
expected: 351,
|
||||||
|
base: 16,
|
||||||
|
bitSize: 64,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
uintParser := processor.UintParse{
|
||||||
|
Base: test.base,
|
||||||
|
BitSize: test.bitSize,
|
||||||
|
}
|
||||||
got, err := uintParser.Process(t.Context(), test.payload)
|
got, err := uintParser.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
gotUint, ok := got.(uint64)
|
gotUint, ok := got.(uint64)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Errorf("uint.parse returned a %T payload: %s", got, got)
|
t.Fatalf("uint.parse returned a %T payload: %s", got, got)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("uint.parse failed: %s", err)
|
t.Fatalf("uint.parse failed: %s", err)
|
||||||
}
|
}
|
||||||
if gotUint != test.expected {
|
if gotUint != test.expected {
|
||||||
t.Errorf("uint.parse got %d, expected %d", gotUint, test.expected)
|
t.Fatalf("uint.parse got %d, expected %d", gotUint, test.expected)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -50,18 +166,31 @@ func TestBadUintParse(t *testing.T) {
|
|||||||
processor processor.Processor
|
processor processor.Processor
|
||||||
name string
|
name string
|
||||||
payload any
|
payload any
|
||||||
|
base int
|
||||||
|
bitSize int
|
||||||
errorString string
|
errorString string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "non-string input",
|
name: "non-string input",
|
||||||
payload: []byte{0x01},
|
payload: []byte{0x01},
|
||||||
|
base: 10,
|
||||||
|
bitSize: 64,
|
||||||
errorString: "uint.parse processor only accepts a string",
|
errorString: "uint.parse processor only accepts a string",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "not uint string",
|
name: "not uint string",
|
||||||
payload: "-1234",
|
payload: "-1234",
|
||||||
|
base: 10,
|
||||||
|
bitSize: 64,
|
||||||
errorString: "strconv.ParseUint: parsing \"-1234\": invalid syntax",
|
errorString: "strconv.ParseUint: parsing \"-1234\": invalid syntax",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "bit overflow",
|
||||||
|
payload: "123456789012345678901234567",
|
||||||
|
base: 10,
|
||||||
|
bitSize: 32,
|
||||||
|
errorString: "strconv.ParseUint: parsing \"123456789012345678901234567\": value out of range",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
@@ -69,11 +198,11 @@ func TestBadUintParse(t *testing.T) {
|
|||||||
got, err := uintParser.Process(t.Context(), test.payload)
|
got, err := uintParser.Process(t.Context(), test.payload)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("uint.parse expected to fail but succeeded, got: %v", got)
|
t.Fatalf("uint.parse expected to fail but succeeded, got: %v", got)
|
||||||
|
|
||||||
}
|
}
|
||||||
if err.Error() != test.errorString {
|
if err.Error() != test.errorString {
|
||||||
t.Errorf("uint.parse got error '%s', expected '%s'", err.Error(), test.errorString)
|
t.Fatalf("uint.parse got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
61
internal/processor/uint-random.go
Normal file
61
internal/processor/uint-random.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package processor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"math/rand/v2"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UintRandom struct {
|
||||||
|
Min uint
|
||||||
|
Max uint
|
||||||
|
config config.ProcessorConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ur *UintRandom) Process(ctx context.Context, payload any) (any, error) {
|
||||||
|
payloadInt := rand.UintN(ur.Max-ur.Min+1) + ur.Min
|
||||||
|
return payloadInt, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ur *UintRandom) Type() string {
|
||||||
|
return ur.config.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RegisterProcessor(ProcessorRegistration{
|
||||||
|
Type: "uint.random",
|
||||||
|
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||||
|
params := config.Params
|
||||||
|
|
||||||
|
min, ok := params["min"]
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("uint.random requires a min parameter")
|
||||||
|
}
|
||||||
|
|
||||||
|
minFloat, ok := min.(float64)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("uint.random min must be a number")
|
||||||
|
}
|
||||||
|
|
||||||
|
max, ok := params["max"]
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("uint.random requires a max parameter")
|
||||||
|
}
|
||||||
|
|
||||||
|
maxFloat, ok := max.(float64)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("uint.random max must be a number")
|
||||||
|
}
|
||||||
|
|
||||||
|
if maxFloat < minFloat {
|
||||||
|
return nil, errors.New("uint.random max must be greater than min")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &UintRandom{config: config, Min: uint(minFloat), Max: uint(maxFloat)}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -8,6 +8,11 @@ import (
|
|||||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type routeContextKey string
|
||||||
|
|
||||||
|
var RouterContextKey routeContextKey = routeContextKey("router")
|
||||||
|
var SourceContextKey routeContextKey = routeContextKey("source")
|
||||||
|
|
||||||
type RouteError struct {
|
type RouteError struct {
|
||||||
Index int
|
Index int
|
||||||
Config config.RouteConfig
|
Config config.RouteConfig
|
||||||
@@ -21,14 +26,13 @@ type RouteIOError struct {
|
|||||||
|
|
||||||
type RouteIO interface {
|
type RouteIO interface {
|
||||||
HandleInput(sourceId string, payload any) []RouteIOError
|
HandleInput(sourceId string, payload any) []RouteIOError
|
||||||
HandleOutput(sourceId string, destinationId string, payload any) error
|
HandleOutput(ctx context.Context, destinationId string, payload any) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type Route interface {
|
type Route interface {
|
||||||
Input() string
|
Input() string
|
||||||
Output() string
|
Output() string
|
||||||
HandleInput(ctx context.Context, sourceId string, payload any, router RouteIO) error
|
ProcessPayload(ctx context.Context, payload any) (any, error)
|
||||||
HandleOutput(ctx context.Context, sourceId string, payload any, router RouteIO) error
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ProcessorRoute struct {
|
type ProcessorRoute struct {
|
||||||
@@ -66,21 +70,18 @@ func (r *ProcessorRoute) Output() string {
|
|||||||
return r.output
|
return r.output
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *ProcessorRoute) HandleInput(ctx context.Context, sourceId string, payload any, router RouteIO) error {
|
func (r *ProcessorRoute) ProcessPayload(ctx context.Context, payload any) (any, error) {
|
||||||
var err error
|
|
||||||
for _, processor := range r.processors {
|
for _, processor := range r.processors {
|
||||||
payload, err = processor.Process(ctx, payload)
|
processedPayload, err := processor.Process(ctx, payload)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
//NOTE(jwetzell) nil payload will result in the route being "terminated"
|
//NOTE(jwetzell) nil payload will result in the route being "terminated"
|
||||||
if payload == nil {
|
if processedPayload == nil {
|
||||||
return nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
payload = processedPayload
|
||||||
}
|
}
|
||||||
return r.HandleOutput(ctx, sourceId, payload, router)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ProcessorRoute) HandleOutput(ctx context.Context, sourceId string, payload any, router RouteIO) error {
|
return payload, nil
|
||||||
return router.HandleOutput(sourceId, r.output, payload)
|
|
||||||
}
|
}
|
||||||
|
|||||||
166
internal/route/route_test.go
Normal file
166
internal/route/route_test.go
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
package route_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/config"
|
||||||
|
"github.com/jwetzell/showbridge-go/internal/route"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRouteCreate(t *testing.T) {
|
||||||
|
routeConfig := config.RouteConfig{
|
||||||
|
Input: "input",
|
||||||
|
Output: "output",
|
||||||
|
}
|
||||||
|
|
||||||
|
testRoute, err := route.NewRoute(routeConfig)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("route failed to create: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if testRoute.Input() != routeConfig.Input {
|
||||||
|
t.Fatalf("route input does not match expected input")
|
||||||
|
}
|
||||||
|
if testRoute.Output() != routeConfig.Output {
|
||||||
|
t.Fatalf("route output does not match expected output")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type MockRouter struct{}
|
||||||
|
|
||||||
|
func (mr *MockRouter) HandleInput(sourceId string, payload any) []route.RouteIOError {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mr *MockRouter) HandleOutput(ctx context.Context, destinationId string, payload any) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGoodRouteHandleInput(t *testing.T) {
|
||||||
|
routeConfig := config.RouteConfig{
|
||||||
|
Input: "input",
|
||||||
|
Processors: []config.ProcessorConfig{
|
||||||
|
{Type: "string.encode"},
|
||||||
|
},
|
||||||
|
Output: "output",
|
||||||
|
}
|
||||||
|
|
||||||
|
testRoute, err := route.NewRoute(routeConfig)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("route failed to create: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
inputData := "test input data"
|
||||||
|
payload, err := testRoute.ProcessPayload(context.WithValue(t.Context(), route.RouterContextKey, &MockRouter{}), inputData)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("route ProcessPayload returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
payloadBytes, ok := payload.([]byte)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("payload should be []byte got %T", payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !slices.Equal([]byte(inputData), payloadBytes) {
|
||||||
|
t.Fatalf("route returned the wrong payload. expected: %+v got %+v", inputData, payloadBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouteHandleInputWithProcessorError(t *testing.T) {
|
||||||
|
routeConfig := config.RouteConfig{
|
||||||
|
Input: "input",
|
||||||
|
Processors: []config.ProcessorConfig{
|
||||||
|
{Type: "string.create", Params: map[string]any{"template": "{{.invalid}}}"}},
|
||||||
|
},
|
||||||
|
Output: "output",
|
||||||
|
}
|
||||||
|
|
||||||
|
testRoute, err := route.NewRoute(routeConfig)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("route failed to create: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
inputData := "test input data"
|
||||||
|
_, err = testRoute.ProcessPayload(context.WithValue(t.Context(), route.RouterContextKey, &MockRouter{}), inputData)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("route HandleOutput did not return error for bad processor")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouteHandleNilPayload(t *testing.T) {
|
||||||
|
routeConfig := config.RouteConfig{
|
||||||
|
Input: "input",
|
||||||
|
Processors: []config.ProcessorConfig{},
|
||||||
|
Output: "output",
|
||||||
|
}
|
||||||
|
|
||||||
|
testRoute, err := route.NewRoute(routeConfig)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("route failed to create: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, err := testRoute.ProcessPayload(context.WithValue(t.Context(), route.RouterContextKey, &MockRouter{}), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("route ProcessPayload returned error: %v", err)
|
||||||
|
}
|
||||||
|
if payload != nil {
|
||||||
|
t.Fatalf("route returned the wrong payload")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouteHandleNilPayloadFromProcessor(t *testing.T) {
|
||||||
|
routeConfig := config.RouteConfig{
|
||||||
|
Input: "input",
|
||||||
|
Processors: []config.ProcessorConfig{
|
||||||
|
{Type: "script.js", Params: map[string]any{"program": "payload = undefined"}},
|
||||||
|
},
|
||||||
|
Output: "output",
|
||||||
|
}
|
||||||
|
|
||||||
|
testRoute, err := route.NewRoute(routeConfig)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("route failed to create: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, err := testRoute.ProcessPayload(context.WithValue(t.Context(), route.RouterContextKey, &MockRouter{}), "test")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("route HandleOutput returned error for nil payload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if payload != nil {
|
||||||
|
t.Fatalf("route returned the wrong payload")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouteUnknownProcessor(t *testing.T) {
|
||||||
|
routeConfig := config.RouteConfig{
|
||||||
|
Input: "input",
|
||||||
|
Processors: []config.ProcessorConfig{
|
||||||
|
{Type: "asdfasdflkjalkj"},
|
||||||
|
},
|
||||||
|
Output: "output",
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := route.NewRoute(routeConfig)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("route error expected when creating route with an unknown processor, got nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouteBadProcessorConfig(t *testing.T) {
|
||||||
|
routeConfig := config.RouteConfig{
|
||||||
|
Input: "input",
|
||||||
|
Processors: []config.ProcessorConfig{
|
||||||
|
{Type: "string.create", Params: map[string]any{}},
|
||||||
|
},
|
||||||
|
Output: "output",
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := route.NewRoute(routeConfig)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("route error expected creating route with bad processor, got nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
31
router.go
31
router.go
@@ -24,15 +24,17 @@ type Router struct {
|
|||||||
func NewRouter(ctx context.Context, config config.Config) (*Router, []module.ModuleError, []route.RouteError) {
|
func NewRouter(ctx context.Context, config config.Config) (*Router, []module.ModuleError, []route.RouteError) {
|
||||||
|
|
||||||
routerContext, cancel := context.WithCancel(ctx)
|
routerContext, cancel := context.WithCancel(ctx)
|
||||||
|
|
||||||
router := Router{
|
router := Router{
|
||||||
Context: routerContext,
|
|
||||||
contextCancel: cancel,
|
contextCancel: cancel,
|
||||||
ModuleInstances: []module.Module{},
|
ModuleInstances: []module.Module{},
|
||||||
RouteInstances: []route.Route{},
|
RouteInstances: []route.Route{},
|
||||||
logger: slog.Default().With("component", "router"),
|
logger: slog.Default().With("component", "router"),
|
||||||
}
|
}
|
||||||
|
|
||||||
router.logger.Debug("creating router")
|
router.Context = context.WithValue(routerContext, route.RouterContextKey, &router)
|
||||||
|
|
||||||
|
router.logger.Debug("creating")
|
||||||
|
|
||||||
var moduleErrors []module.ModuleError
|
var moduleErrors []module.ModuleError
|
||||||
|
|
||||||
@@ -68,7 +70,7 @@ func NewRouter(ctx context.Context, config config.Config) (*Router, []module.Mod
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !moduleInstanceExists {
|
if !moduleInstanceExists {
|
||||||
moduleInstance, err := moduleInfo.New(router.Context, moduleDecl, &router)
|
moduleInstance, err := moduleInfo.New(router.Context, moduleDecl)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if moduleErrors == nil {
|
if moduleErrors == nil {
|
||||||
moduleErrors = []module.ModuleError{}
|
moduleErrors = []module.ModuleError{}
|
||||||
@@ -107,23 +109,23 @@ func NewRouter(ctx context.Context, config config.Config) (*Router, []module.Mod
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Router) Run() {
|
func (r *Router) Run() {
|
||||||
r.logger.Info("running router")
|
r.logger.Info("running")
|
||||||
for _, moduleInstance := range r.ModuleInstances {
|
for _, moduleInstance := range r.ModuleInstances {
|
||||||
r.moduleWait.Add(1)
|
r.moduleWait.Go(func() {
|
||||||
go func() {
|
|
||||||
err := moduleInstance.Run()
|
err := moduleInstance.Run()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
r.logger.Error("error encountered running module", "error", err)
|
r.logger.Error("error encountered running module", "error", err)
|
||||||
}
|
}
|
||||||
r.moduleWait.Done()
|
})
|
||||||
}()
|
|
||||||
}
|
}
|
||||||
<-r.Context.Done()
|
<-r.Context.Done()
|
||||||
|
r.logger.Debug("waiting for modules to exit")
|
||||||
r.moduleWait.Wait()
|
r.moduleWait.Wait()
|
||||||
r.logger.Info("router done")
|
r.logger.Info("done")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Router) Stop() {
|
func (r *Router) Stop() {
|
||||||
|
r.logger.Debug("stopping")
|
||||||
r.contextCancel()
|
r.contextCancel()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,7 +133,9 @@ func (r *Router) HandleInput(sourceId string, payload any) []route.RouteIOError
|
|||||||
var routingErrors []route.RouteIOError
|
var routingErrors []route.RouteIOError
|
||||||
for routeIndex, routeInstance := range r.RouteInstances {
|
for routeIndex, routeInstance := range r.RouteInstances {
|
||||||
if routeInstance.Input() == sourceId {
|
if routeInstance.Input() == sourceId {
|
||||||
err := routeInstance.HandleInput(r.Context, sourceId, payload, r)
|
routeContext := context.WithValue(r.Context, route.SourceContextKey, sourceId)
|
||||||
|
|
||||||
|
payload, err := routeInstance.ProcessPayload(routeContext, payload)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if routingErrors == nil {
|
if routingErrors == nil {
|
||||||
routingErrors = []route.RouteIOError{}
|
routingErrors = []route.RouteIOError{}
|
||||||
@@ -140,17 +144,18 @@ func (r *Router) HandleInput(sourceId string, payload any) []route.RouteIOError
|
|||||||
Index: routeIndex,
|
Index: routeIndex,
|
||||||
Error: err,
|
Error: err,
|
||||||
})
|
})
|
||||||
r.logger.Error("router unable to route input", "route", routeIndex, "source", sourceId, "error", err)
|
r.logger.Error("unable to route input", "route", routeIndex, "source", sourceId, "error", err)
|
||||||
}
|
}
|
||||||
|
r.HandleOutput(routeContext, routeInstance.Output(), payload)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return routingErrors
|
return routingErrors
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Router) HandleOutput(sourceId string, destinationId string, payload any) error {
|
func (r *Router) HandleOutput(ctx context.Context, destinationId string, payload any) error {
|
||||||
for _, moduleInstance := range r.ModuleInstances {
|
for _, moduleInstance := range r.ModuleInstances {
|
||||||
if moduleInstance.Id() == destinationId {
|
if moduleInstance.Id() == destinationId {
|
||||||
return moduleInstance.Output(payload)
|
return moduleInstance.Output(ctx, payload)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return fmt.Errorf("router could not find module instance for destination %s", destinationId)
|
return fmt.Errorf("router could not find module instance for destination %s", destinationId)
|
||||||
|
|||||||
Reference in New Issue
Block a user