Deprecated: Function jetpack_form_register_pattern is deprecated since version jetpack-13.4! Use Automattic\Jetpack\Forms\ContactForm\Util::register_pattern instead. in /var/www/html/wp-includes/functions.php on line 6078 Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-includes/functions.php:6078) in /var/www/html/wp-includes/feed-rss2.php on line 8 Home Assistant – D Khaz https://khaz.me Things that I spend my time on... Sun, 24 Mar 2024 19:36:48 +0000 en-US hourly 1 https://khaz.me/wp-content/uploads/2018/05/DK_logo_square___100x100.png Home Assistant – D Khaz https://khaz.me 32 32 147286311 Home Assistant Template Sensor for PGE EV2-A Rate Plan https://khaz.me/home-assistant-template-sensor-for-pge-ev2-a-rate-plan/ Sun, 24 Mar 2024 19:36:46 +0000 https://khaz.me/?p=632 I wanted to implement a sensor to tell me what the current price per kW is for any time of day.

My rate plan is Home Charging EV2-A and needs to account for the season and several hour-of-day checks to select the correct price. So here is the template sensor I’ve created:

sensor:
- platform: template
  sensors:
    pge_ev2a_energy_rate: # UPDATED MARCH 2024
      friendly_name: PGE EV2-A Energy Rate
      unit_of_measurement: '$/kWh'
      value_template: >
        {% set rate = { "winterPeak": 0.53117, "winterPartialPeak": 0.51447, "winterOffPeak": 0.34578, "summerPeak": 0.65828, "summerPartialPeak": 0.54779, "summerOffPeak": 0.34578 } %}
        {% set time = { "month": (now().strftime('%m') | int), "hour": (now().strftime('%H') | int) } %}
        {%if ((time.month >= 10) or (time.month < 6)) %}
          {%if (time.hour >= 15) and (time.hour < 16) %}
            {{ rate.winterPartialPeak }}
          {%elif (time.hour >= 16) and (time.hour < 21) %}
            {{ rate.winterPeak }}
          {%elif (time.hour >= 21) and (time.hour < 24) %}
            {{ rate.winterPartialPeak }}
          {%else%}
            {{ rate.winterOffPeak }}
          {%endif%}
        {%else%}
          {%if (time.hour >= 15) and (time.hour < 16) %}
            {{ rate.summerPartialPeak }}
          {%elif (time.hour >= 16) and (time.hour < 21) %}
            {{ rate.summerPeak }}
          {%elif (time.hour >= 21) and (time.hour < 24) %}
            {{ rate.summerPartialPeak }}
          {%else%}
            {{ rate.summerOffPeak }}
          {%endif%}
        {%endif%}

Credit to this post for the bones of the sensor logic.

]]>
632
Home Theater: Automating my subwoofer with Home Assistant and Node-RED https://khaz.me/home-theater-automating-my-subwoofer-with-home-assistant-and-node-red/ Sat, 11 Jan 2020 20:14:13 +0000 https://khaz.me/?p=283 A while back, we decided to rearrange our living room, get new furniture, etc.  I took this opportunity to expand my home automation addiction and pull more items into Home Assistant.  My plan included running wiring through the ceiling for power and audio, automating my projector, screen, and subwoofer.   This how-to will outline how I’m controlling the power of my remotely mounted subwoofer all from a one-word activation with my Google Home, but more on that in another post. This is the first of multiple posts for automating my home theater experience.

Hardware

While my subwoofer’s power switch has an auto setting that is only supposed to turn on the amp when it’s getting signal from the receiver, this never really worked.  And as we rearranged the room, it’s new location did not allow it to be wired into the receiver’s builtin switched receptacle.  Thus, I needed a way to remotely control the sub being on or off.

Original Subwoofer

The Sonoff Basic is perfect for this job as you are switching 120v for the subwoofer’s power.  It does not matter which version of the Sonoff Basic you use (Original, R2, or R3) as they will perform the same here.  I have a half dozen R2s that came as part of a bulk order, so that’s what I used. Splicing the Sonoff into the subwoofer’s power cable was very straight forward.  All you have to do is cut the cable and insert the Sonoff in the middle, with the plug side of the cable wired to the input side of the Sonoff and the subwoofer side to the output side.

My installation of subwoofer with Sonoff spliced into the power cable

I chose to take a step further by disassembling my subwoofer and installing the Sonoff inside of the subwoofer.  This means it’s spliced on the power cable after the cable enters the subwoofer.  I used a couple of strong zip ties to mount the Sonoff, in its enclosure, to one of the sub’s metal components.

Sonoff mounted to the subwoofer amplifier

Firmware

The overall process is to flash this unit with custom firmware that tightly integrated to Home Assistant.  To get the unit converted from the original firmware, I used a USB FTDI converter combined with ESPHome to get this accomplished.  If you are not familiar with this process, JuanMTech and many others have great detailed steps for this part. Head over to your ESPHome dashboard and create a new device.  Paste the YAML below into the device configuration:

substitutions:
  platform: ESP8266
  board: esp01_1m
  device_name: esphome_subwoofer
  friendly_name: "Subwoofer"
  reboot_timeout_wifi: 900s
  reboot_timeout_api: 1800s
  output_power: 17dB

# <<: !include z_common.yaml

esphome:
  platform: ${platform}
  board: ${board}
  name: ${device_name}
  esp8266_restore_from_flash: true

wifi:
  ssid: !secret wifi_iot_ssid
  password: !secret wifi_iot_pwd
  fast_connect: on
  reboot_timeout: ${reboot_timeout_wifi}
  output_power: ${output_power}
  ap:
    ssid: "AP_${friendly_name}"
    password: !secret wifi_backup_pwd

api:
  reboot_timeout: ${reboot_timeout_api}

ota:

web_server:
  port: 80

logger:

captive_portal:

binary_sensor:
- platform: gpio
  pin:
    number: GPIO0
    mode: INPUT_PULLUP
    inverted: True
  id: sonoff_button
  internal: true
  on_press:
    - switch.toggle: sonoff_relay

switch:
- platform: restart
  name: '${friendly_name} REBOOT'

- platform: gpio
  name: "${friendly_name} Power"
  icon: "mdi:speaker"
  id: sonoff_relay
  pin:
    number: GPIO12
  restore_mode: ALWAYS_ON

status_led:
  pin:
    number: GPIO13
    inverted: True

text_sensor:  
  - platform: version
    name: ${friendly_name} ESPhome Version

Add the device to Home Assistant

Now, go to the Home Assistant Integrations page (Configuration>Integrations). You should see the ESPHome device show up in the discovered section after a minute or two.  Click configure, and submit, and that’s it.  Alternatively, you can manually add the device by clicking “CONFIGURE” on the ESPHome integration and entering “<NODE_NAME>.local” as the host.

Once the device is added, it will be in the lower part of this page (under Configured).  Clicking through to the device will show you the entity names that are auto-magically created by the ESPHome integration.

Node-RED Automation

Now, you cannot be expected to have to switch on the subwoofer through Home Assistant like a barbarian!  So my fix for this is to automate it with the state of my receiver’s power.  This is a very easy automation to create in Node-RED, my automation engine for Home Assistant.

This automation is looking for any messages about the on/off state of my receiver (media_player.rx_v675) and then outputs that state through an on/off switch (splitter).  If the receiver state becomes on, the flow calls to turn on the subwoofer switch to on. You can copy and paste the JSON flow below to import it into your Node-RED instance.

[{"id":"cf3c6f80.3beae","type":"server-state-changed","z":"57657673.d86dd8","name":"Receiver state","server":"c75798f0.9eb148","version":1,"entityidfilter":"media_player.rx_v675","entityidfiltertype":"exact","outputinitially":false,"state_type":"habool","haltifstate":"","halt_if_type":"str","halt_if_compare":"is","outputs":1,"output_only_on_state_change":true,"x":120,"y":890,"wires":[["67b8934a.8ffaec"]]},{"id":"67b8934a.8ffaec","type":"switch","z":"57657673.d86dd8","name":"on / off","property":"payload","propertyType":"msg","rules":[{"t":"true"},{"t":"false"}],"checkall":"true","repair":false,"outputs":2,"x":350,"y":890,"wires":[["2e23fe27.8fa362"],["6b0f2645.bdd0a8"]]},{"id":"2e23fe27.8fa362","type":"api-call-service","z":"57657673.d86dd8","name":"Turn on sub","server":"c75798f0.9eb148","version":1,"service_domain":"homeassistant","service":"turn_on","entityId":"switch.subwoofer_power","data":"","dataType":"json","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":580,"y":860,"wires":[[]]},{"id":"6b0f2645.bdd0a8","type":"api-call-service","z":"57657673.d86dd8","name":"Turn off sub","server":"c75798f0.9eb148","version":"1","service_domain":"homeassistant","service":"turn_off","entityId":"switch.subwoofer_power","data":"","dataType":"json","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":580,"y":920,"wires":[[]]},{"id":"c75798f0.9eb148","type":"server","z":"","name":"Home Assistant","legacy":false,"hassio":false,"rejectUnauthorizedCerts":false,"ha_boolean":"y|yes|true|on|home|open","connectionDelay":true}]

Concerns

I had some initial concerns that the Sonoff would be subjected to stress/interference that could make it work incorrectly or breakdown faster.  However, after making this modification last May, I’ve had zero issues with this setup.  It just works. If you’ve got any questions, feel free to ping me below.

]]>
283
Home Assistant integrated WiFi Power Strip for your HomeLAB https://khaz.me/home-assistant-integrated-wifi-power-strip-for-your-homelab/ Fri, 25 Oct 2019 06:43:23 +0000 https://khaz.me/?p=252 One of the things the lazy side of me hates, is physically having to go to my HomeLAB to hard reset any device.  While this has been happening less and less, it’s still something I dread.  My solution to the problem is to make a poor man’s rack PDU that’s integrated into Home Assistant. This how-to will outline how you can do the same for less than $7 per controlled socket using ESPHome firmware.

Hardware

I have used a Teckin and Tunbox (white or black), but there are many manufacturers that seem to brand label the same physical product.  The key is that the description needs to mention the “Smart Life” app as that means it’s using the Tuya WiFi module.

Teckin WiFi Power Strip

Firmware

The overall process is to flash this unit with custom firmware that tightly integrated to Home Assistant.  To get the unit converted from the original firmware, I used Tuya Convert combined with ESPHome to get this accomplished.  If you are not familiar with these, digiblurDIY and DrZzs both have extensive videos on how to get started with these.  I will cover the detailed configuration for these power strips.

The configuration I’ve set up for this device is focused on keeping the power on, as typically you do not want to shut it off accidentally. So, the physical button on the unit only toggles the USB power and all power sockets default to being ON when it’s plugged in or power is restored.  The only way to control the power sockets is through the device’s webpage or Home Assistant.

Follow the guides linked above to flash your power strip via the tuya convert method.  Then create a new device in ESPHome and load the YAML below to this device.

substitutions:
  board: esp01_1m
  device_name: esphome_homelab_powerstrip
  friendly_name: Homelab Powerstrip 1

esphome:
  name: ${device_name}
  platform: ESP8266
  board: ${board}

wifi:
  ssid: !secret wifi_iot_ssid
  password: !secret wifi_iot_pwd
  fast_connect: on
  ap:
    ssid: !secret wifi_backup_ssid
    password: !secret wifi_backup_pwd
  reboot_timeout: 0s

api:

ota:

web_server:
  port: 80

logger:

switch:
- platform: gpio
  name: "${friendly_name} Socket 1"
  icon: mdi:power-socket-us
  id: relay1
  pin:
    number: GPIO4
    inverted: True
  restore_mode: RESTORE_DEFAULT_ON
  on_turn_on:
  - switch.turn_on: red_led
  on_turn_off:
    - if:
        condition:
          and:
            - switch.is_off: relay2
            - switch.is_off: relay3
            - switch.is_off: relay4
        then:
          - switch.turn_off: red_led
- platform: gpio
  name: "${friendly_name} Socket 2"
  icon: mdi:power-socket-us
  id: relay2
  pin:
    number: GPIO13
    inverted: True
  restore_mode: RESTORE_DEFAULT_ON
  on_turn_on:
  - switch.turn_on: red_led
  on_turn_off:
    - if:
        condition:
          and:
            - switch.is_off: relay1
            - switch.is_off: relay3
            - switch.is_off: relay4
        then:
          - switch.turn_off: red_led
- platform: gpio
  name: "${friendly_name} Socket 3"
  icon: mdi:power-socket-us
  id: relay3
  pin:
    number: GPIO12
    inverted: True
  restore_mode: RESTORE_DEFAULT_ON
  on_turn_on:
  - switch.turn_on: red_led
  on_turn_off:
    - if:
        condition:
          and:
            - switch.is_off: relay1
            - switch.is_off: relay2
            - switch.is_off: relay4
        then:
          - switch.turn_off: red_led
- platform: gpio
  name: "${friendly_name} Socket 4"
  icon: mdi:power-socket-us
  id: relay4
  pin:
    number: GPIO14
    inverted: True
  restore_mode: RESTORE_DEFAULT_ON
  on_turn_on:
  - switch.turn_on: red_led
  on_turn_off:
    - if:
        condition:
          and:
            - switch.is_off: relay1
            - switch.is_off: relay2
            - switch.is_off: relay3
        then:
          - switch.turn_off: red_led
- platform: gpio
  name: "${friendly_name} USB Ports"
  icon: mdi:usb
  id: relay5
  pin:
    number: GPIO16
    inverted: False
  restore_mode: RESTORE_DEFAULT_ON

- platform: gpio
  internal: true
  id: red_led
  pin:
    number: GPIO3
    inverted: True

- platform: restart
  name: '${friendly_name} REBOOT'

binary_sensor:
- platform: gpio
  pin:
    number: GPIO5
    mode: INPUT_PULLUP
    inverted: False
  internal: true
  on_press:
    - switch.toggle: relay5

status_led:
  id: blue_led
  pin:
    number: GPIO0
    inverted: True

text_sensor:  
  - platform: version
    name: ${friendly_name} ESPhome Version

Home Assistant UI (Lovelace)

At first, I did not want to display these in my lovelace UI because I was worried about fat fingering something by accident.  Then, I discovered the Toggle Lock Entity Row plugin developed by Thomas Loven.  The easiest method for installing this is to utilize HACS (Home Assistant Community Store) – if you don’t have it, get it…now.  This plugin prevents accidental switching by requiring a secondary click within 5 seconds in order to turn off the device.

In my instance, I have chosen to name the entities generically via the firmware and add the label in lovelace.

- type: entities
        show_header_toggle: false
        title: HomeLAB Powerstrip 1
        entities:
          - entity: switch.homelab_powerstrip_1_socket_1
            name: Modem
            type: custom:toggle-lock-entity-row
          - entity: switch.homelab_powerstrip_1_socket_2
            name: UniFi USG
            type: custom:toggle-lock-entity-row
          - entity: switch.homelab_powerstrip_1_socket_3
            name: UniFi Switch
            type: custom:toggle-lock-entity-row
          - entity: switch.homelab_powerstrip_1_socket_4
            name: Dell R210
            type: custom:toggle-lock-entity-row
          - entity: switch.homelab_powerstrip_1_usb_ports
            name: UniFi Console Pi
            type: custom:toggle-lock-entity-row

 

Concerns

One of the concerns I initially had with this setup was the relays.  Since these are going to be on 99.9% of their life, the coil will be energized all of that time.  I couldn’t find a coil life listed anywhere from the manufacturer of the Y3F-SS-105DM.  After some googling, it appears for DC coils, this is a somewhat negligible concern as they will run very cool.  My power strip has been on since April 2018 without issues.

 

If you’ve got any questions, feel free to ping me below.

]]>
252
Weather notification through RGB light in Home Assistant and Node-RED https://khaz.me/weather-notification-through-rgb-light-with-home-assistant-and-node-red/ https://khaz.me/weather-notification-through-rgb-light-with-home-assistant-and-node-red/#comments Wed, 25 Sep 2019 23:25:52 +0000 https://khaz.me/?p=266

Recently while discussing the subject of home automation with my SO, she mentioned that she’d like a way to be notified what the weather was going to be when she’s getting ready.  The timing of this couldn’t be any better as I had just started playing around with an automation to do this very thing.

The best and worst part of this was that I already have all the hardware installed to make this happen. Our hallway has a receptacle where I’ve mounted the Xiaomi Hub (pronounced shaw-me) as well as a motion sensor in the ceiling fixture.  The has an RGB LED light ring that will be in the perfect location in front of the bathroom.  Luckily, because I live in San Francisco, we really only notification for abnormal weather of it being hot (above 72 degrees) or raining.  Yes, I know 72 isn’t hot if you are in many parts of the world, but for SF residents it’s hot.

Node-RED is my automation engine for all of my Home Assistant needs, so naturally, this is where it’s built.  Here is what the flow looks like. It is available here for you to import into your system.

Node-RED flow for weather notification via RGB light

This is a pretty basic flow:

  1. It’s triggered by the hall motion sensor
  2. If the time is between the set range, the flow continues
  3. The flow splits into two and checks each individual weather entity, and if it meets the requirement, the flow continues to trigger each light.
  4. If a weather flow continues, it also triggers a 60-minute timer to turn off the light

Some things to note:

  • There is a throttling node that limits the number of times this “runs” to once per half hour
  • A second delay helps spread out the requests to HA
  • Before turning off the light, I set it to white for a split second so that a future turn-on of the light will be white instead of the previously set red or blue
  • This can easily be expanded to multiple other weather entities and to include additional lights
]]>
https://khaz.me/weather-notification-through-rgb-light-with-home-assistant-and-node-red/feed/ 2 266
Cheap and Easy Multiroom Sensing for your HVAC with Xiaomi Aqara and Home Assistant https://khaz.me/cheap-and-easy-multiroom-sensing-for-your-hvac-with-xiaomi-aqara-and-home-assistant/ https://khaz.me/cheap-and-easy-multiroom-sensing-for-your-hvac-with-xiaomi-aqara-and-home-assistant/#comments Sun, 08 Sep 2019 21:32:57 +0000 https://khaz.me/?p=240

As with most things, this is a solution to solve the problem that I have. My home has an unfortunate problem: zero insulation.  Before you go down the road of suggestions, trust me, it’s not an option for my property until I can afford to do a remodel.   As a result, my natural drive of efficiency has forced me to try to improve the heating system as much as I can.  In comes Home Assistant to the rescue.  Originally I had a [completely] manually operated forced-air heating system with every room/area that had a single duct, regardless of the room size, and you had to manually control the odd-sized 10″ x 14″ register to adjust the airflow. All of that was driven by a single point mercury thermostat from the ’80s which was placed in the rarely occupied dining room.  As a result, if you had all vents open, the living room would get hottest as it’s closest to the heater unit, while our bedroom and guestroom would be a good 15 degrees lower when the dining room reached its set point.

So after more years of living with this system than I’d like to admit, I decided to solve the problem.  My idea was to make a multi-sensor system that would allow me to drive the heating system based on a selected room input.  This began the drive to find the best/most cost-effective system for monitoring room temps across many rooms.  As I already had a Xiaomi Aqara hub, it’s temp and humidity sensors offered the best expansion for my existing system.  These are just the sensors I choose, but ultimately you can use any sensor that gives you a temperature datapoint.

Once I had my hardware picked out, I added them through the Xiaomi Gateway component.  After you have the gateway added to your HA config, any and all new sensors/device need to be paired to the gateway.  I’ve found that it’s easiest for me to do this via the Xiaomi Mi Home app.  I have been very surprised with the reliability of the hub integration as I’ve never had it fail to issue a command.  I did have a single temp sensor that was a bit flaky, but the hub has been great.

The architecture of Xiaomi devices to the WLAN

Next, I went to implementing the software.  What I ultimately wanted is a way for my heating system based on the room(s) that I was occupying.  What I came up with is a generic climate sensor that follows the various temp sensors that I’ve configured.  So here I will walk you through the example of how I have it configured.  I have had this working great for the last year or so, so let me know if you run into issues.

Here is my entire climate.yaml package file:

input_select:
  heater_target_sensor:
    name: Heater target sensor
    options:
     - Living Room
     - Guest Bedroom
     - Master Bedroom
    icon: mdi:radiator

binary_sensor:
  - platform: template
    sensors:
      heater_target_seleceted_living_room:
        friendly_name: "Living Room"
        value_template: "{{ is_state('input_select.heater_target_sensor', 'Living Room') }}"
  - platform: template
    sensors:
      heater_target_seleceted_master_bedroom:
        friendly_name: "Master Bedroom"
        value_template: "{{ is_state('input_select.heater_target_sensor', 'Master Bedroom') }}"
  - platform: template
    sensors:
      heater_target_seleceted_guest_bedroom:
        friendly_name: "Guest Bedroom"
        value_template: "{{ is_state('input_select.heater_target_sensor', 'Guest Bedroom') }}"

sensor:
- platform: template
  sensors:
    heater_target_sensor_template:
      friendly_name: "Heater target sensor"
      unit_of_measurement: "°F"
      value_template: >-
          {% if is_state('input_select.heater_target_sensor', 'Master Bedroom') %}
              {{ states.sensor.master_bedroom_temperature.state  | float }}
          {% elif is_state('input_select.heater_target_sensor', 'Guest Bedroom') %}
              {{ states.sensor.guest_bedroom_temperature.state  | float }}
          {% elif is_state('input_select.heater_target_sensor', 'Living Room') %}
              {{ states.sensor.living_room_temperature.state  | float }}
          {% endif %}


climate:
- platform: generic_thermostat
  name: Heater
  heater: switch.heater_heat
  target_sensor: sensor.heater_target_sensor_template
  min_temp: 55
  max_temp: 72
  ac_mode: False
  target_temp: 68
  cold_tolerance: 1
  hot_tolerance: 2
  away_temp: 55
  precision: 0.1
  min_cycle_duration:
    minutes: 20

The basic system is that you define a number input selects which matches the number of temperature sensors you have to drive the heating system.  For me, this was three rooms consisting of a living room, guest bedroom, and a master bedroom.  Then, you create a single binary target sensor which is on when you select that specific room.  Finally, you need a template sensor equal to the value of the temperature of the room you selected in the binary sensor.  Based on what the input select is selected to, this will drive a template sensor to define the target temperature of a room.  From this final setpoint, we create a climate system that drives to this target.

Finally, to make this easy to set, I’ve created a set of buttons that allows me to easily set this via lovelace.  The magic is the custom button card.   This allows me to show each of my three target sensors and whether they are selected.

- type: horizontal-stack
  cards:
    - type: custom:button-card
      entity: binary_sensor.heater_target_seleceted_living_room
      name_template: >
        return 'Living Room: ' + states['sensor.living_room_temperature'].state
      show_state: false
      tap_action:
        action: call-service
        service: input_select.select_option
        service_data:
            entity_id: input_select.heater_target_sensor
            option: Living Room
      size: 30%
      styles:
        card:
          - height: 100px
        name:
          - font-size: 14px
    - type: custom:button-card
      entity: binary_sensor.heater_target_seleceted_master_bedroom
      name_template: >
        return 'Master Bed: ' + states['sensor.master_bedroom_temperature'].state
      show_state: false
      tap_action:
        action: call-service
        service: input_select.select_option
        service_data:
            entity_id: input_select.heater_target_sensor
            option: Master Bedroom
      size: 30%
      styles:
        card:
          - height: 100px
        name:
          - font-size: 14px
    - type: custom:button-card
      entity: binary_sensor.heater_target_seleceted_guest_bedroom
      name_template: >
        return 'Guest Bed: ' + states['sensor.guest_bedroom_temperature'].state
      show_state: false
      tap_action:
        action: call-service
        service: input_select.select_option
        service_data:
            entity_id: input_select.heater_target_sensor
            option: Guest Bedroom
      size: 30%
      styles:
        card:
          - height: 100px
        name:
          - font-size: 14px

Shown here selecting various rooms controls the input as seen by the climate component. Temp from the buttons were removed for a cleaner UI.

This config should work for both AC and heat even though I’m only using it as a target for my heating system.  Feel free to experiment with various configurations within your lovelace to make it the best setup for your configuration.

In order to automate this target sensor, I have it set via some Node-Red flows to make it automagically set to where I want it, but that’s for another post!  Let me know if you want me to go into the details of configuring the Xiaomi sensors.

If you want to support me, buy me a coffee or buy the Xiaomi Hub kit or Temp sensors through my referral links.

As always, feel free to post up questions you come across and I’ll try to help where I can.

]]>
https://khaz.me/cheap-and-easy-multiroom-sensing-for-your-hvac-with-xiaomi-aqara-and-home-assistant/feed/ 2 240
Cheap and Easy Control of 8 Relays through Home Assistant https://khaz.me/cheap-and-easy-control-of-8-relays-through-home-assistant/ https://khaz.me/cheap-and-easy-control-of-8-relays-through-home-assistant/#comments Sat, 06 Jul 2019 16:27:06 +0000 https://khaz.me/?p=238 Home Assistant and ESPHome

Following up on my previous post of the Cheap and Easy series, I’m going to show you how you can control 8 relay channels for about 25 bucks and in about 30 minutes. If you’re not familiar with Home Assistant or ESPHome, check out my previous post.

In this project, I use a Wemos D1 Mini as the wifi enable the controller to interface with the relay module using the IO expansion shield.  The magic of this setup is using the IO module and soldering it directly onto the relay board.  This eliminates the narly mess you see you when would typically have 8 channels of relays.  As a bonus, since you are only using 8 of the available 16 channels on the IO module, you could use the remaining 8 IO to do all sorts of other things.

Shopping list:

  1. Wemos D1 Mini – The Wemos D1 Mini is an ESP8266 based microcontroller that will handle the heavy lifting of WiFi and communicating to your Home Assistant instance [ Amazon, 3 Pack, Amazon, 5 Pack ]
  2. MCP23017 IO Expansion Module – This is what you will use to allow you to drive all 8 relay channels with minimal effort [ Amazon ]
  3. 8 Channel Relay Board – I added the DHT to get temperature and humidity data [ Amazon ]
  4. Assorted Dupont Jumpers – Always have a bunch of these handy, they have a tendency to disappear and get used up in projects. [ Amazon ]OPTIONAL: If you want to control 12v or 24v loads
  5. Appropriate DC power supply for your loads – This will vary on what you are trying to control, links to some options. [ Amazon 12v 5A | Amazon 24v 3A ]
  6. LM2596S DC-DC power regulator – It converts garage door’s 12V DC to 5V DC for the Wemos or use a microUSB cable. [ Amazon ]
  7. Soldering Iron Kit – It’s likely that you already have this if you’ve been DIYing for a while [ Amazon ]

Installation is cake

You will need to provide 5v DC power to power the system.  To get started, you will want to place the IO module over the pins of the relay module.  Make sure to line these up correctly as I’ve indicated below.  If you don’t, it’s a big pain to remove it and put it back on correctly, especially if you’ve soldered it in place.  Ask me how I know.
The IO module will have a total of 4 wires connected to it:  two for +5v and GND from the power supply, and two for the I2C (SDA and SCL) from the Wemos.
The IO module will have a total of 4 wires connected to it:  two for +5v and GND from the power supply, and two for the I2C (SDA and SCL) from the Wemos.
That’s it!

Wiring for all of the devices

Pay careful attention to the alignment of the pins

Soldered IO module on to the relay module

Since it’s likely that you will want to switch/power things that are of higher voltage than the 5v rail you need to power the Wemos, I’ve included the 12v and 24v optional power supplies.  Be sure that you do not connect any of these higher voltages to any of the logic pins on the Wemos or the IO, only connect them to the relay output terminals.

ESPHome config

I created the 8 channels as output switches and for the time being omitted the remaining 8 channels which can be configured as inputs or outputs.  I created a new device, named it esphome_relay_board using a D1 mini board with the following config:

esphome:
  name: esphome_relay_board
  platform: ESP8266
  board: d1_mini

wifi:
  ssid: 'insert'
  password: 'your_own'
  fast_connect: on
  
api:

ota:

web_server:
  port: 80

logger:

i2c:
  sda: D1
  scl: D2
  scan: True

mcp23017:
  - id: 'mcp23017_hub'
    address: 0x20

switch:
- platform: restart
  name: "Relay Channel Board REBOOT"

- platform: gpio
  name: relay_channel_1
  icon: mdi:electric-switch
  pin:
    mcp23xxx: mcp23017_hub
    number: 15
    mode: OUTPUT
    inverted: True
- platform: gpio
  name: relay_channel_2
  icon: mdi:electric-switch
  pin:
    mcp23xxx: mcp23017_hub
    number: 14
    mode: OUTPUT
    inverted: True
- platform: gpio
  name: relay_channel_3
  icon: mdi:electric-switch
  pin:
    mcp23xxx: mcp23017_hub
    number: 13
    mode: OUTPUT
    inverted: True
- platform: gpio
  name: relay_channel_4
  icon: mdi:electric-switch
  pin:
    mcp23xxx: mcp23017_hub
    number: 12
    mode: OUTPUT
    inverted: True
- platform: gpio
  name: relay_channel_5
  icon: mdi:electric-switch
  pin:
    mcp23xxx: mcp23017_hub
    number: 11
    mode: OUTPUT
    inverted: True
- platform: gpio
  name: relay_channel_6
  icon: mdi:electric-switch
  pin:
    mcp23xxx: mcp23017_hub
    number: 10
    mode: OUTPUT
    inverted: True
- platform: gpio
  name: relay_channel_7
  icon: mdi:electric-switch
  pin:
    mcp23xxx: mcp23017_hub
    number: 9
    mode: OUTPUT
    inverted: True
- platform: gpio
  name: relay_channel_8
  icon: mdi:electric-switch
  pin:
    mcp23xxx: mcp23017_hub
    number: 8
    mode: OUTPUT
    inverted: True

status_led:
  id: status_led
  pin:
    number: GPIO2

The components above include

  • An I2C component to enable I2C communication
  • A MCP23017 component for the IO module
  • A switch restart component to reboot the Wemos
  • A switch GPIO component for the relay
  • A status LED component for indicating networking/error status.

Now can compile the firmware and flash it to your Wemos D1.  Again, if you’re not familiar with how to do this, reference the videos linked above.  Once it’s flashed, power cycle the device.  Now you should be able to open the web GUI for the device by either going to it’s IP or going to http://esphome_relay_board.local in your browser, or whatever you named it.  When the page loads up, you should test out the relay switches by hitting the button next to them.

Integration into Home Assistant

Now to integrate it into Home Assistant, you will need to go to configuration > integrations.  Assuming you have discovery enabled, you will have a new ESPHome device, click configure and add it to your system.  If you don’t have any existing conflicting entities, your entity names should match the ones I have.  I’m using the following config for lovelace:

- type: entities
        title: Garage Relay Module + IO
        show_header_toggle: false
        entities:
          - switch.relay_channel_1
          - switch.relay_channel_2
          - switch.relay_channel_3
          - switch.relay_channel_4
          - switch.relay_channel_5
          - switch.relay_channel_6
          - switch.relay_channel_7
          - switch.relay_channel_8
          - switch.garage_relay_module_reboot

This provides you with a simple switch list.  Each icon shows you the state of the relay.  And lastly, you get the reset switch to reset the ESP.

]]>
https://khaz.me/cheap-and-easy-control-of-8-relays-through-home-assistant/feed/ 41 238
Home Assistant controlled fireplaces sconces with Sonoff Basic and ESPHome https://khaz.me/home-assistant-controlled-fireplaces-sconces-with-sonoff-basic-and-esphome/ https://khaz.me/home-assistant-controlled-fireplaces-sconces-with-sonoff-basic-and-esphome/#respond Sat, 06 Apr 2019 21:56:57 +0000 https://khaz.me/?p=196

Following up on my previous post about the Home Assistant controlled garage door, I want to show my simple solution to controlling a light with HA.  My house is a few years away from its centennial birthday.  With that age come some interesting “features”, like knob and tube wiring, and always on lights with physical switches per fixture, and lots of other tidbits.   The individual switches were a bit annoying and the old fixtures were quite ugly.  Besides, controlling the lights with Home Assistant is a great as it gives you infinite flexibility with automations and voice assistant integrations.   The Sonoff Basic is a great little wifi switch that’s easily flashed with your custom firmware of choice to keep all of the control local and out of the nasty cloud.  As I mentioned before, ESPHome has become my goto for anything that is ESP8266 or ESP32 controlled.  It’s ease of use, flexibility, and rapid development (massive thanks to OttoWinter) make it the best firmware option for me.

Parts List

  1. Sconce light fixture – Simple unswitched wall sconce [HomeDepot | Amazon]
  2. LED bulb – Make sure it’s 110v to match your house voltage and fits your fixture’s bulb socket [ Amazon ]
  3. Sonoff Basic – The wifi controlled switch that will simulate the previous physical switch [ Amazon ]
  4. FTDI Programmer – I like the micro USB one with the 3.3v/5v selection jumper  [ Amazon ]
  5. Ferrules and Crimper – These are great for preventing wire strands from going crazy when pushing them into the terminals and make your job look very professional [ Amazon ]
  6. Hot glue gun – You probably have one of these, I just upgraded my 20 year old one to this one [ Amazon ]

DIY

Again, I’m not going to go through the details of setting up ESPHome.  You can watch either Rob’s or digiblur’s videos to get a good explanation on it.  Once you have it up and running, you will need to create a new device by populating the name and WiFi details.   Here is my config:

esphome:
  name: esphome_light_sconce_right
  platform: ESP8266
  board: esp01_1m

wifi:
  ssid: 'insert'
  password: 'your_own'
  fast_connect: on
  
api:

ota:

web_server:
  port: 80

logger:

binary_sensor:
- platform: gpio
  pin:
    number: GPIO0
    mode: INPUT_PULLUP
    inverted: True
  id: sonoff_button
  internal: true
  on_press:
    - light.toggle: light

output:
- platform: gpio
  id: sonoff_relay
  pin:
    number: GPIO12

light:
- platform: binary
  name: "Sconce, Right"
  id: light
  output: sonoff_relay

switch:
- platform: restart
  name: 'Sconce, Right REBOOT'

status_led:
  id: status_led
  pin:
    number: GPIO13
    inverted: True

 

The components above include

  • A binary sensor component for the button on the Sonoff Basic
  • An output component for controlling the relay state
  • A light component since you want this to show up as a light in HA
  • A switch restart component to reboot the Sonoff
  • A status LED component for indicating networking/error status on the Sonoff

Now can compile the firmware and flash it to your Sonoff Basic. The FTDI adapter only needs four wires connected to the Basic: VCC, GND, RX, TX.  Again, if you’re not familiar with how to do this, reference the videos linked above.  Once it’s flashed, power cycle the device.   Now you should be able to open the web GUI for the device by either going to it’s IP or going to esphome_light_sconce_right.local in your browser.  If the page loads, you’ve done everything correctly up to this point.  Since the Basic’s relay needs line power to operate, you will need to disconnect your FTDI programmer and connect it your mains power.  Remember, this is mains voltage, so be careful and if you’re not comfortable with this, put the unit back in its case before proceeding.  After the Basic powers up, you should be able to test out the light switch by hitting the button on the web UI.

ESPHome webserver UI

Now I needed to mount the Basic inside of my sconce.  Part of the reason that I picked this sconce fixture was that I thought it had plenty of room in the base.  Unfortunately, I was almost right except for the LED and push button that were just a hair too long.  So I used my Dremel rotary tool’s cutoff disc to cut the button down to about half length and resoldered the LED a 1/4″ lower into the PCB.  In order to insulate the bottom of the PCB from the metal sconce, I used a plastic raft that I had sitting around form a previous 3D print.  Alternatively, you can use the bottom of the Basic’s case or anything else that’s non conducting.  For me, the case was a bit wider than I liked and I had the raft sitting there.  I used hot glue to attach the raft to the sconce, and the Basic to the raft.  The last step was to put ferrules on the sconces wires and plug them in.  Then I did a final bench test: first with the Basic connected to mains to make sure it was working by hearing the relay click, and finally plugging in the bulb into the fixture’s socket to make sure it lit up.  Now, just install it based on the directions from your fixture, and turn on the breaker (fuse in my case).

Sonoff Basic (v2) mounted on a piece of plastic inside the light fixture

To integrate it into Home Assistant, you will need to go to configuration > integrations.  Assuming you have discovery enabled, you will have a new ESPHome device, click configure and add it to your system.  If you don’t have any existing conflicting entities, your entity names should match the ones I have.  I’m using lovelace with the following config:

- type: horizontal-stack
        cards:
          - type: entity-button
            name: Crown Molding
            icon: mdi:crown
            tap_action:
              action: call-service
              service: light.toggle
              service_data:
                entity_id: light.crown_molding
            hold_action:
              action: more-info
            entity: light.crown_molding
          - type: entity-button
            name: Sconce Left
            icon: mdi:wall-sconce
            tap_action:
              action: call-service
              service: light.toggle
              service_data:
                entity_id: light.sconce_left
            hold_action:
              action: more-info
            entity: light.sconce_left
          - type: entity-button
            name: Sconce Right
            icon: mdi:wall-sconce
            tap_action:
              action: call-service
              service: light.toggle
              service_data:
                entity_id: light.sconce_right
            hold_action:
              action: more-info
            entity: light.sconce_right

This provides you with a simple button row who’s icon shows you the state of the lights.

I’ve exposed these lights to my Google Assistant integration.  So I just walk into the living room and say “Hey Google, turn on the sconces” and they fire right up.

]]>
https://khaz.me/home-assistant-controlled-fireplaces-sconces-with-sonoff-basic-and-esphome/feed/ 0 196