<commit_before>"""Get ride details and liveboard details for NMBS (Belgian railway)."""
import logging

from pyrail import iRail
import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    ATTR_ATTRIBUTION,
    ATTR_LATITUDE,
    ATTR_LONGITUDE,
    CONF_NAME,
    CONF_SHOW_ON_MAP,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
import homeassistant.util.dt as dt_util

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = "NMBS"

DEFAULT_ICON = "mdi:train"
DEFAULT_ICON_ALERT = "mdi:alert-octagon"

CONF_STATION_FROM = "station_from"
CONF_STATION_TO = "station_to"
CONF_STATION_LIVE = "station_live"
CONF_EXCLUDE_VIAS = "exclude_vias"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_STATION_FROM): cv.string,
        vol.Required(CONF_STATION_TO): cv.string,
        vol.Optional(CONF_STATION_LIVE): cv.string,
        vol.Optional(CONF_EXCLUDE_VIAS, default=False): cv.boolean,
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
        vol.Optional(CONF_SHOW_ON_MAP, default=False): cv.boolean,
    }
)


def get_time_until(departure_time=None):
    """Calculate the time between now and a train's departure time."""
    if departure_time is None:
        return 0

    delta = dt_util.utc_from_timestamp(int(departure_time)) - dt_util.now()
    return round((delta.total_seconds() / 60))


def get_delay_in_minutes(delay=0):
    """Get the delay in minutes from a delay in seconds."""
    return round((int(delay) / 60))


def get_ride_duration(departure_time, arrival_time, delay=0):
    """Calculate the total travel time in minutes."""
    duration = dt_util.utc_from_timestamp(
        int(arrival_time)
    ) - dt_util.utc_from_timestamp(int(departure_time))
    duration_time = int(round((duration.total_seconds() / 60)))
    return duration_time + get_delay_in_minutes(delay)


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the NMBS sensor with iRail API."""

    api_client = iRail()

    name = config[CONF_NAME]
    show_on_map = config[CONF_SHOW_ON_MAP]
    station_from = config[CONF_STATION_FROM]
    station_to = config[CONF_STATION_TO]
    station_live = config.get(CONF_STATION_LIVE)
    excl_vias = config[CONF_EXCLUDE_VIAS]

    sensors = [
        NMBSSensor(api_client, name, show_on_map, station_from, station_to, excl_vias)
    ]

    if station_live is not None:
        sensors.append(NMBSLiveBoard(api_client, station_live))

    add_entities(sensors, True)


class NMBSLiveBoard(Entity):
    """Get the next train from a station's liveboard."""

    def __init__(self, api_client, live_station):
        """Initialize the sensor for getting liveboard data."""
        self._station = live_station
        self._api_client = api_client

        self._attrs = {}
        self._state = None

    @property
    def name(self):
        """Return the sensor default name."""
        return "NMBS Live"

    @property
    def icon(self):
        """Return the default icon or an alert icon if delays."""
        if self._attrs and int(self._attrs["delay"]) > 0:
            return DEFAULT_ICON_ALERT

        return DEFAULT_ICON

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

    @property
    def device_state_attributes(self):
        """Return the sensor attributes if data is available."""<commit_msg>Make name of nmbs live sensor customizable via unique_id (#29662)<commit_after>"""Get ride details and liveboard details for NMBS (Belgian railway)."""
import logging

from pyrail import iRail
import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    ATTR_ATTRIBUTION,
    ATTR_LATITUDE,
    ATTR_LONGITUDE,
    CONF_NAME,
    CONF_SHOW_ON_MAP,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
import homeassistant.util.dt as dt_util

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = "NMBS"

DEFAULT_ICON = "mdi:train"
DEFAULT_ICON_ALERT = "mdi:alert-octagon"

CONF_STATION_FROM = "station_from"
CONF_STATION_TO = "station_to"
CONF_STATION_LIVE = "station_live"
CONF_EXCLUDE_VIAS = "exclude_vias"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_STATION_FROM): cv.string,
        vol.Required(CONF_STATION_TO): cv.string,
        vol.Optional(CONF_STATION_LIVE): cv.string,
        vol.Optional(CONF_EXCLUDE_VIAS, default=False): cv.boolean,
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
        vol.Optional(CONF_SHOW_ON_MAP, default=False): cv.boolean,
    }
)


def get_time_until(departure_time=None):
    """Calculate the time between now and a train's departure time."""
    if departure_time is None:
        return 0

    delta = dt_util.utc_from_timestamp(int(departure_time)) - dt_util.now()
    return round((delta.total_seconds() / 60))


def get_delay_in_minutes(delay=0):
    """Get the delay in minutes from a delay in seconds."""
    return round((int(delay) / 60))


def get_ride_duration(departure_time, arrival_time, delay=0):
    """Calculate the total travel time in minutes."""
    duration = dt_util.utc_from_timestamp(
        int(arrival_time)
    ) - dt_util.utc_from_timestamp(int(departure_time))
    duration_time = int(round((duration.total_seconds() / 60)))
    return duration_time + get_delay_in_minutes(delay)


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the NMBS sensor with iRail API."""

    api_client = iRail()

    name = config[CONF_NAME]
    show_on_map = config[CONF_SHOW_ON_MAP]
    station_from = config[CONF_STATION_FROM]
    station_to = config[CONF_STATION_TO]
    station_live = config.get(CONF_STATION_LIVE)
    excl_vias = config[CONF_EXCLUDE_VIAS]

    sensors = [
        NMBSSensor(api_client, name, show_on_map, station_from, station_to, excl_vias)
    ]

    if station_live is not None:
        sensors.append(NMBSLiveBoard(api_client, station_live))

    add_entities(sensors, True)


class NMBSLiveBoard(Entity):
    """Get the next train from a station's liveboard."""

    def __init__(self, api_client, live_station):
        """Initialize the sensor for getting liveboard data."""
        self._station = live_station
        self._api_client = api_client
        self._unique_id = f"nmbs_live_{self._station}"
        self._attrs = {}
        self._state = None

    @property
    def name(self):
        """Return the sensor default name."""
        return "NMBS Live"

    @property
    def unique_id(self):
        """Return a unique ID."""
        return self._unique_id

    @property
    def icon(self):
        """Return the default icon or an alert icon if delays."""
        if self._attrs and int(self._attrs["delay"]) > 0:
            return DEFAULT_ICON_ALERT

        return DEFAULT_ICON

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

    @property
    def device_state_attributes(self):
        """Return the sensor attributes if data is available."""
{'fraction_non_alphanumeric': 0.0973093545239091, 'fraction_numerical': 0.0034852920674752546, 'mean_word_length': 3.6644993498049416, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, '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': '1545596', 'n_tokens_mistral': 2377, 'n_tokens_neox': 2275, 'n_words': 539}