IoT Zap Tutorials

How to use the app, send and receive on your device, and encrypt both ways · Updated 24 November 2026

New to MQTT? Think of it as a noticeboard. A broker is the board, a topic is a labelled section of it. Your device pins notes (publishes) to one section and reads notes from another (subscribes). IoT Zap does the same from your phone. That is all you need to know to start.

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.

1 Encrypted connection: TLS / secure WebSocket 2 Private topics: iz/<your tag>/… 3 AES-256 message encryption your data {"temp":28.4} broker sees: AAECAwQF… What each layer stops 1 Listening in or changingtraffic on the network 2 Collisions and guessing ona shared public broker 3 Anyone reading your dataon the broker itself 4 Accounts: one-time code login,hashed passwords, or guest mode:nothing leaves your phone
Layers 1 to 3 protect each message. Layer 4 protects your account (or removes it).
LayerHow to switch it onLearn 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 passwordSection 2 and 5.5
2 Private topicsTopics 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 wordsSection 7
4 Safe accountsLog in with a one-time code (passwords are stored hashed), or tap Continue without loginPrivacy Policy
Recommended for any public broker:
  • 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:

Your device ESP32 / Arduino / Pi MQTT broker public or your own IoT Zap app 1 data topic 1 data topic 2 command topic 2 command topic
Green: sensor values go device → broker → app. Blue: commands go app → broker → device.
DirectionWho publishesWho subscribesWhere you set the topic
Data (device → app)Your deviceThe appProject settings → Topics → Data topic
Commands (app → device)The app (widgets and automations)Your deviceProject 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

  1. 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.
  2. Create a project. On the Projects tab tap New project (or Try the example project to see a ready dashboard).
  3. 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.
  4. Topics tab. Type a Data topic (device → app), for example home/data, and a Command topic (app → device), for example home/cmd. Keep Make my topics unique switched on (see section 3).
  5. 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.
  6. Security tab (optional). Turn on Encrypt messages (AES-256) and set a passphrase (section 7).
  7. Add widgets. Open the dashboard, tap the pencil, then Add widget. Pick a widget, give it a Data key such as temp or relay1 and save. Long-press a widget and drag it to rearrange the dashboard.
BrokerTopicsData SecurityPins where to connectaddress, login data topic (in)command (out) JSON / key=valuemarkers, format AES-256 switchpassphrase data keyscreated for you Project settings (pencil icon on a project, or Project settings in the dashboard menu)
The five tabs of Project settings.

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:

message published by the device {"temp": 28.4,"hum": 65,"relay1": 1} temp → Gauge28.4 hum → Gauge65 % relay1 → SwitchON
One message, three widgets. The key in the message is the Data key you typed in the widget.

The widgets

WidgetShows or sendsTypical use
Gauge, Value display, Live chartShows a numberTemperature, humidity, power
Thermometer, Tank level, Battery, Progress barShows a number between a minimum and a maximumWater level, battery %, fan speed
LEDShows on/offDoor open, motion detected
SwitchSends ON value / OFF value (default 1 / 0)Relay, light, pump
Push buttonSends the ON value while pressed and the OFF value on releaseDoorbell, momentary motor
Slider, Knob, Stepper (+/−)Sends a numberDimmer, servo angle, set-point
SelectorSends the value of the option you pickMode: Off=0, Low=1, High=2
Colour pickerSends a colour such as #FF3B30RGB LED strip
Direction padSends up, down, left, right, then stop when you let go (editable)Robot car
Text boxSends the text you typeDisplay 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>.

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.

iz7462108984f6660fe81fbe14home/data iz7462108984f6660fe81fbe14home/cmd /// /// alwaysSHA-256 of your e-mailSHA-256 of name + timeData topic from the app Command topic from the app device publisheshere device listenshere
Example for 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 easy way: open your dashboard, tap the ⋮ menu and choose Device setup info. It shows the exact data topic (with your tag and project ID), command topic and an example message. Copy them into your device code. If you used Continue without login, your prefix is shown on the Account tab (“Private topic prefix”). It is made from a one-way hash of your phone’s Android ID, so it is unique to your phone and stays the same if you reinstall the app. It is never your advertising ID.

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:

Python
import 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.

FormatWhat the device sendsHow 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=Valuetemp=28.4,hum=65Pairs are split by the separator (default comma)
Delimited list28.4,65,1Each pin has a Position: 0 is the first item
Plain text per topicPayload 28.4 on its own topicEach 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.

#{"temp":28.4,"hum":65}$hello? start markeryour dataend marker ignored: no markersaccepted
Only the first message is used by the dashboard.

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

3V3GNDGPIO 4GPIO 26 ESP32 DHT22 sensor VCCDATAGND GNDIN(VCC to 5 V) Relay module lamp / pump
Red: power. Green: signals. Dashed grey: ground. Most relay modules need 5 V on their own VCC pin.

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):

Python 3 · paho-mqtt 2.x
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
}
Tips. Publish every few seconds, not hundreds of times a second. Publish a message with the retain flag if you want a freshly opened dashboard to show the last values immediately. Send only the keys that changed, or all of them, whichever suits you: each key updates only its own widgets.

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

WidgetWhen it sendsValue
Switchwhen you flip itON value or OFF value (default 1 / 0)
Push buttonon press, and again on releaseON value, then OFF value
Slider, Knobwhen you let goa number in the range you set
Steppereach tap on + or −the new number
Selectorwhen you pick an optionthe option's value, for example 2
Colour pickerwhen you pick a colourtext such as #FF3B30
Direction padon press, and stop on releaseup / down / left / right (editable)
Text boxwhen you tap sendthe 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:

SettingTopic the app publishes toPayload
JSON (default)the command topic{"relay1":1} (numbers stay numbers, text stays text)
Key=Valuethe command topicrelay1=1
Value onlycommand 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" */ }
}
Good habit: after you act on a command, publish the real state back to the data topic (the examples do this for 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.

What is and is not encrypted. The message text is encrypted (the data, the commands, and your start/end markers, which sit inside the encrypted text). The topic names are not encrypted, and the broker can still see that a message was sent and how big it is.

7.1 On the app side

  1. Open your project’s settings and go to the Security tab.
  2. Turn on Encrypt messages (AES-256).
  3. Type a Secret passphrase (at least 6 characters; longer is better). Use exactly the same passphrase in your device code.
  4. 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.

Where the passphrase is stored: it is part of your project settings. If you are signed in, project settings (including the passphrase) sync to your account so your other phones can connect; the Privacy Policy explains this. In guest mode (Continue without login) it stays on your phone only.

7.2 The exact recipe

Any language works as long as it follows these rules. Nothing else is added: no header, no extra data.

ItemValue
AlgorithmAES-256-GCM, no padding, no additional authenticated data
KeySHA-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
Tag128 bits = 16 bytes, appended after the ciphertext
Plain textUTF-8. If start/end markers are on, they are part of the plain text: #{"relay1":1}$
Message on the wireBase64( IV ∥ ciphertext ∥ tag ), standard Base64 with = padding and no line breaks, sent as the MQTT payload text

Encrypting (sender)

plain message #{"relay1":1}$ AES-256-GCMencrypt key = SHA-256(passphrase)32 bytes, same on both sides random IV, 12 bytesnew for every message IVciphertexttag 12 Bn B16 B the bytes of the message Base64 encode AAECAwQFBgcICQoL… publish as text
The receiver needs only the passphrase: IV and tag travel inside the message.

Decrypting (receiver)

received text AAECAwQFBgcICQoL… decode IVciphertexttag first 12 Beverything betweenlast 16 B AES-256-GCMdecrypt + check tag key = SHA-256(passphrase)the same 32 bytes plain message #{"relay1":1}$ tag mismatch: reject wrong passphrase or changed ok
If the tag does not match, throw the message away. Never use data from a message that failed.

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.)

Passphrasemy-secret-123
Key = SHA-2565bc39cdcb1f92daee20c4ada9b8bc04c9e4e5bf97367e07aeca5e9eca8ab074d
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.

Python 3 · cryptography
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 crypto
const 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:

ESP32 · Arduino C++ (mbedTLS)
#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
//   }
Smaller boards. An Arduino Uno or Nano does not have the memory for AES-GCM. Use an ESP32, an ESP8266 with the BearSSL library (same recipe), or a Raspberry Pi/PC as a gateway that encrypts for the small board. An encrypted message is about a third bigger than the plain one plus roughly 40 bytes, so raise the buffer with 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:

SettingChoicesWhat it means
MethodAES-GCM (default) · AES-CBC · AES-CTR · AES-ECB · Encoding onlyThe 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 sizeAES-128 · 192 · 25616, 24 or 32 key bytes
Key is made fromSHA-256 · SHA-1 · MD5 · the passphrase itself · PBKDF2-HMAC-SHA256How 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 wordsany textHash methods: key = hash(passphrase + salt). PBKDF2: the salt (required) with the iteration count you set
IV (nonce)Random, sent in front · Fixed, not sentRandom: 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 asBase64 · HexHow the bytes become MQTT text
Use the Test box. At the bottom of the Security tab, type a sample and tap Encrypt, then compare with what your device produces (a random IV makes the text differ each time, so also try Decrypt on a message copied from your device). If it says it cannot decrypt, one of the settings above does not match.
Hashes cannot be decrypted. SHA-256, SHA-1, MD5 and bcrypt are one-way: there is no way back to the original text, so no app can “decrypt” them. IoT Zap uses SHA-256, SHA-1, MD5 and PBKDF2 only to make the AES key from your passphrase and salt words. bcrypt and Argon2 are made for storing passwords, not for messages, so they are not offered.

A Python example for AES-CBC with salt words that matches those settings (verified against reference messages made by another implementation):

Python 3 · cryptography
import 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 ruleWhat it does
Topic to send toAny topic. Leave empty for the project’s command topic. Your private prefix is added when it is on
Message formatJSON, key=value pairs, or plain text
Keys and valuesOne 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.

SettingWhat it does
How many times1 runs on every match (the default). 10 runs on the 10th match
Count them: In a rowOne 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 totalReadings 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 withinStill 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.

GroupWidgets
Controls (send to the device)Switch, push button, slider, knob, stepper + / −, selector, colour picker, direction pad, text box
DisplaysValue, LED, gauge, speedometer, donut gauge, progress bar, tank level, thermometer, battery, value + trend, min / max / average
ChartsLive (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

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.

SettingWhat it does
ThemePencil 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 pictureChoose 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:

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.

SettingWhat it does
X axis: TimeThe 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 valueType 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 showHow many of the latest readings to draw (default 60, bar 24, pie 6; up to 120).
Pie: Several keysOne slice per key (the widget’s key plus the “other data keys” you list), each with its latest value.
Pie: Recent readingsOne 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 seeLikely causeFix
Widgets show -- and the monitor has no RX linesThe device publishes to a different topic than the app listens to. The private iz/… prefix is the usual culpritCopy the topics from Device setup info. Test with mosquitto_pub (section 5.4)
RX line, then ignored: no pin matched this messageThe keys in the message do not match any widget’s Data keyMake the key in the widget identical to the JSON key (temp, relay1…)
ignored: not valid JSONBroken JSON, such as single quotes or a missing braceUse double quotes: {"temp":28.4}
ignored: missing start… / end… markerMarkers 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 formatCompare with the test vector in section 7.2. The passphrase is case-sensitive
The device never receives commandsIt subscribed to the data topic instead of the command topic, or the subscribe happened before it connectedSubscribe 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 happensFormat mismatch (JSON vs Key=Value vs Value only), or markers/encryption not handledSee 6.2 and 6.3. Print the raw payload on the serial monitor first
Status says Offline, retryingWrong broker address or port, no internet, or the broker is busyCheck 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).

Still stuck? Write to support@zealyenlabs.in and include a screenshot of the Live monitor. Please remove your passphrase and any passwords first.