Skip to content

Commit

Permalink
Merge pull request #18 from robbinjanssen/rja/v1.3.0
Browse files Browse the repository at this point in the history
v1.3.0
  • Loading branch information
robbinjanssen authored May 7, 2020
2 parents 54bad0d + a118dfc commit 64c9241
Show file tree
Hide file tree
Showing 4 changed files with 120 additions and 28 deletions.
43 changes: 36 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# Home Assistant Omnik Inverter
The Omnik Inverter Sensor component will retrieve data from an Omnik inverter connected to your local network.
It has been tested and developed on an Omnik 4K TL2 and it might work for other inverters as well.
It has been tested and developed on an Omnik 4k TL2, 2k TL2 and it might work for other inverters as well.

The values will be presented as sensors in [Home Assistant](https://home-assistant.io/).

Expand All @@ -12,7 +12,7 @@ Your Omnik Inverter needs to be connected to your local network, as this custom

## HACS installation

Add this component using HACS by searching for `omnik-inverter` on the `Integrations` page.
Add this component using HACS by searching for `Omnik Inverter` on the `Integrations` page.

## Manual installation

Expand Down Expand Up @@ -49,7 +49,8 @@ sensor:

## How does it work?

The web interface has a javascript file that contains the actual values. This is updated every minute (afaik). Check it out in your browser at `http://<your omnik ip address>/js/status.js`
The web interface has a javascript file that contains the actual values. This is updated every
5 minutes. Check it out in your browser at `http://<your omnik ip address>/js/status.js`

The result contains a lot of information, but there is one part we're interested in:
```js
Expand All @@ -60,16 +61,44 @@ var myDeviceArray=new Array(); myDeviceArray[0]="AANN3020,V5.04Build230,V4.13Bui
// ... Even more data
```

This variable declaration contains your serial number, firmware versions, hardware information, the current power output: 1920, the energy generated today: 429 and the total energy generated: 87419.
This output contains your serial number, firmware versions, hardware information, the
current power output: 1920, the energy generated today: 429 and the total energy generated: 87419.

This custom component basically requests the URL, looks for the _webData_ part and extracts the values as the following sensors:
The custom component basically requests the URL, looks for the _webData_ part and extracts the
values as the following sensors:
- `sensor.solar_power_current` (Watt)
- `sensor.solar_power_today` (kWh)
- `sensor.solar_power_total` (kWh)

### Caching power today.
### My inverter doesn't show any output when I go to the URL.

In a few cases the Omnik inverter resets the `solar_power_today` to 0.0 after for example 21:00. By setting the `cache_power_today` config attribute to `true` (default) this component will cache the the value and only resets to 0.0 after midnight. If you do not experience this, then disable the cache by setting the config variable to `false`.
> Use this if you have an Omnik Inverter 2k TL2.

Some inverters use a JSON status file to output the values. Check if your
inverter outputs JSON data by navigating to: `http://<your omnik ip address>/status.json?CMD=inv_query&rand=0.1234567`.

If so, then use the `use_json` config boolean to make the component use the URL above.

``` YAML
sensor:
- platform: omnik_inverter
host: 192.168.100.100
use_json: true
```

### Caching "power today".

In a few cases the Omnik inverter resets the `solar_power_today` to 0.0 after for example 21:00. By
setting the `cache_power_today` config attribute to `true` (default) this component will cache the
value and only resets to 0.0 after midnight. If you do not experience this, then disable the
cache by setting the config variable to `false`.

``` YAML
sensor:
- platform: omnik_inverter
host: 192.168.100.100
cache_power_today: false
```

## References

Expand Down
82 changes: 68 additions & 14 deletions custom_components/omnik_inverter/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
- platform: omnik_inverter
host: 192.168.100.100
cache_power_today: true
use_json: false
"""
import json
import logging
from random import random
from datetime import timedelta
from datetime import datetime

Expand All @@ -23,16 +26,18 @@
import re
import pickle

VERSION = '1.2.2'
VERSION = '1.3.0'

CONF_CACHE_POWER_TODAY = 'cache_power_today'
CONF_USE_JSON = 'use_json'

BASE_URL = 'http://{0}/js/status.js'
BASE_CACHE_NAME = '.{0}.pickle'
JS_URL = 'http://{0}/js/status.js'
JSON_URL = 'http://{0}/status.json?CMD=inv_query&rand={1}'
CACHE_NAME = '.{0}.pickle'

_LOGGER = logging.getLogger(__name__)

MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=500)

SENSOR_TYPES = {
'powercurrent': ['Solar Power Current', POWER_WATT, 'mdi:weather-sunny'],
Expand All @@ -42,17 +47,22 @@

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_CACHE_POWER_TODAY, default=True): cv.boolean
vol.Optional(CONF_CACHE_POWER_TODAY, default=True): cv.boolean,
vol.Optional(CONF_USE_JSON, default=False): cv.boolean
})


def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Solar Portal sensors."""
host = config.get(CONF_HOST)
cache = config.get(CONF_CACHE_POWER_TODAY)
use_json = config.get(CONF_USE_JSON)

try:
data = OmnikInverterWeb(host)
if use_json is False:
data = OmnikInverterWeb(host)
else:
data = OmnikInverterJson(host)
except RuntimeError:
_LOGGER.error("Unable to fetch data from Omnik Inverter %s", host)
return False
Expand All @@ -75,10 +85,12 @@ def __init__(self, host):

@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Update the data from the omnik inverter."""
dataurl = BASE_URL.format(self._host)
"""Update the data from the Omnik Inverter."""
dataurl = JS_URL.format(self._host)
try:
r = urlopen(dataurl).read()
fp = urlopen(dataurl)
r = fp.read()
fp.close()
except OSError:
_LOGGER.error("Unable to fetch data from Omnik Inverter %s", self._host)
return False
Expand All @@ -94,7 +106,45 @@ def update(self):

# Split the values
if matches is not None:
self.result = matches.group(0).split(',')
data = matches.group(0).split(',')
self.result = [
int(data[5]),
int(data[6]),
int(data[7])
]
else:
_LOGGER.error("Empty data from Omnik Inverter %s", self._host)

_LOGGER.debug("Data = %s", self.result)


class OmnikInverterJson(object):
"""Representation of the Omnik Inverter Json."""

def __init__(self, host):
"""Initialize the inverter."""
self._host = host
self.result = None

@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Update the data from the Omnik Inverter."""
dataurl = JSON_URL.format(self._host, random())
try:
fp = urlopen(dataurl)
data = json.load(fp)
fp.close()
except (OSError, JSONDecodeError):
_LOGGER.error("Unable to fetch data from Omnik Inverter %s", self._host)
return False

# Split the values
if data is not None:
self.result = [
int(data["i_pow_n"]),
int(float(data["i_eday"]) * 100),
int(float(data["i_eall"]) * 10)
]
else:
_LOGGER.error("Empty data from Omnik Inverter %s", self._host)

Expand Down Expand Up @@ -148,15 +198,19 @@ def update(self):
# Get the result data
result = self.data.result

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

if self.type == 'powercurrent':
# Update the sensor state
self._state = int(result[5])
self._state = result[0]
elif self.type == 'powertoday':
# Define the cache name
cacheName = BASE_CACHE_NAME.format(self.type)
cacheName = CACHE_NAME.format(self.type)

# Prepare the current actual values
currentValue = int(result[6])
currentValue = result[1]
currentDay = int(datetime.now().strftime('%Y%m%d'))

# Check if caching is enabled
Expand Down Expand Up @@ -205,4 +259,4 @@ def update(self):
self._state = (currentValue / 100)
elif self.type == 'powertotal':
# Update the sensor state, divide by 10 to make it kWh
self._state = (int(result[7]) / 10)
self._state = (result[2] / 10)
4 changes: 2 additions & 2 deletions hacs.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "Omnik Inverter",
"name": "Omnik Inverter Solar Sensor (No Cloud)",
"country": "NL",
"domains": ["sensor"],
"homeassistant": "0.109.0"
}
}
19 changes: 14 additions & 5 deletions info.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
# Omnik Inverter Sensor Component for Home Assistant.
## Omnik Inverter Sensor Component for Home Assistant.

The Omnik solar sensor component will retrieve data from an Omnik solar inverter.
The values will be presented as sensors (or attributes of sensors) in Home Assistant.

## Example
## Configuration

``` YAML
sensor:
- platform: omnik_inverter
host: 192.168.100.100
```
### Entities
Entities:
- `sensor.solar_power_current` (Watt)
- `sensor.solar_power_today` (kWh)
- `sensor.solar_power_total` (kWh)

### Example

![Omnik Inverter Sensor Entities](https://github.com/robbinjanssen/home-assistant-omnik-inverter/blob/master/images/entities.png)

## Documentation
### Documentation

Find the full documentation [here](https://github.com/robbinjanssen/home-assistant-omnik-inverter/blob/master/README.md).
Find the full documentation [here](https://github.com/robbinjanssen/home-assistant-omnik-inverter).

0 comments on commit 64c9241

Please sign in to comment.