Skip to content

Instantly share code, notes, and snippets.

@passie
Created February 8, 2019 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save passie/44e6f2c6cee9e5b59fe67be6b1bba367 to your computer and use it in GitHub Desktop.
Save passie/44e6f2c6cee9e5b59fe67be6b1bba367 to your computer and use it in GitHub Desktop.
"""
Sensor for retrieving the value's of your Zeversolar inverter.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.zeverzolar/
"""
from datetime import timedelta
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_API_KEY, STATE_UNKNOWN, CONF_NAME, CONF_RESOURCES, CONF_RESOURCES)
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
REQUIREMENTS = ['zeversolar_api==0.1.0']
_LOGGER = logging.getLogger(__name__)
CONF_VERSION = 'version'
DEFAULT_NAME = 'ZeverSolar'
DEFAULT_HOST = 'www.zevercloud.com'
DOMAIN = 'zeversolar'
DEFAULT_VERSION = 1
MIN_TIME_BETWEEN_UPDATES = timedelta(hours=1)
SENSOR_TYPES = {
'sid': ['sid', 'ID'],
'E-Today': ['Energy Today', ''],
'E-Month': ['Energy Month', ''],
'E-Total': ['Energy Total', ''],
'TotalYield': ['Total Yield', ''],
'CO2Avoided': ['CO2 Avoided', ''],
'Power': ['Power', '']
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_RESOURCES, default=['sid']):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
vol.Optional(CONF_VERSION, default=DEFAULT_VERSION): vol.In(1),
})
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the Zeversolar sensor."""
from zeversolar_api import Zeversolar
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
version = config.get(CONF_VERSION)
var_conf = config.get(CONF_RESOURCES)
session = async_get_clientsession(hass)
zeversolar = ZeversolarData(
Zeversolar(hass.loop, session, host=host, version=version))
await zeversolar.async_update()
if zeversolar.api.data is None:
raise PlatformNotReady
dev = []
for resource in var_conf:
dev.append(ZeverzolarSensor(zeversolar, name, resource))
async_add_entities(dev, True)
class ZeverzolarSensor(Entity):
"""Implementation of a Zeversolar sensor."""
def __init__(self, zeversolar, name, sensor_type):
"""Initialize the sensor."""
self.zeversolar = zeversolar
self._name = name
self.type = sensor_type
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
@property
def name(self):
"""Return the name of the sensor."""
if self._name is None:
return SENSOR_TYPES[self.type][0]
return '{} {}'.format(self._name, SENSOR_TYPES[self.type][0])
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
@property
def available(self):
"""Could the device be accessed during the last update call."""
return self.zeversolar.available
@property
def state(self):
"""Return the state of the resources."""
return self._state
async def async_update(self):
"""Get the latest data from REST API."""
await self.zeversolar.async_update()
value = self.zeversolar.api.data
if value is not None:
if self.type == 'sid':
self._state = value['sid']
elif self.type == 'E-Today':
self._state = value['E-Today']['value']
self._unit_of_measurement = value['E-Today']['unit']
elif self.type == 'E-Month':
self._state = value['E-Month']['value']
self._unit_of_measurement = value['E-Month']['unit']
elif self.type == 'E-Total':
self._state = value['E-Total']['value']
self._unit_of_measurement = value['E-Total']['unit']
elif self.type == 'TotalYield':
self._state = value['TotalYield']['value']
self._unit_of_measurement = value['TotalYield']['unit']
elif self.type == 'CO2Avoided':
self._state = value['CO2Avoided']['value']
self._unit_of_measurement = value['CO2Avoided']['unit']
elif self.type == 'Power':
self._state = value['Power']['value']
self._unit_of_measurement = value['Power']['unit']
class ZeversolarData:
"""The class for handling the data retrieval."""
def __init__(self, api):
"""Initialize the data object."""
self.api = api
self.available = True
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Get the latest data from the Zeversolar REST API."""
from zeversolar_api.exceptions import ZeversolarApiError
try:
await self.api.get_data()
self.available = True
except ZeversolarApiError:
_LOGGER.error("Unable to fetch data from Zeversolar cloud")
self.available = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment