text
stringlengths
1
93.6k
# <FILESEP>
import asyncio
import logging
import time
from const import (
ERROR_LOOKBACK_MIN,
MAX_ERROR_COUNT,
MAX_RETRY_ATTEMPT,
UDPC_UPDATE_CHECK_TIMEOUT,
)
from juicebox_telnet import JuiceboxTelnet
_LOGGER = logging.getLogger(__name__)
class JuiceboxUDPCUpdater:
def __init__(
self,
juicebox_host,
jpp_host,
telnet_port,
udpc_port=8047,
telnet_timeout=None,
loglevel=None,
):
if loglevel is not None:
_LOGGER.setLevel(loglevel)
self._juicebox_host = juicebox_host
self._jpp_host = jpp_host
self._udpc_port = udpc_port
self._telnet_port = telnet_port
self._telnet_timeout = telnet_timeout
self._default_sleep_interval = 30
self._udpc_update_loop_task = None
self._telnet = None
self._error_count = 0
self._error_timestamp_list = []
async def start(self):
_LOGGER.info("Starting JuiceboxUDPCUpdater")
await self._connect()
async def close(self):
if self._telnet is not None:
await self._telnet.close()
self._telnet = None
async def _connect(self):
connect_attempt = 1
while (
self._telnet is None
and connect_attempt <= MAX_RETRY_ATTEMPT
and self._error_count < MAX_ERROR_COUNT
):
_LOGGER.debug(
f"Telnet connection attempt {connect_attempt} of {MAX_RETRY_ATTEMPT}"
)
connect_attempt += 1
self._telnet = JuiceboxTelnet(
self._juicebox_host,
self._telnet_port,
loglevel=_LOGGER.getEffectiveLevel(),
timeout=self._telnet_timeout,
)
try:
await self._telnet.open()
except TimeoutError as e:
_LOGGER.warning(
"JuiceboxUDPCUpdater Telnet Timeout. Reconnecting. "
f"({e.__class__.__qualname__}: {e})"
)
await self._add_error()
await self._telnet.close()
self._telnet = None
pass
except ConnectionResetError as e:
_LOGGER.warning(
"JuiceboxUDPCUpdater Telnet Connection Error. Reconnecting. "
f"({e.__class__.__qualname__}: {e})"
)
await self._add_error()
await self._telnet.close()
self._telnet = None
pass
if self._telnet is None:
raise ChildProcessError("JuiceboxUDPCUpdater: Unable to connect to Telnet.")
if self._udpc_update_loop_task is None or self._udpc_update_loop_task.done():
self._udpc_update_loop_task = await self._udpc_update_loop()
self._loop.create_task(self._udpc_update_loop_task)
_LOGGER.info("JuiceboxUDPCUpdater Connected to Juicebox Telnet")
async def _udpc_update_loop(self):
_LOGGER.debug("Starting JuiceboxUDPCUpdater Loop")
while self._error_count < MAX_ERROR_COUNT:
sleep_interval = self._default_sleep_interval
if self._telnet is None:
_LOGGER.warning(
"JuiceboxUDPCUpdater Telnet Connection Lost. Reconnecting."