Add sensor to show how many clients are connected. (#4430)

* Add sensor to show how many clients are connected.

* Lint

* Fix tests
pull/4447/head
Paulus Schoutsen 2016-11-17 21:54:47 -08:00 committed by GitHub
parent 23fb8c4cdd
commit af77341494
2 changed files with 100 additions and 0 deletions

View File

@ -0,0 +1,61 @@
"""Entity to track connections to stream API."""
import asyncio
import logging
from homeassistant.helpers.entity import Entity
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 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
self.entity.schedule_update_ha_state()
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up the logger for filters."""
entity = APICount()
logging.getLogger('homeassistant.components.api').addHandler(
StreamHandler(entity))
yield from async_add_devices([entity])
class APICount(Entity):
"""Entity to represent how many people are connected to 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):
"""Unit of measurement."""
return "clients"

View File

@ -0,0 +1,39 @@
import asyncio
import logging
from homeassistant.bootstrap import async_setup_component
from tests.common import assert_setup_component
@asyncio.coroutine
def test_api_streams(hass):
"""Test API streams."""
log = logging.getLogger('homeassistant.components.api')
with assert_setup_component(1):
yield from async_setup_component(hass, 'sensor', {
'sensor': {
'platform': 'api_streams',
}
})
state = hass.states.get('sensor.connected_clients')
assert state.state == '0'
log.debug('STREAM 1 ATTACHED')
yield from hass.async_block_till_done()
state = hass.states.get('sensor.connected_clients')
assert state.state == '1'
log.debug('STREAM 1 ATTACHED')
yield from hass.async_block_till_done()
state = hass.states.get('sensor.connected_clients')
assert state.state == '2'
log.debug('STREAM 1 RESPONSE CLOSED')
yield from hass.async_block_till_done()
state = hass.states.get('sensor.connected_clients')
assert state.state == '1'