1
0
mirror of https://github.com/home-assistant/core.git synced 2025-09-02 09:01:05 +00:00
Files
.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
.translations
__init__.py
alarm_control_panel.py
binary_sensor.py
climate.py
config_flow.py
connection.py
const.py
cover.py
light.py
lock.py
manifest.json
sensor.py
storage.py
strings.json
switch.py
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
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
core/homeassistant/components/homekit_controller/connection.py
Jc2k 2bd832cd7a Skip homekit_controller polls when system is overloaded and still trying to process the previous one ()
* Skip async_update if there are signs of backpressure

* Black

* Only warn once

* Log on recovery

* Formatting fix
2019-08-17 21:14:46 -07:00

356 lines
12 KiB
Python

"""Helpers for managing a pairing with a HomeKit accessory or bridge."""
import asyncio
import datetime
import logging
from homekit.exceptions import (
AccessoryDisconnectedError,
AccessoryNotFoundError,
EncryptionError,
)
from homekit.model.services import ServicesTypes
from homekit.model.characteristics import CharacteristicsTypes
from homeassistant.helpers.event import async_track_time_interval
from .const import DOMAIN, HOMEKIT_ACCESSORY_DISPATCH, ENTITY_MAP
DEFAULT_SCAN_INTERVAL = datetime.timedelta(seconds=60)
RETRY_INTERVAL = 60 # seconds
_LOGGER = logging.getLogger(__name__)
def get_accessory_information(accessory):
"""Obtain the accessory information service of a HomeKit device."""
result = {}
for service in accessory["services"]:
stype = service["type"].upper()
if ServicesTypes.get_short(stype) != "accessory-information":
continue
for characteristic in service["characteristics"]:
ctype = CharacteristicsTypes.get_short(characteristic["type"])
if "value" in characteristic:
result[ctype] = characteristic["value"]
return result
def get_bridge_information(accessories):
"""Return the accessory info for the bridge."""
for accessory in accessories:
if accessory["aid"] == 1:
return get_accessory_information(accessory)
return get_accessory_information(accessories[0])
def get_accessory_name(accessory_info):
"""Return the name field of an accessory."""
for field in ("name", "model", "manufacturer"):
if field in accessory_info:
return accessory_info[field]
return None
class HKDevice:
"""HomeKit device."""
def __init__(self, hass, config_entry, pairing_data):
"""Initialise a generic HomeKit device."""
from homekit.controller.ip_implementation import IpPairing
self.hass = hass
self.config_entry = config_entry
# We copy pairing_data because homekit_python may mutate it, but we
# don't want to mutate a dict owned by a config entry.
self.pairing_data = pairing_data.copy()
self.pairing = IpPairing(self.pairing_data)
self.accessories = {}
self.config_num = 0
# A list of callbacks that turn HK service metadata into entities
self.listeners = []
# The platorms we have forwarded the config entry so far. If a new
# accessory is added to a bridge we may have to load additional
# platforms. We don't want to load all platforms up front if its just
# a lightbulb. And we dont want to forward a config entry twice
# (triggers a Config entry already set up error)
self.platforms = set()
# This just tracks aid/iid pairs so we know if a HK service has been
# mapped to a HA entity.
self.entities = []
# There are multiple entities sharing a single connection - only
# allow one entity to use pairing at once.
self.pairing_lock = asyncio.Lock()
self.available = True
self.signal_state_updated = "_".join((DOMAIN, self.unique_id, "state_updated"))
# Current values of all characteristics homekit_controller is tracking.
# Key is a (accessory_id, characteristic_id) tuple.
self.current_state = {}
self.pollable_characteristics = []
# If this is set polling is active and can be disabled by calling
# this method.
self._polling_interval_remover = None
# Never allow concurrent polling of the same accessory or bridge
self._polling_lock = asyncio.Lock()
self._polling_lock_warned = False
def add_pollable_characteristics(self, characteristics):
"""Add (aid, iid) pairs that we need to poll."""
self.pollable_characteristics.extend(characteristics)
def remove_pollable_characteristics(self, accessory_id):
"""Remove all pollable characteristics by accessory id."""
self.pollable_characteristics = [
char for char in self.pollable_characteristics if char[0] != accessory_id
]
def async_set_unavailable(self):
"""Mark state of all entities on this connection as unavailable."""
self.available = False
self.hass.helpers.dispatcher.async_dispatcher_send(self.signal_state_updated)
async def async_setup(self):
"""Prepare to use a paired HomeKit device in homeassistant."""
cache = self.hass.data[ENTITY_MAP].get_map(self.unique_id)
if not cache:
if await self.async_refresh_entity_map(self.config_num):
self._polling_interval_remover = async_track_time_interval(
self.hass, self.async_update, DEFAULT_SCAN_INTERVAL
)
return True
return False
self.accessories = cache["accessories"]
self.config_num = cache["config_num"]
# Ensure the Pairing object has access to the latest version of the
# entity map.
self.pairing.pairing_data["accessories"] = self.accessories
self.async_load_platforms()
self.add_entities()
await self.async_update()
self._polling_interval_remover = async_track_time_interval(
self.hass, self.async_update, DEFAULT_SCAN_INTERVAL
)
return True
async def async_unload(self):
"""Stop interacting with device and prepare for removal from hass."""
if self._polling_interval_remover:
self._polling_interval_remover()
unloads = []
for platform in self.platforms:
unloads.append(
self.hass.config_entries.async_forward_entry_unload(
self.config_entry, platform
)
)
results = await asyncio.gather(*unloads)
return False not in results
async def async_refresh_entity_map(self, config_num):
"""Handle setup of a HomeKit accessory."""
try:
async with self.pairing_lock:
self.accessories = await self.hass.async_add_executor_job(
self.pairing.list_accessories_and_characteristics
)
except AccessoryDisconnectedError:
# If we fail to refresh this data then we will naturally retry
# later when Bonjour spots c# is still not up to date.
return
self.hass.data[ENTITY_MAP].async_create_or_update_map(
self.unique_id, config_num, self.accessories
)
self.config_num = config_num
# For BLE, the Pairing instance relies on the entity map to map
# aid/iid to GATT characteristics. So push it to there as well.
self.pairing.pairing_data["accessories"] = self.accessories
self.async_load_platforms()
# Register and add new entities that are available
self.add_entities()
await self.async_update()
return True
def add_listener(self, add_entities_cb):
"""Add a callback to run when discovering new entities."""
self.listeners.append(add_entities_cb)
self._add_new_entities([add_entities_cb])
def add_entities(self):
"""Process the entity map and create HA entities."""
self._add_new_entities(self.listeners)
def _add_new_entities(self, callbacks):
for accessory in self.accessories:
aid = accessory["aid"]
for service in accessory["services"]:
iid = service["iid"]
stype = ServicesTypes.get_short(service["type"].upper())
service["stype"] = stype
if (aid, iid) in self.entities:
# Don't add the same entity again
continue
for listener in callbacks:
if listener(aid, service):
self.entities.append((aid, iid))
break
def async_load_platforms(self):
"""Load any platforms needed by this HomeKit device."""
for accessory in self.accessories:
for service in accessory["services"]:
stype = ServicesTypes.get_short(service["type"].upper())
if stype not in HOMEKIT_ACCESSORY_DISPATCH:
continue
platform = HOMEKIT_ACCESSORY_DISPATCH[stype]
if platform in self.platforms:
continue
self.hass.async_create_task(
self.hass.config_entries.async_forward_entry_setup(
self.config_entry, platform
)
)
self.platforms.add(platform)
async def async_update(self, now=None):
"""Poll state of all entities attached to this bridge/accessory."""
if not self.pollable_characteristics:
_LOGGER.debug("HomeKit connection not polling any characteristics.")
return
if self._polling_lock.locked():
if not self._polling_lock_warned:
_LOGGER.warning(
"HomeKit controller update skipped as previous poll still in flight"
)
self._polling_lock_warned = True
return
if self._polling_lock_warned:
_LOGGER.info(
"HomeKit controller no longer detecting back pressure - not skipping poll"
)
self._polling_lock_warned = False
async with self._polling_lock:
_LOGGER.debug("Starting HomeKit controller update")
try:
new_values_dict = await self.get_characteristics(
self.pollable_characteristics
)
except AccessoryNotFoundError:
# Not only did the connection fail, but also the accessory is not
# visible on the network.
self.async_set_unavailable()
return
except (AccessoryDisconnectedError, EncryptionError):
# Temporary connection failure. Device is still available but our
# connection was dropped.
return
self.process_new_events(new_values_dict)
_LOGGER.debug("Finished HomeKit controller update")
def process_new_events(self, new_values_dict):
"""Process events from accessory into HA state."""
self.available = True
for (aid, cid), value in new_values_dict.items():
accessory = self.current_state.setdefault(aid, {})
accessory[cid] = value
self.hass.helpers.dispatcher.async_dispatcher_send(self.signal_state_updated)
async def get_characteristics(self, *args, **kwargs):
"""Read latest state from homekit accessory."""
async with self.pairing_lock:
chars = await self.hass.async_add_executor_job(
self.pairing.get_characteristics, *args, **kwargs
)
return chars
async def put_characteristics(self, characteristics):
"""Control a HomeKit device state from Home Assistant."""
chars = []
for row in characteristics:
chars.append((row["aid"], row["iid"], row["value"]))
async with self.pairing_lock:
results = await self.hass.async_add_executor_job(
self.pairing.put_characteristics, chars
)
# Feed characteristics back into HA and update the current state
# results will only contain failures, so anythin in characteristics
# but not in results was applied successfully - we can just have HA
# reflect the change immediately.
new_entity_state = {}
for row in characteristics:
key = (row["aid"], row["iid"])
# If the key was returned by put_characteristics() then the
# change didnt work
if key in results:
continue
# Otherwise it was accepted and we can apply the change to
# our state
new_entity_state[key] = {"value": row["value"]}
self.process_new_events(new_entity_state)
@property
def unique_id(self):
"""
Return a unique id for this accessory or bridge.
This id is random and will change if a device undergoes a hard reset.
"""
return self.pairing_data["AccessoryPairingID"]
@property
def connection_info(self):
"""Return accessory information for the main accessory."""
return get_bridge_information(self.accessories)
@property
def name(self):
"""Name of the bridge accessory."""
return get_accessory_name(self.connection_info) or self.unique_id