Use voluptuous for Octoprint (#3111)

* Migrate to voluptuous

* Fix pylint issues
This commit is contained in:
Fabian Affolter 2016-09-02 12:26:23 +02:00 committed by GitHub
parent 000832a82c
commit 6a84b82663
3 changed files with 93 additions and 64 deletions

View file

@ -5,34 +5,47 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.octoprint/ https://home-assistant.io/components/binary_sensor.octoprint/
""" """
import logging import logging
import requests import requests
import voluptuous as vol
from homeassistant.const import CONF_NAME, STATE_ON, STATE_OFF from homeassistant.const import (
from homeassistant.components.binary_sensor import BinarySensorDevice CONF_NAME, STATE_ON, STATE_OFF, CONF_MONITORED_CONDITIONS)
from homeassistant.components.binary_sensor import (
BinarySensorDevice, PLATFORM_SCHEMA)
from homeassistant.loader import get_component from homeassistant.loader import get_component
import homeassistant.helpers.config_validation as cv
DEPENDENCIES = ["octoprint"]
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['octoprint']
DEFAULT_NAME = 'OctoPrint'
SENSOR_TYPES = { SENSOR_TYPES = {
# API Endpoint, Group, Key, unit # API Endpoint, Group, Key, unit
"Printing": ["printer", "state", "printing", None], 'Printing': ['printer', 'state', 'printing', None],
"Printing Error": ["printer", "state", "error", None] 'Printing Error': ['printer', 'state', 'error', None]
} }
_LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_MONITORED_CONDITIONS, default=SENSOR_TYPES):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the available OctoPrint binary sensors.""" """Setup the available OctoPrint binary sensors."""
octoprint = get_component('octoprint') octoprint = get_component('octoprint')
name = config.get(CONF_NAME, "OctoPrint") name = config.get(CONF_NAME)
monitored_conditions = config.get("monitored_conditions", monitored_conditions = config.get(CONF_MONITORED_CONDITIONS,
SENSOR_TYPES.keys()) SENSOR_TYPES.keys())
devices = [] devices = []
for octo_type in monitored_conditions: for octo_type in monitored_conditions:
if octo_type in SENSOR_TYPES:
new_sensor = OctoPrintBinarySensor(octoprint.OCTOPRINT, new_sensor = OctoPrintBinarySensor(octoprint.OCTOPRINT,
octo_type, octo_type,
SENSOR_TYPES[octo_type][2], SENSOR_TYPES[octo_type][2],
@ -40,10 +53,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
SENSOR_TYPES[octo_type][3], SENSOR_TYPES[octo_type][3],
SENSOR_TYPES[octo_type][0], SENSOR_TYPES[octo_type][0],
SENSOR_TYPES[octo_type][1], SENSOR_TYPES[octo_type][1],
"flags") 'flags')
devices.append(new_sensor) devices.append(new_sensor)
else:
_LOGGER.error("Unknown OctoPrint sensor type: %s", octo_type)
add_devices(devices) add_devices(devices)
@ -52,14 +63,14 @@ class OctoPrintBinarySensor(BinarySensorDevice):
"""Representation an OctoPrint binary sensor.""" """Representation an OctoPrint binary sensor."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, api, condition, sensor_type, sensor_name, def __init__(self, api, condition, sensor_type, sensor_name, unit,
unit, endpoint, group, tool=None): endpoint, group, tool=None):
"""Initialize a new OctoPrint sensor.""" """Initialize a new OctoPrint sensor."""
self.sensor_name = sensor_name self.sensor_name = sensor_name
if tool is None: if tool is None:
self._name = sensor_name + ' ' + condition self._name = '{} {}'.format(sensor_name, condition)
else: else:
self._name = sensor_name + ' ' + condition self._name = '{} {}'.format(sensor_name, condition)
self.sensor_type = sensor_type self.sensor_type = sensor_type
self.api = api self.api = api
self._state = False self._state = False

View file

@ -5,37 +5,41 @@ For more details about this component, please refer to the documentation at
https://home-assistant.io/components/octoprint/ https://home-assistant.io/components/octoprint/
""" """
import logging import logging
import time import time
import requests import requests
import voluptuous as vol
from homeassistant.const import CONF_API_KEY, CONF_HOST from homeassistant.const import CONF_API_KEY, CONF_HOST, CONTENT_TYPE_JSON
from homeassistant.helpers import validate_config, discovery from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
DOMAIN = "octoprint"
OCTOPRINT = None
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DISCOVER_SENSORS = 'octoprint.sensors'
DISCOVER_BINARY_SENSORS = 'octoprint.binary_sensor' DISCOVER_BINARY_SENSORS = 'octoprint.binary_sensor'
DISCOVER_SENSORS = 'octoprint.sensors'
DOMAIN = 'octoprint'
OCTOPRINT = None
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_HOST): cv.string,
}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config): def setup(hass, config):
"""Set up OctoPrint API.""" """Set up OctoPrint API."""
if not validate_config(config, {DOMAIN: [CONF_API_KEY], base_url = 'http://{}/api/'.format(config[DOMAIN][CONF_HOST])
DOMAIN: [CONF_HOST]},
_LOGGER):
return False
base_url = config[DOMAIN][CONF_HOST] + "/api/"
api_key = config[DOMAIN][CONF_API_KEY] api_key = config[DOMAIN][CONF_API_KEY]
global OCTOPRINT global OCTOPRINT
try: try:
OCTOPRINT = OctoPrintAPI(base_url, api_key) OCTOPRINT = OctoPrintAPI(base_url, api_key)
OCTOPRINT.get("printer") OCTOPRINT.get('printer')
OCTOPRINT.get("job") OCTOPRINT.get('job')
except requests.exceptions.RequestException as conn_err: except requests.exceptions.RequestException as conn_err:
_LOGGER.error("Error setting up OctoPrint API: %r", conn_err) _LOGGER.error("Error setting up OctoPrint API: %r", conn_err)
return False return False
@ -55,7 +59,7 @@ class OctoPrintAPI(object):
def __init__(self, api_url, key): def __init__(self, api_url, key):
"""Initialize OctoPrint API and set headers needed later.""" """Initialize OctoPrint API and set headers needed later."""
self.api_url = api_url self.api_url = api_url
self.headers = {'content-type': 'application/json', self.headers = {'content-type': CONTENT_TYPE_JSON,
'X-Api-Key': key} 'X-Api-Key': key}
self.printer_last_reading = [{}, None] self.printer_last_reading = [{}, None]
self.job_last_reading = [{}, None] self.job_last_reading = [{}, None]

View file

@ -5,31 +5,44 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.octoprint/ https://home-assistant.io/components/sensor.octoprint/
""" """
import logging import logging
import requests
from homeassistant.const import TEMP_CELSIUS, CONF_NAME import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
TEMP_CELSIUS, CONF_NAME, CONF_MONITORED_CONDITIONS)
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.loader import get_component from homeassistant.loader import get_component
import homeassistant.helpers.config_validation as cv
DEPENDENCIES = ["octoprint"]
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['octoprint']
DEFAULT_NAME = 'OctoPrint'
SENSOR_TYPES = { SENSOR_TYPES = {
# API Endpoint, Group, Key, unit # API Endpoint, Group, Key, unit
"Temperatures": ["printer", "temperature", "*", TEMP_CELSIUS], 'Temperatures': ['printer', 'temperature', '*', TEMP_CELSIUS],
"Current State": ["printer", "state", "text", None], 'Current State': ['printer', 'state', 'text', None],
"Job Percentage": ["job", "progress", "completion", "%"], 'Job Percentage': ['job', 'progress', 'completion', '%'],
} }
_LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_MONITORED_CONDITIONS, default=SENSOR_TYPES):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the available OctoPrint sensors.""" """Setup the available OctoPrint sensors."""
octoprint = get_component('octoprint') octoprint = get_component('octoprint')
name = config.get(CONF_NAME, "OctoPrint") name = config.get(CONF_NAME)
monitored_conditions = config.get("monitored_conditions", monitored_conditions = config.get(CONF_MONITORED_CONDITIONS)
SENSOR_TYPES.keys())
devices = [] devices = []
types = ["actual", "target"] types = ["actual", "target"]
@ -46,7 +59,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
SENSOR_TYPES[octo_type][1], SENSOR_TYPES[octo_type][1],
tool) tool)
devices.append(new_sensor) devices.append(new_sensor)
elif octo_type in SENSOR_TYPES: else:
_LOGGER.error("Unknown OctoPrint sensor type: %s", octo_type)
new_sensor = OctoPrintSensor(octoprint.OCTOPRINT, new_sensor = OctoPrintSensor(octoprint.OCTOPRINT,
octo_type, octo_type,
SENSOR_TYPES[octo_type][2], SENSOR_TYPES[octo_type][2],
@ -55,8 +70,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
SENSOR_TYPES[octo_type][0], SENSOR_TYPES[octo_type][0],
SENSOR_TYPES[octo_type][1]) SENSOR_TYPES[octo_type][1])
devices.append(new_sensor) devices.append(new_sensor)
else:
_LOGGER.error("Unknown OctoPrint sensor type: %s", octo_type)
add_devices(devices) add_devices(devices)
@ -66,14 +79,15 @@ class OctoPrintSensor(Entity):
"""Representation of an OctoPrint sensor.""" """Representation of an OctoPrint sensor."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, api, condition, sensor_type, sensor_name, def __init__(self, api, condition, sensor_type, sensor_name, unit,
unit, endpoint, group, tool=None): endpoint, group, tool=None):
"""Initialize a new OctoPrint sensor.""" """Initialize a new OctoPrint sensor."""
self.sensor_name = sensor_name self.sensor_name = sensor_name
if tool is None: if tool is None:
self._name = sensor_name + ' ' + condition self._name = '{} {}'.format(sensor_name, condition)
else: else:
self._name = sensor_name + ' ' + condition + ' ' + tool + ' temp' self._name = '{} {} {} {}'.format(
sensor_name, condition, tool, ' temp')
self.sensor_type = sensor_type self.sensor_type = sensor_type
self.api = api self.api = api
self._state = None self._state = None