1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-10 22:10:02 +00:00
Files
.devcontainer
.github
.vscode
docs
homeassistant
auth
backports
brands
components
3_day_blinds
abode
accuweather
acer_projector
acmeda
actiontec
adax
adguard
ads
advantage_air
aemet
aftership
agent_dvr
air_quality
airly
airnow
airq
airthings
airthings_ble
airtouch4
airvisual
airvisual_pro
airzone
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
almond
alpha_vantage
amazon_polly
amberelectric
ambiclimate
ambient_station
amcrest
amp_motorization
ampio
analytics
android_ip_webcam
androidtv
anel_pwrctrl
anthemav
anwb_energie
apache_kafka
apcupsd
api
apple_tv
application_credentials
apprise
aprs
aqualogic
aquostv
aranet
arcam_fmj
arest
arris_tg2492lg
aruba
arwn
aseko_pool_live
asterisk_cdr
asterisk_mbox
asuswrt
atag
aten_pe
atome
august
august_ble
aurora
aurora_abb_powerone
aussie_broadband
auth
automation
avea
avion
awair
aws
axis
azure_devops
azure_event_hub
azure_service_bus
backup
baf
baidu
balboa
bayesian
bbox
beewi_smartclim
binary_sensor
bitcoin
bizkaibus
blackbird
blebox
blink
blinksticklight
bliss_automation
bloc_blinds
blockchain
bloomsky
bluemaestro
blueprint
bluesound
bluetooth
bluetooth_adapters
bluetooth_le_tracker
bluetooth_tracker
bmw_connected_drive
bond
bosch_shc
brandt
braviatv
brel_home
broadlink
brother
brottsplatskartan
browser
brunt
bsblan
bswitch
bt_home_hub_5
bt_smarthub
bthome
bticino
bubendorff
buienradar
button
caldav
calendar
camera
canary
cast
cert_expiry
channels
circuit
cisco_ios
cisco_mobility_express
cisco_webex_teams
citybikes
clementine
clickatell
clicksend
clicksend_tts
climacell
climate
cloud
cloudflare
cmus
co2signal
coinbase
color_extractor
comed_hourly_pricing
comfoconnect
command_line
compensation
concord232
config
configurator
control4
conversation
coolmaster
coronavirus
counter
cover
cozytouch
cppm_tracker
cpuspeed
crownstone
cups
currencylayer
dacia
daikin
danfoss_air
darksky
datadog
ddwrt
debugpy
deconz
decora
decora_wifi
default_config
delijn
deluge
demo
denon
denonavr
derivative
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
devolo_home_network
dexcom
dhcp
diagnostics
dialogflow
diaz
digital_loggers
digital_ocean
directv
discogs
discord
discovery
dlib_face_detect
dlib_face_identify
dlink
dlna_dmr
dlna_dms
dnsip
dominos
doods
doorbird
dooya
dovado
downloader
dsmr
dsmr_reader
dte_energy_bridge
dublin_bus_transport
duckdns
dunehd
dwd_weather_warnings
dweet
dynalite
eafm
ebox
ebusd
ecoal_boiler
ecobee
econet
ecovacs
ecowitt
eddystone_temperature
edimax
edl21
efergy
egardia
eight_sleep
elgato
eliqonline
elkm1
elmax
elv
emby
emoncms
emoncms_history
emonitor
emulated_hue
emulated_kasa
emulated_roku
energie_vanons
energy
energyzero
enigma2
enocean
enphase_envoy
entur_public_transport
environment_canada
envisalink
ephember
epson
epsonworkforce
eq3btsmart
escea
esphome
etherscan
eufy
everlights
evil_genius_labs
evohome
ezviz
faa_delays
facebook
facebox
fail2ban
familyhub
fan
fastdotcom
feedreader
ffmpeg
ffmpeg_motion
ffmpeg_noise
fibaro
fido
file
file_upload
filesize
filter
fints
fireservicerota
firmata
fitbit
fivem
fixer
fjaraskupan
fleetgo
flexit
flexom
flic
flick_electric
flipr
flo
flock
flume
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
fortios
foscam
foursquare
free_mobile
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
frontier_silicon
fully_kiosk
futurenow
garadget
garages_amsterdam
gaviota
gc100
gdacs
generic
generic_hygrostat
generic_thermostat
geniushub
geo_json_events
geo_location
geo_rss_events
geocaching
geofency
geonetnz_quakes
geonetnz_volcano
gios
github
gitlab_ci
gitter
glances
goalfeed
goalzero
gogogate2
goodwe
google
google_assistant
google_assistant_sdk
google_cloud
google_domains
google_mail
google_maps
google_pubsub
google_sheets
google_translate
google_travel_time
google_wifi
govee_ble
gpsd
gpslogger
graphite
gree
greeneye_monitor
greenwave
group
growatt_server
gstreamer
gtfs
guardian
habitica
hardkernel
hardware
harman_kardon_avr
harmony
hassio
havana_shade
haveibeenpwned
hddtemp
hdmi_cec
heatmiser
heiwa
heos
here_travel_time
hexaom
hi_kumo
hikvision
hikvisioncam
hisense_aehw4a1
history
history_stats
hitron_coda
hive
hlk_sw16
home_connect
home_plus_control
homeassistant
homeassistant_alerts
homeassistant_hardware
homeassistant_sky_connect
homeassistant_yellow
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
homeworks
honeywell
horizon
hp_ilo
html5
http
huawei_lte
hue
huisbaasje
humidifier
hunterdouglas_powerview
hurrican_shutters_wholesale
hvv_departures
hydrawise
hyperion
ialarm
iammeter
iaqualink
ibeacon
icloud
idteck_prox
ifttt
iglo
ign_sismologia
ihc
image_processing
image_upload
imap
imap_email_content
incomfort
influxdb
inkbird
input_boolean
input_button
input_datetime
translations
__init__.py
manifest.json
recorder.py
reproduce_state.py
services.yaml
strings.json
input_number
input_select
input_text
inspired_shades
insteon
integration
intellifire
intent
intent_script
intesishome
ios
iotawatt
iperf3
ipma
ipp
iqvia
irish_rail_transport
islamic_prayer_times
ismartwindow
iss
isy994
itach
itunes
izone
jellyfin
jewish_calendar
joaoapps_join
juicenet
justnimbus
kaiterra
kaleidescape
kankun
keba
keenetic_ndms2
kef
kegtron
keyboard
keyboard_remote
keymitt_ble
kira
kitchen_sink
kiwi
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
kulersky
kwb
lacrosse
lacrosse_view
lametric
landisgyr_heat_meter
lannouncer
lastfm
launch_library
laundrify
lcn
ld2410_ble
led_ble
legrand
lg_netcast
lg_soundbar
lidarr
life360
lifx
lifx_cloud
light
lightwave
limitlessled
linksys_smart
linode
linux_battery
lirc
litejet
litterrobot
livisi
llamalab_automate
local_calendar
local_file
local_ip
locative
lock
logbook
logentries
logger
logi_circle
london_air
london_underground
lookin
lovelace
luci
luftdaten
lupusec
lutron
lutron_caseta
luxaflex
lw12wifi
lyric
magicseaweed
mailbox
mailgun
manual
manual_mqtt
map
marantz
martec
marytts
mastodon
matrix
matter
maxcube
mazda
meater
media_extractor
media_player
media_source
mediaroom
melcloud
melissa
melnor
meraki
message_bird
met
met_eireann
meteo_france
meteoalarm
meteoclimatic
metoffice
mfi
microsoft
microsoft_face
microsoft_face_detect
microsoft_face_identify
miflora
mijndomein_energie
mikrotik
mill
min_max
minecraft_server
minio
mitemp_bt
mjpeg
moat
mobile_app
mochad
modbus
modem_callerid
modern_forms
moehlenhoff_alpha2
mold_indicator
monoprice
moon
motion_blinds
motioneye
mpd
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
msteams
mullvad
mutesync
mvglive
my
mycroft
myq
mysensors
mystrom
mythicbeastsdns
nad
nam
namecheapdns
nanoleaf
neato
nederlandse_spoorwegen
ness_alarm
nest
netatmo
netdata
netgear
netgear_lte
netio
network
neurio_energy
nexia
nexity
nextbus
nextcloud
nextdns
nfandroidtv
nibe_heatpump
nightscout
niko_home_control
nilu
nina
nissan_leaf
nmap_tracker
nmbs
no_ip
noaa_tides
nobo_hub
norway_air
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuki
numato
number
nut
nutrichef
nws
nx584
nzbget
oasa_telematics
obihai
octoprint
oem
ohmconnect
ombi
omnilogic
onboarding
oncue
ondilo_ico
onewire
onkyo
onvif
open_meteo
openalpr_cloud
openalpr_local
opencv
openerz
openevse
openexchangerates
opengarage
openhardwaremonitor
openhome
opensensemap
opensky
opentherm_gw
openuv
openweathermap
opnsense
opple
oralb
oru
orvibo
osramlightify
otp
overkiz
ovo_energy
owntracks
p1_monitor
panasonic_bluray
panasonic_viera
pandora
panel_custom
panel_iframe
pcs_lighting
peco
pencom
persistent_notification
person
philips_js
pi_hole
picnic
picotts
pilight
ping
pioneer
pjlink
plaato
plant
plex
plugwise
plum_lightpad
pocketcasts
point
poolsense
powerwall
profiler
progettihwsw
proliphix
prometheus
prosegur
prowl
proximity
proxmoxve
proxy
prusalink
ps4
pulseaudio_loopback
pure_energie
purpleair
push
pushbullet
pushover
pushsafer
pvoutput
pvpc_hourly_pricing
pyload
python_script
qbittorrent
qingping
qld_bushfire
qnap
qnap_qsw
qrcode
quantum_gateway
qvr_pro
qwikswitch
rachio
radarr
radio_browser
radiotherm
rainbird
raincloud
rainforest_eagle
rainmachine
random
raspberry_pi
raspyrfm
raven_rock_mfg
rdw
recollect_waste
recorder
recswitch
reddit
rejseplanen
remember_the_milk
remote
remote_rpi_gpio
renault
reolink
repairs
repetier
rest
rest_command
rexel
rflink
rfxtrx
rhasspy
ridwell
ring
ripple
risco
rituals_perfume_genie
rmvtransport
roborock
rocketchat
roku
roomba
roon
route53
rova
rpi_camera
rpi_power
rss_feed_template
rtorrent
rtsp_to_webrtc
ruckus_unleashed
russound_rio
russound_rnet
ruuvi_gateway
ruuvitag_ble
sabnzbd
safe_mode
saj
samsungtv
satel_integra
scene
schedule
schluter
scrape
screenaway
screenlogic
script
scsgate
search
season
select
sendgrid
sense
senseme
sensibo
sensirion_ble
sensor
sensorblue
sensorpro
sensorpush
sentry
senz
serial
serial_pm
sesame
seven_segments
seventeentrack
sfr_box
sharkiq
shell_command
shelly
shiftr
shodan
shopping_list
sia
sigfox
sighthound
signal_messenger
simplepush
simplisafe
simply_automated
simu
simulated
sinch
siren
sisyphus
sky_hub
skybeacon
skybell
slack
sleepiq
slide
slimproto
sma
smappee
smart_blinds
smart_home
smart_meter_texas
smarther
smartthings
smarttub
smarty
smhi
sms
smtp
snapcast
snips
snmp
snooz
solaredge
solaredge_local
solarlog
solax
soma
somfy
somfy_mylink
sonarr
songpal
sonos
sony_projector
soundtouch
spaceapi
spc
speedtestdotnet
spider
splunk
spotify
sql
squeezebox
srp_energy
ssdp
starline
starlingbank
starlink
startca
statistics
statsd
steam_online
steamist
stiebel_eltron
stookalert
stream
streamlabswater
stt
subaru
suez_water
sun
supervisord
supla
surepetcare
swiss_hydrological_data
swiss_public_transport
swisscom
switch
switch_as_x
switchbee
switchbot
switcher_kis
switchmate
symfonisk
syncthing
syncthru
synology_chat
synology_dsm
synology_srm
syslog
system_bridge
system_health
system_log
systemmonitor
tado
tag
tailscale
tank_utility
tankerkoenig
tapsaff
tasmota
tautulli
tcp
ted5000
telegram
telegram_bot
tellduslive
tellstick
telnet
temper
template
tensorflow
tesla_wall_connector
text
tfiac
thermobeacon
thermoplus
thermopro
thermoworks_smoke
thethingsnetwork
thingspeak
thinkingcleaner
thomson
threshold
tibber
tikteck
tile
tilt_ble
time_date
timer
tmb
tod
todoist
tolo
tomato
tomorrowio
toon
torque
totalconnect
touchline
tplink
tplink_lte
traccar
trace
tractive
tradfri
trafikverket_ferry
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
travisci
trend
tts
tuya
twentemilieu
twilio
twilio_call
twilio_sms
twinkly
twitch
twitter
ubiwizz
ubus
ue_smart_radio
uk_transport
ukraine_alarm
ultraloq
unifi
unifi_direct
unifiled
unifiprotect
universal
upb
upc_connect
upcloud
update
upnp
uprise_smart_shades
uptime
uptimerobot
usb
usgs_earthquakes_feed
utility_meter
uvc
vacuum
vallox
vasttrafik
velbus
velux
venstar
vera
verisure
versasense
version
vesync
viaggiatreno
vicare
vilfo
vivotek
vizio
vlc
vlc_telnet
voicerss
volkszaehler
volumio
volvooncall
vulcan
vultr
w800rf32
wake_on_lan
wallbox
waqi
water_heater
waterfurnace
watson_iot
watson_tts
watttime
waze_travel_time
weather
webhook
webostv
websocket_api
wemo
whirlpool
whois
wiffi
wilight
wirelesstag
withings
wiz
wled
wolflink
workday
worldclock
worldtidesinfo
worxlandroid
ws66i
wsdot
x10
xbox
xbox_live
xeoma
xiaomi
xiaomi_aqara
xiaomi_ble
xiaomi_miio
xiaomi_tv
xmpp
xs1
yale_smart_alarm
yalexs_ble
yamaha
yamaha_musiccast
yandex_transport
yandextts
yeelight
yeelightsunflower
yi
yolink
youless
zabbix
zamg
zengge
zeroconf
zerproc
zestimate
zeversolar
zha
zhong_hong
ziggo_mediabox_xl
zodiac
zone
zoneminder
zwave_js
zwave_me
__init__.py
generated
helpers
scripts
util
__init__.py
__main__.py
block_async_io.py
bootstrap.py
config.py
config_entries.py
const.py
core.py
data_entry_flow.py
exceptions.py
loader.py
package_constraints.txt
requirements.py
runner.py
setup.py
strings.json
machine
pylint
rootfs
script
tests
.core_files.yaml
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.pre-commit-config.yaml
.prettierignore
.readthedocs.yml
.strict-typing
.yamllint
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
build.yaml
codecov.yml
mypy.ini
pyproject.toml
requirements.txt
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt
setup.cfg
core/homeassistant/components/input_datetime/reproduce_state.py
2021-10-17 20:15:48 +02:00

95 lines
2.7 KiB
Python

"""Reproduce an Input datetime state."""
from __future__ import annotations
import asyncio
from collections.abc import Iterable
import logging
from typing import Any
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import Context, HomeAssistant, State
from homeassistant.util import dt as dt_util
from . import ATTR_DATE, ATTR_DATETIME, ATTR_TIME, CONF_HAS_DATE, CONF_HAS_TIME, DOMAIN
_LOGGER = logging.getLogger(__name__)
def is_valid_datetime(string: str) -> bool:
"""Test if string dt is a valid datetime."""
try:
return dt_util.parse_datetime(string) is not None
except ValueError:
return False
def is_valid_date(string: str) -> bool:
"""Test if string dt is a valid date."""
return dt_util.parse_date(string) is not None
def is_valid_time(string: str) -> bool:
"""Test if string dt is a valid time."""
return dt_util.parse_time(string) is not None
async def _async_reproduce_state(
hass: HomeAssistant,
state: State,
*,
context: Context | None = None,
reproduce_options: dict[str, Any] | None = None,
) -> None:
"""Reproduce a single state."""
if (cur_state := hass.states.get(state.entity_id)) is None:
_LOGGER.warning("Unable to find entity %s", state.entity_id)
return
has_time = cur_state.attributes.get(CONF_HAS_TIME)
has_date = cur_state.attributes.get(CONF_HAS_DATE)
if not (
(is_valid_datetime(state.state) and has_date and has_time)
or (is_valid_date(state.state) and has_date and not has_time)
or (is_valid_time(state.state) and has_time and not has_date)
):
_LOGGER.warning(
"Invalid state specified for %s: %s", state.entity_id, state.state
)
return
# Return if we are already at the right state.
if cur_state.state == state.state:
return
service_data = {ATTR_ENTITY_ID: state.entity_id}
if has_time and has_date:
service_data[ATTR_DATETIME] = state.state
elif has_time:
service_data[ATTR_TIME] = state.state
elif has_date:
service_data[ATTR_DATE] = state.state
await hass.services.async_call(
DOMAIN, "set_datetime", service_data, context=context, blocking=True
)
async def async_reproduce_states(
hass: HomeAssistant,
states: Iterable[State],
*,
context: Context | None = None,
reproduce_options: dict[str, Any] | None = None,
) -> None:
"""Reproduce Input datetime states."""
await asyncio.gather(
*(
_async_reproduce_state(
hass, state, context=context, reproduce_options=reproduce_options
)
for state in states
)
)