core/homeassistant/components/upnp.py

53 lines
1.3 KiB
Python
Raw Normal View History

2016-04-11 00:44:57 +00:00
"""
This module will attempt to open a port in your router for Home Assistant.
2017-05-31 16:08:53 +00:00
For more details about this component, please refer to the documentation at
2016-04-11 00:44:57 +00:00
https://home-assistant.io/components/upnp/
"""
import logging
2017-05-31 16:08:53 +00:00
from urllib.parse import urlsplit
2016-04-11 00:44:57 +00:00
import voluptuous as vol
2016-04-11 00:44:57 +00:00
from homeassistant.const import (EVENT_HOMEASSISTANT_STOP)
2016-04-11 00:44:57 +00:00
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['api']
DOMAIN = 'upnp'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({}),
}, extra=vol.ALLOW_EXTRA)
2016-04-11 00:44:57 +00:00
# pylint: disable=import-error, no-member, broad-except
2016-04-11 00:44:57 +00:00
def setup(hass, config):
"""Register a port mapping for Home Assistant via UPnP."""
import miniupnpc
upnp = miniupnpc.UPnP()
upnp.discoverdelay = 200
upnp.discover()
try:
upnp.selectigd()
except Exception:
2017-05-31 16:08:53 +00:00
_LOGGER.exception("Error when attempting to discover an UPnP IGD")
2016-04-11 00:44:57 +00:00
return False
2017-05-31 16:08:53 +00:00
base_url = urlsplit(hass.config.api.base_url)
host = base_url.hostname
external_port = internal_port = base_url.port
upnp.addportmapping(
external_port, 'TCP', host, internal_port, 'Home Assistant', '')
2016-04-11 00:44:57 +00:00
def deregister_port(event):
"""De-register the UPnP port mapping."""
upnp.deleteportmapping(hass.config.api.port, 'TCP')
2016-04-11 00:44:57 +00:00
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, deregister_port)
return True