BAPSicle/helpers/device_manager.py

59 lines
1.7 KiB
Python
Raw Normal View History

from typing import Any, Dict, List, Optional
2020-11-03 21:24:45 +00:00
import sounddevice as sd
from helpers.os_environment import isLinux, isMacOS, isWindows
import glob
2020-11-03 21:24:45 +00:00
2021-04-08 19:53:51 +00:00
class DeviceManager:
2020-11-03 21:28:05 +00:00
@classmethod
2021-04-08 19:53:51 +00:00
def _isOutput(cls, device: Dict[str, Any]) -> bool:
2020-11-03 21:28:05 +00:00
return device["max_output_channels"] > 0
2020-11-03 21:24:45 +00:00
2020-11-03 21:28:05 +00:00
@classmethod
2021-04-04 22:14:30 +00:00
def _getAudioDevices(cls) -> sd.DeviceList:
2020-11-03 21:28:05 +00:00
# To update the list of devices
# Sadly this doesn't work on MacOS.
if not isMacOS():
sd._terminate()
sd._initialize()
2020-12-19 14:57:37 +00:00
devices: sd.DeviceList = sd.query_devices()
2020-11-03 21:28:05 +00:00
return devices
2020-11-03 21:24:45 +00:00
2020-11-03 21:28:05 +00:00
@classmethod
2021-04-04 22:14:30 +00:00
def getAudioOutputs(cls) -> List[Dict]:
outputs: List[Dict] = list(filter(cls._isOutput, cls._getAudioDevices()))
2021-04-08 19:53:51 +00:00
outputs = sorted(outputs, key=lambda k: k["name"])
2021-04-04 22:14:30 +00:00
return [{"name": None}] + outputs
@classmethod
def getSerialPorts(cls) -> List[Optional[str]]:
2021-04-08 19:53:51 +00:00
"""Lists serial port names
2021-04-08 19:53:51 +00:00
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
# TODO: Get list of COM ports properly. (Can't use )
if isWindows():
2021-04-08 19:53:51 +00:00
ports = ["COM%s" % (i + 1) for i in range(8)]
elif isLinux():
# this excludes your current terminal "/dev/tty"
2021-04-08 19:53:51 +00:00
ports = glob.glob("/dev/tty[A-Za-z]*")
elif isMacOS():
2021-04-08 19:53:51 +00:00
ports = glob.glob("/dev/tty.*")
else:
2021-04-08 19:53:51 +00:00
raise EnvironmentError("Unsupported platform")
valid: List[str] = ports
result: List[Optional[str]] = []
if len(valid) > 0:
valid.sort()
2021-04-08 19:53:51 +00:00
result.append(None) # Add the None option
result.extend(valid)
return result