Skip to content
This repository has been archived by the owner on Jun 27, 2022. It is now read-only.

Commit

Permalink
Add sensor for countries
Browse files Browse the repository at this point in the history
  • Loading branch information
LiJu09 committed May 4, 2021
1 parent d9f8746 commit 2273655
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 12 deletions.
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Analytics Stats


#### Still in development
#### Maybe in development

Sensor for data from Home Assistant Analytics

Expand All @@ -22,8 +22,15 @@ Sensor for data from Home Assistant Analytics
- Add configuration to `configuration.yaml`
- Restart Home Assistant

##### Configuration:
### Options
| Option | Description | Required | Example |
--- | --- | --- | ---
| countries | String of [country codes](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) separated by space | no | `"SK CZ"` |


#### Example configuration:
```yaml
sensor:
- platform: analytics_stats
countries: "SK CZ"
```
2 changes: 1 addition & 1 deletion custom_components/analytics_stats/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"domain": "analytics_stats",
"name": "Analytics Stats",
"version": "0.1.3",
"version": "0.2.0",
"documentation": "https://github.com/LiJu09/analytics-stats",
"requirements": [],
"dependencies": [],
Expand Down
57 changes: 48 additions & 9 deletions custom_components/analytics_stats/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,29 @@
import logging

import requests
#import voluptuous as vol
import voluptuous as vol

#from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.components.sensor import SensorEntity
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.exceptions import PlatformNotReady
#import homeassistant.helpers.config_validation as cv
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
#from homeassistant.util.dt import utcnow

_LOGGER = logging.getLogger(__name__)

MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
SCAN_INTERVAL = timedelta(seconds=600)
RETRY_INTERVAL = timedelta(seconds=30)

CONF_COUNTRY = 'countries'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_COUNTRY): cv.string,
})

def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Analytics Stats platform."""
data = AnalyticsStatsData(config, hass)
countries = config.get(CONF_COUNTRY)
data = AnalyticsStatsData(config, hass, countries)
if data.data is None:
raise PlatformNotReady
add_entities(data.devices, True)
Expand Down Expand Up @@ -58,9 +62,8 @@ def state(self):
def update(self):
"""Update the sensor from a new JSON object."""
self._data.update()
latest = self._data.data["current"]
_LOGGER.debug("🆙 Updating %s", self._name)
self.value = round(latest[self.path], self.decimal)
self.value = round(self._data.data["current"][self.path], self.decimal)


class AnalyticsStatsInstallTypesSensor(SensorEntity):
Expand Down Expand Up @@ -110,16 +113,48 @@ def update(self):
for key in key_list:
self.install_types_attr.update({key: latest["installation_types"][key]})

class AnalyticsStatsCountrySensor(SensorEntity):
"""Sensor used to display information from Home Asistant Analytics."""

def __init__(self, data, name, icon, path):
"""Initialize an AnalyticsStatsSensor sensor."""
self._data = data
self._name = name
self._icon = icon
self.path = path
self.value = None

@property
def name(self):
"""Return the name of the sensor."""
return self._name

@property
def icon(self):
"""Return the mdi icon of the sensor."""
return self._icon

@property
def state(self):
"""Return the state of the sensor."""
return self.value

def update(self):
"""Update the sensor from a new JSON object."""
self._data.update()
_LOGGER.debug("🆙 Updating %s", self._name)
self.value = self._data.data["current"]["countries"][self.path]

class AnalyticsStatsData:
"""Class used to pull data from API and create sensors."""

def __init__(self, config, hass):
def __init__(self, config, hass, countries):
"""Initialize the Analytics Stats data-handler."""
self.data = None
self._config = config
self._hass = hass
self.devices = []
self.countries = countries
self.initialize()

@Throttle(MIN_TIME_BETWEEN_UPDATES)
Expand Down Expand Up @@ -157,3 +192,7 @@ def initialize(self):
AnalyticsStatsSensor(self, "Average Automations", "mdi:robot", "avg_automations", 2),
AnalyticsStatsSensor(self, "Average Users", "mdi:account-multiple", "avg_users", 2),
]

if self.countries is not None:
for country in self.countries.split(" "):
self.devices += [AnalyticsStatsCountrySensor(self, country + " Installations", "mdi:home-group", country),]

0 comments on commit 2273655

Please sign in to comment.