core/homeassistant/components/moon/sensor.py

73 lines
1.9 KiB
Python
Raw Normal View History

"""Support for tracking the moon phases."""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
2019-07-31 19:25:30 +00:00
from homeassistant.const import CONF_NAME
import homeassistant.util.dt as dt_util
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
2019-07-31 19:25:30 +00:00
DEFAULT_NAME = "Moon"
2019-07-31 19:25:30 +00:00
ICON = "mdi:brightness-3"
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string}
)
2019-07-31 19:25:30 +00:00
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Moon sensor."""
name = config.get(CONF_NAME)
async_add_entities([MoonSensor(name)], True)
class MoonSensor(Entity):
"""Representation of a Moon sensor."""
def __init__(self, name):
"""Initialize the sensor."""
self._name = name
self._state = None
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def state(self):
"""Return the state of the device."""
2017-03-09 21:54:04 +00:00
if self._state == 0:
2019-07-31 19:25:30 +00:00
return "new_moon"
if self._state < 7:
2019-07-31 19:25:30 +00:00
return "waxing_crescent"
if self._state == 7:
2019-07-31 19:25:30 +00:00
return "first_quarter"
if self._state < 14:
2019-07-31 19:25:30 +00:00
return "waxing_gibbous"
if self._state == 14:
2019-07-31 19:25:30 +00:00
return "full_moon"
if self._state < 21:
2019-07-31 19:25:30 +00:00
return "waning_gibbous"
if self._state == 21:
2019-07-31 19:25:30 +00:00
return "last_quarter"
return "waning_crescent"
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return ICON
2018-06-04 12:44:55 +00:00
async def async_update(self):
"""Get the time and updates the states."""
from astral import Astral
today = dt_util.as_local(dt_util.utcnow()).date()
self._state = Astral().moon_phase(today)