Compare commits

..

No commits in common. "c46ca8a8c8ba98c2ffe8954cc95e14e3ef3387a1" and "98ec9b715f44655ead52c53d7f40db9ab8711049" have entirely different histories.

9 changed files with 80 additions and 128 deletions

View File

@ -548,7 +548,7 @@ You may pass the following optional keyword arguments:
- `channel`: int=0, channel on which to send the UDP requests.
- `pdirty`: boolean=False, parameter updates
- `ldirty`: boolean=False, level updates
- `script_ratelimit`: float | None=None, ratelimit for vban.sendtext() specifically.
- `script_ratelimit`: float=0.05, default to 20 script requests per second. This affects vban.sendtext() specifically.
- `timeout`: int=5, timeout for socket operations.
- `disable_rt_listeners`: boolean=False, set `True` if you don't wish to receive RT packets.
- You can still send Matrix string requests ending with `?` and receive a response.

View File

@ -1,6 +1,6 @@
[project]
name = "vban-cmd"
version = "2.10.2"
version = "2.10.1"
description = "Python interface for the VBAN RT Packet Service (Sendtext)"
authors = [{ name = "Onyx and Iris", email = "code@onyxandiris.online" }]
license = { text = "MIT" }

View File

@ -1,18 +1,6 @@
from .packet.enums import ServiceTypes, SubProtocols
class VBANCMDError(Exception):
"""Base VBANCMD Exception class."""
class VBANCMDConnectionError(VBANCMDError):
"""Exception raised when connection/timeout errors occur"""
class VBANCMDPacketError(VBANCMDError):
"""Exception raised when packet parsing errors occur"""
def __init__(self, message: str, protocol: SubProtocols, type_: ServiceTypes):
super().__init__(message)
self.protocol = protocol
self.type = type_

View File

@ -89,7 +89,7 @@ class FactoryBase(VbanCmd):
'streamname': 'Command1',
'bps': 256000,
'channel': 0,
'script_ratelimit': None, # if None or 0, no rate limit applied to script commands
'script_ratelimit': 0.05, # 20 commands per second, to avoid overloading Voicemeeter
'timeout': 5, # timeout on socket operations, in seconds
'disable_rt_listeners': False,
'sync': False,

View File

@ -48,18 +48,26 @@ class IRemote(abc.ABC):
def apply(self, data):
"""Sets all parameters of a dict for the channel."""
script = ''
def fget(attr, val):
if attr == 'mode':
return (getattr(self, attr), val, 1)
return (self, attr, val)
return (f'mode.{val}', 1)
elif attr == 'knob':
return ('', val)
return (attr, val)
for attr, val in data.items():
if not isinstance(val, dict):
if attr in dir(self): # avoid calling getattr (with hasattr)
target, attr, val = fget(attr, val)
setattr(target, attr, val)
else:
self.logger.error(f'invalid attribute {attr} for {self}')
attr, val = fget(attr, val)
if isinstance(val, bool):
val = 1 if val else 0
self._remote.cache[self._cmd(attr)] = val
script += f'{self._cmd(attr)}={val};'
else:
target = getattr(self, attr)
target.apply(val)
self._remote.sendtext(script)

View File

@ -2,7 +2,6 @@ import struct
from dataclasses import dataclass
from vban_cmd.enums import NBS
from vban_cmd.error import VBANCMDPacketError
from vban_cmd.kinds import KindMapClass
from .enums import ServiceTypes, StreamTypes, SubProtocols
@ -11,15 +10,6 @@ PINGPONG_PACKET_SIZE = 704 # Size of the PING/PONG header + payload in bytes
MAX_PACKET_SIZE = 1436
HEADER_SIZE = 4 + 1 + 1 + 1 + 1 + 16
STREAMNAME_MAX_LENGTH = 16
# fmt: off
BPS_OPTS = [
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,
]
# fmt: on
@dataclass
class VbanPingHeader:
@ -38,9 +28,7 @@ class VbanPingHeader:
@property
def streamname(self) -> bytes:
return self.name.encode('ascii')[:STREAMNAME_MAX_LENGTH].ljust(
STREAMNAME_MAX_LENGTH, b'\x00'
)
return self.name.encode('ascii')[:16].ljust(16, b'\x00')
@classmethod
def to_bytes(cls, framecounter: int = 0) -> bytes:
@ -76,9 +64,7 @@ class VbanPongHeader:
@property
def streamname(self) -> bytes:
return self.name.encode('ascii')[:STREAMNAME_MAX_LENGTH].ljust(
STREAMNAME_MAX_LENGTH, b'\x00'
)
return self.name.encode('ascii')[:16].ljust(16, b'\x00')
@classmethod
def from_bytes(cls, data: bytes):
@ -88,11 +74,7 @@ class VbanPongHeader:
# PONG responses use the same service type as PING (0x00)
# and are identified by having payload data
if parsed['format_nbc'] != ServiceTypes.PONG.value:
raise VBANCMDPacketError(
f'Not a PONG response packet: {parsed["format_nbc"]:02x}',
protocol=SubProtocols(parsed['format_sr'] & SubProtocols.MASK.value),
type_=ServiceTypes(parsed['format_nbc']),
)
raise ValueError(f'Not a PONG response packet: {parsed["format_nbc"]:02x}')
return cls(**parsed)
@ -151,7 +133,7 @@ class VbanRTPacket:
class VbanRTSubscribeHeader:
"""Represents the header of an RT subscription packet"""
_nbs: NBS = NBS.zero
nbs: NBS = NBS.zero
name: str = 'Register-RTP'
timeout: int = 15
@ -160,38 +142,36 @@ class VbanRTSubscribeHeader:
return b'VBAN'
@property
def sr(self) -> int:
return SubProtocols.SERVICE.value
def format_sr(self) -> bytes:
return SubProtocols.SERVICE.value.to_bytes(1, 'little')
@property
def nbs(self) -> int:
return self._nbs.value & 0xFF
def format_nbs(self) -> bytes:
return (self.nbs.value & 0xFF).to_bytes(1, 'little')
@property
def nbc(self) -> int:
return ServiceTypes.RTPACKETREGISTER.value
def format_nbc(self) -> bytes:
return ServiceTypes.RTPACKETREGISTER.value.to_bytes(1, 'little')
@property
def bit(self) -> int:
return self.timeout & 0xFF
def format_bit(self) -> bytes:
return (self.timeout & 0xFF).to_bytes(1, 'little')
@property
def streamname(self) -> bytes:
return self.name.encode()[:STREAMNAME_MAX_LENGTH].ljust(
STREAMNAME_MAX_LENGTH, b'\x00'
)
return self.name.encode('ascii') + bytes(16 - len(self.name))
@classmethod
def to_bytes(cls, nbs: NBS, framecounter: int) -> bytes:
header = cls(_nbs=nbs)
header = cls(nbs=nbs)
return struct.pack(
'<4s4B16sI',
header.vban,
header.sr,
header.nbs,
header.nbc,
header.bit,
header.format_sr[0],
header.format_nbs[0],
header.format_nbc[0],
header.format_bit[0],
header.streamname,
framecounter,
)
@ -202,64 +182,59 @@ class VbanRTRequestHeader:
"""Represents the header of an RT request packet"""
name: str
bps: int
bps_index: int
channel: int
framecounter: int = 0
def __post_init__(self):
if self.bps not in BPS_OPTS:
raise ValueError(
f'Invalid bps value: {self.bps}. Must be one of {BPS_OPTS}'
)
self.bps_index = BPS_OPTS.index(self.bps)
@property
def vban(self) -> bytes:
return b'VBAN'
@property
def sr(self) -> int:
return self.bps_index | SubProtocols.TEXT.value
def sr(self) -> bytes:
return (self.bps_index | SubProtocols.TEXT.value).to_bytes(1, 'little')
@property
def nbs(self) -> int:
return 0
def nbs(self) -> bytes:
return (0).to_bytes(1, 'little')
@property
def nbc(self) -> int:
return self.channel
def nbc(self) -> bytes:
return (self.channel).to_bytes(1, 'little')
@property
def bit(self) -> int:
return StreamTypes.UTF8.value
def bit(self) -> bytes:
return (StreamTypes.UTF8.value).to_bytes(1, 'little')
@property
def streamname(self) -> bytes:
return self.name.encode()[:STREAMNAME_MAX_LENGTH].ljust(
STREAMNAME_MAX_LENGTH, b'\x00'
)
return self.name.encode()[:16].ljust(16, b'\x00')
@classmethod
def to_bytes(cls, name: str, bps: int, channel: int, framecounter: int) -> bytes:
header = cls(name=name, bps=bps, channel=channel, framecounter=framecounter)
def to_bytes(
cls, name: str, bps_index: int, channel: int, framecounter: int
) -> bytes:
header = cls(
name=name, bps_index=bps_index, channel=channel, framecounter=framecounter
)
return struct.pack(
'<4s4B16sI',
header.vban,
header.sr,
header.nbs,
header.nbc,
header.bit,
header.sr[0],
header.nbs[0],
header.nbc[0],
header.bit[0],
header.streamname,
header.framecounter,
)
@classmethod
def encode_with_payload(
cls, name: str, bps: int, channel: int, framecounter: int, payload: str
cls, name: str, bps_index: int, channel: int, framecounter: int, payload: str
) -> bytes:
"""Creates the complete packet with header and payload."""
return cls.to_bytes(name, bps, channel, framecounter) + payload.encode()
return cls.to_bytes(name, bps_index, channel, framecounter) + payload.encode()
def _parse_vban_service_header(data: bytes) -> dict:
@ -278,10 +253,7 @@ def _parse_vban_service_header(data: bytes) -> dict:
# Verify this is a service protocol packet
protocol = format_sr & SubProtocols.MASK.value
if protocol != SubProtocols.SERVICE.value:
raise VBANCMDPacketError(
f'Invalid protocol in service header: {protocol:02x}',
protocol=SubProtocols(protocol),
)
raise ValueError(f'Not a service protocol packet: {protocol:02x}')
# Extract stream name and frame counter
name = data[8:24].rstrip(b'\x00').decode('utf-8', errors='ignore')
@ -314,9 +286,7 @@ class VbanRTResponseHeader:
@property
def streamname(self) -> bytes:
return self.name.encode()[:STREAMNAME_MAX_LENGTH].ljust(
STREAMNAME_MAX_LENGTH, b'\x00'
)
return self.name.encode('ascii') + bytes(16 - len(self.name))
@classmethod
def from_bytes(cls, data: bytes):
@ -325,10 +295,8 @@ class VbanRTResponseHeader:
# Validate this is an RTPacket response
if parsed['format_nbc'] != ServiceTypes.RTPACKET.value:
raise VBANCMDPacketError(
f'Not an RTPacket response packet: {parsed["format_nbc"]:02x}',
protocol=SubProtocols(parsed['format_sr'] & SubProtocols.MASK.value),
type_=ServiceTypes(parsed['format_nbc']),
raise ValueError(
f'Not an RTPacket response packet: {parsed["format_nbc"]:02x}'
)
return cls(**parsed)
@ -351,29 +319,16 @@ class VbanMatrixResponseHeader:
@property
def streamname(self) -> bytes:
return self.name.encode()[:STREAMNAME_MAX_LENGTH].ljust(
STREAMNAME_MAX_LENGTH, b'\x00'
)
return self.name.encode('ascii')[:16].ljust(16, b'\x00')
@classmethod
def from_bytes(cls, data: bytes):
"""Parse a matrix response packet from bytes."""
parsed = _parse_vban_service_header(data)
# Validate this is a service reply packet (dual encoding scheme)
# Validate this is a service reply packet
if parsed['format_nbs'] != ServiceTypes.FNCT_REPLY.value:
raise VBANCMDPacketError(
f'Not a service reply packet: {parsed["format_nbs"]:02x}',
protocol=SubProtocols(parsed['format_sr'] & SubProtocols.MASK.value),
type_=ServiceTypes(parsed['format_nbs']),
)
if parsed['format_nbc'] != ServiceTypes.REQUESTREPLY.value:
raise VBANCMDPacketError(
f'Not a request reply packet: {parsed["format_nbc"]:02x}',
protocol=SubProtocols(parsed['format_sr'] & SubProtocols.MASK.value),
type_=ServiceTypes(parsed['format_nbc']),
)
raise ValueError(f'Not a service reply packet: {parsed["format_nbs"]:02x}')
return cls(**parsed)

View File

@ -5,12 +5,12 @@ from typing import Iterator
from .error import VBANCMDConnectionError
def script_ratelimit(func):
"""script_ratelimit decorator for {VbanCmd}.sendtext, to prevent flooding the network with script requests."""
def ratelimit(func):
"""ratelimit decorator for {VbanCmd}.sendtext, to prevent flooding the network with script requests."""
def wrapper(*args, **kwargs):
self, *rem = args
if self.script_ratelimit:
if self.script_ratelimit > 0:
now = time.time()
elapsed = now - self._last_script_request_time
if elapsed < self.script_ratelimit:

View File

@ -17,7 +17,7 @@ from .packet.headers import (
)
from .packet.ping0 import VbanPing0Payload, VbanServerType
from .subject import Subject
from .util import bump_framecounter, deep_merge, pong_timeout, script_ratelimit
from .util import bump_framecounter, deep_merge, pong_timeout, ratelimit
from .worker import Producer, Subscriber, Updater
logger = logging.getLogger(__name__)
@ -27,6 +27,13 @@ class VbanCmd(abc.ABC):
"""Abstract Base Class for Voicemeeter VBAN Command Interfaces"""
DELAY = 0.001
# fmt: off
BPS_OPTS = [
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,
]
# fmt: on
def __init__(self, **kwargs):
self.logger = logger.getChild(self.__class__.__name__)
@ -196,7 +203,7 @@ class VbanCmd(abc.ABC):
self.sock.sendto(
VbanRTRequestHeader.encode_with_payload(
name=self.streamname,
bps=self.bps,
bps_index=self.BPS_OPTS.index(self.bps),
channel=self.channel,
framecounter=self._get_next_framecounter(),
payload=payload,
@ -209,7 +216,7 @@ class VbanCmd(abc.ABC):
self._send_request(f'{cmd}={val};')
self.cache[cmd] = val
@script_ratelimit
@ratelimit
def sendtext(self, script) -> str | None:
"""Sends a multiple parameter string over a network."""
self._send_request(script)

View File

@ -3,8 +3,7 @@ import threading
import time
from .enums import NBS
from .error import VBANCMDConnectionError, VBANCMDPacketError
from .packet.enums import SubProtocols
from .error import VBANCMDConnectionError
from .packet.headers import (
HEADER_SIZE,
VbanRTPacket,
@ -82,12 +81,7 @@ class Producer(threading.Thread):
try:
header = VbanRTResponseHeader.from_bytes(data[:HEADER_SIZE])
except VBANCMDPacketError as e:
match e.protocol:
case SubProtocols.SERVICE:
# Silently ignore periodic SERVICE packets unrelated to vban-cmd
pass
case _:
except ValueError as e:
self.logger.debug(f'Error parsing response packet: {e}')
continue