mirror of
https://github.com/home-assistant/core.git
synced 2025-07-19 19:27:45 +00:00
Optimized process component.
This commit is contained in:
parent
b30aeb1777
commit
472308ec71
@ -13,39 +13,47 @@
|
|||||||
# Edit time: 19 min
|
# Edit time: 19 min
|
||||||
#
|
#
|
||||||
"""
|
"""
|
||||||
|
homeassistant.components.process
|
||||||
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
Process watcher.
|
Provides functionality to watch for specific processes running
|
||||||
|
on the host machine.
|
||||||
The arguments are <subentityname>=<substring to find in process list>
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from homeassistant.components import (STATE_ON, STATE_OFF)
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
from homeassistant.components import STATE_ON, STATE_OFF
|
||||||
|
import homeassistant.util as util
|
||||||
|
|
||||||
DOMAIN = 'process'
|
DOMAIN = 'process'
|
||||||
ENTITY_ID_FORMAT = DOMAIN + '.{}'
|
ENTITY_ID_FORMAT = DOMAIN + '.{}'
|
||||||
|
|
||||||
PS_STRING = 'ps awx'
|
PS_STRING = 'ps awx'
|
||||||
|
|
||||||
|
|
||||||
def setup(hass, processes):
|
def setup(hass, processes):
|
||||||
""" Track local processes. """
|
""" Sets up a check if specified processes are running.
|
||||||
|
|
||||||
|
processes: dict mapping entity id to substring to search for
|
||||||
|
in process list.
|
||||||
|
"""
|
||||||
|
|
||||||
|
entities = {ENTITY_ID_FORMAT.format(util.slugify(pname)): pstring
|
||||||
|
for pname, pstring in processes.items()}
|
||||||
|
|
||||||
# pylint: disable=unused-argument
|
# pylint: disable=unused-argument
|
||||||
def _update_process_state(time):
|
def update_process_states(time):
|
||||||
""" Check ps for currently running processes. """
|
""" Check ps for currently running processes and update states. """
|
||||||
with os.popen(PS_STRING, 'r') as psfile:
|
with os.popen(PS_STRING, 'r') as psfile:
|
||||||
lines = list(iter(psfile))
|
lines = list(psfile)
|
||||||
for pname, pstring in processes.items():
|
|
||||||
found = False
|
for entity_id, pstring in entities.items():
|
||||||
for line in lines:
|
state = STATE_ON if any(pstring in l for l in lines) else STATE_OFF
|
||||||
if pstring in line:
|
|
||||||
found = True
|
hass.states.set(entity_id, state)
|
||||||
break
|
|
||||||
entity_id = ENTITY_ID_FORMAT.format(pname)
|
update_process_states(None)
|
||||||
state = found and STATE_ON or STATE_OFF
|
|
||||||
hass.states.set(entity_id, state)
|
hass.track_time_change(update_process_states, second=[0, 30])
|
||||||
|
|
||||||
_update_process_state(None)
|
|
||||||
hass.track_time_change(_update_process_state, second=[0, 30])
|
|
||||||
return True
|
return True
|
||||||
|
Loading…
x
Reference in New Issue
Block a user