1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-13 15:30:03 +00:00
Files
.github
docs
homeassistant
auth
components
abode
acer_projector
actiontec
ads
aftership
air_quality
airvisual
aladdin_connect
alarm_control_panel
alarmdecoder
alarmdotcom
alert
alexa
alpha_vantage
amazon_polly
ambient_station
amcrest
android_ip_webcam
androidtv
anel_pwrctrl
anthemav
apcupsd
api
api_streams
apns
apple_tv
aqualogic
aquostv
arduino
arest
arlo
aruba
arwn
asterisk_cdr
asterisk_mbox
asuswrt
august
aurora
auth
automatic
automation
avion
awair
aws
aws_lambda
aws_sns
aws_sqs
axis
baidu
bayesian
bbb_gpio
bbox
bh1750
binary_sensor
bitcoin
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
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
deluge
demo
denon
denonavr
deutsche_bahn
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
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
edp_redy
ee_brightbox
efergy
egardia
eight_sleep
eliqonline
elkm1
emby
emoncms
emoncms_history
emulated_hue
emulated_roku
enigma2
enocean
enphase_envoy
entur_public_transport
envirophat
envisalink
ephember
epson
eq3btsmart
esphome
etherscan
eufy
everlights
evohome
facebook
facebox
fail2ban
familyhub
fan
fastdotcom
fedex
feedreader
ffmpeg
ffmpeg_motion
ffmpeg_noise
fibaro
fido
file
filesize
filter
fints
fitbit
fixer
flexit
flic
flock
flunearyou
flux
flux_led
folder
folder_watcher
foobot
foscam
foursquare
free_mobile
freebox
freedns
fritz
fritzbox
fritzbox_callmonitor
fritzbox_netmonitor
fritzdect
frontend
frontier_silicon
futurenow
garadget
gc100
gearbest
geizhals
generic
generic_thermostat
geo_json_events
geo_location
geo_rss_events
geofency
github
gitlab_ci
gitter
glances
gntp
goalfeed
gogogate2
google
google_assistant
google_domains
google_maps
google_pubsub
google_travel_time
google_wifi
googlehome
gpmdp
gpsd
gpslogger
graphite
greeneye_monitor
greenwave
group
gstreamer
gtfs
gtt
habitica
hangouts
harman_kardon_avr
harmony
hassio
haveibeenpwned
hddtemp
hdmi_cec
heatmiser
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
icloud
idteck_prox
ifttt
iglo
ihc
image_processing
imap
imap_email_content
influxdb
input_boolean
input_datetime
input_number
input_select
input_text
insteon
insteon_local
insteon_plm
integration
intent_script
introduction
ios
iota
iperf3
ipma
irish_rail_transport
islamic_prayer_times
iss
isy994
itach
itunes
jewish_calendar
joaoapps_join
juicenet
kankun
keenetic_ndms2
keyboard
keyboard_remote
kira
kiwi
knx
kodi
konnected
kwb
lacrosse
lametric
lannouncer
lastfm
launch_library
lcn
lg_netcast
lg_soundbar
lifx
lifx_cloud
lifx_legacy
light
lightwave
limitlessled
linksys_ap
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
media_extractor
media_player
mediaroom
melissa
meraki
message_bird
met
meteo_france
metoffice
mfi
mhz19
microsoft
microsoft_face
microsoft_face_detect
microsoft_face_identify
miflora
mikrotik
mill
min_max
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
__init__.py
binary_sensor.py
climate.py
const.py
cover.py
device.py
device_tracker.py
gateway.py
handler.py
helpers.py
light.py
notify.py
sensor.py
switch.py
mystrom
mythicbeastsdns
nad
namecheapdns
nanoleaf
neato
nederlandse_spoorwegen
nello
ness_alarm
nest
netatmo
netatmo_public
netdata
netgear
netgear_lte
netio
neurio_energy
nfandroidtv
niko_home_control
nilu
nissan_leaf
nmap_tracker
nmbs
no_ip
noaa_tides
norway_air
notify
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuimo_controller
nuki
nut
nx584
nzbget
octoprint
oem
ohmconnect
onboarding
onewire
onkyo
onvif
openalpr_cloud
openalpr_local
opencv
openevse
openexchangerates
opengarage
openhardwaremonitor
openhome
opensensemap
opensky
opentherm_gw
openuv
openweathermap
opple
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
plant
plex
plum_lightpad
pocketcasts
point
pollen
postnl
prezzibenzina
proliphix
prometheus
prowl
proximity
proxy
ps4
pulseaudio_loopback
push
pushbullet
pushetta
pushover
pushsafer
pvoutput
pyload
python_script
qbittorrent
qnap
qrcode
quantum_gateway
qwikswitch
rachio
radarr
radiotherm
rainbird
raincloud
rainmachine
random
raspihats
raspyrfm
recollect_waste
recorder
recswitch
reddit
rejseplanen
remember_the_milk
remote
rest
rest_command
rflink
rfxtrx
ring
ripple
ritassist
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
ruter
sabnzbd
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
sma
smappee
smartthings
smhi
smtp
snapcast
snips
snmp
sochain
socialblade
solaredge
sonarr
songpal
sonos
sony_projector
soundtouch
spaceapi
spc
speedtestdotnet
spider
splunk
spotcrime
spotify
sql
squeezebox
srp_energy
starlingbank
startca
statistics
statsd
steam_online
stream
stride
sun
supervisord
swiss_hydrological_data
swiss_public_transport
swisscom
switch
switchbot
switchmate
syncthru
synology
synology_chat
synology_srm
synologydsm
syslog
system_health
system_log
systemmonitor
sytadin
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_weatherstation
transmission
transport_nsw
travisci
trend
tts
tuya
twilio
twilio_call
twilio_sms
twitch
twitter
ubee
uber
ubus
ue_smart_radio
uk_transport
unifi
unifi_direct
universal
upc_connect
upcloud
updater
upnp
ups
uptime
uptimerobot
uscis
usgs_earthquakes_feed
usps
utility_meter
uvc
vacuum
vasttrafik
velbus
velux
venstar
vera
verisure
version
vesync
viaggiatreno
vizio
vlc
voicerss
volkszaehler
volumio
volvooncall
vultr
w800rf32
wake_on_lan
waqi
water_heater
waterfurnace
watson_iot
waze_travel_time
weather
webhook
weblink
webostv
websocket_api
wemo
whois
wink
wirelesstag
workday
worldclock
worldtidesinfo
worxlandroid
wsdot
wunderground
wunderlist
x10
xbox_live
xeoma
xfinity
xiaomi
xiaomi_aqara
xiaomi_miio
xiaomi_tv
xmpp
xs1
yale_smart_alarm
yamaha
yamaha_musiccast
yandextts
yeelight
yeelightsunflower
yessssms
yi
yr
yweather
zabbix
zamg
zengge
zeroconf
zestimate
zha
zhong_hong
zigbee
ziggo_mediabox_xl
zone
zoneminder
zwave
__init__.py
services.yaml
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
virtualization
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hound.yml
.ignore
.readthedocs.yml
.travis.yml
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
LICENSE.md
MANIFEST.in
README.rst
mypy.ini
pylintrc
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
setup.cfg
setup.py
tox.ini
core/homeassistant/components/mysensors/switch.py
Fabian Affolter 161c368c9d Update file header ()
* Update file header

* Update __init__.py
2019-02-13 20:35:12 -08:00

146 lines
5.3 KiB
Python

"""Support for MySensors switches."""
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components import mysensors
from homeassistant.components.switch import DOMAIN, SwitchDevice
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
ATTR_IR_CODE = 'V_IR_SEND'
SERVICE_SEND_IR_CODE = 'mysensors_send_ir_code'
SEND_IR_CODE_SERVICE_SCHEMA = vol.Schema({
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Required(ATTR_IR_CODE): cv.string,
})
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the mysensors platform for switches."""
device_class_map = {
'S_DOOR': MySensorsSwitch,
'S_MOTION': MySensorsSwitch,
'S_SMOKE': MySensorsSwitch,
'S_LIGHT': MySensorsSwitch,
'S_LOCK': MySensorsSwitch,
'S_IR': MySensorsIRSwitch,
'S_BINARY': MySensorsSwitch,
'S_SPRINKLER': MySensorsSwitch,
'S_WATER_LEAK': MySensorsSwitch,
'S_SOUND': MySensorsSwitch,
'S_VIBRATION': MySensorsSwitch,
'S_MOISTURE': MySensorsSwitch,
'S_WATER_QUALITY': MySensorsSwitch,
}
mysensors.setup_mysensors_platform(
hass, DOMAIN, discovery_info, device_class_map,
async_add_entities=async_add_entities)
async def async_send_ir_code_service(service):
"""Set IR code as device state attribute."""
entity_ids = service.data.get(ATTR_ENTITY_ID)
ir_code = service.data.get(ATTR_IR_CODE)
devices = mysensors.get_mysensors_devices(hass, DOMAIN)
if entity_ids:
_devices = [device for device in devices.values()
if isinstance(device, MySensorsIRSwitch) and
device.entity_id in entity_ids]
else:
_devices = [device for device in devices.values()
if isinstance(device, MySensorsIRSwitch)]
kwargs = {ATTR_IR_CODE: ir_code}
for device in _devices:
await device.async_turn_on(**kwargs)
hass.services.async_register(
DOMAIN, SERVICE_SEND_IR_CODE, async_send_ir_code_service,
schema=SEND_IR_CODE_SERVICE_SCHEMA)
class MySensorsSwitch(mysensors.device.MySensorsEntity, SwitchDevice):
"""Representation of the value of a MySensors Switch child node."""
@property
def assumed_state(self):
"""Return True if unable to access real state of entity."""
return self.gateway.optimistic
@property
def current_power_w(self):
"""Return the current power usage in W."""
set_req = self.gateway.const.SetReq
return self._values.get(set_req.V_WATT)
@property
def is_on(self):
"""Return True if switch is on."""
return self._values.get(self.value_type) == STATE_ON
async def async_turn_on(self, **kwargs):
"""Turn the switch on."""
self.gateway.set_child_value(
self.node_id, self.child_id, self.value_type, 1)
if self.gateway.optimistic:
# Optimistically assume that switch has changed state
self._values[self.value_type] = STATE_ON
self.async_schedule_update_ha_state()
async def async_turn_off(self, **kwargs):
"""Turn the switch off."""
self.gateway.set_child_value(
self.node_id, self.child_id, self.value_type, 0)
if self.gateway.optimistic:
# Optimistically assume that switch has changed state
self._values[self.value_type] = STATE_OFF
self.async_schedule_update_ha_state()
class MySensorsIRSwitch(MySensorsSwitch):
"""IR switch child class to MySensorsSwitch."""
def __init__(self, *args):
"""Set up instance attributes."""
super().__init__(*args)
self._ir_code = None
@property
def is_on(self):
"""Return True if switch is on."""
set_req = self.gateway.const.SetReq
return self._values.get(set_req.V_LIGHT) == STATE_ON
async def async_turn_on(self, **kwargs):
"""Turn the IR switch on."""
set_req = self.gateway.const.SetReq
if ATTR_IR_CODE in kwargs:
self._ir_code = kwargs[ATTR_IR_CODE]
self.gateway.set_child_value(
self.node_id, self.child_id, self.value_type, self._ir_code)
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_LIGHT, 1)
if self.gateway.optimistic:
# Optimistically assume that switch has changed state
self._values[self.value_type] = self._ir_code
self._values[set_req.V_LIGHT] = STATE_ON
self.async_schedule_update_ha_state()
# Turn off switch after switch was turned on
await self.async_turn_off()
async def async_turn_off(self, **kwargs):
"""Turn the IR switch off."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
self.node_id, self.child_id, set_req.V_LIGHT, 0)
if self.gateway.optimistic:
# Optimistically assume that switch has changed state
self._values[set_req.V_LIGHT] = STATE_OFF
self.async_schedule_update_ha_state()
async def async_update(self):
"""Update the controller with the latest value from a sensor."""
await super().async_update()
self._ir_code = self._values.get(self.value_type)