Secure connectivity at a glance
Security is a plus point of IoT Zap. Your messages are protected in layers, and you decide how many to switch on. Each layer is explained step by step further down this page.
| Layer | How to switch it on | Learn more |
|---|---|---|
| 1 Encrypted connection MQTT over TLS or secure WebSocket (wss) | Broker tab → Connection type: MQTT + TLS (port 8883) or Secure WebSocket (port 8084). Add the broker username and password | Section 2 and 5.5 |
| 2 Private topics | Topics tab → Make my topics unique (on by default) | Section 3 |
| 3 Message encryption AES-256, GCM by default | Security tab → Encrypt / encode messages and a passphrase. Or match your device’s own AES with salt words | Section 7 |
| 4 Safe accounts | Log in with a one-time code (passwords are stored hashed), or tap Continue without login | Privacy Policy |
- Use TLS (port 8883) or secure WebSocket (port 8084), and give your broker a username and password.
- Keep Make my topics unique on.
- Turn on message encryption with the default AES-GCM and a long passphrase (a sentence works well).
- Use TLS and encryption together: TLS protects the road to the broker, the encryption protects the message while it is on the broker.
- Keep exported HTML files private if you saved your login or passphrase inside them.
1. The big picture
Your device and the app never talk to each other directly. Both connect to an MQTT broker (a free public one such as broker.emqx.io, or your own Mosquitto/HiveMQ/EMQX). They exchange text messages on two topics:
| Direction | Who publishes | Who subscribes | Where you set the topic |
|---|---|---|---|
| Data (device → app) | Your device | The app | Project settings → Topics → Data topic |
| Commands (app → device) | The app (widgets and automations) | Your device | Project settings → Topics → Command topic |
IoT Zap does not run a broker or store your sensor data. Messages go straight between your phone, your broker and your device.
2. Set up the app
- Open IoT Zap. Log in with your e-mail (a one-time code arrives in your inbox), or tap Continue without login. Without login everything stays on your phone only: no backup and no sync to other devices.
- Create a project. On the Projects tab tap New project (or Try the example project to see a ready dashboard).
- Broker tab. Enter the broker address, for example
broker.emqx.io, and choose how to connect. Add a username and password if your broker needs them. - Topics tab. Type a Data topic (device → app), for example
home/data, and a Command topic (app → device), for examplehome/cmd. Keep Make my topics unique switched on (see section 3). - Data tab. Choose how incoming messages are read (JSON is the default) and how commands are sent. Optional start and end markers live here too.
- Security tab (optional). Turn on Encrypt messages (AES-256) and set a passphrase (section 7).
- Add widgets. Open the dashboard, tap the pencil, then Add widget. Pick a widget, give it a Data key such as
temporrelay1and save. Long-press a widget and drag it to rearrange the dashboard.
How a message becomes widgets
Every widget is linked to a plain data key (no virtual pins). If the device publishes this to the data topic, the three widgets update by themselves:
The widgets
| Widget | Shows or sends | Typical use |
|---|---|---|
| Gauge, Value display, Live chart | Shows a number | Temperature, humidity, power |
| Thermometer, Tank level, Battery, Progress bar | Shows a number between a minimum and a maximum | Water level, battery %, fan speed |
| LED | Shows on/off | Door open, motion detected |
| Switch | Sends ON value / OFF value (default 1 / 0) | Relay, light, pump |
| Push button | Sends the ON value while pressed and the OFF value on release | Doorbell, momentary motor |
| Slider, Knob, Stepper (+/−) | Sends a number | Dimmer, servo angle, set-point |
| Selector | Sends the value of the option you pick | Mode: Off=0, Low=1, High=2 |
| Colour picker | Sends a colour such as #FF3B30 | RGB LED strip |
| Direction pad | Sends up, down, left, right, then stop when you let go (editable) | Robot car |
| Text box | Sends the text you type | Display message, command line |
3. Topics and your private prefix
With Make my topics unique on (the default), the app adds a private prefix so you do not collide with strangers on a public broker. The full topic has four parts: iz/<your tag>/<project id>/<your topic>.
izis always the same.- Your tag is the first 12 hex characters of the SHA-256 of your e-mail (lower case, no spaces).
- The project ID is the first 12 hex characters of the SHA-256 of “project name|creation time in milliseconds”, so every project has its own topics.
- Your topic is the data or command topic you typed in the project, for example
home/dataandhome/cmd.
About the project ID. It is made once when the project is saved and never changes, even if you rename the project, and two projects (even with the same name) never share it. Your device cannot work it out, because it depends on the exact moment the project was created, so copy it from the app: Device setup info in the dashboard menu, or the Topics tab of the project settings, shows the finished topics. Projects made before this feature keep their old topics without a project ID (iz/<your tag>/home/data) until you switch on Separate topics for this project in their Topics tab. If you switch it on, update your device to the new topics.
demo@example.com and one project. The tag comes from your own e-mail, and every project gets its own project ID (first 12 characters of the SHA-256 of the project name and creation time).The tag can be computed in a script. The project ID cannot (it depends on the exact creation time), so copy it from the app:
Pythonimport hashlib
email = "demo@example.com" # the e-mail you sign in with
tag = hashlib.sha256(email.strip().lower().encode()).hexdigest()[:12]
project_id = "660fe81fbe14" # copy it from the app: Project settings > Topics > Project ID
print(f"iz/{tag}/{project_id}/home/data") # iz/7462108984f6/660fe81fbe14/home/data
print(f"iz/{tag}/{project_id}/home/cmd") # iz/7462108984f6/660fe81fbe14/home/cmd
Node.js
const crypto = require('crypto');
const email = 'demo@example.com'; // the e-mail you sign in with
const tag = crypto.createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 12);
const projectId = '660fe81fbe14'; // copy it from the app: Project settings > Topics > Project ID
console.log(`iz/${tag}/${projectId}/home/data`); // iz/7462108984f6/660fe81fbe14/home/data
console.log(`iz/${tag}/${projectId}/home/cmd`); // iz/7462108984f6/660fe81fbe14/home/cmd
Switch Make my topics unique off and the app uses exactly the topics you typed, with no prefix and no project ID. That is fine on your own private broker. Every device example below uses the finished topic iz/7462108984f6/660fe81fbe14/home/data: replace both 12-character parts with the ones from your own Device setup info.
4. Data formats the app understands
Choose the format in Project settings → Data. The device must publish in that format to the data topic.
| Format | What the device sends | How keys are matched |
|---|---|---|
| JSON (default) | {"temp":28.4,"hum":65,"relay1":1} | The widget's data key is the JSON key. Nested keys use dots: room.temp reads {"room":{"temp":21}} |
| Key=Value | temp=28.4,hum=65 | Pairs are split by the separator (default comma) |
| Delimited list | 28.4,65,1 | Each pin has a Position: 0 is the first item |
| Plain text per topic | Payload 28.4 on its own topic | Each pin has a Sub-topic, for example temp |
Switches and LEDs understand 1, 0, true, false, on, off, yes, no, high and low. Numbers are shown with the decimals you set on the widget.
Start and end markers (optional)
Set a start and an end marker (for example # and $) and the app processes only messages that begin and end with them. Anything else on the topic is ignored, which is handy on a busy public broker or a noisy serial link. The same markers are put around the commands the app sends.
5. Send data from the device (device → app)
Sending is just publishing a message to the data topic. Use the exact topic from Device setup info and the format you chose in the Data tab (JSON below).
5.1 Wiring for the ESP32 example
5.2 ESP32 / Arduino IDE (Wi-Fi)
Install the libraries PubSubClient, ArduinoJson (version 7) and DHT sensor library from the Library Manager. This one sketch both sends the sensors and receives the relay command:
ESP32 · Arduino C++#include <WiFi.h>
#include <PubSubClient.h> // Library Manager: "PubSubClient" by Nick O'Leary
#include <ArduinoJson.h> // Library Manager: "ArduinoJson" by Benoit Blanchon (version 7)
#include <DHT.h> // Library Manager: "DHT sensor library" by Adafruit
const char* WIFI_SSID = "your-wifi-name";
const char* WIFI_PASS = "your-wifi-password";
const char* BROKER = "broker.emqx.io";
const int PORT = 1883;
// Copy both topics from the app: open the dashboard, menu, "Device setup info".
const char* DATA_TOPIC = "iz/7462108984f6/660fe81fbe14/home/data"; // device -> app
const char* CMD_TOPIC = "iz/7462108984f6/660fe81fbe14/home/cmd"; // app -> device
const int RELAY_PIN = 26;
DHT dht(4, DHT22); // DHT22 data pin on GPIO 4
WiFiClient net;
PubSubClient mqtt(net);
// ---- app -> device: the app sent a command, for example {"relay1":1} ----
void onMessage(char* topic, byte* payload, unsigned int len) {
JsonDocument doc;
if (deserializeJson(doc, payload, len)) return; // not JSON, ignore it
if (!doc["relay1"].isNull()) {
digitalWrite(RELAY_PIN, doc["relay1"].as<int>() ? HIGH : LOW);
mqtt.publish(DATA_TOPIC, doc["relay1"].as<int>() ? "{\"relay1\":1}" : "{\"relay1\":0}"); // confirm the state
}
}
void connectMqtt() {
while (!mqtt.connected()) {
String id = "esp32-" + String((uint32_t)ESP.getEfuseMac(), HEX);
if (mqtt.connect(id.c_str())) mqtt.subscribe(CMD_TOPIC);
else delay(2000);
}
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
dht.begin();
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) delay(300);
mqtt.setServer(BROKER, PORT);
mqtt.setBufferSize(512); // room for longer or encrypted messages
mqtt.setCallback(onMessage);
}
void loop() {
if (!mqtt.connected()) connectMqtt();
mqtt.loop();
// ---- device -> app: send the sensors every 5 seconds ----
static uint32_t last = 0;
if (millis() - last > 5000) {
last = millis();
float t = dht.readTemperature(), h = dht.readHumidity();
if (!isnan(t) && !isnan(h)) {
JsonDocument doc;
doc["temp"] = t;
doc["hum"] = h;
char buf[96];
serializeJson(doc, buf, sizeof(buf)); // {"temp":28.4,"hum":65.0}
mqtt.publish(DATA_TOPIC, buf);
}
}
}
5.3 Python on a Raspberry Pi or PC
Install the client with pip install paho-mqtt. This script sends fake sensor values every 5 seconds and also listens for commands (it was tested against a real phone running the app):
import json, random, time
import paho.mqtt.client as mqtt # pip install paho-mqtt
BROKER = "broker.emqx.io"
DATA_TOPIC = "iz/7462108984f6/660fe81fbe14/home/data" # device -> app (copy from "Device setup info")
CMD_TOPIC = "iz/7462108984f6/660fe81fbe14/home/cmd" # app -> device
def on_connect(client, userdata, flags, reason_code, properties=None):
print("connected:", reason_code)
client.subscribe(CMD_TOPIC)
def on_message(client, userdata, msg):
try:
cmd = json.loads(msg.payload) # for example {"relay1": 1}
except ValueError:
return # not JSON, ignore
print("command:", cmd)
if "relay1" in cmd:
print("relay ON" if cmd["relay1"] else "relay OFF") # drive your GPIO pin here
# Report the new state so the app's switch/LED matches the real relay:
client.publish(DATA_TOPIC, json.dumps({"relay1": cmd["relay1"]}))
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.on_message = on_message
client.connect(BROKER, 1883, 60)
client.loop_start()
while True: # send sensor data every 5 seconds
data = {"temp": round(random.uniform(22, 30), 1), "hum": random.randint(50, 70)}
client.publish(DATA_TOPIC, json.dumps(data))
print("sent:", data)
time.sleep(5)
5.4 Test without any hardware
Install the Mosquitto command-line tools and pretend to be the device. The dashboard updates a second after you press Enter:
Terminal# Pretend to be the device and send data to the app:
mosquitto_pub -h broker.emqx.io -t "iz/7462108984f6/660fe81fbe14/home/data" -m '{"temp":28.4,"hum":65,"relay1":1}'
# With start/end markers (# and $) turned on in the app:
mosquitto_pub -h broker.emqx.io -t "iz/7462108984f6/660fe81fbe14/home/data" -m '#{"temp":28.4,"hum":65}$'
# Watch what the app sends to your device when you tap a widget:
mosquitto_sub -h broker.emqx.io -t "iz/7462108984f6/660fe81fbe14/home/cmd" -v
5.5 Connect securely (TLS)
Plain MQTT on port 1883 is not encrypted: anyone on the same network can read it. Switch to port 8883 (MQTT over TLS) in the app’s Broker tab and on the device. A device should also check the broker’s certificate, so nobody can pretend to be the broker.
Python 3 · paho-mqtt (tested against a TLS broker)import json, ssl, time
import paho.mqtt.client as mqtt # pip install paho-mqtt
BROKER = "broker.emqx.io"
PORT = 8883 # MQTT over TLS (1883 is plain, unencrypted)
DATA_TOPIC = "iz/7462108984f6/660fe81fbe14/home/data"
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.tls_set(cert_reqs=ssl.CERT_REQUIRED) # check the broker's certificate with the system CA list
# client.username_pw_set("user", "password") # if your broker needs a login
client.connect(BROKER, PORT, 60)
client.loop_start()
info = client.publish(DATA_TOPIC, json.dumps({"temp": 24.5}), qos=1)
info.wait_for_publish()
print("published over TLS:", info.is_published())
time.sleep(1)
client.loop_stop()
ESP32 · Arduino C++
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
WiFiClientSecure net; // instead of WiFiClient
PubSubClient mqtt(net);
// Paste the broker's ROOT certificate (PEM). Public brokers publish theirs on their website;
// for your own broker it is the certificate authority (CA) that signed your server certificate.
const char* ROOT_CA = R"EOF(
-----BEGIN CERTIFICATE-----
...paste your broker's root CA certificate here...
-----END CERTIFICATE-----
)EOF";
void setup() {
// ... connect Wi-Fi as before ...
net.setCACert(ROOT_CA); // verifies the broker, so nobody can pretend to be it
// net.setInsecure(); // TESTING ONLY: encrypts but does NOT check who the broker is
mqtt.setServer("broker.emqx.io", 8883); // TLS port instead of 1883
mqtt.setBufferSize(512);
// mqtt.connect(clientId, "user", "password") if your broker needs a login
}
6. Receive commands on the device (app → device)
When you flip a switch, drag a slider or press a button, the app publishes to the command topic. Your device just subscribes to that topic and acts on what arrives. The example sketch and the Python script above already do this for relay1.
6.1 What each widget sends
| Widget | When it sends | Value |
|---|---|---|
| Switch | when you flip it | ON value or OFF value (default 1 / 0) |
| Push button | on press, and again on release | ON value, then OFF value |
| Slider, Knob | when you let go | a number in the range you set |
| Stepper | each tap on + or − | the new number |
| Selector | when you pick an option | the option's value, for example 2 |
| Colour picker | when you pick a colour | text such as #FF3B30 |
| Direction pad | on press, and stop on release | up / down / left / right (editable) |
| Text box | when you tap send | the text |
6.2 Three ways the command can be packed
Choose it in Project settings → Data → Commands are sent as. The widget's data key (for example relay1) and its value are packed like this:
| Setting | Topic the app publishes to | Payload |
|---|---|---|
| JSON (default) | the command topic | {"relay1":1} (numbers stay numbers, text stays text) |
| Key=Value | the command topic | relay1=1 |
| Value only | command topic + / + key (or the pin's sub-topic) | 1 |
If start and end markers are set they wrap the payload, for example #{"relay1":1}$. Subscribe to <command topic>/# when you use Value only.
6.3 The other two formats and the markers on the ESP32
ESP32 · Arduino C++// 1) START / END MARKERS (Project settings > Data). Example: start "#", end "$"
// Send: mqtt.publish(DATA_TOPIC, (String("#") + json + "$").c_str());
// Receive: strip them before parsing.
bool stripMarkers(String& s, char startCh, char endCh) {
s.trim();
if (s.length() < 2 || s[0] != startCh || s[s.length() - 1] != endCh) return false; // not for us
s = s.substring(1, s.length() - 1);
return true;
}
// 2) "Commands are sent as: Key=Value" -> payload relay1=1
void handleKeyValue(const String& s) {
int i = s.indexOf('=');
if (i < 1) return;
String key = s.substring(0, i), val = s.substring(i + 1);
if (key == "relay1") digitalWrite(RELAY_PIN, val.toInt() ? HIGH : LOW);
}
// 3) "Commands are sent as: Value only"
// The value is published to <command topic>/<key>, for example .../home/cmd/relay1 with payload 1
// Subscribe with a wildcard: mqtt.subscribe("iz/7462108984f6/660fe81fbe14/home/cmd/#");
void onMessage(char* topic, byte* payload, unsigned int len) {
String t = topic, v;
for (unsigned int i = 0; i < len; i++) v += (char)payload[i];
if (t.endsWith("/relay1")) digitalWrite(RELAY_PIN, v.toInt() ? HIGH : LOW);
if (t.endsWith("/speed")) ledcWrite(0, v.toInt()); // slider, knob, stepper send numbers
if (t.endsWith("/color")) { /* v is like "#FF3B30" */ }
if (t.endsWith("/move")) { /* v is "up", "down", "left", "right" or "stop" */ }
}
relay1). Then the switch and LED in the app always show what the device is really doing, even if the command was lost.
7. Encryption and decryption
On a public broker anyone can read your topics. Switching on encryption makes every message unreadable to the broker and to everyone else: only the app and your device, which share a secret passphrase, can read or write them. IoT Zap uses AES-256-GCM, a modern standard that also detects tampering.
7.1 On the app side
- Open your project’s settings and go to the Security tab.
- Turn on Encrypt messages (AES-256).
- Type a Secret passphrase (at least 6 characters; longer is better). Use exactly the same passphrase in your device code.
- Save. From now on the app encrypts everything it sends (widget commands and automation messages) and decrypts everything it receives. The Live monitor shows the readable text after decryption.
If a message cannot be decrypted (wrong passphrase, or the device did not encrypt it), the Live monitor shows a grey/red line saying decryption failed (wrong secret or not encrypted) and the message is ignored. A dashboard exported as HTML asks for the passphrase when opened, unless you chose to save it inside the file.
7.2 The exact recipe
Any language works as long as it follows these rules. Nothing else is added: no header, no extra data.
| Item | Value |
|---|---|
| Algorithm | AES-256-GCM, no padding, no additional authenticated data |
| Key | SHA-256 of the passphrase (UTF-8 bytes): exactly 32 raw bytes |
| IV (nonce) | 12 random bytes, new for every message. Never reuse an IV with the same key |
| Tag | 128 bits = 16 bytes, appended after the ciphertext |
| Plain text | UTF-8. If start/end markers are on, they are part of the plain text: #{"relay1":1}$ |
| Message on the wire | Base64( IV ∥ ciphertext ∥ tag ), standard Base64 with = padding and no line breaks, sent as the MQTT payload text |
Encrypting (sender)
Decrypting (receiver)
Test vector: check your own code
Decrypt this message with your implementation. If you get #{"temp":28.4,"hum":65}$ back, you are compatible with the app. (The IV is fixed here only so the result is repeatable. In real use it must be random.)
| Passphrase | my-secret-123 |
|---|---|
| Key = SHA-256 | 5bc39cdcb1f92daee20c4ada9b8bc04c9e4e5bf97367e07aeca5e9eca8ab074d |
| IV (hex) | 000102030405060708090a0b |
| Plain text (24 bytes) | #{"temp":28.4,"hum":65}$ |
| Ciphertext (hex) | 08673ffc128a1b316ba1888e2c5ea7beb402108a2e5d47df |
| Tag (hex) | c271cfd2fa3443898ed5bfa87a272923 |
| Message on the wire (12 + 24 + 16 = 52 bytes, 72 characters) | AAECAwQFBgcICQoLCGc//BKKGzFroYiOLF6nvrQCEIouXUffwnHP0vo0Q4mO1b+oeicpIw== |
7.3 On the device side
Encrypt what the device publishes to the data topic, and decrypt what it receives on the command topic. Use the same passphrase as in the app.
Raspberry Pi, PC or server: Python
Install pip install cryptography. Verified against the test vector above, and a message encrypted by this code was decrypted by the Node.js code below and the other way round.
import base64, hashlib, os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM # pip install cryptography
def key_from(passphrase: str) -> bytes:
return hashlib.sha256(passphrase.encode()).digest() # 32 bytes = AES-256 key
def encrypt(plain: str, passphrase: str) -> str:
iv = os.urandom(12) # new random IV for every message
ct_and_tag = AESGCM(key_from(passphrase)).encrypt(iv, plain.encode(), None)
return base64.b64encode(iv + ct_and_tag).decode() # IV + ciphertext + 16-byte tag
def decrypt(b64: str, passphrase: str) -> str:
raw = base64.b64decode(b64)
iv, ct_and_tag = raw[:12], raw[12:]
return AESGCM(key_from(passphrase)).decrypt(iv, ct_and_tag, None).decode() # raises InvalidTag if wrong
if __name__ == "__main__":
pw = "my-secret-123"
msg = encrypt('#{"relay1":1}$', pw)
print(msg)
print(decrypt(msg, pw))
# Test vector from this page (must print the original message):
print(decrypt("AAECAwQFBgcICQoLCGc//BKKGzFroYiOLF6nvrQCEIouXUffwnHP0vo0Q4mO1b+oeicpIw==", pw))
Then, in the MQTT callbacks of the earlier example:
client.publish(DATA_TOPIC, encrypt('#' + json.dumps(data) + '$', "my-secret-123")) # send
def on_message(client, userdata, msg): # receive
try:
plain = decrypt(msg.payload.decode(), "my-secret-123") # '#{"relay1":1}$'
except Exception:
return # wrong passphrase or not encrypted
cmd = json.loads(plain.strip('#$')) # remove the markers, then parse
Node.js (Node-RED function, server, desktop)
Node.js · built-in cryptoconst crypto = require('crypto'); // built into Node.js
const keyFrom = (passphrase) => crypto.createHash('sha256').update(passphrase).digest(); // 32 bytes
function encrypt(plain, passphrase) {
const iv = crypto.randomBytes(12); // new random IV for every message
const c = crypto.createCipheriv('aes-256-gcm', keyFrom(passphrase), iv);
const ct = Buffer.concat([c.update(plain, 'utf8'), c.final()]);
return Buffer.concat([iv, ct, c.getAuthTag()]).toString('base64'); // IV + ciphertext + 16-byte tag
}
function decrypt(b64, passphrase) {
const raw = Buffer.from(b64, 'base64');
const d = crypto.createDecipheriv('aes-256-gcm', keyFrom(passphrase), raw.subarray(0, 12));
d.setAuthTag(raw.subarray(raw.length - 16));
return Buffer.concat([d.update(raw.subarray(12, raw.length - 16)), d.final()]).toString('utf8'); // throws if wrong
}
const pw = 'my-secret-123';
const msg = encrypt('#{"relay1":1}$', pw);
console.log(msg);
console.log(decrypt(msg, pw));
console.log(decrypt('AAECAwQFBgcICQoLCGc//BKKGzFroYiOLF6nvrQCEIouXUffwnHP0vo0Q4mO1b+oeicpIw==', pw)); // test vector
ESP32 (Arduino IDE): mbedTLS is already built in
No extra library is needed. Make the key once in setup(), then call encryptMsg() before publishing and decryptMsg() in the callback:
#include <vector>
#include "mbedtls/gcm.h"
#include "mbedtls/sha256.h"
#include "mbedtls/base64.h"
#include <esp_random.h>
const char* PASSPHRASE = "my-secret-123"; // exactly the same as in the app (Security tab)
static uint8_t KEY[32];
void makeKey() { // key = SHA-256(passphrase). Call once in setup().
mbedtls_sha256((const unsigned char*)PASSPHRASE, strlen(PASSPHRASE), KEY, 0); // 0 = SHA-256 (not SHA-224)
}
// plain text -> Base64( IV[12] + ciphertext + tag[16] )
String encryptMsg(const String& plain) {
size_t n = plain.length();
std::vector<uint8_t> buf(12 + n + 16);
esp_fill_random(buf.data(), 12); // new random IV for every message
mbedtls_gcm_context g; mbedtls_gcm_init(&g);
mbedtls_gcm_setkey(&g, MBEDTLS_CIPHER_ID_AES, KEY, 256);
mbedtls_gcm_crypt_and_tag(&g, MBEDTLS_GCM_ENCRYPT, n, buf.data(), 12, NULL, 0,
(const uint8_t*)plain.c_str(), buf.data() + 12, 16, buf.data() + 12 + n);
mbedtls_gcm_free(&g);
size_t outLen = 0;
std::vector<uint8_t> b64(4 * ((buf.size() + 2) / 3) + 1);
mbedtls_base64_encode(b64.data(), b64.size(), &outLen, buf.data(), buf.size());
b64[outLen] = 0;
return String((char*)b64.data());
}
// Base64 text -> plain text. Returns false when the passphrase is wrong or the message was changed.
bool decryptMsg(const uint8_t* b64, size_t b64len, String& out) {
std::vector<uint8_t> raw(b64len);
size_t rawLen = 0;
if (mbedtls_base64_decode(raw.data(), raw.size(), &rawLen, b64, b64len) != 0) return false;
if (rawLen < 12 + 16) return false;
size_t n = rawLen - 12 - 16;
std::vector<uint8_t> plain(n + 1);
mbedtls_gcm_context g; mbedtls_gcm_init(&g);
mbedtls_gcm_setkey(&g, MBEDTLS_CIPHER_ID_AES, KEY, 256);
int rc = mbedtls_gcm_auth_decrypt(&g, n, raw.data(), 12, NULL, 0,
raw.data() + 12 + n, 16, raw.data() + 12, plain.data());
mbedtls_gcm_free(&g);
if (rc != 0) return false;
plain[n] = 0;
out = String((char*)plain.data());
return true;
}
// ---- how to use it ----
// setup(): makeKey(); mqtt.setBufferSize(512);
//
// Send (device -> app). If start/end markers are on, put them INSIDE the encrypted text:
// String json = "{\"temp\":28.4,\"hum\":65}";
// mqtt.publish(DATA_TOPIC, encryptMsg("#" + json + "$").c_str());
//
// Receive (app -> device):
// void onMessage(char* topic, byte* payload, unsigned int len) {
// String plain;
// if (!decryptMsg(payload, len, plain)) return; // wrong passphrase or not encrypted
// // plain is now #{"relay1":1}$ -> remove the markers, then parse the JSON as usual
// }
mqtt.setBufferSize(512) in PubSubClient.
7.4 Other methods, salt words and AES from another device
Your device may already encrypt in its own way, or you may want extra “salt words” mixed into the key. IoT Zap can match most AES set-ups. Open Project settings → Security, choose a Method, and tap Advanced to match the rest:
| Setting | Choices | What it means |
|---|---|---|
| Method | AES-GCM (default) · AES-CBC · AES-CTR · AES-ECB · Encoding only | The cipher mode. GCM also detects tampering. CBC and ECB add PKCS#7 padding. Encoding only just converts to/from Base64 or Hex and is not secret |
| Key size | AES-128 · 192 · 256 | 16, 24 or 32 key bytes |
| Key is made from | SHA-256 · SHA-1 · MD5 · the passphrase itself · PBKDF2-HMAC-SHA256 | How the key bytes come from your passphrase. A hash is cut, or zero-padded if too short, to the key size. “Passphrase itself” uses the passphrase bytes directly, cut or zero-padded |
| Salt words | any text | Hash methods: key = hash(passphrase + salt). PBKDF2: the salt (required) with the iteration count you set |
| IV (nonce) | Random, sent in front · Fixed, not sent | Random: 12 bytes (GCM) or 16 bytes (CBC, CTR) placed before the ciphertext. Fixed: the same bytes every time (text, or hex that starts with 0x); weaker, use only to match an old device |
| Message is written as | Base64 · Hex | How the bytes become MQTT text |
A Python example for AES-CBC with salt words that matches those settings (verified against reference messages made by another implementation):
Python 3 · cryptographyimport base64, hashlib, os
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
# Match these to Project settings > Security > Advanced in the app:
PASSPHRASE = "my-secret-123"
SALT = "pepper" # salt words ("" if none)
KEY_BITS = 256 # AES-128 / 192 / 256
# Key made from passphrase + salt (pick ONE, the same as "Key is made from" in the app):
def key_sha256(): return hashlib.sha256((PASSPHRASE + SALT).encode()).digest()[:KEY_BITS // 8]
def key_pbkdf2(): return hashlib.pbkdf2_hmac("sha256", PASSPHRASE.encode(), SALT.encode(), 10000, KEY_BITS // 8)
def key_raw(): return PASSPHRASE.encode().ljust(KEY_BITS // 8, b"\0")[:KEY_BITS // 8] # cut or zero-padded
KEY = key_sha256()
# ---- AES-CBC: random 16-byte IV sent in front of the message, PKCS#7 padding ----
def encrypt_cbc(plain: str, as_hex=False) -> str:
iv = os.urandom(16)
padder = padding.PKCS7(128).padder()
data = padder.update(plain.encode()) + padder.finalize()
enc = Cipher(algorithms.AES(KEY), modes.CBC(iv)).encryptor()
raw = iv + enc.update(data) + enc.finalize()
return raw.hex() if as_hex else base64.b64encode(raw).decode()
def decrypt_cbc(text: str, as_hex=False) -> str:
raw = bytes.fromhex(text) if as_hex else base64.b64decode(text)
iv, body = raw[:16], raw[16:]
dec = Cipher(algorithms.AES(KEY), modes.CBC(iv)).decryptor()
unpad = padding.PKCS7(128).unpadder()
return (unpad.update(dec.update(body) + dec.finalize()) + unpad.finalize()).decode()
# Other modes in the same style:
# AES-CTR: modes.CTR(iv), no padding AES-GCM: use AESGCM(KEY).encrypt(iv12, data, None) (see section 7.3)
# AES-ECB: modes.ECB(), no IV, PKCS#7 Fixed IV: use the same 16 bytes every time and do NOT put it in front
if __name__ == "__main__":
msg = encrypt_cbc('#{"relay1":1}$')
print(msg)
print(decrypt_cbc(msg))
The exported HTML dashboard understands GCM, CBC and CTR with SHA-256, SHA-1, passphrase or PBKDF2 keys. A browser cannot do AES-ECB or MD5, so a project that uses those works in the app only.
The Automations screen (dashboard menu) lets the app answer on its own while a project is connected: IF a value changes (temp is less than 20) or it is a time of day, THEN set a widget, show a notification, or send a custom message to any topic.
| Setting in the rule | What it does |
|---|---|
| Topic to send to | Any topic. Leave empty for the project’s command topic. Your private prefix is added when it is on |
| Message format | JSON, key=value pairs, or plain text |
| Keys and values | One key=value per line. Numbers and true/false become real JSON numbers and booleans |
| Placeholders | {value} the reading that triggered the rule · {temp}, {hum}… the latest value of any key · {time} · {rule} |
Run only after it happened N times
By default a rule runs on every reading that matches. Under IF, set How many times to wait for a pattern instead of a single reading: IF temp is at most 32, 10 times in a row, THEN notify me. The app counts each reading it receives for that key; on the 10th matching one the action runs, and counting starts again from zero.
| Setting | What it does |
|---|---|
| How many times | 1 runs on every match (the default). 10 runs on the 10th match |
| Count them: In a row | One reading that does not match (for example temp 40) throws the count away and starts over. Use it for “stayed low for 10 readings” |
| Count them: In total | Readings that do not match are ignored; only matching ones are added up. Use it for “was low 10 times” |
| Within (seconds) | Only matches from the last N seconds count. 60 with 10 times = ten matches inside one minute. 0 means no time limit |
| Don’t repeat within | Still applies after the rule has run, so a busy sensor cannot trigger it over and over |
The Live monitor shows the progress ('Cold room': condition met 7 of 10) so you can see it working. Counting runs while the project is connected and restarts from zero when you edit the rule or reconnect. It is counted per reading received, so a device that sends once a minute needs ten minutes for ten readings. The time-of-day trigger has no count.
Example: the rule IF temp < 20 with the lines cmd=heater, state=on, temp={value} publishes {"cmd":"heater","state":"on","temp":18.5} to the topic you chose. If encryption or markers are on they are applied to automation messages too, so your device decrypts them exactly like any other command.
9. Your dashboard: layout, themes, alarms and charts
Everything here is done on the phone, on the dashboard screen. Nothing needs code on your device: widgets only read the data keys your device already sends.
9.1 Adding widgets
Tap the pencil icon (edit mode), then Add widget. The widget box has 25 widgets in three groups. Pick one, type the data key it should read (for example temp) and save.
| Group | Widgets |
|---|---|
| Controls (send to the device) | Switch, push button, slider, knob, stepper + / −, selector, colour picker, direction pad, text box |
| Displays | Value, LED, gauge, speedometer, donut gauge, progress bar, tank level, thermometer, battery, value + trend, min / max / average |
| Charts | Live (line) chart, area chart, bar chart, multi-line chart, pie chart |
The speedometer is a bike-style dial with ticks, numbers and a needle that turns around the centre, with the value in digits under it. Set its range (for example 0–120) and unit (for example km/h) in the editor.
9.2 Move and resize widgets
- Move: in edit mode, press and hold a widget until it lifts, then drag it to any place and let go. It snaps to the nearest cell of a 4-column grid, and an outline shows where it will land. A widget that is in the way is pushed down, so two widgets never overlap. Empty space is allowed.
- Resize: drag the round handle in the bottom-right corner of a widget. You can also type the columns (1–4) and rows in the widget editor.
- Change: tap a widget in edit mode to open its editor (title, data key, range, colour, units, alarms, size, delete).
- Too small? When a widget is made smaller than its content, the content shrinks to fit instead of being cut off.
The layout is saved with your project, so it syncs to your other devices and the exported HTML dashboard uses the same positions and sizes.
9.3 Card background (transparent widgets)
Every widget sits on a card. In the widget editor, the Card background slider goes from 100 % (normal card) down to 0 %, which removes the box completely so the widget floats on your theme or background picture. In edit mode a thin outline is drawn so you can still find it.
9.4 Themes and background picture
Dashboard menu (⋮) → Appearance.
| Setting | What it does |
|---|---|
| Theme | Pencil sketch (the default hand-drawn look), Clean light, Midnight (dark) or Blueprint (blue with a grid). Each project has its own theme, and it syncs to your account. |
| Background picture | Choose any picture from your phone. A slider darkens it so the widgets stay readable. Cards become slightly see-through over a picture. |
The picture is copied into the app and stays on that phone only: it is never uploaded and does not sync to your other devices. The exported HTML dashboard includes the theme and the picture (made smaller) inside the one file.
9.5 High and low alarms
For any value widget (gauge, speedometer, tank, battery, thermometer, progress, value, charts…) open the editor and fill the Alarms section:
- High alarm and Low alarm are numbers in the widget’s own units.
90on a tank that shows percent means 90 %. Leave a field empty for no alarm. - When the value reaches the high alarm (or falls to the low alarm) the whole widget turns the alarm colour you picked (red by default; orange, amber, magenta, purple and blue are also offered) and shows ▲ HIGH or ▼ LOW. It returns to its normal colour as soon as the value is back in range.
- On the speedometer the alarm zone is also painted on the rim of the dial.
An alarm only changes colour. For a notification or a message to your device, add an automation (for example IF temp is at least 90 THEN show a notification).
9.6 Units
Under Unit in the editor there is a row of one-tap units: %, V, mV, A, mA, W, kW, kWh, °C, °F, K, km/h, mph, m/s, rpm, Hz, bar, psi, hPa, kPa, lux, ppm, dB, m, cm, mm, L, mL, kg, g, s, min, h. Tap one to use it, tap it again to clear it, or type any unit yourself. The unit is only a label: the app shows the number your device sends.
9.7 Chart options: time or another value on X
Line, area, bar and pie charts have a Chart data section in the editor.
| Setting | What it does |
|---|---|
| X axis: Time | The default. The last readings of the key are drawn in the order they arrived, with their time (HH:mm:ss) written under the chart. |
| X axis: Another value | Type a second data key, for example hum. Each reading of the widget’s key (temp) is paired with the latest value of that key at the same moment. Points are sorted by X and the X values are written under the chart: a temp by humidity chart. Line and area charts place points at their true X distance; bars are evenly spaced. |
| Readings to show | How many of the latest readings to draw (default 60, bar 24, pie 6; up to 120). |
| Pie: Several keys | One slice per key (the widget’s key plus the “other data keys” you list), each with its latest value. |
| Pie: Recent readings | One slice per recent reading of the key, named by its time or by the X value. The legend shows each slice’s share in percent. |
Charts are drawn from the readings received since the project was connected (the last 120 per key are kept in memory). The Data logs screen keeps the long history and exports it as CSV. The multi-line chart draws several keys on shared axes, listing the extra keys in Other data keys.
10. Debugging and troubleshooting
Open the dashboard menu and choose Live monitor. It lists every message with the time and the topic: RX received, TX sent, and grey or red lines for anything that was ignored together with the reason. At the bottom you can publish a test message yourself.
| What you see | Likely cause | Fix |
|---|---|---|
Widgets show -- and the monitor has no RX lines | The device publishes to a different topic than the app listens to. The private iz/… prefix is the usual culprit | Copy the topics from Device setup info. Test with mosquitto_pub (section 5.4) |
| RX line, then ignored: no pin matched this message | The keys in the message do not match any widget’s Data key | Make the key in the widget identical to the JSON key (temp, relay1…) |
| ignored: not valid JSON | Broken JSON, such as single quotes or a missing brace | Use double quotes: {"temp":28.4} |
| ignored: missing start… / end… marker | Markers are set in the app but the device does not send them (or the other way round) | Make both sides agree, or clear the markers in the Data tab |
| decryption failed (wrong secret or not encrypted) | Different passphrase, plain text sent while encryption is on, or a wrong format | Compare with the test vector in section 7.2. The passphrase is case-sensitive |
| The device never receives commands | It subscribed to the data topic instead of the command topic, or the subscribe happened before it connected | Subscribe to the command topic after every (re)connect. Check the TX line in the monitor, then mosquitto_sub the same topic |
| Device receives but nothing happens | Format mismatch (JSON vs Key=Value vs Value only), or markers/encryption not handled | See 6.2 and 6.3. Print the raw payload on the serial monitor first |
| Status says Offline, retrying | Wrong broker address or port, no internet, or the broker is busy | Check the Broker tab. Try Reconnect in the dashboard menu |
11. Questions
Can I use my own broker with a password and TLS?
Yes. In the Broker tab choose MQTT + TLS (usually port 8883) or Secure WebSocket and fill in the username and password. TLS protects the connection to the broker; message encryption (section 7) protects the content even on the broker itself. You can use both.
Can two phones control the same device?
Yes. Sign in with the same account on both and the project (including its topics) syncs, or enter the same topics by hand. Both phones talk to the same broker and topics.
My device already uses AES with its own settings. Can IoT Zap read it?
Usually yes. Choose the same mode (GCM, CBC, CTR or ECB), key size, key method, salt words, IV style and Base64/Hex output in Security → Advanced, then check with the Test box. See section 7.4.
Why a passphrase and not a random key?
So you can type it into the app and into your code. The key is derived from it with SHA-256. A long, unusual passphrase (a sentence works well) is as strong as a random key for this purpose.
Can I run the dashboard in a browser?
Yes. In the dashboard menu choose Export as HTML. You get one file that shows the same widgets and works over WebSocket, including encrypted projects (it asks for the passphrase).
Do the apps keep working with the screen off?
A connected project keeps running with the screen off. To keep it running after you close the app, switch on Keep working when the app is closed on the Account tab (it shows a notification with a Stop button).