Compare commits

...

69 Commits
v0.4.0 ... main

Author SHA1 Message Date
github-actions[bot]
2ce055c198 chore: auto-update Go modules 2026-03-09 00:05:20 +00:00
be2715816b move versionFromBuild() 2026-03-07 12:40:58 +00:00
55d14b0d07 upd tested against
add macOS badge
2026-03-07 01:07:37 +00:00
b7cd658d7c add vbanTxtUtf8 to give the magic value meaning
OR the bpsIndex with the mask value.
2026-03-07 00:53:35 +00:00
b506265e37 make the ratelimiting more accurate. 2026-03-07 00:52:58 +00:00
github-actions[bot]
843f7c5e0d chore: auto-update Go modules 2026-02-23 00:05:50 +00:00
754369668b rewrite versionFromBuild() 2026-02-16 01:19:54 +00:00
5485927311 return nil, nil if --version of --help flags passed 2026-02-16 00:55:08 +00:00
a0a8159557 return nil explicitly if no error 2026-02-16 00:10:00 +00:00
github-actions[bot]
87c2afbf03 chore: auto-update Go modules 2026-02-16 00:06:01 +00:00
5d9924ff58 replace exitOnError with a deferred exit function.
this ensures the closer() cleanup function is always called.
2026-02-15 11:08:25 +00:00
00acafa290 fix docstring 2026-02-15 10:51:59 +00:00
f97d241f64 add linter exclusion for test files
set thresholds for issues
2026-02-15 09:54:12 +00:00
87ea26ab03 build-{OS} targets internal 2026-02-14 21:25:39 +00:00
331d4e2f9a add macos target to Taskfile+makefile 2026-02-14 21:18:31 +00:00
d21dfb9481 add 0.6.0 to CHANGELOG 2026-02-14 20:53:42 +00:00
510d43ca33 migrate golangci config to version 2.
update golang-cl workflow
2026-02-14 20:46:22 +00:00
acac22f70e add versionFromBuild() and sendCommands() to separate the logic in main() a little.
Flags now implements fmt.Stringer interface.

import lint fix
2026-02-14 20:45:13 +00:00
b568767f86 lint fix 2026-02-14 20:44:03 +00:00
08909b6b66 log at warn level invalid bps, channel values. inform user of default value. 2026-02-14 20:43:55 +00:00
c6d03e87d7 errors from newPacket() now propogated
Send() and Close() methods now use pointer receivers.
2026-02-14 20:42:33 +00:00
0d0dbedbcd used fixed-sized array for streamname instead of slice.
factory method now validates streamname size.

framecounter now stored as uint32. it's written to a byte buffer on each call to {Packet}.header()
add comment regarding framecounter wraparound.
2026-02-14 20:40:38 +00:00
github-actions[bot]
ecd16545ab chore: auto-update Go modules 2026-02-09 00:06:13 +00:00
github-actions[bot]
abdc50bf1f chore: auto-update Go modules 2026-02-02 01:04:10 +00:00
bf22881227 add chore: to changelog filter 2026-01-28 21:39:56 +00:00
github-actions[bot]
1473c53dea chore: auto-update Go modules 2026-01-26 00:04:13 +00:00
github-actions[bot]
6f10f3ce20 chore: auto-update Go modules 2026-01-19 00:04:12 +00:00
github-actions[bot]
f803a38619 chore: auto-update Go modules 2026-01-12 00:04:10 +00:00
github-actions[bot]
862f127d54 chore: auto-update Go modules 2025-12-22 00:04:48 +00:00
github-actions[bot]
500a1c886a chore: auto-update Go modules 2025-12-15 00:04:02 +00:00
github-actions[bot]
707f2c9a2c chore: auto-update Go modules 2025-12-01 00:04:22 +00:00
github-actions[bot]
9c9242bae4 chore: auto-update Go modules 2025-11-17 00:03:59 +00:00
github-actions[bot]
b56b4afcbf chore: auto-update Go modules 2025-11-10 00:04:01 +00:00
github-actions[bot]
c08019a063 chore: auto-update Go modules 2025-11-03 00:04:10 +00:00
github-actions[bot]
29a503ce8f chore: auto-update Go modules 2025-10-27 00:04:09 +00:00
github-actions[bot]
22529a0b39 chore: auto-update Go modules 2025-10-20 00:04:08 +00:00
github-actions[bot]
a153830d3f chore: auto-update Go modules 2025-10-13 00:03:57 +00:00
github-actions[bot]
e7736f383b chore: auto-update Go modules 2025-10-06 00:03:52 +00:00
github-actions[bot]
458ea95da0 chore: auto-update Go modules 2025-09-29 00:04:04 +00:00
github-actions[bot]
805a3250fc chore: auto-update Go modules 2025-09-15 00:04:06 +00:00
github-actions[bot]
defcbbc8a7 chore: auto-update Go modules 2025-09-08 00:03:47 +00:00
github-actions[bot]
19011b0b34 chore: auto-update Go modules 2025-08-25 00:03:51 +00:00
github-actions[bot]
923e741455 chore: auto-update Go modules 2025-08-18 00:03:57 +00:00
github-actions[bot]
5a0cf42347 chore: auto-update Go modules 2025-08-11 00:04:02 +00:00
github-actions[bot]
0f9dad3015 chore: auto-update Go modules 2025-07-21 00:04:25 +00:00
github-actions[bot]
9106a19486 chore: auto-update Go modules 2025-07-14 00:03:51 +00:00
github-actions[bot]
84ef1904fc chore: auto-update Go modules 2025-06-23 00:03:44 +00:00
f9ca8a05db add darwin + arm64 builds 2025-06-18 00:28:29 +01:00
9844d22c46 upd install instructions 2025-06-16 21:20:06 +01:00
github-actions[bot]
e7e158981b chore: auto-update Go modules 2025-06-16 00:03:45 +00:00
b60909e6ec typo 2025-06-15 07:50:11 +01:00
9a15ad98a8 fix flag name 2025-06-14 17:17:27 +01:00
b8fa4d5be0 fix env prefix 2025-06-14 17:05:16 +01:00
64c1cb8fbe update/reorganise readme 2025-06-14 17:03:49 +01:00
eeb789003b add changelog links 2025-06-14 09:16:19 +01:00
4fd190bc4e read host, streamname from env 2025-06-14 09:13:25 +01:00
c0aad67199 add 0.5.0 section to CHANGELOG 2025-06-14 09:05:34 +01:00
be65f41813 update Configuration section to reflect ff changes 2025-06-14 09:03:44 +01:00
fd72628530 inject version at build time 2025-06-14 09:00:04 +01:00
898fbc3ae2 implement flag parsing with flags first package
run it with the environment resolver

add --version/-v flag.
2025-06-14 08:59:05 +01:00
5b8219d107 swap out logrus for charmbracelet/log 2025-06-14 07:39:08 +01:00
8ab543df0f remove config/util 2025-06-14 07:38:33 +01:00
github-actions[bot]
2035e158b1 chore: auto-update Go modules 2025-05-12 00:03:44 +00:00
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
20 changed files with 602 additions and 348 deletions

View File

@ -2,11 +2,11 @@ name: CI
on: on:
push: push:
branches: [ "main" ] branches: ['main']
paths: paths:
- '**.go' - '**.go'
pull_request: pull_request:
branches: [ "main" ] branches: ['main']
paths: paths:
- '**.go' - '**.go'
jobs: jobs:
@ -23,7 +23,8 @@ jobs:
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
go-version: '1.24' go-version: '1.24'
- name: Install golangci-lint - name: golangci-lint
run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest uses: golangci/golangci-lint-action@v9
- name: Run golangci-lint with:
run: golangci-lint run ./... version: v2.6.0
args: --config .golangci.yml

2
.gitignore vendored
View File

@ -17,3 +17,5 @@ bin/
# Added by goreleaser init: # Added by goreleaser init:
dist/ dist/
.envrc

View File

@ -1,54 +1,125 @@
version: '2'
run: run:
# timeout for analysis, e.g. 30s, 3m, default is 1m
timeout: 3m timeout: 3m
# exclude test files
tests: true tests: true
go: '1.24'
linters: 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: enable:
- gosimple # Default enabled linters
- govet - errcheck # Check for unchecked errors
- ineffassign - govet # Go's built-in vetting tool
- staticcheck - ineffassign # Detect ineffectual assignments
- unused - staticcheck # Advanced static analysis
- gofmt - unused # Check for unused code
- gofumpt # Additional useful linters
- misspell - misspell # Detect common misspellings
- unparam - unparam # Check for unused function parameters
- gosec - gosec # Security checks
- asciicheck - asciicheck # Check for non-ASCII characters
- errname - errname # Check error variable names
- gci - godot # Check for missing periods in comments
- godot - revive # Highly configurable linter for style and correctness
- goimports - gocritic # Detect code issues and suggest improvements
- revive - gocyclo # Check for cyclomatic complexity
- dupl # Check for code duplication
- predeclared # Check for shadowing of predeclared identifiers
- copyloopvar # Check for loop variable capture in goroutines
- errorlint # Check for common mistakes in error handling
- goconst # Check for repeated strings that could be constants
- gosmopolitan # Check for non-portable code
linters-settings: settings:
gofmt: misspell:
rewrite-rules: locale: UK
- pattern: 'interface{}'
replacement: 'any'
- pattern: 'a[b:len(a)]'
replacement: 'a[b:]'
misspell: errcheck:
locale: UK check-type-assertions: true
check-blank: true
errcheck: revive:
check-type-assertions: true rules:
# Code quality and style
- name: exported
arguments:
- 'checkPrivateReceivers'
- 'sayRepetitiveInsteadOfStutters'
- name: var-naming
- name: package-comments
- name: range-val-in-closure
- name: time-naming
- name: context-as-argument
- name: context-keys-type
- name: dot-imports
- name: empty-block
- name: error-return
- name: error-strings
- name: error-naming
- name: if-return
- name: increment-decrement
- name: indent-error-flow
- name: receiver-naming
- name: redefines-builtin-id
- name: superfluous-else
- name: unexported-return
- name: unreachable-code
- name: unused-parameter
- name: var-declaration
- name: blank-imports
- name: range
# Disabled rules (can be enabled if needed)
# - name: line-length-limit
# arguments: [120]
# - name: function-length
# arguments: [50, 0]
# - name: cyclomatic
# arguments: [10]
gosec:
excludes:
- G104 # Duplicated errcheck checks
- G115 # integer overflow conversion int -> uint32
exclusions:
warn-unused: false
rules:
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- gocyclo
- errcheck
- dupl
- gosec
# Formatters configuration
formatters:
# Enable specific formatters
enable:
- gofumpt # Stricter gofmt alternative
- goimports # Organizes imports
- gci # Controls import order/grouping
- golines # Enforces line length
# Formatter-specific settings
settings:
goimports:
local-prefixes: [github.com/onyx-and-iris/vbantxt]
gci:
# Define import sections order
sections:
- standard # Standard library
- default # Everything else
- prefix(github.com/onyx-and-iris/vbantxt) # Current module
gofumpt:
extra-rules: true # Enable additional formatting rules
issues: issues:
max-same-issues: 0 # Limit the number of same issues reported to avoid spam
max-issues-per-linter: 0 max-same-issues: 50
exclude-use-default: false
exclude: # Limit the number of issues per linter to keep output manageable
# gosec: Duplicated errcheck checks max-issues-per-linter: 100
- G104
# gosec: integer overflow conversion int -> uint32
- G115

View File

@ -22,8 +22,10 @@ builds:
goos: goos:
- linux - linux
- windows - windows
- darwin
goarch: goarch:
- amd64 - amd64
- arm64
archives: archives:
- formats: ['tar.gz'] - formats: ['tar.gz']
@ -46,6 +48,7 @@ changelog:
exclude: exclude:
- '^docs:' - '^docs:'
- '^test:' - '^test:'
- '^chore:'
release: release:
footer: >- footer: >-

View File

@ -11,6 +11,44 @@ Before any major/minor/patch bump all unit tests will be run to verify they pass
- [x] - [x]
# [0.6.0] - 2025-02-14
### Added
- streamname length validation added to {packet} factory method.
### Changed
- {packet}.bspIndex now defaults to *indexOf(BpsOpts, 256000)*.
- this doesn't affect the CLI which already defaulted to 256000.
- WithBPSOpt and WithChannel functional options now log at warn level if passed out of bounds value. They will fallback to valid defaults.
# [0.5.0] - 2025-06-25
### Added
- it's now possible to load configuration from environment variables. See [Environment Variables](https://github.com/onyx-and-iris/vbantxt/tree/main?tab=readme-ov-file#environment-variables)
- --version/-v command
### Changed
- shortname for --host flag is now -H.
- shortname for --channel flag is now -n.
- toml loader no longer requires a `[connection]` table. See [TOML Config](https://github.com/onyx-and-iris/vbantxt/tree/main?tab=readme-ov-file#toml-config)
# [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 # [0.2.1] - 2024-11-07
### Fixed ### Fixed

123
README.md
View File

@ -1,5 +1,6 @@
![Windows](https://img.shields.io/badge/Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white) ![Windows](https://img.shields.io/badge/Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white)
![Linux](https://img.shields.io/badge/Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black) ![Linux](https://img.shields.io/badge/Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black)
![macOS](https://img.shields.io/badge/mac%20os-000000?style=for-the-badge&logo=macos&logoColor=F0F0F0)
# VBAN Sendtext # VBAN Sendtext
@ -7,23 +8,34 @@ Send Voicemeeter/Matrix vban requests.
For an outline of past/future changes refer to: [CHANGELOG](CHANGELOG.md) For an outline of past/future changes refer to: [CHANGELOG](CHANGELOG.md)
## Tested against ---
- Basic 1.0.8.4 ## Table of Contents
- Banana 2.0.6.4
- Potato 3.0.2.4 - [Installation](#installation)
- Matrix 1.0.0.3 - [VBANTXT Package](#vbantxt-package)
- [VBANTXT CLI](#vbantxt-cli)
- [License](#license)
## Requirements ## Requirements
- [Voicemeeter](https://voicemeeter.com/) or [Matrix](https://vb-audio.com/Matrix/) - [Voicemeeter](https://voicemeeter.com/) or [Matrix](https://vb-audio.com/Matrix/)
- Go 1.18 or greater (if you want to compile yourself, otherwise check `Releases`) - Go 1.18 or greater (a binary is available in [Releases](https://github.com/onyx-and-iris/vbantxt/releases))
## Tested against
- Basic 1.1.2.2
- Banana 2.1.2.2
- Potato 3.1.2.2
- Matrix 1.0.2.6
--- ---
## `Use` ## `VBANTXT Package`
`go get github.com/onyx-and-iris/vbantxt` ```console
go get github.com/onyx-and-iris/vbantxt
```
```go ```go
package main package main
@ -55,44 +67,91 @@ func main() {
} }
``` ```
## `Command Line` ## `VBANTXT CLI`
Pass `host`, `port` and `streamname` as flags, for example: ### Installation
``` ```console
vbantxt -h="gamepc.local" -p=6980 -s=Command1 "strip[0].mute=1 strip[1].mono=1" go install github.com/onyx-and-iris/vbantxt/cmd/vbantxt@latest
``` ```
You may also store them in a `config.toml` located in `home directory / .config / vbantxt /` ### Use
A valid `config.toml` might look like this: Simply pass your vban commands as command line arguments:
```console
vbantxt "strip[0].mute=1 strip[1].mono=1"
```
### Configuration
#### Flags
```console
FLAGS
-H, --host STRING VBAN host (default: localhost)
-p, --port INT VBAN port (default: 6980)
-s, --streamname STRING VBAN stream name (default: Command1)
-b, --bps INT VBAN BPS (default: 256000)
-n, --channel INT VBAN channel (default: 0)
-r, --ratelimit INT VBAN rate limit (ms) (default: 20)
-C, --config STRING Path to the configuration file (default: $XDG_CONFIG_HOME/vbantxt/config.toml)
-l, --loglevel STRING Log level (debug, info, warn, error, fatal, panic) (default: warn)
-v, --version Show version information
```
Pass --host, --port and --streamname as flags on the root command, for example:
```console
vbantxt --host=localhost --port=6980 --streamname=Command1 --help
```
#### Environment Variables
All flags have corresponding environment variables, prefixed with `VBANTXT_`:
```bash
#!/usr/bin/env bash
export VBANTXT_HOST=localhost
export VBANTXT_PORT=6980
export VBANTXT_STREAMNAME=Command1
```
Flags will override environment variables.
#### TOML Config
By default the config loader will look for a config in:
- $XDG_CONFIG_HOME / vbantxt / config.toml (see [os.UserConfigDir](https://pkg.go.dev/os#UserConfigDir))
- A custom config path may be passed with the --config/-C flag.
All flags have corresponding keys in the config file, for example:
```toml ```toml
[connection]
host="gamepc.local" host="gamepc.local"
port=6980 port=6980
streamname="Command1" streamname="Command1"
``` ```
- `host` defaults to "localhost"
- `port` defaults to 6980
- `streamname` defaults to "Command1"
Command line flags will override values in a config.toml.
--- ---
## `Script files` ## `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: For example, in Windows with Powershell you could:
`vbantxt $(Get-Content .\script.txt)` ```console
vbantxt $(Get-Content .\script.txt)
```
Or with Bash: Or with Bash:
`xargs vbantxt < script.txt` ```console
xargs vbantxt < script.txt
```
to load commands from a file: to load commands from a file:
@ -108,19 +167,18 @@ bus[3].eq.On=0
Sending commands to VB-Audio Matrix is also possible, for example: Sending commands to VB-Audio Matrix is also possible, for example:
``` ```console
vbantxt -s=streamname "Point(ASIO128.IN[2],ASIO128.OUT[1]).dBGain = -8" vbantxt "Point(ASIO128.IN[2],ASIO128.OUT[1]).dBGain = -8"
``` ```
--- ---
## `Logging` ## `Logging`
The `-log-level` flag allows you to control the verbosity of the application's logging output. The --loglevel/-l flag allows you to control the verbosity of the application's logging output.
Acceptable values for this flag are: Acceptable values for this flag are:
- `trace`
- `debug` - `debug`
- `info` - `info`
- `warn` - `warn`
@ -130,8 +188,13 @@ Acceptable values for this flag are:
For example, to set the log level to `debug`, you can use: For example, to set the log level to `debug`, you can use:
``` ```console
vbantxt -s=streamname -log-level=debug "bus[0].eq.on=1 bus[1].gain=-12.8" vbantxt --loglevel=debug "bus[0].eq.on=1 bus[1].gain=-12.8"
``` ```
The default log level is `warn` if the flag is not specified. The default log level is `warn` if the flag is not specified.
## License
`vbantxt` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.

View File

@ -4,11 +4,12 @@ vars:
PROGRAM: vbantxt PROGRAM: vbantxt
SHELL: '{{if eq .OS "Windows_NT"}}powershell{{end}}' SHELL: '{{if eq .OS "Windows_NT"}}powershell{{end}}'
BIN_DIR: bin BIN_DIR: bin
VERSION:
sh: 'git describe --tags $(git rev-list --tags --max-count=1)'
WINDOWS: '{{.BIN_DIR}}/{{.PROGRAM}}_windows_amd64.exe' WINDOWS: '{{.BIN_DIR}}/{{.PROGRAM}}_windows_amd64.exe'
LINUX: '{{.BIN_DIR}}/{{.PROGRAM}}_linux_amd64' LINUX: '{{.BIN_DIR}}/{{.PROGRAM}}_linux_amd64'
GIT_COMMIT: MACOS: '{{.BIN_DIR}}/{{.PROGRAM}}_darwin_amd64'
sh: git log -n 1 --format=%h
tasks: tasks:
default: default:
@ -22,7 +23,7 @@ tasks:
cmds: cmds:
- task: build-windows - task: build-windows
- task: build-linux - task: build-linux
- task: build-macos
vet: vet:
desc: Vet the code desc: Vet the code
deps: [fmt] deps: [fmt]
@ -37,12 +38,20 @@ tasks:
build-windows: build-windows:
desc: Build the vbantxt project for Windows desc: Build the vbantxt project for Windows
cmds: cmds:
- GOOS=windows GOARCH=amd64 go build -o {{.WINDOWS}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/ - GOOS=windows GOARCH=amd64 go build -o {{.WINDOWS}} -ldflags="-X main.version={{.VERSION}}" ./cmd/{{.PROGRAM}}/
internal: true
build-linux: build-linux:
desc: Build the vbantxt project for Linux desc: Build the vbantxt project for Linux
cmds: cmds:
- GOOS=linux GOARCH=amd64 go build -o {{.LINUX}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/ - GOOS=linux GOARCH=amd64 go build -o {{.LINUX}} -ldflags="-X main.version={{.VERSION}}" ./cmd/{{.PROGRAM}}/
internal: true
build-macos:
desc: Build the vbantxt project for macOS
cmds:
- GOOS=darwin GOARCH=amd64 go build -o {{.MACOS}} -ldflags="-X main.version={{.VERSION}}" ./cmd/{{.PROGRAM}}/
internal: true
test: test:
desc: Run tests desc: Run tests

View File

@ -1,43 +0,0 @@
// Package main provides the configuration loading functionality for the vbantxt application.
package main
import (
"fmt"
"os"
"github.com/BurntSushi/toml"
log "github.com/sirupsen/logrus"
)
type config struct {
Connection connection `toml:"connection"`
}
func (c config) String() string {
return fmt.Sprintf(
"host: %s port: %d streamname: %s",
c.Connection.Host, c.Connection.Port, c.Connection.Streamname)
}
type connection struct {
Host string `toml:"host"`
Port int `toml:"port"`
Streamname string `toml:"streamname"`
}
func loadConfig(configPath string) (*connection, error) {
_, err := os.Stat(configPath)
if err != nil {
return nil, err
}
var config config
_, err = toml.DecodeFile(configPath, &config)
if err != nil {
return nil, err
}
log.Debug(config)
return &config.Connection, nil
}

View File

@ -1,38 +0,0 @@
package main
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLoadConfig_Success(t *testing.T) {
conn, err := loadConfig("testdata/config.toml")
require.NoError(t, err)
assert.Equal(t, conn.Host, "localhost")
assert.Equal(t, conn.Port, 7000)
assert.Equal(t, conn.Streamname, "vbantxt")
}
func TestLoadConfig_Errors(t *testing.T) {
tt := map[string]struct {
input string
err string
}{
"no such file": {
input: "/no/such/dir/config.toml",
err: "no such file or directory",
},
}
for name, tc := range tt {
_, err := loadConfig("/no/such/dir/config.toml")
t.Run(name, func(t *testing.T) {
assert.Error(t, err)
assert.ErrorContains(t, err, tc.err)
})
}
}

View File

@ -1,137 +1,176 @@
// Package main implements a command-line tool for sending text messages over VBAN using the vbantxt library.
package main package main
import ( import (
"flag" "errors"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"runtime/debug"
"strings"
"time" "time"
"github.com/charmbracelet/log"
"github.com/peterbourgon/ff/v4"
"github.com/peterbourgon/ff/v4/ffhelp"
"github.com/peterbourgon/ff/v4/fftoml"
"github.com/onyx-and-iris/vbantxt" "github.com/onyx-and-iris/vbantxt"
log "github.com/sirupsen/logrus"
) )
type opts struct { var version string // Version will be set at build time
host string
port int // versionFromBuild retrieves the version information from the build metadata.
streamname string func versionFromBuild() string {
bps int if version != "" {
channel int return version
ratelimit int }
configPath string
loglevel string info, ok := debug.ReadBuildInfo()
if !ok {
return "(unable to read version)"
}
return strings.Split(info.Main.Version, "-")[0]
} }
func exit(err error) { // Flags holds the command-line flags for the VBANTXT client.
_, _ = fmt.Fprintf(os.Stderr, "Error: %s", err) type Flags struct {
os.Exit(1) Host string
Port int
Streamname string
Bps int
Channel int
Ratelimit int
ConfigPath string // Path to the configuration file
Loglevel string // Log level
Version bool // Version flag
} }
func main() { func (f *Flags) String() string {
var ( return fmt.Sprintf(
host string "Host: %s, Port: %d, Streamname: %s, Bps: %d, Channel: %d, Ratelimit: %dms, ConfigPath: %s, Loglevel: %s",
port int f.Host,
streamname string f.Port,
loglevel string f.Streamname,
configPath string f.Bps,
bps int f.Channel,
channel int f.Ratelimit,
ratelimit int f.ConfigPath,
f.Loglevel,
) )
}
flag.StringVar(&host, "host", "localhost", "vban host") // main is the entry point of the application.
flag.StringVar(&host, "h", "localhost", "vban host (shorthand)") // It sets up a deferred function to handle exiting with the appropriate exit code
flag.IntVar(&port, "port", 6980, "vban server port") // and calls the run function to execute the main logic.
flag.IntVar(&port, "p", 6980, "vban server port (shorthand)") func main() {
flag.StringVar(&streamname, "streamname", "Command1", "stream name for text requests") var exitCode int
flag.StringVar(&streamname, "s", "Command1", "stream name for text requests (shorthand)")
flag.IntVar(&bps, "bps", 256000, "vban bps") // Defer exit with the final exit code
flag.IntVar(&bps, "b", 256000, "vban bps (shorthand)") defer func() {
flag.IntVar(&channel, "channel", 0, "vban channel") if exitCode != 0 {
flag.IntVar(&channel, "c", 0, "vban channel (shorthand)") os.Exit(exitCode)
flag.IntVar(&ratelimit, "ratelimit", 20, "request ratelimit in milliseconds") }
flag.IntVar(&ratelimit, "r", 20, "request ratelimit in milliseconds (shorthand)") }()
closer, err := run()
if closer != nil {
defer closer()
}
if err != nil {
log.Error(err)
exitCode = 1
}
}
// run contains the main application logic and returns a closer function and any error.
func run() (func(), error) {
var flags Flags
// VBAN specific flags
fs := ff.NewFlagSet("vbantxt - A command-line tool for sending text requests over VBAN")
fs.StringVar(&flags.Host, 'H', "host", "localhost", "VBAN host")
fs.IntVar(&flags.Port, 'p', "port", 6980, "VBAN port")
fs.StringVar(&flags.Streamname, 's', "streamname", "Command1", "VBAN stream name")
fs.IntVar(&flags.Bps, 'b', "bps", 256000, "VBAN BPS")
fs.IntVar(&flags.Channel, 'n', "channel", 0, "VBAN channel")
fs.IntVar(&flags.Ratelimit, 'r', "ratelimit", 20, "VBAN rate limit (ms)")
configDir, err := os.UserConfigDir() configDir, err := os.UserConfigDir()
if err != nil { if err != nil {
exit(err) return nil, fmt.Errorf("failed to get user config directory: %w", err)
} }
defaultConfigPath := filepath.Join(configDir, "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.StringVar(&loglevel, "log-level", "warn", "log level")
flag.StringVar(&loglevel, "l", "warn", "log level (shorthand)")
flag.Parse() // Configuration file and logging flags
fs.StringVar(
&flags.ConfigPath,
'C',
"config",
defaultConfigPath,
"Path to the configuration file",
)
fs.StringVar(
&flags.Loglevel,
'l',
"loglevel",
"warn",
"Log level (debug, info, warn, error, fatal, panic)",
)
fs.BoolVar(&flags.Version, 'v', "version", "Show version information")
switch loglevel { err = ff.Parse(fs, os.Args[1:],
case "trace": ff.WithEnvVarPrefix("VBANTXT"),
log.SetLevel(log.TraceLevel) ff.WithConfigFileFlag("config"),
case "debug": ff.WithConfigAllowMissingFile(),
log.SetLevel(log.DebugLevel) ff.WithConfigFileParser(fftoml.Parser{Delimiter: "."}.Parse),
case "info": )
log.SetLevel(log.InfoLevel) switch {
case "warn": case errors.Is(err, ff.ErrHelp):
log.SetLevel(log.WarnLevel) fmt.Fprintf(os.Stderr, "%s\n", ffhelp.Flags(fs, "vbantxt [flags] <vban commands>"))
case "error": return nil, nil
log.SetLevel(log.ErrorLevel) case err != nil:
case "fatal": return nil, fmt.Errorf("failed to parse flags: %w", err)
log.SetLevel(log.FatalLevel)
case "panic":
log.SetLevel(log.PanicLevel)
default:
exit(fmt.Errorf("invalid log level: %s", loglevel))
} }
o := opts{ if flags.Version {
host: host, fmt.Printf("vbantxt version: %s\n", versionFromBuild())
port: port, return nil, nil
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. level, err := log.ParseLevel(flags.Loglevel)
// 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)
}
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 { if err != nil {
exit(err) return nil, fmt.Errorf("invalid log level %q", flags.Loglevel)
} }
defer closer() log.SetLevel(level)
for _, arg := range flag.Args() { log.Debugf("Loaded configuration: %s", flags.String())
err := client.Send(arg)
if err != nil { client, closer, err := createClient(&flags)
log.Error(err) if err != nil {
} return nil, fmt.Errorf("failed to create VBAN client: %w", err)
} }
commands := fs.GetArgs()
if len(commands) == 0 {
return closer, errors.New(
"no VBAN commands provided; please provide at least one command as an argument",
)
}
sendCommands(client, commands)
return closer, nil
} }
// createClient creates a new vban client with the provided options. // createClient creates a new vban client with the provided options.
func createClient(o opts) (*vbantxt.VbanTxt, func(), error) { func createClient(flags *Flags) (*vbantxt.VbanTxt, func(), error) {
client, err := vbantxt.New( client, err := vbantxt.New(
o.host, flags.Host,
o.port, flags.Port,
o.streamname, flags.Streamname,
vbantxt.WithBPSOpt(o.bps), vbantxt.WithBPSOpt(flags.Bps),
vbantxt.WithChannel(o.channel), vbantxt.WithChannel(flags.Channel),
vbantxt.WithRateLimit(time.Duration(o.ratelimit)*time.Millisecond)) vbantxt.WithRateLimit(time.Duration(flags.Ratelimit)*time.Millisecond))
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -142,5 +181,14 @@ func createClient(o opts) (*vbantxt.VbanTxt, func(), error) {
} }
} }
return client, closer, err return client, closer, nil
}
// sendCommands sends the provided VBAN commands using the client and logs any errors that occur.
func sendCommands(client *vbantxt.VbanTxt, commands []string) {
for _, cmd := range commands {
if err := client.Send(cmd); err != nil {
log.Errorf("Failed to send command '%s': %v", cmd, err)
}
}
} }

View File

@ -1,4 +0,0 @@
[connection]
host = "localhost"
port = 7000
streamname = "vbantxt"

View File

@ -1,17 +0,0 @@
package main
import (
"flag"
"slices"
)
func flagsPassed(flags []string) bool {
found := false
flag.Visit(func(f *flag.Flag) {
if slices.Contains(flags, f.Name) {
found = true
return
}
})
return found
}

31
go.mod
View File

@ -1,18 +1,35 @@
module github.com/onyx-and-iris/vbantxt module github.com/onyx-and-iris/vbantxt
go 1.23.0 go 1.25.0
toolchain go1.24.1
require ( require (
github.com/BurntSushi/toml v1.5.0 github.com/charmbracelet/log v0.4.2
github.com/sirupsen/logrus v1.9.3 github.com/peterbourgon/ff/v4 v4.0.0-beta.1
github.com/stretchr/testify v1.9.0 github.com/stretchr/testify v1.10.0
) )
require ( require (
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/charmbracelet/colorprofile v0.4.2 // indirect
github.com/charmbracelet/lipgloss v1.1.0 // indirect
github.com/charmbracelet/x/ansi v0.11.6 // indirect
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-logfmt/logfmt v0.6.1 // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.21 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sys v0.31.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect
golang.org/x/sys v0.42.0 // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

68
go.sum
View File

@ -1,21 +1,61 @@
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/charmbracelet/colorprofile v0.4.2 h1:BdSNuMjRbotnxHSfxy+PCSa4xAmz7szw70ktAtWRYrY=
github.com/charmbracelet/colorprofile v0.4.2/go.mod h1:0rTi81QpwDElInthtrQ6Ni7cG0sDtwAd4C4le060fT8=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
github.com/charmbracelet/log v0.4.2 h1:hYt8Qj6a8yLnvR+h7MwsJv/XvmBJXiueUcI3cIxsyig=
github.com/charmbracelet/log v0.4.2/go.mod h1:qifHGX/tc7eluv2R6pWIpyHDDrrb/AG71Pf2ysQu5nw=
github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=
github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=
github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=
github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 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/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logfmt/logfmt v0.6.1 h1:4hvbpePJKnIzH1B+8OR/JPbTx37NktoI9LE2QZBBkvE=
github.com/go-logfmt/logfmt v0.6.1/go.mod h1:EV2pOAQoZaT1ZXZbqDl5hrymndi4SY9ED9/z6CO0XAk=
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/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
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/mattn/go-runewidth v0.0.21 h1:jJKAZiQH+2mIinzCJIaIG9Be1+0NR+5sz/lYEEjdM8w=
github.com/mattn/go-runewidth v0.0.21/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/peterbourgon/ff/v4 v4.0.0-beta.1 h1:hV8qRu3V7YfiSMsBSfPfdcznAvPQd3jI5zDddSrDoUc=
github.com/peterbourgon/ff/v4 v4.0.0-beta.1/go.mod h1:onQJUKipvCyFmZ1rIYwFAh1BhPOvftb1uhvSI7krNLc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 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= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -5,24 +5,27 @@ BIN_DIR := bin
WINDOWS=$(BIN_DIR)/$(PROGRAM)_windows_amd64.exe WINDOWS=$(BIN_DIR)/$(PROGRAM)_windows_amd64.exe
LINUX=$(BIN_DIR)/$(PROGRAM)_linux_amd64 LINUX=$(BIN_DIR)/$(PROGRAM)_linux_amd64
VERSION=$(shell git log -n 1 --format=%h) MACOS=$(BIN_DIR)/$(PROGRAM)_darwin_amd64
VERSION=$(shell git describe --tags $(shell git rev-list --tags --max-count=1))
.DEFAULT_GOAL := build .DEFAULT_GOAL := build
.PHONY: fmt vet build windows linux test clean .PHONY: fmt vet build windows linux macos test clean
fmt: fmt:
$(GO) fmt ./... $(GO) fmt ./...
vet: fmt vet: fmt
$(GO) vet ./... $(GO) vet ./...
build: vet windows linux | $(BIN_DIR) build: vet windows linux macos | $(BIN_DIR)
@echo version: $(VERSION) @echo version: $(VERSION)
windows: $(WINDOWS) windows: $(WINDOWS)
linux: $(LINUX) linux: $(LINUX)
macos: $(MACOS)
$(WINDOWS): $(WINDOWS):
env GOOS=windows GOARCH=amd64 go build -v -o $(WINDOWS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/ env GOOS=windows GOARCH=amd64 go build -v -o $(WINDOWS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
@ -30,6 +33,9 @@ $(WINDOWS):
$(LINUX): $(LINUX):
env GOOS=linux GOARCH=amd64 go build -v -o $(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/ env GOOS=linux GOARCH=amd64 go build -v -o $(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
$(MACOS):
env GOOS=darwin GOARCH=amd64 go build -v -o $(MACOS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
test: test:
$(GO) test ./... $(GO) test ./...

View File

@ -3,7 +3,7 @@ package vbantxt
import ( import (
"time" "time"
log "github.com/sirupsen/logrus" "github.com/charmbracelet/log"
) )
// Option is a functional option type that allows us to configure the VbanTxt. // Option is a functional option type that allows us to configure the VbanTxt.
@ -19,18 +19,37 @@ func WithRateLimit(ratelimit time.Duration) Option {
// WithBPSOpt is a functional option to set the bps index for {VbanTxt}.packet. // WithBPSOpt is a functional option to set the bps index for {VbanTxt}.packet.
func WithBPSOpt(bps int) Option { func WithBPSOpt(bps int) Option {
return func(vt *VbanTxt) { return func(vt *VbanTxt) {
defaultBps := BpsOpts[vt.packet.bpsIndex]
bpsIndex := indexOf(BpsOpts, bps) bpsIndex := indexOf(BpsOpts, bps)
if bpsIndex == -1 { if bpsIndex == -1 {
log.Warnf("invalid bps value %d, expected one of %v, defaulting to 0", bps, BpsOpts) log.Warnf(
"invalid bps value %d, expected one of %v, defaulting to %d",
bps,
BpsOpts,
defaultBps,
)
return return
} }
vt.packet.bpsIndex = bpsIndex if bpsIndex > 255 {
log.Warnf("bps index %d too large for uint8, defaulting to %d", bpsIndex, defaultBps)
return
}
vt.packet.bpsIndex = uint8(bpsIndex)
} }
} }
// WithChannel is a functional option to set the channel for {VbanTxt}.packet. // WithChannel is a functional option to set the channel for {VbanTxt}.packet.
func WithChannel(channel int) Option { func WithChannel(channel int) Option {
return func(vt *VbanTxt) { return func(vt *VbanTxt) {
vt.packet.channel = channel if channel < 0 || channel > 255 {
log.Warnf(
"channel value %d out of range [0,255], defaulting to %d",
channel,
vt.packet.channel,
)
return
}
vt.packet.channel = uint8(channel)
} }
} }

View File

@ -3,12 +3,14 @@ package vbantxt
import ( import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"fmt"
log "github.com/sirupsen/logrus" "github.com/charmbracelet/log"
) )
const ( const (
vbanProtocolTxt = 0x40 vbanProtocolTxt = 0x40
vbanTxtUtf8 = 0x10
streamNameSz = 16 streamNameSz = 16
headerSz = 4 + 1 + 1 + 1 + 1 + 16 + 4 headerSz = 4 + 1 + 1 + 1 + 1 + 16 + 4
) )
@ -21,30 +23,44 @@ var BpsOpts = []int{
} }
type packet struct { type packet struct {
streamname []byte streamname [streamNameSz]byte
bpsIndex int bpsIndex uint8
channel int channel uint8
framecounter []byte framecounter uint32
hbuf *bytes.Buffer hbuf *bytes.Buffer
} }
// newPacket returns a packet struct with default values, framecounter at 0. // newPacket creates a new packet with the given stream name and default values for other fields.
func newPacket(streamname string) packet { // It validates the stream name length and ensures the default baud rate is present in BpsOpts.
streamnameBuf := make([]byte, streamNameSz) func newPacket(streamname string) (packet, error) {
copy(streamnameBuf, streamname) if len(streamname) > streamNameSz {
return packet{}, fmt.Errorf(
"streamname too long: %d chars, max %d",
len(streamname),
streamNameSz,
)
}
var streamnameBuf [streamNameSz]byte
copy(streamnameBuf[:], streamname)
bpsIndex := indexOf(BpsOpts, 256000)
if bpsIndex == -1 {
return packet{}, fmt.Errorf("default baud rate 256000 not found in BpsOpts")
}
return packet{ return packet{
streamname: streamnameBuf, streamname: streamnameBuf,
bpsIndex: 0, bpsIndex: uint8(bpsIndex),
channel: 0, channel: 0,
framecounter: make([]byte, 4), framecounter: 0,
hbuf: bytes.NewBuffer(make([]byte, headerSz)), hbuf: bytes.NewBuffer(make([]byte, 0, headerSz)),
} }, nil
} }
// sr defines the samplerate for the request. // sr defines the samplerate for the request.
func (p *packet) sr() byte { func (p *packet) sr() byte {
return byte(vbanProtocolTxt + p.bpsIndex) return byte(p.bpsIndex | vbanProtocolTxt)
} }
// nbc defines the channel of the request. // nbc defines the channel of the request.
@ -59,16 +75,21 @@ func (p *packet) header() []byte {
p.hbuf.WriteByte(p.sr()) p.hbuf.WriteByte(p.sr())
p.hbuf.WriteByte(byte(0)) p.hbuf.WriteByte(byte(0))
p.hbuf.WriteByte(p.nbc()) p.hbuf.WriteByte(p.nbc())
p.hbuf.WriteByte(byte(0x10)) p.hbuf.WriteByte(byte(vbanTxtUtf8))
p.hbuf.Write(p.streamname) p.hbuf.Write(p.streamname[:])
p.hbuf.Write(p.framecounter)
var frameBytes [4]byte
binary.LittleEndian.PutUint32(frameBytes[:], p.framecounter)
p.hbuf.Write(frameBytes[:])
return p.hbuf.Bytes() return p.hbuf.Bytes()
} }
// bumpFrameCounter increments the frame counter by 1. // bumpFrameCounter increments the frame counter by 1.
// The uint32 will safely wrap to 0 after reaching max value (4,294,967,295),
// which is expected behaviour for network protocol sequence numbers.
func (p *packet) bumpFrameCounter() { func (p *packet) bumpFrameCounter() {
x := binary.LittleEndian.Uint32(p.framecounter) p.framecounter++
binary.LittleEndian.PutUint32(p.framecounter, x+1)
log.Tracef("framecounter: %d", x) log.Debugf("framecounter: %d", p.framecounter)
} }

View File

@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"net" "net"
log "github.com/sirupsen/logrus" "github.com/charmbracelet/log"
) )
// udpConn represents the UDP client. // udpConn represents the UDP client.

View File

@ -4,26 +4,34 @@ import (
"fmt" "fmt"
"io" "io"
"time" "time"
"github.com/charmbracelet/log"
) )
// VbanTxt is used to send VBAN-TXT requests to a distant Voicemeeter/Matrix. // VbanTxt is used to send VBAN-TXT requests to a distant Voicemeeter/Matrix.
type VbanTxt struct { type VbanTxt struct {
udpConn io.WriteCloser conn io.WriteCloser
packet packet packet packet
ratelimit time.Duration ratelimit time.Duration
lastSend time.Time
} }
// New constructs a fully formed VbanTxt instance. This is the package's entry point. // 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. // 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) { func New(host string, port int, streamname string, options ...Option) (*VbanTxt, error) {
udpConn, err := newUDPConn(host, port) conn, err := newUDPConn(host, port)
if err != nil { if err != nil {
return nil, fmt.Errorf("error creating UDP client for (%s:%d): %w", host, port, err) return nil, fmt.Errorf("error creating UDP client for (%s:%d): %w", host, port, err)
} }
packet, err := newPacket(streamname)
if err != nil {
return nil, fmt.Errorf("error creating packet: %w", err)
}
vt := &VbanTxt{ vt := &VbanTxt{
udpConn: udpConn, conn: conn,
packet: newPacket(streamname), packet: packet,
ratelimit: time.Duration(20) * time.Millisecond, ratelimit: time.Duration(20) * time.Millisecond,
} }
@ -34,24 +42,32 @@ func New(host string, port int, streamname string, options ...Option) (*VbanTxt,
return vt, nil return vt, nil
} }
// Send is resonsible for firing each VBAN-TXT request. // Send is responsible for firing each VBAN-TXT request.
// It waits for {vt.ratelimit} time before returning. // It enforces rate limiting by waiting only when necessary.
func (vt VbanTxt) Send(cmd string) error { func (vt *VbanTxt) Send(cmd string) error {
_, err := vt.udpConn.Write(append(vt.packet.header(), []byte(cmd)...)) if elapsed := time.Since(vt.lastSend); elapsed < vt.ratelimit {
log.Debugf(
"Rate limit in effect. Waiting for %v before sending next command.",
vt.ratelimit-elapsed,
)
time.Sleep(vt.ratelimit - elapsed)
}
vt.lastSend = time.Now()
_, err := vt.conn.Write(append(vt.packet.header(), cmd...))
if err != nil { if err != nil {
return fmt.Errorf("error sending command (%s): %w", cmd, err) return fmt.Errorf("error sending command (%s): %w", cmd, err)
} }
vt.packet.bumpFrameCounter() vt.packet.bumpFrameCounter()
time.Sleep(vt.ratelimit)
return nil 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 { func (vt *VbanTxt) Close() error {
err := vt.udpConn.Close() err := vt.conn.Close()
if err != nil { if err != nil {
return fmt.Errorf("error attempting to close UDP Client: %w", err) return fmt.Errorf("error attempting to close UDP Client: %w", err)
} }

View File

@ -4,10 +4,12 @@ import (
"bufio" "bufio"
"bytes" "bytes"
_ "embed" _ "embed"
"os"
"testing" "testing"
"github.com/onyx-and-iris/vbantxt"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/onyx-and-iris/vbantxt"
) )
//go:embed testdata/vm.txt //go:embed testdata/vm.txt
@ -28,14 +30,14 @@ func run(t *testing.T, client *vbantxt.VbanTxt, script []byte) {
} }
func TestSendVm(t *testing.T) { func TestSendVm(t *testing.T) {
client, err := vbantxt.New("localhost", 6980, "onyx") client, err := vbantxt.New(os.Getenv("VBANTXT_HOST"), 6980, os.Getenv("VBANTXT_STREAMNAME"))
require.NoError(t, err) require.NoError(t, err)
run(t, client, vm) run(t, client, vm)
} }
func TestSendMatrix(t *testing.T) { func TestSendMatrix(t *testing.T) {
client, err := vbantxt.New("localhost", 6990, "onyx") client, err := vbantxt.New(os.Getenv("VBANTXT_HOST"), 6990, os.Getenv("VBANTXT_STREAMNAME"))
require.NoError(t, err) require.NoError(t, err)
run(t, client, matrix) run(t, client, matrix)