mirror of
https://github.com/home-assistant/core.git
synced 2025-08-12 23:10:05 +00:00
.github
docs
homeassistant
components
alarm_control_panel
alexa
automation
binary_sensor
calendar
camera
climate
cloud
config
cover
device_tracker
emulated_hue
fan
frontend
group
http
image_processing
light
lock
mailbox
media_player
mqtt
notify
persistent_notification
recorder
remote
scene
sensor
__init__.py
abode.py
airvisual.py
alarmdecoder.py
amcrest.py
android_ip_webcam.py
apcupsd.py
api_streams.py
arduino.py
arest.py
arlo.py
arwn.py
bbox.py
bh1750.py
bitcoin.py
blink.py
blockchain.py
bloomsky.py
bme280.py
bom.py
broadlink.py
buienradar.py
cert_expiry.py
citybikes.py
coinmarketcap.py
comed_hourly_pricing.py
comfoconnect.py
command_line.py
cpuspeed.py
crimereports.py
cups.py
currencylayer.py
darksky.py
demo.py
deutsche_bahn.py
dht.py
dnsip.py
dovado.py
dsmr.py
dte_energy_bridge.py
dublin_bus_transport.py
dwd_weather_warnings.py
dweet.py
dyson.py
ebox.py
ecobee.py
eddystone_temperature.py
efergy.py
eight_sleep.py
eliqonline.py
emoncms.py
enocean.py
envirophat.py
envisalink.py
etherscan.py
fastdotcom.py
fedex.py
fido.py
file.py
fitbit.py
fixer.py
fritzbox_callmonitor.py
fritzbox_netmonitor.py
geizhals.py
geo_rss_events.py
gitter.py
glances.py
google_travel_time.py
google_wifi.py
gpsd.py
gtfs.py
haveibeenpwned.py
hddtemp.py
history_stats.py
homematic.py
hp_ilo.py
htu21d.py
hydroquebec.py
imap.py
imap_email_content.py
influxdb.py
ios.py
isy994.py
juicenet.py
kira.py
knx.py
kwb.py
lastfm.py
linux_battery.py
london_air.py
london_underground.py
loopenergy.py
lyft.py
metoffice.py
mfi.py
mhz19.py
miflora.py
min_max.py
modbus.py
modem_callerid.py
mold_indicator.py
moon.py
mopar.py
mqtt.py
mqtt_room.py
mvglive.py
mysensors.py
neato.py
nest.py
netatmo.py
netdata.py
neurio_energy.py
nut.py
nzbget.py
octoprint.py
ohmconnect.py
onewire.py
openevse.py
openexchangerates.py
openhardwaremonitor.py
opensky.py
openweathermap.py
otp.py
pi_hole.py
pilight.py
plex.py
pocketcasts.py
pushbullet.py
pvoutput.py
qnap.py
radarr.py
raincloud.py
random.py
rest.py
rflink.py
rfxtrx.py
ring.py
ripple.py
sabnzbd.py
scrape.py
season.py
sensehat.py
serial_pm.py
shodan.py
skybeacon.py
sleepiq.py
sma.py
snmp.py
sonarr.py
speedtest.py
statistics.py
steam_online.py
supervisord.py
swiss_hydrological_data.py
swiss_public_transport.py
synologydsm.py
systemmonitor.py
tado.py
tank_utility.py
tcp.py
ted5000.py
tellduslive.py
tellstick.py
temper.py
template.py
tesla.py
thethingsnetwork.py
thinkingcleaner.py
tibber.py
time_date.py
torque.py
tradfri.py
transmission.py
travisci.py
twitch.py
uber.py
uk_transport.py
upnp.py
ups.py
usps.py
vasttrafik.py
vera.py
verisure.py
version.py
volvooncall.py
waqi.py
wink.py
worldclock.py
worldtidesinfo.py
worxlandroid.py
wsdot.py
wunderground.py
xbox_live.py
xiaomi_aqara.py
yahoo_finance.py
yr.py
yweather.py
zabbix.py
zamg.py
zha.py
zigbee.py
zoneminder.py
zwave.py
switch
telegram_bot
tts
vacuum
weather
zha
zwave
__init__.py
abode.py
alarmdecoder.py
alert.py
amcrest.py
android_ip_webcam.py
apcupsd.py
api.py
apiai.py
apple_tv.py
arduino.py
arlo.py
asterisk_mbox.py
axis.py
bbb_gpio.py
blink.py
bloomsky.py
browser.py
comfoconnect.py
configurator.py
conversation.py
counter.py
datadog.py
demo.py
device_sun_light_trigger.py
digital_ocean.py
discovery.py
doorbird.py
downloader.py
duckdns.py
dweet.py
dyson.py
ecobee.py
eight_sleep.py
emoncms_history.py
enocean.py
envisalink.py
feedreader.py
ffmpeg.py
foursquare.py
google.py
graphite.py
hassio.py
hdmi_cec.py
history.py
history_graph.py
homematic.py
ifttt.py
influxdb.py
input_boolean.py
input_datetime.py
input_number.py
input_select.py
input_text.py
insteon_local.py
insteon_plm.py
intent_script.py
introduction.py
ios.py
isy994.py
joaoapps_join.py
juicenet.py
keyboard.py
keyboard_remote.py
kira.py
knx.py
lametric.py
lirc.py
litejet.py
logbook.py
logentries.py
logger.py
lutron.py
lutron_caseta.py
mailgun.py
maxcube.py
media_extractor.py
microsoft_face.py
mochad.py
modbus.py
mqtt_eventstream.py
mqtt_statestream.py
mycroft.py
mysensors.py
neato.py
nest.py
netatmo.py
nuimo_controller.py
octoprint.py
panel_custom.py
panel_iframe.py
pilight.py
plant.py
prometheus.py
proximity.py
python_script.py
qwikswitch.py
raincloud.py
raspihats.py
rest_command.py
rflink.py
rfxtrx.py
ring.py
rpi_gpio.py
rpi_pfio.py
rss_feed_template.py
satel_integra.py
script.py
scsgate.py
services.yaml
shell_command.py
shiftr.py
shopping_list.py
sleepiq.py
snips.py
spc.py
splunk.py
statsd.py
sun.py
tado.py
tellduslive.py
tellstick.py
tesla.py
thethingsnetwork.py
thingspeak.py
tradfri.py
twilio.py
updater.py
upnp.py
usps.py
velbus.py
velux.py
vera.py
verisure.py
volvooncall.py
wake_on_lan.py
weblink.py
websocket_api.py
wemo.py
wink.py
xiaomi_aqara.py
zabbix.py
zeroconf.py
zigbee.py
zone.py
zoneminder.py
helpers
scripts
util
__init__.py
__main__.py
bootstrap.py
config.py
const.py
core.py
exceptions.py
loader.py
monkey_patch.py
package_constraints.txt
remote.py
setup.py
script
tests
virtualization
.coveragerc
.dockerignore
.gitignore
.gitmodules
.hound.yml
.ignore
.travis.yml
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
LICENSE.md
MANIFEST.in
README.rst
pylintrc
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
setup.cfg
setup.py
tox.ini

This fixes https://github.com/home-assistant/home-assistant/issues/8976 When no data was available the module crashes.
165 lines
5.6 KiB
Python
165 lines
5.6 KiB
Python
"""
|
|
Support for Adafruit DHT temperature and humidity sensor.
|
|
|
|
For more details about this platform, please refer to the documentation at
|
|
https://home-assistant.io/components/sensor.dht/
|
|
"""
|
|
import logging
|
|
from datetime import timedelta
|
|
|
|
import voluptuous as vol
|
|
|
|
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
|
import homeassistant.helpers.config_validation as cv
|
|
from homeassistant.const import (
|
|
TEMP_FAHRENHEIT, CONF_NAME, CONF_MONITORED_CONDITIONS)
|
|
from homeassistant.helpers.entity import Entity
|
|
from homeassistant.util import Throttle
|
|
from homeassistant.util.temperature import celsius_to_fahrenheit
|
|
|
|
# Update this requirement to upstream as soon as it supports Python 3.
|
|
REQUIREMENTS = ['https://github.com/adafruit/Adafruit_Python_DHT/archive/'
|
|
'da8cddf7fb629c1ef4f046ca44f42523c9cf2d11.zip'
|
|
'#Adafruit_DHT==1.3.2']
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
CONF_PIN = 'pin'
|
|
CONF_SENSOR = 'sensor'
|
|
CONF_HUMIDITY_OFFSET = 'humidity_offset'
|
|
CONF_TEMPERATURE_OFFSET = 'temperature_offset'
|
|
|
|
DEFAULT_NAME = 'DHT Sensor'
|
|
|
|
# DHT11 is able to deliver data once per second, DHT22 once every two
|
|
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
|
|
|
|
SENSOR_TEMPERATURE = 'temperature'
|
|
SENSOR_HUMIDITY = 'humidity'
|
|
SENSOR_TYPES = {
|
|
SENSOR_TEMPERATURE: ['Temperature', None],
|
|
SENSOR_HUMIDITY: ['Humidity', '%']
|
|
}
|
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
|
vol.Required(CONF_SENSOR): cv.string,
|
|
vol.Required(CONF_PIN): cv.string,
|
|
vol.Optional(CONF_MONITORED_CONDITIONS, default=[]):
|
|
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
|
|
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
|
vol.Optional(CONF_TEMPERATURE_OFFSET, default=0):
|
|
vol.All(vol.Coerce(float), vol.Range(min=-100, max=100)),
|
|
vol.Optional(CONF_HUMIDITY_OFFSET, default=0):
|
|
vol.All(vol.Coerce(float), vol.Range(min=-100, max=100))
|
|
})
|
|
|
|
|
|
def setup_platform(hass, config, add_devices, discovery_info=None):
|
|
"""Set up the DHT sensor."""
|
|
# pylint: disable=import-error
|
|
import Adafruit_DHT
|
|
|
|
SENSOR_TYPES[SENSOR_TEMPERATURE][1] = hass.config.units.temperature_unit
|
|
available_sensors = {
|
|
"DHT11": Adafruit_DHT.DHT11,
|
|
"DHT22": Adafruit_DHT.DHT22,
|
|
"AM2302": Adafruit_DHT.AM2302
|
|
}
|
|
sensor = available_sensors.get(config.get(CONF_SENSOR))
|
|
pin = config.get(CONF_PIN)
|
|
temperature_offset = config.get(CONF_TEMPERATURE_OFFSET)
|
|
humidity_offset = config.get(CONF_HUMIDITY_OFFSET)
|
|
|
|
if not sensor:
|
|
_LOGGER.error("DHT sensor type is not supported")
|
|
return False
|
|
|
|
data = DHTClient(Adafruit_DHT, sensor, pin)
|
|
dev = []
|
|
name = config.get(CONF_NAME)
|
|
|
|
try:
|
|
for variable in config[CONF_MONITORED_CONDITIONS]:
|
|
dev.append(DHTSensor(
|
|
data, variable, SENSOR_TYPES[variable][1], name,
|
|
temperature_offset, humidity_offset))
|
|
except KeyError:
|
|
pass
|
|
|
|
add_devices(dev, True)
|
|
|
|
|
|
class DHTSensor(Entity):
|
|
"""Implementation of the DHT sensor."""
|
|
|
|
def __init__(self, dht_client, sensor_type, temp_unit, name,
|
|
temperature_offset, humidity_offset):
|
|
"""Initialize the sensor."""
|
|
self.client_name = name
|
|
self._name = SENSOR_TYPES[sensor_type][0]
|
|
self.dht_client = dht_client
|
|
self.temp_unit = temp_unit
|
|
self.type = sensor_type
|
|
self.temperature_offset = temperature_offset
|
|
self.humidity_offset = humidity_offset
|
|
self._state = None
|
|
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
|
|
|
|
@property
|
|
def name(self):
|
|
"""Return the name of the sensor."""
|
|
return '{} {}'.format(self.client_name, self._name)
|
|
|
|
@property
|
|
def state(self):
|
|
"""Return the state of the sensor."""
|
|
return self._state
|
|
|
|
@property
|
|
def unit_of_measurement(self):
|
|
"""Return the unit of measurement of this entity, if any."""
|
|
return self._unit_of_measurement
|
|
|
|
def update(self):
|
|
"""Get the latest data from the DHT and updates the states."""
|
|
self.dht_client.update()
|
|
temperature_offset = self.temperature_offset
|
|
humidity_offset = self.humidity_offset
|
|
data = self.dht_client.data
|
|
|
|
if self.type == SENSOR_TEMPERATURE and SENSOR_TEMPERATURE in data:
|
|
temperature = data[SENSOR_TEMPERATURE]
|
|
_LOGGER.debug("Temperature %.1f \u00b0C + offset %.1f",
|
|
temperature, temperature_offset)
|
|
if (temperature >= -20) and (temperature < 80):
|
|
self._state = round(temperature + temperature_offset, 1)
|
|
if self.temp_unit == TEMP_FAHRENHEIT:
|
|
self._state = round(celsius_to_fahrenheit(temperature), 1)
|
|
elif self.type == SENSOR_HUMIDITY and SENSOR_HUMIDITY in data:
|
|
humidity = data[SENSOR_HUMIDITY]
|
|
_LOGGER.debug("Humidity %.1f%% + offset %.1f",
|
|
humidity, humidity_offset)
|
|
if (humidity >= 0) and (humidity <= 100):
|
|
self._state = round(humidity + humidity_offset, 1)
|
|
|
|
|
|
class DHTClient(object):
|
|
"""Get the latest data from the DHT sensor."""
|
|
|
|
def __init__(self, adafruit_dht, sensor, pin):
|
|
"""Initialize the sensor."""
|
|
self.adafruit_dht = adafruit_dht
|
|
self.sensor = sensor
|
|
self.pin = pin
|
|
self.data = dict()
|
|
|
|
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
|
def update(self):
|
|
"""Get the latest data the DHT sensor."""
|
|
humidity, temperature = self.adafruit_dht.read_retry(
|
|
self.sensor, self.pin)
|
|
if temperature:
|
|
self.data[SENSOR_TEMPERATURE] = temperature
|
|
if humidity:
|
|
self.data[SENSOR_HUMIDITY] = humidity
|