Allow decimal places to be set

This commit is contained in:
Fabian Affolter 2015-09-14 10:44:07 +02:00
parent 6606d2a73c
commit 27845d3fc5

View File

@ -14,6 +14,7 @@ sensor:
command: sensor_command
unit_of_measurement: "°C"
correction_factor: 0.0001
decimal_places: 0
Variables:
@ -33,17 +34,20 @@ correction_factor
*Optional
A float value to do some basic calculations.
decimal_places
*Optional
Number of decimal places of the value. Default is 0.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.command_sensor.html
"""
import logging
from subprocess import check_output, CalledProcessError
import subprocess
from datetime import timedelta
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "Command Sensor"
@ -66,18 +70,21 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
data,
config.get('name', DEFAULT_NAME),
config.get('unit_of_measurement'),
config.get('correction_factor', 1.0)
config.get('correction_factor', None),
config.get('decimal_places', 0)
)])
class CommandSensor(Entity):
""" Represents a sensor that is returning a value of a shell commands. """
def __init__(self, data, name, unit_of_measurement, corr_factor):
def __init__(self, data, name, unit_of_measurement, corr_factor,
decimal_places):
self.data = data
self._name = name
self._state = False
self._unit_of_measurement = unit_of_measurement
self._corr_factor = corr_factor
self._corr_factor = float(corr_factor)
self._decimal_places = decimal_places
self.update()
@property
@ -101,7 +108,11 @@ class CommandSensor(Entity):
value = self.data.value
if value is not None:
self._state = int(round(float(value)) * self._corr_factor)
if self._corr_factor is not None:
self._state = round((int(value) * self._corr_factor),
self._decimal_places)
else:
self._state = value
# pylint: disable=too-few-public-methods
@ -118,7 +129,7 @@ class CommandSensorData(object):
_LOGGER.info('Running command: %s', self.command)
try:
return_value = check_output(self.command.split())
return_value = subprocess.check_output(self.command.split())
self.value = return_value.strip().decode('utf-8')
except CalledProcessError:
except subprocess.CalledProcessError:
_LOGGER.error('Command failed: %s', self.command)