From 4f71633c5eebe81910ef853c30fdfaa56cba0793 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mose=20M=C3=BCller?= Date: Tue, 16 Jan 2024 13:39:35 +0100 Subject: [PATCH] adds backend DeviceConnection component --- src/pydase/components/__init__.py | 2 ++ src/pydase/components/connection.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 src/pydase/components/connection.py diff --git a/src/pydase/components/__init__.py b/src/pydase/components/__init__.py index da271bf..91caee2 100644 --- a/src/pydase/components/__init__.py +++ b/src/pydase/components/__init__.py @@ -28,6 +28,7 @@ print(my_service.voltage.value) # Output: 5 """ from pydase.components.coloured_enum import ColouredEnum +from pydase.components.connection import DeviceConnection from pydase.components.image import Image from pydase.components.number_slider import NumberSlider @@ -35,4 +36,5 @@ __all__ = [ "NumberSlider", "Image", "ColouredEnum", + "DeviceConnection", ] diff --git a/src/pydase/components/connection.py b/src/pydase/components/connection.py new file mode 100644 index 0000000..9b43d76 --- /dev/null +++ b/src/pydase/components/connection.py @@ -0,0 +1,29 @@ +import asyncio +from abc import ABC, abstractmethod + +import pydase + + +class DeviceConnection(pydase.DataService, ABC): + def __init__(self) -> None: + super().__init__() + # self._autostart_tasks = {"_handle_connection": ()} # type: ignore + self._handle_connection_wait_time = 2.0 + + @abstractmethod + def connect(self) -> None: + """Tries to connect to the abstracted device.""" + ... + + @property + @abstractmethod + def available(self) -> bool: + """Checks if the abstracted device is available.""" + ... + + async def _handle_connection(self) -> None: + """Tries reconnecting to the device if it is not available.""" + while True: + if not self.available: + self.connect() + await asyncio.sleep(self._handle_connection_wait_time)