Beispiel #1
0
    async def connect(self) -> bool:
        """Connect to the Harmony Hub."""
        _LOGGER.debug("%s: Connecting", self._name)

        callbacks = {
            "config_updated": self._config_updated,
            "connect": self._connected,
            "disconnect": self._disconnected,
            "new_activity_starting": self._activity_starting,
            "new_activity": self._activity_started,
        }
        self._client = HarmonyClient(
            ip_address=self._address, callbacks=ClientCallbackType(**callbacks)
        )

        connected = False
        try:
            connected = await self._client.connect()
        except (asyncio.TimeoutError, aioexc.TimeOut) as err:
            await self._client.close()
            raise ConfigEntryNotReady(
                f"{self._name}: Connection timed-out to {self._address}:8088"
            ) from err
        except (ValueError, AttributeError) as err:
            await self._client.close()
            raise ConfigEntryNotReady(
                f"{self._name}: Error {err} while connected HUB at: {self._address}:8088"
            ) from err
        if not connected:
            await self._client.close()
            raise ConfigEntryNotReady(
                f"{self._name}: Unable to connect to HUB at: {self._address}:8088"
            )
Beispiel #2
0
 def _update_callbacks(self):
     callbacks = {
         "config_updated": self.new_config,
         "connect": self.got_connected,
         "disconnect": self.got_disconnected,
         "new_activity_starting": self.new_activity,
         "new_activity": self._new_activity_finished,
     }
     self._client.callbacks = ClientCallbackType(**callbacks)
Beispiel #3
0
 def _update_callbacks(self):
     callbacks = {
         "config_updated": self.new_config,
         "connect": self.got_connected,
         "disconnect": self.got_disconnected,
         "new_activity_starting": None,
         "new_activity": None,
     }
     if self._activity_notify:
         callbacks["new_activity_starting"] = self.new_activity
     else:
         callbacks["new_activity"] = self.new_activity
     self._client.callbacks = ClientCallbackType(**callbacks)
Beispiel #4
0
    def __init__(self,
                 ip_address: str,
                 protocol: PROTOCOL = None,
                 callbacks: ClientCallbackType = None,
                 loop: asyncio.AbstractEventLoop = None) -> None:
        _LOGGER.debug("%s: Initialize HUB", ip_address)
        self._ip_address = ip_address
        self._protocol = protocol
        self._callbacks = callbacks if callbacks is not None else \
            ClientCallbackType(None, None, None, None, None)
        self._loop = loop if loop else asyncio.get_event_loop()

        self._hub_config = ClientConfigType({}, {}, {}, {}, None, [], [])
        self._current_activity_id = None
        self._hub_connection = None

        # Get the queue on which JSON responses will be put
        self._response_queue = asyncio.Queue()

        # Get the Response Handler
        self._callback_handler = ResponseHandler(
            message_queue=self._response_queue, name=self.name)

        # Create the lock for sending commands or starting an activity
        self._snd_cmd_act_lck = asyncio.Lock()

        # Create the lock for getting HUB information.
        self._sync_lck = asyncio.Lock()

        # Create the activity start handler object when start activity is finished
        handler = copy.copy(handlers.HANDLER_START_ACTIVITY_FINISHED)
        handler.handler_obj = self._update_activity_callback
        self._callback_handler.register_handler(handler=handler)

        # Create the activity start handler object when start activity is finished
        handler = copy.copy(handlers.HANDLER_START_ACTIVITY_NOTIFY_STARTED)
        handler.handler_obj = self._update_start_activity_callback
        self._callback_handler.register_handler(handler=handler)

        # Create the activity start handler object when start activity is finished
        handler = copy.copy(handlers.HANDLER_STOP_ACTIVITY_NOTIFY_STARTED)
        handler.handler_obj = self._update_start_activity_callback
        self._callback_handler.register_handler(handler=handler)

        # Create the notification handler object
        handler = copy.copy(handlers.HANDLER_NOTIFY)
        handler.handler_obj = self._notification_callback
        self._callback_handler.register_handler(handler=handler)
Beispiel #5
0
    def __init__(self, hass, address: str, name: str, unique_id: str):
        """Initialize a data object."""
        super().__init__(hass)
        self._name = name
        self._unique_id = unique_id
        self._available = False

        callbacks = {
            "config_updated": self._config_updated,
            "connect": self._connected,
            "disconnect": self._disconnected,
            "new_activity_starting": self._activity_starting,
            "new_activity": self._activity_started,
        }
        self._client = HarmonyClient(ip_address=address,
                                     callbacks=ClientCallbackType(**callbacks))
Beispiel #6
0
    async def connect(self) -> bool:
        """Connect to the Harmony Hub."""
        _LOGGER.debug("%s: Connecting", self._name)

        callbacks = {
            "config_updated": self._config_updated,
            "connect": self._connected,
            "disconnect": self._disconnected,
            "new_activity_starting": self._activity_starting,
            "new_activity": self._activity_started,
        }
        self._client = HarmonyClient(ip_address=self._address,
                                     callbacks=ClientCallbackType(**callbacks))

        try:
            if not await self._client.connect():
                _LOGGER.warning("%s: Unable to connect to HUB", self._name)
                await self._client.close()
                return False
        except aioexc.TimeOut:
            _LOGGER.warning("%s: Connection timed-out", self._name)
            return False

        return True
Beispiel #7
0
async def listen_for_new_activities(client, _):
    def new_activity_starting(activity_info: tuple):
        activity_id, activity_name = activity_info
        if activity_id == -1:
            print(
                f"{datetime.today().strftime('%Y-%m-%d %H:%M:%S')} {client.name}: Powering off is starting."
            )
        else:
            print(
                f"{datetime.today().strftime('%Y-%m-%d %H:%M:%S')} {client.name}: New activity ID {activity_id} with name {activity_name} is starting."
            )

    def new_activity_started(activity_info: tuple):
        activity_id, activity_name = activity_info
        if activity_id == -1:
            print(
                f"{datetime.today().strftime('%Y-%m-%d %H:%M:%S')} {client.name}: Powering off completed."
            )
        else:
            print(
                f"{datetime.today().strftime('%Y-%m-%d %H:%M:%S')} {client.name}: New activity ID {activity_id} with name {activity_name} has started."
            )

    activity_id, activity_name = client.current_activity
    print(
        f"{datetime.today().strftime('%Y-%m-%d %H:%M:%S')} {client.name}: Current activity ID {activity_id} with name {activity_name}"
    )

    callbacks = {
        "config_updated": client.callbacks.config_updated,
        "connect": client.callbacks.connect,
        "disconnect": client.callbacks.disconnect,
        "new_activity_starting": new_activity_starting,
        "new_activity": new_activity_started,
    }
    client.callbacks = ClientCallbackType(**callbacks)