<commit_before>"""Support for Lutron Caseta fans."""
import logging

from pylutron_caseta import FAN_HIGH, FAN_LOW, FAN_MEDIUM, FAN_MEDIUM_HIGH, FAN_OFF

from homeassistant.components.fan import (
    DOMAIN,
    SPEED_HIGH,
    SPEED_LOW,
    SPEED_MEDIUM,
    SPEED_OFF,
    SUPPORT_SET_SPEED,
    FanEntity,
)

from . import LutronCasetaDevice
from .const import BRIDGE_DEVICE, BRIDGE_LEAP, DOMAIN as CASETA_DOMAIN

_LOGGER = logging.getLogger(__name__)

VALUE_TO_SPEED = {
    None: SPEED_OFF,
    FAN_OFF: SPEED_OFF,
    FAN_LOW: SPEED_LOW,
    FAN_MEDIUM: SPEED_MEDIUM,
    FAN_MEDIUM_HIGH: SPEED_MEDIUM,
    FAN_HIGH: SPEED_HIGH,
}

SPEED_TO_VALUE = {
    SPEED_OFF: FAN_OFF,
    SPEED_LOW: FAN_LOW,
    SPEED_MEDIUM: FAN_MEDIUM,
    SPEED_HIGH: FAN_HIGH,
}

FAN_SPEEDS = [SPEED_OFF, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH]


async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the Lutron Caseta fan platform.

    Adds fan controllers from the Caseta bridge associated with the config_entry
    as fan entities.
    """

    entities = []
    data = hass.data[CASETA_DOMAIN][config_entry.entry_id]
    bridge = data[BRIDGE_LEAP]
    bridge_device = data[BRIDGE_DEVICE]
    fan_devices = bridge.get_devices_by_domain(DOMAIN)

    for fan_device in fan_devices:
        entity = LutronCasetaFan(fan_device, bridge, bridge_device)
        entities.append(entity)

    async_add_entities(entities, True)


class LutronCasetaFan(LutronCasetaDevice, FanEntity):
    """Representation of a Lutron Caseta fan. Including Fan Speed."""

    @property
    def speed(self) -> str:
        """Return the current speed."""
        return VALUE_TO_SPEED[self._device["fan_speed"]]

    @property
    def speed_list(self) -> list:
        """Get the list of available speeds."""
        return FAN_SPEEDS

    @property
    def supported_features(self) -> int:
        """Flag supported features. Speed Only."""
        return SUPPORT_SET_SPEED

    #
    # The fan entity model has changed to use percentages and preset_modes
    # instead of speeds.
    #
    # Please review
    # https://developers.home-assistant.io/docs/core/entity/fan/
    #
    async def async_turn_on(
        self,
        speed: str = None,
        percentage: int = None,
        preset_mode: str = None,
        **kwargs,
    ):
        """Turn the fan on."""
        if speed is None:
            speed = SPEED_MEDIUM
        await self.async_set_speed(speed)

    async def async_turn_off(self, **kwargs):
        """Turn the fan off."""
        await self.async_set_speed(SPEED_OFF)

    async def async_set_speed(self, speed: str) -> None:
        """Set the speed of the fan."""
        await self._smartbridge.set_fan(self.device_id, SPEED_TO_VALUE[speed])

    @property
    def is_on(self):
        """Return true if device is on."""
        return VALUE_TO_SPEED[self._device["fan_speed"]] in [
            SPEED_LOW,
            SPEED_MEDIUM,
            SPEED_HIGH,
        ]

    async def async_update(self):
        """Update when forcing a refresh of the device."""
        self._device = self._smartbridge.get_device_by_id(self.device_id)
        _LOGGER.debug("State of this lutron fan device is %s", self._device)<commit_msg>Update lutron_caseta to use new fan entity model (#45540)<commit_after>"""Support for Lutron Caseta fans."""
import logging

from pylutron_caseta import FAN_HIGH, FAN_LOW, FAN_MEDIUM, FAN_MEDIUM_HIGH, FAN_OFF

from homeassistant.components.fan import DOMAIN, SUPPORT_SET_SPEED, FanEntity
from homeassistant.util.percentage import (
    ordered_list_item_to_percentage,
    percentage_to_ordered_list_item,
)

from . import LutronCasetaDevice
from .const import BRIDGE_DEVICE, BRIDGE_LEAP, DOMAIN as CASETA_DOMAIN

_LOGGER = logging.getLogger(__name__)

DEFAULT_ON_PERCENTAGE = 50
ORDERED_NAMED_FAN_SPEEDS = [FAN_LOW, FAN_MEDIUM, FAN_MEDIUM_HIGH, FAN_HIGH]


async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the Lutron Caseta fan platform.

    Adds fan controllers from the Caseta bridge associated with the config_entry
    as fan entities.
    """

    entities = []
    data = hass.data[CASETA_DOMAIN][config_entry.entry_id]
    bridge = data[BRIDGE_LEAP]
    bridge_device = data[BRIDGE_DEVICE]
    fan_devices = bridge.get_devices_by_domain(DOMAIN)

    for fan_device in fan_devices:
        entity = LutronCasetaFan(fan_device, bridge, bridge_device)
        entities.append(entity)

    async_add_entities(entities, True)


class LutronCasetaFan(LutronCasetaDevice, FanEntity):
    """Representation of a Lutron Caseta fan. Including Fan Speed."""

    @property
    def percentage(self) -> str:
        """Return the current speed percentage."""
        return ordered_list_item_to_percentage(
            ORDERED_NAMED_FAN_SPEEDS, self._device["fan_speed"]
        )

    @property
    def supported_features(self) -> int:
        """Flag supported features. Speed Only."""
        return SUPPORT_SET_SPEED

    async def async_turn_on(
        self,
        speed: str = None,
        percentage: int = None,
        preset_mode: str = None,
        **kwargs,
    ):
        """Turn the fan on."""
        if percentage is None:
            percentage = DEFAULT_ON_PERCENTAGE

        await self.async_set_percentage(percentage)

    async def async_turn_off(self, **kwargs):
        """Turn the fan off."""
        await self.async_set_percentage(0)

    async def async_set_percentage(self, percentage: int) -> None:
        """Set the speed of the fan."""
        if percentage == 0:
            named_speed = FAN_OFF
        else:
            named_speed = percentage_to_ordered_list_item(
                ORDERED_NAMED_FAN_SPEEDS, percentage
            )

        await self._smartbridge.set_fan(self.device_id, named_speed)

    @property
    def is_on(self):
        """Return true if device is on."""
        return self.percentage and self.percentage > 0

    async def async_update(self):
        """Update when forcing a refresh of the device."""
        self._device = self._smartbridge.get_device_by_id(self.device_id)
        _LOGGER.debug("State of this lutron fan device is %s", self._device)
{'fraction_non_alphanumeric': 0.08842988542843311, 'fraction_numerical': 0.0016136840406648378, 'mean_word_length': 3.0430528375733856, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 1, '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': '4730607', 'n_tokens_mistral': 2054, 'n_tokens_neox': 2039, 'n_words': 493}