56 lines
2.1 KiB
Python
56 lines
2.1 KiB
Python
import logging
|
|
import voluptuous as vol
|
|
from collections import defaultdict
|
|
import homeassistant.helpers.config_validation as cv
|
|
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_USERNAME, CONF_PASSWORD
|
|
from homeassistant.helpers import aiohttp_client
|
|
import functools
|
|
from aiohttp import BasicAuth
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
DOMAIN = 'sysdweb'
|
|
DATA_SYSDWEB = "data_sysdweb"
|
|
CONF_SERVICES = "services"
|
|
|
|
CONFIG_SCHEMA = vol.Schema({
|
|
DOMAIN: cv.ensure_list(vol.Schema({
|
|
vol.Required(CONF_HOST): cv.string,
|
|
vol.Optional(CONF_PORT, default=10080): cv.port,
|
|
vol.Required(CONF_USERNAME): cv.string,
|
|
vol.Required(CONF_PASSWORD): cv.string,
|
|
vol.Required(CONF_SERVICES): cv.ensure_list(cv.string)
|
|
}))
|
|
}, extra=vol.ALLOW_EXTRA)
|
|
|
|
|
|
async def async_setup(hass, config):
|
|
info_map = {}
|
|
for conf_entry in config[DOMAIN]:
|
|
host = conf_entry[CONF_HOST]
|
|
port = conf_entry[CONF_PORT]
|
|
auth = BasicAuth(login=conf_entry[CONF_USERNAME], password=conf_entry[CONF_PASSWORD])
|
|
for service_name in conf_entry[CONF_SERVICES]:
|
|
info_map[(host, service_name)] = (f"http://{host}:{port}/api/v1/{service_name}/", auth)
|
|
hass.data[DATA_SYSDWEB] = info_map
|
|
|
|
# services
|
|
possible_actions = ['start', 'stop', 'restart', 'reload', 'reloadorrestart']
|
|
|
|
async def service_call(call, sysdweb_action):
|
|
assert sysdweb_action in possible_actions
|
|
hostname = call.data.get("hostname")
|
|
service_name = call.data.get("service_name")
|
|
url, auth = hass.data[DATA_SYSDWEB][(hostname, service_name)]
|
|
session = aiohttp_client.async_get_clientsession(hass)
|
|
async with session.get(url + sysdweb_action, auth=auth) as resp:
|
|
resp_json = await resp.json()
|
|
result = resp_json[sysdweb_action]
|
|
if result != 'OK' or resp.status != 200:
|
|
_LOGGER.error(f"Error calling service sysdweb: {action} {resp_json}")
|
|
|
|
for action in possible_actions:
|
|
hass.services.async_register(DOMAIN, action, functools.partial(service_call, sysdweb_action=action))
|
|
|
|
return True
|