mirror of
https://github.com/home-assistant/core.git
synced 2025-08-19 02:10:12 +00:00
.github
docs
homeassistant
auth
components
ads
air_quality
alarm_control_panel
alexa
auth
automation
axis
binary_sensor
blink
bmw_connected_drive
calendar
camera
cast
climate
cloud
config
conversation
counter
cover
daikin
danfoss_air
deconz
device_tracker
dialogflow
dovado
elkm1
emulated_hue
emulated_roku
envisalink
esphome
fan
fibaro
frontend
geo_location
geofency
google_assistant
gpslogger
group
habitica
hangouts
hassio
homekit
homekit_controller
homematic
homematicip_cloud
http
hue
ifttt
ihc
image_processing
insteon
ios
lifx
light
locative
lock
lovelace
luftdaten
mailbox
mailgun
media_player
mqtt
mysensors
nest
notify
onboarding
opentherm_gw
openuv
owntracks
persistent_notification
point
rainmachine
recorder
remember_the_milk
remote
scene
sensor
.translations
__init__.py
abode.py
ads.py
aftership.py
airvisual.py
alarmdecoder.py
alpha_vantage.py
ambient_station.py
amcrest.py
android_ip_webcam.py
apcupsd.py
api_streams.py
aqualogic.py
arduino.py
arest.py
arlo.py
arwn.py
asuswrt.py
awair.py
bbox.py
bh1750.py
bitcoin.py
blink.py
blockchain.py
bloomsky.py
bme280.py
bme680.py
bmw_connected_drive.py
bom.py
broadlink.py
brottsplatskartan.py
buienradar.py
canary.py
cert_expiry.py
citybikes.py
co2signal.py
coinbase.py
coinmarketcap.py
comed_hourly_pricing.py
comfoconnect.py
command_line.py
cpuspeed.py
crimereports.py
cups.py
currencylayer.py
daikin.py
darksky.py
deluge.py
demo.py
deutsche_bahn.py
dht.py
discogs.py
dnsip.py
dsmr.py
dte_energy_bridge.py
dublin_bus_transport.py
duke_energy.py
dwd_weather_warnings.py
dweet.py
dyson.py
ebox.py
ecoal_boiler.py
ecobee.py
eddystone_temperature.py
edp_redy.py
efergy.py
eight_sleep.py
eliqonline.py
elkm1.py
emoncms.py
enocean.py
enphase_envoy.py
entur_public_transport.py
envirophat.py
envisalink.py
etherscan.py
fail2ban.py
fastdotcom.py
fedex.py
fibaro.py
fido.py
file.py
filesize.py
filter.py
fints.py
fitbit.py
fixer.py
flunearyou.py
folder.py
foobot.py
freebox.py
fritzbox_callmonitor.py
fritzbox_netmonitor.py
gearbest.py
geizhals.py
geo_rss_events.py
gitlab_ci.py
gitter.py
glances.py
google_travel_time.py
google_wifi.py
gpsd.py
greeneye_monitor.py
gtfs.py
gtt.py
habitica.py
haveibeenpwned.py
hddtemp.py
history_stats.py
hive.py
homematic.py
homematicip_cloud.py
hp_ilo.py
htu21d.py
huawei_lte.py
hydrawise.py
hydroquebec.py
ihc.py
iliad_italy.py
imap.py
imap_email_content.py
influxdb.py
insteon.py
ios.py
iota.py
iperf3.py
irish_rail_transport.py
islamic_prayer_times.py
isy994.py
jewish_calendar.py
juicenet.py
kira.py
knx.py
kwb.py
lacrosse.py
lastfm.py
launch_library.py
linky.py
linux_battery.py
logi_circle.py
london_air.py
london_underground.py
loopenergy.py
luftdaten.py
lyft.py
magicseaweed.py
meteo_france.py
metoffice.py
mfi.py
mhz19.py
miflora.py
min_max.py
mitemp_bt.py
modbus.py
modem_callerid.py
mold_indicator.py
moon.py
mopar.py
mqtt_room.py
mvglive.py
mychevy.py
mysensors.py
nederlandse_spoorwegen.py
nest.py
netatmo.py
netatmo_public.py
netdata.py
netgear_lte.py
neurio_energy.py
nmbs.py
noaa_tides.py
nsw_fuel_station.py
nut.py
nzbget.py
octoprint.py
ohmconnect.py
onewire.py
openevse.py
openexchangerates.py
openhardwaremonitor.py
opensky.py
opentherm_gw.py
openweathermap.py
otp.py
pi_hole.py
pilight.py
plex.py
pocketcasts.py
point.py
pollen.py
postnl.py
prezzibenzina.py
pushbullet.py
pvoutput.py
pyload.py
qbittorrent.py
qnap.py
qwikswitch.py
radarr.py
rainbird.py
raincloud.py
random.py
rest.py
rflink.py
rfxtrx.py
ring.py
ripple.py
rmvtransport.py
rtorrent.py
ruter.py
sabnzbd.py
scrape.py
season.py
sense.py
sensehat.py
serial.py
serial_pm.py
seventeentrack.py
shodan.py
sht31.py
sigfox.py
simulated.py
skybeacon.py
skybell.py
sleepiq.py
sma.py
smappee.py
snmp.py
sochain.py
socialblade.py
solaredge.py
sonarr.py
speedtest.py
spotcrime.py
sql.py
srp_energy.py
starlingbank.py
startca.py
statistics.py
steam_online.py
strings.moon.json
strings.season.json
supervisord.py
swiss_hydrological_data.py
swiss_public_transport.py
syncthru.py
synologydsm.py
systemmonitor.py
sytadin.py
tado.py
tahoma.py
tank_utility.py
tautulli.py
tcp.py
ted5000.py
teksavvy.py
tellduslive.py
tellstick.py
temper.py
template.py
tesla.py
thermoworks_smoke.py
thethingsnetwork.py
thinkingcleaner.py
tibber.py
time_date.py
toon.py
torque.py
tradfri.py
trafikverket_weatherstation.py
transmission.py
transport_nsw.py
travisci.py
twitch.py
uber.py
uk_transport.py
upnp.py
ups.py
uptime.py
uscis.py
usps.py
vasttrafik.py
velbus.py
vera.py
verisure.py
version.py
viaggiatreno.py
volkszaehler.py
volvooncall.py
vultr.py
waqi.py
waterfurnace.py
waze_travel_time.py
whois.py
wink.py
wirelesstag.py
worldclock.py
worldtidesinfo.py
worxlandroid.py
wsdot.py
wunderground.py
xbox_live.py
xiaomi_aqara.py
xiaomi_miio.py
yr.py
yweather.py
zabbix.py
zamg.py
zestimate.py
zigbee.py
zwave.py
simplisafe
smhi
sonos
switch
system_log
telegram_bot
tellduslive
tibber
timer
tradfri
tts
twilio
unifi
upnp
utility_meter
vacuum
water_heater
weather
websocket_api
wink
wunderlist
zha
zone
zoneminder
zwave
__init__.py
abode.py
alarmdecoder.py
alert.py
amcrest.py
android_ip_webcam.py
apcupsd.py
api.py
apple_tv.py
aqualogic.py
arduino.py
arlo.py
asterisk_mbox.py
asuswrt.py
august.py
bbb_gpio.py
bloomsky.py
browser.py
canary.py
cloudflare.py
coinbase.py
comfoconnect.py
configurator.py
datadog.py
demo.py
device_sun_light_trigger.py
digital_ocean.py
discovery.py
dominos.py
doorbird.py
downloader.py
duckdns.py
dweet.py
dyson.py
ecoal_boiler.py
ecobee.py
ecovacs.py
edp_redy.py
egardia.py
eight_sleep.py
emoncms_history.py
enocean.py
eufy.py
evohome.py
feedreader.py
ffmpeg.py
folder_watcher.py
foursquare.py
freebox.py
freedns.py
fritzbox.py
gc100.py
goalfeed.py
google.py
google_domains.py
graphite.py
greeneye_monitor.py
hdmi_cec.py
history.py
history_graph.py
hive.py
hlk_sw16.py
homeworks.py
huawei_lte.py
hydrawise.py
idteck_prox.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
iota.py
isy994.py
joaoapps_join.py
juicenet.py
keyboard.py
keyboard_remote.py
kira.py
knx.py
konnected.py
lametric.py
lcn.py
lightwave.py
linode.py
lirc.py
litejet.py
logbook.py
logentries.py
logger.py
logi_circle.py
lupusec.py
lutron.py
lutron_caseta.py
map.py
matrix.py
maxcube.py
media_extractor.py
melissa.py
microsoft_face.py
mochad.py
modbus.py
mqtt_eventstream.py
mqtt_statestream.py
mychevy.py
mycroft.py
mythicbeastsdns.py
namecheapdns.py
neato.py
ness_alarm.py
netatmo.py
netgear_lte.py
no_ip.py
nuheat.py
nuimo_controller.py
octoprint.py
panel_custom.py
panel_iframe.py
pilight.py
plant.py
plum_lightpad.py
prometheus.py
proximity.py
python_script.py
qwikswitch.py
rachio.py
rainbird.py
raincloud.py
raspihats.py
rest_command.py
rflink.py
rfxtrx.py
ring.py
roku.py
route53.py
rpi_gpio.py
rpi_pfio.py
rss_feed_template.py
sabnzbd.py
satel_integra.py
script.py
scsgate.py
sense.py
services.yaml
shell_command.py
shiftr.py
shopping_list.py
sisyphus.py
skybell.py
sleepiq.py
smappee.py
snips.py
spaceapi.py
spc.py
spider.py
splunk.py
statsd.py
sun.py
tado.py
tahoma.py
tellstick.py
tesla.py
thethingsnetwork.py
thingspeak.py
toon.py
tplink_lte.py
tuya.py
upcloud.py
updater.py
usps.py
velbus.py
velux.py
vera.py
verisure.py
volvooncall.py
vultr.py
w800rf32.py
wake_on_lan.py
waterfurnace.py
watson_iot.py
webhook.py
weblink.py
wemo.py
wirelesstag.py
xiaomi_aqara.py
zabbix.py
zeroconf.py
zigbee.py
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
91 lines
2.5 KiB
Python
91 lines
2.5 KiB
Python
"""
|
|
Entity to track connections to stream API.
|
|
|
|
For more details about this platform, please refer to the documentation at
|
|
https://home-assistant.io/components/sensor.api_streams/
|
|
"""
|
|
import logging
|
|
|
|
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
|
|
from homeassistant.core import callback
|
|
from homeassistant.helpers.entity import Entity
|
|
|
|
NAME_WS = 'homeassistant.components.websocket_api'
|
|
NAME_STREAM = 'homeassistant.components.api'
|
|
|
|
|
|
class StreamHandler(logging.Handler):
|
|
"""Check log messages for stream connect/disconnect."""
|
|
|
|
def __init__(self, entity):
|
|
"""Initialize handler."""
|
|
super().__init__()
|
|
self.entity = entity
|
|
self.count = 0
|
|
|
|
def handle(self, record):
|
|
"""Handle a log message."""
|
|
if record.name == NAME_STREAM:
|
|
if not record.msg.startswith('STREAM'):
|
|
return
|
|
|
|
if record.msg.endswith('ATTACHED'):
|
|
self.entity.count += 1
|
|
elif record.msg.endswith('RESPONSE CLOSED'):
|
|
self.entity.count -= 1
|
|
|
|
else:
|
|
if not record.msg.startswith('WS'):
|
|
return
|
|
if len(record.args) < 2:
|
|
return
|
|
if record.args[1] == 'Connected':
|
|
self.entity.count += 1
|
|
elif record.args[1] == 'Closed connection':
|
|
self.entity.count -= 1
|
|
|
|
self.entity.schedule_update_ha_state()
|
|
|
|
|
|
async def async_setup_platform(
|
|
hass, config, async_add_entities, discovery_info=None):
|
|
"""Set up the API streams platform."""
|
|
entity = APICount()
|
|
handler = StreamHandler(entity)
|
|
|
|
logging.getLogger(NAME_STREAM).addHandler(handler)
|
|
logging.getLogger(NAME_WS).addHandler(handler)
|
|
|
|
@callback
|
|
def remove_logger(event):
|
|
"""Remove our handlers."""
|
|
logging.getLogger(NAME_STREAM).removeHandler(handler)
|
|
logging.getLogger(NAME_WS).removeHandler(handler)
|
|
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, remove_logger)
|
|
|
|
async_add_entities([entity])
|
|
|
|
|
|
class APICount(Entity):
|
|
"""Entity to represent how many people are connected to the stream API."""
|
|
|
|
def __init__(self):
|
|
"""Initialize the API count."""
|
|
self.count = 0
|
|
|
|
@property
|
|
def name(self):
|
|
"""Return name of entity."""
|
|
return "Connected clients"
|
|
|
|
@property
|
|
def state(self):
|
|
"""Return current API count."""
|
|
return self.count
|
|
|
|
@property
|
|
def unit_of_measurement(self):
|
|
"""Return the unit of measurement."""
|
|
return "clients"
|