Compare commits

...

26 Commits
v0.2.0 ... main

Author SHA1 Message Date
github-actions[bot]
6965b03ae5 chore: auto-update Go modules 2025-04-07 00:03:31 +00:00
09e4b107bf -log-level flag now -loglevel
Some checks failed
CI / Lint (push) Has been cancelled
Auto-Update Go Modules / update-go-modules (push) Has been cancelled
upd README, CHANGELOG
2025-04-05 22:15:29 +01:00
c7b9d75ea1 reword
Some checks failed
CI / Lint (push) Has been cancelled
2025-04-04 05:50:32 +01:00
cc42e928e0 upd tested against 2025-04-04 05:45:24 +01:00
80a675cc6a add/fix dates 2025-04-04 05:39:45 +01:00
6801d9e4e1 upd CHANGELOG 2025-04-04 05:38:46 +01:00
8aceb8229f wsl2 network mirroring now supports localhost. 2025-04-04 05:27:56 +01:00
b070fb615e log-level is now a str flag
add some validation logic

update Logging section in README

bps now defaults to 256000 (same as the vban-text-client)
see: https://github.com/vburel2018/VBAN-Text-Client
2025-04-04 05:27:26 +01:00
b9d0578507 prefer UserConfigDir
Some checks failed
CI / Lint (push) Has been cancelled
2025-03-31 20:57:47 +01:00
github-actions[bot]
438543b87b chore: auto-update Go modules
Some checks failed
Auto-Update Go Modules / update-go-modules (push) Has been cancelled
2025-03-24 00:03:34 +00:00
585b4d4c14 add golang-ci config + action
Some checks failed
CI / Lint (push) Has been cancelled
Auto-Update Go Modules / update-go-modules (push) Has been cancelled
2025-03-10 15:32:25 +00:00
29e6c2e8aa lint fixes 2025-03-10 15:32:10 +00:00
github-actions[bot]
7d93ecb1c7 chore: auto-update Go modules 2025-03-10 00:02:49 +00:00
github-actions[bot]
116ce30f53 chore: auto-update Go modules
Some checks failed
Auto-Update Go Modules / update-go-modules (push) Has been cancelled
2025-02-24 00:03:24 +00:00
4bb79c8500 add update and release actions
Some checks failed
Auto-Update Go Modules / update-go-modules (push) Has been cancelled
2025-02-17 13:13:44 +00:00
db497a017b run through formatter 2025-02-07 23:15:05 +00:00
3afc5ee66c add taskfile 2025-02-03 18:34:22 +00:00
99b630dd47 upd readme 2025-01-23 17:30:45 +00:00
8bd62b72d0 remove cat 2025-01-23 02:56:42 +00:00
e36af2c059 add 0.2.1 to changelog 2024-11-07 19:39:03 +00:00
5a5a6fa893 fix pointer 2024-11-07 19:36:56 +00:00
be11239d39 header now uses reusable buffer 2024-11-07 19:34:44 +00:00
d72c6a2d17 rename client struct to udpConn 2024-11-05 18:35:39 +00:00
c063feb919 fix default config.toml dir in README 2024-11-04 14:37:32 +00:00
ae170ca572 move indexOf into the vbantxt package.
improve the warning message on invalid bps value
2024-11-03 16:15:05 +00:00
7a844e3624 add note about functional options to README 2024-11-03 15:54:34 +00:00
24 changed files with 493 additions and 156 deletions

29
.github/workflows/golang-ci.yml vendored Normal file
View File

@ -0,0 +1,29 @@
name: CI
on:
push:
branches: [ "main" ]
paths:
- '**.go'
pull_request:
branches: [ "main" ]
paths:
- '**.go'
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
timeout-minutes: 3
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: Install golangci-lint
run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
- name: Run golangci-lint
run: golangci-lint run ./...

31
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,31 @@
name: goreleaser
on:
push:
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
permissions:
contents: write
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
-
name: Set up Go
uses: actions/setup-go@v5
-
name: Run GoReleaser
uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: '~> v2'
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

30
.github/workflows/update-go-modules.yml vendored Normal file
View File

@ -0,0 +1,30 @@
name: Auto-Update Go Modules
on:
schedule:
- cron: "0 0 * * 1" # Runs every Monday at midnight
jobs:
update-go-modules:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: stable
- name: Update Dependencies
run: |
go get -u ./...
go mod tidy
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add go.mod go.sum
git commit -m "chore: auto-update Go modules"
git push

3
.gitignore vendored
View File

@ -14,3 +14,6 @@ bin/
# Dependency directories (remove the comment below to include it)
# vendor/
# Added by goreleaser init:
dist/

54
.golangci.yml Normal file
View File

@ -0,0 +1,54 @@
run:
# timeout for analysis, e.g. 30s, 3m, default is 1m
timeout: 3m
# exclude test files
tests: true
linters:
# Set to true runs only fast linters.
# Good option for 'lint on save', pre-commit hook or CI.
fast: true
disable-all: true
enable:
- gosimple
- govet
- ineffassign
- staticcheck
- unused
- gofmt
- gofumpt
- misspell
- unparam
- gosec
- asciicheck
- errname
- gci
- godot
- goimports
- revive
linters-settings:
gofmt:
rewrite-rules:
- pattern: 'interface{}'
replacement: 'any'
- pattern: 'a[b:len(a)]'
replacement: 'a[b:]'
misspell:
locale: UK
errcheck:
check-type-assertions: true
issues:
max-same-issues: 0
max-issues-per-linter: 0
exclude-use-default: false
exclude:
# gosec: Duplicated errcheck checks
- G104
# gosec: integer overflow conversion int -> uint32
- G115

55
.goreleaser.yaml Normal file
View File

@ -0,0 +1,55 @@
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com
# The lines below are called `modelines`. See `:help modeline`
# Feel free to remove those if you don't want/need to use them.
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
version: 2
before:
hooks:
# You may remove this if you don't use go modules.
- go mod tidy
# you may remove this if you don't need go generate
- go generate ./...
builds:
- main: ./cmd/vbantxt/
env:
- CGO_ENABLED=0
goos:
- linux
- windows
goarch:
- amd64
archives:
- formats: ['tar.gz']
# this name template makes the OS and Arch compatible with the results of `uname`.
name_template: >-
{{ .ProjectName }}_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
# use zip for windows archives
format_overrides:
- goos: windows
formats: ['zip']
changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
release:
footer: >-
---
Released by [GoReleaser](https://github.com/goreleaser/goreleaser).

View File

@ -11,12 +11,32 @@ Before any major/minor/patch bump all unit tests will be run to verify they pass
- [x]
# [0.4.1] - 2025-04-05
### Changed
- `-loglevel` flag is now of type string. It accepts any one of trace, debug, info, warn, error, fatal or panic.
- It defaults to warn.
# [0.3.1] - 2025-03-31
### Fixed
- The CLI now uses `os.UserConfigDir()` to load the default *config.toml*, which should respect `$XDG_CONFIG_HOME`. See [UserConfigDir](https://pkg.go.dev/os#UserConfigDir)
# [0.2.1] - 2024-11-07
### Fixed
- {packet}.header() now uses a reusable buffer.
# [0.2.0] - 2024-10-27
### Added
- `config` flag (shorthand `C`), you may now specify a custom config directory. It defaults to `home directory / .config / vbantxt_cli /`.
- please note, the default directory has changed from v0.1.0
- Functional options `WithRateLimit` and `WithBPSOpt` and `WithChannel` added. Use them to configure the vbantxt client. See the [included vbantxt cli][vbantxt-cli] for an example of usage.
### Changed
@ -41,3 +61,5 @@ Before any major/minor/patch bump all unit tests will be run to verify they pass
- Initial release, package implements VBAN PROTOCOL TXT with a basic CLI for configuring options.
- Ability to load configuration settings from a config.toml.
[vbantxt-cli]: https://github.com/onyx-and-iris/vbantxt/blob/main/cmd/vbantxt/main.go

View File

@ -9,10 +9,10 @@ For an outline of past/future changes refer to: [CHANGELOG](CHANGELOG.md)
## Tested against
- Basic 1.0.8.4
- Banana 2.0.6.4
- Potato 3.0.2.4
- Matrix 1.0.0.3
- Basic 1.1.1.8
- Banana 2.1.1.8
- Potato 3.1.1.8
- Matrix 1.0.1.2
## Requirements
@ -41,13 +41,13 @@ func main() {
streamname string = "onyx"
)
vbantxtClient, err := vbantxt.New(host, port, streamname)
client, err := vbantxt.New(host, port, streamname)
if err != nil {
log.Fatal(err)
}
defer vbantxtClient.Close()
defer client.Close()
err = vbantxtClient.Send("strip[0].mute=0")
err = client.Send("strip[0].mute=0")
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Error: %s", err)
os.Exit(1)
@ -60,18 +60,18 @@ func main() {
Pass `host`, `port` and `streamname` as flags, for example:
```
vbantxt-cli -h="gamepc.local" -p=6980 -s=Command1 "strip[0].mute=1 strip[1].mono=1"
vbantxt -h="gamepc.local" -p=6980 -s=Command1 "strip[0].mute=1 strip[1].mono=1"
```
You may also store them in a `config.toml` located in `home directory / .config / vbantxt_cli /`
You may also store them in a `config.toml` located in `home directory / .config / vbantxt /`
A valid `config.toml` might look like this:
```toml
[connection]
Host="gamepc.local"
Port=6980
Streamname="Command1"
host="gamepc.local"
port=6980
streamname="Command1"
```
- `host` defaults to "localhost"
@ -84,15 +84,15 @@ Command line flags will override values in a config.toml.
## `Script files`
The vbantxt-cli utility accepts a single string request or an array of string requests. This means you can pass scripts stored in files.
The vbantxt CLI accepts a single string request or an array of string requests. This means you can pass scripts stored in files.
For example, in Windows with Powershell you could:
`vbantxt-cli $(Get-Content .\script.txt)`
`vbantxt $(Get-Content .\script.txt)`
Or with Bash:
`cat script.txt | xargs vbantxt-cli`
`xargs vbantxt < script.txt`
to load commands from a file:
@ -109,15 +109,29 @@ bus[3].eq.On=0
Sending commands to VB-Audio Matrix is also possible, for example:
```
vbantxt-cli -s=streamname "Point(ASIO128.IN[2],ASIO128.OUT[1]).dBGain = -8"
vbantxt -s=streamname "Point(ASIO128.IN[2],ASIO128.OUT[1]).dBGain = -8"
```
---
## `Logging`
Log level may be set by passing the `-l` flag with a number from 0 up to 6 where
The `-loglevel` flag allows you to control the verbosity of the application's logging output.
0 = Panic, 1 = Fatal, 2 = Error, 3 = Warning, 4 = Info, 5 = Debug, 6 = Trace
Acceptable values for this flag are:
Log level defaults to Warning level.
- `trace`
- `debug`
- `info`
- `warn`
- `error`
- `fatal`
- `panic`
For example, to set the log level to `debug`, you can use:
```
vbantxt -s=streamname -loglevel=debug "bus[0].eq.on=1 bus[1].gain=-12.8"
```
The default log level is `warn` if the flag is not specified.

55
Taskfile.yml Normal file
View File

@ -0,0 +1,55 @@
version: '3'
vars:
PROGRAM: vbantxt
SHELL: '{{if eq .OS "Windows_NT"}}powershell{{end}}'
BIN_DIR: bin
WINDOWS: '{{.BIN_DIR}}/{{.PROGRAM}}_windows_amd64.exe'
LINUX: '{{.BIN_DIR}}/{{.PROGRAM}}_linux_amd64'
GIT_COMMIT:
sh: git log -n 1 --format=%h
tasks:
default:
desc: Build the vbantxt project
cmds:
- task: build
build:
desc: 'Build the vbantxt project'
deps: [vet]
cmds:
- task: build-windows
- task: build-linux
vet:
desc: Vet the code
deps: [fmt]
cmds:
- go vet ./...
fmt:
desc: Fmt the code
cmds:
- go fmt ./...
build-windows:
desc: Build the vbantxt project for Windows
cmds:
- GOOS=windows GOARCH=amd64 go build -o {{.WINDOWS}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/
build-linux:
desc: Build the vbantxt project for Linux
cmds:
- GOOS=linux GOARCH=amd64 go build -o {{.LINUX}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/
test:
desc: Run tests
cmds:
- go test ./...
clean:
desc: Clean the build artifacts
cmds:
- '{{.SHELL}} rm -r {{.BIN_DIR}}'

View File

@ -1,48 +0,0 @@
package vbantxt
import (
"fmt"
"net"
log "github.com/sirupsen/logrus"
)
// client represents the UDP client
type client struct {
conn *net.UDPConn
}
// NewClient returns a UDP client
func newClient(host string, port int) (client, error) {
udpAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("%s:%d", host, port))
if err != nil {
return client{}, err
}
conn, err := net.DialUDP("udp4", nil, udpAddr)
if err != nil {
return client{}, err
}
log.Infof("Outgoing address %s", conn.RemoteAddr())
return client{conn: conn}, nil
}
// Write implements the io.WriteCloser interface
func (c client) Write(buf []byte) (int, error) {
n, err := c.conn.Write(buf)
if err != nil {
return 0, err
}
log.Debugf("Sending '%s' to: %s", string(buf), c.conn.RemoteAddr())
return n, nil
}
// Close implements the io.WriteCloser interface
func (c client) Close() error {
err := c.conn.Close()
if err != nil {
return err
}
return nil
}

View File

@ -1,3 +1,4 @@
// Package main provides the configuration loading functionality for the vbantxt application.
package main
import (

View File

@ -35,5 +35,4 @@ func TestLoadConfig_Errors(t *testing.T) {
assert.ErrorContains(t, err, tc.err)
})
}
}

View File

@ -5,15 +5,25 @@ import (
"fmt"
"os"
"path/filepath"
"slices"
"time"
"github.com/onyx-and-iris/vbantxt"
log "github.com/sirupsen/logrus"
)
type opts struct {
host string
port int
streamname string
bps int
channel int
ratelimit int
configPath string
loglevel string
}
func exit(err error) {
_, _ = fmt.Fprintf(os.Stderr, "Error: %s", err)
_, _ = fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
@ -22,7 +32,7 @@ func main() {
host string
port int
streamname string
loglevel int
loglevel string
configPath string
bps int
channel int
@ -36,43 +46,61 @@ func main() {
flag.StringVar(&streamname, "streamname", "Command1", "stream name for text requests")
flag.StringVar(&streamname, "s", "Command1", "stream name for text requests (shorthand)")
flag.IntVar(&bps, "bps", 0, "vban bps")
flag.IntVar(&bps, "b", 0, "vban bps (shorthand)")
flag.IntVar(&bps, "bps", 256000, "vban bps")
flag.IntVar(&bps, "b", 256000, "vban bps (shorthand)")
flag.IntVar(&channel, "channel", 0, "vban channel")
flag.IntVar(&channel, "c", 0, "vban channel (shorthand)")
flag.IntVar(&ratelimit, "ratelimit", 20, "request ratelimit in milliseconds")
flag.IntVar(&ratelimit, "r", 20, "request ratelimit in milliseconds (shorthand)")
homeDir, err := os.UserHomeDir()
configDir, err := os.UserConfigDir()
if err != nil {
exit(err)
}
defaultConfigPath := filepath.Join(homeDir, ".config", "vbantxt", "config.toml")
defaultConfigPath := filepath.Join(configDir, "vbantxt", "config.toml")
flag.StringVar(&configPath, "config", defaultConfigPath, "config path")
flag.StringVar(&configPath, "C", defaultConfigPath, "config path (shorthand)")
flag.IntVar(&loglevel, "loglevel", int(log.WarnLevel), "log level")
flag.IntVar(&loglevel, "l", int(log.WarnLevel), "log level (shorthand)")
flag.StringVar(&loglevel, "loglevel", "warn", "log level")
flag.StringVar(&loglevel, "l", "warn", "log level (shorthand)")
flag.Parse()
if slices.Contains(log.AllLevels, log.Level(loglevel)) {
log.SetLevel(log.Level(loglevel))
level, err := log.ParseLevel(loglevel)
if err != nil {
exit(fmt.Errorf("invalid log level: %s", loglevel))
}
log.SetLevel(level)
o := opts{
host: host,
port: port,
streamname: streamname,
bps: bps,
channel: channel,
ratelimit: ratelimit,
configPath: configPath,
loglevel: loglevel,
}
// Load the config only if the host, port, and streamname flags are not provided.
// This allows the user to override the config values with command line flags.
if !flagsPassed([]string{"host", "h", "port", "p", "streamname", "s"}) {
config, err := loadConfig(configPath)
if err != nil {
exit(err)
}
host = config.Host
port = config.Port
streamname = config.Streamname
}
client, err := createClient(host, port, streamname, bps, channel, ratelimit)
o.host = config.Host
o.port = config.Port
o.streamname = config.Streamname
}
log.Debugf("opts: %+v", o)
client, closer, err := createClient(o)
if err != nil {
exit(err)
}
defer client.Close()
defer closer()
for _, arg := range flag.Args() {
err := client.Send(arg)
@ -82,16 +110,24 @@ func main() {
}
}
func createClient(host string, port int, streamname string, bps int, channel, ratelimit int) (*vbantxt.VbanTxt, error) {
// createClient creates a new vban client with the provided options.
func createClient(o opts) (*vbantxt.VbanTxt, func(), error) {
client, err := vbantxt.New(
host,
port,
streamname,
vbantxt.WithBPSOpt(indexOf(vbantxt.BpsOpts, bps)),
vbantxt.WithChannel(channel),
vbantxt.WithRateLimit(time.Duration(ratelimit)*time.Millisecond))
o.host,
o.port,
o.streamname,
vbantxt.WithBPSOpt(o.bps),
vbantxt.WithChannel(o.channel),
vbantxt.WithRateLimit(time.Duration(o.ratelimit)*time.Millisecond))
if err != nil {
return nil, err
return nil, nil, err
}
return client, err
closer := func() {
if err := client.Close(); err != nil {
log.Error(err)
}
}
return client, closer, err
}

View File

@ -15,12 +15,3 @@ func flagsPassed(flags []string) bool {
})
return found
}
func indexOf[T comparable](collection []T, e T) int {
for i, x := range collection {
if x == e {
return i
}
}
return -1
}

View File

@ -1,3 +1,4 @@
// Package vbantxt provides utilities for handling VBAN text errors.
package vbantxt
// Error is used to define sentinel errors.

10
go.mod
View File

@ -1,16 +1,18 @@
module github.com/onyx-and-iris/vbantxt
go 1.19
go 1.23.0
toolchain go1.24.1
require (
github.com/BurntSushi/toml v1.2.1
github.com/sirupsen/logrus v1.9.0
github.com/BurntSushi/toml v1.5.0
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.9.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
golang.org/x/sys v0.32.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

11
go.sum
View File

@ -1,18 +1,19 @@
github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak=
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -1,11 +1,11 @@
program = vbantxt
PROGRAM = vbantxt
GO = go
BIN_DIR := bin
WINDOWS=$(BIN_DIR)/$(program)_windows_amd64.exe
LINUX=$(BIN_DIR)/$(program)_linux_amd64
VERSION=$(shell git describe --tags --always --long --dirty)
WINDOWS=$(BIN_DIR)/$(PROGRAM)_windows_amd64.exe
LINUX=$(BIN_DIR)/$(PROGRAM)_linux_amd64
VERSION=$(shell git log -n 1 --format=%h)
.DEFAULT_GOAL := build
@ -25,10 +25,10 @@ linux: $(LINUX)
$(WINDOWS):
env GOOS=windows GOARCH=amd64 go build -v -o $(WINDOWS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/vbantxt/
env GOOS=windows GOARCH=amd64 go build -v -o $(WINDOWS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
$(LINUX):
env GOOS=linux GOARCH=amd64 go build -v -o $(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/vbantxt/
env GOOS=linux GOARCH=amd64 go build -v -o $(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
test:
$(GO) test ./...

View File

@ -9,25 +9,26 @@ import (
// Option is a functional option type that allows us to configure the VbanTxt.
type Option func(*VbanTxt)
// WithRateLimit is a functional option to set the ratelimit for requests
// WithRateLimit is a functional option to set the ratelimit for requests.
func WithRateLimit(ratelimit time.Duration) Option {
return func(vt *VbanTxt) {
vt.ratelimit = ratelimit
}
}
// WithBPSOpt is a functional option to set the bps index for {VbanTx}.{Packet}.bpsIndex
func WithBPSOpt(bpsIndex int) Option {
// WithBPSOpt is a functional option to set the bps index for {VbanTxt}.packet.
func WithBPSOpt(bps int) Option {
return func(vt *VbanTxt) {
if bpsIndex < 0 || bpsIndex >= len(BpsOpts) {
log.Warnf("invalid bpsIndex %d, defaulting to 0", bpsIndex)
bpsIndex := indexOf(BpsOpts, bps)
if bpsIndex == -1 {
log.Warnf("invalid bps value %d, expected one of %v, defaulting to 0", bps, BpsOpts)
return
}
vt.packet.bpsIndex = bpsIndex
}
}
// WithChannel is a functional option to set the bps index for {VbanTx}.{Packet}.channel
// WithChannel is a functional option to set the channel for {VbanTxt}.packet.
func WithChannel(channel int) Option {
return func(vt *VbanTxt) {
vt.packet.channel = channel

View File

@ -1,6 +1,7 @@
package vbantxt
import (
"bytes"
"encoding/binary"
log "github.com/sirupsen/logrus"
@ -12,58 +13,59 @@ const (
headerSz = 4 + 1 + 1 + 1 + 1 + 16 + 4
)
var BpsOpts = []int{0, 110, 150, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 31250,
// BpsOpts defines the available baud rate options.
var BpsOpts = []int{
0, 110, 150, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 31250,
38400, 57600, 115200, 128000, 230400, 250000, 256000, 460800, 921600,
1000000, 1500000, 2000000, 3000000}
1000000, 1500000, 2000000, 3000000,
}
type packet struct {
name string
streamname []byte
bpsIndex int
channel int
framecounter []byte
hbuf *bytes.Buffer
}
// newPacket returns a packet struct with default values, framecounter at 0.
func newPacket(streamname string) packet {
streamnameBuf := make([]byte, streamNameSz)
copy(streamnameBuf, streamname)
return packet{
name: streamname,
streamname: streamnameBuf,
bpsIndex: 0,
channel: 0,
framecounter: make([]byte, 4),
hbuf: bytes.NewBuffer(make([]byte, headerSz)),
}
}
// sr defines the samplerate for the request
// sr defines the samplerate for the request.
func (p *packet) sr() byte {
return byte(vbanProtocolTxt + p.bpsIndex)
}
// nbc defines the channel of the request
// nbc defines the channel of the request.
func (p *packet) nbc() byte {
return byte(p.channel)
}
// streamname defines the stream name of the text request
func (p *packet) streamname() []byte {
b := make([]byte, streamNameSz)
copy(b, p.name)
return b
}
// header returns a fully formed packet header
// header returns a fully formed packet header.
func (p *packet) header() []byte {
h := make([]byte, 0, headerSz)
h = append(h, []byte("VBAN")...)
h = append(h, p.sr())
h = append(h, byte(0))
h = append(h, p.nbc())
h = append(h, byte(0x10))
h = append(h, p.streamname()...)
h = append(h, p.framecounter...)
return h
p.hbuf.Reset()
p.hbuf.WriteString("VBAN")
p.hbuf.WriteByte(p.sr())
p.hbuf.WriteByte(byte(0))
p.hbuf.WriteByte(p.nbc())
p.hbuf.WriteByte(byte(0x10))
p.hbuf.Write(p.streamname)
p.hbuf.Write(p.framecounter)
return p.hbuf.Bytes()
}
// bumpFrameCounter increments the frame counter by 1
// bumpFrameCounter increments the frame counter by 1.
func (p *packet) bumpFrameCounter() {
x := binary.LittleEndian.Uint32(p.framecounter)
binary.LittleEndian.PutUint32(p.framecounter, x+1)

48
udpconn.go Normal file
View File

@ -0,0 +1,48 @@
package vbantxt
import (
"fmt"
"net"
log "github.com/sirupsen/logrus"
)
// udpConn represents the UDP client.
type udpConn struct {
conn *net.UDPConn
}
// newUDPConn returns a UDP client.
func newUDPConn(host string, port int) (udpConn, error) {
udpAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("%s:%d", host, port))
if err != nil {
return udpConn{}, err
}
conn, err := net.DialUDP("udp4", nil, udpAddr)
if err != nil {
return udpConn{}, err
}
log.Infof("Outgoing address %s", conn.RemoteAddr())
return udpConn{conn: conn}, nil
}
// Write implements the io.WriteCloser interface.
func (u udpConn) Write(buf []byte) (int, error) {
n, err := u.conn.Write(buf)
if err != nil {
return 0, err
}
log.Debugf("Sending '%s' to: %s", string(buf), u.conn.RemoteAddr())
return n, nil
}
// Close implements the io.WriteCloser interface.
func (u udpConn) Close() error {
err := u.conn.Close()
if err != nil {
return err
}
return nil
}

10
util.go Normal file
View File

@ -0,0 +1,10 @@
package vbantxt
func indexOf[T comparable](collection []T, e T) int {
for i, x := range collection {
if x == e {
return i
}
}
return -1
}

View File

@ -8,7 +8,7 @@ import (
// VbanTxt is used to send VBAN-TXT requests to a distant Voicemeeter/Matrix.
type VbanTxt struct {
client io.WriteCloser
udpConn io.WriteCloser
packet packet
ratelimit time.Duration
}
@ -16,13 +16,13 @@ type VbanTxt struct {
// New constructs a fully formed VbanTxt instance. This is the package's entry point.
// It sets default values for it's fields and then runs the option functions.
func New(host string, port int, streamname string, options ...Option) (*VbanTxt, error) {
client, err := newClient(host, port)
udpConn, err := newUDPConn(host, port)
if err != nil {
return nil, fmt.Errorf("error creating UDP client for (%s:%d): %w", host, port, err)
}
vt := &VbanTxt{
client: client,
udpConn: udpConn,
packet: newPacket(streamname),
ratelimit: time.Duration(20) * time.Millisecond,
}
@ -37,7 +37,7 @@ func New(host string, port int, streamname string, options ...Option) (*VbanTxt,
// Send is resonsible for firing each VBAN-TXT request.
// It waits for {vt.ratelimit} time before returning.
func (vt VbanTxt) Send(cmd string) error {
_, err := vt.client.Write(append(vt.packet.header(), []byte(cmd)...))
_, err := vt.udpConn.Write(append(vt.packet.header(), []byte(cmd)...))
if err != nil {
return fmt.Errorf("error sending command (%s): %w", cmd, err)
}
@ -49,9 +49,9 @@ func (vt VbanTxt) Send(cmd string) error {
return nil
}
// Close is responsible for closing the UDP Client connection
// Close is responsible for closing the UDP Client connection.
func (vt VbanTxt) Close() error {
err := vt.client.Close()
err := vt.udpConn.Close()
if err != nil {
return fmt.Errorf("error attempting to close UDP Client: %w", err)
}

View File

@ -28,14 +28,14 @@ func run(t *testing.T, client *vbantxt.VbanTxt, script []byte) {
}
func TestSendVm(t *testing.T) {
client, err := vbantxt.New("vm.local", 6980, "onyx")
client, err := vbantxt.New("localhost", 6980, "onyx")
require.NoError(t, err)
run(t, client, vm)
}
func TestSendMatrix(t *testing.T) {
client, err := vbantxt.New("vm.local", 6990, "onyx")
client, err := vbantxt.New("localhost", 6990, "onyx")
require.NoError(t, err)
run(t, client, matrix)