Advertisement
Guest User

Untitled

a guest
May 3rd, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.05 KB | None | 0 0
  1. """
  2. Allows to configure custom shell commands to turn a value for a sensor.
  3.  
  4. For more details about this platform, please refer to the documentation at
  5. https://home-assistant.io/components/sensor.command_line/
  6. """
  7. from datetime import timedelta
  8. import logging
  9. import subprocess
  10.  
  11. import voluptuous as vol
  12. from homeassistant.helpers import template
  13. from homeassistant.exceptions import TemplateError
  14.  
  15. from homeassistant.components.sensor import PLATFORM_SCHEMA
  16. from homeassistant.const import (
  17.     CONF_NAME, CONF_VALUE_TEMPLATE, CONF_UNIT_OF_MEASUREMENT, CONF_COMMAND,
  18.     STATE_UNKNOWN)
  19. from homeassistant.helpers.entity import Entity
  20. import homeassistant.helpers.config_validation as cv
  21.  
  22. _LOGGER = logging.getLogger(__name__)
  23.  
  24. DEFAULT_NAME = 'Templated Command Sensor'
  25.  
  26. SCAN_INTERVAL = timedelta(seconds=60)
  27.  
  28. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
  29.     vol.Required(CONF_COMMAND): cv.string,
  30.     vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
  31.     vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
  32.     vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
  33. })
  34.  
  35.  
  36. # pylint: disable=unused-argument
  37. def setup_platform(hass, config, add_devices, discovery_info=None):
  38.     """Setup the Command Sensor."""
  39.     name = config.get(CONF_NAME)
  40.     command = config.get(CONF_COMMAND)
  41.     unit = config.get(CONF_UNIT_OF_MEASUREMENT)
  42.     value_template = config.get(CONF_VALUE_TEMPLATE)
  43.     if value_template is not None:
  44.         value_template.hass = hass
  45.     data = TemplatedCommandSensorData(hass, command)
  46.  
  47.     add_devices([TemplatedCommandSensor(hass, data, name, unit, value_template)])
  48.  
  49.  
  50. class TemplatedCommandSensor(Entity):
  51.     """Representation of a sensor that is using shell commands."""
  52.  
  53.     def __init__(self, hass, data, name, unit_of_measurement, value_template):
  54.         """Initialize the sensor."""
  55.         self._hass = hass
  56.         self.data = data
  57.         self._name = name
  58.         self._state = STATE_UNKNOWN
  59.         self._unit_of_measurement = unit_of_measurement
  60.         self._value_template = value_template
  61.         self.update()
  62.  
  63.     @property
  64.     def name(self):
  65.         """Return the name of the sensor."""
  66.         return self._name
  67.  
  68.     @property
  69.     def unit_of_measurement(self):
  70.         """Return the unit the value is expressed in."""
  71.         return self._unit_of_measurement
  72.  
  73.     @property
  74.     def state(self):
  75.         """Return the state of the device."""
  76.         return self._state
  77.  
  78.     def update(self):
  79.         """Get the latest data and updates the state."""
  80.         globals()['hass']=self._hass
  81.         self.data.update(hass)
  82.         value = self.data.value
  83.  
  84.         if value is None:
  85.             value = STATE_UNKNOWN
  86.         elif self._value_template is not None:
  87.             self._state = self._value_template.render_with_possible_json_value(
  88.                 value, STATE_UNKNOWN)
  89.         else:
  90.             self._state = value
  91.  
  92.  
  93. class TemplatedCommandSensorData(object):
  94.     """The class for handling the data retrieval."""
  95.  
  96.     def __init__(self, hass, command):
  97.         """Initialize the data object."""
  98.         self.command = command
  99.         self.hass = hass
  100.         self.value = None
  101.  
  102.     def update(self, hass):
  103.         """Get the latest data with a shell command."""
  104.         """Run the command through the template engine to substitute parameters"""
  105.         #_LOGGER.info("____________rendere_______________:"+help(template.Template.render))
  106.         hass.hass = hass
  107.         cmd = template.Template.render(self, {'shell_command': self.command})
  108.        
  109.         #cmd = template.Template.render(None, {'shell_command': self.command})
  110.         _LOGGER.info('Running command: %s', cmd)
  111.  
  112.         try:
  113.             return_value = subprocess.check_output(cmd, shell=True,
  114.                                                    timeout=15)
  115.             self.value = return_value.strip().decode('utf-8')
  116.         except subprocess.CalledProcessError:
  117.             _LOGGER.error('Command failed: %s', cmd)
  118.         except subprocess.TimeoutExpired:
  119.             _LOGGER.error('Timeout for command: %s', cmd)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement