Skip to content

Commit 4b617db

Browse files
authored
Add Ruckus Unleashed integration (home-assistant#40002)
* Add Ruckus Unleashed integration * Tweak catches to better rely on CoordinatorEntity error handling, rename LoginError to AuthenticationError * Make router_update be a callback function * Make name property return hint match the newer value * Add entity to tracked set when restoring on boot * Add a device's MAC to the attributes
1 parent de300dd commit 4b617db

16 files changed

+690
-0
lines changed

CODEOWNERS

+1
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,7 @@ homeassistant/components/roku/* @ctalkington
364364
homeassistant/components/roomba/* @pschmitt @cyr-ius @shenxn
365365
homeassistant/components/roon/* @pavoni
366366
homeassistant/components/rpi_power/* @shenxn @swetoast
367+
homeassistant/components/ruckus_unleashed/* @gabe565
367368
homeassistant/components/safe_mode/* @home-assistant/core
368369
homeassistant/components/saj/* @fredericvl
369370
homeassistant/components/salt/* @bjornorri
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""The Ruckus Unleashed integration."""
2+
import asyncio
3+
4+
from pyruckus import Ruckus
5+
import voluptuous as vol
6+
7+
from homeassistant.config_entries import ConfigEntry
8+
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
9+
from homeassistant.core import HomeAssistant
10+
from homeassistant.exceptions import ConfigEntryNotReady
11+
12+
from .const import COORDINATOR, DOMAIN, PLATFORMS, UNDO_UPDATE_LISTENERS
13+
from .coordinator import RuckusUnleashedDataUpdateCoordinator
14+
15+
CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema({})}, extra=vol.ALLOW_EXTRA)
16+
17+
18+
async def async_setup(hass: HomeAssistant, entry: ConfigEntry) -> bool:
19+
"""Set up the Ruckus Unleashed component."""
20+
hass.data[DOMAIN] = {}
21+
return True
22+
23+
24+
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
25+
"""Set up Ruckus Unleashed from a config entry."""
26+
try:
27+
ruckus = await hass.async_add_executor_job(
28+
Ruckus,
29+
entry.data[CONF_HOST],
30+
entry.data[CONF_USERNAME],
31+
entry.data[CONF_PASSWORD],
32+
)
33+
except ConnectionError as error:
34+
raise ConfigEntryNotReady from error
35+
36+
coordinator = RuckusUnleashedDataUpdateCoordinator(hass, ruckus=ruckus)
37+
38+
await coordinator.async_refresh()
39+
if not coordinator.last_update_success:
40+
raise ConfigEntryNotReady
41+
42+
hass.data[DOMAIN][entry.entry_id] = {
43+
COORDINATOR: coordinator,
44+
UNDO_UPDATE_LISTENERS: [],
45+
}
46+
47+
for platform in PLATFORMS:
48+
hass.async_create_task(
49+
hass.config_entries.async_forward_entry_setup(entry, platform)
50+
)
51+
52+
return True
53+
54+
55+
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
56+
"""Unload a config entry."""
57+
unload_ok = all(
58+
await asyncio.gather(
59+
*[
60+
hass.config_entries.async_forward_entry_unload(entry, component)
61+
for component in PLATFORMS
62+
]
63+
)
64+
)
65+
if unload_ok:
66+
for listener in hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENERS]:
67+
listener()
68+
69+
hass.data[DOMAIN].pop(entry.entry_id)
70+
71+
return unload_ok
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""Config flow for Ruckus Unleashed integration."""
2+
from pyruckus import Ruckus
3+
from pyruckus.exceptions import AuthenticationError
4+
import voluptuous as vol
5+
6+
from homeassistant import config_entries, core, exceptions
7+
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
8+
9+
from .const import _LOGGER, DOMAIN # pylint:disable=unused-import
10+
11+
DATA_SCHEMA = vol.Schema({"host": str, "username": str, "password": str})
12+
13+
14+
async def validate_input(hass: core.HomeAssistant, data):
15+
"""Validate the user input allows us to connect.
16+
17+
Data has the keys from DATA_SCHEMA with values provided by the user.
18+
"""
19+
20+
try:
21+
ruckus = await hass.async_add_executor_job(
22+
Ruckus, data[CONF_HOST], data[CONF_USERNAME], data[CONF_PASSWORD]
23+
)
24+
except AuthenticationError as error:
25+
raise InvalidAuth from error
26+
except ConnectionError as error:
27+
raise CannotConnect from error
28+
29+
mesh_name = ruckus.mesh_name()
30+
31+
return {"title": mesh_name}
32+
33+
34+
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
35+
"""Handle a config flow for Ruckus Unleashed."""
36+
37+
VERSION = 1
38+
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
39+
40+
async def async_step_user(self, user_input=None):
41+
"""Handle the initial step."""
42+
errors = {}
43+
if user_input is not None:
44+
try:
45+
info = await validate_input(self.hass, user_input)
46+
except CannotConnect:
47+
errors["base"] = "cannot_connect"
48+
except InvalidAuth:
49+
errors["base"] = "invalid_auth"
50+
except Exception: # pylint: disable=broad-except
51+
_LOGGER.exception("Unexpected exception")
52+
errors["base"] = "unknown"
53+
else:
54+
await self.async_set_unique_id(user_input[CONF_HOST])
55+
self._abort_if_unique_id_configured()
56+
return self.async_create_entry(title=info["title"], data=user_input)
57+
58+
return self.async_show_form(
59+
step_id="user", data_schema=DATA_SCHEMA, errors=errors
60+
)
61+
62+
63+
class CannotConnect(exceptions.HomeAssistantError):
64+
"""Error to indicate we cannot connect."""
65+
66+
67+
class InvalidAuth(exceptions.HomeAssistantError):
68+
"""Error to indicate there is invalid auth."""
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
"""Constants for the Ruckus Unleashed integration."""
2+
import logging
3+
4+
DOMAIN = "ruckus_unleashed"
5+
PLATFORMS = ["device_tracker"]
6+
SCAN_INTERVAL = 180
7+
8+
_LOGGER = logging.getLogger(__name__)
9+
10+
COORDINATOR = "coordinator"
11+
UNDO_UPDATE_LISTENERS = "undo_update_listeners"
12+
13+
CLIENTS = "clients"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""Ruckus Unleashed DataUpdateCoordinator."""
2+
from datetime import timedelta
3+
4+
from pyruckus import Ruckus
5+
from pyruckus.exceptions import AuthenticationError
6+
7+
from homeassistant.core import HomeAssistant
8+
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
9+
10+
from .const import _LOGGER, CLIENTS, DOMAIN, SCAN_INTERVAL
11+
12+
13+
class RuckusUnleashedDataUpdateCoordinator(DataUpdateCoordinator):
14+
"""Coordinator to manage data from Ruckus Unleashed client."""
15+
16+
def __init__(self, hass: HomeAssistant, *, ruckus: Ruckus):
17+
"""Initialize global Ruckus Unleashed data updater."""
18+
self.ruckus = ruckus
19+
20+
update_interval = timedelta(seconds=SCAN_INTERVAL)
21+
22+
super().__init__(
23+
hass,
24+
_LOGGER,
25+
name=DOMAIN,
26+
update_interval=update_interval,
27+
)
28+
29+
async def _async_update_data(self) -> dict:
30+
"""Fetch Ruckus Unleashed data."""
31+
try:
32+
return {
33+
CLIENTS: await self.hass.async_add_executor_job(self.ruckus.clients)
34+
}
35+
except (AuthenticationError, ConnectionError) as error:
36+
raise UpdateFailed(error) from error
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
"""Support for Ruckus Unleashed devices."""
2+
from homeassistant.components.device_tracker import (
3+
ATTR_MAC,
4+
ATTR_SOURCE_TYPE,
5+
SOURCE_TYPE_ROUTER,
6+
)
7+
from homeassistant.components.device_tracker.config_entry import ScannerEntity
8+
from homeassistant.config_entries import ConfigEntry
9+
from homeassistant.const import CONF_NAME
10+
from homeassistant.core import callback
11+
from homeassistant.helpers import entity_registry
12+
from homeassistant.helpers.typing import HomeAssistantType
13+
from homeassistant.helpers.update_coordinator import CoordinatorEntity
14+
15+
from .const import CLIENTS, COORDINATOR, DOMAIN, UNDO_UPDATE_LISTENERS
16+
17+
18+
async def async_setup_entry(
19+
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
20+
) -> None:
21+
"""Set up device tracker for Ruckus Unleashed component."""
22+
coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR]
23+
24+
tracked = set()
25+
26+
@callback
27+
def router_update():
28+
"""Update the values of the router."""
29+
add_new_entities(coordinator, async_add_entities, tracked)
30+
31+
router_update()
32+
33+
hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENERS].append(
34+
coordinator.async_add_listener(router_update)
35+
)
36+
37+
registry = await entity_registry.async_get_registry(hass)
38+
restore_entities(registry, coordinator, entry, async_add_entities, tracked)
39+
40+
41+
@callback
42+
def add_new_entities(coordinator, async_add_entities, tracked):
43+
"""Add new tracker entities from the router."""
44+
new_tracked = []
45+
46+
for mac in coordinator.data[CLIENTS].keys():
47+
if mac in tracked:
48+
continue
49+
50+
device = coordinator.data[CLIENTS][mac]
51+
new_tracked.append(RuckusUnleashedDevice(coordinator, mac, device[CONF_NAME]))
52+
tracked.add(mac)
53+
54+
if new_tracked:
55+
async_add_entities(new_tracked, True)
56+
57+
58+
@callback
59+
def restore_entities(registry, coordinator, entry, async_add_entities, tracked):
60+
"""Restore clients that are not a part of active clients list."""
61+
missing = []
62+
63+
for entity in registry.entities.values():
64+
if entity.config_entry_id == entry.entry_id and entity.platform == DOMAIN:
65+
if entity.unique_id not in coordinator.data[CLIENTS]:
66+
missing.append(
67+
RuckusUnleashedDevice(
68+
coordinator, entity.unique_id, entity.original_name
69+
)
70+
)
71+
tracked.add(entity.unique_id)
72+
73+
if missing:
74+
async_add_entities(missing, True)
75+
76+
77+
class RuckusUnleashedDevice(CoordinatorEntity, ScannerEntity):
78+
"""Representation of a Ruckus Unleashed client."""
79+
80+
def __init__(self, coordinator, mac, name) -> None:
81+
"""Initialize a Ruckus Unleashed client."""
82+
super().__init__(coordinator)
83+
self._mac = mac
84+
self._name = name
85+
86+
@property
87+
def unique_id(self) -> str:
88+
"""Return a unique ID."""
89+
return self._mac
90+
91+
@property
92+
def name(self) -> str:
93+
"""Return the name."""
94+
if self.is_connected:
95+
return (
96+
self.coordinator.data[CLIENTS][self._mac][CONF_NAME]
97+
or f"Ruckus {self._mac}"
98+
)
99+
return self._name
100+
101+
@property
102+
def is_connected(self) -> bool:
103+
"""Return true if the device is connected to the network."""
104+
return self._mac in self.coordinator.data[CLIENTS]
105+
106+
@property
107+
def source_type(self) -> str:
108+
"""Return the source type."""
109+
return SOURCE_TYPE_ROUTER
110+
111+
@property
112+
def state_attributes(self) -> dict:
113+
"""Return the state attributes."""
114+
return {
115+
ATTR_SOURCE_TYPE: self.source_type,
116+
ATTR_MAC: self._mac,
117+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"domain": "ruckus_unleashed",
3+
"name": "Ruckus Unleashed",
4+
"config_flow": true,
5+
"documentation": "https://www.home-assistant.io/integrations/ruckus_unleashed",
6+
"requirements": [
7+
"pyruckus==0.7"
8+
],
9+
"ssdp": [],
10+
"zeroconf": [],
11+
"homekit": {},
12+
"dependencies": [],
13+
"codeowners": [
14+
"@gabe565"
15+
]
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"title": "Ruckus Unleashed",
3+
"config": {
4+
"step": {
5+
"user": {
6+
"data": {
7+
"host": "Host",
8+
"username": "Username",
9+
"password": "Password"
10+
}
11+
}
12+
},
13+
"error": {
14+
"cannot_connect": "Failed to connect",
15+
"invalid_auth": "Invalid authentication",
16+
"unknown": "Unexpected error"
17+
},
18+
"abort": {
19+
"already_configured": "Device is already configured"
20+
}
21+
}
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"config": {
3+
"abort": {
4+
"already_configured": "Device is already configured"
5+
},
6+
"error": {
7+
"cannot_connect": "Failed to connect",
8+
"invalid_auth": "Invalid authentication",
9+
"unknown": "Unexpected error"
10+
},
11+
"step": {
12+
"user": {
13+
"data": {
14+
"host": "Host",
15+
"password": "Password",
16+
"username": "Username"
17+
}
18+
}
19+
}
20+
},
21+
"title": "Ruckus Unleashed"
22+
}

homeassistant/generated/config_flows.py

+1
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@
158158
"roomba",
159159
"roon",
160160
"rpi_power",
161+
"ruckus_unleashed",
161162
"samsungtv",
162163
"sense",
163164
"sentry",

0 commit comments

Comments
 (0)