Integration with Home Assistant - Custom binary sensor component

Continuing the discussion from Integration for Home Automation:

I went ahead and built out my example of using Sense’s on/off detection to generate a voice announcement via Home Assistant. I wrote a simple custom component for Home Assistant (leveraging this Pyhton project), and it works!

For those who are familiar with Home Assistant, here’s the required config excerpt:

binary_sensor:
  - platform: sense
    email: !secret email
    password: !secret sense_password

This will generate a binary (on/off) sensor for each device in your device list (i.e. merged devices are a single sensor). You can then use the state transitions of these binary sensors to trigger automations, including calling a text-to-speech (TTS) service with whatever message you would like.

For those who are interested, here’s the code for the custom component:

"""
Support for the Sense power monitor.

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

import datetime
import logging

import requests
import voluptuous as vol
from sense_energy import Senseable

from homeassistant.components.binary_sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_NAME, CONF_EMAIL, CONF_PASSWORD,
                                STATE_ON, STATE_OFF)
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv

REQUIREMENTS = ['sense_energy==0.3.1']

_LOGGER = logging.getLogger(__name__)

MIN_TIME_BETWEEN_UPDATES = datetime.timedelta(seconds=60)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_NAME): cv.string,
    vol.Required(CONF_EMAIL): cv.string,
    vol.Required(CONF_PASSWORD): cv.string
})


def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up Sense device binary sensors."""
    sense_object = Senseable(config.get(CONF_EMAIL),
                             config.get(CONF_PASSWORD))    
    sense_object.get_realtime()
    device_details = sense_object.get_discovered_device_data()

    device_list = []
    for d in device_details:
        if d['tags']['DeviceListAllowed'] == 'true':
            device_list.append(d['name'])

    add_devices([SenseBinarySensor(sense_object, d)
                 for d in device_list])


class SenseBinarySensor(Entity):
    """Implementation of a Sense binary sensor."""
    
    def __init__(self, sense_object, device_name):
        """Initialize the sensor."""
        self.device_name = device_name
        self.sense_object = sense_object
        
    @property
    def name(self):
        """Return the name of the sensor."""
        return self.device_name
        
    @property
    def state(self):
        """Return the state of the sensor."""
        if self.device_name in self.sense_object.active_devices:
            return STATE_ON
        else:
            return STATE_OFF

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Update sensor data."""
        self.sense_object.get_realtime()

I’ll submit a pull request to have this merged into Home Assistant as a core component, but in the meantime please let me know if you find it useful.

4 Likes

All my IoT devices support IFTTT. Is there any advantages to using Home Assistant for basic on/off sensing instead of IFTTT?

1 Like

I haven’t used IFTTT a lot, but when I used it with my garage door I experienced a lot of lag. I also found it to be kind of a black box, which I didn’t like. There’s a lot more flexibility in Home Assistant beyond what IFTTT typically provides (e.g. there’s a Bayesian sensor for when you want to do if-this-then-maybe-that).

I’ve recently switched to Home Assistant from OpenHAB, and I’m really impressed with the platform. Not only are there more than 1,000 integrations available, it’s also pretty simple for someone with a basic understanding of Python to add their own as well.

I’m pretty into Home Assistant stuff right now, so feel free to fire away with any questions.

2 Likes

Awesome, I’ll use this the moment it gets merged.

2 Likes

This doesn’t seem to be merged yet, I assume you’re not running HASS.io? If you are, how are you successfully running a custom(ized) component?

I never bothered to merge mine in, but @enbickar recently added this functionality in. It looks like it’s been merged into 0.82: https://github.com/home-assistant/home-assistant/pull/17645. The updated documentation isn’t up yet, but it’s at Updated to include new devices configuration by kbickar · Pull Request #6983 · home-assistant/home-assistant.io · GitHub.

You’re correct, I don’t use HASS.io, so I just loaded up the custom component in my Docker installation.