Skip to content

Commit

Permalink
sync
Browse files Browse the repository at this point in the history
  • Loading branch information
iloveicedgreentea committed Jul 6, 2024
1 parent e9aa37f commit 4f112f1
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 41 deletions.
32 changes: 13 additions & 19 deletions custom_components/madvr/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
from typing import Any

import aiohttp
from madvr.errors import CannotConnect
from madvr.madvr import HeartBeatError, Madvr
import voluptuous as vol

from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PORT
from homeassistant.const import CONF_HOST, CONF_PORT

from .const import DEFAULT_NAME, DEFAULT_PORT, DOMAIN
from .errors import CannotConnect

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -45,32 +45,27 @@ async def async_step_user(
port = user_input[CONF_PORT]

try:
# get the mac address from device
# ensure we can connect and get the mac address from device
mac = await self._test_connection(host, port)
except CannotConnect:
_LOGGER.error("CannotConnect error caught")
errors["base"] = "cannot_connect"
mac = ""

if not mac:
_LOGGER.error("No MAC address found")
if errors.get("base") != "cannot_connect":
errors["base"] = "no_mac"
else:
if not mac:
errors["base"] = "no_mac"
if not errors:
_LOGGER.debug("MAC address found: %s", mac)
# this will prevent the user from adding the same device twice
# this will prevent the user from adding the same device twice and persist the mac address
await self.async_set_unique_id(mac)
self._abort_if_unique_id_configured()

if not errors:
_LOGGER.debug("Creating entry")
# persist the mac address between HA restarts
user_input[CONF_MAC] = mac
# create the entry
return self.async_create_entry(
title=DEFAULT_NAME,
data=user_input,
)
# Whether it's the first attempt or a retry, show the form

# this will show the form or allow the user to retry if there was an error
return self.async_show_form(
step_id="user",
data_schema=self.add_suggested_values_to_schema(
Expand Down Expand Up @@ -114,7 +109,6 @@ async def _test_connection(self, host: str, port: int) -> str:

async def _close_test_connection(self, madvr_client: Madvr) -> None:
"""Close the test connection."""
if madvr_client:
madvr_client.stop()
await madvr_client.async_cancel_tasks()
await madvr_client.close_connection()
madvr_client.stop()
await madvr_client.async_cancel_tasks()
await madvr_client.close_connection()
14 changes: 7 additions & 7 deletions custom_components/madvr/coordinator.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
"""Coordinator for handling data fetching and updates."""

from __future__ import annotations

import logging
from typing import Any
from typing import TYPE_CHECKING, Any

from madvr.madvr import Madvr

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_MAC
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

type MadVRConfigEntry = ConfigEntry[MadVRCoordinator]
if TYPE_CHECKING:
from . import MadVRConfigEntry


class MadVRCoordinator(DataUpdateCoordinator[dict[str, Any]]):
Expand All @@ -29,9 +30,8 @@ def __init__(
) -> None:
"""Initialize madvr coordinator."""
super().__init__(hass, _LOGGER, name=DOMAIN)
self.entry_id = self.config_entry.entry_id
# get the mac address from the config entry
self.mac = self.config_entry.data.get(CONF_MAC)
self.mac = self.config_entry.unique_id
assert self.mac
self.client = client
self.client.set_update_callback(self.handle_push_data)
_LOGGER.debug("MadVRCoordinator initialized with mac: %s", self.mac)
Expand Down
5 changes: 5 additions & 0 deletions custom_components/madvr/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Errors for the madvr component."""


class CannotConnect(Exception):
"""Error to indicate we cannot connect."""
30 changes: 15 additions & 15 deletions custom_components/madvr/remote.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
"""Support for MadVR remote control."""

from __future__ import annotations

from collections.abc import Iterable
import logging
from typing import Any
from typing import TYPE_CHECKING, Any, cast

from homeassistant.components.remote import RemoteEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from . import MadVRConfigEntry
if TYPE_CHECKING:
from . import MadVRConfigEntry
from .const import DOMAIN
from .coordinator import MadVRCoordinator

Expand All @@ -35,6 +38,7 @@ class MadvrRemote(CoordinatorEntity[MadVRCoordinator], RemoteEntity):
"""Remote entity for the MadVR integration."""

_attr_has_entity_name = True
_attr_name = None

def __init__(
self,
Expand All @@ -45,24 +49,20 @@ def __init__(
"""Initialize the remote entity."""
super().__init__(coordinator)
self.madvr_client = coordinator.client
self._attr_name = None
self._attr_unique_id = f"{coordinator.mac}"
self._attr_unique_id = cast(str, coordinator.mac)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, cast(str, coordinator.mac))},
name="madVR Envy",
manufacturer="madVR",
model="Envy",
connections={(CONNECTION_NETWORK_MAC, cast(str, coordinator.mac))},
)

@property
def is_on(self) -> bool:
"""Return true if the device is on."""
return self.madvr_client.is_on

@property
def device_info(self) -> DeviceInfo:
"""Return the DeviceInfo of this madVR Envy."""
return DeviceInfo(
identifiers={(DOMAIN, self.coordinator.mac)},
name="madVR Envy",
manufacturer="madVR",
model="Envy",
)

async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the device."""
_LOGGER.debug("Turning off")
Expand Down

0 comments on commit 4f112f1

Please sign in to comment.