Broadlink SP3S Power consumption sensor

It needs to be like this:

switch:
  - platform: broadlink
    friendly_name: "lampo"
    mac: '34:EA:34:XX:XX:XX'
    type:  sp3
    host:  192.168.137.101
# Sensors
sensor:

 - platform: template
    sensors:
      rig_pow:
       friendly_name: "RIG POW"
       value_template: "{{ states.switch.lampo.current_power_w }}"
       unit_of_measurement: 'W' 

Hi all

I’m just trying to get my SP3S working also with power consumption.

Switch is ok

I’ve copied this as broadlink_power.py

"""
Support for the Broadlink SP2 and SP3s power measurement sensor.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.broadlinkpower/
"""
from datetime import timedelta
import binascii
import logging
import socket

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    CONF_HOST, CONF_MAC, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_TIMEOUT)
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv

REQUIREMENTS = ['broadlink==0.6']

_LOGGER = logging.getLogger(__name__)

CONF_UPDATE_INTERVAL = 'update_interval'
DEVICE_DEFAULT_NAME = 'Broadlink power sensor'
DEFAULT_TIMEOUT = 10

SENSOR_TYPES = {
    'energy': ['Energy', 'W']
}

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_NAME, default=DEVICE_DEFAULT_NAME): vol.Coerce(str),
    vol.Optional(CONF_MONITORED_CONDITIONS, default=[]):
        vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
    vol.Optional(CONF_UPDATE_INTERVAL, default=timedelta(seconds=300)): (
        vol.All(cv.time_period, cv.positive_timedelta)),
    vol.Required(CONF_HOST): cv.string,
    vol.Required(CONF_MAC): cv.string,
    vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int
})


# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Broadlink device sensors."""
    host = config.get(CONF_HOST)
    mac = config.get(CONF_MAC).encode().replace(b':', b'')
    mac_addr = binascii.unhexlify(mac)
    name = config.get(CONF_NAME)
    timeout = config.get(CONF_TIMEOUT)
    update_interval = config.get(CONF_UPDATE_INTERVAL)

    broadlink_data = BroadlinkData(update_interval, host, mac_addr, timeout)

    dev = []
    for variable in config[CONF_MONITORED_CONDITIONS]:
        dev.append(BroadlinkSensor(name, broadlink_data, variable))
    add_devices(dev, True)


class BroadlinkSensor(Entity):
    """Representation of a Broadlink device sensor."""

    def __init__(self, name, broadlink_data, sensor_type):
        """Initialize the sensor."""
        self._name = '{} {}'.format(name, SENSOR_TYPES[sensor_type][0])
        self._state = None
        self._type = sensor_type
        self._broadlink_data = broadlink_data
        self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]

    @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 this state is expressed in."""
        return self._unit_of_measurement

    def update(self):
        """Get the latest data from the sensor."""
        self._broadlink_data.update()
        if self._broadlink_data.data is None:
            return
        self._state = self._broadlink_data.data[self._type]


class BroadlinkData(object):
    """Representation of a Broadlink data object."""

    def __init__(self, interval, ip_addr, mac_addr, timeout):
        """Initialize the data object."""
        import broadlink
        self.data = None
        self._device = broadlink.sp2((ip_addr, 80), mac_addr)
        self._device.timeout = timeout
        self._schema = vol.Schema({
            vol.Optional('energy'): vol.Range(min=-0, max=3600)
            })
        self.update = Throttle(interval)(self._update)
        if not self._auth():
            _LOGGER.warning("Failed to connect to device")

    def _update(self, retry=3):
        try:
            data = self._device.get_energy_raw_p3()
            if data is not None:
                self.data = self._schema(data)
                return
        except socket.timeout as error:
            if retry < 1:
                _LOGGER.error(error)
                return
        except vol.Invalid:
            pass  # Continue quietly if device returned malformed data
        if retry > 0 and self._auth():
            self._update(retry-1)

    def _auth(self, retry=3):
        try:
            auth = self._device.auth()
        except socket.timeout:
            auth = False
        if not auth and retry > 0:
            return self._auth(retry-1)
        return auth

I’m on Hassio and I saw people saying that a file called __init__.py have to be copied somewhere. Where in Hassio?

My switches and sensor config are

  - platform: broadlink
    friendly_name: "lampo"
    mac: 'xx:xx:xx:xx:xx'
    type:  sp3
    host:  192.168.xx.xx

  - platform: template
    sensors:
      rig_pow:
       friendly_name: "Broadlink Power"
       value_template: "{{ states.switch.lampo.current_power_w }}"
       unit_of_measurement: 'W'

What can I check more?

Thanks

With this config you don’t need to copy any files because it’s native homeassistant component.

`

switch:
  - platform: broadlink
    friendly_name: "lampo"
    mac: 'xx:xx:xx:xx:xx'
    type:  sp3
    host:  192.168.xx.xx
sensor:
  - platform: template
     sensors:
       rig_pow:
        friendly_name: "Broadlink Power"
        value_template: "{{ states.switch.lampo.current_power_w }}"
        unit_of_measurement: 'W'

`

@n1k5y thanks

Just tried to remove the .py file from custom_components and restarted HA and now I can see the sensor.rig_pow but has no value, even if now my plug is on and consuming power.

10

Any suggestion?

Thanks!

When you press on switch can you printscreen that?

Like this:
image

Thanks @n1k5y !!!

if I look at the switch I can see the power value

55

Is it correct that is I have the sensor in a screen value is not shown?

48

Is there a way to show it?

What do you have in dev states?

52

This is what I have in dev states… :thinking:

Sorry, it’s my mistake I accidently remove something :frowning:
Sensor need to be like this.

`

sensor:
  - platform: template
     sensors:
       rig_pow:
        friendly_name: "Broadlink Power"
        value_template: "{{ states.switch.lampo.attributes.current_power_w }}"
        unit_of_measurement: 'W'

`

Thanks!!!

It’s working perfectly…

I’ve had success using the Broadlink platform with the Ankuoo Wall Switch & Neo Plug in the past. Just got a Neo Pro plug and was hoping to see the power consumption, I can control the switch from HA to change the on/off state but not seeing the power consumption. Does anyone know if this feature works on the Neo Pro plug?

hi i have a few problem with Sp3s

first problem:

switch is off but graph don’t show correctly

Untitled

secend problem:
Trigger don’t work.

  • alias: oven turned off
    trigger:
    • below: ā€˜1’
      entity_id: sensor.oven
      platform: numeric_state
      action:
    • data:
      entity_id: script.stuff
      service: homeassistant.turn_off
    • data:
      entity_id: script.stuff_loop
      service: homeassistant.turn_off
    • service: script.hassio_talk
      data:
      message: ā€œoven is off!ā€

do you have any idea ?

Problem with off power consumption I fixed with nodeRED. I don’t use YAML automation so I can give you just my nodeRED solution. I then just use it as mqtt sensor. Here is my nodeRED sequence.

[{"id":"500cf087.27b6","type":"change","z":"f0d0173f.b4a34","name":"GET current_power_w","rules":[{"t":"move","p":"data.attributes.current_power_w","pt":"msg","to":"payload","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":690,"y":391,"wires":[["8bbc8a5d.9e771"]]},{"id":"8bbc8a5d.9e771","type":"mqtt out","z":"f0d0173f.b4a34","name":"","topic":"rig/powc","qos":"0","retain":"","broker":"6ff515af.ecdbcc","x":879,"y":356,"wires":[]},{"id":"1f06139.494efec","type":"poll-state","z":"f0d0173f.b4a34","name":"","server":"3c4e982f.072f98","updateinterval":"15","outputinitially":true,"outputonchanged":true,"entity_id":"switch.broadlink_switch","state_type":"str","halt_if":"","halt_if_type":"","halt_if_compare":"is","outputs":1,"x":232,"y":374,"wires":[["42872c2c.39a484"]]},{"id":"42872c2c.39a484","type":"switch","z":"f0d0173f.b4a34","name":"","property":"payload","propertyType":"msg","rules":[{"t":"eq","v":"off","vt":"str"},{"t":"else"}],"checkall":"false","repair":false,"outputs":2,"x":480,"y":373,"wires":[["241c8cef.b3c0e4"],["500cf087.27b6"]]},{"id":"241c8cef.b3c0e4","type":"change","z":"f0d0173f.b4a34","name":"TO 0","rules":[{"t":"set","p":"payload","pt":"msg","to":"0","tot":"num"}],"action":"","property":"","from":"","to":"","reg":false,"x":640,"y":357,"wires":[["8bbc8a5d.9e771"]]},{"id":"6ff515af.ecdbcc","type":"mqtt-broker","z":"","name":"00","broker":"","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"3c4e982f.072f98","type":"server","z":"","name":"Home Assistant1111","legacy":true}]

Hi guys,

I don’t know what I’m doing wrong. If I understood correctly, you say that home assistant now supports this without custom component?
I just had a fresh install of HA ver 0.86.2. It runs on RPI 3, Hassbian. Broadlink switch is SP3s contros.
In config I put:

switch:
  - platform: broadlink
    timeout: 30
    host: !secret sp3switch_ip
    mac: !secret sp3switch_mac
    friendly_name: "SP3 switch"
    type: sp3

sensor:
  - platform: template
    sensors:
      rig_pow:
        friendly_name: "Broadlink Power"
        value_template: "{{ states.switch.sp3_switch.attributes.current_power_w }}"
        unit_of_measurement: 'W' 

Switch works fine, however sensor shows nothing. Looking at atributes of SP3 entity, it shows no atribute current_power_w.

Am I missing something here?

Thanks

What do you have in dev states? Can you ss? Like this:

Only friendly_name.
image
I’m thinking maybe an issue with switch firmware. When i list it in E-control app it shows v10006.
Could you check your firmware version?

It also show v10006 for me

friendly_name: "sp3_switch"

Hi Vahid,

I think this shouldn’t matter as in dev states is identified as switch.sp3_switch. I wasn’t lazy, so I tried it, but switch still shows no attribute current_power_w.
Anyhow, after several restarts of HA, due to setup of other components, it suddenly started reporting the consumption in the sensor card (lovelace). Line graph shows peak when there is a consumption, and sensor reads the current consumption correctly. However when I click the more info card, reporting is incorrect. It shows the constant consumption, even if the switch is off. (For example it was on at 5.10 AM for 10 min).

image

Also, I’ve been experiencing random false state reading. Switch reports ā€˜on’ state in the front-end, while it is actually off. Haven’t been able to figure out what is causing it. When it loses sync it can go for hours, reporting wrong state and no consumption. HA restart or automation restores the sync.

I have that problem too. sometimes it didn’t show correct consumption. @n1k5y suggest me to use red_node… I am trying to run rednode but it was not successful yet…