configuration.yaml

The GUI has its limits for configuration especially when integrations are missing or generic communication protocols are used. In this case the configuration file configuration.yaml needs to be edited.

Important

After editing configuration.yaml it is highly recommended to check in Home Assistant Gui Tools CHECK CONFIGURATION https://www.home-assistant.io/common-tasks/core/#configuration-check to see if the syntax is correct and if a restart will be sucessful.

For new items a restart is necessary after that modifications need just a YAML reload, click an green tick should appear.

To get a modular configuration configuration.yaml can includes other yaml files. To move out the mqtt stuff in a separate mqtt.yaml file add to configuration.yaml

mqtt: !include mqtt.yaml

then create the mqtt.yaml without repeating mqtt again and define the mqtt topic to be subscribed:

sensor:
  - name: "raspi_soc_temperature"
    state_topic: "raspi/soc/temperature"

Friendly names and Entity ID

Friendly names are names put in quotes *This is a friendly name" and are written as a human would do. To be come computer readable it is converted in lowercase with underscore names having a prefix as sensor.and are then used as entity ID: sensor.this_is_a_friendly_name

MQTT Integration

Configure mosquitto integration and give as IP 127.0.0.1 with port 1883 and user name and password. The mosquitto integration gui allows to subscribe and publish MQTT topics. As first test it can communicate to console windows.

It is assumed that a MQTT broker as mosquitto is running and configured in Home Assistant running.

localhost can be put when running mosquitto on the same computer as homeassistant

When running mosquitto in a docker container it must be able to communicate with homeassistant. One way of doing this is setting in docker-compose.yml

network_mode: host

then it can be accessed under 127.0.0.1.

For password less communication in a local LAN anonymous must bee set in mosquitto.conf

listener 1883
allow_anonymous true
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log 

Read from a custom MQTT sensor

MQTT and subscribe values

To test that subscribed MQTT arrive, a MQTT message needs to be published.

If there is no MQTT publisher, create one with a script that reads and publishes the raspberries SoC temperature.

If mosquitto is installed as regular application requiring a password create and run the script:

#! /bin/bash
mosquitto_pub \
  -t "raspi/soc/temperature" \
  -m "$(/usr/bin/vcgencmd measure_temp | sed -E 's/temp=([0-9]+\.[0-9]+).*/\1/')" -u <username> -P <password>

Having a published MQTT message, check in an other console that subscribing is working:

mosquitto_sub -t "raspi/soc/temperature" -u <username> -P <password>

If mosquitto runs in docker use the following commands to publish:

/usr/bin/docker exec mosquitto mosquitto_pub -h localhost -t "raspi/soc/temperature" -m "$(/usr/bin/vcgencmd measure_temp | sed -E "s/temp=([0-9]+\.[0-9]+).*/\1/")"

and to subscribe:

/usr/bin/docker exec mosquitto mosquitto_sub -t "raspi/soc/temp erature"

sed is used to just get the numerical value.

The script could be added to cron:

*/15 * * * * /opt/RaspiTemperature/raspitemp.sh

or to see cron error messages:

*/15 * * * * /opt/RaspiTemperature/raspitemp.sh >> /tmp/raspitemp-cron.log 2>&1

Now edit ha-config/configuration.yaml

mqtt:
  sensor:
    - name: "raspi_soc_temperature"
      state_topic: "raspi/soc/temperature"

In Home Assistant -> Developer Tools -> CHECK CONFIGURATION and reload the or all YAML

A new entity sensor.raspi_soc_temperature should now appear and can be used as in a sensor card.

MQTT and subscribe Json

The payload might be json instead of single data. For every data structured in Json a separate MQTT entry must be done, some data is nested so the path needs to be included. The entries would look as:

sensor:
  - name: "raspi_soc_temperature"
    state_topic: "raspi/soc/temperature"
  - name: "raspi_manager_battery_soc"
    state_topic: "raspi/manager"
    value_template: "{{ value_json['battery' ].soc }}"
  - name: "raspi_manager_power"
    state_topic: "raspi/manager"
    value_template: "{{ value_json.power }}"

Write to a custom MQTT sensor

MQTT and send to Shelly Mini1PMG3

Shelly Mini1PMG3 is not yet directly supported in Home Assistant and has a rather complicated payload to be turned on. Everything is therefore be packed into payload_on and payload_off

switch:
  - name: "mini1pmg3"
    command_topic: "shelly1pmminig3-5432044f7414/rpc"
    payload_on:  '{"id": 1, "src": "hass", "method":"Switch.Set", "params":{"id":0,"on":true}}'
    payload_off: '{"id": 1, "src": "hass", "method":"Switch.Set", "params":{"id":0,"on":false}}'
    retain: false

There is no state_topic and value_template therefore it works just in the publishing direction. To have mosquitto know the payload in case the Shelly Mini1PMG3 is powered off and will be powered on later retain: true must be set.

To have a switch bidirectional, a state_topic must be added, since the switch status is inside json a value_template is required and since the state data is different from command data, state_on and state_off is defined. To work it well during power on an off retain is set to true:

switch:
  - name: "mini1pmg3"
    command_topic: "shelly1pmminig3-5432044f7414/rpc"
    payload_on:  '{"id": 1, "src": "hass", "method":"Switch.Set", "params":{"id":0,"on":true}}'
    payload_off: '{"id": 1, "src": "hass", "method":"Switch.Set", "params":{"id":0,"on":false}}'
    retain: true
    state_topic: "shelly1pmminig3-5432044f7414/status/switch:0"
    value_template: "{{ value_json.output }}"
    state_on: true
    state_off: false

template support and mqtt

There are more then on way to do something in Home Assistant, this might be a source of confusion.

Templates allow a more generic way and are flexible way to handle things. Publishing MQTT topics is also possible within a template section:

template:
  - button:
      - name: "MQTT Button 1"
        press:
          service: mqtt.publish
          data:
            topic: "object_detection/switch"
            payload: 1

      - name: "MQTT Button 2"
        press:
          service: mqtt.publish
          data:
            topic: "object_detection/switch"
            payload: 2

      - name: "MQTT Button 3"
        press:
          service: mqtt.publish
          data:
            topic: "object_detection/switch"
            payload: 3.

command line support

Results from command line calls can be used as entities by adding to configuration.yaml

command_line:
  - sensor:
      name: "Raspberry Pi SOC Temperature"
      unique_id: rpi_soc_temperature
      command: "cat /sys/class/thermal/thermal_zone0/temp"
      scan_interval: 60
      unit_of_measurement: "°C"
      value_template: "{{ (value | float / 1000) | round(1) }}"

Add a card as sensor or gauge and use the entity sensor.raspberry_pi_soc_temperature

rest API support

Rest API calls can be used by adding to configuration.yaml:

rest_commend:

Entities

Important

The same entities can be appear in two forms:

"Camera 1 Raw" as used in the GUI and configuration.yaml

sensor.camera1_raw as used in the dashboard cards

Give it a unique id so the gui editor can find it and handle the connection between the different forms.

One way is to put a MAC address in the identifier to assure it stays unique

unique_id: "raspi4_soc_temp-e45f016dc555"

If applicable give a unit to the value

unit_of_measurement: "W"

Automations

Automations is the logic added to Home Assistant that takes inputs or events and controls outputs or actions. It is what Home Assistant does automatically. Automations have triggers.

Automations can be created and edited via the gui or yaml.

Note

Some evolution is going on how to write the yaml code and unfortunately it can look very different between new HA and old HA setups. Backward compatibility might work. Gui will create yaml in the actual version.

If it gets complicated then the logic can be moved into python code and have it communicate to HA using MQTT

The following are older yaml code examples:

Turn on an output of a tasmota device at 8 o'clock:

alias: Tasmota Switch On at 20:00
description: Turn on switch.tasmota2 at 20:00
trigger:
  - platform: time
    at: "20:00:00"
action:
  - service: switch.turn_on
    target:
      entity_id: switch.tasmota2
    data: {}

Or turn it on at sunset:

alias: Tasmota Switch On at sunset
description: Turn on switch.tasmota2 at sunset 
trigger:
  - platform: sun
    event: sunset
    offset: "0"
condition: []
action:
  - service: switch.turn_on
    target:
      entity_id: switch.tasmota2
    data: {}
mode: single

And a humidity alarm:

alias: Humidity Alarm Bathroom On
description: Humidity is above level
trigger:
  - platform: numeric_state
    entity_id: sensor.shellyplusuni_a0a3b36865f4_humidity
    above: 45
condition: []
action:
  - type: turn_on
    device_id: f9ecf0bcd602949c51a780527ac19b57
    entity_id: switch.shellyplusuni_a0a3b36865f4_switch_0
    domain: switch
mode: single

Automation and mqtt

If a value changes then an automation can publish a mqtt value, Add to automations.yaml:

alias: "MQTT: Publish Numeric Helper on Change"
description: "Publishes helper states to MQTT whenever they change"
trigger:
  - platform: state
    entity_id:
      - input_number.helper_1
      - input_number.helper_2
action:
  - service: mqtt.publish
    data:
    # Use states('entity_id') to extract the numeric string
      payload: "{{ states(trigger.entity_id) }}"
      topic: "sensor/{{ trigger.entity_id.split('.')[1] }}"
      retain: true
mode: queued

Reload the automation yaml, Home Assistant does not need to be restarted and test it: docker exec -it mosquitto mosquitto_sub -t "battery_manager/#" -v

Dashboards

Dashboards are the ones appearing in the main window of homeassistant, The list of dashboards appear in the sidebar. Via Settings > Dashboards they can be managed and new dashboards added. Some dashboards as Overview are build in, others are user added. To sort them click and hold on the text Home Assistant until a menu pops up.

Dashboards can be edited with the GUI but also as YAML.

Dashboards can have views that are like tabs. This prevents to have too many dashboards listed on the sidebar

Dashboards have view layouts how they place the cards on it (Section, Masonry), so it adapts to any screen size.

  • Masonry puts cards side by side. If a row is full the next card will be placed underneath the shortest card.

  • Sections, has sections that hold a group of cards, the sections are then added sequentially on the screen.

An other way is using cards that can contain other cards, as the grid card or the Marketplace Layout Card (that must be downloaded and installed first). This gives better control how to place the cards but might not work well if different screens are used.

Cards

Cards can be added to dashboards.

Grid card

The grid card helps how to put cards on a dashboard. The dashboard will just see the grid card and not its contents. The cards are put side by side to the grid card until all columns are full then it starts with a new row. It allows cards to spawn multiple columns

Markdown card

The markdown card can be used to print text.

Manual cards

Home Assistant is shown as a web page. Web pages can have Java Scripts and those JavaScripts can be debugged the regular way using a featured web browser.

Create the Javascript config/www/hello-card.js

class HelloCard extends HTMLElement {
  setConfig(config) {
    this.config = config;
    this.innerHTML = `<ha-card header="Hello Card">
      <div style="padding: 16px;">Hello World!</div>
    </ha-card>`;
  }

  set hass(hass) {
    // will be called on each state-update
  }

  getCardSize() {
    return 1;
  }
}

customElements.define("hello-card", HelloCard);

In Settings Dashboard add as resource /local/hello-card.js

If Ctrl+F5 in firefox does not fetch the newest file go to in developer tools to network and disable cache.

If this does not work edit the dashboard click on right 3 point icon and then ressorces add a dummy version query parameter to the url as /local/my-elevator-card.js?v=1.0.1 inctease the number with every change made.

the same could also be done using configuration.yaml:

lovelace:
  mode: yaml
  resources:
  - url: /local/my-elevator-card.js?v=1.0.1
    type: module 

To have the js be known by the card go to the dashboard and edit the card. YAML of manual card needs to be linked to the entities received..

type: custom:hello-card
entity: sensor.elevator_position
min: 1
max: 10
floor_height: 40
cabin_height: 30
cabin_call_topic: elevator/car_call/{floor}
ack_entity_template: sensor.elevator_ack_{floor}
ack_on_state: '1'

docker exec -it mosquitto mosquitto_sub -t "elevator/#" -v

If entities are used in the card they need to be added and can have a restriction as min and max

Note

If the the subdirectory www had to be create manually it might be thatc save fails.

Check http://<hostname>:8123/local/hello-card.js if it finds and open the file. If not Home Assistant is not aware about the directory and a restart might solve the issue.

The tag <div> inserts HTML code into the manual card inside the Home Assistant page.

Instead of simple text svg xml code can be added.

Helpers the user Input

User Input is done via Helpers. Settings > Devices & Services > Helpers

Enter a number

Create a Number helper. The options are Slider or Input field Then use it in Dashboards. The modified values will be stored persistent

Creating the helper in configuration.yaml allows to set an initial value without the need of going into different dashboards and modify the values.

input_number:
  peak_shaving_soc:
    name: "Peak Shaving SoC"
    min: 0
    max: 100
    step: 1
    initial: 20
    unit_of_measurement: "%"
    mode: box 

Linurs startpage