Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DSMR sensor #4309

Merged
merged 22 commits into from
Nov 23, 2016
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 153 additions & 0 deletions homeassistant/components/sensor/dsmr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
"""
Support for Dutch Smart Meter Requirements.

Also known as: Smartmeter or P1 port.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.dsmr/
"""

import asyncio
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_DEVICE
from homeassistant.helpers.entity import Entity

DOMAIN = 'dsmr'

REQUIREMENTS = ['dsmr-parser==0.2']

CONF_DSMR_VERSION = 'dsmr_version'
DEFAULT_DEVICE = '/dev/ttyUSB0'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't recommend to do that because this will most likely not work on macOS and Windows.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Mac it uses a tty device name with a random number I believe, will verify that, for windows it would default to COM0 I guess? So for Mac/Windows you would have to set the device but for Linux it would work without config if its the only device. There should be no harm in keeping a default in that case I think.

On this topic, I have been pondering about a auto discovery implementation for serial devices. It is out of scope for this PR but I think it could be doable. I want to implement it for my own setup as I have some other devices that get assigned a device name in random order at boot.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue with that default is that it would be hard to debug for a no-Linux user.

DEFAULT_DSMR_VERSION = '4'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_DEVICE, default=DEFAULT_DEVICE): cv.string,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For serial ports we use port: for the configuration.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this kind of stuff documented somewhere? Because I took the zigbee module as an example which uses 'device' so my guess was that was the convention https://github.com/home-assistant/home-assistant/blob/ece58ce78fe44b521122e3f41b79e670010bc905/homeassistant/components/zigbee.py#L30

and port seems to be generally used only in tcp/udp context.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it's not documented. I'm trying to establish a common base for the configuration and not use usb_path, filename, and others. It's a connection over a serial port. Even better than port would serial_port be, distinguish between the network port and the physical port.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason it is not outlined in a document yet?

In my opinion if you want to work toward a convention for (for example) naming you outline it first in a document, this should make it easy for (new) contributors to learn about what the conventions are. Now I had to learn this convention through a pullrequest review, as the only other information I could go on is other components.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I rename the config to port, let me know if you want me to take initiative on documenting the conventions.

vol.Optional(CONF_DSMR_VERSION, default=DEFAULT_DSMR_VERSION): vol.All(
cv.string, vol.In(['4', '2.2'])),
})

_LOGGER = logging.getLogger(__name__)


@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup DSMR sensors."""
from dsmr_parser.obis_references import (
CURRENT_ELECTRICITY_USAGE,
CURRENT_ELECTRICITY_DELIVERY,
ELECTRICITY_ACTIVE_TARIFF
)

devices = []

dsmr = DSMR(hass, config, devices)

devices += [
DSMREntity('Power Usage', CURRENT_ELECTRICITY_USAGE, dsmr),
DSMREntity('Power Production', CURRENT_ELECTRICITY_DELIVERY, dsmr),
DSMRTariff('Power Tariff', ELECTRICITY_ACTIVE_TARIFF, dsmr),
]
yield from async_add_devices(devices, True)
yield from dsmr.async_update()


class DSMR:
"""DSMR interface."""

def __init__(self, hass, config, devices):
"""Setup DSMR serial interface and add device entities."""
from dsmr_parser.serial import (
SERIAL_SETTINGS_V4,
SERIAL_SETTINGS_V2_2,
SerialReader
)
from dsmr_parser import telegram_specifications

dsmr_versions = {
'4': (SERIAL_SETTINGS_V4, telegram_specifications.V4),
'2.2': (SERIAL_SETTINGS_V2_2, telegram_specifications.V2_2),
}

device = config[CONF_DEVICE]
dsmr_version = config[CONF_DSMR_VERSION]

self.dsmr_parser = SerialReader(
device=device,
serial_settings=dsmr_versions[dsmr_version][0],
telegram_specification=dsmr_versions[dsmr_version][1],
)

self.hass = hass
self.devices = devices
self._telegram = {}

@asyncio.coroutine
def async_update(self):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I can tell, this isn't making use of any asyncio functionality - this probably shouldn't be async as the update func should be run in an executor by the core.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm quiet new to the whole asyncio stuff in python3 but I thought this was the new way to go with components according to (https://home-assistant.io/developers/asyncio/) and since the current library (dsmr-parser) is implemented blocking I figured I might implement it non-blocking using asyncio (see todo).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@aequitas if you're planning on making dsmr-parser then your current implementation will be appropriate.

"""Wait for DSMR telegram to be received and parsed."""
_LOGGER.info('retrieving new telegram')

self._telegram = self.read_telegram()

_LOGGER.info('got new telegram')

yield from asyncio.sleep(10, loop=self.hass.loop)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's this sleep for?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should have documented this, but this is a temporary poor-mans semi-non-blocking implementation: the smartmeter sends 'telegrams' every 10 seconds. So the update only has to check every 10 seconds after the first telegram is received. This will be removed if non-blocking is implemented.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@aequitas you'll be better off using @Throttle in that case 👍

tasks = []
for device in self.devices:
tasks.append(device.async_update_ha_state())

yield from asyncio.gather(*tasks, loop=self.hass.loop)

def read_telegram(self):
"""Read telegram."""
return next(self.dsmr_parser.read())

@property
def telegram(self):
"""Return latest received telegram."""
return self._telegram


class DSMREntity(Entity):
"""Entity reading values from DSMR telegram."""

def __init__(self, name, obis, interface):
""""Initialize entity."""
self._name = name
self._obis = obis
self._interface = interface

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

@property
def state(self):
"""Return the state of the sensor."""
return getattr(self._interface.telegram.get(self._obis, {}),
'value', None)

@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return getattr(self._interface.telegram.get(self._obis, {}),
'unit', None)


class DSMRTariff(DSMREntity):
"""Convert integer tariff value to text."""

@property
def state(self):
"""Convert 2/1 to high/low."""
tariff = super().state
if tariff == '0002':
return 'high'
elif tariff == '0001':
return 'low'
else:
return None
3 changes: 3 additions & 0 deletions requirements_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ dnspython3==1.15.0
# homeassistant.components.sensor.dovado
dovado==0.1.15

# homeassistant.components.sensor.dsmr
dsmr-parser==0.2

# homeassistant.components.dweet
# homeassistant.components.sensor.dweet
dweepy==0.2.0
Expand Down
43 changes: 43 additions & 0 deletions tests/components/sensor/test_dsmr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Test for DSMR components."""

import asyncio
from decimal import Decimal
from unittest.mock import patch

from homeassistant.bootstrap import async_setup_component
from tests.common import assert_setup_component


@asyncio.coroutine
def test_default_setup(hass):
"""Test the default setup."""
from dsmr_parser.obis_references import (
CURRENT_ELECTRICITY_USAGE,
ELECTRICITY_ACTIVE_TARIFF,
)
from dsmr_parser.objects import CosemObject

config = {'platform': 'dsmr'}

telegram = {
CURRENT_ELECTRICITY_USAGE: CosemObject([
{'value': Decimal('0.1'), 'unit': 'kWh'}
]),
ELECTRICITY_ACTIVE_TARIFF: CosemObject([
{'value': '0001', 'unit': ''}
]),
}

with patch('homeassistant.components.sensor.dsmr.DSMR.read_telegram',
return_value=telegram), assert_setup_component(1):
yield from async_setup_component(hass, 'sensor', {'sensor': config})

state = hass.states.get('sensor.power_usage')

assert state.state == '0.1'
assert state.attributes.get('unit_of_measurement') is 'kWh'

state = hass.states.get('sensor.power_tariff')

assert state.state == 'low'
assert state.attributes.get('unit_of_measurement') is None