1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-22 03:40:02 +00:00
Files
.devcontainer
.github
.vscode
docs
homeassistant
auth
components
abode
accuweather
acer_projector
acmeda
actiontec
adguard
ads
advantage_air
aftership
agent_dvr
air_quality
airly
airvisual
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
almond
alpha_vantage
amazon_polly
ambiclimate
ambient_station
amcrest
ampio
android_ip_webcam
androidtv
anel_pwrctrl
anthemav
apache_kafka
apcupsd
api
apns
apple_tv
apprise
aprs
aqualogic
aquostv
arcam_fmj
arduino
arest
arlo
arris_tg2492lg
aruba
arwn
asterisk_cdr
asterisk_mbox
asuswrt
atag
aten_pe
atome
august
aurora
aurora_abb_powerone
auth
automation
avea
avion
avri
awair
aws
axis
azure_devops
azure_event_hub
azure_service_bus
baidu
bayesian
bbb_gpio
bbox
beewi_smartclim
bh1750
binary_sensor
bitcoin
bizkaibus
blackbird
blebox
blink
blinksticklight
blinkt
blockchain
bloomsky
bluesound
bluetooth_le_tracker
bluetooth_tracker
bme280
bme680
bmp280
bmw_connected_drive
bom
bond
braviatv
broadlink
brother
brottsplatskartan
browser
brunt
bsblan
bt_home_hub_5
bt_smarthub
buienradar
caldav
calendar
camera
canary
cast
cert_expiry
channels
circuit
cisco_ios
cisco_mobility_express
cisco_webex_teams
citybikes
clementine
clickatell
clicksend
clicksend_tts
climate
cloud
cloudflare
cmus
co2signal
coinbase
coinmarketcap
comed_hourly_pricing
comfoconnect
command_line
concord232
config
configurator
control4
conversation
coolmaster
coronavirus
counter
cover
cppm_tracker
cpuspeed
crimereports
cups
currencylayer
daikin
danfoss_air
darksky
datadog
ddwrt
debugpy
deconz
decora
decora_wifi
default_config
delijn
deluge
demo
denon
denonavr
derivative
deutsche_bahn
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
dexcom
dht
dialogflow
digital_ocean
digitalloggers
directv
discogs
discord
discovery
dlib_face_detect
dlib_face_identify
dlink
dlna_dmr
dnsip
dominos
doods
doorbird
dovado
downloader
dsmr
dsmr_reader
dte_energy_bridge
dublin_bus_transport
duckdns
dunehd
dwd_weather_warnings
dweet
dynalite
dyson
eafm
ebox
ebusd
ecoal_boiler
ecobee
econet
ecovacs
eddystone_temperature
edimax
edl21
ee_brightbox
efergy
egardia
eight_sleep
elgato
eliqonline
elkm1
elv
emby
emoncms
emoncms_history
emulated_hue
emulated_kasa
emulated_roku
enigma2
enocean
enphase_envoy
entur_public_transport
environment_canada
envirophat
envisalink
ephember
epson
epsonworkforce
eq3btsmart
esphome
essent
etherscan
eufy
everlights
evohome
ezviz
facebook
facebox
fail2ban
familyhub
fan
fastdotcom
feedreader
ffmpeg
ffmpeg_motion
ffmpeg_noise
fibaro
fido
file
filesize
filter
fints
firmata
fitbit
fixer
fleetgo
flexit
flic
flick_electric
flo
flock
flume
flunearyou
flux
flux_led
folder
folder_watcher
foobot
forked_daapd
fortios
foscam
foursquare
free_mobile
freebox
freedns
fritz
fritzbox
fritzbox_callmonitor
fritzbox_netmonitor
fronius
frontend
frontier_silicon
futurenow
garadget
garmin_connect
gc100
gdacs
geizhals
generic
generic_thermostat
geniushub
geo_json_events
geo_location
geo_rss_events
geofency
geonetnz_quakes
geonetnz_volcano
gios
github
gitlab_ci
gitter
glances
gntp
goalfeed
goalzero
gogogate2
google
google_assistant
google_cloud
google_domains
google_maps
google_pubsub
google_translate
google_travel_time
google_wifi
gpmdp
gpsd
gpslogger
graphite
gree
greeneye_monitor
greenwave
griddy
group
growatt_server
gstreamer
gtfs
guardian
habitica
hangouts
harman_kardon_avr
harmony
hassio
haveibeenpwned
hddtemp
hdmi_cec
heatmiser
heos
here_travel_time
hikvision
hikvisioncam
hisense_aehw4a1
history
history_stats
hitron_coda
hive
hlk_sw16
home_connect
homeassistant
homekit
homekit_controller
homematic
homematicip_cloud
homeworks
honeywell
horizon
hp_ilo
html5
http
htu21d
huawei_lte
huawei_router
hue
humidifier
hunterdouglas_powerview
hvv_departures
hydrawise
hyperion
ialarm
iammeter
iaqualink
icloud
idteck_prox
ifttt
iglo
ign_sismologia
ihc
image
image_processing
imap
imap_email_content
incomfort
influxdb
input_boolean
input_datetime
input_number
input_select
input_text
insteon
integration
__init__.py
manifest.json
sensor.py
intent
intent_script
intesishome
ios
iota
iperf3
ipma
ipp
iqvia
irish_rail_transport
islamic_prayer_times
iss
isy994
itach
itunes
izone
jewish_calendar
joaoapps_join
juicenet
kaiterra
kankun
keba
keenetic_ndms2
kef
keyboard
keyboard_remote
kira
kiwi
knx
kodi
konnected
kwb
lacrosse
lametric
lannouncer
lastfm
launch_library
lcn
lg_netcast
lg_soundbar
life360
lifx
lifx_cloud
lifx_legacy
light
lightwave
limitlessled
linksys_smart
linode
linux_battery
lirc
litejet
llamalab_automate
local_file
local_ip
locative
lock
logbook
logentries
logger
logi_circle
london_air
london_underground
loopenergy
lovelace
luci
luftdaten
lupusec
lutron
lutron_caseta
lw12wifi
lyft
magicseaweed
mailbox
mailgun
manual
manual_mqtt
map
marytts
mastodon
matrix
maxcube
mcp23017
media_extractor
media_player
media_source
mediaroom
melcloud
melissa
meraki
message_bird
met
meteo_france
meteoalarm
metoffice
mfi
mhz19
microsoft
microsoft_face
microsoft_face_detect
microsoft_face_identify
miflora
mikrotik
mill
min_max
minecraft_server
minio
mitemp_bt
mjpeg
mobile_app
mochad
modbus
modem_callerid
mold_indicator
monoprice
moon
mpchc
mpd
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
msteams
mvglive
mychevy
mycroft
myq
mysensors
mystrom
mythicbeastsdns
n26
nad
namecheapdns
nanoleaf
neato
nederlandse_spoorwegen
nello
ness_alarm
nest
netatmo
netdata
netgear
netgear_lte
netio
neurio_energy
nexia
nextbus
nextcloud
nfandroidtv
nightscout
niko_home_control
nilu
nissan_leaf
nmap_tracker
nmbs
no_ip
noaa_tides
norway_air
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuimo_controller
nuki
numato
nut
nws
nx584
nzbget
oasa_telematics
obihai
octoprint
oem
ohmconnect
ombi
omnilogic
onboarding
onewire
onkyo
onvif
openalpr_cloud
openalpr_local
opencv
openerz
openevse
openexchangerates
opengarage
openhardwaremonitor
openhome
opensensemap
opensky
opentherm_gw
openuv
openweathermap
opnsense
opple
orangepi_gpio
oru
orvibo
osramlightify
otp
ovo_energy
owntracks
ozw
panasonic_bluray
panasonic_viera
pandora
panel_custom
panel_iframe
pcal9535a
pencom
persistent_notification
person
philips_js
pi4ioe5v9xxxx
pi_hole
picotts
piglow
pilight
ping
pioneer
pjlink
plaato
plant
plex
plugwise
plum_lightpad
pocketcasts
point
poolsense
powerwall
profiler
progettihwsw
proliphix
prometheus
prowl
proximity
proxmoxve
proxy
ps4
ptvsd
pulseaudio_loopback
push
pushbullet
pushover
pushsafer
pvoutput
pvpc_hourly_pricing
pyload
python_script
qbittorrent
qld_bushfire
qnap
qrcode
quantum_gateway
qvr_pro
qwikswitch
rachio
radarr
radiotherm
rainbird
raincloud
rainforest_eagle
rainmachine
random
raspihats
raspyrfm
recollect_waste
recorder
recswitch
reddit
rejseplanen
remember_the_milk
remote
remote_rpi_gpio
repetier
rest
rest_command
rflink
rfxtrx
ring
ripple
risco
rmvtransport
rocketchat
roku
roomba
roon
route53
rova
rpi_camera
rpi_gpio
rpi_gpio_pwm
rpi_pfio
rpi_power
rpi_rf
rss_feed_template
rtorrent
ruckus_unleashed
russound_rio
russound_rnet
sabnzbd
safe_mode
saj
salt
samsungtv
satel_integra
scene
schluter
scrape
script
scsgate
search
season
sendgrid
sense
sensehat
sensibo
sensor
sentry
serial
serial_pm
sesame
seven_segments
seventeentrack
sharkiq
shell_command
shelly
shiftr
shodan
shopping_list
sht31
sigfox
sighthound
signal_messenger
simplepush
simplisafe
simulated
sinch
sisyphus
sky_hub
skybeacon
skybell
slack
sleepiq
slide
sma
smappee
smart_meter_texas
smarthab
smartthings
smarty
smhi
sms
smtp
snapcast
snips
snmp
sochain
socialblade
solaredge
solaredge_local
solarlog
solax
soma
somfy
somfy_mylink
sonarr
songpal
sonos
sony_projector
soundtouch
spaceapi
spc
speedtestdotnet
spider
splunk
spotcrime
spotify
sql
squeezebox
ssdp
starline
starlingbank
startca
statistics
statsd
steam_online
stiebel_eltron
stookalert
stream
streamlabswater
stt
suez_water
sun
supervisord
supla
surepetcare
swiss_hydrological_data
swiss_public_transport
swisscom
switch
switchbot
switcher_kis
switchmate
syncthru
synology
synology_chat
synology_dsm
synology_srm
syslog
system_health
system_log
systemmonitor
tado
tag
tahoma
tank_utility
tankerkoenig
tapsaff
tasmota
tautulli
tcp
ted5000
telegram
telegram_bot
tellduslive
tellstick
telnet
temper
template
tensorflow
tesla
tfiac
thermoworks_smoke
thethingsnetwork
thingspeak
thinkingcleaner
thomson
threshold
tibber
tikteck
tile
time_date
timer
tmb
tod
todoist
tof
tomato
toon
torque
totalconnect
touchline
tplink
tplink_lte
traccar
trackr
tradfri
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
travisci
trend
tts
tuya
twentemilieu
twilio
twilio_call
twilio_sms
twitch
twitter
ubee
ubus
ue_smart_radio
uk_transport
unifi
unifi_direct
unifiled
universal
upb
upc_connect
upcloud
updater
upnp
uptime
uptimerobot
uscis
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
vultr
w800rf32
wake_on_lan
waqi
water_heater
waterfurnace
watson_iot
watson_tts
waze_travel_time
weather
webhook
webostv
websocket_api
wemo
whois
wiffi
wilight
wink
wirelesstag
withings
wled
wolflink
workday
worldclock
worldtidesinfo
worxlandroid
wsdot
wunderground
x10
xbee
xbox
xbox_live
xeoma
xfinity
xiaomi
xiaomi_aqara
xiaomi_miio
xiaomi_tv
xmpp
xs1
yale_smart_alarm
yamaha
yamaha_musiccast
yandex_transport
yandextts
yeelight
yeelightsunflower
yessssms
yi
zabbix
zamg
zengge
zeroconf
zerproc
zestimate
zha
zhong_hong
ziggo_mediabox_xl
zodiac
zone
zoneminder
zwave
__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
rootfs
script
tests
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.ignore
.pre-commit-config.yaml
.prettierignore
.readthedocs.yml
.travis.yml
.yamllint
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
azure-pipelines-ci.yml
azure-pipelines-release.yml
azure-pipelines-translation.yml
azure-pipelines-wheels.yml
build.json
codecov.yml
pyproject.toml
requirements.txt
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt
setup.cfg
setup.py
tox.ini
core/homeassistant/components/integration/sensor.py

212 lines
6.6 KiB
Python

"""Numeric integration of data coming from a source sensor over time."""
from decimal import Decimal, DecimalException
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
CONF_NAME,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
TIME_DAYS,
TIME_HOURS,
TIME_MINUTES,
TIME_SECONDS,
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.restore_state import RestoreEntity
# mypy: allow-untyped-defs, no-check-untyped-defs
_LOGGER = logging.getLogger(__name__)
ATTR_SOURCE_ID = "source"
CONF_SOURCE_SENSOR = "source"
CONF_ROUND_DIGITS = "round"
CONF_UNIT_PREFIX = "unit_prefix"
CONF_UNIT_TIME = "unit_time"
CONF_UNIT_OF_MEASUREMENT = "unit"
CONF_METHOD = "method"
TRAPEZOIDAL_METHOD = "trapezoidal"
LEFT_METHOD = "left"
RIGHT_METHOD = "right"
INTEGRATION_METHOD = [TRAPEZOIDAL_METHOD, LEFT_METHOD, RIGHT_METHOD]
# SI Metric prefixes
UNIT_PREFIXES = {None: 1, "k": 10 ** 3, "M": 10 ** 6, "G": 10 ** 9, "T": 10 ** 12}
# SI Time prefixes
UNIT_TIME = {
TIME_SECONDS: 1,
TIME_MINUTES: 60,
TIME_HOURS: 60 * 60,
TIME_DAYS: 24 * 60 * 60,
}
ICON = "mdi:chart-histogram"
DEFAULT_ROUND = 3
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_NAME): cv.string,
vol.Required(CONF_SOURCE_SENSOR): cv.entity_id,
vol.Optional(CONF_ROUND_DIGITS, default=DEFAULT_ROUND): vol.Coerce(int),
vol.Optional(CONF_UNIT_PREFIX, default=None): vol.In(UNIT_PREFIXES),
vol.Optional(CONF_UNIT_TIME, default=TIME_HOURS): vol.In(UNIT_TIME),
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
vol.Optional(CONF_METHOD, default=TRAPEZOIDAL_METHOD): vol.In(
INTEGRATION_METHOD
),
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the integration sensor."""
integral = IntegrationSensor(
config[CONF_SOURCE_SENSOR],
config.get(CONF_NAME),
config[CONF_ROUND_DIGITS],
config[CONF_UNIT_PREFIX],
config[CONF_UNIT_TIME],
config.get(CONF_UNIT_OF_MEASUREMENT),
config[CONF_METHOD],
)
async_add_entities([integral])
class IntegrationSensor(RestoreEntity):
"""Representation of an integration sensor."""
def __init__(
self,
source_entity,
name,
round_digits,
unit_prefix,
unit_time,
unit_of_measurement,
integration_method,
):
"""Initialize the integration sensor."""
self._sensor_source_id = source_entity
self._round_digits = round_digits
self._state = 0
self._method = integration_method
self._name = name if name is not None else f"{source_entity} integral"
if unit_of_measurement is None:
self._unit_template = (
f"{'' if unit_prefix is None else unit_prefix}{{}}{unit_time}"
)
# we postpone the definition of unit_of_measurement to later
self._unit_of_measurement = None
else:
self._unit_of_measurement = unit_of_measurement
self._unit_prefix = UNIT_PREFIXES[unit_prefix]
self._unit_time = UNIT_TIME[unit_time]
async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
try:
self._state = Decimal(state.state)
except ValueError as err:
_LOGGER.warning("Could not restore last state: %s", err)
@callback
def calc_integration(event):
"""Handle the sensor state changes."""
old_state = event.data.get("old_state")
new_state = event.data.get("new_state")
if (
old_state is None
or old_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]
or new_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]
):
return
if self._unit_of_measurement is None:
unit = new_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
self._unit_of_measurement = self._unit_template.format(
"" if unit is None else unit
)
try:
# integration as the Riemann integral of previous measures.
area = 0
elapsed_time = (
new_state.last_updated - old_state.last_updated
).total_seconds()
if self._method == TRAPEZOIDAL_METHOD:
area = (
(Decimal(new_state.state) + Decimal(old_state.state))
* Decimal(elapsed_time)
/ 2
)
elif self._method == LEFT_METHOD:
area = Decimal(old_state.state) * Decimal(elapsed_time)
elif self._method == RIGHT_METHOD:
area = Decimal(new_state.state) * Decimal(elapsed_time)
integral = area / (self._unit_prefix * self._unit_time)
assert isinstance(integral, Decimal)
except ValueError as err:
_LOGGER.warning("While calculating integration: %s", err)
except DecimalException as err:
_LOGGER.warning(
"Invalid state (%s > %s): %s", old_state.state, new_state.state, err
)
except AssertionError as err:
_LOGGER.error("Could not calculate integral: %s", err)
else:
self._state += integral
self.async_write_ha_state()
async_track_state_change_event(
self.hass, [self._sensor_source_id], calc_integration
)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return round(self._state, self._round_digits)
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def device_state_attributes(self):
"""Return the state attributes of the sensor."""
return {ATTR_SOURCE_ID: self._sensor_source_id}
@property
def icon(self):
"""Return the icon to use in the frontend."""
return ICON