<commit_before>"""Support for monitoring energy usage using the DTE energy bridge."""
from http import HTTPStatus
import logging

import requests
import voluptuous as vol

from homeassistant.components.sensor import (
    PLATFORM_SCHEMA,
    STATE_CLASS_MEASUREMENT,
    SensorEntity,
)
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

CONF_IP_ADDRESS = "ip"
CONF_VERSION = "version"

DEFAULT_NAME = "Current Energy Usage"
DEFAULT_VERSION = 1

ICON = "mdi:flash"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_IP_ADDRESS): cv.string,
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
        vol.Optional(CONF_VERSION, default=DEFAULT_VERSION): vol.All(
            vol.Coerce(int), vol.Any(1, 2)
        ),
    }
)


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the DTE energy bridge sensor."""
    name = config[CONF_NAME]
    ip_address = config[CONF_IP_ADDRESS]
    version = config[CONF_VERSION]

    add_entities([DteEnergyBridgeSensor(ip_address, name, version)], True)


class DteEnergyBridgeSensor(SensorEntity):
    """Implementation of the DTE Energy Bridge sensors."""

    _attr_state_class = STATE_CLASS_MEASUREMENT

    def __init__(self, ip_address, name, version):
        """Initialize the sensor."""
        self._version = version

        if self._version == 1:
            self._url = f"http://{ip_address}/instantaneousdemand"
        elif self._version == 2:
            self._url = f"http://{ip_address}:8888/zigbee/se/instantaneousdemand"

        self._name = name
        self._unit_of_measurement = "kW"
        self._state = None

    @property
    def name(self):
        """Return the name of th sensor."""
        return self._name

    @property
    def native_value(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def native_unit_of_measurement(self):
        """Return the unit of measurement of this entity, if any."""
        return self._unit_of_measurement

    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        return ICON

    def update(self):
        """Get the energy usage data from the DTE energy bridge."""
        try:
            response = requests.get(self._url, timeout=5)
        except (requests.exceptions.RequestException, ValueError):
            _LOGGER.warning(
                "Could not update status for DTE Energy Bridge (%s)", self._name
            )
            return

        if response.status_code != HTTPStatus.OK:
            _LOGGER.warning(
                "Invalid status_code from DTE Energy Bridge: %s (%s)",
                response.status_code,
                self._name,
            )
            return

        response_split = response.text.split()

        if len(response_split) != 2:
            _LOGGER.warning(
                'Invalid response from DTE Energy Bridge: "%s" (%s)',
                response.text,
                self._name,
            )
            return

        val = float(response_split[0])

        # A workaround for a bug in the DTE energy bridge.
        # The returned value can randomly be in W or kW.  Checking for a
        # a decimal seems to be a reliable way to determine the units.
        # Limiting to version 1 because version 2 apparently always returns
        # values in the format 000000.000 kW, but the scaling is Watts
        # NOT kWatts
        if self._version == 1 and "." in response_split[0]:
            self._state = val
        else:
            self._state = val / 1000<commit_msg>Use _attr_* in dte_energy_bridge (#61353)<commit_after>"""Support for monitoring energy usage using the DTE energy bridge."""
from http import HTTPStatus
import logging

import requests
import voluptuous as vol

from homeassistant.components.sensor import (
    PLATFORM_SCHEMA,
    SensorEntity,
    SensorStateClass,
)
from homeassistant.const import CONF_NAME, POWER_KILO_WATT
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

CONF_IP_ADDRESS = "ip"
CONF_VERSION = "version"

DEFAULT_NAME = "Current Energy Usage"
DEFAULT_VERSION = 1

ICON = "mdi:flash"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_IP_ADDRESS): cv.string,
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
        vol.Optional(CONF_VERSION, default=DEFAULT_VERSION): vol.All(
            vol.Coerce(int), vol.Any(1, 2)
        ),
    }
)


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the DTE energy bridge sensor."""
    name = config[CONF_NAME]
    ip_address = config[CONF_IP_ADDRESS]
    version = config[CONF_VERSION]

    add_entities([DteEnergyBridgeSensor(ip_address, name, version)], True)


class DteEnergyBridgeSensor(SensorEntity):
    """Implementation of the DTE Energy Bridge sensors."""

    _attr_icon = ICON
    _attr_native_unit_of_measurement = POWER_KILO_WATT
    _attr_state_class = SensorStateClass.MEASUREMENT

    def __init__(self, ip_address, name, version):
        """Initialize the sensor."""
        self._version = version

        if self._version == 1:
            self._url = f"http://{ip_address}/instantaneousdemand"
        elif self._version == 2:
            self._url = f"http://{ip_address}:8888/zigbee/se/instantaneousdemand"

        self._attr_name = name

    def update(self):
        """Get the energy usage data from the DTE energy bridge."""
        try:
            response = requests.get(self._url, timeout=5)
        except (requests.exceptions.RequestException, ValueError):
            _LOGGER.warning(
                "Could not update status for DTE Energy Bridge (%s)", self._attr_name
            )
            return

        if response.status_code != HTTPStatus.OK:
            _LOGGER.warning(
                "Invalid status_code from DTE Energy Bridge: %s (%s)",
                response.status_code,
                self._attr_name,
            )
            return

        response_split = response.text.split()

        if len(response_split) != 2:
            _LOGGER.warning(
                'Invalid response from DTE Energy Bridge: "%s" (%s)',
                response.text,
                self._attr_name,
            )
            return

        val = float(response_split[0])

        # A workaround for a bug in the DTE energy bridge.
        # The returned value can randomly be in W or kW.  Checking for a
        # a decimal seems to be a reliable way to determine the units.
        # Limiting to version 1 because version 2 apparently always returns
        # values in the format 000000.000 kW, but the scaling is Watts
        # NOT kWatts
        if self._version == 1 and "." in response_split[0]:
            self._attr_native_value = val
        else:
            self._attr_native_value = val / 1000
{'fraction_non_alphanumeric': 0.08904502437625467, 'fraction_numerical': 0.009033553197591053, 'mean_word_length': 2.4292035398230087, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '5390699', 'n_tokens_mistral': 2060, 'n_tokens_neox': 1962, 'n_words': 568}