Category Archives: IOT / Domoticz

Raspberry Zero with display

I’ve installed a headless Raspbian on a Pi Zero with a 2×16 Chars lcd display. As part of the Escape Room over the internet

Using the raspberry imager:
I’ve set the username/password and ssh access in this tool.
For wifi access i’ve placed below file on the SDcard in /boot
(You can do this in the tool, but i want to make this dynamic when connected at a remote site.)
file: wpa_supplicant.conf

country=NL
update_config=1
ctrl_interface=/var/run/wpa_supplicant

network={
 scan_ssid=1
 ssid="MYSSID"
 psk="MYSSIDPASS"
}

ssh into the RPi

sudo raspi-config
Interface options and enable I2C

sudo apt-get install python3-smbus

wget https://gist.githubusercontent.com/DenisFromHR/cc863375a6e19dce359d/raw/36b82e787450d127f5019a40e0a55b08bd43435a/RPi_I2C_driver.py
and 
wget https://gist.githubusercontent.com/DenisFromHR/cc863375a6e19dce359d/raw/36b82e787450d127f5019a40e0a55b08bd43435a/examples.py

For python3 edit the example and put at the top

# requires RPi_I2C_driver.py
import RPi_I2C_driver
from time import *
unichr = chr

Run with 
python3 examples.py
lcd display with i2c backpack
I2C backpack

Below is a mockup session.

Next todo:

  • Add more hardware (like buttons) to the RPI
  • Configure an Accesspoint on this Rpi for other devices to connect to
  • Install a local Mqtt broker, which connects secure to my internet facing broker
Setup example

Started on a mobile over the internet Escape room experiment

I’ve been working on some modular gadgets which can be combined to make a complete puzzle.

I like games like Keep-talking-and-nobody-dies. (Which is a computer game, but you have to play it with multiple persons and a physical “manual” Great fun!)
https://keeptalkinggame.com/

And i like real escape rooms.
There are some puzzle “rooms” you can buy in the game store, it is okay but many are for single use only.

I’ve been following some people on youtube, i saw some great ideas but not a remote over the internet using physical knobs and switches.

This is a RFID reader with an old Amico Esp8266 Arduino. It sends RFID information to the MQTT broker

Some other tools ‘n knobs .. and stuff

I want to use Adhoc Wifi and a Mqtt/Nodered setup which uses a mqtt over the internet to get people (and their knobs) connected

I already got a lot of test schematics

Left part of the “connect the wires puzzle” right a solenoid electrical lock)

Schematic for the MQTT enabled RFID module

ESP8266 <-> RC522
D8            SDA
D5            SCK
D7           MOSI
D6           MISO
GND           GND
D1            RST
3V3           3V3
 

Code

Below will write the RFID id to “rfid/id” and resets this when you remove the tag to “rfid/id = 0”

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#include <MFRC522.h>

#define SS_PIN D8
#define RST_PIN D1

MFRC522 mfrc522(SS_PIN, RST_PIN);
unsigned long cardId = 0;

WiFiClient net;
PubSubClient client(net);

const char* mqtt_server = "MQTTBROKER";
const char* ssid = "MYSSID";
const char* password = "MYWIFIPASSWD";

void setup() {
  SPI.begin();
  mfrc522.PCD_Init();

  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);

  client.setServer(mqtt_server, 1883);
}

void reconnect() {
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    WiFi.begin(ssid, password);
  }

  while (!client.connected()) {
    String clientId = "NodeMCUClient-";
    clientId += String(random(0xffff), HEX);

    if (!client.connect(clientId.c_str(), "rfidclient", "...")) {
      delay(5000);
    }
  }
}

void loop() {
  reconnect();

  if (!mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  if (!mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  cardId = getCardId();

  char buffer[10];
  sprintf(buffer, "%lu", cardId);
  client.publish("rfid/id", buffer);

  uint8_t control = 0x00;

  do {
    control = 0;
    for (int i = 0; i < 3; i++) {
      if (!mfrc522.PICC_IsNewCardPresent()) {
        if (mfrc522.PICC_ReadCardSerial()) {
          control |= 0x16;
        }

        if (mfrc522.PICC_ReadCardSerial()) {
          control |= 0x16;
        }
        control += 0x1;
      }
      control += 0x4;
    }

    delay(0);
  } while (control == 13 || control == 14);

  reconnect();
  client.publish("rfid/id", "0");
  delay(500);

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}

unsigned long getCardId() {
  byte readCard[4];
  for (int i = 0; i < 4; i++) {
    readCard[i] = mfrc522.uid.uidByte[i];
  }

  return (unsigned long)readCard[0] << 24
    | (unsigned long)readCard[1] << 16
    | (unsigned long)readCard[2] << 8
    | (unsigned long)readCard[3];
}

Schematics used for the Solenoid lock

Software is a mqtt example from the internet which toggles a PIN on the arduino.

Magic Mirror no more .. lets reuse the display

I never look in the mirror, so why do i need one?
The mirror foil was already ugly in the corners.
There were bumps.
Never finished a proper interface

This one was made using a touch screen, so there are always fingerprints you could see

I’m going to use the display for an in-house small Escape Room idea i have.

Only the time part still worked, but i could not find the right cables for the touch part. The buttons displayed are meaningless anyway 🙂
Just a mockup

Mirror part was done using a Safety/One way mirror foil.
Cut a part as large as you screen, spray a little water and stick it on.

At some point i displayed Dashticz on there.
Apparently i started playing with a magic mirror setup in 2015, according some timestamps of code on my fileserver.

Migrating some old Sonoff S20 smart plugs

(From ESPEASY to ESPHOME without soldering)

I previously had these smartplugs flashed with EspEasy (I hate cloud enabled devices)
I will post something about flashing these and others.
Maybe … because you can find a lot of information on the internet.
But i’ve used several tools, and made tools for this process.
( Raspberry Zero mobile tool and 3D printed PCB holder for example)

Well ..

I was using these devices in our previous home using curl commands and on a main wifi network.
So i have to change the SSID and migrate from Espeasy to ESPhome so i can use these devices with Home Assistant.

Step 1 : Start in Access Point mode and migrate to my current Wifi Iot network.

Using my phone i made the necessary changes.

Goto HomeAssistant and ESPhome (you need to install this first via HACS)
Press the green + Add device and give it a name

Next select the device type (Sonoff S20 in this case)

Press install and select manual download

Above will compile a binary for the Sonoff device.

Go back to your Sonoff interface and go to the tools tab.
We can reflash the device without connecting this with wires to our computer.

Press Firmware load and select your downloaded binary

Back in HA it should say “online”

Pressing edit gives us a config page. Nothing works .. yet
We need to add some yaml entries.
( use https://esphome.io/devices/sonoff_s20.html )

binary_sensor:
  - platform: gpio
    pin:
      number: GPIO0
      mode:
        input: true
        pullup: true
      inverted: true
    name: "Sonoff S20 Button"
  - platform: status
    name: "Sonoff S20 Status"
  - platform: gpio
    pin: GPIO2
    name: "Sonoff S20 Sensor"


switch:
  - platform: gpio
    name: "Sonoff S20 Relay"
    pin: GPIO12

output:
  # Register the green LED as a dimmable output ....
  - platform: esp8266_pwm
    id: s20_green_led
    pin:
      number: GPIO13
      inverted: true

light:
  # ... and then make a light out of it.
  - platform: monochromatic
    name: "Sonoff S20 Green LED"
    output: s20_green_led

Now press install

Now we can use wirelessly to upload the config

After this the device can be discovered by HA

Click add, and use the encryption key found in the yaml config to add

Success!

Shelly alarm button

For a while i’ve been using the wireless shelly button for all kinds of notifications.
Most of the time i like to use it as a kind of alarm/need-help-now button.

The f*ckin’ awesome button i’m talking about (pictured above) is a small (45x45mm 16mm height) button, which can connect to your wifi and send MQTT messages.
It even has a strap thingy to attach it to your keychain,

Four types of messages:

  • short press
  • 2x short presses
  • 3x short presses
  • and long press

When using pushover, you can push alarm and messages to your android (even overriding mute/silent if you configure it that way!)

Configuring the button:
https://www.shelly.cloud/documents/user_guide/shelly_button_1.pdf

Configuring pushover:
https://www.npmjs.com/package/node-red-node-pushover

My node red config:

Switch node

[
    {
        "id": "abb6a4fea5021683",
        "type": "mqtt in",
        "z": "458ff8a6.218fa8",
        "name": "",
        "topic": "shellies/shellybutton1-11CDAC2C21D3/input_event/0",
        "qos": "2",
        "datatype": "auto",
        "broker": "8c74c5f6.9a7a48",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 320,
        "y": 760,
        "wires": [
            [
                "bebce75c2be0b54d"
            ]
        ]
    },
    {
        "id": "8eac36b9c194977b",
        "type": "comment",
        "z": "458ff8a6.218fa8",
        "name": "Shelly Button",
        "info": "",
        "x": 200,
        "y": 720,
        "wires": []
    },
    {
        "id": "699c63fede80052b",
        "type": "debug",
        "z": "458ff8a6.218fa8",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "statusVal": "",
        "statusType": "auto",
        "x": 890,
        "y": 700,
        "wires": []
    },
    {
        "id": "604ae0babdcf3929",
        "type": "switch",
        "z": "458ff8a6.218fa8",
        "name": "",
        "property": "payload.event",
        "propertyType": "msg",
        "rules": [
            {
                "t": "eq",
                "v": "S",
                "vt": "str"
            },
            {
                "t": "eq",
                "v": "SS",
                "vt": "str"
            },
            {
                "t": "eq",
                "v": "SSS",
                "vt": "str"
            },
            {
                "t": "eq",
                "v": "L",
                "vt": "str"
            }
        ],
        "checkall": "true",
        "repair": false,
        "outputs": 4,
        "x": 690,
        "y": 700,
        "wires": [
            [
                "699c63fede80052b",
                "5f289f050b9eea26"
            ],
            [
                "e895ce98af0a9c35"
            ],
            [
                "50c9c06fc3dbdcdd"
            ],
            [
                "06efa30e61695599"
            ]
        ]
    },
    {
        "id": "e895ce98af0a9c35",
        "type": "debug",
        "z": "458ff8a6.218fa8",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "statusVal": "",
        "statusType": "auto",
        "x": 890,
        "y": 760,
        "wires": []
    },
    {
        "id": "50c9c06fc3dbdcdd",
        "type": "debug",
        "z": "458ff8a6.218fa8",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "statusVal": "",
        "statusType": "auto",
        "x": 890,
        "y": 820,
        "wires": []
    },
    {
        "id": "06efa30e61695599",
        "type": "debug",
        "z": "458ff8a6.218fa8",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "statusVal": "",
        "statusType": "auto",
        "x": 890,
        "y": 880,
        "wires": []
    },
    {
        "id": "bebce75c2be0b54d",
        "type": "json",
        "z": "458ff8a6.218fa8",
        "name": "",
        "property": "payload",
        "action": "",
        "pretty": false,
        "x": 600,
        "y": 780,
        "wires": [
            [
                "604ae0babdcf3929",
                "699c63fede80052b"
            ]
        ]
    },
    {
        "id": "5f289f050b9eea26",
        "type": "pushover",
        "z": "458ff8a6.218fa8",
        "name": "",
        "device": "",
        "title": "Alarm",
        "priority": "2",
        "sound": "persistent",
        "url": "",
        "url_title": "",
        "html": false,
        "x": 1150,
        "y": 640,
        "wires": []
    },
    {
        "id": "8c74c5f6.9a7a48",
        "type": "mqtt-broker",
        "name": "MQTTBROKER",
        "broker": "MQTTBROKER",
        "port": "1883",
        "clientid": "",
        "usetls": false,
        "compatmode": true,
        "keepalive": "15",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthPayload": "",
        "closeTopic": "",
        "closePayload": "",
        "willTopic": "",
        "willQos": "0",
        "willPayload": ""
    }
]

Domoticz + NodeRed + HomeAssistant MQTT

UPDATE 20240122 : below

I’ve got my RFXCOM connected to my Domoticz, and not connected to my HA.

RFXCOM 433 Mhz

To have the changes of my IOT devices being known to HomeAssistant I wanted to use mqtt.

Domoticz writes the mqtt topic (payload) like this
(topic: domoticz/out)

{
	"Battery" : 100,
	"LastUpdate" : "2022-11-17 18:21:59",
	"RSSI" : 6,
	"description" : "",
	"dtype" : "Temp + Humidity",
	"hwid" : "4",
	"id" : "230E",
	"idx" : 8461,
	"name" : "Living Temp/Hum",
	"nvalue" : 0,
	"stype" : "Cresta, TFA TS34C",
	"svalue1" : "20.0",
	"svalue2" : "60",
	"svalue3" : "1",
	"unit" : 1
}

So you can’t see which device it is by the topic name, the idx is in the json (8461)

To get this device ( a temperature sensor) into HA using mqtt i rewrote the mqtt topic using NodeRed

Temperature Humidity Sensor

NodeRed flow

[
    {
        "id": "836cc419ddb2ca2b",
        "type": "mqtt in",
        "z": "cfb00976f06591d6",
        "name": "",
        "topic": "domoticz/out/#",
        "qos": "2",
        "datatype": "auto-detect",
        "broker": "8c74c5f6.9a7a48",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 200,
        "y": 140,
        "wires": [
            [
                "dbe628e18027a287"
            ]
        ]
    },
    {
        "id": "a6cb517fd1cc9987",
        "type": "mqtt out",
        "z": "cfb00976f06591d6",
        "name": "",
        "topic": "",
        "qos": "",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "8c74c5f6.9a7a48",
        "x": 870,
        "y": 140,
        "wires": []
    },
    {
        "id": "dbe628e18027a287",
        "type": "function",
        "z": "cfb00976f06591d6",
        "name": "MQTT REWRITE",
        "func": "var varidx = msg.payload.idx;\nmsg.topic = \"home/\"+varidx+\"/payload\";\nreturn msg;\n",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 570,
        "y": 140,
        "wires": [
            [
                "a6cb517fd1cc9987"
            ]
        ]
    },
    {
        "id": "8c74c5f6.9a7a48",
        "type": "mqtt-broker",
        "name": "MQTTSERVERIP",
        "broker": "MQTTSERVERIP",
        "port": "1883",
        "clientid": "",
        "usetls": false,
        "compatmode": true,
        "keepalive": "15",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthPayload": "",
        "closeTopic": "",
        "closePayload": "",
        "willTopic": "",
        "willQos": "0",
        "willPayload": ""
    }
]

The function node code ( rewrites the mqtt topic)

var varidx = msg.payload.idx;
msg.topic = "home/"+varidx+"/payload";
return msg;

Now we have a idx separated payload “home/IDX/payload”
(The other entries svalue/nvalue are from testing.

Adding the MQTT entries to HomeAssistant configuration.conf

mqtt:
 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 }}"

Now i can add the card to the dashboard.

This should now be a generic mqtt translator

A quick update:

Adding a motion sensor:

Home Assistant
  - name: "LivingMotion"
    state_topic: "home/45/payload"
    value_template: "{{ value_json.nvalue }}"

Add sensors to be reset to the switch node

[
    {
        "id": "836cc419ddb2ca2b",
        "type": "mqtt in",
        "z": "cfb00976f06591d6",
        "name": "",
        "topic": "domoticz/out/#",
        "qos": "2",
        "datatype": "auto-detect",
        "broker": "8c74c5f6.9a7a48",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 200,
        "y": 140,
        "wires": [
            [
                "dbe628e18027a287",
                "768bb6e4b6731436"
            ]
        ]
    },
    {
        "id": "a6cb517fd1cc9987",
        "type": "mqtt out",
        "z": "cfb00976f06591d6",
        "name": "",
        "topic": "",
        "qos": "",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "8c74c5f6.9a7a48",
        "x": 870,
        "y": 140,
        "wires": []
    },
    {
        "id": "dbe628e18027a287",
        "type": "function",
        "z": "cfb00976f06591d6",
        "name": "MQTT REWRITE",
        "func": "var varidx = msg.payload.idx;\nmsg.topic = \"home/\"+varidx+\"/payload\";\nreturn msg;\n",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 570,
        "y": 140,
        "wires": [
            [
                "a6cb517fd1cc9987"
            ]
        ]
    },
    {
        "id": "768bb6e4b6731436",
        "type": "switch",
        "z": "cfb00976f06591d6",
        "name": "",
        "property": "payload.idx",
        "propertyType": "msg",
        "rules": [
            {
                "t": "eq",
                "v": "45",
                "vt": "str"
            }
        ],
        "checkall": "true",
        "repair": false,
        "outputs": 1,
        "x": 330,
        "y": 260,
        "wires": [
            [
                "e46fed76a596a719"
            ]
        ]
    },
    {
        "id": "e46fed76a596a719",
        "type": "delay",
        "z": "cfb00976f06591d6",
        "name": "",
        "pauseType": "delay",
        "timeout": "5",
        "timeoutUnits": "seconds",
        "rate": "1",
        "nbRateUnits": "1",
        "rateUnits": "second",
        "randomFirst": "1",
        "randomLast": "5",
        "randomUnits": "seconds",
        "drop": false,
        "allowrate": false,
        "outputs": 1,
        "x": 500,
        "y": 260,
        "wires": [
            [
                "3f7eeffc8d066de3"
            ]
        ]
    },
    {
        "id": "3f7eeffc8d066de3",
        "type": "function",
        "z": "cfb00976f06591d6",
        "name": "nvalue 0",
        "func": "msg.payload.nvalue = 0;\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 700,
        "y": 260,
        "wires": [
            [
                "dbe628e18027a287"
            ]
        ]
    },
    {
        "id": "8c74c5f6.9a7a48",
        "type": "mqtt-broker",
        "name": "MQTTIP",
        "broker": "MQTTIP",
        "port": "1883",
        "clientid": "",
        "usetls": false,
        "compatmode": true,
        "keepalive": "15",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthPayload": "",
        "closeTopic": "",
        "closePayload": "",
        "willTopic": "",
        "willQos": "0",
        "willPayload": ""
    }
]

UPDATE 20240122

I’m using domoticz as a 433->mqtt bridge, and some virtual devices i can toggle with curl (bash scripts)

I needed to make a custom 433 door sensor in Home Assistant with toggles to OFF after a few seconds. (There is NO off signal in this cheap sensor i’m using)

I’m changing the payload complete, to have a payload which matches the device class for door: (state with on/off)
It was nvalue = 0/1

(Whenever the IDX changes, I only have to update this Nodered part)
HA won’t notice the change.

var nvalue = msg.payload.nvalue;
msg.payload = {};
if(nvalue == 1)
{
msg.payload.state = "ON";
return msg;
} 

AND after 5 seconds

msg.payload = {};
msg.payload.state = "OFF";
return msg;

Node-RED Deploy
Export nodes
Export
[
    {
        "id": "d8a1af40d14307a9",
        "type": "mqtt in",
        "z": "a8ec6104.cb08c",
        "name": "",
        "topic": "home/35/payload",
        "qos": "2",
        "datatype": "auto-detect",
        "broker": "8c74c5f6.9a7a48",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 220,
        "y": 720,
        "wires": [
            [
                "ac3f66d770bb8f56"
            ]
        ]
    },
    {
        "id": "31cb1ca9e4060710",
        "type": "delay",
        "z": "a8ec6104.cb08c",
        "name": "",
        "pauseType": "delay",
        "timeout": "5",
        "timeoutUnits": "seconds",
        "rate": "1",
        "nbRateUnits": "1",
        "rateUnits": "second",
        "randomFirst": "1",
        "randomLast": "5",
        "randomUnits": "seconds",
        "drop": false,
        "allowrate": false,
        "outputs": 1,
        "x": 660,
        "y": 760,
        "wires": [
            [
                "dbf50e2146f5e631"
            ]
        ]
    },
    {
        "id": "96d60ca0976c555c",
        "type": "mqtt out",
        "z": "a8ec6104.cb08c",
        "name": "",
        "topic": "home/frontdoor/payload",
        "qos": "",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "8c74c5f6.9a7a48",
        "x": 1010,
        "y": 720,
        "wires": []
    },
    {
        "id": "ac3f66d770bb8f56",
        "type": "function",
        "z": "a8ec6104.cb08c",
        "name": "If open",
        "func": "var nvalue = msg.payload.nvalue;\nmsg.payload = {};\nif(nvalue == 1)\n{\nmsg.payload.state = \"ON\";\nreturn msg;\n} \n",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 490,
        "y": 720,
        "wires": [
            [
                "31cb1ca9e4060710",
                "96d60ca0976c555c"
            ]
        ]
    },
    {
        "id": "dbf50e2146f5e631",
        "type": "function",
        "z": "a8ec6104.cb08c",
        "name": "Send Close",
        "func": "msg.payload = {};\nmsg.payload.state = \"OFF\";\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 810,
        "y": 760,
        "wires": [
            [
                "96d60ca0976c555c"
            ]
        ]
    },
    {
        "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": ""
    }
]

HA Part : Instead of the generic setup above (Old post part)

mqtt:
 binary_sensor:
  - name: "FrontDoor"
    state_topic: "home/frontdoor/payload"
    value_template: "{{ value_json.state }}"
    device_class: door

Radar module RCWL-0516 with MQTT

RCWL-0516 module (radar)

Last year i was playing with this radar module also, but today i made a version with MQTT and a linux client.
(There is a project on the internet which uses a HC-SR04, and a arduino connected to the Laptop. This setup is more sensitive and no need for a usb thinghy.)

HC-SR04 module (ultrasound)

Last years version, using a micro transformer and a ESP-12

When using MQTT i can integrate this in HomeAssistant, Domoticz, NodeRed and more.
But i’ve written a python script which runs on my Laptop.
For example i can: Kill vlc, change to my work desktop, stop sound output and lock the screen. (everything you can script)

I wanted to have a “mobile” version of the sensor so i can place it anywhere. (Frontdoor, gardengate, candydrawer 🙂 )

These modules are very cheap, but do their job well!

I’ve used a Wroom ESP32 and a BattBorg together with the module, that’s it.

Simplified schematic (without the battborg)

I’m using PIN34 as an analog input.

Radar module pins:

  • CDS not used
  • VIN 5V power
  • OUT 0-3.3V signal (analog)
  • GND
  • 3v3 not used

Arduino sketch

#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>

const char* ssid = "MYSSID";
const char* password = "MYPASS";
const char* mqtt_server = "IP-MQTT-SERVER";
const char* mqtt_username = "";
const char* mqtt_password = "";
const char* clientID = "radar";

const int tiltPin = 34;
int tiltState = 0;    
int previousState = 0;   

WiFiClient espClient;

PubSubClient client(espClient);

String translateEncryptionType(wifi_auth_mode_t encryptionType) {
 
  switch (encryptionType) {
    case (WIFI_AUTH_OPEN):
      return "Open";
    case (WIFI_AUTH_WEP):
      return "WEP";
    case (WIFI_AUTH_WPA_PSK):
      return "WPA_PSK";
    case (WIFI_AUTH_WPA2_PSK):
      return "WPA2_PSK";
    case (WIFI_AUTH_WPA_WPA2_PSK):
      return "WPA_WPA2_PSK";
    case (WIFI_AUTH_WPA2_ENTERPRISE):
      return "WPA2_ENTERPRISE";
  }
}
 
void scanNetworks() {
   int numberOfNetworks = WiFi.scanNetworks();
   Serial.print("Number of networks found: ");
  Serial.println(numberOfNetworks);
   for (int i = 0; i < numberOfNetworks; i++) {
 
    Serial.print("Network name: ");
    Serial.println(WiFi.SSID(i));
 
    Serial.print("Signal strength: ");
    Serial.println(WiFi.RSSI(i));
 
    Serial.print("MAC address: ");
    Serial.println(WiFi.BSSIDstr(i));
 
    Serial.print("Encryption type: ");
    String encryptionTypeDescription = translateEncryptionType(WiFi.encryptionType(i));
    Serial.println(encryptionTypeDescription);
    Serial.println("-----------------------");
 
  }
}
 
void connectToNetwork() {
  WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Establishing connection to WiFi..");
  }
   Serial.println("Connected to network");
 }

void reconnect() {
  while (!client.connected()) {
    if (client.connect(clientID, mqtt_username, mqtt_password)) {
    } else {
      delay(2000);
    }
  }
}
void setup()
{
  {
    Serial.begin(115200);
    scanNetworks();
    connectToNetwork();
    Serial.println(WiFi.macAddress());
    Serial.println(WiFi.localIP());
    client.setServer(mqtt_server, 1883);
    pinMode(tiltPin, INPUT);
  }
}
void loop() {
  tiltState = analogRead(tiltPin);
    if (tiltState < 3048) {
      client.publish("radar/state", "0"); //
    } else {
      client.publish("radar/state", "1"); //
    }
     delay(100);
   {
    if (!client.connected()) {
      reconnect();
    }
    client.loop();
  }
}

Lockscreen!

Below shows the speed of detection, and sending though the network

Python script which does a lock-screen using XDOTOOL

from paho.mqtt import client as mqtt_client
import subprocess
import time

broker = 'MQTT-SERVER'
port = 1883
topic = "radar/state"
client_id = "radarclient"

def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        state = msg.payload.decode()
        print (state)
        if state == "1":
            subprocess.Popen(["xdotool","key","Super_L+l"])
            time.sleep(30)


    client.subscribe(topic)
    client.on_message = on_message

def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()

if __name__ == '__main__':
    run()

change
subprocess.Popen([“xdotool”,”key”,”Super_L+l”])
into
subprocess.Popen([“switchdesktop”])
to run a script named switchdesktop

#!/bin/bash
# This is the switchdesktop script, it goes to the next screen using winows-page-down combo
xdotool key "Super_L+Page_Down"

Todo:

3D print a case
Make a version which becomes a Access Point.
Then make another arduino setup which controls my Nikon.
So it can act like a wildcam (offline)

Something like below, using a optocoupler ( i still got some leftovers from my doorbell to gpio-pin project.)

Home Assistant/NodeRed update

Upgraded the 2nd (Main) nodered machine to 3.0
Now the node-red-contrib-home-assistant-websocket nodes work again.

Also updated HA, and added some iframes using below.
The HA update broke my mqtt lighting due to changes in the code.

Below also in the example some iframe entries.
( When adding grafana, you need to change grafana.ini

allow_embedding = true

mqtt:
 broker: mqttbrokerserver <--- still errors on this part, 
 discovery: true   <--- but where to configure?
 light:                             <--- Moved this under mqtt
  - name: "KitchenOutside"          <--- added a dash
    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

panel_iframe:                     <--- iframes added
  nodered:
    title: "NodeRed"
    url: "http://noderedserver:1880/"
    icon: si:nodered
    require_admin: true
  domoticz:
    title: "Domoticz"
    url: "http://domoticzserver:8080/"
    icon: si:homeadvisor
    require_admin: true
    
influxdb:
    host: influxserver
    port: 8086
    database: homeassistant
    max_retries: 3
    default_measurement: state <--- changed this
    

HomeAssistant add long-lived access token:

  • Click you profile icon bottom right
  • Scroll all the way down and press create token

Node-red

Add a HA node to a flow, double click and add a server with the little pencil

Base URL is important, you can’t just add http://internalip:port
Use a the URL configured in HA (config/network)

Home Assistant and 433 Dimmers

Getting 433Mhz dimmers working under HA is a pain in the *ss.

After moving my Rfxcom from domoticz to HA, there was still no good way to add dimmers.
I’ve tried adding switches and migrating them to lights, but it didn’t work.

So i took another approach.

Domoticz has a good 433 to mqtt plugin. So i used NodeRed to talk to HA and Domoticz via MQTT.

Rfxcom 433Mhz

Domoticz

MQTT gateway setup

Home Assistant

/config/configuration.yaml

light:    
  - platform: mqtt
    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
  - platform: mqtt
    name: "Living5Spots"
    payload_on: "30"
    payload_off: "0"
    unique_id: "Living5Spots"
    brightness_scale: "30"
    brightness_state_topic: ha433/Living5Spots/brightcontrol
    brightness_command_topic: ha433/Living5Spots/brightcontrol
    state_topic: ha433/Living5Spots/brightcontrol
    command_topic: ha433/Living5Spots/control
    optimistic: false
    on_command_type: brightness

Node Red

Flow

Node-RED Deploy
Search flows
Node	
"d4aab6722750908c"
Type	function
show more 
Export nodes
Export
[
    {
        "id": "31dba0859e04acb4",
        "type": "mqtt in",
        "z": "a49c5bcd66c12a46",
        "name": "",
        "topic": "ha433/kitchenoutside/brightcontrol",
        "qos": "2",
        "datatype": "auto",
        "broker": "8c74c5f6.9a7a48",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 330,
        "y": 160,
        "wires": [
            [
                "e2501f2b6e2ab43d"
            ]
        ]
    },
    {
        "id": "e2501f2b6e2ab43d",
        "type": "function",
        "z": "a49c5bcd66c12a46",
        "name": "Dimmer function",
        "func": "var idx = 9735;\nvar bright = msg.payload;\nmsg.payload = {};\nmsg.payload = {\"command\": \"switchlight\", \"idx\": idx, \"switchcmd\": \"Set Level\", \"level\": bright};\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 690,
        "y": 160,
        "wires": [
            [
                "5f0314b0950d24c0"
            ]
        ]
    },
    {
        "id": "5f0314b0950d24c0",
        "type": "mqtt out",
        "z": "a49c5bcd66c12a46",
        "name": "",
        "topic": "domoticz2/in",
        "qos": "",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "8c74c5f6.9a7a48",
        "x": 970,
        "y": 160,
        "wires": []
    },
    {
        "id": "95eb4d0ed97fdefb",
        "type": "mqtt in",
        "z": "a49c5bcd66c12a46",
        "name": "",
        "topic": "ha433/kitchenoutside/control",
        "qos": "2",
        "datatype": "auto",
        "broker": "8c74c5f6.9a7a48",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 320,
        "y": 220,
        "wires": [
            [
                "d4aab6722750908c"
            ]
        ]
    },
    {
        "id": "d4aab6722750908c",
        "type": "function",
        "z": "a49c5bcd66c12a46",
        "name": "Off function",
        "func": "var idx = 9735;\nvar bright = 0;\nmsg.payload = {};\nmsg.payload = {\"command\": \"switchlight\", \"idx\": idx, \"switchcmd\": \"Set Level\", \"level\": bright};\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 670,
        "y": 220,
        "wires": [
            [
                "5f0314b0950d24c0"
            ]
        ]
    },
    {
        "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": ""
    }
]
Mqtt Broker output

So …. this works, and i have now a generic mqtt “router”

Update: Below works now

Not much new

Last days .. welllll doing al kinds of stuff.

Composite video print designed and ordered from china.

Changed some vlans in my network.
I need to think of a way to extract/migrate domoticz 433 info into a new instance.
For example .. i’ve got some instances in my device list which are only being controlled by domoticz, there is no remote i can reuse.

Tried welding again, because i could not do it for a long time, i noticed i have to practice again after 2 years.
(I’ve got a dedicated power outlet outside now .. 🙂

Last 8mm films work done. (Converted all of my dad’s old 8mm reels)

Designed a hidden remote cabinet, holding remotes out of sight for the occasions when automation doesn’t work.

Designed also a wooden wall with hidden cabinets in our bedroom.

Repaired a Gardena Leafblower .. again!