<commit_before>"""SMA Solar Webconnect interface."""
import asyncio
from datetime import timedelta
import logging

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    CONF_HOST,
    CONF_PASSWORD,
    CONF_SCAN_INTERVAL,
    CONF_SSL,
    CONF_VERIFY_SSL,
    EVENT_HOMEASSISTANT_STOP,
    CONF_PATH,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.const import MINOR_VERSION, MAJOR_VERSION

_LOGGER = logging.getLogger(__name__)

CONF_CUSTOM = "custom"
CONF_FACTOR = "factor"
CONF_GROUP = "group"
CONF_KEY = "key"
CONF_SENSORS = "sensors"
CONF_UNIT = "unit"

GROUPS = ["user", "installer"]
OLD_CONFIG_DEPRECATED = MAJOR_VERSION > 0 or MINOR_VERSION > 98


def _check_sensor_schema(conf):
    """Check sensors and attributes are valid."""
    try:
        import pysma

        valid = [s.name for s in pysma.Sensors()]
    except (ImportError, AttributeError):
        return conf

    customs = list(conf[CONF_CUSTOM].keys())

    if isinstance(conf[CONF_SENSORS], dict):
        msg = '"sensors" should be a simple list from 0.99'
        if OLD_CONFIG_DEPRECATED:
            raise vol.Invalid(msg)
        _LOGGER.warning(msg)
        valid.extend(customs)

        for sname, attrs in conf[CONF_SENSORS].items():
            if sname not in valid:
                raise vol.Invalid("{} does not exist".format(sname))
            if attrs:
                _LOGGER.warning(
                    "Attributes on sensors will be deprecated in 0.99. Start using only individual sensors: %s: %s",
                    sname,
                    ", ".join(attrs),
                )
            for attr in attrs:
                if attr in valid:
                    continue
                raise vol.Invalid("{} does not exist [{}]".format(attr, sname))
        return conf

    # Sensors is a list (only option from from 0.99)
    for sensor in conf[CONF_SENSORS]:
        if sensor in customs:
            _LOGGER.warning(
                "All custom sensors will be added automatically, no need to include them in sensors: %s",
                sensor,
            )
        elif sensor not in valid:
            raise vol.Invalid("{} does not exist".format(sensor))
    return conf


CUSTOM_SCHEMA = vol.Any(
    {
        vol.Required(CONF_KEY): vol.All(cv.string, vol.Length(min=13, max=15)),
        vol.Required(CONF_UNIT): cv.string,
        vol.Optional(CONF_FACTOR, default=1): vol.Coerce(float),
        vol.Optional(CONF_PATH): vol.All(cv.ensure_list, [cv.string]),
    }
)

PLATFORM_SCHEMA = vol.All(
    PLATFORM_SCHEMA.extend(
        {
            vol.Required(CONF_HOST): cv.string,
            vol.Optional(CONF_SSL, default=False): cv.boolean,
            vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean,
            vol.Required(CONF_PASSWORD): cv.string,
            vol.Optional(CONF_GROUP, default=GROUPS[0]): vol.In(GROUPS),
            vol.Optional(CONF_SENSORS, default=[]): vol.Any(
                cv.schema_with_slug_keys(cv.ensure_list),  # will be deprecated
                vol.All(cv.ensure_list, [str]),
            ),
            vol.Optional(CONF_CUSTOM, default={}): cv.schema_with_slug_keys(
                CUSTOM_SCHEMA
            ),
        },
        extra=vol.PREVENT_EXTRA,
    ),
    _check_sensor_schema,
)


async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up SMA WebConnect sensor."""
    import pysma

    # Check config again during load - dependency available
    config = _check_sensor_schema(config)

    # Init all default sensors
    sensor_def = pysma.Sensors()

    # Sensor from the custom config
    sensor_def.add(
        [
            pysma.Sensor(o[CONF_KEY], n, o[CONF_UNIT], o[CONF_FACTOR], o.get(CONF_PATH))
            for n, o in config[CONF_CUSTOM].items()
        ]
    )

    # Use all sensors by default
    config_sensors = config[CONF_SENSORS]
    hass_sensors = []
    used_sensors = []

    if isinstance(config_sensors, dict):  # will be remove from 0.99
        if not config_sensors:  # Use all sensors by default
            config_sensors = {s.name: [] for s in sensor_def}

        # Prepare all HASS sensor entities
        for name, attr in config_sensors.items():
            sub_sensors = [sensor_def[s] for s in attr]
            hass_sensors.append(SMAsensor(sensor_def[name], sub_sensors))
            used_sensors.append(name)
            used_sensors.extend(attr)
        used_sensors = [sensor_def[s] for s in set(used_sensors)]

    if isinstance(config_sensors, list):
        if not config_sensors:  # Use all sensors by default
            config_sensors = [s.name for s in sensor_def]
        used_sensors = list(set(config_sensors + list(config[CONF_CUSTOM].keys())))
        for sensor in used_sensors:
            hass_sensors.append(SMAsensor(sensor_def[sensor], []))

    async_add_entities(hass_sensors)

    # Init the SMA interface
    session = async_get_clientsession(hass, verify_ssl=config[CONF_VERIFY_SSL])
    grp = config[CONF_GROUP]

    url = "http{}://{}".format("s" if config[CONF_SSL] else "", config[CONF_HOST])

    sma = pysma.SMA(session, url, config[CONF_PASSWORD], group=grp)

    # Ensure we logout on shutdown<commit_msg>SMA beta fix #26225 (#26244)<commit_after>"""SMA Solar Webconnect interface."""
import asyncio
from datetime import timedelta
import logging

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    CONF_HOST,
    CONF_PASSWORD,
    CONF_SCAN_INTERVAL,
    CONF_SSL,
    CONF_VERIFY_SSL,
    EVENT_HOMEASSISTANT_STOP,
    CONF_PATH,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.const import MINOR_VERSION, MAJOR_VERSION

_LOGGER = logging.getLogger(__name__)

CONF_CUSTOM = "custom"
CONF_FACTOR = "factor"
CONF_GROUP = "group"
CONF_KEY = "key"
CONF_SENSORS = "sensors"
CONF_UNIT = "unit"

GROUPS = ["user", "installer"]
OLD_CONFIG_DEPRECATED = MAJOR_VERSION > 0 or MINOR_VERSION > 98


def _check_sensor_schema(conf):
    """Check sensors and attributes are valid."""
    try:
        import pysma

        valid = [s.name for s in pysma.Sensors()]
    except (ImportError, AttributeError):
        return conf

    customs = list(conf[CONF_CUSTOM].keys())

    if isinstance(conf[CONF_SENSORS], dict):
        msg = '"sensors" should be a simple list from 0.99'
        if OLD_CONFIG_DEPRECATED:
            raise vol.Invalid(msg)
        _LOGGER.warning(msg)
        valid.extend(customs)

        for sname, attrs in conf[CONF_SENSORS].items():
            if sname not in valid:
                raise vol.Invalid("{} does not exist".format(sname))
            if attrs:
                _LOGGER.warning(
                    "Attributes on sensors will be deprecated in 0.99. Start using only individual sensors: %s: %s",
                    sname,
                    ", ".join(attrs),
                )
            for attr in attrs:
                if attr in valid:
                    continue
                raise vol.Invalid("{} does not exist [{}]".format(attr, sname))
        return conf

    # Sensors is a list (only option from from 0.99)
    for sensor in conf[CONF_SENSORS]:
        if sensor in customs:
            _LOGGER.warning(
                "All custom sensors will be added automatically, no need to include them in sensors: %s",
                sensor,
            )
        elif sensor not in valid:
            raise vol.Invalid("{} does not exist".format(sensor))
    return conf


CUSTOM_SCHEMA = vol.Any(
    {
        vol.Required(CONF_KEY): vol.All(cv.string, vol.Length(min=13, max=15)),
        vol.Required(CONF_UNIT): cv.string,
        vol.Optional(CONF_FACTOR, default=1): vol.Coerce(float),
        vol.Optional(CONF_PATH): vol.All(cv.ensure_list, [cv.string]),
    }
)

PLATFORM_SCHEMA = vol.All(
    PLATFORM_SCHEMA.extend(
        {
            vol.Required(CONF_HOST): cv.string,
            vol.Optional(CONF_SSL, default=False): cv.boolean,
            vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean,
            vol.Required(CONF_PASSWORD): cv.string,
            vol.Optional(CONF_GROUP, default=GROUPS[0]): vol.In(GROUPS),
            vol.Optional(CONF_SENSORS, default=[]): vol.Any(
                cv.schema_with_slug_keys(cv.ensure_list),  # will be deprecated
                vol.All(cv.ensure_list, [str]),
            ),
            vol.Optional(CONF_CUSTOM, default={}): cv.schema_with_slug_keys(
                CUSTOM_SCHEMA
            ),
        },
        extra=vol.PREVENT_EXTRA,
    ),
    _check_sensor_schema,
)


async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up SMA WebConnect sensor."""
    import pysma

    # Check config again during load - dependency available
    config = _check_sensor_schema(config)

    # Init all default sensors
    sensor_def = pysma.Sensors()

    # Sensor from the custom config
    sensor_def.add(
        [
            pysma.Sensor(o[CONF_KEY], n, o[CONF_UNIT], o[CONF_FACTOR], o.get(CONF_PATH))
            for n, o in config[CONF_CUSTOM].items()
        ]
    )

    # Use all sensors by default
    config_sensors = config[CONF_SENSORS]
    hass_sensors = []
    used_sensors = []

    if isinstance(config_sensors, dict):  # will be remove from 0.99
        if not config_sensors:  # Use all sensors by default
            config_sensors = {s.name: [] for s in sensor_def}

        # Prepare all HASS sensor entities
        for name, attr in config_sensors.items():
            sub_sensors = [sensor_def[s] for s in attr]
            hass_sensors.append(SMAsensor(sensor_def[name], sub_sensors))
            used_sensors.append(name)
            used_sensors.extend(attr)

    if isinstance(config_sensors, list):
        if not config_sensors:  # Use all sensors by default
            config_sensors = [s.name for s in sensor_def]
        used_sensors = list(set(config_sensors + list(config[CONF_CUSTOM].keys())))
        for sensor in used_sensors:
            hass_sensors.append(SMAsensor(sensor_def[sensor], []))

    used_sensors = [sensor_def[s] for s in set(used_sensors)]
    async_add_entities(hass_sensors)

    # Init the SMA interface
    session = async_get_clientsession(hass, verify_ssl=config[CONF_VERIFY_SSL])
    grp = config[CONF_GROUP]

    url = "http{}://{}".format("s" if config[CONF_SSL] else "", config[CONF_HOST])

    sma = pysma.SMA(session, url, config[CONF_PASSWORD], group=grp)

    # Ensure we logout on shutdown
{'fraction_non_alphanumeric': 0.0977696859353664, 'fraction_numerical': 0.004733727810650888, 'mean_word_length': 2.605513619954053, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1870394', 'n_tokens_mistral': 3484, 'n_tokens_neox': 3361, 'n_words': 827}