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
backports
components
abode
accuweather
acer_projector
acmeda
actiontec
adax
adguard
ads
advantage_air
aemet
aftership
agent_dvr
air_quality
airly
airnow
airthings
airtouch4
airvisual
airzone
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
apple_tv
apprise
aprs
aqualogic
aquostv
arcam_fmj
arest
arlo
arris_tg2492lg
aruba
arwn
aseko_pool_live
asterisk_cdr
asterisk_mbox
asuswrt
atag
aten_pe
atome
august
aurora
aurora_abb_powerone
aussie_broadband
auth
automation
avea
avion
awair
aws
axis
azure_devops
azure_event_hub
azure_service_bus
backup
baidu
balboa
bayesian
bbox
beewi_smartclim
binary_sensor
bitcoin
bizkaibus
blackbird
blebox
blink
blinksticklight
blockchain
bloomsky
blueprint
bluesound
bluetooth_le_tracker
bluetooth_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
broadlink
brother
brottsplatskartan
browser
brunt
bsblan
bt_home_hub_5
bt_smarthub
buienradar
button
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
diagnostics
dialogflow
digital_ocean
digitalloggers
directv
discogs
discord
discovery
dlib_face_detect
dlib_face_identify
dlink
dlna_dmr
dlna_dms
dnsip
dominos
doods
doorbird
dovado
downloader
dsmr
dsmr_reader
dte_energy_bridge
dublin_bus_transport
duckdns
dunehd
dwd_weather_warnings
dweet
dynalite
eafm
ebox
ebusd
ecoal_boiler
ecobee
econet
ecovacs
eddystone_temperature
edimax
edl21
efergy
egardia
eight_sleep
elgato
eliqonline
elkm1
elmax
elv
emby
emoncms
emoncms_history
emonitor
emulated_hue
emulated_kasa
emulated_roku
energy
enigma2
enocean
enphase_envoy
entur_public_transport
environment_canada
envisalink
ephember
epson
epsonworkforce
eq3btsmart
esphome
etherscan
eufy
everlights
evil_genius_labs
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
fivem
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
goalfeed
goalzero
gogogate2
goodwe
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
homewizard
homeworks
honeywell
horizon
hp_ilo
html5
http
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_button
input_datetime
input_number
input_select
input_text
insteon
integration
intellifire
intent
intent_script
intesishome
ios
iotawatt
iperf3
ipma
ipp
iqvia
irish_rail_transport
islamic_prayer_times
iss
isy994
itach
itunes
izone
jellyfin
jewish_calendar
joaoapps_join
juicenet
kaiterra
kaleidescape
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
lovelace
luci
luftdaten
lupusec
lutron
lutron_caseta
lw12wifi
lyric
magicseaweed
mailbox
mailgun
manual
manual_mqtt
map
marytts
mastodon
matrix
maxcube
mazda
media_extractor
media_player
media_source
mediaroom
melcloud
melissa
meraki
message_bird
met
met_eireann
meteo_france
meteoalarm
meteoclimatic
metoffice
mfi
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
moehlenhoff_alpha2
mold_indicator
monoprice
moon
motion_blinds
motioneye
mpd
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
msteams
mullvad
mutesync
mvglive
my
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
nina
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
oncue
ondilo_ico
onewire
onkyo
onvif
open_meteo
openalpr_cloud
openalpr_local
opencv
openerz
openevse
openexchangerates
opengarage
openhardwaremonitor
openhome
opensensemap
opensky
opentherm_gw
openuv
openweathermap
opnsense
opple
oru
orvibo
osramlightify
otp
overkiz
ovo_energy
owntracks
p1_monitor
panasonic_bluray
panasonic_viera
pandora
panel_custom
panel_iframe
pencom
persistent_notification
person
philips_js
pi_hole
picnic
picotts
pilight
ping
pioneer
pjlink
plaato
plant
plex
plugwise
plum_lightpad
pocketcasts
point
poolsense
powerwall
profiler
progettihwsw
proliphix
prometheus
prosegur
prowl
proximity
proxmoxve
proxy
ps4
translations
__init__.py
config_flow.py
const.py
manifest.json
media_player.py
services.yaml
strings.json
pulseaudio_loopback
pure_energie
push
pushbullet
pushover
pushsafer
pvoutput
pvpc_hourly_pricing
pyload
python_script
qbittorrent
qld_bushfire
qnap
qrcode
quantum_gateway
qvr_pro
qwikswitch
rachio
radarr
radio_browser
radiotherm
rainbird
raincloud
rainforest_eagle
rainmachine
random
raspyrfm
rdw
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_power
rss_feed_template
rtorrent
rtsp_to_webrtc
ruckus_unleashed
russound_rio
russound_rnet
sabnzbd
safe_mode
saj
samsungtv
satel_integra
scene
schluter
scrape
screenlogic
script
scsgate
search
season
select
sendgrid
sense
senseme
sensibo
sensor
sentry
serial
serial_pm
sesame
seven_segments
seventeentrack
sharkiq
shell_command
shelly
shiftr
shodan
shopping_list
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
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
steamist
stiebel_eltron
stookalert
stream
streamlabswater
stt
subaru
suez_water
sun
supervisord
supla
surepetcare
swiss_hydrological_data
swiss_public_transport
swisscom
switch
switch_as_x
switchbot
switcher_kis
switchmate
syncthing
syncthru
synology_chat
synology_dsm
synology_srm
syslog
system_bridge
system_health
system_log
systemmonitor
tado
tag
tailscale
tank_utility
tankerkoenig
tapsaff
tasmota
tautulli
tcp
ted5000
telegram
telegram_bot
tellduslive
tellstick
telnet
temper
template
tensorflow
tesla_wall_connector
tfiac
thermoworks_smoke
thethingsnetwork
thingspeak
thinkingcleaner
thomson
threshold
tibber
tikteck
tile
time_date
timer
tmb
tod
todoist
tolo
tomato
tomorrowio
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
unifiprotect
universal
upb
upc_connect
upcloud
update
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
wiz
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_js
zwave_me
__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
.core_files.yaml
.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.yaml
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
tox.ini
core/homeassistant/components/ps4/config_flow.py
2022-01-11 17:33:50 +01:00

205 lines
7.0 KiB
Python

"""Config Flow for PlayStation 4."""
from collections import OrderedDict
from pyps4_2ndscreen.errors import CredentialTimeout
from pyps4_2ndscreen.helpers import Helper
from pyps4_2ndscreen.media_art import COUNTRIES
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import (
CONF_CODE,
CONF_HOST,
CONF_IP_ADDRESS,
CONF_NAME,
CONF_REGION,
CONF_TOKEN,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.util import location
from .const import (
CONFIG_ENTRY_VERSION,
COUNTRYCODE_NAMES,
DEFAULT_ALIAS,
DEFAULT_NAME,
DOMAIN,
)
CONF_MODE = "Config Mode"
CONF_AUTO = "Auto Discover"
CONF_MANUAL = "Manual Entry"
LOCAL_UDP_PORT = 1988
UDP_PORT = 987
TCP_PORT = 997
PORT_MSG = {UDP_PORT: "port_987_bind_error", TCP_PORT: "port_997_bind_error"}
PIN_LENGTH = 8
class PlayStation4FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a PlayStation 4 config flow."""
VERSION = CONFIG_ENTRY_VERSION
def __init__(self):
"""Initialize the config flow."""
self.helper = Helper()
self.creds = None
self.name = None
self.host = None
self.region = None
self.pin = None
self.m_device = None
self.location = None
self.device_list = []
async def async_step_user(self, user_input=None):
"""Handle a user config flow."""
# Check if able to bind to ports: UDP 987, TCP 997.
ports = PORT_MSG.keys()
failed = await self.hass.async_add_executor_job(self.helper.port_bind, ports)
if failed in ports:
reason = PORT_MSG[failed]
return self.async_abort(reason=reason)
return await self.async_step_creds()
async def async_step_creds(self, user_input=None):
"""Return PS4 credentials from 2nd Screen App."""
errors = {}
if user_input is not None:
try:
self.creds = await self.hass.async_add_executor_job(
self.helper.get_creds, DEFAULT_ALIAS
)
if self.creds is not None:
return await self.async_step_mode()
return self.async_abort(reason="credential_error")
except CredentialTimeout:
errors["base"] = "credential_timeout"
return self.async_show_form(step_id="creds", errors=errors)
async def async_step_mode(self, user_input=None):
"""Prompt for mode."""
errors = {}
mode = [CONF_AUTO, CONF_MANUAL]
if user_input is not None:
if user_input[CONF_MODE] == CONF_MANUAL:
try:
if device := user_input[CONF_IP_ADDRESS]:
self.m_device = device
except KeyError:
errors[CONF_IP_ADDRESS] = "no_ipaddress"
if not errors:
return await self.async_step_link()
mode_schema = OrderedDict()
mode_schema[vol.Required(CONF_MODE, default=CONF_AUTO)] = vol.In(list(mode))
mode_schema[vol.Optional(CONF_IP_ADDRESS)] = str
return self.async_show_form(
step_id="mode", data_schema=vol.Schema(mode_schema), errors=errors
)
async def async_step_link(self, user_input=None):
"""Prompt user input. Create or edit entry."""
regions = sorted(COUNTRIES.keys())
default_region = None
errors = {}
if user_input is None:
# Search for device.
# If LOCAL_UDP_PORT cannot be used, a random port will be selected.
devices = await self.hass.async_add_executor_job(
self.helper.has_devices, self.m_device, LOCAL_UDP_PORT
)
# Abort if can't find device.
if not devices:
return self.async_abort(reason="no_devices_found")
self.device_list = [device["host-ip"] for device in devices]
# Check that devices found aren't configured per account.
entries = self._async_current_entries()
if entries:
# Retrieve device data from all entries if creds match.
conf_devices = [
device
for entry in entries
if self.creds == entry.data[CONF_TOKEN]
for device in entry.data["devices"]
]
# Remove configured device from search list.
for c_device in conf_devices:
if c_device["host"] in self.device_list:
# Remove configured device from search list.
self.device_list.remove(c_device["host"])
# If list is empty then all devices are configured.
if not self.device_list:
return self.async_abort(reason="already_configured")
# Login to PS4 with user data.
if user_input is not None:
self.region = user_input[CONF_REGION]
self.name = user_input[CONF_NAME]
# Assume pin had leading zeros, before coercing to int.
self.pin = str(user_input[CONF_CODE]).zfill(PIN_LENGTH)
self.host = user_input[CONF_IP_ADDRESS]
is_ready, is_login = await self.hass.async_add_executor_job(
self.helper.link,
self.host,
self.creds,
self.pin,
DEFAULT_ALIAS,
LOCAL_UDP_PORT,
)
if is_ready is False:
errors["base"] = "cannot_connect"
elif is_login is False:
errors["base"] = "login_failed"
else:
device = {
CONF_HOST: self.host,
CONF_NAME: self.name,
CONF_REGION: self.region,
}
# Create entry.
return self.async_create_entry(
title="PlayStation 4",
data={CONF_TOKEN: self.creds, "devices": [device]},
)
# Try to find region automatically.
if not self.location:
self.location = await location.async_detect_location_info(
async_get_clientsession(self.hass)
)
if self.location:
country = COUNTRYCODE_NAMES.get(self.location.country_code)
if country in COUNTRIES:
default_region = country
# Show User Input form.
link_schema = OrderedDict()
link_schema[vol.Required(CONF_IP_ADDRESS)] = vol.In(list(self.device_list))
link_schema[vol.Required(CONF_REGION, default=default_region)] = vol.In(
list(regions)
)
link_schema[vol.Required(CONF_CODE)] = vol.All(
vol.Strip, vol.Length(max=PIN_LENGTH), vol.Coerce(int)
)
link_schema[vol.Required(CONF_NAME, default=DEFAULT_NAME)] = str
return self.async_show_form(
step_id="link", data_schema=vol.Schema(link_schema), errors=errors
)