Tag Archives: mqtt

Home Assistant – Reboot, start,shutdown and switch OS

This is my short log about (re)starting booting machines.

configuration.yaml

#WOL to start a machine
  - platform: wake_on_lan
    name: "wakeserver"
    mac: ec:be:5f:ee:11:78

#SHELL command to remote start reboot2windows script (multiboot machine)
shell_command:
    ssh_reboottowindows: ssh -i /config/ssh/id_ed25519 -o 'StrictHostKeyChecking=no' root@192.168.1.2 '/root/reboot2windows'
shell_command:
    ssh_haltlinux: ssh -i /config/ssh/id_ed25519 -o 'StrictHostKeyChecking=no' root@192.168.1.2 'halt -p'

reboot2windows linux script (on the remote server)

#!/bin/bash
#place in /root/
#chmod +x /root/reboot2windows
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
WINDOWS_TITLE=`grep -i "^menuentry 'Windows" /boot/grub/grub.cfg|head -n 1|cut -d"'" -f2`
grub-reboot "$WINDOWS_TITLE"
reboot

install https://iotlink.gitlab.io/ on your windows instance

scripts.yaml (with a helper button rebootwindows2linux, shutdownwindows)

#Reboot windows, linux is the default
windows2linux:
  alias: rebootwinserver
  sequence:
  - service: mqtt.publish
    metadata: {}
    data:
      qos: 0
      retain: false
      topic: iotlink/workgroup/winserver/commands/reboot
  mode: single
shutdownwindows:
  alias: shutdownwinserver
  sequence:
  - service: mqtt.publish
    metadata: {}
    data:
      qos: 0
      retain: false
      topic: iotlink/workgroup/winserver/commands/shutdown
  mode: single

automation rebootlinux2windows

(using a helper button rebootlinux2windows)

alias: rebootlinux2windows
description: ""
trigger:
  - platform: state
    entity_id:
      - input_button.rebootlinux2windows
condition: []
action:
  - service: shell_command.ssh_reboottowindows
    data: {}
mode: single

Configuring ssh keys

Open HA terminal

cd
ssh-keygen (enter) (enter) (enter) (enter) 
mkdir -p config/ssh
cp ~/.ssh/id* config/ssh/ 

Waveshare Epaper ESPHOME and Mqtt Notification over secure mqtt

UPDATE: AccessPoint on Arduino implemented with captive portal for Wifi Configuration

Got my Waveshare Epaper Cloud running on ESPHome

This is a Epaper display with a 2000mAh Lipo and a passive buzzer.
Running parts of my Smoker monitor.

Below a little movie clip with RTTTL sound notification.
(Send from Home Assistant)
B.t.w. RTTTL are those ringtones we used to have. (Ring Tone Text Transfer Language)

Sending from HA

Parts of the ESPHOME Yaml
NOTE: For the time, you need the time integration to get hours:minutes as a sensor!

esphome:
  name: epaperesp32

esp32:
  board: esp32dev
  framework:
    type: arduino

# Enable logging
logger:

# Enable Home Assistant API
api:
  services:
    - service: play_rtttl
      variables:
        song_str: string
      then:
        - rtttl.play:
            rtttl: !lambda 'return song_str;'

output:
  - platform: ledc
    pin: GPIO22
    id: rtttl_out

rtttl:
  output: rtttl_out
  on_finished_playback:
    - logger.log: 'Song ended!'

ota:
  password: "xxxxxxxxxxxxxxxxxxxxxxxxxxx"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Epaperesp32 Fallback Hotspot"
    password: "xxxxxxxxxxxxxxxxx"

captive_portal:

font:
  - file: 'fonts/tahoma.ttf'
    id: font1
    size: 16
  - file: 'fonts/tahoma.ttf'
    id: font2
    size: 32

sensor:
  - platform: adc
    pin: GPIO36
    name: "epaperesp32 Battery voltage"
    id: battery_voltage
    icon: mdi:battery
    device_class: voltage
    attenuation: auto 
    filters:
     - multiply: 3
    update_interval: 60s

text_sensor:
  - platform: homeassistant
    entity_id: sensor.bbqenv
    name: "mystate"
    id: mystate
    internal: true
  - platform: homeassistant
    entity_id: sensor.bbqcore
    name: "mystate1"
    id: mystate1
    internal: true
  - platform: homeassistant
    entity_id: sensor.time
    name: "mytime"
    id: mytime
    internal: true

spi:
  clk_pin: GPIO13
  mosi_pin: GPIO14

binary_sensor:
  - platform: gpio
    pin:
      number: GPIO12
      inverted: true 
      mode:          
        input: true
        pullup: true
    name: "epaperesp32 button"
    filters:
      - delayed_on: 50ms
    on_press:
      - logger.log: "Button pressed"

display:
  - platform: waveshare_epaper
    cs_pin: GPIO15
    dc_pin: GPIO27
    busy_pin: GPIO25
    reset_pin: GPIO26
    model: 2.13in-ttgo
    rotation: 270
    full_update_every: 12
    update_interval: 10s
    lambda: |-
      it.print(0, 0, id(font2), "BBQ Meter V3");
      it.printf( 35, 32, id(font2), "%s", id(mystate).state.c_str());
      it.printf( 155, 32, id(font2), "%s", id(mystate1).state.c_str());

MQTT Notifier over Internet

This is part of a test where my friends and me can have notifications LEDs over the internet.

Using certificate parts from:
Controlling the led will be done using Mattermost webhooks, or slashcommand with custom scripting.
(Mattermost is my own hosted chat server)

I flashed a Wemos with below code:
(Rotary/display/button part removed.)

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <time.h>
#include <PubSubClient.h>
#include <Adafruit_NeoPixel.h>

#define encoderCLK 5   //D1
#define encoderDT 4    //D2
#define rgbled D4       //D4

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(1, rgbled, NEO_RGB + NEO_KHZ400);

int servoAngle = 0;
int crntCLK;
int prvsCLK;

String myString;
char ang[50];


#ifndef SECRET
const char ssid[] = "MYSSID";
const char pass[] = "MYPASS";

#define HOSTNAME "henrimqtt"

const char MQTT_HOST[] = "www.henriaanstoot.nl";
const int MQTT_PORT = 9883;
const char MQTT_USER[] = "xxxxxx"; // leave blank if no credentials used
const char MQTT_PASS[] = "xxxxxx"; // leave blank if no credentials used

const char MQTT_SUB_TOPIC[] = "notification/" HOSTNAME "/in";
const char MQTT_PUB_TOPIC[] = "notification/" HOSTNAME "/out";
const char MQTT_PUB_TOPIC_angle[] = "notification/" HOSTNAME "/send";

#ifdef CHECK_CA_ROOT
static const char digicert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFtTCCA52gAwIBAgIUXEEQRLHhYox8a95YiAYX/wQ/XeMwDQYJKoZIhvcNAQEN
//--------------- SNIP SNIP ... generated cert here
vht8GyCCgCH55Syvy9ls6gCyLjTT2rtllw==
-----END CERTIFICATE-----
)EOF";
    #endif

    #ifdef CHECK_PUB_KEY
    // Extracted by: openssl x509 -pubkey -noout -in ca.crt
    static const char pubkey[] PROGMEM = R"KEY(
    -----BEGIN PUBLIC KEY-----
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxx
    -----END PUBLIC KEY-----
    )KEY";
    #endif

    #ifdef CHECK_FINGERPRINT
        // Extracted by: openssl x509 -fingerprint -in ca.crt
    static const char fp[] PROGMEM = "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD";
    #endif
#endif

//////////////////////////////////////////////////////

#if (defined(CHECK_PUB_KEY) and defined(CHECK_CA_ROOT)) or (defined(CHECK_PUB_KEY) and defined(CHECK_FINGERPRINT)) or (defined(CHECK_FINGERPRINT) and defined(CHECK_CA_ROOT)) or (defined(CHECK_PUB_KEY) and defined(CHECK_CA_ROOT) and defined(CHECK_FINGERPRINT))
  #error "cant have both CHECK_CA_ROOT and CHECK_PUB_KEY enabled"
#endif

BearSSL::WiFiClientSecure net;
PubSubClient client(net);

time_t now;
unsigned long lastMillis = 0;

void mqtt_connect()
{
  while (!client.connected()) {
    Serial.print("Time: ");
    Serial.print(ctime(&now));
    Serial.print("MQTT connecting ... ");
    if (client.connect(HOSTNAME, MQTT_USER, MQTT_PASS)) {
      Serial.println("connected.");
      client.subscribe(MQTT_SUB_TOPIC);
    } else {
      Serial.print("failed, status code =");
      Serial.print(client.state());
      Serial.println(". Try again in 5 seconds.");
      /* Wait 5 seconds before retrying */
      delay(5000);
    }
  }


}

void receivedCallback(char* topic, byte* payload, unsigned int length) {
    //  pixels.clear(); // Set all pixel colors to 'off'
 
  Serial.print("Received [");
  Serial.print(topic);
  Serial.print("]: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
if (!strncmp((char *)payload, "0", length)) {
       pixels.setPixelColor(0, pixels.Color(0, 0, 0));
      pixels.show();   // Send the updated pixel colors to the hardware.
}
if (!strncmp((char *)payload, "1", length)) {
       pixels.setPixelColor(0, pixels.Color(150, 0, 0));
      pixels.show();   // Send the updated pixel colors to the hardware.
}
if (!strncmp((char *)payload, "2", length)) {
       pixels.setPixelColor(0, pixels.Color(0, 0, 150));
      pixels.show();   // Send the updated pixel colors to the hardware.
}
if (!strncmp((char *)payload, "3", length)) {
       pixels.setPixelColor(0, pixels.Color(0, 150, 0));
      pixels.show();   // Send the updated pixel colors to the hardware.
}
}

void setup()
{
  pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)

  pinMode (encoderCLK,INPUT_PULLUP);
  pinMode (encoderDT,INPUT_PULLUP);
  prvsCLK = digitalRead(encoderCLK);
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.print("Attempting to connect to SSID: ");
  Serial.print(ssid);
  WiFi.hostname(HOSTNAME);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("connected!");

  Serial.print("Setting time using SNTP");
  configTime(1 * 3600, 0, "pool.ntp.org", "time.nist.gov");
  now = time(nullptr);
  while (now < 1510592825) {
    delay(500);
    Serial.print(".");
    now = time(nullptr);
  }
  Serial.println("done!");
  struct tm timeinfo;
  gmtime_r(&now, &timeinfo);
  Serial.print("Current time: ");
  Serial.print(asctime(&timeinfo));

  #ifdef CHECK_CA_ROOT
    BearSSL::X509List cert(digicert);
    net.setTrustAnchors(&cert);
  #endif
  #ifdef CHECK_PUB_KEY
    BearSSL::PublicKey key(pubkey);
    net.setKnownKey(&key);
  #endif
  #ifdef CHECK_FINGERPRINT
    net.setFingerprint(fp);
  #endif
  #if (!defined(CHECK_PUB_KEY) and !defined(CHECK_CA_ROOT) and !defined(CHECK_FINGERPRINT))
    net.setInsecure();
  #endif

      
  client.setServer(MQTT_HOST, MQTT_PORT);
  client.setCallback(receivedCallback);
  mqtt_connect();
       pixels.setPixelColor(0, pixels.Color(0, 0, 0));
      pixels.show();   // Send the updated pixel colors to the hardware.

}

void loop()
{
   crntCLK = digitalRead(encoderCLK);

 if (crntCLK != prvsCLK){
      // If the encoderDT state is different than the encoderCLK state then the rotary encoder is rotating counterclockwise
        if (digitalRead(encoderDT) != crntCLK) {
          servoAngle ++;

        }
        else {
          servoAngle --;
         }
         Serial.println(servoAngle);
          String myString = String(servoAngle);
          myString.toCharArray(ang, myString.length() + 1);
          client.publish(MQTT_PUB_TOPIC_angle, ang, false);
 }
  prvsCLK = crntCLK;

  now = time(nullptr);
  if (WiFi.status() != WL_CONNECTED)
  {
    Serial.print("Checking wifi");
    while (WiFi.waitForConnectResult() != WL_CONNECTED)
    {
      WiFi.begin(ssid, pass);
      Serial.print(".");
      delay(10);
    }
    Serial.println("connected");
  }
  else
  {
    if (!client.connected())
    {
      mqtt_connect();
    }
    else
    {
      client.loop();
    }
  }

  if (millis() - lastMillis > 5000) {
    lastMillis = millis();
    client.publish(MQTT_PUB_TOPIC, ctime(&now), false);
  }
}

Last week’s stuff

Update: https://www.henriaanstoot.nl/2024/01/14/hlk-ld2410b-with-a-wemos-mini-d1-v4-connected-to-home-assistant-using-esphome/

Case for presence detector

Update: BBQ watch

Not posted in the past, new version using ESPHOME and a m5stickc

Previous version using a ESP12
A “watch” with core and environment temperature of my smoker with a alarm, and button for timers.

ESP32 dac’s drawing on oscilloscope ( no additional components)

ESP32 in front of scope, two clips for x and y

For above i used sin/cos functions 2:3, which creates Lissajous figures.
See: https://www.henriaanstoot.nl/1992/01/01/oscilloscope-graphics-using-a-amiga-bonus-vectrex/

3 battery operated buttons (no wires needed) to control my shelly dimmer at the dinner table.

left button on, middle steps per 20% and 3rd button off.
(This cheapass button only sends ON commands)

Node red code

[
    {
        "id": "8190a851.8d02b8",
        "type": "mqtt in",
        "z": "44d7a4fb.e41a5c",
        "name": "domoticz-out",
        "topic": "domoticz/out",
        "qos": "0",
        "broker": "8c74c5f6.9a7a48",
        "inputs": 0,
        "x": 190,
        "y": 600,
        "wires": [
            [
                "543a2fa3.af27c",
                "c70d463.da52ab8",
                "ffa2f6be.afe618"
            ]
        ]
    },
    {
        "id": "543a2fa3.af27c",
        "type": "function",
        "z": "44d7a4fb.e41a5c",
        "name": "Filter IDX + nvalue",
        "func": "var varPayload = JSON.parse(msg.payload);\nvar varidx = varPayload.idx;\nvar varnvalue = varPayload.nvalue;\nif(varidx == 2473)\n{\nmsg.payload = {};\nmsg.payload.turn = \"on\";\nmsg.payload.brightness = 50;\nreturn msg;\n}",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 410,
        "y": 600,
        "wires": [
            [
                "d7b0f308db912817"
            ]
        ]
    },
    {
        "id": "c70d463.da52ab8",
        "type": "function",
        "z": "44d7a4fb.e41a5c",
        "name": "Filter IDX + nvalue",
        "func": "var varPayload = JSON.parse(msg.payload);\nvar varidx = varPayload.idx;\nvar varnvalue = varPayload.nvalue;\nif(varidx == 2474)\n{\nmsg.payload = {};\nmsg.payload.turn = \"on\";\nvar count = context.get(\"counter\") || 0;\ncount = (count+1) % 6;\ncontext.set(\"counter\", count);\ncount = count * 20; \nmsg.payload.brightness = count;\nreturn msg;\n}",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 410,
        "y": 680,
        "wires": [
            [
                "d7b0f308db912817"
            ]
        ]
    },
    {
        "id": "ffa2f6be.afe618",
        "type": "function",
        "z": "44d7a4fb.e41a5c",
        "name": "Filter IDX + nvalue",
        "func": "var varPayload = JSON.parse(msg.payload);\nvar varidx = varPayload.idx;\nvar varnvalue = varPayload.nvalue;\nif(varidx == 2475)\n{\nmsg.payload = {};\nmsg.payload.turn = \"off\";\n//msg.payload.brightness = 0;\nreturn msg;\n}",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 410,
        "y": 760,
        "wires": [
            [
                "d7b0f308db912817"
            ]
        ]
    },
    {
        "id": "35f35737.b4f2c8",
        "type": "comment",
        "z": "44d7a4fb.e41a5c",
        "name": "Living Dinner Table Shelly 2024",
        "info": "",
        "x": 250,
        "y": 560,
        "wires": []
    },
    {
        "id": "b080c84e.2c3968",
        "type": "comment",
        "z": "44d7a4fb.e41a5c",
        "name": "butt1 on / (butt2 off)",
        "info": "",
        "x": 510,
        "y": 560,
        "wires": []
    },
    {
        "id": "ac892b87.1c7358",
        "type": "comment",
        "z": "44d7a4fb.e41a5c",
        "name": "butt3 toggle",
        "info": "",
        "x": 390,
        "y": 720,
        "wires": []
    },
    {
        "id": "b5bdbd65.c4e1c",
        "type": "comment",
        "z": "44d7a4fb.e41a5c",
        "name": "butt 2 step dimmer",
        "info": "",
        "x": 410,
        "y": 640,
        "wires": []
    },
    {
        "id": "d7b0f308db912817",
        "type": "mqtt out",
        "z": "44d7a4fb.e41a5c",
        "name": "",
        "topic": "shellies/shellydimmer-D0DF15/light/0/set",
        "qos": "",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "8c74c5f6.9a7a48",
        "x": 860,
        "y": 600,
        "wires": []
    },
    {
        "id": "8c74c5f6.9a7a48",
        "type": "mqtt-broker",
        "name": "MQTTSERVER",
        "broker": "MQTTSERVER",
        "port": "1883",
        "clientid": "",
        "usetls": false,
        "compatmode": true,
        "keepalive": "15",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthPayload": "",
        "closeTopic": "",
        "closePayload": "",
        "willTopic": "",
        "willQos": "0",
        "willPayload": ""
    }
]

Vector graphics on my demo arduino nano.

My configs to set and get domoticz-433Mhz from Home Assistant

I’ve posted about some integrations here:

There are three kinds of 433 connections I’m using:

  • Switches
  • Sensors (read-only)
  • Dimmers

Mqtt Home Assistant Config Yaml

Here are 3 mqtt examples using the Node-Red rewriter (see above post)

mqtt:
 light:    
  - name: "KitchenOutside"
    payload_on: "99"
    payload_off: "0"
    unique_id: "KitchenOutside"
    brightness_scale: "99"
    brightness_state_topic: ha433/kitchenoutside/brightcontrolstate
    brightness_command_topic: ha433/kitchenoutside/brightcontrol
    state_topic: ha433/kitchenoutside/brightcontrolstate
    command_topic: ha433/kitchenoutside/control
    optimistic: false
    on_command_type: brightness
 binary_sensor:
  - name: "AtelierDoor"
    state_topic: "home2/3331/payload"
    value_template: "{{ value_json.nvalue }}"
    off_delay: 5
    payload_off: "0"
 sensor:
  - name: "LivingTemperature"
    state_topic: "home/9999/payload"
    unit_of_measurement: "°C"
    value_template: "{{ value_json.svalue1 }}"
  - name: "LivingHumidity"
    state_topic: "home/9999/payload"
    unit_of_measurement: "%"
    value_template: "{{ value_json.svalue2 }}"

Here is a virtual switch sensor using curl commands

command_line:
  - switch:
      name: PatioSlinger
      command_on: >
        curl "http://domoticz:pass@192.168.1.1:8080/json.htm?type=command&param=switchlight&idx=6&switchcmd=On"
      command_off: >
        curl "http://domoticz:pass@192.168.1.1:8080/json.htm?type=command&param=switchlight&idx=6&switchcmd=Off"
      command_state: > 
        curl "http://domoticz:pass@192.168.1.1:8080/json.htm?type=command&param=getdevices&rid=6" | grep Status | cut -f4 -d\"
      value_template: >
#        "{{ value_json.result[0].Status }}"
        "{{ value_json.result[0].Status == 'On'}}"
      icon: >
        {% if value_json.result[0].Status == 'On' %} mdi:toggle-switch
        {% else %} mdi:toggle-switch-off
        {% endif %}
  - switch:
      name: DoorChimeManual
      command_on: >
        curl "http://domoticz:pass@192.168.1.1:8080/json.htm?type=command&param=switchlight&idx=9999&switchcmd=On"

Nodered mqtt payload rewriter for dimmer
Note: I still need to write the state part

Function code

var idx = 9999;
var bright = msg.payload;
msg.payload = {};
msg.payload = {"command": "switchlight", "idx": idx, "switchcmd": "Set Level", "level": bright};
return msg;

Adding a rotary encoder to Home Assistant to control dimmers using EspHome

Config for mqtt-433 and home assistant entities.
Maybe I’ll add a display to select which dimmer to change.

ESPHome Config for direct communication to a MQTT enabled 443mhz dimmer.

When using GND to the rotary you have to use a pullup entry in your yaml

esphome:
  name: rotarywhite
  friendly_name: RotaryWhite

esp8266:
  board: esp01_1m

# Enable logging
logger:

# Enable Home Assistant API
api:
  encryption:
    key: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="

ota:
  password: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Rotarywhite Fallback Hotspot"
    password: "xxxxxxxxxxxxxxxxxxx"

captive_portal:
    
sensor:
  - platform: rotary_encoder
    name: "WhiteRotaryEncoder"
    id: rotvalue
    min_value: 0
    max_value: 50
    resolution: 1
    pin_a:
      number: GPIO0
      inverted: true
      mode:
        input: true
        pullup: true
    pin_b:
      number: GPIO2
      inverted: true
      mode:
        input: true
        pullup: true
    on_value:    
      - mqtt.publish:
          topic: "ha433/Living5Spots/brightcontrol"
          payload: !lambda |-
              return to_string(id(rotvalue).state);
mqtt:
  discovery: false
  broker: 192.168.1.1
  port: 1883
  discovery_prefix: homeassistant

Config part to change Home Assistant entities.
WARNING YOU HAVE TO CHANGE RIGHTS!

Settings > Addons > EspHome > Configuration
(press configure to change service calls)

sensor:
  - platform: rotary_encoder
    name: "WhiteRotaryEncoder"
    id: rotvalue
    min_value: 0
    max_value: 50
    resolution: 1
    pin_a:
      number: GPIO0
      inverted: true
      mode:
        input: true
        pullup: true
    pin_b:
      number: GPIO2
      inverted: true
      mode:
        input: true
        pullup: true
    on_value:    
      - homeassistant.service:
          service: light.turn_on
          data_template:
                entity_id: light.bedroomdimmer  
                brightness: "{{ brightness_1 | int }}"    
          variables:
              brightness_1: !lambda 'return id(rotvalue).state * 4;'

Home Assistant Speech and More

I made my own Mqtt to speech thingy in the past.
Sending a text to a mqtt topic would be picked up by my domoticz raspberry and using a bash script the topic payload was converted to speech and being played on a connected speaker.

This speaker migrated to my Home Assistant NUC.
So i changed the speech engine.

Beside this migration, i’ve started using the HA voice assistant capabilities.
This was a major impact/project in 2023.

I’m not going to talk about configuring this .. There are many good YT tutorials and forum topics about this.

https://www.home-assistant.io/voice_control/thirteen-usd-voice-remote/

This is the device: a ESP32 pico, Microphone, leds and Speaker are being used for this sound assistant.
(It uses ESPHOME)

Back to the speaker being hooked-up to my HA NUC.

Install the addon PicoTTS (speech synthesis)

configuration.yaml

# Text to speech
tts:
  - platform: picotts
# My part
input_text:
  mqttspeech:
    name: mqttspeech
    initial: ""
    

Then install notified addon

Add a text field to your dashboard …

Home Assistant ESPHome with toggle for interval

Posted because I could not find a good example on the interwebs.

Below creates a virtual HA button which toggles a blinking led.
(button and variables are called eprint for another function, change to something meaningful. )

Home Assistant virtual mqtt switch (configuration.yml)

See switch part

mqtt:
 light:    
  - name: "KitchenOutside"
    payload_on: "99"
    payload_off: "0"
    unique_id: "KitchenOutside"
    brightness_scale: "99"
    brightness_state_topic: ha433/kitchenoutside/brightcontrol
    brightness_command_topic: ha433/kitchenoutside/brightcontrol
    state_topic: ha433/kitchenoutside/brightcontrol
    command_topic: ha433/kitchenoutside/control
    optimistic: false
    on_command_type: brightness
#-----8<-------------snip ########### EXAMPLES light and sensor
 sensor:
  - name: "LivingTemperature"
    state_topic: "home/8461/payload"
    unit_of_measurement: "°C"
    value_template: "{{ value_json.svalue1 }}"
  - name: "LivingHumidity"
    state_topic: "home/8461/payload"
    unit_of_measurement: "%"
    value_template: "{{ value_json.svalue2 }}"
#--------8<--- snip ################################ ONLY PART BELOW NEEDED 
 switch:
    unique_id: esphome_switch
    name: "Esp Home Switch"
    state_topic: "esphome/eprint/tmpstate"
    command_topic: "esphome/eprint/state"
    payload_on: "ON"
    payload_off: "OFF"
    state_on: "ON"
    state_off: "OFF"
    optimistic: false
    qos: 0
    retain: true

ESP Home config for a ESP32

esphome:
  name: lolin32litemqttled
  friendly_name: lolin32litemqttled

esp32:
  board: esp32dev
  framework:
    type: arduino

# Enable logging
logger:

# Enable Home Assistant API
api:
  encryption:
    key: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="

ota:
  password: "xxxxxxxxxxxxxxxxxxxxxxxx"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Lolin32Litemqttled"
    password: "xxxxxxxxxxxxxxxxxxx"

captive_portal:
    
switch:
  - platform: gpio
    pin:
      number: 22
      mode: output
    id: blueLED
  - platform: template
    name: "eprint"
    id: eprint_enable
    optimistic: on

interval:
  - interval: 1000ms
    then:
      if:
        condition:
          switch.is_on: eprint_enable
        then:
          - switch.toggle: blueLED

mqtt:
  broker: 192.168.1.2
  on_message:
  - topic: esphome/eprint/state
    qos: 0
    payload: "OFF"
    then:
      - switch.turn_off: eprint_enable
  - topic: esphome/eprint/state
    qos: 0
    payload: "ON"
    then:
      - switch.turn_off: eprint_enable

Calibrating temperature/humidity with mqtt

Example uses a shelly sensor, which has a offset mode in its new firmware. So below is not needed any more.
But the example can be used for any calibration/adjustments.

I’ve put two examples in the NodeRed function

First the solution

var temperature=msg.payload.tC;
var humidity=msg.payload.tF;
// calc new offset example
// simple offset + 2.3 off real measurement
msg.payload.tC=temperature + 2.3;
// more complex example
// take two measurements (with a big difference)
msg.payload.tF=1.11 * (humidity - 1);
return msg;

First adjustment is plus or minus a value.
Second is more precise when the temperature needs more adjusting

Dots on the red line are measured values
Blue is how it should be

So measured was 2.8 but should be 2
And measured 14.5 but needs to be 15

slope = (14.5-2.8)/(15-2) = 0.9

To get the multiplication factor = 1/0.9 = 1.1111

=(2.8-heightadjust)*1,1111 should give us 2

2/1.1111 = 2.8 – heightadjust

1.8 = 2.8 – heightadjust = 1

So the formula is realhumid = 1,1111 * ( measuredhumid – adjust )

Python Spotify Genre Cube v2

Spotify version

Next to do: Lasercut a wooden cube with better lettering.

Run the python part on a server

and

First export some API credentials

export SPOTIPY_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
export SPOTIPY_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
export SPOTIPY_REDIRECT_URI="http://localhost:8080/callback"

Code below:

from flask import Flask, request, redirect
from requests_oauthlib import OAuth2Session
from requests.auth import HTTPBasicAuth
import requests
import json
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from pprint import pprint
from time import sleep
import spotipy.util as util
import sys
import paho.mqtt.client as mqttClient
import time
import os
import subprocess

Connected = False


broker_address = "MQTTSERVER"
port = 1883


def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to broker")
        global Connected
        Connected =True
    else:
        print("Connection failed")

def on_message(client, userdata, message):
    print (message.payload)
    myurl = 'spotify:playlist:' + str(message.payload.decode())

    results = sp.start_playback(context_uri=myurl, offset={"position": 1})

client = mqttClient.Client("PythonSpotifyGenreCube")
client.on_connect = on_connect
client.on_message = on_message

client.connect(broker_address, port=port,keepalive=60 )
client.loop_start()
time.sleep(4) # Wait for connection setup to complete
client.subscribe('spotify/playlist')
#client.loop_stop()    #Stop loop

#while Connected != True:
#    client.loop()
#    time.sleep(0.1)
#    print("test")
#    client.subscribe('spotify/playlist')



app = Flask(__name__)

AUTH_URL = 'https://accounts.spotify.com/authorize'
TOKEN_URL = 'https://accounts.spotify.com/api/token'
REDIRECT_URI = 'http://localhost:8080/callback'
CLIENT_ID = "xxxxxxxxxxxxxxxxxx"
CLIENT_SECRET = "xxxxxxxxxxxxxxxxxxxxx"
SCOPE = [
    "user-read-email",
    "playlist-read-collaborative"
]

@app.route("/login")
def login():
    spotify = OAuth2Session(CLIENT_ID, scope=SCOPE, redirect_uri=REDIRECT_URI)
    authorization_url, state = spotify.authorization_url(AUTH_URL)
    return redirect(authorization_url)

@app.route("/callback", methods=['GET'])
def callback():
    code = request.args.get('code')
    res = requests.post(TOKEN_URL,
        auth=HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET),
        data={
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': REDIRECT_URI
        })
    return json.dumps(res.json())


username = "fashice"
scope = "user-read-playback-state,user-modify-playback-state,playlist-read-private"
util.prompt_for_user_token(username,scope,client_id='xxxxxxxxxxxxxxxxxxxxx',client_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxx',redirect_uri='http://localhost:8080/callback')

sp = spotipy.Spotify(client_credentials_manager=SpotifyOAuth(scope=scope))

# Shows playing devices
res = sp.devices()
pprint(res)


# Change track
#sp.start_playback(uris=['spotify:track:6gdLoMygxxxxxxxxxxxxxxx'])
#results = sp.start_playback(context_uri=myurl, offset={"position": 1})


## Change volume
#sp.volume(100)
#sleep(2)
#sp.volume(50)
#sleep(2)
#sp.volume(100)
#


playlists = sp.user_playlists(username)

#for playlist in playlists['items']:
#    print(playlist['name'])


playlists = sp.current_user_playlists()
#print (playlists)
for playlist in playlists['items']:
    print(playlist['id'] + ' ' +  playlist['name'])



#if __name__ == '__main__':
#   app.run(port=8080,debug=True)


while Connected != True:
    time.sleep(0.1)
    client.subscribe('spotify/playlist')

try:
    while True:
        time.sleep(1)


except KeyboardInterrupt:
    print ("exiting")
    client.disconnect()
    client.loop_stop()