Advertisement
Guest User

Untitled

a guest
Dec 5th, 2017
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.53 KB | None | 0 0
  1. """
  2. Support for RESTful API sensors.
  3. For more details about this platform, please refer to the documentation at
  4. https://home-assistant.io/components/sensor.rest/
  5. Modified to parse a JSON reply and store data as attributes
  6.  
  7. DISCUSSIONE UFFICIALE
  8. https://community.home-assistant.io/t/solved-parsing-a-json-value-from-an-existing-entity-in-a-template-sensor/20490/19
  9.  
  10. VERSIONE MOD. 0.57.1
  11. https://gist.github.com/sti0/23f47d8aec03a0981f1c4aa2d6f9c258
  12. """
  13. import logging
  14.  
  15. import voluptuous as vol
  16. import json
  17. import requests
  18. from requests.auth import HTTPBasicAuth, HTTPDigestAuth
  19.  
  20. from homeassistant.components.sensor import PLATFORM_SCHEMA
  21. from homeassistant.const import (
  22. CONF_PAYLOAD, CONF_NAME, CONF_VALUE_TEMPLATE, CONF_METHOD, CONF_RESOURCE,
  23. CONF_UNIT_OF_MEASUREMENT, STATE_UNKNOWN, STATE_ON, CONF_VERIFY_SSL,
  24. CONF_USERNAME, CONF_PASSWORD, CONF_AUTHENTICATION,
  25. HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION, CONF_HEADERS)
  26. from homeassistant.helpers.entity import Entity
  27. import homeassistant.helpers.config_validation as cv
  28.  
  29. _LOGGER = logging.getLogger(__name__)
  30.  
  31. DEFAULT_METHOD = 'GET'
  32. DEFAULT_NAME = 'JSON REST Sensor'
  33. DEFAULT_VERIFY_SSL = True
  34.  
  35. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
  36. vol.Required(CONF_RESOURCE): cv.url,
  37. vol.Optional(CONF_AUTHENTICATION):
  38. vol.In([HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION]),
  39. vol.Optional(CONF_HEADERS): {cv.string: cv.string},
  40. vol.Optional(CONF_METHOD, default=DEFAULT_METHOD): vol.In(['POST', 'GET']),
  41. vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
  42. vol.Optional(CONF_PASSWORD): cv.string,
  43. vol.Optional(CONF_PAYLOAD): cv.string,
  44. vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
  45. vol.Optional(CONF_USERNAME): cv.string,
  46. vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
  47. vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean,
  48. })
  49.  
  50.  
  51. def setup_platform(hass, config, add_devices, discovery_info=None):
  52. """Set up the RESTful sensor."""
  53. name = config.get(CONF_NAME)
  54. resource = config.get(CONF_RESOURCE)
  55. method = config.get(CONF_METHOD)
  56. payload = config.get(CONF_PAYLOAD)
  57. verify_ssl = config.get(CONF_VERIFY_SSL)
  58. username = config.get(CONF_USERNAME)
  59. password = config.get(CONF_PASSWORD)
  60. headers = config.get(CONF_HEADERS)
  61. unit = config.get(CONF_UNIT_OF_MEASUREMENT)
  62. value_template = config.get(CONF_VALUE_TEMPLATE)
  63. if value_template is not None:
  64. value_template.hass = hass
  65.  
  66. if username and password:
  67. if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
  68. auth = HTTPDigestAuth(username, password)
  69. else:
  70. auth = HTTPBasicAuth(username, password)
  71. else:
  72. auth = None
  73. rest = JSONRestData(method, resource, auth, headers, payload, verify_ssl)
  74. rest.update()
  75.  
  76. if rest.data is None:
  77. _LOGGER.error("Unable to fetch REST data")
  78. return False
  79.  
  80. add_devices([JSONRestSensor(hass, rest, name, unit, value_template)])
  81.  
  82.  
  83. class JSONRestSensor(Entity):
  84. """Implementation of a REST sensor."""
  85.  
  86. def __init__(self, hass, rest, name, unit_of_measurement, value_template):
  87. """Initialize the REST sensor."""
  88. self._hass = hass
  89. self.rest = rest
  90. self._name = name
  91. self._attributes = []
  92. self._state = STATE_UNKNOWN
  93. self._unit_of_measurement = unit_of_measurement
  94. self._value_template = value_template
  95. self.update()
  96.  
  97. @property
  98. def name(self):
  99. """Return the name of the sensor."""
  100. return self._name
  101.  
  102. @property
  103. def unit_of_measurement(self):
  104. """Return the unit the value is expressed in."""
  105. return self._unit_of_measurement
  106.  
  107. @property
  108. def state(self):
  109. """Return the state of the device."""
  110. return self._state
  111.  
  112. def update(self):
  113. """Get the latest data from REST API and update the state."""
  114. self.rest.update()
  115. value = self.rest.data
  116.  
  117. if value is None:
  118. value = STATE_UNKNOWN
  119. elif self._value_template is not None:
  120. value = self._value_template.render_with_possible_json_value(
  121. value, STATE_UNKNOWN)
  122.  
  123. self._state = STATE_ON
  124.  
  125. """ Parse the return text as JSON and save the json as an attribute. """
  126. try:
  127. self._attributes = json.loads(value)
  128. except json.JSONDecodeError:
  129. self._attributes = []
  130. pass
  131.  
  132.  
  133. @property
  134. def state_attributes(self):
  135. """Return the attributes of the entity.
  136. Provide the parsed JSON data (if any).
  137. """
  138.  
  139. return self._attributes
  140.  
  141.  
  142. class JSONRestData(object):
  143. """Class for handling the data retrieval."""
  144.  
  145. def __init__(self, method, resource, auth, headers, data, verify_ssl):
  146. """Initialize the data object."""
  147. self._request = requests.Request(
  148. method, resource, headers=headers, auth=auth, data=data).prepare()
  149. self._verify_ssl = verify_ssl
  150. self.data = None
  151.  
  152. def update(self):
  153. """Get the latest data from REST service with provided method."""
  154. try:
  155. with requests.Session() as sess:
  156. response = sess.send(
  157. self._request, timeout=10, verify=self._verify_ssl)
  158.  
  159. self.data = response.text
  160. except requests.exceptions.RequestException:
  161. _LOGGER.error("Error fetching data: %s", self._request)
  162. self.data = None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement