1
0
mirror of https://github.com/home-assistant/core.git synced 2025-09-05 11:16:21 +00:00
Files
.devcontainer
.github
.vscode
docs
homeassistant
auth
components
abode
accuweather
acer_projector
acmeda
actiontec
adax
adguard
ads
advantage_air
aemet
aftership
agent_dvr
air_quality
airly
airnow
airthings
airtouch4
airvisual
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
almond
alpha_vantage
amazon_polly
ambee
amberelectric
ambiclimate
ambient_station
amcrest
ampio
analytics
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
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
blueprint
bluesound
bluetooth_le_tracker
bluetooth_tracker
bme280
bme680
bmp280
bmw_connected_drive
bond
bosch_shc
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
climacell
climate
cloud
cloudflare
cmus
co2signal
coinbase
color_extractor
comed_hourly_pricing
comfoconnect
command_line
compensation
concord232
config
configurator
control4
conversation
coolmaster
coronavirus
counter
cover
cppm_tracker
cpuspeed
crownstone
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
devolo_home_network
dexcom
dhcp
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
emonitor
emulated_hue
emulated_kasa
emulated_roku
energy
enigma2
enocean
enphase_envoy
entur_public_transport
environment_canada
envirophat
envisalink
ephember
epson
epsonworkforce
eq3btsmart
esphome
etherscan
eufy
everlights
evohome
ezviz
faa_delays
facebook
facebox
fail2ban
familyhub
fan
fastdotcom
feedreader
ffmpeg
ffmpeg_motion
ffmpeg_noise
fibaro
fido
file
filesize
filter
fints
fireservicerota
firmata
fitbit
fixer
fjaraskupan
fleetgo
flexit
flic
flick_electric
flipr
flo
flock
flume
flunearyou
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
fortios
foscam
foursquare
free_mobile
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
frontier_silicon
futurenow
garadget
garages_amsterdam
gc100
gdacs
generic
generic_hygrostat
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
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
home_plus_control
homeassistant
homekit
homekit_controller
homematic
homematicip_cloud
homeworks
honeywell
horizon
hp_ilo
html5
http
htu21d
huawei_lte
hue
huisbaasje
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
intent
intent_script
intesishome
ios
iota
iotawatt
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
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
kulersky
kwb
lacrosse
lametric
lannouncer
lastfm
launch_library
lcn
lg_netcast
lg_soundbar
life360
lifx
lifx_cloud
light
lightwave
limitlessled
linksys_smart
linode
linux_battery
lirc
litejet
litterrobot
llamalab_automate
local_file
local_ip
locative
lock
logbook
logentries
logger
logi_circle
london_air
london_underground
lookin
loopenergy
lovelace
luci
luftdaten
lupusec
lutron
lutron_caseta
lw12wifi
lyric
magicseaweed
mailbox
mailgun
manual
manual_mqtt
map
marytts
mastodon
matrix
maxcube
mazda
mcp23017
media_extractor
media_player
media_source
mediaroom
melcloud
melissa
meraki
message_bird
met
met_eireann
meteo_france
meteoalarm
meteoclimatic
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
modern_forms
mold_indicator
monoprice
moon
motion_blinds
motioneye
mpchc
mpd
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
msteams
mullvad
mutesync
mvglive
my
mychevy
mycroft
myq
mysensors
mystrom
mythicbeastsdns
nad
nam
namecheapdns
nanoleaf
neato
nederlandse_spoorwegen
ness_alarm
nest
netatmo
netdata
netgear
netgear_lte
netio
network
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
nuki
numato
number
nut
nws
nx584
nzbget
oasa_telematics
obihai
octoprint
oem
ohmconnect
ombi
omnilogic
onboarding
ondilo_ico
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
p1_monitor
panasonic_bluray
panasonic_viera
pandora
panel_custom
panel_iframe
pcal9535a
pencom
persistent_notification
person
philips_js
pi4ioe5v9xxxx
pi_hole
picnic
picotts
piglow
pilight
ping
pioneer
pjlink
plaato
plant
plex
plugwise
plum_lightpad
pocketcasts
point
poolsense
powerwall
profiler
progettihwsw
proliphix
prometheus
prosegur
prowl
proximity
proxmoxve
proxy
ps4
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
renault
repetier
rest
rest_command
rflink
rfxtrx
ridwell
ring
ripple
risco
rituals_perfume_genie
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
samsungtv
satel_integra
scene
schluter
scrape
screenlogic
script
scsgate
search
season
select
sendgrid
sense
sensehat
sensibo
sensor
sentry
serial
serial_pm
sesame
seven_segments
seventeentrack
sharkiq
shell_command
shelly
shiftr
shodan
shopping_list
sht31
sia
sigfox
sighthound
signal_messenger
simplepush
simplisafe
simulated
sinch
siren
sisyphus
sky_hub
skybeacon
skybell
slack
sleepiq
slide
sma
smappee
smart_meter_texas
smarthab
smartthings
translations
__init__.py
binary_sensor.py
climate.py
config_flow.py
const.py
cover.py
fan.py
light.py
lock.py
manifest.json
scene.py
sensor.py
smartapp.py
strings.json
switch.py
smarttub
smarty
smhi
sms
smtp
snapcast
snips
snmp
sochain
solaredge
solaredge_local
solarlog
solax
soma
somfy
somfy_mylink
sonarr
songpal
sonos
sony_projector
soundtouch
spaceapi
spc
speedtestdotnet
spider
splunk
spotify
sql
squeezebox
srp_energy
ssdp
starline
starlingbank
startca
statistics
statsd
steam_online
stiebel_eltron
stookalert
stream
streamlabswater
stt
subaru
suez_water
sun
supervisord
supla
surepetcare
swiss_hydrological_data
swiss_public_transport
swisscom
switch
switchbot
switcher_kis
switchmate
syncthing
syncthru
synology_chat
synology_dsm
synology_srm
syslog
system_bridge
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
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
trace
tractive
tradfri
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
travisci
trend
tts
tuya
twentemilieu
twilio
twilio_call
twilio_sms
twinkly
twitch
twitter
ubus
ue_smart_radio
uk_transport
unifi
unifi_direct
unifiled
universal
upb
upc_connect
upcloud
updater
upnp
uptime
uptimerobot
usb
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
wallbox
waqi
water_heater
waterfurnace
watson_iot
watson_tts
watttime
waze_travel_time
weather
webhook
webostv
websocket_api
wemo
whirlpool
whois
wiffi
wilight
wirelesstag
withings
wled
wolflink
workday
worldclock
worldtidesinfo
worxlandroid
wsdot
x10
xbee
xbox
xbox_live
xeoma
xiaomi
xiaomi_aqara
xiaomi_miio
xiaomi_tv
xmpp
xs1
yale_smart_alarm
yamaha
yamaha_musiccast
yandex_transport
yandextts
yeelight
yeelightsunflower
yi
youless
zabbix
zamg
zengge
zeroconf
zerproc
zestimate
zha
zhong_hong
ziggo_mediabox_xl
zodiac
zone
zoneminder
zwave
zwave_js
__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
pylint
rootfs
script
tests
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.ignore
.pre-commit-config.yaml
.prettierignore
.readthedocs.yml
.strict-typing
.yamllint
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
build.json
codecov.yml
mypy.ini
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/smartthings/config_flow.py
2021-10-23 20:49:04 +02:00

238 lines
9.1 KiB
Python

"""Config flow to configure SmartThings."""
from http import HTTPStatus
import logging
from aiohttp import ClientResponseError
from pysmartthings import APIResponseError, AppOAuth, SmartThings
from pysmartthings.installedapp import format_install_url
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import (
APP_OAUTH_CLIENT_NAME,
APP_OAUTH_SCOPES,
CONF_APP_ID,
CONF_INSTALLED_APP_ID,
CONF_LOCATION_ID,
CONF_REFRESH_TOKEN,
DOMAIN,
VAL_UID_MATCHER,
)
from .smartapp import (
create_app,
find_app,
format_unique_id,
get_webhook_url,
setup_smartapp,
setup_smartapp_endpoint,
update_app,
validate_webhook_requirements,
)
_LOGGER = logging.getLogger(__name__)
class SmartThingsFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle configuration of SmartThings integrations."""
VERSION = 2
def __init__(self):
"""Create a new instance of the flow handler."""
self.access_token = None
self.app_id = None
self.api = None
self.oauth_client_secret = None
self.oauth_client_id = None
self.installed_app_id = None
self.refresh_token = None
self.location_id = None
async def async_step_import(self, user_input=None):
"""Occurs when a previously entry setup fails and is re-initiated."""
return await self.async_step_user(user_input)
async def async_step_user(self, user_input=None):
"""Validate and confirm webhook setup."""
await setup_smartapp_endpoint(self.hass)
webhook_url = get_webhook_url(self.hass)
# Abort if the webhook is invalid
if not validate_webhook_requirements(self.hass):
return self.async_abort(
reason="invalid_webhook_url",
description_placeholders={
"webhook_url": webhook_url,
"component_url": "https://www.home-assistant.io/integrations/smartthings/",
},
)
# Show the confirmation
if user_input is None:
return self.async_show_form(
step_id="user",
description_placeholders={"webhook_url": webhook_url},
)
# Show the next screen
return await self.async_step_pat()
async def async_step_pat(self, user_input=None):
"""Get the Personal Access Token and validate it."""
errors = {}
if user_input is None or CONF_ACCESS_TOKEN not in user_input:
return self._show_step_pat(errors)
self.access_token = user_input[CONF_ACCESS_TOKEN]
# Ensure token is a UUID
if not VAL_UID_MATCHER.match(self.access_token):
errors[CONF_ACCESS_TOKEN] = "token_invalid_format"
return self._show_step_pat(errors)
# Setup end-point
self.api = SmartThings(async_get_clientsession(self.hass), self.access_token)
try:
app = await find_app(self.hass, self.api)
if app:
await app.refresh() # load all attributes
await update_app(self.hass, app)
# Find an existing entry to copy the oauth client
existing = next(
(
entry
for entry in self._async_current_entries()
if entry.data[CONF_APP_ID] == app.app_id
),
None,
)
if existing:
self.oauth_client_id = existing.data[CONF_CLIENT_ID]
self.oauth_client_secret = existing.data[CONF_CLIENT_SECRET]
else:
# Get oauth client id/secret by regenerating it
app_oauth = AppOAuth(app.app_id)
app_oauth.client_name = APP_OAUTH_CLIENT_NAME
app_oauth.scope.extend(APP_OAUTH_SCOPES)
client = await self.api.generate_app_oauth(app_oauth)
self.oauth_client_secret = client.client_secret
self.oauth_client_id = client.client_id
else:
app, client = await create_app(self.hass, self.api)
self.oauth_client_secret = client.client_secret
self.oauth_client_id = client.client_id
setup_smartapp(self.hass, app)
self.app_id = app.app_id
except APIResponseError as ex:
if ex.is_target_error():
errors["base"] = "webhook_error"
else:
errors["base"] = "app_setup_error"
_LOGGER.exception(
"API error setting up the SmartApp: %s", ex.raw_error_response
)
return self._show_step_pat(errors)
except ClientResponseError as ex:
if ex.status == HTTPStatus.UNAUTHORIZED:
errors[CONF_ACCESS_TOKEN] = "token_unauthorized"
_LOGGER.debug(
"Unauthorized error received setting up SmartApp", exc_info=True
)
elif ex.status == HTTPStatus.FORBIDDEN:
errors[CONF_ACCESS_TOKEN] = "token_forbidden"
_LOGGER.debug(
"Forbidden error received setting up SmartApp", exc_info=True
)
else:
errors["base"] = "app_setup_error"
_LOGGER.exception("Unexpected error setting up the SmartApp")
return self._show_step_pat(errors)
except Exception: # pylint:disable=broad-except
errors["base"] = "app_setup_error"
_LOGGER.exception("Unexpected error setting up the SmartApp")
return self._show_step_pat(errors)
return await self.async_step_select_location()
async def async_step_select_location(self, user_input=None):
"""Ask user to select the location to setup."""
if user_input is None or CONF_LOCATION_ID not in user_input:
# Get available locations
existing_locations = [
entry.data[CONF_LOCATION_ID] for entry in self._async_current_entries()
]
locations = await self.api.locations()
locations_options = {
location.location_id: location.name
for location in locations
if location.location_id not in existing_locations
}
if not locations_options:
return self.async_abort(reason="no_available_locations")
return self.async_show_form(
step_id="select_location",
data_schema=vol.Schema(
{vol.Required(CONF_LOCATION_ID): vol.In(locations_options)}
),
)
self.location_id = user_input[CONF_LOCATION_ID]
await self.async_set_unique_id(format_unique_id(self.app_id, self.location_id))
return await self.async_step_authorize()
async def async_step_authorize(self, user_input=None):
"""Wait for the user to authorize the app installation."""
user_input = {} if user_input is None else user_input
self.installed_app_id = user_input.get(CONF_INSTALLED_APP_ID)
self.refresh_token = user_input.get(CONF_REFRESH_TOKEN)
if self.installed_app_id is None:
# Launch the external setup URL
url = format_install_url(self.app_id, self.location_id)
return self.async_external_step(step_id="authorize", url=url)
return self.async_external_step_done(next_step_id="install")
def _show_step_pat(self, errors):
if self.access_token is None:
# Get the token from an existing entry to make it easier to setup multiple locations.
self.access_token = next(
(
entry.data.get(CONF_ACCESS_TOKEN)
for entry in self._async_current_entries()
),
None,
)
return self.async_show_form(
step_id="pat",
data_schema=vol.Schema(
{vol.Required(CONF_ACCESS_TOKEN, default=self.access_token): str}
),
errors=errors,
description_placeholders={
"token_url": "https://account.smartthings.com/tokens",
"component_url": "https://www.home-assistant.io/integrations/smartthings/",
},
)
async def async_step_install(self, data=None):
"""Create a config entry at completion of a flow and authorization of the app."""
data = {
CONF_ACCESS_TOKEN: self.access_token,
CONF_REFRESH_TOKEN: self.refresh_token,
CONF_CLIENT_ID: self.oauth_client_id,
CONF_CLIENT_SECRET: self.oauth_client_secret,
CONF_LOCATION_ID: self.location_id,
CONF_APP_ID: self.app_id,
CONF_INSTALLED_APP_ID: self.installed_app_id,
}
location = await self.api.location(data[CONF_LOCATION_ID])
return self.async_create_entry(title=location.name, data=data)