mirror of
https://github.com/jwetzell/showbridge-go.git
synced 2026-04-27 13:25:40 +00:00
Compare commits
437 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f706becdc | ||
|
|
13a494239e | ||
|
|
153de944a2 | ||
|
|
42c75074fe | ||
|
|
361b07ec00 | ||
|
|
8c4f0591e1 | ||
|
|
09ddc40f1f | ||
|
|
6382cf6944 | ||
|
|
0732113a02 | ||
|
|
e5db9a48a9 | ||
|
|
9502201261 | ||
|
|
9859aa8fd4 | ||
|
|
b7b05cbb77 | ||
|
|
7b1fe47039 | ||
|
|
0848d8ab6e | ||
|
|
c1bb2ff4cb | ||
|
|
50898b9130 | ||
|
|
05e68e90af | ||
|
|
cd4c3f59f2 | ||
|
|
50399fa811 | ||
|
|
2dd44a11fd | ||
|
|
b7a8b04a72 | ||
|
|
078e6ec68c | ||
|
|
b58187d6a9 | ||
|
|
38b8e44f04 | ||
|
|
dff33f722d | ||
|
|
572a54d3b2 | ||
|
|
6a21cc2639 | ||
|
|
0d4ec24a9b | ||
|
|
10c6e84682 | ||
|
|
7ac0ec7582 | ||
|
|
c25a36f09c | ||
|
|
8d2c022baf | ||
|
|
76318b4e10 | ||
|
|
633eaba0ec | ||
|
|
00b6f3660d | ||
|
|
a275cd2b78 | ||
|
|
5cb2f845a1 | ||
|
|
8f769f0a4a | ||
|
|
fdd4b341cb | ||
|
|
9a9bf10078 | ||
|
|
ea46885f70 | ||
|
|
fa8f0b7cfc | ||
|
|
d316147411 | ||
|
|
30564523d7 | ||
|
|
f7231e54c2 | ||
|
|
14de829e7a | ||
|
|
33a54eb24c | ||
|
|
3c6c50c914 | ||
|
|
da516f5102 | ||
|
|
1f88819428 | ||
|
|
df4f0f745d | ||
|
|
d86bff30cd | ||
|
|
22d8bbf88d | ||
|
|
925873a124 | ||
|
|
08308c1891 | ||
|
|
f68312ee84 | ||
|
|
cd1b5e1437 | ||
|
|
34af7d7aec | ||
|
|
df14024012 | ||
|
|
af39c16f30 | ||
|
|
7d2a3225a7 | ||
|
|
b5ffee022a | ||
|
|
cd264d9ed4 | ||
|
|
9d14e5929f | ||
|
|
8fe1463198 | ||
|
|
28a5d1ea90 | ||
|
|
e9d5931e9d | ||
|
|
d90f103d00 | ||
|
|
05b0de1dfd | ||
|
|
0d8dbab743 | ||
|
|
fb599f1057 | ||
|
|
a2efed0ee2 | ||
|
|
533fe150c8 | ||
|
|
b653179e6d | ||
|
|
695cabf15e | ||
|
|
ccac116f8d | ||
|
|
c298f63ffc | ||
|
|
183182e6cd | ||
|
|
01f172dbee | ||
|
|
20fd4170ed | ||
|
|
bcf9299505 | ||
|
|
4f7820af5e | ||
|
|
87fcc63068 | ||
|
|
1c49776662 | ||
|
|
1a7207ae4c | ||
|
|
f86a34cc92 | ||
|
|
d9d64bd248 | ||
|
|
e828dc1b0b | ||
|
|
cc4d50bc17 | ||
|
|
abd37439c5 | ||
|
|
8c3f93b601 | ||
|
|
2f7f6967e1 | ||
|
|
09b030efa6 | ||
|
|
bb49dba22e | ||
|
|
4ed6866731 | ||
|
|
2d392873ca | ||
|
|
11e25ab8f7 | ||
|
|
87e6b09156 | ||
|
|
8cb2a0e9f0 | ||
|
|
263943f4d6 | ||
|
|
f9865765c6 | ||
|
|
e6aaffbb95 | ||
|
|
90a14b4d1b | ||
|
|
8bdd338a27 | ||
|
|
b20c16be4f | ||
|
|
de060057e6 | ||
|
|
4526e805af | ||
|
|
1d8baa8c17 | ||
|
|
060c12512c | ||
|
|
444093d375 | ||
|
|
a217b729cd | ||
|
|
ad76480008 | ||
|
|
a408e281a3 | ||
|
|
f028634401 | ||
|
|
961316d28b | ||
|
|
e22a941e4a | ||
|
|
b0cffe819d | ||
|
|
0cdd1f6e6a | ||
|
|
a9245ab88c | ||
|
|
d69d3a370d | ||
|
|
019624f152 | ||
|
|
90a3119fb8 | ||
|
|
54c14cbbae | ||
|
|
969ac6e04b | ||
|
|
bfa63499c3 | ||
|
|
6b178d1ae4 | ||
|
|
988437fccf | ||
|
|
dc19d18b81 | ||
|
|
86f1082159 | ||
|
|
a46054c427 | ||
|
|
9dc4706fd8 | ||
|
|
f91cb9dbbf | ||
|
|
10b5cbae6c | ||
|
|
a9f9f1ba2c | ||
|
|
8e27dc81a2 | ||
|
|
42bd5c46b5 | ||
|
|
515a8d14fd | ||
|
|
1f3a2b9076 | ||
|
|
5dc897c4b2 | ||
|
|
7015a9d7a2 | ||
|
|
3c6d98638e | ||
|
|
8ec8ad91a6 | ||
|
|
f919017ca6 | ||
|
|
66f170047a | ||
|
|
7ff20e0136 | ||
|
|
b53494fddc | ||
|
|
3688510ded | ||
|
|
d0bdc44c30 | ||
|
|
1c49548a4c | ||
|
|
4ea6c8f11f | ||
|
|
0ef512eb28 | ||
|
|
ebbce3261c | ||
|
|
79fa925823 | ||
|
|
659c95102b | ||
|
|
e06c4195c7 | ||
|
|
28e3c99ad8 | ||
|
|
7312bfec20 | ||
|
|
4bbf69e644 | ||
|
|
1ba51446ad | ||
|
|
2266d6a9b8 | ||
|
|
f1f340f963 | ||
|
|
4ca989280c | ||
|
|
ef83e84e84 | ||
|
|
b8ad912855 | ||
|
|
f766d0e2a4 | ||
|
|
725e8ad670 | ||
|
|
7fa3b6d33d | ||
|
|
5e957d7d03 | ||
|
|
bd89df3da2 | ||
|
|
914f6aa833 | ||
|
|
2104d9f1a9 | ||
|
|
457ff83c23 | ||
|
|
37c7a23063 | ||
|
|
9ba3a88e8c | ||
|
|
33ecc94097 | ||
|
|
8f5091cf9b | ||
|
|
b095419b6e | ||
|
|
1e872ba0b9 | ||
|
|
b959b88527 | ||
|
|
0dfbf30fa7 | ||
|
|
abff674a75 | ||
|
|
a920f34926 | ||
|
|
4dac1faae0 | ||
|
|
ab5b40ee72 | ||
|
|
5a29139e63 | ||
|
|
1587f84981 | ||
|
|
0cb13a30f9 | ||
|
|
8212d15a70 | ||
|
|
eee356225f | ||
|
|
5cd02f9e3a | ||
|
|
100edab869 | ||
|
|
fd4c2cb59b | ||
|
|
b6ee3c68f1 | ||
|
|
7e0c2b2560 | ||
|
|
c9a3eb80bc | ||
|
|
2a5feec07a | ||
|
|
ced4bc839e | ||
|
|
ce6a9ff4a8 | ||
|
|
bd3b8a19d5 | ||
|
|
cb738a9b8e | ||
|
|
1b59dbc1e5 | ||
|
|
c75a2327d5 | ||
|
|
a17be985e6 | ||
|
|
78737f57af | ||
|
|
720c0cd52a | ||
|
|
3e1d4f07f9 | ||
|
|
452e308f8f | ||
|
|
d16d833520 | ||
|
|
f203b32261 | ||
|
|
361c4f4499 | ||
|
|
a76d12d799 | ||
|
|
7d91e64ec4 | ||
|
|
589c59c693 | ||
|
|
56c67c5445 | ||
|
|
13229215a6 | ||
|
|
909b4d2337 | ||
|
|
3bcb9a6608 | ||
|
|
17dcffc09b | ||
|
|
8318645eef | ||
|
|
0c777a8874 | ||
|
|
a8f9894ff0 | ||
|
|
f0f74f50e5 | ||
|
|
bb3a8b982b | ||
|
|
be9ce5a8aa | ||
|
|
ac2cf078a4 | ||
|
|
0fc264d0e9 | ||
|
|
3c99eef999 | ||
|
|
f7c3a85649 | ||
|
|
76caccd9f8 | ||
|
|
e8c71562a6 | ||
|
|
42551127ba | ||
|
|
a99fef9389 | ||
|
|
e6099b6acd | ||
|
|
b93d754c19 | ||
|
|
710dcf3a02 | ||
|
|
ac83b339a6 | ||
|
|
cb06e2dbb5 | ||
|
|
3ef41d0026 | ||
|
|
8dcb70bfee | ||
|
|
59f00c1a32 | ||
|
|
6e88d259b8 | ||
|
|
bb33974e1c | ||
|
|
bd2a68ff6e | ||
|
|
7e2d76ef3a | ||
|
|
d1cec1e094 | ||
|
|
477d70fad0 | ||
|
|
70f4636522 | ||
|
|
0248ca6973 | ||
|
|
4aa586427b | ||
|
|
6d3cf6692f | ||
|
|
a263b10690 | ||
|
|
3ce2909b0f | ||
|
|
b15e282d59 | ||
|
|
f97f9b9fc9 | ||
|
|
12de947f3d | ||
|
|
7335ba973a | ||
|
|
a994286402 | ||
|
|
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 | ||
|
|
168265f0a9 | ||
|
|
caee7b269c | ||
|
|
b0cc47236f | ||
|
|
f6c2b1d9ac | ||
|
|
f977b845be | ||
|
|
0166383978 | ||
|
|
66cfaa3091 | ||
|
|
0904d2fcb8 | ||
|
|
6a13c38e77 | ||
|
|
1a8ccfc64a | ||
|
|
2e3bb408c3 | ||
|
|
3d75165a61 | ||
|
|
50f755f914 | ||
|
|
b10e296d0a | ||
|
|
91c44420cb | ||
|
|
c1b2fa714e | ||
|
|
ff1949ce69 | ||
|
|
76583b1fb8 | ||
|
|
e6433878b5 | ||
|
|
3ad067cbb8 | ||
|
|
30b406d601 | ||
|
|
7315d40015 | ||
|
|
e7105b8b39 | ||
|
|
ec40194ecb | ||
|
|
85d8dc5787 | ||
|
|
b27bfb1a6d | ||
|
|
fb9c0bc657 | ||
|
|
d32d23041b | ||
|
|
b4149df00a | ||
|
|
61bd4b64f5 | ||
|
|
38d73881c9 | ||
|
|
3138bdfcdb | ||
|
|
ba862300b2 | ||
|
|
e414bf336e | ||
|
|
da95fb5c75 | ||
|
|
1fdc30aa9e | ||
|
|
128920dff9 | ||
|
|
9cb7abcc8f | ||
|
|
991111deba | ||
|
|
9b1ca9da96 | ||
|
|
b726745aa2 | ||
|
|
a8bcf7a785 | ||
|
|
32d8633402 | ||
|
|
f3aaa86a1c | ||
|
|
25b06ffc6d | ||
|
|
ca3d662df7 | ||
|
|
86fe006af8 | ||
|
|
d94232871e | ||
|
|
5c8605104d | ||
|
|
e7b43b6637 | ||
|
|
2221207036 | ||
|
|
dca1535f5a | ||
|
|
8b2eaf3ef4 | ||
|
|
c19837df1e | ||
|
|
783c333b46 | ||
|
|
2497c9c8e4 | ||
|
|
54a8164dd3 | ||
|
|
2c6a2f5a36 | ||
|
|
92f91cf260 | ||
|
|
5c94cddc74 | ||
|
|
7a0e945ecd | ||
|
|
1eaabf2e75 | ||
|
|
955dcca8c6 | ||
|
|
d312baeb6e | ||
|
|
00f78b5a50 | ||
|
|
b59da597ba | ||
|
|
8ca105a0b6 | ||
|
|
e027f22f8b | ||
|
|
55f5767d47 | ||
|
|
66435fc2ba | ||
|
|
a85b0e64e0 | ||
|
|
202d1aea1f | ||
|
|
3a7b484c76 | ||
|
|
ffb39b1034 | ||
|
|
bb78b7b08b | ||
|
|
48ac2640d0 | ||
|
|
25324a4dcd | ||
|
|
bebcd56d70 | ||
|
|
ce8e18dd4f | ||
|
|
f4021d858b | ||
|
|
008d7665bd | ||
|
|
917f728f14 | ||
|
|
e3b6783a98 | ||
|
|
5e7ebd1bf1 | ||
|
|
0bd43ca0c3 | ||
|
|
2e7feede28 | ||
|
|
a5deea6447 | ||
|
|
3f6914282b | ||
|
|
7a01ce6691 | ||
|
|
5be40a5abf | ||
|
|
388851f8bd | ||
|
|
9a06949b5b | ||
|
|
8d8347fc4d | ||
|
|
07108918f1 | ||
|
|
2c6502b622 | ||
|
|
4c0f7c1723 | ||
|
|
04103cc6ca | ||
|
|
66097f7297 | ||
|
|
3eb3ccca0c | ||
|
|
55452d9dd0 | ||
|
|
ed4f7dc1f7 | ||
|
|
190bdd8b44 | ||
|
|
a7f889f6b5 | ||
|
|
5c5111a25e | ||
|
|
b31729fafe | ||
|
|
dff5430eb4 | ||
|
|
eaca0dbf86 | ||
|
|
aa3a1032f3 | ||
|
|
51a62f7fb2 | ||
|
|
2c8efcea4b | ||
|
|
df1882b8f7 | ||
|
|
1c8346cf65 | ||
|
|
ba2fead834 | ||
|
|
cb7504922e | ||
|
|
59d9405781 | ||
|
|
fbda348b58 | ||
|
|
c1a98483a4 | ||
|
|
cd567e5b97 | ||
|
|
d8d53f01d2 | ||
|
|
f363fbf0a6 | ||
|
|
d629146592 | ||
|
|
b06ced2631 | ||
|
|
a33fe88757 | ||
|
|
ce673e31db | ||
|
|
38857f7a29 | ||
|
|
45965a4eac | ||
|
|
b372b53422 | ||
|
|
97cf721abc | ||
|
|
afa32b8c2f | ||
|
|
d3244fbe90 | ||
|
|
d6e73d1bb0 | ||
|
|
067412ec9f | ||
|
|
0741cd2293 |
5
.dockerignore
Normal file
5
.dockerignore
Normal file
@@ -0,0 +1,5 @@
|
||||
Dockerfile
|
||||
.github
|
||||
.vscode
|
||||
README.md
|
||||
LICENSE
|
||||
2
.github/FUNDING.yml
vendored
Normal file
2
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
# These are supported funding model platforms
|
||||
github: [jwetzell]
|
||||
27
.github/labeler.yml
vendored
Normal file
27
.github/labeler.yml
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
config:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/config/**'
|
||||
|
||||
framer:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/framer/**'
|
||||
|
||||
module:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/module/**'
|
||||
|
||||
processor:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/processor/**'
|
||||
|
||||
router:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'router*'
|
||||
|
||||
route:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/route/**'
|
||||
|
||||
cli:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'cmd/showbridge/**'
|
||||
29
.github/release.yml
vendored
Normal file
29
.github/release.yml
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
changelog:
|
||||
exclude:
|
||||
authors:
|
||||
- dependabot
|
||||
labels:
|
||||
- dependencies
|
||||
categories:
|
||||
- title: Config ⚙️
|
||||
labels:
|
||||
- config
|
||||
- title: Framer 🖼️
|
||||
labels:
|
||||
- framer
|
||||
- title: Module 📦
|
||||
labels:
|
||||
- module
|
||||
- title: Processor 🏭
|
||||
labels:
|
||||
- processor
|
||||
- title: Routing 🛣️
|
||||
labels:
|
||||
- router
|
||||
- route
|
||||
- title: CLI ⌨️
|
||||
labels:
|
||||
- cli
|
||||
- title: Other Changes
|
||||
labels:
|
||||
- '*'
|
||||
18
.github/workflows/label-pr.yaml
vendored
Normal file
18
.github/workflows/label-pr.yaml
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
# Taken from https://github.com/go-gitea/gitea
|
||||
name: Add labels to PR
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened]
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
labeler:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/labeler@634933edcd8ababfe52f92936142cc22ac488b1b # v6.0.1
|
||||
with:
|
||||
sync-labels: true
|
||||
43
.github/workflows/release-showbridge.yaml
vendored
43
.github/workflows/release-showbridge.yaml
vendored
@@ -3,7 +3,7 @@ name: showbridge release
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "*"
|
||||
- "v*"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -17,11 +17,11 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
- name: release
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
uses: goreleaser/goreleaser-action@v7
|
||||
with:
|
||||
workdir: cmd/showbridge
|
||||
distribution: goreleaser
|
||||
@@ -29,3 +29,40 @@ jobs:
|
||||
args: release --clean
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
docker:
|
||||
runs-on: ubuntu-latest
|
||||
needs: goreleaser
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Setup Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
with:
|
||||
images: |
|
||||
jwetzell/showbridge
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
|
||||
with:
|
||||
push: true
|
||||
context: ./
|
||||
file: ./Dockerfile
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
platforms: linux/amd64
|
||||
|
||||
16
.github/workflows/test-showbridge.yaml
vendored
16
.github/workflows/test-showbridge.yaml
vendored
@@ -17,7 +17,7 @@ on:
|
||||
- 'go.sum'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@@ -34,4 +34,16 @@ jobs:
|
||||
run: go mod tidy
|
||||
|
||||
- name: run tests
|
||||
run: go test ./...
|
||||
run: go test ./... -count=1 -coverpkg "github.com/jwetzell/showbridge-go/..." -coverprofile coverage.out
|
||||
|
||||
- name: clean up coverage report
|
||||
run: cat coverage.out | grep -v "github.com/jwetzell/showbridge-go/cmd" > coverage.nocmd.out
|
||||
- name: Update coverage report
|
||||
uses: ncruces/go-coverage-report@v0.3.2
|
||||
with:
|
||||
coverage-file: coverage.nocmd.out
|
||||
report: true
|
||||
chart: true
|
||||
amend: true
|
||||
if: github.event_name == 'push'
|
||||
continue-on-error: true
|
||||
|
||||
18
.vscode/launch.json
vendored
Normal file
18
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
|
||||
{
|
||||
"name": "Launch showbridge",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "cmd/showbridge",
|
||||
"args": ["--log-level", "debug"],
|
||||
"cwd": "./"
|
||||
}
|
||||
]
|
||||
}
|
||||
15
Dockerfile
Normal file
15
Dockerfile
Normal file
@@ -0,0 +1,15 @@
|
||||
ARG GO_VERSION=1.26.0
|
||||
FROM golang:${GO_VERSION}-alpine AS build
|
||||
RUN apk --no-cache add ca-certificates tzdata
|
||||
WORKDIR /build
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build ./cmd/showbridge
|
||||
|
||||
FROM scratch
|
||||
WORKDIR /app
|
||||
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
COPY --from=build /usr/share/zoneinfo /usr/share/zoneinfo
|
||||
COPY --from=build /build/showbridge /app/showbridge
|
||||
ENTRYPOINT [ "/app/showbridge" ]
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Joel Wetzell
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
44
README.md
Normal file
44
README.md
Normal file
@@ -0,0 +1,44 @@
|
||||
<div align="center">
|
||||
|
||||
# showbridge (go edition)
|
||||
|
||||
[](https://raw.githack.com/wiki/jwetzell/showbridge-go/coverage.html)
|
||||
|
||||
Simple protocol router _/s_
|
||||
|
||||
</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
|
||||
- HTTP
|
||||
- UDP
|
||||
- TCP
|
||||
- [MQTT](https://mqtt.org/)
|
||||
- [NATS](https://nats.io/)
|
||||
- [PosiStageNet](https://posistage.net/)
|
||||
- MIDI (not included in pre-built binaries yet)
|
||||
- Serial (not included in pre-built binaries yet)
|
||||
- [OSC](https://opensoundcontrol.stanford.edu/spec-1_0.html)
|
||||
- [FreeD](https://ptzoptics.com/freed/)
|
||||
- [SIP](https://en.wikipedia.org/wiki/Session_Initiation_Protocol)
|
||||
|
||||
### CLI Usage
|
||||
|
||||
```
|
||||
NAME:
|
||||
showbridge - Simple protocol router /s
|
||||
|
||||
USAGE:
|
||||
showbridge [global options]
|
||||
|
||||
GLOBAL OPTIONS:
|
||||
--config string path to config file (default: "./config.yaml")
|
||||
--log-level string set log level (default: "info")
|
||||
--log-format string log format to use (default: "text")
|
||||
--help, -h show help
|
||||
--version, -v print the version
|
||||
```
|
||||
@@ -14,6 +14,8 @@ builds:
|
||||
goarch:
|
||||
- "amd64"
|
||||
- "arm64"
|
||||
ldflags:
|
||||
- '-s -w -X main.version={{.RawVersion}}-{{.ShortCommit}}'
|
||||
|
||||
archives:
|
||||
- formats: [tar.gz]
|
||||
@@ -24,6 +26,7 @@ archives:
|
||||
|
||||
changelog:
|
||||
sort: asc
|
||||
use: github-native
|
||||
|
||||
release:
|
||||
draft: true
|
||||
|
||||
@@ -2,49 +2,78 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"slices"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/jwetzell/showbridge-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/urfave/cli/v3"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.39.0"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
var (
|
||||
version = "dev"
|
||||
sigHangup = make(chan os.Signal, 1)
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := &cli.Command{
|
||||
Name: "showbridge",
|
||||
Name: "showbridge",
|
||||
Usage: "Simple protocol router /s",
|
||||
Version: version,
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "config",
|
||||
Value: "./config.yaml",
|
||||
Usage: "path to config file",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "log-level",
|
||||
Value: "info",
|
||||
Usage: "set log level",
|
||||
Validator: func(level string) error {
|
||||
levels := []string{"debug", "info", "warn", "error"}
|
||||
if !slices.Contains(levels, level) {
|
||||
return fmt.Errorf("unknown log level: %s", level)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "log-format",
|
||||
Value: "text",
|
||||
Usage: "log format to use",
|
||||
Validator: func(format string) error {
|
||||
formats := []string{"text", "json"}
|
||||
if !slices.Contains(formats, format) {
|
||||
return fmt.Errorf("unknown log format: %s", format)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "trace",
|
||||
Value: false,
|
||||
Usage: "enable OpenTelemetry tracing",
|
||||
},
|
||||
},
|
||||
Action: func(ctx context.Context, c *cli.Command) error {
|
||||
configPath := c.String("config")
|
||||
if configPath == "" {
|
||||
return fmt.Errorf("config value cannot be empty")
|
||||
}
|
||||
|
||||
config, err := readConfig(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
router, moduleErrors, routeErrors := showbridge.NewRouter(ctx, config)
|
||||
for _, moduleError := range moduleErrors {
|
||||
slog.Error("problem initializing module", "index", moduleError.Index, "error", moduleError.Error)
|
||||
}
|
||||
|
||||
for _, routeError := range routeErrors {
|
||||
slog.Error("problem initializing route", "index", routeError.Index, "error", routeError.Error)
|
||||
}
|
||||
router.Run()
|
||||
return nil
|
||||
},
|
||||
Action: run,
|
||||
}
|
||||
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Interrupt)
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
|
||||
signal.Notify(sigHangup, syscall.SIGHUP)
|
||||
defer cancel()
|
||||
err := cmd.Run(ctx, os.Args)
|
||||
|
||||
@@ -54,19 +83,183 @@ func main() {
|
||||
|
||||
}
|
||||
|
||||
func readConfig(configPath string) (showbridge.Config, error) {
|
||||
type showbridgeApp struct {
|
||||
ctx context.Context
|
||||
configPath string
|
||||
logger *slog.Logger
|
||||
router *showbridge.Router
|
||||
routerRunner *sync.WaitGroup
|
||||
routerMutex sync.Mutex
|
||||
}
|
||||
|
||||
func readConfig(configPath string) (config.Config, error) {
|
||||
cfg := config.Config{}
|
||||
|
||||
configBytes, err := os.ReadFile(configPath)
|
||||
|
||||
if err != nil {
|
||||
return showbridge.Config{}, err
|
||||
return config.Config{}, err
|
||||
}
|
||||
|
||||
config := showbridge.Config{}
|
||||
|
||||
err = yaml.Unmarshal(configBytes, &config)
|
||||
err = yaml.Unmarshal(configBytes, &cfg)
|
||||
if err != nil {
|
||||
return showbridge.Config{}, err
|
||||
return config.Config{}, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func run(ctx context.Context, c *cli.Command) error {
|
||||
configPath := c.String("config")
|
||||
if configPath == "" {
|
||||
return errors.New("config path cannot be empty")
|
||||
}
|
||||
|
||||
logLevel := slog.LevelInfo
|
||||
|
||||
logLevelFromFlag := c.String("log-level")
|
||||
|
||||
switch logLevelFromFlag {
|
||||
case "debug":
|
||||
logLevel = slog.LevelDebug
|
||||
case "info":
|
||||
logLevel = slog.LevelInfo
|
||||
case "warn":
|
||||
logLevel = slog.LevelWarn
|
||||
case "error":
|
||||
logLevel = slog.LevelError
|
||||
default:
|
||||
logLevel = slog.LevelInfo
|
||||
}
|
||||
|
||||
logHandlerOptions := &slog.HandlerOptions{
|
||||
Level: logLevel,
|
||||
}
|
||||
|
||||
logOutput := os.Stderr
|
||||
|
||||
var logHandler slog.Handler
|
||||
|
||||
logFormat := c.String("log-format")
|
||||
|
||||
switch logFormat {
|
||||
case "json":
|
||||
logHandler = slog.NewJSONHandler(logOutput, logHandlerOptions)
|
||||
case "text":
|
||||
logHandler = slog.NewTextHandler(logOutput, logHandlerOptions)
|
||||
default:
|
||||
logHandler = slog.NewTextHandler(logOutput, logHandlerOptions)
|
||||
}
|
||||
|
||||
slog.SetDefault(slog.New(logHandler))
|
||||
|
||||
if c.Bool("trace") {
|
||||
exporter, err := otlptracehttp.New(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create trace exporter: %w", err)
|
||||
}
|
||||
|
||||
tracerProvider := newTracerProvider(exporter)
|
||||
otel.SetTracerProvider(tracerProvider)
|
||||
defer tracerProvider.Shutdown(ctx)
|
||||
|
||||
otel.SetTracerProvider(tracerProvider)
|
||||
}
|
||||
|
||||
showbridgeApp := &showbridgeApp{
|
||||
ctx: ctx,
|
||||
configPath: configPath,
|
||||
logger: slog.Default().With("component", "cmd"),
|
||||
routerRunner: &sync.WaitGroup{},
|
||||
}
|
||||
|
||||
router, err := showbridgeApp.getNewRouter()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize router: %w", err)
|
||||
}
|
||||
showbridgeApp.routerMutex.Lock()
|
||||
showbridgeApp.router = router
|
||||
|
||||
showbridgeApp.routerRunner.Go(func() {
|
||||
router.Start(context.Background())
|
||||
})
|
||||
showbridgeApp.routerMutex.Unlock()
|
||||
|
||||
go showbridgeApp.handleHangup()
|
||||
|
||||
<-showbridgeApp.ctx.Done()
|
||||
showbridgeApp.logger.Debug("shutting down router")
|
||||
showbridgeApp.router.Stop()
|
||||
showbridgeApp.logger.Debug("waiting for router to exit")
|
||||
showbridgeApp.routerRunner.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (app *showbridgeApp) handleHangup() {
|
||||
for {
|
||||
select {
|
||||
case <-sigHangup:
|
||||
app.logger.Info("received SIGHUP, reloading configuration")
|
||||
newRouter, err := app.getNewRouter()
|
||||
if err != nil {
|
||||
app.logger.Error("failed to reload configuration", "error", err)
|
||||
continue
|
||||
}
|
||||
app.routerMutex.Lock()
|
||||
app.router.Stop()
|
||||
app.routerRunner.Wait()
|
||||
app.router = newRouter
|
||||
app.routerRunner.Go(func() {
|
||||
app.router.Start(context.Background())
|
||||
})
|
||||
app.logger.Info("configuration reloaded successfully")
|
||||
app.routerMutex.Unlock()
|
||||
case <-app.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (app *showbridgeApp) getNewRouter() (*showbridge.Router, error) {
|
||||
// TODO(jwetzell): what should happen when the config file is unchanged?
|
||||
config, err := readConfig(app.configPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
router, moduleErrors, routeErrors := showbridge.NewRouter(config)
|
||||
|
||||
for _, moduleError := range moduleErrors {
|
||||
app.logger.Error("problem initializing module", "index", moduleError.Index, "error", moduleError.Error)
|
||||
}
|
||||
|
||||
for _, routeError := range routeErrors {
|
||||
app.logger.Error("problem initializing route", "index", routeError.Index, "error", routeError.Error)
|
||||
}
|
||||
|
||||
if moduleErrors != nil || routeErrors != nil {
|
||||
return nil, fmt.Errorf("errors initializing modules or routes")
|
||||
}
|
||||
|
||||
return router, nil
|
||||
}
|
||||
|
||||
func newTracerProvider(exp sdktrace.SpanExporter) *sdktrace.TracerProvider {
|
||||
r, err := resource.Merge(
|
||||
resource.Default(),
|
||||
resource.NewWithAttributes(
|
||||
semconv.SchemaURL,
|
||||
semconv.ServiceName("showbridge"),
|
||||
semconv.ServiceVersion(version),
|
||||
),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return sdktrace.NewTracerProvider(
|
||||
sdktrace.WithBatcher(exp),
|
||||
sdktrace.WithResource(r),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
package showbridge
|
||||
|
||||
type Config struct {
|
||||
Modules []ModuleConfig `json:"modules"`
|
||||
Routes []RouteConfig `json:"routes"`
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
modules:
|
||||
- id: http
|
||||
type: net.http.server
|
||||
type: http.server
|
||||
params:
|
||||
port: 3000
|
||||
- id: udp
|
||||
@@ -13,6 +13,8 @@ routes:
|
||||
processors:
|
||||
- type: osc.message.create
|
||||
params:
|
||||
address: "{{.URL.Path}}"
|
||||
address: "{{.Payload.URL.Path}}"
|
||||
- type: osc.message.encode
|
||||
output: udp
|
||||
- type: router.output
|
||||
params:
|
||||
module: udp
|
||||
|
||||
83
go.mod
83
go.mod
@@ -1,33 +1,88 @@
|
||||
module github.com/jwetzell/showbridge-go
|
||||
|
||||
go 1.25.3
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/expr-lang/expr v1.17.6
|
||||
github.com/emiago/diago v0.27.0
|
||||
github.com/emiago/sipgo v1.2.0
|
||||
github.com/expr-lang/expr v1.17.8
|
||||
github.com/extism/go-sdk v1.7.1
|
||||
github.com/jwetzell/artnet-go v0.2.1
|
||||
github.com/jwetzell/free-d-go v0.1.0
|
||||
github.com/jwetzell/osc-go v0.1.0
|
||||
github.com/jwetzell/psn-go v0.2.1
|
||||
github.com/urfave/cli/v3 v3.6.1
|
||||
gitlab.com/gomidi/midi/v2 v2.3.16
|
||||
modernc.org/quickjs v0.17.0
|
||||
github.com/jwetzell/osc-go v0.2.0
|
||||
github.com/jwetzell/psn-go v0.3.0
|
||||
github.com/nats-io/nats-server/v2 v2.12.4
|
||||
github.com/nats-io/nats.go v1.49.0
|
||||
github.com/urfave/cli/v3 v3.7.0
|
||||
gitlab.com/gomidi/midi/v2 v2.3.23
|
||||
go.bug.st/serial v1.6.4
|
||||
go.opentelemetry.io/otel v1.41.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0
|
||||
go.opentelemetry.io/otel/sdk v1.41.0
|
||||
go.opentelemetry.io/otel/trace v1.41.0
|
||||
modernc.org/quickjs v0.17.1
|
||||
sigs.k8s.io/yaml v1.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/creack/goselect v0.1.2 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a // indirect
|
||||
github.com/emiago/dtls/v3 v3.0.0-20260122183559-8b8d23e359c0 // indirect
|
||||
github.com/go-audio/riff v1.0.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/gobwas/glob v0.2.3 // indirect
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
github.com/gobwas/ws v1.4.0 // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca // indirect
|
||||
github.com/icholy/digest v1.1.0 // indirect
|
||||
github.com/klauspost/compress v1.18.3 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76 // indirect
|
||||
github.com/nats-io/jwt/v2 v2.8.0 // indirect
|
||||
github.com/nats-io/nkeys v0.4.12 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/pion/logging v0.2.4 // indirect
|
||||
github.com/pion/randutil v0.1.0 // indirect
|
||||
github.com/pion/rtcp v1.2.16 // indirect
|
||||
github.com/pion/rtp v1.8.26 // indirect
|
||||
github.com/pion/srtp/v3 v3.0.9 // indirect
|
||||
github.com/pion/transport/v3 v3.1.1 // indirect
|
||||
github.com/pion/transport/v4 v4.0.1 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect
|
||||
github.com/tetratelabs/wazero v1.9.0 // indirect
|
||||
github.com/zaf/g711 v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.41.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
golang.org/x/net v0.44.0 // indirect
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/sys v0.36.0 // indirect
|
||||
modernc.org/libc v1.66.10 // indirect
|
||||
modernc.org/libquickjs v0.12.2 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
|
||||
golang.org/x/net v0.50.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
golang.org/x/time v0.14.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 // indirect
|
||||
google.golang.org/grpc v1.79.1 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/hraban/opus.v2 v2.0.0-20230925203106-0188a62cb302 // indirect
|
||||
modernc.org/libc v1.67.1 // indirect
|
||||
modernc.org/libquickjs v0.12.3 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
|
||||
199
go.sum
199
go.sum
@@ -1,60 +1,189 @@
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op h1:Ucf+QxEKMbPogRO5guBNe5cgd9uZgfoJLOYs8WWhtjM=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0=
|
||||
github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a h1:UwSIFv5g5lIvbGgtf3tVwC7Ky9rmMFBp0RMs+6f6YqE=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU=
|
||||
github.com/expr-lang/expr v1.17.6 h1:1h6i8ONk9cexhDmowO/A64VPxHScu7qfSl2k8OlINec=
|
||||
github.com/expr-lang/expr v1.17.6/go.mod h1:8/vRC7+7HBzESEqt5kKpYXxrxkr31SaO8r40VO/1IT4=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/emiago/diago v0.27.0 h1:5SQBbcLR9ooxhSMlTkU9QSuDv/2nhMO9lxuWJTd/7rE=
|
||||
github.com/emiago/diago v0.27.0/go.mod h1:8hUxCDPJY2p32hh+4ed7vHW/3yTMmEa3BjNctUPeGD0=
|
||||
github.com/emiago/dtls/v3 v3.0.0-20260122183559-8b8d23e359c0 h1:o4LxpUnZ1zxiQ+Qjc9kLwXcjz31NGAHmnZ7xoJto3VM=
|
||||
github.com/emiago/dtls/v3 v3.0.0-20260122183559-8b8d23e359c0/go.mod h1:ydcZ977eS1I6uOWodzMuw30BwvNAzT9su/xcNYSJqjA=
|
||||
github.com/emiago/sipgo v1.2.0 h1:rmHFdCu9zu2Cabfd8+/eC9HQWyooqk8x+ti550z5lBw=
|
||||
github.com/emiago/sipgo v1.2.0/go.mod h1:DuwAxBZhKMqIzQFPGZb1MVAGU6Wuxj64oTOhd5dx/FY=
|
||||
github.com/expr-lang/expr v1.17.8 h1:W1loDTT+0PQf5YteHSTpju2qfUfNoBt4yw9+wOEU9VM=
|
||||
github.com/expr-lang/expr v1.17.8/go.mod h1:8/vRC7+7HBzESEqt5kKpYXxrxkr31SaO8r40VO/1IT4=
|
||||
github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
|
||||
github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA=
|
||||
github.com/go-audio/riff v1.0.0 h1:d8iCGbDvox9BfLagY94fBynxSPHO80LmZCaOsmKxokA=
|
||||
github.com/go-audio/riff v1.0.0/go.mod h1:l3cQwc85y79NQFCRB7TiPoNiaijp6q8Z0Uv38rVG498=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
|
||||
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
|
||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
|
||||
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
|
||||
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca h1:T54Ema1DU8ngI+aef9ZhAhNGQhcRTrWxVeG07F+c/Rw=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
|
||||
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/jwetzell/artnet-go v0.2.1 h1:iYTKWcwYrF5kBkYfkw2UbWvoueeA23iKEn7fR27mWZE=
|
||||
github.com/jwetzell/artnet-go v0.2.1/go.mod h1:gli97Z32a0kMkZ6taoTiK7/lqHcF/dhiGjGJdx/PxqA=
|
||||
github.com/jwetzell/free-d-go v0.1.0 h1:xHt6dvyit98X+OC3jVzV0aLidxbyzi3vI9QiYkteEtA=
|
||||
github.com/jwetzell/free-d-go v0.1.0/go.mod h1:KmrkooRARRaxJTBSPvwt/6IMAIaHH1R8bSA8cwbbELw=
|
||||
github.com/jwetzell/osc-go v0.1.0 h1:EXxup5VWBErHot2Ri4MFToPf6KCzLDTbCt2x6GLfw8I=
|
||||
github.com/jwetzell/osc-go v0.1.0/go.mod h1:xLz0jTwebSxtx1TkKN1YVdeRqvpFNweDhTut5TE393A=
|
||||
github.com/jwetzell/psn-go v0.2.1 h1:pNG6XNfVRTb4qctH6pJjRJ1ReYGnGgNRA4H7tNbmzRU=
|
||||
github.com/jwetzell/psn-go v0.2.1/go.mod h1:bcEAeti4sQM375buujb3mIfmUstD4Aby18gq3ENb6+o=
|
||||
github.com/jwetzell/osc-go v0.2.0 h1:4as+BYCeZhEddFczGveP5yZZxvY728Uavz+ZSLZfOII=
|
||||
github.com/jwetzell/osc-go v0.2.0/go.mod h1:D3ZIXYB12bt4S35lKFUqgCFbF1Y+9Ld0sOhHA9mGZZM=
|
||||
github.com/jwetzell/psn-go v0.3.0 h1:WVpCEmExYE8a+I5hQak5jNJJp2x35VdGX/VuMUKPmhY=
|
||||
github.com/jwetzell/psn-go v0.3.0/go.mod h1:bcEAeti4sQM375buujb3mIfmUstD4Aby18gq3ENb6+o=
|
||||
github.com/klauspost/compress v1.18.3 h1:9PJRvfbmTabkOX8moIpXPbMMbYN60bWImDDU7L+/6zw=
|
||||
github.com/klauspost/compress v1.18.3/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76 h1:KGuD/pM2JpL9FAYvBrnBBeENKZNh6eNtjqytV6TYjnk=
|
||||
github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
|
||||
github.com/nats-io/jwt/v2 v2.8.0 h1:K7uzyz50+yGZDO5o772eRE7atlcSEENpL7P+b74JV1g=
|
||||
github.com/nats-io/jwt/v2 v2.8.0/go.mod h1:me11pOkwObtcBNR8AiMrUbtVOUGkqYjMQZ6jnSdVUIA=
|
||||
github.com/nats-io/nats-server/v2 v2.12.4 h1:ZnT10v2LU2Xcoiy8ek9X6Se4YG8EuMfIfvAEuFVx1Ts=
|
||||
github.com/nats-io/nats-server/v2 v2.12.4/go.mod h1:5MCp/pqm5SEfsvVZ31ll1088ZTwEUdvRX1Hmh/mTTDg=
|
||||
github.com/nats-io/nats.go v1.49.0 h1:yh/WvY59gXqYpgl33ZI+XoVPKyut/IcEaqtsiuTJpoE=
|
||||
github.com/nats-io/nats.go v1.49.0/go.mod h1:fDCn3mN5cY8HooHwE2ukiLb4p4G4ImmzvXyJt+tGwdw=
|
||||
github.com/nats-io/nkeys v0.4.12 h1:nssm7JKOG9/x4J8II47VWCL1Ds29avyiQDRn0ckMvDc=
|
||||
github.com/nats-io/nkeys v0.4.12/go.mod h1:MT59A1HYcjIcyQDJStTfaOY6vhy9XTUjOFo+SVsvpBg=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
|
||||
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
|
||||
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
|
||||
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
|
||||
github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo=
|
||||
github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo=
|
||||
github.com/pion/rtp v1.8.26 h1:VB+ESQFQhBXFytD+Gk8cxB6dXeVf2WQzg4aORvAvAAc=
|
||||
github.com/pion/rtp v1.8.26/go.mod h1:rF5nS1GqbR7H/TCpKwylzeq6yDM+MM6k+On5EgeThEM=
|
||||
github.com/pion/srtp/v3 v3.0.9 h1:lRGF4G61xxj+m/YluB3ZnBpiALSri2lTzba0kGZMrQY=
|
||||
github.com/pion/srtp/v3 v3.0.9/go.mod h1:E+AuWd7Ug2Fp5u38MKnhduvpVkveXJX6J4Lq4rxUYt8=
|
||||
github.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM=
|
||||
github.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=
|
||||
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
|
||||
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/urfave/cli/v3 v3.6.1 h1:j8Qq8NyUawj/7rTYdBGrxcH7A/j7/G8Q5LhWEW4G3Mo=
|
||||
github.com/urfave/cli/v3 v3.6.1/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.16 h1:yufWSENyjnJ4LFQa9BerzUm4E4aLfTyzw5nmnCteO0c=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.16/go.mod h1:jDpP4O4skYi+7iVwt6Zyp18bd2M4hkjtMuw2cmgKgfw=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk=
|
||||
github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=
|
||||
github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM=
|
||||
github.com/urfave/cli/v3 v3.7.0 h1:AGSnbUyjtLiM+WJUb4dzXKldl/gL+F8OwmRDtVr6g2U=
|
||||
github.com/urfave/cli/v3 v3.7.0/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso=
|
||||
github.com/zaf/g711 v1.4.0 h1:XZYkjjiAg9QTBnHqEg37m2I9q3IIDv5JRYXs2N8ma7c=
|
||||
github.com/zaf/g711 v1.4.0/go.mod h1:eCDXt3dSp/kYYAoooba7ukD/Q75jvAaS4WOMr0l1Roo=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.23 h1:P8NxV4EzV9c+BjpwTeB+G/qa+Xdq/UTazS2fKxY0O0g=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.23/go.mod h1:jDpP4O4skYi+7iVwt6Zyp18bd2M4hkjtMuw2cmgKgfw=
|
||||
go.bug.st/serial v1.6.4 h1:7FmqNPgVp3pu2Jz5PoPtbZ9jJO5gnEnZIvnI1lzve8A=
|
||||
go.bug.st/serial v1.6.4/go.mod h1:nofMJxTeNVny/m6+KaafC6vJGj3miwQZ6vW4BZUGJPI=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.41.0 h1:YlEwVsGAlCvczDILpUXpIpPSL/VPugt7zHThEMLce1c=
|
||||
go.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 h1:ao6Oe+wSebTlQ1OEht7jlYTzQKE+pnx/iNywFvTbuuI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0/go.mod h1:u3T6vz0gh/NVzgDgiwkgLxpsSF6PaPmo2il0apGJbls=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 h1:inYW9ZhgqiDqh6BioM7DVHHzEGVq76Db5897WLGZ5Go=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0/go.mod h1:Izur+Wt8gClgMJqO/cZ8wdeeMryJ/xxiOVgFSSfpDTY=
|
||||
go.opentelemetry.io/otel/metric v1.41.0 h1:rFnDcs4gRzBcsO9tS8LCpgR0dxg4aaxWlJxCno7JlTQ=
|
||||
go.opentelemetry.io/otel/metric v1.41.0/go.mod h1:xPvCwd9pU0VN8tPZYzDZV/BMj9CM9vs00GuBjeKhJps=
|
||||
go.opentelemetry.io/otel/sdk v1.41.0 h1:YPIEXKmiAwkGl3Gu1huk1aYWwtpRLeskpV+wPisxBp8=
|
||||
go.opentelemetry.io/otel/sdk v1.41.0/go.mod h1:ahFdU0G5y8IxglBf0QBJXgSe7agzjE4GiTJ6HT9ud90=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.41.0 h1:siZQIYBAUd1rlIWQT2uCxWJxcCO7q3TriaMlf08rXw8=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.41.0/go.mod h1:HNBuSvT7ROaGtGI50ArdRLUnvRTRGniSUZbxiWxSO8Y=
|
||||
go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa9TIN0=
|
||||
go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||
go.yaml.in/yaml/v3 v3.0.3 h1:bXOww4E/J3f66rav3pX3m8w6jDE4knZjGOw8b5Y6iNE=
|
||||
go.yaml.in/yaml/v3 v3.0.3/go.mod h1:tBHosrYAkRZjRAOREWbDnBXUf08JOwYq++0QNwQiWzI=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
|
||||
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
|
||||
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
|
||||
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
|
||||
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
|
||||
golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c=
|
||||
golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU=
|
||||
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
||||
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
||||
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE=
|
||||
golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
|
||||
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 h1:JLQynH/LBHfCTSbDWl+py8C+Rg/k1OVH3xfcaiANuF0=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:kSJwQxqmFXeo79zOmbrALdflXQeAYcUbgS7PbpMknCY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 h1:mWPCjDEyshlQYzBpMNHaEof6UX1PmHcaUODUywQ0uac=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
|
||||
google.golang.org/grpc v1.79.1 h1:zGhSi45ODB9/p3VAawt9a+O/MULLl9dpizzNNpq7flY=
|
||||
google.golang.org/grpc v1.79.1/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/hraban/opus.v2 v2.0.0-20230925203106-0188a62cb302 h1:xeVptzkP8BuJhoIjNizd2bRHfq9KB9HfOLZu90T04XM=
|
||||
gopkg.in/hraban/opus.v2 v2.0.0-20230925203106-0188a62cb302/go.mod h1:/L5E7a21VWl8DeuCPKxQBdVG5cy+L0MRZ08B1wnqt7g=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
|
||||
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
|
||||
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
|
||||
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.30.1 h1:4r4U1J6Fhj98NKfSjnPUN7Ze2c6MnAdL0hWw6+LrJpc=
|
||||
@@ -67,18 +196,18 @@ modernc.org/gc/v3 v3.1.1 h1:k8T3gkXWY9sEiytKhcgyiZ2L0DTyCQ/nvX+LoCljoRE=
|
||||
modernc.org/gc/v3 v3.1.1/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A=
|
||||
modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I=
|
||||
modernc.org/libquickjs v0.12.2 h1:XtF6iD+aoN/pEz1MAQjg1wMZT412pzmOlO11UGLW/wQ=
|
||||
modernc.org/libquickjs v0.12.2/go.mod h1:n+vyuJ4mXh1pQYt1bJttvoCE+2t+MqCM8BFlcSDg/70=
|
||||
modernc.org/libc v1.67.1 h1:bFaqOaa5/zbWYJo8aW0tXPX21hXsngG2M7mckCnFSVk=
|
||||
modernc.org/libc v1.67.1/go.mod h1:QvvnnJ5P7aitu0ReNpVIEyesuhmDLQ8kaEoyMjIFZJA=
|
||||
modernc.org/libquickjs v0.12.3 h1:2IU9B6njBmce2PuYttJDkXeoLRV9WnvgP+eU5HAC8YI=
|
||||
modernc.org/libquickjs v0.12.3/go.mod h1:iCsgVxnHTX3i0YPxxHBmJk0GLA5sVUHXWI/090UXgeE=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/quickjs v0.17.0 h1:gYZRSCKVokyOiHhZEKwran/NoBaGjAaWk+xJq52SWfQ=
|
||||
modernc.org/quickjs v0.17.0/go.mod h1:TE+wpAYX4V7Nvi/sHRUrd9l5L176ZIiS0as3MMObvC0=
|
||||
modernc.org/quickjs v0.17.1 h1:CbYnbTf7ksZk9YZ1rRM2Ab1Zfi+X6s50kXiOhpd2NIg=
|
||||
modernc.org/quickjs v0.17.1/go.mod h1:hATT7DIJc33I5Q/Fjffhm0tpUHNSqdKHma/ossibTA0=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type HTTPClient struct {
|
||||
config ModuleConfig
|
||||
router *Router
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.http.client",
|
||||
New: func(config ModuleConfig) (Module, error) {
|
||||
|
||||
return &HTTPClient{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Id() string {
|
||||
return hc.config.Id
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Type() string {
|
||||
return hc.config.Type
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) RegisterRouter(router *Router) {
|
||||
hc.router = router
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Run() error {
|
||||
|
||||
hc.client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
<-hc.router.Context.Done()
|
||||
slog.Debug("router context done in module", "id", hc.config.Id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Output(payload any) error {
|
||||
|
||||
payloadRequest, ok := payload.(*http.Request)
|
||||
|
||||
if !ok {
|
||||
return fmt.Errorf("net.http.client is only able to output an http.Request")
|
||||
}
|
||||
|
||||
if hc.client == nil {
|
||||
return fmt.Errorf("net.http.client client is nil")
|
||||
}
|
||||
|
||||
response, err := hc.client.Do(payloadRequest)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if hc.router != nil {
|
||||
hc.router.HandleInput(hc.config.Id, response)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
107
http-server.go
107
http-server.go
@@ -1,107 +0,0 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type HTTPServer struct {
|
||||
config ModuleConfig
|
||||
Port uint16
|
||||
router *Router
|
||||
}
|
||||
|
||||
type ResponseData struct {
|
||||
Message string `json:"message"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.http.server",
|
||||
New: func(config ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
port, ok := params["port"]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("net.http.server requires a port parameter")
|
||||
}
|
||||
|
||||
portNum, ok := port.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("net.http.server port must be uint16")
|
||||
}
|
||||
|
||||
return &HTTPServer{Port: uint16(portNum), config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Id() string {
|
||||
return hs.config.Id
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Type() string {
|
||||
return hs.config.Type
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) RegisterRouter(router *Router) {
|
||||
hs.router = router
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) HandleDefault(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
response := ResponseData{
|
||||
Message: "routing successful",
|
||||
Status: "ok",
|
||||
}
|
||||
|
||||
if hs.router != nil {
|
||||
routingErrors := hs.router.HandleInput(hs.config.Id, r)
|
||||
if routingErrors != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
response.Status = "error"
|
||||
response.Message = "routing failed"
|
||||
} else {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
response.Message = "routing successful"
|
||||
}
|
||||
} else {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
response.Message = "no router registered"
|
||||
response.Status = "error"
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Run() error {
|
||||
http.HandleFunc("/", hs.HandleDefault)
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", hs.Port),
|
||||
Handler: http.DefaultServeMux,
|
||||
}
|
||||
|
||||
go func() {
|
||||
<-hs.router.Context.Done()
|
||||
slog.Debug("router context done in module", "id", hs.config.Id)
|
||||
httpServer.Close()
|
||||
}()
|
||||
|
||||
err := httpServer.ListenAndServe()
|
||||
slog.Debug("net.http.server closed", "id", hs.config.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
<-hs.router.Context.Done()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Output(payload any) error {
|
||||
return fmt.Errorf("net.http.server output is not implemented")
|
||||
}
|
||||
22
internal/common/common.go
Normal file
22
internal/common/common.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package common
|
||||
|
||||
import "context"
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RouterContextKey contextKey = contextKey("router")
|
||||
const SourceContextKey contextKey = contextKey("source")
|
||||
const ModulesContextKey contextKey = contextKey("modules")
|
||||
const SenderContextKey contextKey = contextKey("sender")
|
||||
|
||||
type RouteIO interface {
|
||||
HandleInput(ctx context.Context, sourceId string, payload any) (bool, []RouteIOError)
|
||||
HandleOutput(ctx context.Context, destinationId string, payload any) error
|
||||
}
|
||||
|
||||
type RouteIOError struct {
|
||||
Index int
|
||||
OutputError error
|
||||
ProcessError error
|
||||
InputError error
|
||||
}
|
||||
281
internal/config/config.go
Normal file
281
internal/config/config.go
Normal file
@@ -0,0 +1,281 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Modules []ModuleConfig `json:"modules"`
|
||||
Routes []RouteConfig `json:"routes"`
|
||||
}
|
||||
|
||||
type Params map[string]any
|
||||
|
||||
var (
|
||||
ErrParamNotFound = errors.New("not found")
|
||||
ErrParamNotString = errors.New("not a string")
|
||||
ErrParamNotNumber = errors.New("not a number")
|
||||
ErrParamNotInteger = errors.New("not an integer")
|
||||
ErrParamNotBool = errors.New("not a boolean")
|
||||
ErrParamNotSlice = errors.New("not a slice")
|
||||
)
|
||||
|
||||
func (p Params) GetString(key string) (string, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return "", ErrParamNotFound
|
||||
}
|
||||
|
||||
stringValue, ok := value.(string)
|
||||
if !ok {
|
||||
return "", ErrParamNotString
|
||||
}
|
||||
return stringValue, nil
|
||||
}
|
||||
|
||||
func (p Params) GetInt(key string) (int, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return intValue, nil
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return int(uintValue), nil
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return int(byteValue), nil
|
||||
}
|
||||
|
||||
floatValue, ok := value.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return 0, ErrParamNotInteger
|
||||
}
|
||||
return int(floatValue), nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetFloat32(key string) (float32, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
float32Value, ok := value.(float32)
|
||||
if ok {
|
||||
return float32Value, nil
|
||||
}
|
||||
|
||||
float64Value, ok := value.(float64)
|
||||
if ok {
|
||||
return float32(float64Value), nil
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return float32(intValue), nil
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return float32(uintValue), nil
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return float32(byteValue), nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetFloat64(key string) (float64, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
float64Value, ok := value.(float64)
|
||||
if ok {
|
||||
return float64Value, nil
|
||||
}
|
||||
|
||||
float32Value, ok := value.(float32)
|
||||
if ok {
|
||||
return float64(float32Value), nil
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return float64(intValue), nil
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return float64(uintValue), nil
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return float64(byteValue), nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetBool(key string) (bool, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return false, ErrParamNotFound
|
||||
}
|
||||
|
||||
boolValue, ok := value.(bool)
|
||||
if !ok {
|
||||
return false, ErrParamNotBool
|
||||
}
|
||||
return boolValue, nil
|
||||
}
|
||||
|
||||
func (p Params) GetStringSlice(key string) ([]string, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
interfaceSlice, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil, ErrParamNotSlice
|
||||
}
|
||||
|
||||
stringSlice := make([]string, len(interfaceSlice))
|
||||
for i, v := range interfaceSlice {
|
||||
str, ok := v.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("element at index %d is not a string", i)
|
||||
}
|
||||
stringSlice[i] = str
|
||||
}
|
||||
return stringSlice, nil
|
||||
}
|
||||
|
||||
func (p Params) GetIntSlice(key string) ([]int, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, ErrParamNotSlice
|
||||
}
|
||||
|
||||
result := make([]int, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
byteValue, ok := elem.(byte)
|
||||
if ok {
|
||||
result[i] = int(byteValue)
|
||||
continue
|
||||
}
|
||||
uintValue, ok := elem.(uint)
|
||||
if ok {
|
||||
result[i] = int(uintValue)
|
||||
continue
|
||||
}
|
||||
intValue, ok := elem.(int)
|
||||
if ok {
|
||||
result[i] = int(intValue)
|
||||
continue
|
||||
}
|
||||
floatValue, ok := elem.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return nil, fmt.Errorf("element at index %d is not an integer", i)
|
||||
}
|
||||
result[i] = int(floatValue)
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("element at index %d is not a number", i)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (p Params) GetByteSlice(key string) ([]byte, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, ErrParamNotSlice
|
||||
}
|
||||
|
||||
result := make([]byte, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
byteValue, ok := elem.(byte)
|
||||
if ok {
|
||||
result[i] = byteValue
|
||||
continue
|
||||
}
|
||||
uintValue, ok := elem.(uint)
|
||||
if ok {
|
||||
if uintValue > 255 {
|
||||
return nil, fmt.Errorf("element at index %d is out of byte range", i)
|
||||
}
|
||||
result[i] = byte(uintValue)
|
||||
continue
|
||||
}
|
||||
intValue, ok := elem.(int)
|
||||
if ok {
|
||||
if intValue < 0 || intValue > 255 {
|
||||
return nil, fmt.Errorf("element at index %d is out of byte range", i)
|
||||
}
|
||||
result[i] = byte(intValue)
|
||||
continue
|
||||
}
|
||||
floatValue, ok := elem.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return nil, fmt.Errorf("element at index %d is not an integer", i)
|
||||
}
|
||||
if floatValue < 0 || floatValue > 255 {
|
||||
return nil, fmt.Errorf("element at index %d is out of byte range", i)
|
||||
}
|
||||
result[i] = byte(floatValue)
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("element at index %d is not a number", i)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type ModuleConfig struct {
|
||||
Id string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params"`
|
||||
}
|
||||
|
||||
type RouteConfig struct {
|
||||
Input string `json:"input"`
|
||||
Processors []ProcessorConfig `json:"processors"`
|
||||
}
|
||||
|
||||
type ProcessorConfig struct {
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params"`
|
||||
}
|
||||
297
internal/config/config_test.go
Normal file
297
internal/config/config_test.go
Normal file
@@ -0,0 +1,297 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func TestGoodStringParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "string param",
|
||||
paramsJSON: `{"key": "value"}`,
|
||||
key: "key",
|
||||
expected: "value",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetString(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetString returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetString got %s, expected %s", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodIntParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected int
|
||||
}{
|
||||
{
|
||||
name: "int param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetInt(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetInt returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetInt got %d, expected %d", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodFloat32ParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected float32
|
||||
}{
|
||||
{
|
||||
name: "no decimal param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "float param",
|
||||
paramsJSON: `{"key": 1.23}`,
|
||||
key: "key",
|
||||
expected: 1.23,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetFloat32(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFloat32 returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetFloat32 got %f, expected %f", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodFloat64ParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected float64
|
||||
}{
|
||||
{
|
||||
name: "no decimal param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "float param",
|
||||
paramsJSON: `{"key": 1.23}`,
|
||||
key: "key",
|
||||
expected: 1.23,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetFloat64(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFloat64 returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetFloat64 got %f, expected %f", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodBoolParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "bool param",
|
||||
paramsJSON: `{"key": true}`,
|
||||
key: "key",
|
||||
expected: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetBool(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBool returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetBool got %t, expected %t", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodStringSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "string array",
|
||||
paramsJSON: `{"key": ["value1", "value2"]}`,
|
||||
key: "key",
|
||||
expected: []string{"value1", "value2"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetStringSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetStringSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetStringSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodIntSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []int
|
||||
}{
|
||||
{
|
||||
name: "int array",
|
||||
paramsJSON: `{"key": [1, 2, 3]}`,
|
||||
key: "key",
|
||||
expected: []int{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "int array with floats",
|
||||
paramsJSON: `{"key": [1.0, 2.0, 3.0]}`,
|
||||
key: "key",
|
||||
expected: []int{1, 2, 3},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetIntSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIntSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetIntSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodByteSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []byte
|
||||
}{
|
||||
{
|
||||
name: "byte array",
|
||||
paramsJSON: `{"key": [1,2,3,4]}`,
|
||||
key: "key",
|
||||
expected: []byte{1, 2, 3, 4},
|
||||
},
|
||||
{
|
||||
name: "byte array with floats",
|
||||
paramsJSON: `{"key": [1.0,2.0,3.0,4.0]}`,
|
||||
key: "key",
|
||||
expected: []byte{1, 2, 3, 4},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetByteSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByteSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetByteSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
25
internal/framer/framer.go
Normal file
25
internal/framer/framer.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package framer
|
||||
|
||||
type Framer interface {
|
||||
Decode([]byte) [][]byte
|
||||
Encode([]byte) []byte
|
||||
Clear()
|
||||
Buffer() []byte
|
||||
}
|
||||
|
||||
func GetFramer(framingType string) Framer {
|
||||
switch framingType {
|
||||
case "CR":
|
||||
return NewByteSeparatorFramer([]byte{'\r'})
|
||||
case "LF":
|
||||
return NewByteSeparatorFramer([]byte{'\n'})
|
||||
case "CRLF":
|
||||
return NewByteSeparatorFramer([]byte{'\r', '\n'})
|
||||
case "SLIP":
|
||||
return NewSlipFramer()
|
||||
case "RAW":
|
||||
return NewRawFramer()
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
23
internal/framer/raw.go
Normal file
23
internal/framer/raw.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package framer
|
||||
|
||||
type RawFramer struct{}
|
||||
|
||||
func NewRawFramer() *RawFramer {
|
||||
return &RawFramer{}
|
||||
}
|
||||
|
||||
func (rf *RawFramer) Decode(data []byte) [][]byte {
|
||||
return [][]byte{data}
|
||||
}
|
||||
|
||||
func (rf *RawFramer) Encode(data []byte) []byte {
|
||||
return data
|
||||
}
|
||||
|
||||
func (rf *RawFramer) Clear() {
|
||||
// NOTE(jwetzell): no internal state to clear
|
||||
}
|
||||
|
||||
func (rf *RawFramer) Buffer() []byte {
|
||||
return []byte{}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package framing
|
||||
package framer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -35,3 +35,7 @@ func (bsf *ByteSeparatorFramer) Encode(data []byte) []byte {
|
||||
func (bsf *ByteSeparatorFramer) Clear() {
|
||||
bsf.buffer = []byte{}
|
||||
}
|
||||
|
||||
func (bsf *ByteSeparatorFramer) Buffer() []byte {
|
||||
return bsf.buffer
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package framing
|
||||
package framer
|
||||
|
||||
type SlipFramer struct {
|
||||
buffer []byte
|
||||
@@ -59,9 +59,9 @@ func (sf *SlipFramer) Encode(data []byte) []byte {
|
||||
for _, byteToEncode := range data {
|
||||
switch byteToEncode {
|
||||
case END:
|
||||
encodedBytes = append(encodedBytes, ESC_END)
|
||||
encodedBytes = append(encodedBytes, ESC, ESC_END)
|
||||
case ESC:
|
||||
encodedBytes = append(encodedBytes, ESC_ESC)
|
||||
encodedBytes = append(encodedBytes, ESC, ESC_ESC)
|
||||
default:
|
||||
encodedBytes = append(encodedBytes, byteToEncode)
|
||||
}
|
||||
@@ -74,3 +74,7 @@ func (sf *SlipFramer) Encode(data []byte) []byte {
|
||||
func (sf *SlipFramer) Clear() {
|
||||
sf.buffer = []byte{}
|
||||
}
|
||||
|
||||
func (sf *SlipFramer) Buffer() []byte {
|
||||
return sf.buffer
|
||||
}
|
||||
15
internal/framer/test/framer_test.go
Normal file
15
internal/framer/test/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/test/raw_test.go
Normal file
78
internal/framer/test/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())
|
||||
}
|
||||
}
|
||||
130
internal/framer/test/separator_test.go
Normal file
130
internal/framer/test/separator_test.go
Normal file
@@ -0,0 +1,130 @@
|
||||
package framer_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
)
|
||||
|
||||
func TestGoodSeparatorFramerDecode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
framer framer.Framer
|
||||
input []byte
|
||||
expected [][]byte
|
||||
buffer []byte
|
||||
}{
|
||||
{
|
||||
name: "new line separator",
|
||||
framer: framer.GetFramer("LF"),
|
||||
input: []byte("Hello\nWorld\nThis is a test\n"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello"),
|
||||
[]byte("World"),
|
||||
[]byte("This is a test"),
|
||||
},
|
||||
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",
|
||||
framer: framer.GetFramer("CRLF"),
|
||||
input: []byte("Hello\r\nWorld\r\nThis is a test\r\n"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello"),
|
||||
[]byte("World"),
|
||||
[]byte("This is a test"),
|
||||
},
|
||||
buffer: []byte{},
|
||||
},
|
||||
{
|
||||
name: "extra data after separator",
|
||||
framer: framer.GetFramer("CRLF"),
|
||||
input: []byte("Hello\r\nWorld\r\nThis is a test\r\nextra"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello"),
|
||||
[]byte("World"),
|
||||
[]byte("This is a test"),
|
||||
},
|
||||
buffer: []byte("extra"),
|
||||
},
|
||||
}
|
||||
|
||||
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("separator 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("separator framer frame %d got %s, expected %s", i, frame, test.expected[i])
|
||||
}
|
||||
}
|
||||
if !slices.Equal(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())
|
||||
}
|
||||
}
|
||||
110
internal/framer/test/slip_test.go
Normal file
110
internal/framer/test/slip_test.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package framer_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
)
|
||||
|
||||
func TestGoodSLIPFramerDecode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
framer framer.Framer
|
||||
input []byte
|
||||
expected [][]byte
|
||||
buffer []byte
|
||||
}{
|
||||
{
|
||||
name: "OSC SLIP messages",
|
||||
framer: framer.GetFramer("SLIP"),
|
||||
input: []byte{0xc0, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0xc0},
|
||||
expected: [][]byte{
|
||||
{0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00},
|
||||
},
|
||||
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 {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
frames := test.framer.Decode(test.input)
|
||||
if len(frames) != len(test.expected) {
|
||||
t.Fatalf("SLIP 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("SLIP framer frame %d got %s, expected %s", i, frame, test.expected[i])
|
||||
}
|
||||
}
|
||||
if !slices.Equal(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())
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package framing
|
||||
|
||||
type Framer interface {
|
||||
Decode([]byte) [][]byte
|
||||
Encode([]byte) []byte
|
||||
Clear()
|
||||
}
|
||||
211
internal/module/http-server.go
Normal file
211
internal/module/http-server.go
Normal file
@@ -0,0 +1,211 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type HTTPServer struct {
|
||||
config config.ModuleConfig
|
||||
Port uint16
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type ResponseIOError struct {
|
||||
Index int `json:"index"`
|
||||
OutputError *string `json:"outputError"`
|
||||
ProcessError *string `json:"processError"`
|
||||
InputError *string `json:"inputError"`
|
||||
}
|
||||
|
||||
type IOResponseData struct {
|
||||
IOErrors []ResponseIOError `json:"ioErrors"`
|
||||
Message string `json:"message"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type httpServerContextKey string
|
||||
|
||||
type HTTPServerResponseWriter struct {
|
||||
http.ResponseWriter
|
||||
done bool
|
||||
}
|
||||
|
||||
func (hsrw *HTTPServerResponseWriter) WriteHeader(status int) {
|
||||
hsrw.done = true
|
||||
hsrw.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (hsrw *HTTPServerResponseWriter) Write(data []byte) (int, error) {
|
||||
hsrw.done = true
|
||||
return hsrw.ResponseWriter.Write(data)
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "http.server",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.server port error: %w", err)
|
||||
}
|
||||
return &HTTPServer{Port: uint16(portNum), config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Id() string {
|
||||
return hs.config.Id
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Type() string {
|
||||
return hs.config.Type
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
responseWriter := HTTPServerResponseWriter{ResponseWriter: w}
|
||||
|
||||
response := IOResponseData{
|
||||
Message: "routing successful",
|
||||
Status: "ok",
|
||||
}
|
||||
if hs.router != nil {
|
||||
inputContext := context.WithValue(hs.ctx, httpServerContextKey("responseWriter"), &responseWriter)
|
||||
senderAddr, err := net.ResolveTCPAddr("tcp", r.RemoteAddr)
|
||||
if err == nil {
|
||||
inputContext = context.WithValue(inputContext, common.SenderContextKey, senderAddr)
|
||||
}
|
||||
aRouteFound, routingErrors := hs.router.HandleInput(inputContext, hs.Id(), r)
|
||||
if !responseWriter.done {
|
||||
if aRouteFound {
|
||||
if routingErrors != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
response.Status = "error"
|
||||
response.Message = "routing failed"
|
||||
|
||||
response.IOErrors = []ResponseIOError{}
|
||||
for _, responseIOError := range routingErrors {
|
||||
errorToAdd := ResponseIOError{
|
||||
Index: responseIOError.Index,
|
||||
}
|
||||
|
||||
if responseIOError.InputError != nil {
|
||||
errorMsg := responseIOError.InputError.Error()
|
||||
errorToAdd.InputError = &errorMsg
|
||||
}
|
||||
|
||||
if responseIOError.ProcessError != nil {
|
||||
errorMsg := responseIOError.ProcessError.Error()
|
||||
errorToAdd.ProcessError = &errorMsg
|
||||
}
|
||||
|
||||
if responseIOError.OutputError != nil {
|
||||
errorMsg := responseIOError.OutputError.Error()
|
||||
errorToAdd.OutputError = &errorMsg
|
||||
}
|
||||
|
||||
response.IOErrors = append(response.IOErrors, errorToAdd)
|
||||
|
||||
}
|
||||
json.NewEncoder(w).Encode(response)
|
||||
return
|
||||
} else {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
response.Message = "routing successful"
|
||||
json.NewEncoder(w).Encode(response)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
response.Status = "error"
|
||||
response.Message = "no matching routes found"
|
||||
json.NewEncoder(w).Encode(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
response.Message = "no router registered"
|
||||
response.Status = "error"
|
||||
json.NewEncoder(w).Encode(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Start(ctx context.Context) error {
|
||||
hs.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.server unable to get router from context")
|
||||
}
|
||||
hs.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
hs.ctx = moduleContext
|
||||
hs.cancel = cancel
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", hs.Port),
|
||||
Handler: hs,
|
||||
}
|
||||
|
||||
go func() {
|
||||
<-hs.ctx.Done()
|
||||
httpServer.Close()
|
||||
}()
|
||||
|
||||
err := httpServer.ListenAndServe()
|
||||
// TODO(jwetzell): handle server closed error differently
|
||||
if err != nil {
|
||||
if err.Error() != "http: Server closed" {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
<-hs.ctx.Done()
|
||||
hs.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Output(ctx context.Context, payload any) error {
|
||||
responseWriter, ok := ctx.Value(httpServerContextKey("responseWriter")).(*HTTPServerResponseWriter)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.server output must originate from an http.server input")
|
||||
}
|
||||
|
||||
payloadResponse, ok := processor.GetAnyAs[processor.HTTPResponse](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.server is only able to output HTTPResponse")
|
||||
}
|
||||
|
||||
if responseWriter.done {
|
||||
return errors.New("http.server response writer has already been written to")
|
||||
}
|
||||
|
||||
responseWriter.WriteHeader(payloadResponse.Status)
|
||||
responseWriter.Write(payloadResponse.Body)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Stop() {
|
||||
hs.cancel()
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("http.server does not support Get")
|
||||
}
|
||||
100
internal/module/midi-input.go
Normal file
100
internal/module/midi-input.go
Normal file
@@ -0,0 +1,100 @@
|
||||
//go:build cgo
|
||||
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
_ "gitlab.com/gomidi/midi/v2/drivers/rtmididrv"
|
||||
)
|
||||
|
||||
type MIDIInput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
Port string
|
||||
SendFunc func(midi.Message) error
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "midi.input",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
portString, err := params.GetString("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.input port error: %w", err)
|
||||
}
|
||||
|
||||
return &MIDIInput{config: config, Port: portString, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Id() string {
|
||||
return mi.config.Id
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Type() string {
|
||||
return mi.config.Type
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Start(ctx context.Context) error {
|
||||
mi.logger.Debug("running")
|
||||
defer midi.CloseDriver()
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.input unable to get router from context")
|
||||
}
|
||||
mi.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
mi.ctx = moduleContext
|
||||
mi.cancel = cancel
|
||||
|
||||
in, err := midi.FindInPort(mi.Port)
|
||||
if err != nil {
|
||||
return fmt.Errorf("midi.input can't find input port: %s", mi.Port)
|
||||
}
|
||||
|
||||
stop, err := midi.ListenTo(in, func(msg midi.Message, timestampms int32) {
|
||||
if mi.router != nil {
|
||||
mi.router.HandleInput(mi.ctx, mi.Id(), msg)
|
||||
}
|
||||
}, midi.UseSysEx())
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer stop()
|
||||
|
||||
<-mi.ctx.Done()
|
||||
mi.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("midi.input output is not implemented")
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Stop() {
|
||||
mi.cancel()
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "port":
|
||||
return mi.Port, nil
|
||||
default:
|
||||
return nil, errors.New("midi.input key not found")
|
||||
}
|
||||
}
|
||||
108
internal/module/midi-output.go
Normal file
108
internal/module/midi-output.go
Normal file
@@ -0,0 +1,108 @@
|
||||
//go:build cgo
|
||||
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
_ "gitlab.com/gomidi/midi/v2/drivers/rtmididrv"
|
||||
)
|
||||
|
||||
type MIDIOutput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
Port string
|
||||
SendFunc func(midi.Message) error
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "midi.output",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
|
||||
portString, err := params.GetString("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.output port error: %w", err)
|
||||
}
|
||||
|
||||
return &MIDIOutput{config: config, Port: portString, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Id() string {
|
||||
return mo.config.Id
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Type() string {
|
||||
return mo.config.Type
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Start(ctx context.Context) error {
|
||||
mo.logger.Debug("running")
|
||||
defer midi.CloseDriver()
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.output unable to get router from context")
|
||||
}
|
||||
mo.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
mo.ctx = moduleContext
|
||||
mo.cancel = cancel
|
||||
|
||||
out, err := midi.FindOutPort(mo.Port)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("midi.output can't find output port: %s", mo.Port)
|
||||
}
|
||||
|
||||
send, err := midi.SendTo(out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mo.SendFunc = send
|
||||
|
||||
<-mo.ctx.Done()
|
||||
mo.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Output(ctx context.Context, payload any) error {
|
||||
if mo.SendFunc == nil {
|
||||
return errors.New("midi.output output is not setup")
|
||||
}
|
||||
|
||||
payloadMessage, ok := processor.GetAnyAs[midi.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.output can only ouptut midi.Message")
|
||||
}
|
||||
|
||||
return mo.SendFunc(payloadMessage)
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Stop() {
|
||||
mo.cancel()
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "port":
|
||||
return mo.Port, nil
|
||||
default:
|
||||
return nil, errors.New("midi.output key not found")
|
||||
}
|
||||
}
|
||||
57
internal/module/module.go
Normal file
57
internal/module/module.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type ModuleError struct {
|
||||
Index int
|
||||
Config config.ModuleConfig
|
||||
Error error
|
||||
}
|
||||
|
||||
type Module interface {
|
||||
Id() string
|
||||
Type() string
|
||||
Start(context.Context) error
|
||||
Stop()
|
||||
Output(context.Context, any) error
|
||||
Get(key string) (any, error)
|
||||
}
|
||||
|
||||
type ModuleRegistration struct {
|
||||
Type string `json:"type"`
|
||||
New func(config.ModuleConfig) (Module, error)
|
||||
}
|
||||
|
||||
func RegisterModule(mod ModuleRegistration) {
|
||||
|
||||
if mod.Type == "" {
|
||||
panic("module type is missing")
|
||||
}
|
||||
if mod.New == nil {
|
||||
panic("missing ModuleInfo.New")
|
||||
}
|
||||
|
||||
moduleRegistryMu.Lock()
|
||||
defer moduleRegistryMu.Unlock()
|
||||
|
||||
if _, ok := ModuleRegistry[string(mod.Type)]; ok {
|
||||
panic(fmt.Sprintf("module already registered: %s", mod.Type))
|
||||
}
|
||||
ModuleRegistry[string(mod.Type)] = mod
|
||||
}
|
||||
|
||||
var (
|
||||
moduleRegistryMu sync.RWMutex
|
||||
ModuleRegistry = make(map[string]ModuleRegistration)
|
||||
)
|
||||
|
||||
func CreateLogger(config config.ModuleConfig) *slog.Logger {
|
||||
return slog.Default().With("component", "module", "id", config.Id, "type", config.Type)
|
||||
}
|
||||
132
internal/module/mqtt-client.go
Normal file
132
internal/module/mqtt-client.go
Normal file
@@ -0,0 +1,132 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type MQTTClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
Broker string
|
||||
ClientID string
|
||||
Topic string
|
||||
client mqtt.Client
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "mqtt.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
brokerString, err := params.GetString("broker")
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mqtt.client broker error: %w", err)
|
||||
}
|
||||
|
||||
topicString, err := params.GetString("topic")
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mqtt.client topic error: %w", err)
|
||||
}
|
||||
|
||||
clientIdString, err := params.GetString("clientId")
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mqtt.client clientId error: %w", err)
|
||||
}
|
||||
|
||||
return &MQTTClient{config: config, Broker: brokerString, Topic: topicString, ClientID: clientIdString, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Id() string {
|
||||
return mc.config.Id
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Type() string {
|
||||
return mc.config.Type
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Start(ctx context.Context) error {
|
||||
mc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("mqtt.client unable to get router from context")
|
||||
}
|
||||
mc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
mc.ctx = moduleContext
|
||||
mc.cancel = cancel
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
opts.AddBroker(mc.Broker)
|
||||
opts.SetClientID(mc.ClientID)
|
||||
opts.SetAutoReconnect(true)
|
||||
opts.SetCleanSession(false)
|
||||
|
||||
opts.OnConnect = func(c mqtt.Client) {
|
||||
token := mc.client.Subscribe(mc.Topic, 1, func(c mqtt.Client, m mqtt.Message) {
|
||||
mc.router.HandleInput(mc.ctx, mc.Id(), m)
|
||||
})
|
||||
token.Wait()
|
||||
}
|
||||
|
||||
mc.client = mqtt.NewClient(opts)
|
||||
defer mc.client.Disconnect(250)
|
||||
|
||||
token := mc.client.Connect()
|
||||
|
||||
token.Wait()
|
||||
err := token.Error()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
<-mc.ctx.Done()
|
||||
mc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Output(ctx context.Context, payload any) error {
|
||||
payloadMessage, ok := processor.GetAnyAs[mqtt.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("mqtt.client is only able to output a MQTTMessage")
|
||||
}
|
||||
|
||||
if mc.client == nil {
|
||||
return errors.New("mqtt.client client is not setup")
|
||||
}
|
||||
|
||||
if !mc.client.IsConnected() {
|
||||
return errors.New("mqtt.client is not connected")
|
||||
}
|
||||
|
||||
token := mc.client.Publish(payloadMessage.Topic(), payloadMessage.Qos(), payloadMessage.Retained(), payloadMessage.Payload())
|
||||
|
||||
token.Wait()
|
||||
|
||||
return token.Error()
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Stop() {
|
||||
mc.cancel()
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Get(key string) (any, error) {
|
||||
return nil, errors.New("mqtt.client does not support Get")
|
||||
}
|
||||
122
internal/module/nats-client.go
Normal file
122
internal/module/nats-client.go
Normal file
@@ -0,0 +1,122 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
type NATSClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
URL string
|
||||
Subject string
|
||||
client *nats.Conn
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "nats.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
urlString, err := params.GetString("url")
|
||||
if err != nil {
|
||||
return nil, errors.New("nats.client url error: " + err.Error())
|
||||
}
|
||||
|
||||
subjectString, err := params.GetString("subject")
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.New("nats.client subject error: " + err.Error())
|
||||
}
|
||||
|
||||
return &NATSClient{config: config, URL: urlString, Subject: subjectString, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Id() string {
|
||||
return nc.config.Id
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Type() string {
|
||||
return nc.config.Type
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Start(ctx context.Context) error {
|
||||
nc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("nats.client unable to get router from context")
|
||||
}
|
||||
|
||||
nc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
nc.ctx = moduleContext
|
||||
nc.cancel = cancel
|
||||
|
||||
client, err := nats.Connect(nc.URL, nats.RetryOnFailedConnect(true))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
nc.client = client
|
||||
|
||||
defer client.Drain()
|
||||
defer client.Close()
|
||||
|
||||
sub, err := nc.client.Subscribe(nc.Subject, func(msg *nats.Msg) {
|
||||
if nc.router != nil {
|
||||
nc.router.HandleInput(nc.ctx, nc.Id(), msg)
|
||||
}
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer sub.Unsubscribe()
|
||||
|
||||
<-nc.ctx.Done()
|
||||
nc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadMessage, ok := processor.GetAnyAs[processor.NATSMessage](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("nats.client is only able to output NATSMessage")
|
||||
}
|
||||
|
||||
if nc.client == nil {
|
||||
return errors.New("nats.client client is not setup")
|
||||
}
|
||||
|
||||
if !nc.client.IsConnected() {
|
||||
return errors.New("nats.client is not connected")
|
||||
}
|
||||
|
||||
err := nc.client.Publish(payloadMessage.Subject, payloadMessage.Payload)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Stop() {
|
||||
nc.cancel()
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Get(key string) (any, error) {
|
||||
return nil, errors.New("nats.client does not support Get")
|
||||
}
|
||||
118
internal/module/nats-server.go
Normal file
118
internal/module/nats-server.go
Normal file
@@ -0,0 +1,118 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
)
|
||||
|
||||
type NATSServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
Ip string
|
||||
Port int
|
||||
router common.RouteIO
|
||||
server *server.Server
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "nats.server",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
portNum = 4222
|
||||
} else {
|
||||
return nil, fmt.Errorf("nats.server port error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
ipString = "0.0.0.0"
|
||||
} else {
|
||||
return nil, fmt.Errorf("nats.server ip error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
_, err = net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", ipString, uint16(portNum)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &NATSServer{config: moduleConfig, logger: CreateLogger(moduleConfig), Ip: ipString, Port: portNum}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Id() string {
|
||||
return ns.config.Id
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Type() string {
|
||||
return ns.config.Type
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Start(ctx context.Context) error {
|
||||
ns.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("nats.server unable to get router from context")
|
||||
}
|
||||
|
||||
ns.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
ns.ctx = moduleContext
|
||||
ns.cancel = cancel
|
||||
|
||||
natsServer, err := server.NewServer(&server.Options{
|
||||
Host: ns.Ip,
|
||||
Port: ns.Port,
|
||||
NoLog: true,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ns.server = natsServer
|
||||
natsServer.Start()
|
||||
defer natsServer.Shutdown()
|
||||
|
||||
if !natsServer.ReadyForConnections(5 * time.Second) {
|
||||
return errors.New("nats.server failed to start")
|
||||
}
|
||||
ns.logger.Info("NATS server started", "client_url", natsServer.ClientURL())
|
||||
|
||||
<-ns.ctx.Done()
|
||||
|
||||
ns.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("nats.server does not support output")
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Stop() {
|
||||
ns.cancel()
|
||||
if ns.server != nil {
|
||||
ns.server.Shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("nats.server does not support Get")
|
||||
}
|
||||
125
internal/module/psn-client.go
Normal file
125
internal/module/psn-client.go
Normal file
@@ -0,0 +1,125 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/psn-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type PSNClient struct {
|
||||
config config.ModuleConfig
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
decoder *psn.Decoder
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "psn.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
|
||||
return &PSNClient{config: config, decoder: psn.NewDecoder(), logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Id() string {
|
||||
return pc.config.Id
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Type() string {
|
||||
return pc.config.Type
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Start(ctx context.Context) error {
|
||||
pc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("psn.client unable to get router from context")
|
||||
}
|
||||
pc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
pc.ctx = moduleContext
|
||||
pc.cancel = cancel
|
||||
|
||||
addr, err := net.ResolveUDPAddr("udp", "236.10.10.10:56565")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
client, err := net.ListenMulticastUDP("udp", nil, addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
pc.conn = client
|
||||
|
||||
buffer := make([]byte, 2048)
|
||||
for {
|
||||
select {
|
||||
case <-pc.ctx.Done():
|
||||
// TODO(jwetzell): cleanup?
|
||||
pc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
pc.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
|
||||
numBytes, _, err := pc.conn.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if numBytes > 0 {
|
||||
message := buffer[:numBytes]
|
||||
err := pc.decoder.Decode(message)
|
||||
if err != nil {
|
||||
pc.logger.Error("problem decoding psn traffic", "error", err)
|
||||
}
|
||||
|
||||
if pc.router != nil {
|
||||
// TODO(jwetzell): better input handling
|
||||
for _, tracker := range pc.decoder.Trackers {
|
||||
pc.router.HandleInput(pc.ctx, pc.Id(), tracker)
|
||||
}
|
||||
} else {
|
||||
pc.logger.Error("has no router")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Output(ctx context.Context, payload any) error {
|
||||
return fmt.Errorf("psn.client output is not implemented")
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Stop() {
|
||||
pc.cancel()
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "trackers":
|
||||
return pc.decoder.Trackers, nil
|
||||
case "name":
|
||||
return pc.decoder.SystemName, nil
|
||||
default:
|
||||
return nil, errors.New("psn.client key not found")
|
||||
}
|
||||
}
|
||||
181
internal/module/serial-client.go
Normal file
181
internal/module/serial-client.go
Normal file
@@ -0,0 +1,181 @@
|
||||
//go:build cgo
|
||||
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
"go.bug.st/serial"
|
||||
)
|
||||
|
||||
type SerialClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
Port string
|
||||
Framer framer.Framer
|
||||
Mode *serial.Mode
|
||||
port serial.Port
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "serial.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
portString, err := params.GetString("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serial.client port error: %w", err)
|
||||
}
|
||||
|
||||
framingMethodString, err := params.GetString("framing")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serial.client framing error: %w", err)
|
||||
}
|
||||
|
||||
framer := framer.GetFramer(framingMethodString)
|
||||
|
||||
if framer == nil {
|
||||
return nil, fmt.Errorf("serial.client unknown framing method: %s", framingMethodString)
|
||||
}
|
||||
|
||||
baudRateInt, err := params.GetInt("baudRate")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serial.client baudRate error: %w", err)
|
||||
}
|
||||
|
||||
mode := serial.Mode{
|
||||
BaudRate: baudRateInt,
|
||||
}
|
||||
|
||||
return &SerialClient{config: config, Port: portString, Framer: framer, Mode: &mode, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Id() string {
|
||||
return sc.config.Id
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Type() string {
|
||||
return sc.config.Type
|
||||
}
|
||||
|
||||
func (sc *SerialClient) SetupPort() error {
|
||||
|
||||
port, err := serial.Open(sc.Port, sc.Mode)
|
||||
if err != nil {
|
||||
return fmt.Errorf("serial.client can't open input port: %s", sc.Port)
|
||||
}
|
||||
|
||||
sc.port = port
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Start(ctx context.Context) error {
|
||||
sc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("serial.client unable to get router from context")
|
||||
}
|
||||
|
||||
sc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
sc.ctx = moduleContext
|
||||
sc.cancel = cancel
|
||||
|
||||
// TODO(jwetzell): shutdown with router.Context properly
|
||||
go func() {
|
||||
<-sc.ctx.Done()
|
||||
sc.logger.Debug("done")
|
||||
if sc.port != nil {
|
||||
sc.port.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
err := sc.SetupPort()
|
||||
if err != nil {
|
||||
if sc.ctx.Err() != nil {
|
||||
sc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
sc.logger.Error("port setup error", "error", err.Error())
|
||||
time.Sleep(time.Second * 2)
|
||||
continue
|
||||
}
|
||||
|
||||
buffer := make([]byte, 1024)
|
||||
select {
|
||||
case <-sc.ctx.Done():
|
||||
sc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
READ:
|
||||
for {
|
||||
select {
|
||||
case <-sc.ctx.Done():
|
||||
sc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
byteCount, err := sc.port.Read(buffer)
|
||||
|
||||
if err != nil {
|
||||
sc.Framer.Clear()
|
||||
break READ
|
||||
}
|
||||
|
||||
if sc.Framer != nil {
|
||||
if byteCount > 0 {
|
||||
messages := sc.Framer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if sc.router != nil {
|
||||
sc.router.HandleInput(sc.ctx, sc.Id(), message)
|
||||
} else {
|
||||
sc.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("serial.client can only ouptut bytes")
|
||||
}
|
||||
|
||||
_, err := sc.port.Write(sc.Framer.Encode(payloadBytes))
|
||||
return err
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Stop() {
|
||||
sc.cancel()
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "port":
|
||||
return sc.Port, nil
|
||||
default:
|
||||
return nil, errors.New("serial.client key not found")
|
||||
}
|
||||
}
|
||||
227
internal/module/sip-call-server.go
Normal file
227
internal/module/sip-call-server.go
Normal file
@@ -0,0 +1,227 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/emiago/diago"
|
||||
"github.com/emiago/diago/media"
|
||||
"github.com/emiago/sipgo"
|
||||
"github.com/emiago/sipgo/sip"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type SIPCallServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
IP string
|
||||
Port int
|
||||
Transport string
|
||||
UserAgent string
|
||||
dg *diago.Diago
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type SIPCallMessage struct {
|
||||
To string
|
||||
}
|
||||
|
||||
type SIPCall struct {
|
||||
inDialog *diago.DialogServerSession
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
type sipCallContextKey string
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "sip.call.server",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
portNum = 5060
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.call.server port error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
ipString = "0.0.0.0"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.call.server ip error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
transportString, err := params.GetString("transport")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
transportString = "udp"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.call.server transport error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
userAgentString, err := params.GetString("userAgent")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
userAgentString = "showbridge"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.call.server userAgent error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &SIPCallServer{config: moduleConfig, IP: ipString, Port: int(portNum), Transport: transportString, UserAgent: userAgentString, logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Id() string {
|
||||
return scs.config.Id
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Type() string {
|
||||
return scs.config.Type
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Start(ctx context.Context) error {
|
||||
scs.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("sip.call.server unable to get router from context")
|
||||
}
|
||||
scs.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
scs.ctx = moduleContext
|
||||
scs.cancel = cancel
|
||||
|
||||
diagoLogger := slog.New(slog.NewJSONHandler(io.Discard, nil))
|
||||
|
||||
ua, _ := sipgo.NewUA(
|
||||
sipgo.WithUserAgent(scs.UserAgent),
|
||||
sipgo.WithUserAgentTransportLayerOptions(sip.WithTransportLayerLogger(diagoLogger)),
|
||||
sipgo.WithUserAgentTransactionLayerOptions(sip.WithTransactionLayerLogger(diagoLogger)),
|
||||
)
|
||||
defer ua.Close()
|
||||
|
||||
sip.SetDefaultLogger(diagoLogger)
|
||||
media.SetDefaultLogger(diagoLogger)
|
||||
dg := diago.NewDiago(ua, diago.WithLogger(diagoLogger), diago.WithTransport(
|
||||
diago.Transport{
|
||||
Transport: scs.Transport,
|
||||
BindHost: scs.IP,
|
||||
BindPort: scs.Port,
|
||||
},
|
||||
))
|
||||
|
||||
go func() {
|
||||
dg.Serve(scs.ctx, func(inDialog *diago.DialogServerSession) {
|
||||
scs.HandleCall(inDialog)
|
||||
})
|
||||
}()
|
||||
|
||||
scs.dg = dg
|
||||
|
||||
<-scs.ctx.Done()
|
||||
scs.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) HandleCall(inDialog *diago.DialogServerSession) {
|
||||
inDialog.Trying()
|
||||
inDialog.Ringing()
|
||||
inDialog.Answer()
|
||||
|
||||
dialogContext := context.WithValue(scs.ctx, sipCallContextKey("call"), &SIPCall{
|
||||
inDialog: inDialog,
|
||||
})
|
||||
scs.router.HandleInput(dialogContext, scs.Id(), SIPCallMessage{
|
||||
To: inDialog.ToUser(),
|
||||
})
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
|
||||
call, ok := ctx.Value(sipCallContextKey("call")).(*SIPCall)
|
||||
|
||||
if !ok {
|
||||
return errors.New("sip.call.server output must originate from sip.call.server input")
|
||||
}
|
||||
|
||||
gotLock := call.lock.TryLock()
|
||||
|
||||
if !gotLock {
|
||||
return errors.New("sip.call.server call is already locked")
|
||||
}
|
||||
|
||||
if call.inDialog.LoadState() == sip.DialogStateEnded {
|
||||
return errors.New("sip.call.server inDialog already ended")
|
||||
}
|
||||
|
||||
payloadDTMFResponse, ok := processor.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
|
||||
if ok {
|
||||
dtmfWriter := call.inDialog.AudioWriterDTMF()
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadDTMFResponse.PreWait))
|
||||
for i, dtmfRune := range payloadDTMFResponse.Digits {
|
||||
err := dtmfWriter.WriteDTMF(dtmfRune)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("sip.dtmf.server error output dtmf digit at index %d", i)
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadDTMFResponse.PostWait))
|
||||
return nil
|
||||
}
|
||||
|
||||
payloadAudioFileResponse, ok := processor.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
|
||||
if ok {
|
||||
audioFile, err := os.Open(payloadAudioFileResponse.AudioFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer audioFile.Close()
|
||||
|
||||
playback, err := call.inDialog.PlaybackCreate()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadAudioFileResponse.PreWait))
|
||||
|
||||
_, err = playback.Play(audioFile, "audio/wav")
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadAudioFileResponse.PostWait))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return errors.New("sip.dtmf.server can only output SipDTMFResponse or SipAudioFileResponse")
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Stop() {
|
||||
scs.cancel()
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("sip.call.server does not support Get")
|
||||
}
|
||||
255
internal/module/sip-dtmf-server.go
Normal file
255
internal/module/sip-dtmf-server.go
Normal file
@@ -0,0 +1,255 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/emiago/diago"
|
||||
"github.com/emiago/diago/media"
|
||||
"github.com/emiago/sipgo"
|
||||
"github.com/emiago/sipgo/sip"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type SIPDTMFServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
IP string
|
||||
Port int
|
||||
Transport string
|
||||
UserAgent string
|
||||
Separator string
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type SIPDTMFMessage struct {
|
||||
To string
|
||||
Digits string
|
||||
}
|
||||
|
||||
type SIPDTMFCall struct {
|
||||
inDialog *diago.DialogServerSession
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "sip.dtmf.server",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
portNum = 5060
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.dtmf.server port error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
ipString = "0.0.0.0"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.dtmf.server ip error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
transportString, err := params.GetString("transport")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
transportString = "udp"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.dtmf.server transport error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
userAgentString, err := params.GetString("userAgent")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
userAgentString = "showbridge"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.dtmf.server userAgent error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
separatorString, err := params.GetString("separator")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sip.dtmf.server separator error: %w", err)
|
||||
}
|
||||
|
||||
if len(separatorString) != 1 {
|
||||
return nil, errors.New("sip.dtmf.server separator must be a single character")
|
||||
}
|
||||
|
||||
if !strings.ContainsRune("0123456789*#ABCD", rune(separatorString[0])) {
|
||||
return nil, errors.New("sip.dtmf.server separator must be a valid DTMF character")
|
||||
}
|
||||
return &SIPDTMFServer{config: moduleConfig, IP: ipString, Port: int(portNum), Transport: transportString, UserAgent: userAgentString, Separator: separatorString, logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Id() string {
|
||||
return sds.config.Id
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Type() string {
|
||||
return sds.config.Type
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Start(ctx context.Context) error {
|
||||
sds.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("sip.dtmf.server unable to get router from context")
|
||||
}
|
||||
sds.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
sds.ctx = moduleContext
|
||||
sds.cancel = cancel
|
||||
|
||||
diagoLogger := slog.New(slog.NewJSONHandler(io.Discard, nil))
|
||||
|
||||
ua, _ := sipgo.NewUA(
|
||||
sipgo.WithUserAgent(sds.UserAgent),
|
||||
sipgo.WithUserAgentTransportLayerOptions(sip.WithTransportLayerLogger(diagoLogger)),
|
||||
sipgo.WithUserAgentTransactionLayerOptions(sip.WithTransactionLayerLogger(diagoLogger)),
|
||||
)
|
||||
defer ua.Close()
|
||||
|
||||
sip.SetDefaultLogger(diagoLogger)
|
||||
media.SetDefaultLogger(diagoLogger)
|
||||
dg := diago.NewDiago(ua, diago.WithLogger(diagoLogger), diago.WithTransport(
|
||||
diago.Transport{
|
||||
Transport: sds.Transport,
|
||||
BindHost: sds.IP,
|
||||
BindPort: sds.Port,
|
||||
},
|
||||
))
|
||||
|
||||
err := dg.Serve(sds.ctx, func(inDialog *diago.DialogServerSession) {
|
||||
sds.HandleCall(inDialog)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
<-sds.ctx.Done()
|
||||
sds.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) HandleCall(inDialog *diago.DialogServerSession) error {
|
||||
inDialog.Trying()
|
||||
inDialog.Ringing()
|
||||
inDialog.Answer()
|
||||
|
||||
reader := inDialog.AudioReaderDTMF()
|
||||
userString := ""
|
||||
|
||||
return reader.Listen(func(dtmf rune) error {
|
||||
if dtmf == rune(sds.Separator[0]) {
|
||||
if sds.router != nil {
|
||||
dialogContext := context.WithValue(sds.ctx, sipCallContextKey("call"), &SIPDTMFCall{
|
||||
inDialog: inDialog,
|
||||
})
|
||||
sds.router.HandleInput(dialogContext, sds.Id(), SIPDTMFMessage{
|
||||
To: inDialog.ToUser(),
|
||||
Digits: userString,
|
||||
})
|
||||
}
|
||||
userString = ""
|
||||
} else {
|
||||
userString += string(dtmf)
|
||||
}
|
||||
return nil
|
||||
}, 5*time.Second)
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||
call, ok := ctx.Value(sipCallContextKey("call")).(*SIPDTMFCall)
|
||||
|
||||
if !ok {
|
||||
return errors.New("sip.dtmf.server output must originate from sip.dtmf.server input")
|
||||
}
|
||||
|
||||
gotLock := call.lock.TryLock()
|
||||
|
||||
if !gotLock {
|
||||
return errors.New("sip.dtmf.server call is already locked")
|
||||
}
|
||||
|
||||
if call.inDialog.LoadState() == sip.DialogStateEnded {
|
||||
return errors.New("sip.dtmf.server inDialog already ended")
|
||||
}
|
||||
|
||||
payloadDTMFResponse, ok := processor.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
|
||||
if ok {
|
||||
dtmfWriter := call.inDialog.AudioWriterDTMF()
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadDTMFResponse.PreWait))
|
||||
for i, dtmfRune := range payloadDTMFResponse.Digits {
|
||||
err := dtmfWriter.WriteDTMF(dtmfRune)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("sip.dtmf.server error output dtmf digit at index %d", i)
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadDTMFResponse.PostWait))
|
||||
return nil
|
||||
}
|
||||
|
||||
payloadAudioFileResponse, ok := processor.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
|
||||
if ok {
|
||||
audioFile, err := os.Open(payloadAudioFileResponse.AudioFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer audioFile.Close()
|
||||
|
||||
playback, err := call.inDialog.PlaybackCreate()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadAudioFileResponse.PreWait))
|
||||
|
||||
_, err = playback.Play(audioFile, "audio/wav")
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadAudioFileResponse.PostWait))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New("sip.dtmf.server can only output SipDTMFResponse or SipAudioFileResponse")
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Stop() {
|
||||
sds.cancel()
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("sip.dtmf.server does not support Get")
|
||||
}
|
||||
183
internal/module/tcp-client.go
Normal file
183
internal/module/tcp-client.go
Normal file
@@ -0,0 +1,183 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type TCPClient struct {
|
||||
config config.ModuleConfig
|
||||
framer framer.Framer
|
||||
conn *net.TCPConn
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
Addr *net.TCPAddr
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.tcp.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
hostString, err := params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.client host error: %w", err)
|
||||
}
|
||||
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.client port error: %w", err)
|
||||
}
|
||||
|
||||
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", hostString, uint16(portNum)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
framingMethodString, err := params.GetString("framing")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.client framing error: %w", err)
|
||||
}
|
||||
|
||||
framer := framer.GetFramer(framingMethodString)
|
||||
|
||||
if framer == nil {
|
||||
return nil, fmt.Errorf("net.tcp.client unknown framing method: %s", framingMethodString)
|
||||
}
|
||||
return &TCPClient{framer: framer, Addr: addr, config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Id() string {
|
||||
return tc.config.Id
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Type() string {
|
||||
return tc.config.Type
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Start(ctx context.Context) error {
|
||||
tc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client unable to get router from context")
|
||||
}
|
||||
tc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
tc.ctx = moduleContext
|
||||
tc.cancel = cancel
|
||||
|
||||
// TODO(jwetzell): shutdown with router.Context properly
|
||||
go func() {
|
||||
<-tc.ctx.Done()
|
||||
tc.logger.Debug("done")
|
||||
if tc.conn != nil {
|
||||
tc.conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
err := tc.SetupConn()
|
||||
if err != nil {
|
||||
if tc.ctx.Err() != nil {
|
||||
tc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
tc.logger.Error("connection error", "error", err.Error())
|
||||
time.Sleep(time.Second * 2)
|
||||
continue
|
||||
}
|
||||
|
||||
buffer := make([]byte, 1024)
|
||||
select {
|
||||
case <-tc.ctx.Done():
|
||||
tc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
READ:
|
||||
for {
|
||||
select {
|
||||
case <-tc.ctx.Done():
|
||||
tc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
byteCount, err := tc.conn.Read(buffer)
|
||||
|
||||
if err != nil {
|
||||
tc.framer.Clear()
|
||||
break READ
|
||||
}
|
||||
|
||||
if tc.framer != nil {
|
||||
if byteCount > 0 {
|
||||
messages := tc.framer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if tc.router != nil {
|
||||
tc.router.HandleInput(tc.ctx, tc.Id(), message)
|
||||
} else {
|
||||
tc.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (tc *TCPClient) SetupConn() error {
|
||||
client, err := net.DialTCP("tcp", nil, tc.Addr)
|
||||
tc.conn = client
|
||||
return err
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Output(ctx context.Context, payload any) error {
|
||||
// NOTE(jwetzell): not sure how this would occur but
|
||||
if tc.conn == nil {
|
||||
err := tc.SetupConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client is only able to output bytes")
|
||||
}
|
||||
_, err := tc.conn.Write(tc.framer.Encode(payloadBytes))
|
||||
return err
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Stop() {
|
||||
tc.cancel()
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "host":
|
||||
host, err := tc.config.Params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.client host error: %w", err)
|
||||
}
|
||||
return host, nil
|
||||
case "ip":
|
||||
return tc.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return tc.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.tcp.client key not found")
|
||||
}
|
||||
}
|
||||
246
internal/module/tcp-server.go
Normal file
246
internal/module/tcp-server.go
Normal file
@@ -0,0 +1,246 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"slices"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type TCPServer struct {
|
||||
config config.ModuleConfig
|
||||
Addr *net.TCPAddr
|
||||
Framer framer.Framer
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
quit chan interface{}
|
||||
wg sync.WaitGroup
|
||||
connections []*net.TCPConn
|
||||
connectionsMu sync.RWMutex
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.tcp.server",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.server port error: %w", err)
|
||||
}
|
||||
|
||||
framingMethodString, err := params.GetString("framing")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.server framing error: %w", err)
|
||||
}
|
||||
|
||||
framer := framer.GetFramer(framingMethodString)
|
||||
|
||||
if framer == nil {
|
||||
return nil, fmt.Errorf("net.tcp.server unknown framing method: %s", framingMethodString)
|
||||
}
|
||||
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
ipString = "0.0.0.0"
|
||||
} else {
|
||||
return nil, fmt.Errorf("net.tcp.server ip error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", ipString, uint16(portNum)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &TCPServer{Framer: framer, Addr: addr, config: moduleConfig, quit: make(chan interface{}), logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Id() string {
|
||||
return ts.config.Id
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Type() string {
|
||||
return ts.config.Type
|
||||
}
|
||||
|
||||
func (ts *TCPServer) handleClient(client *net.TCPConn) {
|
||||
ts.connectionsMu.Lock()
|
||||
ts.connections = append(ts.connections, client)
|
||||
ts.connectionsMu.Unlock()
|
||||
ts.logger.Debug("net.tcp.server connection accepted", "remoteAddr", client.RemoteAddr().String())
|
||||
defer client.Close()
|
||||
|
||||
buffer := make([]byte, 1024)
|
||||
ClientRead:
|
||||
for {
|
||||
select {
|
||||
case <-ts.quit:
|
||||
client.Close()
|
||||
ts.connectionsMu.Lock()
|
||||
for i := 0; i < len(ts.connections); i++ {
|
||||
if ts.connections[i] == client {
|
||||
ts.connections = slices.Delete(ts.connections, i, i+1)
|
||||
break
|
||||
}
|
||||
}
|
||||
ts.connectionsMu.Unlock()
|
||||
return
|
||||
default:
|
||||
client.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
byteCount, err := client.Read(buffer)
|
||||
|
||||
if err != nil {
|
||||
if opErr, ok := err.(*net.OpError); ok {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr.Timeout() {
|
||||
continue ClientRead
|
||||
}
|
||||
if errors.Is(opErr, syscall.ECONNRESET) {
|
||||
ts.connectionsMu.Lock()
|
||||
for i := 0; i < len(ts.connections); i++ {
|
||||
if ts.connections[i] == client {
|
||||
ts.connections = slices.Delete(ts.connections, i, i+1)
|
||||
break
|
||||
}
|
||||
}
|
||||
ts.logger.Debug("connection reset", "remoteAddr", client.RemoteAddr().String())
|
||||
ts.connectionsMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
if err.Error() == "EOF" {
|
||||
ts.connectionsMu.Lock()
|
||||
for i := 0; i < len(ts.connections); i++ {
|
||||
if ts.connections[i] == client {
|
||||
ts.connections = slices.Delete(ts.connections, i, i+1)
|
||||
break
|
||||
}
|
||||
}
|
||||
ts.logger.Debug("stream ended", "remoteAddr", client.RemoteAddr().String())
|
||||
ts.connectionsMu.Unlock()
|
||||
}
|
||||
return
|
||||
}
|
||||
if ts.Framer != nil {
|
||||
if byteCount > 0 {
|
||||
messages := ts.Framer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if ts.router != nil {
|
||||
senderAddr, ok := client.RemoteAddr().(*net.TCPAddr)
|
||||
if ok {
|
||||
senderCtx := context.WithValue(ts.ctx, common.SenderContextKey, senderAddr)
|
||||
ts.router.HandleInput(senderCtx, ts.Id(), message)
|
||||
} else {
|
||||
ts.router.HandleInput(ts.ctx, ts.Id(), message)
|
||||
}
|
||||
} else {
|
||||
ts.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Start(ctx context.Context) error {
|
||||
ts.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.server unable to get router from context")
|
||||
}
|
||||
ts.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
ts.ctx = moduleContext
|
||||
ts.cancel = cancel
|
||||
|
||||
listener, err := net.ListenTCP("tcp", ts.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ts.wg.Add(1)
|
||||
|
||||
go func() {
|
||||
<-ts.ctx.Done()
|
||||
close(ts.quit)
|
||||
listener.Close()
|
||||
ts.logger.Debug("done")
|
||||
}()
|
||||
|
||||
AcceptLoop:
|
||||
for {
|
||||
conn, err := listener.AcceptTCP()
|
||||
if err != nil {
|
||||
select {
|
||||
case <-ts.quit:
|
||||
break AcceptLoop
|
||||
default:
|
||||
ts.logger.Debug("problem with listener", "error", err)
|
||||
}
|
||||
} else {
|
||||
ts.wg.Add(1)
|
||||
go func() {
|
||||
ts.handleClient(conn)
|
||||
ts.wg.Done()
|
||||
}()
|
||||
}
|
||||
}
|
||||
ts.wg.Done()
|
||||
ts.wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Output(ctx context.Context, payload any) error {
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.server is only able to output bytes")
|
||||
}
|
||||
ts.connectionsMu.Lock()
|
||||
errorString := ""
|
||||
|
||||
for _, connection := range ts.connections {
|
||||
_, err := connection.Write(payloadBytes)
|
||||
if err != nil {
|
||||
errorString += fmt.Sprintf("%s\n", err.Error())
|
||||
}
|
||||
}
|
||||
ts.connectionsMu.Unlock()
|
||||
|
||||
if errorString == "" {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("net.tcp.server error during output: %s", errorString)
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Stop() {
|
||||
ts.cancel()
|
||||
ts.wg.Wait()
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "ip":
|
||||
return ts.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return ts.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.tcp.server key not found")
|
||||
}
|
||||
}
|
||||
87
internal/module/test/http-server_test.go
Normal file
87
internal/module/test/http-server_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestHTTPServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["http.server"]
|
||||
if !ok {
|
||||
t.Fatalf("http.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "http.server",
|
||||
Params: map[string]any{
|
||||
"port": 3000,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create http.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("http.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "http.server" {
|
||||
t.Fatalf("http.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadHTTPServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{},
|
||||
errorString: "http.server port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-numeric port",
|
||||
params: map[string]any{"port": "3000"},
|
||||
errorString: "http.server port error: not a number",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["http.server"]
|
||||
if !ok {
|
||||
t.Fatalf("http.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "http.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("http.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("http.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("http.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
87
internal/module/test/midi-input_test.go
Normal file
87
internal/module/test/midi-input_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestMIDIInputFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["midi.input"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.input module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "midi.input",
|
||||
Params: map[string]any{
|
||||
"port": "test",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create midi.input module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("midi.input module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "midi.input" {
|
||||
t.Fatalf("midi.input module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadMIDIInput(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{},
|
||||
errorString: "midi.input port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string port",
|
||||
params: map[string]any{"port": 123},
|
||||
errorString: "midi.input port error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["midi.input"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.input module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "midi.input",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("midi.input got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("midi.input expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("midi.input got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
87
internal/module/test/midi-output_test.go
Normal file
87
internal/module/test/midi-output_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestMIDIOutputFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["midi.output"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.output module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "midi.output",
|
||||
Params: map[string]any{
|
||||
"port": "test",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create midi.output module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("midi.output module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "midi.output" {
|
||||
t.Fatalf("midi.output module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadMIDIOutput(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{},
|
||||
errorString: "midi.output port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string port",
|
||||
params: map[string]any{"port": 123},
|
||||
errorString: "midi.output port error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["midi.output"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.output module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "midi.output",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("midi.output got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("midi.output expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("midi.output got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
85
internal/module/test/module_test.go
Normal file
85
internal/module/test/module_test.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
type TestModule struct {
|
||||
}
|
||||
|
||||
func (m *TestModule) Output(ctx context.Context, payload any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *TestModule) Start(ctx context.Context) error {
|
||||
<-ctx.Done()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *TestModule) Stop() {}
|
||||
|
||||
func (m *TestModule) Type() string {
|
||||
return "module.test"
|
||||
}
|
||||
|
||||
func (m *TestModule) Id() string {
|
||||
return "test"
|
||||
}
|
||||
|
||||
func (m *TestModule) Get(key string) (any, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestModuleBadRegistrationNoType(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Fatalf("module registration should have panicked but did not")
|
||||
}
|
||||
}()
|
||||
|
||||
module.RegisterModule(module.ModuleRegistration{
|
||||
Type: "",
|
||||
New: func(config config.ModuleConfig) (module.Module, error) {
|
||||
return &TestModule{}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestModuleBadRegistrationNoNew(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Fatalf("processor registration should have panicked but did not")
|
||||
}
|
||||
}()
|
||||
|
||||
module.RegisterModule(module.ModuleRegistration{
|
||||
Type: "module.test",
|
||||
New: nil,
|
||||
})
|
||||
}
|
||||
|
||||
func TestModuleBadRegistrationExistingType(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Fatalf("processor registration should have panicked but did not")
|
||||
}
|
||||
}()
|
||||
|
||||
module.RegisterModule(module.ModuleRegistration{
|
||||
Type: "module.test",
|
||||
New: func(config config.ModuleConfig) (module.Module, error) {
|
||||
return &TestModule{}, nil
|
||||
},
|
||||
})
|
||||
|
||||
module.RegisterModule(module.ModuleRegistration{
|
||||
Type: "module.test",
|
||||
New: func(config config.ModuleConfig) (module.Module, error) {
|
||||
return &TestModule{}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
130
internal/module/test/mqtt-client_test.go
Normal file
130
internal/module/test/mqtt-client_test.go
Normal file
@@ -0,0 +1,130 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestMQTTClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["mqtt.client"]
|
||||
if !ok {
|
||||
t.Fatalf("mqtt.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "mqtt.client",
|
||||
Params: map[string]any{
|
||||
"broker": "mqtt://localhost:1883",
|
||||
"topic": "test/topic",
|
||||
"clientId": "test",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create mqtt.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("mqtt.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "mqtt.client" {
|
||||
t.Fatalf("mqtt.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadMQTTClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no broker param",
|
||||
params: map[string]any{
|
||||
"topic": "test/topic",
|
||||
"clientId": "test",
|
||||
},
|
||||
errorString: "mqtt.client broker error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string broker",
|
||||
params: map[string]any{
|
||||
"broker": 123,
|
||||
"topic": "test/topic",
|
||||
"clientId": "test",
|
||||
},
|
||||
errorString: "mqtt.client broker error: not a string",
|
||||
},
|
||||
{
|
||||
name: "no topic param",
|
||||
params: map[string]any{
|
||||
"broker": "mqtt://localhost:1883",
|
||||
"clientId": "test",
|
||||
},
|
||||
errorString: "mqtt.client topic error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string topic",
|
||||
params: map[string]any{
|
||||
"broker": "mqtt://localhost:1883",
|
||||
"topic": 123,
|
||||
"clientId": "test",
|
||||
},
|
||||
errorString: "mqtt.client topic error: not a string",
|
||||
},
|
||||
{
|
||||
name: "no clientId param",
|
||||
params: map[string]any{
|
||||
"broker": "mqtt://localhost:1883",
|
||||
"topic": "test/topic",
|
||||
},
|
||||
errorString: "mqtt.client clientId error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string clientId",
|
||||
params: map[string]any{
|
||||
"broker": "mqtt://localhost:1883",
|
||||
"topic": "test/topic",
|
||||
"clientId": 123,
|
||||
},
|
||||
errorString: "mqtt.client clientId error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["mqtt.client"]
|
||||
if !ok {
|
||||
t.Fatalf("mqtt.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "mqtt.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("mqtt.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("mqtt.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("mqtt.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
108
internal/module/test/nats-client_test.go
Normal file
108
internal/module/test/nats-client_test.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestNATSClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["nats.client"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "nats.client",
|
||||
Params: map[string]any{
|
||||
"url": "nats://127.0.0.1:4222",
|
||||
"subject": "test",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create nats.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("nats.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "nats.client" {
|
||||
t.Fatalf("nats.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadNATSClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no url param",
|
||||
params: map[string]any{
|
||||
"subject": "test/subject",
|
||||
},
|
||||
errorString: "nats.client url error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string url",
|
||||
params: map[string]any{
|
||||
"url": 123,
|
||||
"subject": "test/subject",
|
||||
},
|
||||
errorString: "nats.client url error: not a string",
|
||||
},
|
||||
{
|
||||
name: "no subject param",
|
||||
params: map[string]any{
|
||||
"url": "nats://127.0.0.1:4222",
|
||||
},
|
||||
errorString: "nats.client subject error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string subject",
|
||||
params: map[string]any{
|
||||
"url": "nats://127.0.0.1:4222",
|
||||
"subject": 123,
|
||||
},
|
||||
errorString: "nats.client subject error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["nats.client"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "nats.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("nats.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("nats.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("nats.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
85
internal/module/test/nats-server_test.go
Normal file
85
internal/module/test/nats-server_test.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestNATSServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["nats.server"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "nats.server",
|
||||
Params: map[string]any{
|
||||
"ip": "127.0.0.1",
|
||||
"port": 4222,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create nats.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("nats.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "nats.server" {
|
||||
t.Fatalf("nats.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadNATSServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "non-string ip",
|
||||
params: map[string]any{
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "nats.server ip error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["nats.server"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "nats.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("nats.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("nats.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("nats.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
73
internal/module/test/psn-client_test.go
Normal file
73
internal/module/test/psn-client_test.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestPSNClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["psn.client"]
|
||||
if !ok {
|
||||
t.Fatalf("psn.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "psn.client",
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create psn.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("psn.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "psn.client" {
|
||||
t.Fatalf("psn.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadPSNClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["psn.client"]
|
||||
if !ok {
|
||||
t.Fatalf("psn.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "psn.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("psn.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("psn.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("psn.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
117
internal/module/test/serial-client_test.go
Normal file
117
internal/module/test/serial-client_test.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestSerialClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["serial.client"]
|
||||
if !ok {
|
||||
t.Fatalf("serial.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "serial.client",
|
||||
Params: map[string]any{
|
||||
"port": "/dev/ttyUSB0",
|
||||
"framing": "LF",
|
||||
"baudRate": 9600,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create serial.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("serial.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "serial.client" {
|
||||
t.Fatalf("serial.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadSerialClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "serial.client port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string port param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "serial.client port error: not a string",
|
||||
},
|
||||
{
|
||||
name: "no framing param",
|
||||
params: map[string]any{
|
||||
"port": "/dev/ttyUSB0",
|
||||
},
|
||||
errorString: "serial.client framing error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string framing param",
|
||||
params: map[string]any{
|
||||
"port": "/dev/ttyUSB0",
|
||||
"framing": 1,
|
||||
},
|
||||
errorString: "serial.client framing error: not a string",
|
||||
},
|
||||
{
|
||||
name: "unkown framing method",
|
||||
params: map[string]any{
|
||||
"port": "/dev/ttyUSB0",
|
||||
"framing": "asdfasdfasdfasdflkj",
|
||||
},
|
||||
errorString: "serial.client unknown framing method: asdfasdfasdfasdflkj",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["serial.client"]
|
||||
if !ok {
|
||||
t.Fatalf("serial.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "serial.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("serial.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("serial.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("serial.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
102
internal/module/test/sip-call-server_test.go
Normal file
102
internal/module/test/sip-call-server_test.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestSIPCallServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["sip.call.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.call.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "sip.call.server",
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create sip.call.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("sip.call.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "sip.call.server" {
|
||||
t.Fatalf("sip.call.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadSIPCallServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "sip.call.server port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "sip.call.server ip error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-string transport param",
|
||||
params: map[string]any{
|
||||
"transport": 123,
|
||||
},
|
||||
errorString: "sip.call.server transport error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-string userAgent param",
|
||||
params: map[string]any{
|
||||
"userAgent": 123,
|
||||
},
|
||||
errorString: "sip.call.server userAgent error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["sip.call.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.call.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "sip.call.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("sip.call.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("sip.call.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("sip.call.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
121
internal/module/test/sip-dtmf-server_test.go
Normal file
121
internal/module/test/sip-dtmf-server_test.go
Normal file
@@ -0,0 +1,121 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestSIPDTMFServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["sip.dtmf.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.dtmf.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "sip.dtmf.server",
|
||||
Params: map[string]any{
|
||||
"separator": "#",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create sip.dtmf.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("sip.dtmf.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "sip.dtmf.server" {
|
||||
t.Fatalf("sip.dtmf.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadSIPDTMFServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no separator param",
|
||||
params: map[string]any{},
|
||||
errorString: "sip.dtmf.server separator error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string separator param",
|
||||
params: map[string]any{
|
||||
"separator": 123,
|
||||
},
|
||||
errorString: "sip.dtmf.server separator error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"separator": "#",
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "sip.dtmf.server port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"separator": "#",
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "sip.dtmf.server ip error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-string transport param",
|
||||
params: map[string]any{
|
||||
"separator": "#",
|
||||
"transport": 123,
|
||||
},
|
||||
errorString: "sip.dtmf.server transport error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-string userAgent param",
|
||||
params: map[string]any{
|
||||
"separator": "#",
|
||||
"userAgent": 123,
|
||||
},
|
||||
errorString: "sip.dtmf.server userAgent error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["sip.dtmf.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.dtmf.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "sip.dtmf.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("sip.dtmf.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("sip.dtmf.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("sip.dtmf.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
109
internal/module/test/tcp-client_test.go
Normal file
109
internal/module/test/tcp-client_test.go
Normal file
@@ -0,0 +1,109 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTCPClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["net.tcp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.tcp.client",
|
||||
Params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create net.tcp.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("net.tcp.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "net.tcp.client" {
|
||||
t.Fatalf("net.tcp.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTCPClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
},
|
||||
errorString: "net.tcp.client port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "net.tcp.client port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "no host param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.tcp.client host error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string host param",
|
||||
params: map[string]any{
|
||||
"host": 123,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.tcp.client host error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["net.tcp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.tcp.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("net.tcp.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.tcp.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("net.tcp.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
134
internal/module/test/tcp-server_test.go
Normal file
134
internal/module/test/tcp-server_test.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTCPServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["net.tcp.server"]
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.tcp.server",
|
||||
Params: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create net.tcp.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("net.tcp.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "net.tcp.server" {
|
||||
t.Fatalf("net.tcp.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTCPServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "net.tcp.server port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"port": "8000",
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "net.tcp.server port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "no framing param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.tcp.server framing error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string framing param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": 1,
|
||||
},
|
||||
errorString: "net.tcp.server framing error: not a string",
|
||||
},
|
||||
{
|
||||
name: "unkown framing method",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": "asdfasdfasdfasdflkj",
|
||||
},
|
||||
errorString: "net.tcp.server unknown framing method: asdfasdfasdfasdflkj",
|
||||
},
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "net.tcp.server ip error: not a string",
|
||||
},
|
||||
{
|
||||
name: "invalid addr",
|
||||
params: map[string]any{
|
||||
"ip": "127.0.0.",
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "lookup 127.0.0.: no such host",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["net.tcp.server"]
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.tcp.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("net.tcp.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.tcp.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("net.tcp.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
89
internal/module/test/time-interval_test.go
Normal file
89
internal/module/test/time-interval_test.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTimeIntervalFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["time.interval"]
|
||||
if !ok {
|
||||
t.Fatalf("time.interval module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "time.interval",
|
||||
Params: map[string]any{
|
||||
"duration": 1000,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create time.interval module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("time.interval module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "time.interval" {
|
||||
t.Fatalf("time.interval module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTimeInterval(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no duration param",
|
||||
params: map[string]any{},
|
||||
errorString: "time.interval duration error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number duration param",
|
||||
params: map[string]any{
|
||||
"duration": "8000",
|
||||
},
|
||||
errorString: "time.interval duration error: not a number",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["time.interval"]
|
||||
if !ok {
|
||||
t.Fatalf("time.interval module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "time.interval",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("time.interval got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("time.interval expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("time.interval got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
89
internal/module/test/time-timer_test.go
Normal file
89
internal/module/test/time-timer_test.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTimeTimerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["time.timer"]
|
||||
if !ok {
|
||||
t.Fatalf("time.timer module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "time.timer",
|
||||
Params: map[string]any{
|
||||
"duration": 1000,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create time.timer module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("time.timer module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "time.timer" {
|
||||
t.Fatalf("time.timer module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTimeTimer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no duration param",
|
||||
params: map[string]any{},
|
||||
errorString: "time.timer duration error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number duration param",
|
||||
params: map[string]any{
|
||||
"duration": "8000",
|
||||
},
|
||||
errorString: "time.timer duration error: not a number",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["time.timer"]
|
||||
if !ok {
|
||||
t.Fatalf("time.timer module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "time.timer",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("time.timer got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("time.timer expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("time.timer got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
109
internal/module/test/udp-client_test.go
Normal file
109
internal/module/test/udp-client_test.go
Normal file
@@ -0,0 +1,109 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestUDPClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["net.udp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("udp.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.client",
|
||||
Params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create net.udp.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("net.udp.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "net.udp.client" {
|
||||
t.Fatalf("net.udp.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadUDPClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
},
|
||||
errorString: "net.udp.client port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "net.udp.client port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "no host param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.client host error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string host param",
|
||||
params: map[string]any{
|
||||
"host": 123,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.client host error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["net.udp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("net.udp.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.udp.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("net.udp.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
116
internal/module/test/udp-multicast_test.go
Normal file
116
internal/module/test/udp-multicast_test.go
Normal file
@@ -0,0 +1,116 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestUDPMulticastFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["net.udp.multicast"]
|
||||
if !ok {
|
||||
t.Fatalf("udp.multicast module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.multicast",
|
||||
Params: map[string]any{
|
||||
"ip": "236.10.10.10",
|
||||
"port": 56565,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create net.udp.multicast module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("net.udp.multicast module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "net.udp.multicast" {
|
||||
t.Fatalf("net.udp.multicast module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadUDPMulticast(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"ip": "localhost",
|
||||
},
|
||||
errorString: "net.udp.multicast port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"ip": "localhost",
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "net.udp.multicast port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "no ip param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.multicast ip error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"ip": 123,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.multicast ip error: not a string",
|
||||
},
|
||||
{
|
||||
name: "invalid addr",
|
||||
params: map[string]any{
|
||||
"ip": "127.0.0.",
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "lookup 127.0.0.: no such host",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["net.udp.multicast"]
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.multicast module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.multicast",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("net.udp.multicast got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.udp.multicast expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("net.udp.multicast got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
113
internal/module/test/udp-server_test.go
Normal file
113
internal/module/test/udp-server_test.go
Normal file
@@ -0,0 +1,113 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestUDPServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["net.udp.server"]
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.server",
|
||||
Params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create udp.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("udp.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "net.udp.server" {
|
||||
t.Fatalf("net.udp.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadUDPServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{},
|
||||
errorString: "net.udp.server port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "net.udp.server port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "net.udp.server ip error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-number bufferSize param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"bufferSize": "1024",
|
||||
},
|
||||
errorString: "net.udp.server bufferSize error: not a number",
|
||||
},
|
||||
{
|
||||
name: "invalid addr",
|
||||
params: map[string]any{
|
||||
"ip": "127.0.0.",
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "lookup 127.0.0.: no such host",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["net.udp.server"]
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("net.udp.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.udp.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("net.udp.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
93
internal/module/time-interval.go
Normal file
93
internal/module/time-interval.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type TimeInterval struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
ticker *time.Ticker
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "time.interval",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
|
||||
durationInt, err := params.GetInt("duration")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("time.interval duration error: %w", err)
|
||||
}
|
||||
return &TimeInterval{Duration: uint32(durationInt), config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Id() string {
|
||||
return i.config.Id
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Type() string {
|
||||
return i.config.Type
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Start(ctx context.Context) error {
|
||||
i.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("time.interval unable to get router from context")
|
||||
}
|
||||
i.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
i.ctx = moduleContext
|
||||
i.cancel = cancel
|
||||
|
||||
ticker := time.NewTicker(time.Millisecond * time.Duration(i.Duration))
|
||||
i.ticker = ticker
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-i.ctx.Done():
|
||||
i.logger.Debug("done")
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
if i.router != nil {
|
||||
i.router.HandleInput(i.ctx, i.Id(), time.Now())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Output(ctx context.Context, payload any) error {
|
||||
i.ticker.Reset(time.Millisecond * time.Duration(i.Duration))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Stop() {
|
||||
i.cancel()
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "duration":
|
||||
return i.Duration, nil
|
||||
default:
|
||||
return nil, errors.New("time.interval key not found")
|
||||
}
|
||||
}
|
||||
92
internal/module/time-timer.go
Normal file
92
internal/module/time-timer.go
Normal file
@@ -0,0 +1,92 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type TimeTimer struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
timer *time.Timer
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "time.timer",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
|
||||
durationNum, err := params.GetInt("duration")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("time.timer duration error: %w", err)
|
||||
}
|
||||
|
||||
return &TimeTimer{Duration: uint32(durationNum), config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Id() string {
|
||||
return t.config.Id
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Type() string {
|
||||
return t.config.Type
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Start(ctx context.Context) error {
|
||||
t.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client unable to get router from context")
|
||||
}
|
||||
t.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
t.ctx = moduleContext
|
||||
t.cancel = cancel
|
||||
|
||||
t.timer = time.NewTimer(time.Millisecond * time.Duration(t.Duration))
|
||||
defer t.timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.ctx.Done():
|
||||
t.timer.Stop()
|
||||
t.logger.Debug("done")
|
||||
return nil
|
||||
case time := <-t.timer.C:
|
||||
if t.router != nil {
|
||||
t.router.HandleInput(t.ctx, t.Id(), time)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Output(ctx context.Context, payload any) error {
|
||||
t.timer.Reset(time.Millisecond * time.Duration(t.Duration))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Stop() {
|
||||
t.cancel()
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "duration":
|
||||
return t.Duration, nil
|
||||
default:
|
||||
return nil, errors.New("time.timer key not found")
|
||||
}
|
||||
}
|
||||
126
internal/module/udp-client.go
Normal file
126
internal/module/udp-client.go
Normal file
@@ -0,0 +1,126 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type UDPClient struct {
|
||||
config config.ModuleConfig
|
||||
Addr *net.UDPAddr
|
||||
Port uint16
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.udp.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
hostString, err := params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.client host error: %w", err)
|
||||
}
|
||||
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.client port error: %w", err)
|
||||
}
|
||||
|
||||
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", hostString, uint16(portNum)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &UDPClient{Addr: addr, config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Id() string {
|
||||
return uc.config.Id
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Type() string {
|
||||
return uc.config.Type
|
||||
}
|
||||
|
||||
func (uc *UDPClient) SetupConn() error {
|
||||
client, err := net.DialUDP("udp", nil, uc.Addr)
|
||||
uc.conn = client
|
||||
return err
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Start(ctx context.Context) error {
|
||||
uc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.udp.client unable to get router from context")
|
||||
}
|
||||
uc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
uc.ctx = moduleContext
|
||||
uc.cancel = cancel
|
||||
|
||||
err := uc.SetupConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
<-uc.ctx.Done()
|
||||
uc.logger.Debug("done")
|
||||
if uc.conn != nil {
|
||||
uc.conn.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.udp.client is only able to output bytes")
|
||||
}
|
||||
if uc.conn != nil {
|
||||
_, err := uc.conn.Write(payloadBytes)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return errors.New("net.udp.client client is not setup")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Stop() {
|
||||
uc.cancel()
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "host":
|
||||
host, err := uc.config.Params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.client host error: %w", err)
|
||||
}
|
||||
return host, nil
|
||||
case "ip":
|
||||
return uc.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return uc.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.udp.client key not found")
|
||||
}
|
||||
}
|
||||
138
internal/module/udp-multicast.go
Normal file
138
internal/module/udp-multicast.go
Normal file
@@ -0,0 +1,138 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type UDPMulticast struct {
|
||||
config config.ModuleConfig
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
Addr *net.UDPAddr
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.udp.multicast",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.multicast ip error: %w", err)
|
||||
}
|
||||
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.multicast port error: %w", err)
|
||||
}
|
||||
|
||||
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", ipString, uint16(portNum)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &UDPMulticast{config: moduleConfig, Addr: addr, logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Id() string {
|
||||
return um.config.Id
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Type() string {
|
||||
return um.config.Type
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Start(ctx context.Context) error {
|
||||
um.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.udp.multicast unable to get router from context")
|
||||
}
|
||||
um.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
um.ctx = moduleContext
|
||||
um.cancel = cancel
|
||||
|
||||
client, err := net.ListenMulticastUDP("udp", nil, um.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
um.conn = client
|
||||
|
||||
buffer := make([]byte, 2048)
|
||||
for {
|
||||
select {
|
||||
case <-um.ctx.Done():
|
||||
// TODO(jwetzell): cleanup?
|
||||
um.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
um.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
|
||||
numBytes, _, err := um.conn.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if numBytes > 0 {
|
||||
message := buffer[:numBytes]
|
||||
|
||||
if um.router != nil {
|
||||
um.router.HandleInput(um.ctx, um.Id(), message)
|
||||
} else {
|
||||
um.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.udp.multicast can only output bytes")
|
||||
}
|
||||
|
||||
if um.conn == nil {
|
||||
return errors.New("net.udp.multicast connection is not setup")
|
||||
}
|
||||
|
||||
_, err := um.conn.Write(payloadBytes)
|
||||
return err
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Stop() {
|
||||
um.cancel()
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "ip":
|
||||
return um.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return um.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.udp.multicast key not found")
|
||||
}
|
||||
}
|
||||
136
internal/module/udp-server.go
Normal file
136
internal/module/udp-server.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type UDPServer struct {
|
||||
Addr *net.UDPAddr
|
||||
BufferSize int
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.udp.server",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.server port error: %w", err)
|
||||
}
|
||||
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
ipString = "0.0.0.0"
|
||||
} else {
|
||||
return nil, fmt.Errorf("net.udp.server ip error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", ipString, uint16(portNum)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
bufferSizeNum, err := params.GetInt("bufferSize")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
bufferSizeNum = 2048
|
||||
} else {
|
||||
return nil, fmt.Errorf("net.udp.server bufferSize error: %w", err)
|
||||
}
|
||||
}
|
||||
return &UDPServer{Addr: addr, BufferSize: bufferSizeNum, config: moduleConfig, logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (us *UDPServer) Id() string {
|
||||
return us.config.Id
|
||||
}
|
||||
|
||||
func (us *UDPServer) Type() string {
|
||||
return us.config.Type
|
||||
}
|
||||
|
||||
func (us *UDPServer) Start(ctx context.Context) error {
|
||||
us.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.udp.server unable to get router from context")
|
||||
}
|
||||
us.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
us.ctx = moduleContext
|
||||
us.cancel = cancel
|
||||
|
||||
listener, err := net.ListenUDP("udp", us.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer listener.Close()
|
||||
|
||||
buffer := make([]byte, us.BufferSize)
|
||||
for {
|
||||
select {
|
||||
case <-us.ctx.Done():
|
||||
// TODO(jwetzell): cleanup?
|
||||
us.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
listener.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
|
||||
numBytes, senderAddr, err := listener.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
message := buffer[:numBytes]
|
||||
if us.router != nil {
|
||||
senderCtx := context.WithValue(us.ctx, common.SenderContextKey, senderAddr)
|
||||
us.router.HandleInput(senderCtx, us.Id(), message)
|
||||
} else {
|
||||
us.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (us *UDPServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("net.udp.server output is not implemented")
|
||||
}
|
||||
|
||||
func (us *UDPServer) Stop() {
|
||||
us.cancel()
|
||||
}
|
||||
|
||||
func (us *UDPServer) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "ip":
|
||||
return us.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return us.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.udp.server key not found")
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
type DebugLog struct {
|
||||
config ProcessorConfig
|
||||
}
|
||||
|
||||
func (dl *DebugLog) Process(ctx context.Context, payload any) (any, error) {
|
||||
slog.Debug("debug.log", "payload", payload, "payloadType", fmt.Sprintf("%T", payload))
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (dl *DebugLog) Type() string {
|
||||
return dl.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "debug.log",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
return &DebugLog{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
)
|
||||
|
||||
type FreeDDecode struct {
|
||||
config ProcessorConfig
|
||||
}
|
||||
|
||||
func (fdd *FreeDDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.decode processor only accepts a []byte")
|
||||
}
|
||||
|
||||
payloadMessage, err := freeD.Decode(payloadBytes)
|
||||
if err != nil {
|
||||
slog.Error("error decoding", "err", err)
|
||||
}
|
||||
return payloadMessage, nil
|
||||
}
|
||||
|
||||
func (fdd *FreeDDecode) Type() string {
|
||||
return fdd.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "freed.decode",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
return &FreeDDecode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
)
|
||||
|
||||
type FreeDEncode struct {
|
||||
config ProcessorConfig
|
||||
}
|
||||
|
||||
func (fde *FreeDEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPosition, ok := payload.(freeD.FreeDPosition)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.decode processor only accepts a FreeDEncode")
|
||||
}
|
||||
|
||||
payloadBytes := freeD.Encode(payloadPosition)
|
||||
return payloadBytes, nil
|
||||
}
|
||||
|
||||
func (fde *FreeDEncode) Type() string {
|
||||
return fde.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "freed.encode",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
return &FreeDEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
type HTTPRequestCreate struct {
|
||||
config ProcessorConfig
|
||||
Method string
|
||||
URL *template.Template
|
||||
}
|
||||
|
||||
func (hre *HTTPRequestCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
var urlBuffer bytes.Buffer
|
||||
err := hre.URL.Execute(&urlBuffer, payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
urlString := urlBuffer.String()
|
||||
|
||||
//TODO(jwetzell): support body
|
||||
request, err := http.NewRequest(hre.Method, urlString, bytes.NewBuffer([]byte{}))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return request, nil
|
||||
}
|
||||
|
||||
func (hre *HTTPRequestCreate) Type() string {
|
||||
return hre.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.create",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
method, ok := params["method"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.create requires an method parameter")
|
||||
}
|
||||
|
||||
methodString, ok := method.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.create url must be a string")
|
||||
}
|
||||
|
||||
url, ok := params["url"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.create requires an url parameter")
|
||||
}
|
||||
|
||||
urlString, ok := url.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.create url must be a string")
|
||||
}
|
||||
|
||||
urlTemplate, err := template.New("url").Parse(urlString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &HTTPRequestCreate{config: config, URL: urlTemplate, Method: methodString}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type HTTPRequestEncode struct {
|
||||
config ProcessorConfig
|
||||
}
|
||||
|
||||
func (hre *HTTPRequestEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadRequest, ok := payload.(*http.Request)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.encode processor only accepts an http.Request")
|
||||
}
|
||||
|
||||
bytes, err := io.ReadAll(payloadRequest.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return bytes, nil
|
||||
}
|
||||
|
||||
func (hre *HTTPRequestEncode) Type() string {
|
||||
return hre.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.encode",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
return &HTTPRequestEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type HTTPRequestFilter struct {
|
||||
config ProcessorConfig
|
||||
Path *regexp.Regexp
|
||||
Method string
|
||||
}
|
||||
|
||||
func (hrf *HTTPRequestFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
payloadRequest, ok := payload.(*http.Request)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.filter can only operate on http.Request payloads")
|
||||
}
|
||||
|
||||
if hrf.Method != "" {
|
||||
if payloadRequest.Method != hrf.Method {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
if !hrf.Path.MatchString(payloadRequest.URL.Path) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadRequest, nil
|
||||
}
|
||||
|
||||
func (hrf *HTTPRequestFilter) Type() string {
|
||||
return hrf.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.filter",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
path, ok := params["path"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.filter requires an path parameter")
|
||||
}
|
||||
|
||||
pathString, ok := path.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.filter path must be a string")
|
||||
}
|
||||
|
||||
pathRegexp, err := regexp.Compile(fmt.Sprintf("^%s$", pathString))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
method, ok := params["method"]
|
||||
|
||||
if ok {
|
||||
methodString, ok := method.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.filter method must be a string")
|
||||
}
|
||||
return &HTTPRequestFilter{config: config, Path: pathRegexp, Method: methodString}, nil
|
||||
}
|
||||
|
||||
return &HTTPRequestFilter{config: config, Path: pathRegexp}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type HTTPResponseEncode struct {
|
||||
config ProcessorConfig
|
||||
}
|
||||
|
||||
func (hre *HTTPResponseEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadResponse, ok := payload.(*http.Response)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.response.encode processor only accepts an http.Response")
|
||||
}
|
||||
defer payloadResponse.Body.Close()
|
||||
|
||||
bytes, err := io.ReadAll(payloadResponse.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return bytes, nil
|
||||
}
|
||||
|
||||
func (hre *HTTPResponseEncode) Type() string {
|
||||
return hre.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.response.encode",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
return &HTTPResponseEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type MQTTMessage struct {
|
||||
Topic string
|
||||
QoS byte
|
||||
Payload any
|
||||
Retained bool
|
||||
}
|
||||
|
||||
type MQTTMessageCreate struct {
|
||||
config ProcessorConfig
|
||||
Topic string
|
||||
QoS byte
|
||||
Retained bool
|
||||
Payload any
|
||||
}
|
||||
|
||||
func (mmc *MQTTMessageCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
message := MQTTMessage{
|
||||
Topic: mmc.Topic,
|
||||
QoS: mmc.QoS,
|
||||
Retained: mmc.Retained,
|
||||
Payload: mmc.Payload,
|
||||
}
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (mmc *MQTTMessageCreate) Type() string {
|
||||
return mmc.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "mqtt.message.create",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
topic, ok := params["topic"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("mqtt.message.create requires an topic parameter")
|
||||
}
|
||||
|
||||
topicString, ok := topic.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("mqtt.message.create topic must be a string")
|
||||
}
|
||||
|
||||
qos, ok := params["qos"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("mqtt.message.create requires an qos parameter")
|
||||
}
|
||||
|
||||
qosByte, ok := qos.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("mqtt.message.create qos must be a number")
|
||||
}
|
||||
|
||||
retained, ok := params["retained"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("mqtt.message.create requires an retained parameter")
|
||||
}
|
||||
|
||||
retainedBool, ok := retained.(bool)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("mqtt.message.create retained must be a boolean")
|
||||
}
|
||||
|
||||
//TODO(jwetzell): convert payload into []byte or string for sending
|
||||
payload, ok := params["payload"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("mqtt.message.create requires an payload parameter")
|
||||
}
|
||||
|
||||
return &MQTTMessageCreate{config: config, Topic: topicString, QoS: byte(qosByte), Retained: retainedBool, Payload: payload}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
osc "github.com/jwetzell/osc-go"
|
||||
)
|
||||
|
||||
type OSCMessageDecode struct {
|
||||
config ProcessorConfig
|
||||
}
|
||||
|
||||
func (o *OSCMessageDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("osc.message.decode processor only accepts a []byte payload")
|
||||
}
|
||||
|
||||
if len(payloadBytes) == 0 {
|
||||
return nil, fmt.Errorf("osc.message.decode processor can't work on empty []byte")
|
||||
}
|
||||
|
||||
if payloadBytes[0] != '/' {
|
||||
return nil, fmt.Errorf("osc.message.decode processor needs an OSC looking []byte")
|
||||
}
|
||||
|
||||
message, err := osc.MessageFromBytes(payloadBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (o *OSCMessageDecode) Type() string {
|
||||
return o.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "osc.message.decode",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
return &OSCMessageDecode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
osc "github.com/jwetzell/osc-go"
|
||||
)
|
||||
|
||||
type OSCMessageEncode struct {
|
||||
config ProcessorConfig
|
||||
}
|
||||
|
||||
func (o *OSCMessageEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMessage, ok := payload.(osc.OSCMessage)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("osc.message.encode processor only accepts an OSCMessage")
|
||||
}
|
||||
|
||||
bytes := payloadMessage.ToBytes()
|
||||
return bytes, nil
|
||||
}
|
||||
|
||||
func (o *OSCMessageEncode) Type() string {
|
||||
return o.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "osc.message.encode",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
return &OSCMessageEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/jwetzell/osc-go"
|
||||
)
|
||||
|
||||
type OSCMessageFilter struct {
|
||||
config ProcessorConfig
|
||||
Address *regexp.Regexp
|
||||
}
|
||||
|
||||
func (o *OSCMessageFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
payloadMessage, ok := payload.(osc.OSCMessage)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("osc.message.filter can only operate on OSCMessage payloads")
|
||||
}
|
||||
|
||||
if !o.Address.MatchString(payloadMessage.Address) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadMessage, nil
|
||||
}
|
||||
|
||||
func (o *OSCMessageFilter) Type() string {
|
||||
return o.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "osc.message.filter",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
address, ok := params["address"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("osc.message.filter requires an address parameter")
|
||||
}
|
||||
|
||||
addressString, ok := address.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("osc.message.filter address must be a string")
|
||||
}
|
||||
|
||||
addressPattern := strings.ReplaceAll(addressString, "?", ".")
|
||||
addressPattern = strings.ReplaceAll(addressPattern, "*", "[^/]*")
|
||||
addressPattern = strings.ReplaceAll(addressPattern, "[!", "[^")
|
||||
addressPattern = strings.ReplaceAll(addressPattern, "{", "(")
|
||||
addressPattern = strings.ReplaceAll(addressPattern, "}", ")")
|
||||
addressPattern = strings.ReplaceAll(addressPattern, ",", "|")
|
||||
|
||||
addressPatternRegexp, err := regexp.Compile(fmt.Sprintf("^%s$", addressPattern))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &OSCMessageFilter{config: config, Address: addressPatternRegexp}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"text/template"
|
||||
|
||||
osc "github.com/jwetzell/osc-go"
|
||||
)
|
||||
|
||||
type OSCMessageTransform struct {
|
||||
config ProcessorConfig
|
||||
Address *template.Template
|
||||
}
|
||||
|
||||
func (o *OSCMessageTransform) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMessage, ok := payload.(osc.OSCMessage)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("osc.message.transform processor only accepts an OSCMessage")
|
||||
}
|
||||
|
||||
var addressBuffer bytes.Buffer
|
||||
//TODO(jwetzell): actually inject data into template
|
||||
err := o.Address.Execute(&addressBuffer, payloadMessage)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
addressString := addressBuffer.String()
|
||||
|
||||
if len(addressString) == 0 {
|
||||
return nil, fmt.Errorf("osc.message.transform address must not be empty")
|
||||
}
|
||||
|
||||
if addressString[0] != '/' {
|
||||
return nil, fmt.Errorf("osc.message.transform address must start with '/'")
|
||||
}
|
||||
|
||||
payloadMessage.Address = addressString
|
||||
|
||||
return payloadMessage, nil
|
||||
}
|
||||
|
||||
func (o *OSCMessageTransform) Type() string {
|
||||
return o.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "osc.message.transform",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
address, ok := params["address"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("osc.message.transform requires an address parameter")
|
||||
}
|
||||
|
||||
addressString, ok := address.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("osc.message.transform address must be a string")
|
||||
}
|
||||
|
||||
addressTemplate, err := template.New("address").Parse(addressString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &OSCMessageTransform{config: config, Address: addressTemplate}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Processor interface {
|
||||
Type() string
|
||||
Process(context.Context, any) (any, error)
|
||||
}
|
||||
|
||||
type ProcessorConfig struct {
|
||||
Type string `json:"type"`
|
||||
Params map[string]any `json:"params"`
|
||||
}
|
||||
|
||||
type ProcessorRegistration struct {
|
||||
Type string `json:"type"`
|
||||
New func(ProcessorConfig) (Processor, error)
|
||||
}
|
||||
|
||||
func RegisterProcessor(processor ProcessorRegistration) {
|
||||
|
||||
if processor.Type == "" {
|
||||
panic("processor type is missing")
|
||||
}
|
||||
if processor.New == nil {
|
||||
panic("missing ProcessorRegistration.New")
|
||||
}
|
||||
|
||||
processorRegistryMu.Lock()
|
||||
defer processorRegistryMu.Unlock()
|
||||
|
||||
if _, ok := ProcessorRegistry[string(processor.Type)]; ok {
|
||||
panic(fmt.Sprintf("processor already registered: %s", processor.Type))
|
||||
}
|
||||
ProcessorRegistry[string(processor.Type)] = processor
|
||||
}
|
||||
|
||||
var (
|
||||
processorRegistryMu sync.RWMutex
|
||||
ProcessorRegistry = make(map[string]ProcessorRegistration)
|
||||
)
|
||||
@@ -1,41 +0,0 @@
|
||||
package processing_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/processing"
|
||||
)
|
||||
|
||||
func TestGoodStringDecode(t *testing.T) {
|
||||
stringDecoder := processing.StringDecode{}
|
||||
tests := []struct {
|
||||
processor processing.Processor
|
||||
name string
|
||||
payload any
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
processor: &stringDecoder,
|
||||
name: "hello",
|
||||
payload: []byte{0x68, 0x65, 0x6c, 0x6c, 0x6f},
|
||||
expected: "hello",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := test.processor.Process(t.Context(), test.payload)
|
||||
|
||||
gotString, ok := got.(string)
|
||||
if !ok {
|
||||
t.Errorf("string.decode returned a %T payload: %s", got, got)
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("string.decode failed: %s", err)
|
||||
}
|
||||
if gotString != test.expected {
|
||||
t.Errorf("string.decode got %s, expected %s", got, test.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type StringFilter struct {
|
||||
config ProcessorConfig
|
||||
Pattern *regexp.Regexp
|
||||
}
|
||||
|
||||
func (se *StringFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := payload.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("string.filter processor only accepts a string")
|
||||
}
|
||||
|
||||
if !se.Pattern.MatchString(payloadString) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadString, nil
|
||||
}
|
||||
|
||||
func (se *StringFilter) Type() string {
|
||||
return se.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "string.filter",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
pattern, ok := params["pattern"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.filter requires an pattern parameter")
|
||||
}
|
||||
|
||||
patternString, ok := pattern.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("http.request.filter pattern must be a string")
|
||||
}
|
||||
|
||||
patternRegexp, err := regexp.Compile(fmt.Sprintf("^%s$", patternString))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &StringFilter{config: config, Pattern: patternRegexp}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type StringSplit struct {
|
||||
config ProcessorConfig
|
||||
Separator string
|
||||
}
|
||||
|
||||
func (se *StringSplit) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := payload.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("string.split only accepts a string")
|
||||
}
|
||||
|
||||
payloadParts := strings.Split(payloadString, se.Separator)
|
||||
|
||||
return payloadParts, nil
|
||||
}
|
||||
|
||||
func (se *StringSplit) Type() string {
|
||||
return se.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "string.split",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
separator, ok := params["separator"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("string.split requires a separator")
|
||||
}
|
||||
|
||||
separatorString, ok := separator.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("string.split separator must be a string")
|
||||
}
|
||||
|
||||
return &StringSplit{config: config, Separator: separatorString}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
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 := GetAnyAs[[]byte](payload)
|
||||
|
||||
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 := GetAnyAs[artnet.ArtNetPacket](payload)
|
||||
|
||||
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
|
||||
},
|
||||
})
|
||||
}
|
||||
34
internal/processor/debug-log.go
Normal file
34
internal/processor/debug-log.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type DebugLog struct {
|
||||
config config.ProcessorConfig
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func (dl *DebugLog) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString := fmt.Sprintf("%+v", payload)
|
||||
payloadType := fmt.Sprintf("%T", payload)
|
||||
dl.logger.Debug("", "payload", payloadString, "payloadType", payloadType)
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (dl *DebugLog) Type() string {
|
||||
return dl.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "debug.log",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &DebugLog{config: config, logger: slog.Default().With("component", "processor", "type", config.Type)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
61
internal/processor/filter-expr.go
Normal file
61
internal/processor/filter-expr.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/expr-lang/expr"
|
||||
"github.com/expr-lang/expr/vm"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
// NOTE(jwetzell): see language definition https://expr-lang.org/docs/language-definition
|
||||
type FilterExpr struct {
|
||||
config config.ProcessorConfig
|
||||
Program *vm.Program
|
||||
}
|
||||
|
||||
func (fe *FilterExpr) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
exprEnv := GetEnvData(ctx, payload)
|
||||
|
||||
output, err := expr.Run(fe.Program, exprEnv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputBool, ok := output.(bool)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("filter.expr expression did not return a boolean")
|
||||
}
|
||||
if !outputBool {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (fe *FilterExpr) Type() string {
|
||||
return fe.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "filter.expr",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
expressionString, err := params.GetString("expression")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("filter.expr expression error: %w", err)
|
||||
}
|
||||
|
||||
program, err := expr.Compile(expressionString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &FilterExpr{config: config, Program: program}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
52
internal/processor/float-parse.go
Normal file
52
internal/processor/float-parse.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type FloatParse struct {
|
||||
BitSize int
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fp *FloatParse) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("float.parse processor only accepts a string")
|
||||
}
|
||||
|
||||
payloadFloat, err := strconv.ParseFloat(payloadString, fp.BitSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return payloadFloat, nil
|
||||
}
|
||||
|
||||
func (fp *FloatParse) Type() string {
|
||||
return fp.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "float.parse",
|
||||
New: func(moduleConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := moduleConfig.Params
|
||||
|
||||
bitSizeNum, err := params.GetInt("bitSize")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
bitSizeNum = 64
|
||||
} else {
|
||||
return nil, fmt.Errorf("float.parse bitSize error: %w", err)
|
||||
}
|
||||
}
|
||||
return &FloatParse{config: moduleConfig, BitSize: bitSizeNum}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
71
internal/processor/float-random.go
Normal file
71
internal/processor/float-random.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type FloatRandom struct {
|
||||
BitSize int
|
||||
Min float64
|
||||
Max float64
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fr *FloatRandom) Process(ctx context.Context, payload any) (any, error) {
|
||||
if fr.BitSize == 32 {
|
||||
payloadFloat := rand.Float32()*(float32(fr.Max)-float32(fr.Min)) + float32(fr.Min)
|
||||
return payloadFloat, nil
|
||||
}
|
||||
if fr.BitSize == 64 {
|
||||
payloadFloat := rand.Float64()*(fr.Max-fr.Min) + fr.Min
|
||||
return payloadFloat, nil
|
||||
}
|
||||
return nil, errors.New("float.random bitSize error: must be 32 or 64")
|
||||
}
|
||||
|
||||
func (fr *FloatRandom) Type() string {
|
||||
return fr.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "float.random",
|
||||
New: func(processorConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := processorConfig.Params
|
||||
|
||||
bitSizeInt, err := params.GetInt("bitSize")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
bitSizeInt = 32
|
||||
} else {
|
||||
return nil, fmt.Errorf("float.random bitSize error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if bitSizeInt != 32 && bitSizeInt != 64 {
|
||||
return nil, errors.New("float.random bitSize error: must be 32 or 64")
|
||||
}
|
||||
|
||||
minFloat, err := params.GetFloat64("min")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("float.random min error: %w", err)
|
||||
}
|
||||
|
||||
maxFloat, err := params.GetFloat64("max")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("float.random max error: %w", err)
|
||||
}
|
||||
|
||||
if maxFloat < minFloat {
|
||||
return nil, errors.New("float.random max must be greater than min")
|
||||
}
|
||||
|
||||
return &FloatRandom{config: processorConfig, Min: minFloat, Max: maxFloat, BitSize: bitSizeInt}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package processing
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -8,10 +8,11 @@ import (
|
||||
"text/template"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type FreeDCreate struct {
|
||||
config ProcessorConfig
|
||||
config config.ProcessorConfig
|
||||
Id *template.Template
|
||||
Pan *template.Template
|
||||
Tilt *template.Template
|
||||
@@ -25,8 +26,10 @@ type FreeDCreate struct {
|
||||
|
||||
func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var idBuffer bytes.Buffer
|
||||
err := fc.Id.Execute(&idBuffer, payload)
|
||||
err := fc.Id.Execute(&idBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -41,7 +44,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var panBuffer bytes.Buffer
|
||||
err = fc.Pan.Execute(&panBuffer, payload)
|
||||
err = fc.Pan.Execute(&panBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -51,8 +54,12 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
panNum, err := strconv.ParseFloat(panString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var tiltBuffer bytes.Buffer
|
||||
err = fc.Tilt.Execute(&tiltBuffer, payload)
|
||||
err = fc.Tilt.Execute(&tiltBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -62,8 +69,12 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
tiltNum, err := strconv.ParseFloat(tiltString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var rollBuffer bytes.Buffer
|
||||
err = fc.Tilt.Execute(&rollBuffer, payload)
|
||||
err = fc.Tilt.Execute(&rollBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -77,12 +88,8 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var posXBuffer bytes.Buffer
|
||||
err = fc.PosX.Execute(&posXBuffer, payload)
|
||||
err = fc.PosX.Execute(&posXBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -97,7 +104,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var posYBuffer bytes.Buffer
|
||||
err = fc.PosY.Execute(&posYBuffer, payload)
|
||||
err = fc.PosY.Execute(&posYBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -112,7 +119,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var posZBuffer bytes.Buffer
|
||||
err = fc.PosZ.Execute(&posZBuffer, payload)
|
||||
err = fc.PosZ.Execute(&posZBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -127,7 +134,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var zoomBuffer bytes.Buffer
|
||||
err = fc.Zoom.Execute(&zoomBuffer, payload)
|
||||
err = fc.Zoom.Execute(&zoomBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -142,7 +149,7 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
}
|
||||
|
||||
var focusBuffer bytes.Buffer
|
||||
err = fc.Zoom.Execute(&focusBuffer, payload)
|
||||
err = fc.Focus.Execute(&focusBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -178,20 +185,13 @@ func (fc *FreeDCreate) Type() string {
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "freed.create",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
// TODO(jwetzell): make some params optional
|
||||
params := config.Params
|
||||
id, ok := params["id"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create requires an id parameter")
|
||||
}
|
||||
|
||||
idString, ok := id.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create id must be a string")
|
||||
idString, err := params.GetString("id")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create id error: %w", err)
|
||||
}
|
||||
|
||||
idTemplate, err := template.New("id").Parse(idString)
|
||||
@@ -200,44 +200,23 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pan, ok := params["pan"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create requires an pan parameter")
|
||||
}
|
||||
|
||||
panString, ok := pan.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create pan must be a string")
|
||||
panString, err := params.GetString("pan")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create pan error: %w", err)
|
||||
}
|
||||
|
||||
panTemplate, err := template.New("pan").Parse(panString)
|
||||
|
||||
tilt, ok := params["tilt"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create requires an tilt parameter")
|
||||
}
|
||||
|
||||
tiltString, ok := tilt.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create tilt must be a string")
|
||||
tiltString, err := params.GetString("tilt")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create tilt error: %w", err)
|
||||
}
|
||||
|
||||
tiltTemplate, err := template.New("tilt").Parse(tiltString)
|
||||
|
||||
roll, ok := params["roll"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create requires an roll parameter")
|
||||
}
|
||||
|
||||
rollString, ok := roll.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create roll must be a string")
|
||||
rollString, err := params.GetString("roll")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create roll error: %w", err)
|
||||
}
|
||||
|
||||
rollTemplate, err := template.New("roll").Parse(rollString)
|
||||
@@ -246,16 +225,9 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
posX, ok := params["posX"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create requires a posX parameter")
|
||||
}
|
||||
|
||||
posXString, ok := posX.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create posX must be a string")
|
||||
posXString, err := params.GetString("posX")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create posX error: %w", err)
|
||||
}
|
||||
|
||||
posXTemplate, err := template.New("posX").Parse(posXString)
|
||||
@@ -264,16 +236,9 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
posY, ok := params["posY"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create requires a posY parameter")
|
||||
}
|
||||
|
||||
posYString, ok := posY.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create posY must be a string")
|
||||
posYString, err := params.GetString("posY")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create posY error: %w", err)
|
||||
}
|
||||
|
||||
posYTemplate, err := template.New("posY").Parse(posYString)
|
||||
@@ -282,16 +247,9 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
posZ, ok := params["posZ"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create requires a posZ parameter")
|
||||
}
|
||||
|
||||
posZString, ok := posZ.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create posZ must be a string")
|
||||
posZString, err := params.GetString("posZ")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create posZ error: %w", err)
|
||||
}
|
||||
|
||||
posZTemplate, err := template.New("posZ").Parse(posZString)
|
||||
@@ -300,30 +258,16 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
zoom, ok := params["zoom"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create requires an zoom parameter")
|
||||
}
|
||||
|
||||
zoomString, ok := zoom.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create zoom must be a string")
|
||||
zoomString, err := params.GetString("zoom")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create zoom error: %w", err)
|
||||
}
|
||||
|
||||
zoomTemplate, err := template.New("zoom").Parse(zoomString)
|
||||
|
||||
focus, ok := params["focus"]
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create requires an focus parameter")
|
||||
}
|
||||
|
||||
focusString, ok := focus.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("freed.create focus must be a string")
|
||||
focusString, err := params.GetString("focus")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create focus error: %w", err)
|
||||
}
|
||||
|
||||
focusTemplate, err := template.New("focus").Parse(focusString)
|
||||
40
internal/processor/free-d-decode.go
Normal file
40
internal/processor/free-d-decode.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type FreeDDecode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fd *FreeDDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.decode processor only accepts a []byte")
|
||||
}
|
||||
|
||||
payloadMessage, err := freeD.Decode(payloadBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return payloadMessage, nil
|
||||
}
|
||||
|
||||
func (fd *FreeDDecode) Type() string {
|
||||
return fd.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "freed.decode",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &FreeDDecode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
37
internal/processor/free-d-encode.go
Normal file
37
internal/processor/free-d-encode.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type FreeDEncode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fe *FreeDEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPosition, ok := GetAnyAs[freeD.FreeDPosition](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.decode processor only accepts a FreeDEncode")
|
||||
}
|
||||
|
||||
payloadBytes := freeD.Encode(payloadPosition)
|
||||
return payloadBytes, nil
|
||||
}
|
||||
|
||||
func (fe *FreeDEncode) Type() string {
|
||||
return fe.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "freed.encode",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &FreeDEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
93
internal/processor/http-request-do.go
Normal file
93
internal/processor/http-request-do.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPRequestDo struct {
|
||||
config config.ProcessorConfig
|
||||
client *http.Client
|
||||
Method string
|
||||
URL *template.Template
|
||||
}
|
||||
|
||||
func (hrd *HTTPRequestDo) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var urlBuffer bytes.Buffer
|
||||
err := hrd.URL.Execute(&urlBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
urlString := urlBuffer.String()
|
||||
|
||||
//TODO(jwetzell): support body
|
||||
request, err := http.NewRequest(hrd.Method, urlString, bytes.NewBuffer([]byte{}))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
response, err := hrd.client.Do(request)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(response.Body)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//TODO(jwetzell): support headers, etc
|
||||
return HTTPResponse{
|
||||
Status: response.StatusCode,
|
||||
Body: body,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (hrd *HTTPRequestDo) Type() string {
|
||||
return hrd.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.do",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
methodString, err := params.GetString("method")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.request.do method error: %w", err)
|
||||
}
|
||||
|
||||
urlString, err := params.GetString("url")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.request.do url error: %w", err)
|
||||
}
|
||||
|
||||
urlTemplate, err := template.New("url").Parse(urlString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
return &HTTPRequestDo{config: config, URL: urlTemplate, Method: methodString, client: client}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
69
internal/processor/http-response-create.go
Normal file
69
internal/processor/http-response-create.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"text/template"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPResponseCreate struct {
|
||||
Status int
|
||||
BodyTmpl *template.Template
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
type HTTPResponse struct {
|
||||
Status int
|
||||
Body []byte
|
||||
}
|
||||
|
||||
func (hrc *HTTPResponseCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var bodyBuffer bytes.Buffer
|
||||
err := hrc.BodyTmpl.Execute(&bodyBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return HTTPResponse{
|
||||
Status: hrc.Status,
|
||||
Body: bodyBuffer.Bytes(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (hrc *HTTPResponseCreate) Type() string {
|
||||
return hrc.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.response.create",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
statusNum, err := params.GetInt("status")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.response.create status error: %w", err)
|
||||
}
|
||||
|
||||
bodyTemplateString, err := params.GetString("bodyTemplate")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.response.create bodyTemplate error: %w", err)
|
||||
}
|
||||
|
||||
bodyTemplate, err := template.New("body").Parse(bodyTemplateString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// TODO(jwetzell): support other body kind (direct bytes from input, from file?)
|
||||
return &HTTPResponseCreate{config: config, Status: int(statusNum), BodyTmpl: bodyTemplate}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
62
internal/processor/int-parse.go
Normal file
62
internal/processor/int-parse.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type IntParse struct {
|
||||
Base int
|
||||
BitSize int
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (ip *IntParse) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("int.parse processor only accepts a string")
|
||||
}
|
||||
|
||||
payloadInt, err := strconv.ParseInt(payloadString, ip.Base, ip.BitSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return payloadInt, nil
|
||||
}
|
||||
|
||||
func (ip *IntParse) Type() string {
|
||||
return ip.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "int.parse",
|
||||
New: func(moduleConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := moduleConfig.Params
|
||||
|
||||
baseNum, err := params.GetInt("base")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
baseNum = 10
|
||||
} else {
|
||||
return nil, fmt.Errorf("int.parse base error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
bitSizeNum, err := params.GetInt("bitSize")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
bitSizeNum = 64
|
||||
} else {
|
||||
return nil, fmt.Errorf("int.parse bitSize error: %w", err)
|
||||
}
|
||||
}
|
||||
return &IntParse{config: moduleConfig, Base: baseNum, BitSize: bitSizeNum}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
50
internal/processor/int-random.go
Normal file
50
internal/processor/int-random.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type IntRandom struct {
|
||||
Min int
|
||||
Max int
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (ir *IntRandom) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadInt := rand.IntN(ir.Max-ir.Min+1) + ir.Min
|
||||
return payloadInt, nil
|
||||
}
|
||||
|
||||
func (ir *IntRandom) Type() string {
|
||||
return ir.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "int.random",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
minInt, err := params.GetInt("min")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("int.random min error: %w", err)
|
||||
}
|
||||
|
||||
maxInt, err := params.GetInt("max")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("int.random max error: %w", err)
|
||||
}
|
||||
|
||||
if maxInt < minInt {
|
||||
return nil, errors.New("int.random max must be greater than min")
|
||||
}
|
||||
|
||||
return &IntRandom{config: config, Min: int(minInt), Max: int(maxInt)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
49
internal/processor/json-decode.go
Normal file
49
internal/processor/json-decode.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type JsonDecode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (jd *JsonDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
payloadBytes, ok := GetAnyAsByteSlice(payload)
|
||||
|
||||
if !ok {
|
||||
payloadString, ok := GetAnyAs[string](payload)
|
||||
if !ok {
|
||||
return nil, errors.New("json.decode can only process a string or []byte")
|
||||
}
|
||||
payloadBytes = []byte(payloadString)
|
||||
}
|
||||
|
||||
payloadJson := make(map[string]any)
|
||||
|
||||
err := json.Unmarshal(payloadBytes, &payloadJson)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return payloadJson, nil
|
||||
|
||||
}
|
||||
|
||||
func (jd *JsonDecode) Type() string {
|
||||
return jd.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "json.decode",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &JsonDecode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
42
internal/processor/json-encode.go
Normal file
42
internal/processor/json-encode.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type JsonEncode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (je *JsonEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
var payloadBuffer bytes.Buffer
|
||||
|
||||
err := json.NewEncoder(&payloadBuffer).Encode(payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
payloadBytes := payloadBuffer.Bytes()
|
||||
|
||||
payloadBytes = payloadBytes[0 : len(payloadBytes)-1]
|
||||
|
||||
return payloadBytes, nil
|
||||
}
|
||||
|
||||
func (je *JsonEncode) Type() string {
|
||||
return je.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "json.encode",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &JsonEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
324
internal/processor/midi-message-create.go
Normal file
324
internal/processor/midi-message-create.go
Normal file
@@ -0,0 +1,324 @@
|
||||
//go:build cgo
|
||||
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"text/template"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
)
|
||||
|
||||
// TODO(jwetzell): support using numbers in config file treated as hardcoded values
|
||||
type MIDIMessageCreate struct {
|
||||
config config.ProcessorConfig
|
||||
ProcessFunc func(ctx context.Context, payload any) (any, error)
|
||||
}
|
||||
|
||||
func (mmc *MIDIMessageCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
return mmc.ProcessFunc(ctx, payload)
|
||||
}
|
||||
|
||||
func (mmc *MIDIMessageCreate) Type() string {
|
||||
return mmc.config.Type
|
||||
}
|
||||
|
||||
func newMidiNoteOnCreate(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
params := config.Params
|
||||
|
||||
channelString, err := params.GetString("channel")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create channel error: %w", err)
|
||||
}
|
||||
|
||||
channelTemplate, err := template.New("channel").Parse(channelString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
noteString, err := params.GetString("note")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create note error: %w", err)
|
||||
}
|
||||
|
||||
noteTemplate, err := template.New("note").Parse(noteString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
velocityString, err := params.GetString("velocity")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create velocity error: %w", err)
|
||||
}
|
||||
|
||||
velocityTemplate, err := template.New("velocity").Parse(velocityString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &MIDIMessageCreate{config: config, ProcessFunc: func(ctx context.Context, payload any) (any, error) {
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var channelBuffer bytes.Buffer
|
||||
err := channelTemplate.Execute(&channelBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
channelValue, err := strconv.ParseUint(channelBuffer.String(), 10, 8)
|
||||
|
||||
var noteBuffer bytes.Buffer
|
||||
err = noteTemplate.Execute(¬eBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
noteValue, err := strconv.ParseUint(noteBuffer.String(), 10, 8)
|
||||
|
||||
var velocityBuffer bytes.Buffer
|
||||
err = velocityTemplate.Execute(&velocityBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
velocityValue, err := strconv.ParseUint(velocityBuffer.String(), 10, 8)
|
||||
payloadMessage := midi.NoteOn(uint8(channelValue), uint8(noteValue), uint8(velocityValue))
|
||||
return payloadMessage, nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func newMidiNoteOffCreate(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
params := config.Params
|
||||
|
||||
channelString, err := params.GetString("channel")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create channel error: %w", err)
|
||||
}
|
||||
|
||||
channelTemplate, err := template.New("channel").Parse(channelString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
noteString, err := params.GetString("note")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create note error: %w", err)
|
||||
}
|
||||
|
||||
noteTemplate, err := template.New("note").Parse(noteString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
velocityString, err := params.GetString("velocity")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create velocity error: %w", err)
|
||||
}
|
||||
|
||||
velocityTemplate, err := template.New("velocity").Parse(velocityString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &MIDIMessageCreate{config: config, ProcessFunc: func(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var channelBuffer bytes.Buffer
|
||||
err := channelTemplate.Execute(&channelBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
channelValue, err := strconv.ParseUint(channelBuffer.String(), 10, 8)
|
||||
|
||||
var noteBuffer bytes.Buffer
|
||||
err = noteTemplate.Execute(¬eBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
noteValue, err := strconv.ParseUint(noteBuffer.String(), 10, 8)
|
||||
|
||||
var velocityBuffer bytes.Buffer
|
||||
err = velocityTemplate.Execute(&velocityBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
velocityValue, err := strconv.ParseUint(velocityBuffer.String(), 10, 8)
|
||||
|
||||
payloadMessage := midi.NoteOffVelocity(uint8(channelValue), uint8(noteValue), uint8(velocityValue))
|
||||
return payloadMessage, nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func newMidiControlChangeCreate(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
params := config.Params
|
||||
|
||||
channelString, err := params.GetString("channel")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create channel error: %w", err)
|
||||
}
|
||||
|
||||
channelTemplate, err := template.New("channel").Parse(channelString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
controlString, err := params.GetString("control")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create control error: %w", err)
|
||||
}
|
||||
|
||||
controlTemplate, err := template.New("control").Parse(controlString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
valueString, err := params.GetString("value")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create value error: %w", err)
|
||||
}
|
||||
|
||||
valueTemplate, err := template.New("value").Parse(valueString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &MIDIMessageCreate{config: config, ProcessFunc: func(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var channelBuffer bytes.Buffer
|
||||
err := channelTemplate.Execute(&channelBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
channelValue, err := strconv.ParseUint(channelBuffer.String(), 10, 8)
|
||||
|
||||
var controlBuffer bytes.Buffer
|
||||
err = controlTemplate.Execute(&controlBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
controlValue, err := strconv.ParseUint(controlBuffer.String(), 10, 8)
|
||||
|
||||
var valueBuffer bytes.Buffer
|
||||
err = valueTemplate.Execute(&valueBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
valueValue, err := strconv.ParseUint(valueBuffer.String(), 10, 8)
|
||||
|
||||
payloadMessage := midi.ControlChange(uint8(channelValue), uint8(controlValue), uint8(valueValue))
|
||||
return payloadMessage, nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func newMidiProgramChangeCreate(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
params := config.Params
|
||||
|
||||
channelString, err := params.GetString("channel")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create channel error: %w", err)
|
||||
}
|
||||
|
||||
channelTemplate, err := template.New("channel").Parse(channelString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
programString, err := params.GetString("program")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create program error: %w", err)
|
||||
}
|
||||
|
||||
programTemplate, err := template.New("program").Parse(programString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &MIDIMessageCreate{config: config, ProcessFunc: func(ctx context.Context, payload any) (any, error) {
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var channelBuffer bytes.Buffer
|
||||
err := channelTemplate.Execute(&channelBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
channelValue, err := strconv.ParseUint(channelBuffer.String(), 10, 8)
|
||||
|
||||
var programBuffer bytes.Buffer
|
||||
err = programTemplate.Execute(&programBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
programValue, err := strconv.ParseUint(programBuffer.String(), 10, 8)
|
||||
|
||||
payloadMessage := midi.ProgramChange(uint8(channelValue), uint8(programValue))
|
||||
return payloadMessage, nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "midi.message.create",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
msgTypeString, err := params.GetString("type")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.message.create type error: %w", err)
|
||||
}
|
||||
|
||||
switch msgTypeString {
|
||||
case "NoteOn", "noteon", "note_on":
|
||||
return newMidiNoteOnCreate(config)
|
||||
case "NoteOff", "noteoff", "note_off":
|
||||
return newMidiNoteOffCreate(config)
|
||||
case "ControlChange", "controlchange", "control_change":
|
||||
return newMidiControlChangeCreate(config)
|
||||
case "ProgramChange", "programchange", "program_change":
|
||||
return newMidiProgramChangeCreate(config)
|
||||
default:
|
||||
return nil, fmt.Errorf("midi.message.create does not support type %s", msgTypeString)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,23 +1,24 @@
|
||||
//go:build cgo
|
||||
|
||||
package processing
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
)
|
||||
|
||||
type MIDIMessageDecode struct {
|
||||
config ProcessorConfig
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (mmd *MIDIMessageDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("midi.message.decode processor only accepts a []byte")
|
||||
return nil, errors.New("midi.message.decode processor only accepts a []byte")
|
||||
}
|
||||
|
||||
payloadMessage := midi.Message(payloadBytes)
|
||||
@@ -32,7 +33,7 @@ func (mmd *MIDIMessageDecode) Type() string {
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "midi.message.decode",
|
||||
New: func(config ProcessorConfig) (Processor, error) {
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &MIDIMessageDecode{config: config}, nil
|
||||
},
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user