Last active 1738749288

Use this script to send vban text requests over a network

Revision f9333423a9681baad9b3b54886be6fb5870f80fa

sendtext.py Raw
1#!/usr/bin/env python3
2
3# MIT License
4#
5# Copyright (c) 2025 Onyx and Iris
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the "Software"), to deal
9# in the Software without restriction, including without limitation the rights
10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11# copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in all
15# copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23# SOFTWARE.
24
25import argparse
26import logging
27import socket
28import sys
29import time
30from dataclasses import dataclass
31from pathlib import Path
32from typing import Callable
33
34import tomllib
35
36logger = logging.getLogger(__name__)
37
38
39@dataclass
40class RTHeader:
41 name: str
42 bps_index: int
43 channel: int
44 VBAN_PROTOCOL_TXT = 0x40
45 framecounter: bytes = (0).to_bytes(4, 'little')
46
47 def __sr(self) -> bytes:
48 return (RTHeader.VBAN_PROTOCOL_TXT + self.bps_index).to_bytes(1, 'little')
49
50 def __nbc(self) -> bytes:
51 return (self.channel).to_bytes(1, 'little')
52
53 def build(self) -> bytes:
54 header = 'VBAN'.encode('utf-8')
55 header += self.__sr()
56 header += (0).to_bytes(1, 'little')
57 header += self.__nbc()
58 header += (0x10).to_bytes(1, 'little')
59 header += self.name.encode() + bytes(16 - len(self.name))
60 header += RTHeader.framecounter
61 return header
62
63
64class RequestPacket:
65 def __init__(self, header: RTHeader):
66 self.header = header
67
68 def encode(self, text: str) -> bytes:
69 return self.header.build() + text.encode('utf-8')
70
71 def bump_framecounter(self) -> None:
72 self.header.framecounter = (
73 int.from_bytes(self.header.framecounter, 'little') + 1
74 ).to_bytes(4, 'little')
75
76 logger.debug(
77 f'framecounter: {int.from_bytes(self.header.framecounter, "little")}'
78 )
79
80
81def ratelimit(func: Callable) -> Callable:
82 """
83 Decorator to enforce a rate limit on a function.
84 This decorator ensures that the decorated function is not called more frequently
85 than the specified delay. If the function is called before the delay has passed
86 since the last call, it will wait for the remaining time before executing.
87 Args:
88 func (callable): The function to be decorated.
89 Returns:
90 callable: The wrapped function with rate limiting applied.
91 Example:
92 @ratelimit
93 def send_message(self, message):
94 # Function implementation
95 pass
96 """
97
98 def wrapper(self, *args, **kwargs):
99 now = time.time()
100 if now - self.lastsent < self.delay:
101 time.sleep(self.delay - (now - self.lastsent))
102 self.lastsent = time.time()
103 return func(self, *args, **kwargs)
104
105 return wrapper
106
107
108class VbanSendText:
109 # fmt: off
110 BPS_OPTS = [
111 0, 110, 150, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 31250,
112 38400, 57600, 115200, 128000, 230400, 250000, 256000, 460800, 921600,
113 1000000, 1500000, 2000000, 3000000
114 ]
115 # fmt: on
116
117 def __init__(self, **kwargs):
118 defaultkwargs = {
119 'host': 'localhost',
120 'port': 6980,
121 'streamname': 'Command1',
122 'bps': 256000,
123 'channel': 0,
124 'delay': 0.02,
125 }
126 defaultkwargs.update(kwargs)
127 self.__dict__.update(defaultkwargs)
128 self._request = RequestPacket(
129 RTHeader(
130 self.streamname, VbanSendText.BPS_OPTS.index(self.bps), self.channel
131 )
132 )
133 self.lastsent = 0
134
135 def __enter__(self):
136 self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
137 return self
138
139 def __exit__(self, exc_type, exc_value, traceback):
140 self._sock.close()
141
142 @ratelimit
143 def sendtext(self, text: str):
144 """
145 Sends a text message to the specified host and port.
146 Args:
147 text (str): The text message to be sent.
148 """
149
150 self._sock.sendto(self._request.encode(text), (self.host, self.port))
151
152 self._request.bump_framecounter()
153
154
155def conn_from_toml(filepath: str = 'config.toml') -> dict:
156 """
157 Reads a TOML configuration file and returns its contents as a dictionary.
158 Args:
159 filepath (str): The path to the TOML file. Defaults to "config.toml".
160 Returns:
161 dict: The contents of the TOML file as a dictionary.
162 Example:
163 # config.toml
164 host = "localhost"
165 port = 6980
166 streamname = "Command1"
167 """
168
169 pn = Path(filepath)
170 if not pn.exists():
171 logger.info(
172 f'no {pn} found, using defaults: localhost:6980 streamname: Command1'
173 )
174 return {}
175
176 try:
177 with open(pn, 'rb') as f:
178 return tomllib.load(f)
179 except tomllib.TOMLDecodeError as e:
180 raise ValueError(f'Error decoding TOML file: {e}') from e
181
182
183def parse_args() -> argparse.Namespace:
184 """
185 Parse command-line arguments.
186 Returns:
187 argparse.Namespace: Parsed command-line arguments.
188 Command-line arguments:
189 --log-level (str): Set the logging level. Choices are "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL". Default is "INFO".
190 --config (str): Path to config file. Default is "config.toml".
191 -i, --input-file (argparse.FileType): Input file to read from. Default is sys.stdin.
192 text (str, optional): Text to send.
193 """
194
195 parser = argparse.ArgumentParser(description='Voicemeeter VBAN Send Text CLI')
196 parser.add_argument(
197 '--log-level',
198 type=str,
199 choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
200 default='INFO',
201 help='Set the logging level',
202 )
203 parser.add_argument(
204 '--config', type=str, default='config.toml', help='Path to config file'
205 )
206 parser.add_argument(
207 '-i',
208 '--input-file',
209 type=argparse.FileType('r'),
210 default=sys.stdin,
211 )
212 parser.add_argument('text', nargs='?', type=str, help='Text to send')
213 return parser.parse_args()
214
215
216def main(config: dict):
217 """
218 Main function to send text using VbanSendText.
219 Args:
220 config (dict): Configuration dictionary for VbanSendText.
221 Behavior:
222 - If 'args.text' is provided, sends the text and returns.
223 - Otherwise, reads lines from 'args.input_file', strips whitespace, and sends each line.
224 - Stops reading and sending if a line equals "Q".
225 - Logs each line being sent at the debug level.
226 """
227
228 with VbanSendText(**config) as vban:
229 if args.text:
230 vban.sendtext(args.text)
231 return
232
233 for line in args.input_file:
234 line = line.strip()
235 if line.upper() == 'Q':
236 break
237
238 logger.debug(f'Sending {line}')
239 vban.sendtext(line)
240
241
242if __name__ == '__main__':
243 args = parse_args()
244
245 logging.basicConfig(level=args.log_level)
246
247 main(conn_from_toml(args.config))
248