Contents
Shelly is not a hub for third-party sensors. The sensor is not added as a device in the Shelly app. The way to do it is a script on a Shelly relay: it receives presence over MQTT and switches the relay as long as someone is in the room, or, if you set it up that way, as long as a certain detection zone is occupied (e.g. reading light above the sofa). The sensor reports every change immediately, and the relay switches without delay. If you like, a virtual component on the Shelly additionally shows “present/absent” (not on Gen2 Plus devices).
Without an MQTT broker, there is a second version of the script that polls the sensor every 3 seconds over HTTP (see Without a broker).
Replace the placeholders in this guide with your own values:
| Placeholder | Meaning |
|---|---|
<Hauptthema> |
what is entered on the sensor under Connections → Main topic |
<ZONE1> |
Name of a detection zone as it appears in the MQTT topic: in capital letters (the HTTP version needs the name exactly as entered) |
<Adresse des Brokers>, <Port>
|
Name or IP address and port of the broker, the same as on the sensor (usually 1883) |
<IP des Shelly> |
IP address of the Shelly |
<IP des Sensors>, <Login>, <Passwort>
|
IP address and access data of the sensor, only for the HTTP version |
Requirements
- A Shelly device with relay and scripts: Gen2 (Plus and Pro), Gen3, Gen4. Not suitable: Gen1 and the Shelly Wall Display (no scripts).
- For the display as a virtual component, additionally: Gen3, Gen4 and the Pro devices of Gen2.
- Current firmware on the Shelly.
- An MQTT broker on the network (e.g. Mosquitto). A Shelly is not a broker. Without a broker, the HTTP version remains.
- KL MZ multi-zone presence sensor with firmware 1.4.3 or newer on the same network as the Shelly.
Setting up the sensor
-
If the relay is to follow a detection zone: name the zone beforehand under Zones → Zone names (short, only letters, digits and
_, no spaces or umlauts, e.g.Sofa) and do not rename it afterwards. The name is part of the script. -
Enter under Connections:
Field Value Connection type MQTT BrokerServer, port Address and port of the broker Main topic only letters, digits and _Home Assistant off -
How long the relay stays on after the last detection is determined by the sensor's timeout (main page, Room timeout or Timeout per zone).
Setup
-
Open the Shelly's web interface (
http://<IP des Shelly>). -
Connect the Shelly to the same broker as the sensor. Enter the following under the MQTT settings and then restart the Shelly:
Setting Value Enable MQTT ( enable)on Server ( server)<Adresse des Brokers>:<Port>User / password ( user,pass)only if the broker requires them -
Scripts → Create script, enter a name (e.g.
anwesenheit), Create. -
Paste in this code and adjust the lines marked with
<<<:// SENVOLON multi-zone presence sensor KL MZ -> Shelly (MQTT) let TOPIC = "stat/<Hauptthema>/PRESENCE"; // <<< ANPASSEN; fuer eine Zone: "stat/<Hauptthema>/ZONES/<ZONE1>" let SWITCH_ID = 0; // <<< Relais, das der Anwesenheit folgt; -1 = keins schalten let BOOLEAN_ID = -1; // <<< optional: ID der virtuellen Komponente (z. B. 200); -1 = keine let shown = BOOLEAN_ID >= 0 ? Virtual.getHandle("boolean:" + BOOLEAN_ID) : null; let last = null; function onMessage(topic, message) { let p; if (message === "True") p = true; else if (message === "False") p = false; else if (message === "") p = false; // zone area deleted: free else return; if (p === last) return; last = p; console.log(topic, p); if (SWITCH_ID >= 0) Shelly.call("Switch.Set", { id: SWITCH_ID, on: p }); if (shown) shown.setValue(p); } if (BOOLEAN_ID >= 0 && !shown) console.log("Virtuelle Komponente boolean:" + BOOLEAN_ID + " fehlt"); MQTT.subscribe(TOPIC, onMessage);Setting in the code Value TOPIC(whole room)stat/<Hauptthema>/PRESENCETOPIC(one detection zone)stat/<Hauptthema>/ZONES/<ZONE1>(zone name in capital letters, e.g.stat/<Hauptthema>/ZONES/SOFA)SWITCH_ID0for the first relay,1for the second …,-1= switch nothingBOOLEAN_ID-1, or the number of the virtual component (see “Optional”) -
Save, then Start. In the script list, switch on Run on startup so the script survives a restart of the Shelly.
The sensor sends presence as retained. The script therefore gets the last value immediately at startup. For several zones, create a script of its own for each zone, each with its own TOPIC and its own relay.
Quick test
- After the start, the console below the editor shows the topic with
trueorfalse, e.g.stat/<Hauptthema>/PRESENCE trueorstat/<Hauptthema>/ZONES/SOFA true. The relay is set accordingly. - Leave the room or the zone: after the sensor's timeout,
… falseappears and the relay switches off. - If nothing appears after the start: check whether the Shelly and the sensor are on the same broker and whether
TOPICis exactly right (main topic, zone name in capital letters).
Without a broker: HTTP version
This version does not need a broker. It polls the sensor every 3 seconds, so the relay switches up to 3 seconds later. The sensor needs a fixed IP address (permanently assign the address in the router). The MQTT settings on the sensor and the Shelly are not needed.
Check that http://<IP des Sensors>/measurements shows a line like this in the browser:
{"presence": true, "detection": 1, "zones": {"Sofa": true}, "temperature": 21.5, "pressure": 1014.6, "humidity": 49.9, "brightness": 184.6}
Leave Authentication under System switched off, or append the access data to the address: …/measurements?login=<Login>&password=<Passwort>.
Create the script as above (steps 3 to 5), but with this code:
// SENVOLON multi-zone presence sensor KL MZ -> Shelly (HTTP)
let SENSOR_URL = "http://<IP des Sensors>/measurements"; // <<< ANPASSEN: IP des Sensors
let ZONE = ""; // <<< "" = ganzer Raum; sonst Name der Erkennungszone, z. B. "Sofa"
let SWITCH_ID = 0; // <<< Relais, das der Anwesenheit folgt; -1 = keins schalten
let BOOLEAN_ID = -1; // <<< optional: ID der virtuellen Komponente (z. B. 200); -1 = keine
let INTERVAL_S = 3; // Abfrage alle 3 s
let shown = BOOLEAN_ID >= 0 ? Virtual.getHandle("boolean:" + BOOLEAN_ID) : null;
let last = null;
let busy = false;
function apply(p) {
if (p === last) return;
last = p;
console.log(ZONE === "" ? "Raum" : "Zone " + ZONE, p);
if (SWITCH_ID >= 0) Shelly.call("Switch.Set", { id: SWITCH_ID, on: p });
if (shown) shown.setValue(p);
}
function onReply(result, error_code, error_message) {
busy = false;
if (error_code !== 0 || !result || result.code !== 200) {
console.log("Sensor nicht erreichbar:", error_code, error_message, result ? result.code : "");
return;
}
let d;
try {
d = JSON.parse(result.body);
} catch (e) {
console.log("Antwort ist kein JSON");
return;
}
let p = ZONE === "" ? d.presence : (d.zones ? d.zones[ZONE] : undefined);
if (typeof p !== "boolean") {
console.log(ZONE === "" ? "Keine Anwesenheit in der Antwort" : "Zone " + ZONE + " nicht in der Antwort");
return;
}
apply(p);
}
function poll() {
if (busy) return;
busy = true;
Shelly.call("HTTP.GET", { url: SENSOR_URL, timeout: 2 }, onReply);
}
if (BOOLEAN_ID >= 0 && !shown) console.log("Virtuelle Komponente boolean:" + BOOLEAN_ID + " fehlt");
Timer.set(INTERVAL_S * 1000, true, poll);
poll();
| Setting in the code | Value |
|---|---|
SENSOR_URL |
http://<IP des Sensors>/measurements |
ZONE |
"" = presence in the whole room, otherwise the name of the detection zone exactly as entered on the sensor, e.g. "Sofa"
|
SWITCH_ID |
0 for the first relay, 1 for the second …, -1 = switch nothing |
BOOLEAN_ID |
-1, or the number of the virtual component (see “Optional”) |
After the start, the console shows Raum true (or Zone Sofa true) or … false. If it says “Sensor nicht erreichbar” there: check the IP address and, if authentication is switched on at the sensor, the access data in the address. If it says “Zone … nicht in der Antwort” there: check the spelling of the zone name and whether an area has been drawn for the zone on the sensor.
Optional
Display on the Shelly (virtual component, not Gen2 Plus): create a virtual component of the type Boolean. If you cannot find that option in the web interface, this call in the browser creates it:
http://<IP des Shelly>/rpc/Virtual.Add?type="boolean"&config={"name":"Anwesenheit"}
The response gives the number of the component, {"id": 200} when created for the first time. Enter this number in the script at BOOLEAN_ID, save and restart the script.
Limitations
- Presence is not a device of its own in the Shelly app, but a relay or a value on the Shelly device on which the script runs.
- The script only evaluates presence or one zone. It does not take over the number of people or the sensor's measured values, and it does not change the sensor's settings.
- The script only switches when presence changes. If you switch the relay by hand, it stays that way until the next change.
- If the sensor fails, the relay stays as it is, even when switched on. There is no “unreachable” indicator, only the line in the console.
-
Zone names: if you rename the zone on the sensor, the script no longer finds it. Enter the new name in the script. The factory name
Detection 1is in the MQTT topic with a space (DETECTION 1). Therefore rename the zone beforehand. - If MQTT is off on the Shelly, the script aborts. Switch MQTT on and restart the script.
- HTTP version: presence is up to 3 seconds old.
Verification status
This guide is based on the documentation from Shelly.