Naposledy aktivní 1738749288

Use this script to send vban text requests over a network

Revize 4075e4a83477f29993d18526ef00bd1c90d48df8

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 def __init__(self, **kwargs):
110 defaultkwargs = {
111 'host': 'localhost',
112 'port': 6980,
113 'streamname': 'Command1',
114 'bps_index': 0,
115 'channel': 0,
116 'delay': 0.02,
117 }
118 defaultkwargs.update(kwargs)
119 self.__dict__.update(defaultkwargs)
120 self._request = RequestPacket(
121 RTHeader(self.streamname, self.bps_index, self.channel)
122 )
123 self.lastsent = 0
124
125 def __enter__(self):
126 self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
127 return self
128
129 def __exit__(self, exc_type, exc_value, traceback):
130 self._sock.close()
131
132 @ratelimit
133 def sendtext(self, text: str):
134 """
135 Sends a text message to the specified host and port.
136 Args:
137 text (str): The text message to be sent.
138 """
139
140 self._sock.sendto(self._request.encode(text), (self.host, self.port))
141
142 self._request.bump_framecounter()
143
144
145def conn_from_toml(filepath: str = 'config.toml') -> dict:
146 """
147 Reads a TOML configuration file and returns its contents as a dictionary.
148 Args:
149 filepath (str): The path to the TOML file. Defaults to "config.toml".
150 Returns:
151 dict: The contents of the TOML file as a dictionary.
152 Example:
153 # config.toml
154 host = "localhost"
155 port = 6980
156 streamname = "Command1"
157 """
158
159 pn = Path(filepath)
160 if not pn.exists():
161 logger.info(
162 f'no {pn} found, using defaults: localhost:6980 streamname: Command1'
163 )
164 return {}
165
166 try:
167 with open(pn, 'rb') as f:
168 return tomllib.load(f)
169 except tomllib.TOMLDecodeError as e:
170 raise ValueError(f'Error decoding TOML file: {e}') from e
171
172
173def parse_args() -> argparse.Namespace:
174 """
175 Parse command-line arguments.
176 Returns:
177 argparse.Namespace: Parsed command-line arguments.
178 Command-line arguments:
179 --log-level (str): Set the logging level. Choices are "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL". Default is "INFO".
180 --config (str): Path to config file. Default is "config.toml".
181 -i, --input-file (argparse.FileType): Input file to read from. Default is sys.stdin.
182 text (str, optional): Text to send.
183 """
184
185 parser = argparse.ArgumentParser(description='Voicemeeter VBAN Send Text CLI')
186 parser.add_argument(
187 '--log-level',
188 type=str,
189 choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
190 default='INFO',
191 help='Set the logging level',
192 )
193 parser.add_argument(
194 '--config', type=str, default='config.toml', help='Path to config file'
195 )
196 parser.add_argument(
197 '-i',
198 '--input-file',
199 type=argparse.FileType('r'),
200 default=sys.stdin,
201 )
202 parser.add_argument('text', nargs='?', type=str, help='Text to send')
203 return parser.parse_args()
204
205
206def main(config: dict):
207 """
208 Main function to send text using VbanSendText.
209 Args:
210 config (dict): Configuration dictionary for VbanSendText.
211 Behavior:
212 - If 'args.text' is provided, sends the text and returns.
213 - Otherwise, reads lines from 'args.input_file', strips whitespace, and sends each line.
214 - Stops reading and sending if a line equals "Q".
215 - Logs each line being sent at the debug level.
216 """
217
218 with VbanSendText(**config) as vban:
219 if args.text:
220 vban.sendtext(args.text)
221 return
222
223 for line in args.input_file:
224 line = line.strip()
225 if line.upper() == 'Q':
226 break
227
228 logger.debug(f'Sending {line}')
229 vban.sendtext(line)
230
231
232if __name__ == '__main__':
233 args = parse_args()
234
235 logging.basicConfig(level=args.log_level)
236
237 main(conn_from_toml(args.config))
238