Skip to content

Commit

Permalink
Fix load_json calls
Browse files Browse the repository at this point in the history
  • Loading branch information
robbinjanssen committed Aug 4, 2020
1 parent 9a41e20 commit 7bab87f
Showing 1 changed file with 46 additions and 45 deletions.
91 changes: 46 additions & 45 deletions custom_components/omnik_inverter/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
JS_URL = 'http://{0}/js/status.js'
JSON_URL = 'http://{0}/status.json?CMD=inv_query&rand={1}'
CACHE_NAME = '.{0}.json'
CACHE_VALUE_KEY = "cache_value"
CACHE_DAY_KEY = "cache_day"

_LOGGER = logging.getLogger(__name__)

Expand All @@ -58,6 +60,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
cache = config.get(CONF_CACHE_POWER_TODAY)
use_json = config.get(CONF_USE_JSON)
scan_interval = config.get(CONF_SCAN_INTERVAL)
cache_name = hass.config.path(CACHE_NAME)

try:
if use_json is False:
Expand All @@ -71,7 +74,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
entities = []

for sensor_type in SENSOR_TYPES:
entities.append(OmnikInverterSensor(data, sensor_type, cache))
entities.append(OmnikInverterSensor(data, sensor_type, cache, cache_name))

add_devices(entities)

Expand All @@ -92,7 +95,7 @@ def _update(self):
"""Update the data from the Omnik Inverter."""
dataurl = JS_URL.format(self._host)
try:
fp = urlopen(dataurl, 30)
fp = urlopen(dataurl, timeout=30)
r = fp.read()
except OSError:
_LOGGER.error("Unable to fetch data from Omnik Inverter %s", self._host)
Expand Down Expand Up @@ -140,7 +143,7 @@ def _update(self):
"""Update the data from the Omnik Inverter."""
dataurl = JSON_URL.format(self._host, random())
try:
fp = urlopen(dataurl, 30)
fp = urlopen(dataurl, timeout=30)
data = json.load(fp)
except (OSError, JSONDecodeError):
_LOGGER.error("Unable to fetch data from Omnik Inverter %s", self._host)
Expand All @@ -165,17 +168,22 @@ def _update(self):
class OmnikInverterSensor(Entity):
"""Representation of a OmnikInverter sensor from the web data."""

def __init__(self, data, sensor_type, cache):
def __init__(self, data, sensor_type, cache, cache_name):
"""Initialize the sensor."""
self.data = data
self.type = sensor_type
self.cache = cache
self._name = SENSOR_TYPES[self.type][0]
self._unit_of_measurement = SENSOR_TYPES[self.type][1]
self._icon = SENSOR_TYPES[self.type][2]
self._data = data
self._type = sensor_type
self._name = SENSOR_TYPES[self._type][0]
self._unit_of_measurement = SENSOR_TYPES[self._type][1]
self._icon = SENSOR_TYPES[self._type][2]
self._state = None

# Set caching data.
self._cache = cache
self._cache_name = cache_name.format(self._type)

# Trigger an update to get the unique ID.
self.update()
self._unique_id = f"{self.data.result[0]}-{self._name}"
self._unique_id = f"{self._data.result[0]}-{self._name}"

@property
def unique_id(self):
Expand Down Expand Up @@ -204,75 +212,68 @@ def unit_of_measurement(self):

def update(self):
"""Get the latest data and use it to update our sensor state."""
self.data.update()
self._data.update()

# Get the result data
result = self.data.result
result = self._data.result

if result is None:
_LOGGER.debug("No data found for %s", self.type)
_LOGGER.debug("No data found for %s", self._type)
return False

if self.type == 'powercurrent':
if self._type == 'powercurrent':
# Update the sensor state
self._state = result[1]
elif self.type == 'powertoday':
# Define the cache name
cacheName = self.hass.config.path(CACHE_NAME.format(self.type))

elif self._type == 'powertoday':
# Prepare the current actual values
currentValue = result[2]
currentDay = int(datetime.now().strftime('%Y%m%d'))
current_value = result[2]
current_day = int(datetime.now().strftime('%Y%m%d'))

# Check if caching is enabled
if self.cache:
try:
cache = load_json(cacheName)
_LOGGER.debug("Loaded cache: %s", json.dumps(cache))
except HomeAssistantError as error:
cache = {"cacheValue": 0, "cacheDay": 0}
_LOGGER.error("Failed to load cache file: %s", error)
if self._cache:
cache = load_json(self._cache_name, default={CACHE_VALUE_KEY: 0, CACHE_DAY_KEY: 0})
_LOGGER.debug("Loaded cache: %s", json.dumps(cache))

# Extract the cache values
cacheValue = int(cache["cacheValue"])
cacheDay = int(cache["cacheDay"])
cache_value = int(cache[CACHE_VALUE_KEY])
cache_day = int(cache[CACHE_DAY_KEY])

# If the day has not yet passed, and the current value is bigger then
# the cached value, then we update the cached value to the current
# value.
if currentDay == cacheDay and currentValue >= cacheValue:
cacheValue = currentValue
cacheDay = currentDay
if current_day == cache_day and current_value >= cache_value:
cache_value = current_value
cache_day = current_day

# Else if the day has not yet passed but the cache value is bigger then
# the current value, the inverter might have reset the current value
# to 0 to early. Therefor the cached value is used as output.
elif currentDay == cacheDay and cacheValue > currentValue:
currentValue = cacheValue
elif current_day == cache_day and cache_value > current_value:
current_value = cache_value

# Else if the day has passed, but the current value is the same as the
# cached value, then the inverter has NOT reset the current value to
# 0 yet. Therefor manually output the value 0.
elif currentDay > cacheDay and currentValue == cacheValue:
currentValue = 0
elif current_day > cache_day and current_value == cache_value:
current_value = 0

# Lastly if the day has passed and the current value does not match
# the cached value, it is probably reset to 0. So update the cache
# value to the current value.
elif currentDay > cacheDay and currentValue != cacheValue:
cacheValue = currentValue
cacheDay = currentDay
elif current_day > cache_day and current_value != cache_value:
cache_value = current_value
cache_day = current_day

# Store new stats
try:
nextCache = {"cacheValue": cacheValue, "cacheDay": cacheDay}
save_json(cacheName, nextCache)
_LOGGER.debug("Saved cache: %s", json.dumps(nextCache))
next_cache = {CACHE_VALUE_KEY: cache_value, CACHE_DAY_KEY: cache_day}
save_json(self._cache_name, next_cache)
_LOGGER.debug("Saved cache: %s", json.dumps(next_cache))
except OSError as error:
_LOGGER.error("Could not save cache, %s", error)

# Update the sensor state, divide by 100 to make it kWh
self._state = (currentValue / 100)
elif self.type == 'powertotal':
self._state = (current_value / 100)
elif self._type == 'powertotal':
# Update the sensor state, divide by 10 to make it kWh
self._state = (result[3] / 10)

0 comments on commit 7bab87f

Please sign in to comment.