2022-09-28 18:13:07 +01:00
|
|
|
import logging
|
2022-06-16 16:10:06 +01:00
|
|
|
import socket
|
2023-08-04 23:13:58 +01:00
|
|
|
import threading
|
2022-06-16 16:10:06 +01:00
|
|
|
import time
|
|
|
|
from abc import ABCMeta, abstractmethod
|
2022-10-07 20:00:56 +01:00
|
|
|
from pathlib import Path
|
2023-06-25 03:40:14 +01:00
|
|
|
from queue import Queue
|
2023-07-12 04:52:50 +01:00
|
|
|
from typing import Iterable, Union
|
2022-06-16 16:10:06 +01:00
|
|
|
|
2023-06-25 03:40:14 +01:00
|
|
|
from .error import VBANCMDError
|
2022-09-28 18:03:22 +01:00
|
|
|
from .event import Event
|
2022-08-10 17:49:21 +01:00
|
|
|
from .packet import RequestHeader
|
2022-06-16 16:10:06 +01:00
|
|
|
from .subject import Subject
|
2023-07-12 04:52:50 +01:00
|
|
|
from .util import Socket, deep_merge, script
|
2023-06-25 03:40:14 +01:00
|
|
|
from .worker import Producer, Subscriber, Updater
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class VbanCmd(metaclass=ABCMeta):
|
2022-08-10 17:49:21 +01:00
|
|
|
"""Base class responsible for communicating with the VBAN RT Packet Service"""
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
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):
|
2023-06-25 03:40:14 +01:00
|
|
|
self.logger = logger.getChild(self.__class__.__name__)
|
|
|
|
self.event = Event({k: kwargs.pop(k) for k in ("pdirty", "ldirty")})
|
|
|
|
if not kwargs["ip"]:
|
|
|
|
kwargs |= self._conn_from_toml()
|
2022-06-16 16:10:06 +01:00
|
|
|
for attr, val in kwargs.items():
|
|
|
|
setattr(self, attr, val)
|
|
|
|
|
2022-08-10 17:49:21 +01:00
|
|
|
self.packet_request = RequestHeader(
|
2022-06-16 16:10:06 +01:00
|
|
|
name=self.streamname,
|
|
|
|
bps_index=self.BPS_OPTS.index(self.bps),
|
|
|
|
channel=self.channel,
|
|
|
|
)
|
|
|
|
self.socks = tuple(
|
2022-06-18 11:12:09 +01:00
|
|
|
socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for _ in Socket
|
2022-06-16 16:10:06 +01:00
|
|
|
)
|
2023-06-25 03:40:14 +01:00
|
|
|
self.subject = self.observer = Subject()
|
2022-10-04 15:42:36 +01:00
|
|
|
self.cache = {}
|
2022-10-19 14:20:23 +01:00
|
|
|
self._pdirty = False
|
2022-10-19 14:32:54 +01:00
|
|
|
self._ldirty = False
|
2023-07-05 19:20:57 +01:00
|
|
|
self._script = str()
|
2023-08-05 14:05:18 +01:00
|
|
|
self.stop_event = None
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def __str__(self):
|
|
|
|
"""Ensure subclasses override str magic method"""
|
|
|
|
pass
|
|
|
|
|
2023-06-25 03:40:14 +01:00
|
|
|
def _conn_from_toml(self) -> dict:
|
|
|
|
try:
|
|
|
|
import tomllib
|
|
|
|
except ModuleNotFoundError:
|
|
|
|
import tomli as tomllib
|
|
|
|
|
|
|
|
def get_filepath():
|
|
|
|
filepaths = [
|
|
|
|
Path.cwd() / "vban.toml",
|
2023-07-11 20:27:52 +01:00
|
|
|
Path.cwd() / "configs" / "vban.toml",
|
2023-06-25 03:40:14 +01:00
|
|
|
Path.home() / ".config" / "vban-cmd" / "vban.toml",
|
2023-07-11 20:27:52 +01:00
|
|
|
Path.home() / "Documents" / "Voicemeeter" / "configs" / "vban.toml",
|
2023-06-25 03:40:14 +01:00
|
|
|
]
|
|
|
|
for filepath in filepaths:
|
|
|
|
if filepath.exists():
|
|
|
|
return filepath
|
|
|
|
|
|
|
|
if filepath := get_filepath():
|
|
|
|
with open(filepath, "rb") as f:
|
|
|
|
conn = tomllib.load(f)
|
2023-06-25 13:58:19 +01:00
|
|
|
assert (
|
2023-07-11 20:27:52 +01:00
|
|
|
"connection" in conn and "ip" in conn["connection"]
|
|
|
|
), "expected [connection][ip] in vban config"
|
2023-06-25 03:40:14 +01:00
|
|
|
return conn["connection"]
|
2023-07-11 20:27:52 +01:00
|
|
|
raise VBANCMDError("no ip provided and no vban.toml located.")
|
2022-10-07 20:00:56 +01:00
|
|
|
|
2022-06-16 16:10:06 +01:00
|
|
|
def __enter__(self):
|
|
|
|
self.login()
|
|
|
|
return self
|
|
|
|
|
2023-08-02 17:19:08 +01:00
|
|
|
def login(self) -> None:
|
2023-07-05 14:08:27 +01:00
|
|
|
"""Starts the subscriber and updater threads (unless in outbound mode)"""
|
|
|
|
if not self.outbound:
|
2023-07-05 02:55:42 +01:00
|
|
|
self.event.info()
|
|
|
|
|
2023-08-04 23:13:58 +01:00
|
|
|
self.stop_event = threading.Event()
|
|
|
|
self.stop_event.clear()
|
|
|
|
self.subscriber = Subscriber(self, self.stop_event)
|
2023-07-05 02:55:42 +01:00
|
|
|
self.subscriber.start()
|
|
|
|
|
|
|
|
queue = Queue()
|
|
|
|
self.updater = Updater(self, queue)
|
|
|
|
self.updater.start()
|
2023-08-04 23:13:58 +01:00
|
|
|
self.producer = Producer(self, queue, self.stop_event)
|
2023-07-05 02:55:42 +01:00
|
|
|
self.producer.start()
|
2022-06-16 16:10:06 +01:00
|
|
|
|
2023-07-08 17:25:38 +01:00
|
|
|
self.logger.info(
|
2023-07-11 20:27:52 +01:00
|
|
|
"Successfully logged into VBANCMD {kind} with ip='{ip}', port={port}, streamname='{streamname}'".format(
|
2023-07-08 17:25:38 +01:00
|
|
|
**self.__dict__
|
|
|
|
)
|
|
|
|
)
|
2022-09-28 18:13:07 +01:00
|
|
|
|
2023-08-04 23:13:58 +01:00
|
|
|
def stopped(self):
|
2023-08-05 14:05:18 +01:00
|
|
|
return self.stop_event is None or self.stop_event.is_set()
|
2023-08-04 23:13:58 +01:00
|
|
|
|
2023-07-05 19:20:57 +01:00
|
|
|
def _set_rt(self, cmd: str, val: Union[str, float]):
|
2022-06-16 16:10:06 +01:00
|
|
|
"""Sends a string request command over a network."""
|
2022-08-08 13:43:19 +01:00
|
|
|
self.socks[Socket.request].sendto(
|
2023-07-05 19:20:57 +01:00
|
|
|
self.packet_request.header + f"{cmd}={val};".encode(),
|
2022-06-16 16:10:06 +01:00
|
|
|
(socket.gethostbyname(self.ip), self.port),
|
|
|
|
)
|
2023-06-25 13:58:19 +01:00
|
|
|
self.packet_request.framecounter = (
|
|
|
|
int.from_bytes(self.packet_request.framecounter, "little") + 1
|
|
|
|
).to_bytes(4, "little")
|
2023-07-05 19:20:57 +01:00
|
|
|
self.cache[cmd] = val
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
@script
|
2023-07-05 19:20:57 +01:00
|
|
|
def sendtext(self, script):
|
2022-06-16 16:10:06 +01:00
|
|
|
"""Sends a multiple parameter string over a network."""
|
2023-06-25 03:40:14 +01:00
|
|
|
self.socks[Socket.request].sendto(
|
2023-07-05 19:20:57 +01:00
|
|
|
self.packet_request.header + script.encode(),
|
2023-06-25 03:40:14 +01:00
|
|
|
(socket.gethostbyname(self.ip), self.port),
|
|
|
|
)
|
2023-06-25 13:58:19 +01:00
|
|
|
self.packet_request.framecounter = (
|
|
|
|
int.from_bytes(self.packet_request.framecounter, "little") + 1
|
|
|
|
).to_bytes(4, "little")
|
2023-07-08 17:25:38 +01:00
|
|
|
self.logger.debug(f"sendtext: {script}")
|
2022-06-16 16:10:06 +01:00
|
|
|
time.sleep(self.DELAY)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def type(self) -> str:
|
|
|
|
"""Returns the type of Voicemeeter installation."""
|
|
|
|
return self.public_packet.voicemeetertype
|
|
|
|
|
|
|
|
@property
|
|
|
|
def version(self) -> str:
|
2022-06-17 17:52:09 +01:00
|
|
|
"""Returns Voicemeeter's version as a string"""
|
2022-10-04 15:42:36 +01:00
|
|
|
return "{0}.{1}.{2}.{3}".format(*self.public_packet.voicemeeterversion)
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
@property
|
|
|
|
def pdirty(self):
|
|
|
|
"""True iff a parameter has changed"""
|
2022-07-07 00:48:15 +01:00
|
|
|
return self._pdirty
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
@property
|
|
|
|
def ldirty(self):
|
|
|
|
"""True iff a level value has changed."""
|
2022-10-04 15:42:36 +01:00
|
|
|
return self._ldirty
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
@property
|
|
|
|
def public_packet(self):
|
|
|
|
return self._public_packet
|
|
|
|
|
2023-08-02 17:19:08 +01:00
|
|
|
def clear_dirty(self) -> None:
|
2022-06-16 16:10:06 +01:00
|
|
|
while self.pdirty:
|
2022-10-19 14:20:23 +01:00
|
|
|
time.sleep(self.DELAY)
|
2022-06-16 16:10:06 +01:00
|
|
|
|
2022-07-06 13:40:46 +01:00
|
|
|
def _get_levels(self, packet) -> Iterable:
|
|
|
|
"""
|
|
|
|
returns both level arrays (strip_levels, bus_levels) BEFORE math conversion
|
2022-06-16 16:10:06 +01:00
|
|
|
|
2022-07-06 13:40:46 +01:00
|
|
|
strip levels in PREFADER mode.
|
|
|
|
"""
|
|
|
|
return (
|
2022-10-04 15:42:36 +01:00
|
|
|
packet.inputlevels,
|
|
|
|
packet.outputlevels,
|
2022-06-16 16:10:06 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
def apply(self, data: dict):
|
|
|
|
"""
|
|
|
|
Sets all parameters of a dict
|
|
|
|
|
|
|
|
minor delay between each recursion
|
|
|
|
"""
|
|
|
|
|
2023-08-09 17:03:55 +01:00
|
|
|
def target(key):
|
|
|
|
kls, m2, *rem = key.split("-")
|
|
|
|
match kls:
|
|
|
|
case "strip" | "bus" | "button":
|
|
|
|
index = m2
|
|
|
|
target = getattr(self, kls)
|
|
|
|
case "vban":
|
|
|
|
dir = f"{m2.rstrip('stream')}stream"
|
|
|
|
index = rem[0]
|
|
|
|
target = getattr(self.vban, dir)
|
|
|
|
case _:
|
|
|
|
ERR_MSG = f"invalid config key '{kls}'"
|
|
|
|
self.logger.error(ERR_MSG)
|
|
|
|
raise ValueError(ERR_MSG)
|
|
|
|
return target[int(index)]
|
|
|
|
|
|
|
|
[target(key).apply(di).then_wait() for key, di in data.items()]
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
def apply_config(self, name):
|
|
|
|
"""applies a config from memory"""
|
2023-07-11 20:27:52 +01:00
|
|
|
ERR_MSG = (
|
2022-06-16 16:10:06 +01:00
|
|
|
f"No config with name '{name}' is loaded into memory",
|
|
|
|
f"Known configs: {list(self.configs.keys())}",
|
|
|
|
)
|
|
|
|
try:
|
2023-07-12 04:52:50 +01:00
|
|
|
config = self.configs[name]
|
2023-07-08 17:25:38 +01:00
|
|
|
except KeyError as e:
|
2023-07-11 20:27:52 +01:00
|
|
|
self.logger.error(("\n").join(ERR_MSG))
|
|
|
|
raise VBANCMDError(("\n").join(ERR_MSG)) from e
|
|
|
|
|
|
|
|
if "extends" in config:
|
2023-07-12 04:52:50 +01:00
|
|
|
extended = config["extends"]
|
|
|
|
config = {
|
|
|
|
k: v
|
|
|
|
for k, v in deep_merge(self.configs[extended], config)
|
|
|
|
if k not in ("extends")
|
|
|
|
}
|
2023-07-11 20:27:52 +01:00
|
|
|
self.logger.debug(
|
|
|
|
f"profile '{name}' extends '{extended}', profiles merged.."
|
|
|
|
)
|
|
|
|
self.apply(config)
|
|
|
|
self.logger.info(f"Profile '{name}' applied!")
|
2022-06-16 16:10:06 +01:00
|
|
|
|
2023-08-02 17:19:08 +01:00
|
|
|
def logout(self) -> None:
|
2023-08-04 23:13:58 +01:00
|
|
|
if not self.stopped():
|
|
|
|
self.logger.debug("events thread shutdown started")
|
|
|
|
self.stop_event.set()
|
|
|
|
self.subscriber.join() # wait for subscriber thread to complete cycle
|
2022-06-16 16:10:06 +01:00
|
|
|
[sock.close() for sock in self.socks]
|
2022-09-29 11:48:30 +01:00
|
|
|
self.logger.info(f"{type(self).__name__}: Successfully logged out of {self}")
|
2022-06-16 16:10:06 +01:00
|
|
|
|
2023-08-02 17:19:08 +01:00
|
|
|
def __exit__(self, exc_type, exc_value, exc_traceback) -> None:
|
2022-06-16 16:10:06 +01:00
|
|
|
self.logout()
|