def setup(hass, config):
    # pylint: disable=import-error
    import miniupnpc

    # pylint: disable=no-member
    upnp = miniupnpc.UPnP()

    upnp.discoverdelay = 200
    upnp.discover()
    try:
        upnp.selectigd()
    # pylint: disable=broad-except
    except Exception:
        _LOGGER.exception("Error when attempting to discover a UPnP IGD")
        return False

    upnp.addportmapping(hass.config.api.port, "TCP",
                        hass.config.api.host, hass.config.api.port,
                        "Home Assistant", "")

    def deregister_port(event):
        """De-register the UPnP port mapping."""
        upnp.deleteportmapping(hass.config.api.port, "TCP")

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, deregister_port)

    return True
Register a port mapping for Home Assistant via UPnP.
dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/components/upnp.py/setup