From 4fd2f773ad0f8fb8eca22cd1f8ccf3bf3d8a6cf0 Mon Sep 17 00:00:00 2001
From: Baptiste Lecocq <baptiste.lecocq@gmail.com>
Date: Mon, 24 Sep 2018 08:09:34 +0200
Subject: [PATCH] Add linky sensor (#16468)

* Add linky component

* Update requirements_all.txt

* Add timeout to pylinky requests

* Make linky platform fail fast
---
 .coveragerc                              |  1 +
 homeassistant/components/sensor/linky.py | 91 ++++++++++++++++++++++++
 requirements_all.txt                     |  3 +
 3 files changed, 95 insertions(+)
 create mode 100644 homeassistant/components/sensor/linky.py

diff --git a/.coveragerc b/.coveragerc
index 79afac5709f..a8d7d89544d 100644
--- a/.coveragerc
+++ b/.coveragerc
@@ -695,6 +695,7 @@ omit =
     homeassistant/components/sensor/kwb.py
     homeassistant/components/sensor/lacrosse.py
     homeassistant/components/sensor/lastfm.py
+    homeassistant/components/sensor/linky.py
     homeassistant/components/sensor/linux_battery.py
     homeassistant/components/sensor/loopenergy.py
     homeassistant/components/sensor/luftdaten.py
diff --git a/homeassistant/components/sensor/linky.py b/homeassistant/components/sensor/linky.py
new file mode 100644
index 00000000000..83a6d793085
--- /dev/null
+++ b/homeassistant/components/sensor/linky.py
@@ -0,0 +1,91 @@
+"""
+Support for Linky.
+
+For more details about this component, please refer to the documentation at
+https://home-assistant.io/components/sensor.linky/
+"""
+import logging
+import json
+from datetime import timedelta
+
+import voluptuous as vol
+
+from homeassistant.const import CONF_USERNAME, CONF_PASSWORD, CONF_TIMEOUT
+from homeassistant.components.sensor import PLATFORM_SCHEMA
+from homeassistant.helpers.entity import Entity
+from homeassistant.util import Throttle
+import homeassistant.helpers.config_validation as cv
+
+REQUIREMENTS = ['pylinky==0.1.6']
+_LOGGER = logging.getLogger(__name__)
+
+SCAN_INTERVAL = timedelta(minutes=10)
+DEFAULT_TIMEOUT = 10
+
+PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
+    vol.Required(CONF_USERNAME): cv.string,
+    vol.Required(CONF_PASSWORD): cv.string,
+    vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
+})
+
+
+def setup_platform(hass, config, add_entities, discovery_info=None):
+    """Configure the platform and add the Linky sensor."""
+    username = config[CONF_USERNAME]
+    password = config[CONF_PASSWORD]
+    timeout = config[CONF_TIMEOUT]
+
+    from pylinky.client import LinkyClient, PyLinkyError
+    client = LinkyClient(username, password, None, timeout)
+
+    try:
+        client.fetch_data()
+    except PyLinkyError as exp:
+        _LOGGER.error(exp)
+        return
+
+    devices = [LinkySensor('Linky', client)]
+    add_entities(devices, True)
+
+
+class LinkySensor(Entity):
+    """Representation of a sensor entity for Linky."""
+
+    def __init__(self, name, client):
+        """Initialize the sensor."""
+        self._name = name
+        self._client = client
+        self._state = None
+
+    @property
+    def name(self):
+        """Return the name of the sensor."""
+        return self._name
+
+    @property
+    def state(self):
+        """Return the state of the sensor."""
+        return self._state
+
+    @property
+    def unit_of_measurement(self):
+        """Return the unit of measurement."""
+        return 'kWh'
+
+    @Throttle(SCAN_INTERVAL)
+    def update(self):
+        """Fetch new state data for the sensor."""
+        from pylinky.client import PyLinkyError
+        try:
+            self._client.fetch_data()
+        except PyLinkyError as exp:
+            _LOGGER.error(exp)
+            return
+
+        _LOGGER.debug(json.dumps(self._client.get_data(), indent=2))
+
+        if self._client.get_data():
+            # get the last past day data
+            self._state = self._client.get_data()['daily'][-2]['conso']
+        else:
+            self._state = None
diff --git a/requirements_all.txt b/requirements_all.txt
index 8e29b7eb74b..d901a787493 100644
--- a/requirements_all.txt
+++ b/requirements_all.txt
@@ -950,6 +950,9 @@ pylgnetcast-homeassistant==0.2.0.dev0
 # homeassistant.components.notify.webostv
 pylgtv==0.1.7
 
+# homeassistant.components.sensor.linky
+pylinky==0.1.6
+
 # homeassistant.components.litejet
 pylitejet==0.1
 
-- 
GitLab