Rename igd to upnp
This commit is contained in:
1 parent
6588dceadd
commit
c19665fed4
13 files changed
+115
-119
No files matched your search
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"config": {
|
||||
"title": "UPnP/IGD",
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "UPnP/IGD"
|
||||
},
|
||||
"user": {
|
||||
"title": "Configuration options for the UPnP/IGD",
|
||||
"data":{
|
||||
"igd": "UPnP/IGD",
|
||||
"sensors": "Add traffic sensors",
|
||||
"port_forward": "Enable port forward for Home Assistant"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
},
|
||||
"abort": {
|
||||
"no_devices_discovered": "No UPnP/IGDs discovered",
|
||||
"already_configured": "UPnP/IGD is already configured",
|
||||
"no_sensors_or_port_forward": "Enable at least sensors or port forward"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"config": {
|
||||
"title": "UPnP/IGD",
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "UPnP/IGD"
|
||||
},
|
||||
"user": {
|
||||
"title": "Extra configuratie options voor UPnP/IGD",
|
||||
"data":{
|
||||
"igd": "UPnP/IGD",
|
||||
"sensors": "Verkeer sensors toevoegen",
|
||||
"port_forward": "Maak port forward voor Home Assistant"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
},
|
||||
"abort": {
|
||||
"no_devices_discovered": "Geen UPnP/IGDs gevonden",
|
||||
"already_configured": "UPnP/IGD is reeds geconfigureerd",
|
||||
"no_sensors_or_port_forward": "Kies ten minste sensors of port forward"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
"""
|
||||
Will open a port in your router for Home Assistant and provide statistics.
|
||||
|
||||
For more details about this component, please refer to the documentation at
|
||||
https://home-assistant.io/components/upnp/
|
||||
"""
|
||||
import asyncio
|
||||
from ipaddress import ip_address
|
||||
|
||||
import aiohttp
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
|
||||
from homeassistant.exceptions import PlatformNotReady
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers import discovery
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
from homeassistant.helpers.typing import HomeAssistantType
|
||||
from homeassistant.components.discovery import DOMAIN as DISCOVERY_DOMAIN
|
||||
|
||||
from .const import (
|
||||
CONF_ENABLE_PORT_MAPPING, CONF_ENABLE_SENSORS,
|
||||
CONF_HASS, CONF_LOCAL_IP, CONF_PORTS,
|
||||
CONF_UDN, CONF_SSDP_DESCRIPTION,
|
||||
)
|
||||
from .const import DOMAIN
|
||||
from .const import LOGGER as _LOGGER
|
||||
from .config_flow import ensure_domain_data
|
||||
from .device import Device
|
||||
|
||||
|
||||
REQUIREMENTS = ['async-upnp-client==0.12.4']
|
||||
DEPENDENCIES = ['http']
|
||||
|
||||
NOTIFICATION_ID = 'upnp_notification'
|
||||
NOTIFICATION_TITLE = 'UPnP/IGD Setup'
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema({
|
||||
DOMAIN: vol.Schema({
|
||||
vol.Optional(CONF_ENABLE_PORT_MAPPING, default=False): cv.boolean,
|
||||
vol.Optional(CONF_ENABLE_SENSORS, default=True): cv.boolean,
|
||||
vol.Optional(CONF_LOCAL_IP): vol.All(ip_address, cv.string),
|
||||
vol.Optional(CONF_PORTS):
|
||||
vol.Schema({
|
||||
vol.Any(CONF_HASS, cv.positive_int):
|
||||
vol.Any(CONF_HASS, cv.positive_int)
|
||||
})
|
||||
}),
|
||||
}, extra=vol.ALLOW_EXTRA)
|
||||
|
||||
|
||||
def _substitute_hass_ports(ports, hass_port):
|
||||
# substitute 'hass' for hass_port, both sides
|
||||
if CONF_HASS in ports:
|
||||
ports[hass_port] = ports[CONF_HASS]
|
||||
del ports[CONF_HASS]
|
||||
for port in ports:
|
||||
if ports[port] == CONF_HASS:
|
||||
ports[port] = hass_port
|
||||
|
||||
|
||||
# config
|
||||
async def async_setup(hass: HomeAssistantType, config: ConfigType):
|
||||
"""Register a port mapping for Home Assistant via UPnP."""
|
||||
_LOGGER.debug('async_setup: %s', config.get(DOMAIN))
|
||||
ensure_domain_data(hass)
|
||||
|
||||
# ensure sane config
|
||||
if DOMAIN not in config:
|
||||
return True
|
||||
|
||||
if DISCOVERY_DOMAIN not in config:
|
||||
_LOGGER.warning('UPNP needs discovery, please enable it')
|
||||
return False
|
||||
|
||||
# overridden local ip
|
||||
upnp_config = config[DOMAIN]
|
||||
if CONF_LOCAL_IP in upnp_config:
|
||||
hass.data[DOMAIN]['local_ip'] = upnp_config[CONF_LOCAL_IP]
|
||||
|
||||
# determine ports
|
||||
ports = {CONF_HASS: CONF_HASS} # default, port_forward disabled by default
|
||||
if CONF_PORTS in upnp_config:
|
||||
# copy from config
|
||||
ports = upnp_config[CONF_PORTS]
|
||||
|
||||
hass.data[DOMAIN]['auto_config'] = {
|
||||
'active': True,
|
||||
'port_forward': upnp_config[CONF_ENABLE_PORT_MAPPING],
|
||||
'ports': ports,
|
||||
'sensors': upnp_config[CONF_ENABLE_SENSORS],
|
||||
}
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# config flow
|
||||
async def async_setup_entry(hass: HomeAssistantType,
|
||||
config_entry: ConfigEntry):
|
||||
"""Set up a bridge from a config entry."""
|
||||
_LOGGER.debug('async_setup_entry: %s', config_entry.data)
|
||||
ensure_domain_data(hass)
|
||||
data = config_entry.data
|
||||
|
||||
# build UPnP/IGD device
|
||||
ssdp_description = data[CONF_SSDP_DESCRIPTION]
|
||||
try:
|
||||
device = await Device.async_create_device(hass, ssdp_description)
|
||||
except (asyncio.TimeoutError, aiohttp.ClientError):
|
||||
raise PlatformNotReady()
|
||||
|
||||
hass.data[DOMAIN]['devices'][device.udn] = device
|
||||
|
||||
# port mapping
|
||||
if data.get(CONF_ENABLE_PORT_MAPPING):
|
||||
local_ip = hass.data[DOMAIN].get('local_ip')
|
||||
ports = hass.data[DOMAIN]['auto_config']['ports']
|
||||
_LOGGER.debug('Enabling port mappings: %s', ports)
|
||||
|
||||
hass_port = hass.http.server_port
|
||||
_substitute_hass_ports(ports, hass_port)
|
||||
await device.async_add_port_mappings(ports, local_ip=local_ip)
|
||||
|
||||
# sensors
|
||||
if data.get(CONF_ENABLE_SENSORS):
|
||||
_LOGGER.debug('Enabling sensors')
|
||||
discovery_info = {
|
||||
'udn': device.udn,
|
||||
}
|
||||
hass_config = config_entry.data
|
||||
hass.async_create_task(discovery.async_load_platform(
|
||||
hass, 'sensor', DOMAIN, discovery_info, hass_config))
|
||||
|
||||
async def unload_entry(event):
|
||||
"""Unload entry on quit."""
|
||||
await async_unload_entry(hass, config_entry)
|
||||
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, unload_entry)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistantType,
|
||||
config_entry: ConfigEntry):
|
||||
"""Unload a config entry."""
|
||||
_LOGGER.debug('async_unload_entry: %s', config_entry.data)
|
||||
data = config_entry.data
|
||||
udn = data[CONF_UDN]
|
||||
|
||||
if udn not in hass.data[DOMAIN]['devices']:
|
||||
return True
|
||||
device = hass.data[DOMAIN]['devices'][udn]
|
||||
|
||||
# port mapping
|
||||
if data.get(CONF_ENABLE_PORT_MAPPING):
|
||||
_LOGGER.debug('Deleting port mappings')
|
||||
await device.async_delete_port_mappings()
|
||||
|
||||
# sensors
|
||||
for sensor in hass.data[DOMAIN]['sensors'].get(udn, []):
|
||||
_LOGGER.debug('Deleting sensor: %s', sensor)
|
||||
await sensor.async_remove()
|
||||
|
||||
# clear stored device
|
||||
del hass.data[DOMAIN]['devices'][udn]
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Config flow for UPNP."""
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant import data_entry_flow
|
||||
|
||||
from .const import (
|
||||
CONF_ENABLE_PORT_MAPPING, CONF_ENABLE_SENSORS,
|
||||
CONF_SSDP_DESCRIPTION, CONF_UDN
|
||||
)
|
||||
from .const import DOMAIN
|
||||
|
||||
|
||||
def ensure_domain_data(hass):
|
||||
"""Ensure hass.data is filled properly."""
|
||||
hass.data[DOMAIN] = hass.data.get(DOMAIN, {})
|
||||
hass.data[DOMAIN]['devices'] = hass.data[DOMAIN].get('devices', {})
|
||||
hass.data[DOMAIN]['sensors'] = hass.data[DOMAIN].get('sensors', {})
|
||||
hass.data[DOMAIN]['discovered'] = hass.data[DOMAIN].get('discovered', {})
|
||||
hass.data[DOMAIN]['auto_config'] = hass.data[DOMAIN].get('auto_config', {
|
||||
'active': False,
|
||||
'port_forward': False,
|
||||
'sensors': False,
|
||||
'ports': {'hass': 'hass'},
|
||||
})
|
||||
|
||||
|
||||
@config_entries.HANDLERS.register(DOMAIN)
|
||||
class UpnpFlowHandler(data_entry_flow.FlowHandler):
|
||||
"""Handle a Hue config flow."""
|
||||
|
||||
VERSION = 1
|
||||
|
||||
@property
|
||||
def _configured_upnp_igds(self):
|
||||
"""Get all configured IGDs."""
|
||||
return {
|
||||
entry.data[CONF_UDN]: {
|
||||
'udn': entry.data[CONF_UDN],
|
||||
}
|
||||
for entry in self.hass.config_entries.async_entries(DOMAIN)
|
||||
}
|
||||
|
||||
@property
|
||||
def _discovered_upnp_igds(self):
|
||||
"""Get all discovered entries."""
|
||||
return self.hass.data[DOMAIN]['discovered']
|
||||
|
||||
def _store_discovery_info(self, discovery_info):
|
||||
"""Add discovery info."""
|
||||
udn = discovery_info['udn']
|
||||
self.hass.data[DOMAIN]['discovered'][udn] = discovery_info
|
||||
|
||||
def _auto_config_settings(self):
|
||||
"""Check if auto_config has been enabled."""
|
||||
return self.hass.data[DOMAIN]['auto_config']
|
||||
|
||||
async def async_step_discovery(self, discovery_info):
|
||||
"""
|
||||
Handle a discovered UPnP/IGD.
|
||||
|
||||
This flow is triggered by the discovery component. It will check if the
|
||||
host is already configured and delegate to the import step if not.
|
||||
"""
|
||||
ensure_domain_data(self.hass)
|
||||
|
||||
# store discovered device
|
||||
discovery_info['friendly_name'] = \
|
||||
'{} ({})'.format(discovery_info['host'], discovery_info['name'])
|
||||
self._store_discovery_info(discovery_info)
|
||||
|
||||
# ensure not already discovered/configured
|
||||
udn = discovery_info['udn']
|
||||
if udn in self._configured_upnp_igds:
|
||||
return self.async_abort(reason='already_configured')
|
||||
|
||||
# auto config?
|
||||
auto_config = self._auto_config_settings()
|
||||
if auto_config['active']:
|
||||
import_info = {
|
||||
'name': discovery_info['friendly_name'],
|
||||
'sensors': auto_config['sensors'],
|
||||
'port_forward': auto_config['port_forward'],
|
||||
}
|
||||
|
||||
return await self._async_save_entry(import_info)
|
||||
|
||||
return await self.async_step_user()
|
||||
|
||||
async def async_step_user(self, user_input=None):
|
||||
"""Manual set up."""
|
||||
# if user input given, handle it
|
||||
user_input = user_input or {}
|
||||
if 'name' in user_input:
|
||||
if not user_input['sensors'] and not user_input['port_forward']:
|
||||
return self.async_abort(reason='no_sensors_or_port_forward')
|
||||
|
||||
# ensure not already configured
|
||||
configured_names = [
|
||||
entry['friendly_name']
|
||||
for udn, entry in self._discovered_upnp_igds.items()
|
||||
if udn in self._configured_upnp_igds
|
||||
]
|
||||
if user_input['name'] in configured_names:
|
||||
return self.async_abort(reason='already_configured')
|
||||
|
||||
return await self._async_save_entry(user_input)
|
||||
|
||||
# let user choose from all discovered, non-configured, UPnP/IGDs
|
||||
names = [
|
||||
entry['friendly_name']
|
||||
for udn, entry in self._discovered_upnp_igds.items()
|
||||
if udn not in self._configured_upnp_igds
|
||||
]
|
||||
if not names:
|
||||
return self.async_abort(reason='no_devices_discovered')
|
||||
|
||||
return self.async_show_form(
|
||||
step_id='user',
|
||||
data_schema=vol.Schema({
|
||||
vol.Required('name'): vol.In(names),
|
||||
vol.Optional('sensors', default=False): bool,
|
||||
vol.Optional('port_forward', default=False): bool,
|
||||
})
|
||||
)
|
||||
|
||||
async def async_step_import(self, import_info):
|
||||
"""Import a new UPnP/IGD as a config entry."""
|
||||
return await self._async_save_entry(import_info)
|
||||
|
||||
async def _async_save_entry(self, import_info):
|
||||
"""Store UPNP/IGD as new entry."""
|
||||
# ensure we know the host
|
||||
name = import_info['name']
|
||||
discovery_infos = [info
|
||||
for info in self._discovered_upnp_igds.values()
|
||||
if info['friendly_name'] == name]
|
||||
if not discovery_infos:
|
||||
return self.async_abort(reason='host_not_found')
|
||||
discovery_info = discovery_infos[0]
|
||||
|
||||
return self.async_create_entry(
|
||||
title=discovery_info['name'],
|
||||
data={
|
||||
CONF_SSDP_DESCRIPTION: discovery_info['ssdp_description'],
|
||||
CONF_UDN: discovery_info['udn'],
|
||||
CONF_ENABLE_SENSORS: import_info['sensors'],
|
||||
CONF_ENABLE_PORT_MAPPING: import_info['port_forward'],
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Constants for the IGD component."""
|
||||
import logging
|
||||
|
||||
|
||||
CONF_ENABLE_PORT_MAPPING = 'port_forward'
|
||||
CONF_ENABLE_SENSORS = 'sensors'
|
||||
CONF_HASS = 'hass'
|
||||
CONF_LOCAL_IP = 'local_ip'
|
||||
CONF_PORTS = 'ports'
|
||||
CONF_SSDP_DESCRIPTION = 'ssdp_description'
|
||||
CONF_UDN = 'udn'
|
||||
DOMAIN = 'upnp'
|
||||
LOGGER = logging.getLogger('homeassistant.components.upnp')
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Hass representation of an UPnP/IGD."""
|
||||
import asyncio
|
||||
from ipaddress import IPv4Address
|
||||
|
||||
import aiohttp
|
||||
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.helpers.typing import HomeAssistantType
|
||||
from homeassistant.util import get_local_ip
|
||||
|
||||
from .const import LOGGER as _LOGGER
|
||||
|
||||
|
||||
class Device:
|
||||
"""Hass representation of an UPnP/IGD."""
|
||||
|
||||
def __init__(self, igd_device):
|
||||
"""Initializer."""
|
||||
self._igd_device = igd_device
|
||||
self._mapped_ports = []
|
||||
|
||||
@classmethod
|
||||
async def async_create_device(cls,
|
||||
hass: HomeAssistantType,
|
||||
ssdp_description: str):
|
||||
"""Create UPnP/IGD device."""
|
||||
# build async_upnp_client requester
|
||||
from async_upnp_client.aiohttp import AiohttpSessionRequester
|
||||
session = async_get_clientsession(hass)
|
||||
requester = AiohttpSessionRequester(session, True)
|
||||
|
||||
# create async_upnp_client device
|
||||
from async_upnp_client import UpnpFactory
|
||||
factory = UpnpFactory(requester,
|
||||
disable_state_variable_validation=True)
|
||||
upnp_device = await factory.async_create_device(ssdp_description)
|
||||
|
||||
# wrap with async_upnp_client IgdDevice
|
||||
from async_upnp_client.igd import IgdDevice
|
||||
igd_device = IgdDevice(upnp_device, None)
|
||||
|
||||
return Device(igd_device)
|
||||
|
||||
@property
|
||||
def udn(self):
|
||||
"""Get the UDN."""
|
||||
return self._igd_device.udn
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Get the name."""
|
||||
return self._igd_device.name
|
||||
|
||||
async def async_add_port_mappings(self, ports, local_ip=None):
|
||||
"""Add port mappings."""
|
||||
# determine local ip, ensure sane IP
|
||||
if local_ip is None:
|
||||
local_ip = get_local_ip()
|
||||
|
||||
if local_ip == '127.0.0.1':
|
||||
_LOGGER.error(
|
||||
'Could not create port mapping, our IP is 127.0.0.1')
|
||||
local_ip = IPv4Address(local_ip)
|
||||
|
||||
# create port mappings
|
||||
for external_port, internal_port in ports.items():
|
||||
await self._async_add_port_mapping(external_port,
|
||||
local_ip,
|
||||
internal_port)
|
||||
self._mapped_ports.append(external_port)
|
||||
|
||||
async def _async_add_port_mapping(self,
|
||||
external_port,
|
||||
local_ip,
|
||||
internal_port):
|
||||
"""Add a port mapping."""
|
||||
# create port mapping
|
||||
from async_upnp_client import UpnpError
|
||||
_LOGGER.info('Creating port mapping %s:%s:%s (TCP)',
|
||||
external_port, local_ip, internal_port)
|
||||
try:
|
||||
await self._igd_device.async_add_port_mapping(
|
||||
remote_host=None,
|
||||
external_port=external_port,
|
||||
protocol='TCP',
|
||||
internal_port=internal_port,
|
||||
internal_client=local_ip,
|
||||
enabled=True,
|
||||
description="Home Assistant",
|
||||
lease_duration=None)
|
||||
|
||||
self._mapped_ports.append(external_port)
|
||||
except (asyncio.TimeoutError, aiohttp.ClientError, UpnpError):
|
||||
_LOGGER.error('Could not add port mapping: %s:%s:%s',
|
||||
external_port, local_ip, internal_port)
|
||||
|
||||
async def async_delete_port_mappings(self):
|
||||
"""Remove a port mapping."""
|
||||
for port in self._mapped_ports:
|
||||
await self._async_delete_port_mapping(port)
|
||||
|
||||
async def _async_delete_port_mapping(self, external_port):
|
||||
"""Remove a port mapping."""
|
||||
from async_upnp_client import UpnpError
|
||||
try:
|
||||
await self._igd_device.async_delete_port_mapping(
|
||||
remote_host=None,
|
||||
external_port=external_port,
|
||||
protocol='TCP')
|
||||
|
||||
self._mapped_ports.remove(external_port)
|
||||
except (asyncio.TimeoutError, aiohttp.ClientError, UpnpError):
|
||||
_LOGGER.error('Could not delete port mapping')
|
||||
|
||||
async def async_get_total_bytes_received(self):
|
||||
"""Get total bytes received."""
|
||||
return await self._igd_device.async_get_total_bytes_received()
|
||||
|
||||
async def async_get_total_bytes_sent(self):
|
||||
"""Get total bytes sent."""
|
||||
return await self._igd_device.async_get_total_bytes_sent()
|
||||
|
||||
async def async_get_total_packets_received(self):
|
||||
"""Get total packets received."""
|
||||
# pylint: disable=invalid-name
|
||||
return await self._igd_device.async_get_total_packets_received()
|
||||
|
||||
async def async_get_total_packets_sent(self):
|
||||
"""Get total packets sent."""
|
||||
return await self._igd_device.async_get_total_packets_sent()
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"config": {
|
||||
"title": "UPnP/IGD",
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "UPnP/IGD"
|
||||
},
|
||||
"user": {
|
||||
"title": "Configuration options for the UPnP/IGD",
|
||||
"data":{
|
||||
"igd": "UPnP/IGD",
|
||||
"sensors": "Add traffic sensors",
|
||||
"port_forward": "Enable port forward for Home Assistant"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
},
|
||||
"abort": {
|
||||
"no_devices_discovered": "No UPnP/IGDs discovered",
|
||||
"already_configured": "UPnP/IGD is already configured",
|
||||
"no_sensors_or_port_forward": "Enable at least sensors or port forward"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user