mirror of
https://github.com/home-assistant/core.git
synced 2025-08-21 03:10:02 +00:00
.devcontainer
.github
.vscode
docs
homeassistant
auth
components
abode
acer_projector
actiontec
adguard
ads
aftership
air_quality
airly
airvisual
aladdin_connect
alarm_control_panel
alarmdecoder
alarmdotcom
alert
alexa
alpha_vantage
amazon_polly
ambiclimate
ambient_station
amcrest
ampio
android_ip_webcam
androidtv
anel_pwrctrl
anthemav
apache_kafka
apcupsd
api
apns
apple_tv
aprs
aqualogic
aquostv
arcam_fmj
arduino
arest
arlo
aruba
arwn
asterisk_cdr
asterisk_mbox
asuswrt
atome
august
aurora
aurora_abb_powerone
auth
automatic
automation
avea
avion
awair
aws
axis
azure_event_hub
baidu
bayesian
bbb_gpio
bbox
beewi_smartclim
bh1750
binary_sensor
bitcoin
bizkaibus
blackbird
blink
blinksticklight
blinkt
blockchain
bloomsky
bluesound
bluetooth_le_tracker
bluetooth_tracker
bme280
bme680
bmw_connected_drive
bom
braviatv
broadlink
brottsplatskartan
browser
brunt
bt_home_hub_5
bt_smarthub
buienradar
caldav
calendar
camera
canary
cast
cert_expiry
channels
cisco_ios
cisco_mobility_express
cisco_webex_teams
ciscospark
citybikes
clementine
clickatell
clicksend
clicksend_tts
climate
cloud
cloudflare
cmus
co2signal
coinbase
coinmarketcap
comed_hourly_pricing
comfoconnect
command_line
concord232
config
configurator
conversation
coolmaster
counter
cover
cppm_tracker
cpuspeed
crimereports
cups
currencylayer
daikin
danfoss_air
darksky
datadog
ddwrt
deconz
decora
decora_wifi
default_config
delijn
deluge
demo
denon
denonavr
deutsche_bahn
device_automation
device_sun_light_trigger
device_tracker
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
dte_energy_bridge
dublin_bus_transport
duckdns
duke_energy
dunehd
dwd_weather_warnings
dweet
dyson
ebox
ebusd
ecoal_boiler
ecobee
econet
ecovacs
eddystone_temperature
edimax
ee_brightbox
efergy
egardia
eight_sleep
eliqonline
elkm1
elv
emby
emoncms
emoncms_history
emulated_hue
emulated_roku
enigma2
enocean
enphase_envoy
entur_public_transport
environment_canada
envirophat
envisalink
ephember
epson
epsonworkforce
eq3btsmart
esphome
essent
etherscan
eufy
everlights
evohome
facebook
facebox
fail2ban
familyhub
fan
fastdotcom
feedreader
ffmpeg
ffmpeg_motion
ffmpeg_noise
fibaro
fido
file
filesize
filter
fints
fitbit
fixer
fleetgo
flexit
flic
flock
flunearyou
flux
flux_led
folder
folder_watcher
foobot
fortigate
fortios
foscam
foursquare
free_mobile
freebox
freedns
fritz
fritzbox
fritzbox_callmonitor
fritzbox_netmonitor
fritzdect
fronius
frontend
frontier_silicon
futurenow
garadget
gc100
gearbest
geizhals
generic
generic_thermostat
geniushub
geo_json_events
geo_location
geo_rss_events
geofency
geonetnz_quakes
github
gitlab_ci
gitter
glances
gntp
goalfeed
gogogate2
google
google_assistant
google_cloud
google_domains
google_maps
google_pubsub
google_translate
google_travel_time
google_wifi
gpmdp
gpsd
gpslogger
graphite
greeneye_monitor
greenwave
group
growatt_server
gstreamer
gtfs
gtt
habitica
hangouts
harman_kardon_avr
harmony
hassio
haveibeenpwned
hddtemp
hdmi_cec
heatmiser
heos
here_travel_time
hikvision
hikvisioncam
hipchat
history
history_graph
history_stats
hitron_coda
hive
hlk_sw16
homeassistant
homekit
homekit_controller
homematic
homematicip_cloud
homeworks
honeywell
hook
horizon
hp_ilo
html5
http
htu21d
huawei_lte
huawei_router
hue
hunterdouglas_powerview
hydrawise
hydroquebec
hyperion
ialarm
iaqualink
icloud
idteck_prox
ifttt
iglo
ign_sismologia
ihc
image_processing
imap
imap_email_content
incomfort
influxdb
input_boolean
input_datetime
input_number
input_select
input_text
insteon
integration
intent_script
ios
iota
iperf3
ipma
iqvia
irish_rail_transport
islamic_prayer_times
iss
isy994
itach
itunes
izone
jewish_calendar
joaoapps_join
juicenet
kaiterra
kankun
keba
keenetic_ndms2
keyboard
keyboard_remote
kira
kiwi
knx
kodi
konnected
kwb
lacrosse
__init__.py
manifest.json
sensor.py
lametric
lannouncer
lastfm
launch_library
lcn
lg_netcast
lg_soundbar
life360
lifx
lifx_cloud
lifx_legacy
light
lightwave
limitlessled
linksys_smart
linky
linode
linux_battery
lirc
litejet
liveboxplaytv
llamalab_automate
local_file
locative
lock
lockitron
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
mediaroom
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
minio
mitemp_bt
mjpeg
mobile_app
mochad
modbus
modem_callerid
mold_indicator
monoprice
moon
mopar
mpchc
mpd
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
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
nextbus
nfandroidtv
niko_home_control
nilu
nissan_leaf
nmap_tracker
nmbs
no_ip
noaa_tides
norway_air
notify
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuimo_controller
nuki
nut
nws
nx584
nzbget
oasa_telematics
obihai
octoprint
oem
ohmconnect
ombi
onboarding
onewire
onkyo
onvif
openalpr_cloud
openalpr_local
opencv
openevse
openexchangerates
opengarage
openhardwaremonitor
openhome
opensensemap
opensky
opentherm_gw
openuv
openweathermap
opple
orangepi_gpio
orvibo
osramlightify
otp
owlet
owntracks
panasonic_bluray
panasonic_viera
pandora
panel_custom
panel_iframe
pencom
persistent_notification
person
philips_js
pi_hole
picotts
piglow
pilight
ping
pioneer
pjlink
plaato
plant
plex
plugwise
plum_lightpad
pocketcasts
point
postnl
prezzibenzina
proliphix
prometheus
prowl
proximity
proxy
ps4
ptvsd
pulseaudio_loopback
push
pushbullet
pushetta
pushover
pushsafer
pvoutput
pyload
python_script
qbittorrent
qld_bushfire
qnap
qrcode
quantum_gateway
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
rmvtransport
rocketchat
roku
roomba
route53
rova
rpi_camera
rpi_gpio
rpi_gpio_pwm
rpi_pfio
rpi_rf
rss_feed_template
rtorrent
russound_rio
russound_rnet
sabnzbd
saj
samsungtv
satel_integra
scene
scrape
script
scsgate
season
sendgrid
sense
sensehat
sensibo
sensor
serial
serial_pm
sesame
seven_segments
seventeentrack
shell_command
shiftr
shodan
shopping_list
sht31
sigfox
simplepush
simplisafe
simulated
sisyphus
sky_hub
skybeacon
skybell
slack
sleepiq
slide
sma
smappee
smarthab
smartthings
smarty
smhi
smtp
snapcast
snips
snmp
sochain
socialblade
solaredge
solaredge_local
solax
soma
somfy
somfy_mylink
sonarr
songpal
sonos
sony_projector
soundtouch
spaceapi
spc
speedtestdotnet
spider
splunk
spotcrime
spotify
sql
squeezebox
ssdp
starlingbank
startca
statistics
statsd
steam_online
stiebel_eltron
stream
streamlabswater
stride
suez_water
sun
supervisord
supla
swiss_hydrological_data
swiss_public_transport
swisscom
switch
switchbot
switcher_kis
switchmate
syncthru
synology
synology_chat
synology_srm
synologydsm
syslog
system_health
system_log
systemmonitor
tado
tahoma
tank_utility
tapsaff
tautulli
tcp
ted5000
teksavvy
telegram
telegram_bot
tellduslive
tellstick
telnet
temper
template
tensorflow
tesla
tfiac
thermoworks_smoke
thethingsnetwork
thingspeak
thinkingcleaner
thomson
threshold
tibber
tikteck
tile
time_date
timer
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
universal
upc_connect
upcloud
updater
upnp
uptime
uptimerobot
uscis
usgs_earthquakes_feed
utility_meter
uvc
vacuum
vallox
vasttrafik
velbus
velux
venstar
vera
verisure
version
vesync
viaggiatreno
vicare
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
weblink
webostv
websocket_api
wemo
whois
wink
wirelesstag
withings
workday
worldclock
worldtidesinfo
worxlandroid
wsdot
wunderground
wunderlist
wwlln
x10
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
yr
yweather
zabbix
zamg
zengge
zeroconf
zestimate
zha
zhong_hong
zigbee
ziggo_mediabox_xl
zone
zoneminder
zwave
__init__.py
generated
helpers
scripts
util
__init__.py
__main__.py
bootstrap.py
config.py
config_entries.py
const.py
core.py
data_entry_flow.py
exceptions.py
loader.py
monkey_patch.py
package_constraints.txt
requirements.py
setup.py
script
tests
.codecov.yml
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hound.yml
.ignore
.pre-commit-config.yaml
.readthedocs.yml
.travis.yml
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
azure-pipelines-ci.yml
azure-pipelines-release.yml
azure-pipelines-translation.yml
azure-pipelines-wheels.yml
mypyrc
pylintrc
pyproject.toml
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
setup.cfg
setup.py
tox.ini
240 lines
6.9 KiB
Python
240 lines
6.9 KiB
Python
"""Support for LaCrosse sensor components."""
|
|
from datetime import timedelta
|
|
import logging
|
|
|
|
import voluptuous as vol
|
|
|
|
from homeassistant.components.sensor import ENTITY_ID_FORMAT, PLATFORM_SCHEMA
|
|
from homeassistant.const import (
|
|
CONF_DEVICE,
|
|
CONF_ID,
|
|
CONF_NAME,
|
|
CONF_SENSORS,
|
|
CONF_TYPE,
|
|
EVENT_HOMEASSISTANT_STOP,
|
|
TEMP_CELSIUS,
|
|
)
|
|
from homeassistant.core import callback
|
|
import homeassistant.helpers.config_validation as cv
|
|
from homeassistant.helpers.entity import Entity, async_generate_entity_id
|
|
from homeassistant.helpers.event import async_track_point_in_utc_time
|
|
from homeassistant.util import dt as dt_util
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
CONF_BAUD = "baud"
|
|
CONF_DATARATE = "datarate"
|
|
CONF_EXPIRE_AFTER = "expire_after"
|
|
CONF_FREQUENCY = "frequency"
|
|
CONF_JEELINK_LED = "led"
|
|
CONF_TOGGLE_INTERVAL = "toggle_interval"
|
|
CONF_TOGGLE_MASK = "toggle_mask"
|
|
|
|
DEFAULT_DEVICE = "/dev/ttyUSB0"
|
|
DEFAULT_BAUD = "57600"
|
|
DEFAULT_EXPIRE_AFTER = 300
|
|
|
|
TYPES = ["battery", "humidity", "temperature"]
|
|
|
|
SENSOR_SCHEMA = vol.Schema(
|
|
{
|
|
vol.Required(CONF_ID): cv.positive_int,
|
|
vol.Required(CONF_TYPE): vol.In(TYPES),
|
|
vol.Optional(CONF_EXPIRE_AFTER): cv.positive_int,
|
|
vol.Optional(CONF_NAME): cv.string,
|
|
}
|
|
)
|
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|
{
|
|
vol.Required(CONF_SENSORS): cv.schema_with_slug_keys(SENSOR_SCHEMA),
|
|
vol.Optional(CONF_BAUD, default=DEFAULT_BAUD): cv.string,
|
|
vol.Optional(CONF_DATARATE): cv.positive_int,
|
|
vol.Optional(CONF_DEVICE, default=DEFAULT_DEVICE): cv.string,
|
|
vol.Optional(CONF_FREQUENCY): cv.positive_int,
|
|
vol.Optional(CONF_JEELINK_LED): cv.boolean,
|
|
vol.Optional(CONF_TOGGLE_INTERVAL): cv.positive_int,
|
|
vol.Optional(CONF_TOGGLE_MASK): cv.positive_int,
|
|
}
|
|
)
|
|
|
|
|
|
def setup_platform(hass, config, add_entities, discovery_info=None):
|
|
"""Set up the LaCrosse sensors."""
|
|
import pylacrosse
|
|
from serial import SerialException
|
|
|
|
usb_device = config.get(CONF_DEVICE)
|
|
baud = int(config.get(CONF_BAUD))
|
|
expire_after = config.get(CONF_EXPIRE_AFTER)
|
|
|
|
_LOGGER.debug("%s %s", usb_device, baud)
|
|
|
|
try:
|
|
lacrosse = pylacrosse.LaCrosse(usb_device, baud)
|
|
lacrosse.open()
|
|
except SerialException as exc:
|
|
_LOGGER.warning("Unable to open serial port: %s", exc)
|
|
return False
|
|
|
|
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, lacrosse.close)
|
|
|
|
if CONF_JEELINK_LED in config:
|
|
lacrosse.led_mode_state(config.get(CONF_JEELINK_LED))
|
|
if CONF_FREQUENCY in config:
|
|
lacrosse.set_frequency(config.get(CONF_FREQUENCY))
|
|
if CONF_DATARATE in config:
|
|
lacrosse.set_datarate(config.get(CONF_DATARATE))
|
|
if CONF_TOGGLE_INTERVAL in config:
|
|
lacrosse.set_toggle_interval(config.get(CONF_TOGGLE_INTERVAL))
|
|
if CONF_TOGGLE_MASK in config:
|
|
lacrosse.set_toggle_mask(config.get(CONF_TOGGLE_MASK))
|
|
|
|
lacrosse.start_scan()
|
|
|
|
sensors = []
|
|
for device, device_config in config[CONF_SENSORS].items():
|
|
_LOGGER.debug("%s %s", device, device_config)
|
|
|
|
typ = device_config.get(CONF_TYPE)
|
|
sensor_class = TYPE_CLASSES[typ]
|
|
name = device_config.get(CONF_NAME, device)
|
|
|
|
sensors.append(
|
|
sensor_class(hass, lacrosse, device, name, expire_after, device_config)
|
|
)
|
|
|
|
add_entities(sensors)
|
|
|
|
|
|
class LaCrosseSensor(Entity):
|
|
"""Implementation of a Lacrosse sensor."""
|
|
|
|
_temperature = None
|
|
_humidity = None
|
|
_low_battery = None
|
|
_new_battery = None
|
|
|
|
def __init__(self, hass, lacrosse, device_id, name, expire_after, config):
|
|
"""Initialize the sensor."""
|
|
self.hass = hass
|
|
self.entity_id = async_generate_entity_id(
|
|
ENTITY_ID_FORMAT, device_id, hass=hass
|
|
)
|
|
self._config = config
|
|
self._name = name
|
|
self._value = None
|
|
self._expire_after = expire_after
|
|
self._expiration_trigger = None
|
|
|
|
lacrosse.register_callback(
|
|
int(self._config["id"]), self._callback_lacrosse, None
|
|
)
|
|
|
|
@property
|
|
def name(self):
|
|
"""Return the name of the sensor."""
|
|
return self._name
|
|
|
|
@property
|
|
def device_state_attributes(self):
|
|
"""Return the state attributes."""
|
|
attributes = {
|
|
"low_battery": self._low_battery,
|
|
"new_battery": self._new_battery,
|
|
}
|
|
return attributes
|
|
|
|
def _callback_lacrosse(self, lacrosse_sensor, user_data):
|
|
"""Handle a function that is called from pylacrosse with new values."""
|
|
if self._expire_after is not None and self._expire_after > 0:
|
|
# Reset old trigger
|
|
if self._expiration_trigger:
|
|
self._expiration_trigger()
|
|
self._expiration_trigger = None
|
|
|
|
# Set new trigger
|
|
expiration_at = dt_util.utcnow() + timedelta(seconds=self._expire_after)
|
|
|
|
self._expiration_trigger = async_track_point_in_utc_time(
|
|
self.hass, self.value_is_expired, expiration_at
|
|
)
|
|
|
|
self._temperature = lacrosse_sensor.temperature
|
|
self._humidity = lacrosse_sensor.humidity
|
|
self._low_battery = lacrosse_sensor.low_battery
|
|
self._new_battery = lacrosse_sensor.new_battery
|
|
|
|
@callback
|
|
def value_is_expired(self, *_):
|
|
"""Triggered when value is expired."""
|
|
self._expiration_trigger = None
|
|
self._value = None
|
|
self.async_schedule_update_ha_state()
|
|
|
|
|
|
class LaCrosseTemperature(LaCrosseSensor):
|
|
"""Implementation of a Lacrosse temperature sensor."""
|
|
|
|
@property
|
|
def unit_of_measurement(self):
|
|
"""Return the unit of measurement."""
|
|
return TEMP_CELSIUS
|
|
|
|
@property
|
|
def state(self):
|
|
"""Return the state of the sensor."""
|
|
return self._temperature
|
|
|
|
|
|
class LaCrosseHumidity(LaCrosseSensor):
|
|
"""Implementation of a Lacrosse humidity sensor."""
|
|
|
|
@property
|
|
def unit_of_measurement(self):
|
|
"""Return the unit of measurement."""
|
|
return "%"
|
|
|
|
@property
|
|
def state(self):
|
|
"""Return the state of the sensor."""
|
|
return self._humidity
|
|
|
|
@property
|
|
def icon(self):
|
|
"""Icon to use in the frontend."""
|
|
return "mdi:water-percent"
|
|
|
|
|
|
class LaCrosseBattery(LaCrosseSensor):
|
|
"""Implementation of a Lacrosse battery sensor."""
|
|
|
|
@property
|
|
def state(self):
|
|
"""Return the state of the sensor."""
|
|
if self._low_battery is None:
|
|
state = None
|
|
elif self._low_battery is True:
|
|
state = "low"
|
|
else:
|
|
state = "ok"
|
|
return state
|
|
|
|
@property
|
|
def icon(self):
|
|
"""Icon to use in the frontend."""
|
|
if self._low_battery is None:
|
|
icon = "mdi:battery-unknown"
|
|
elif self._low_battery is True:
|
|
icon = "mdi:battery-alert"
|
|
else:
|
|
icon = "mdi:battery"
|
|
return icon
|
|
|
|
|
|
TYPE_CLASSES = {
|
|
"temperature": LaCrosseTemperature,
|
|
"humidity": LaCrosseHumidity,
|
|
"battery": LaCrosseBattery,
|
|
}
|