<!--
.. title: Introduction to KaZa
.. slug: index
-->

# Introduction to KaZa

KaZa is an open-source home automation platform built entirely on Qt and QML. It provides a unified object model that bridges physical devices — KNX bus sensors and actuators, MQTT topics, HTTP-based appliances — into a single namespace accessible in real time from any platform: Linux, Windows, or Android.

Unlike many home automation systems that rely on web dashboards, KaZa produces native applications. The server runs as a headless systemd daemon on Linux (a Raspberry Pi is the typical target). The client is a native Qt application compiled for each target platform. The user interface is entirely written in QML, giving integrators the full power of a declarative UI toolkit with smooth animations, hardware-accelerated rendering, and full offline capability.

---

## Architecture Overview

KaZa is built around a client/server model with a plugin-based extension system.

```
┌──────────────────────────────────────────────────────────────────┐
│                       User Application                            │
│                    (integrator QML code)                          │
│                                                                   │
│   ┌─────────────┐  ┌─────────────┐  ┌───────────┐  ┌─────────┐ │
│   │  KNX Plugin │  │ MQTT Plugin │  │  Helios   │  │ Custom  │ │
│   │  org.kazoe  │  │  org.kazoe  │  │  Plugin   │  │ Plugin  │ │
│   │   .knx 1.0  │  │  .mqtt 1.0  │  │           │  │         │ │
│   └──────┬──────┘  └──────┬──────┘  └─────┬─────┘  └────┬────┘ │
│          └────────────────┴───────────────-┴─────────────┘       │
│                                   │ KaZaObject                   │
└───────────────────────────────────┼──────────────────────────────┘
                                    │
┌───────────────────────────────────┼──────────────────────────────┐
│                    KaZa Server Core (kazad)                       │
│                                   │                               │
│   ┌────────────┐        ┌─────────▼──────┐        ┌──────────┐  │
│   │ KaZaManager│◄───────│  QML Engine    │        │ systemd  │  │
│   │ (singleton)│        │ (user main.qml)│        │ notify   │  │
│   └─────┬──────┘        └────────────────┘        └──────────┘  │
│         │                                                         │
│   ┌─────┴──────────────────┬──────────────────┐                  │
│   │                        │                  │                  │
│ ┌─▼──────┐         ┌───────▼──┐      ┌────────▼────────┐        │
│ │SSL Port│         │ Control  │      │   PostgreSQL    │        │
│ │  1756  │         │Port 43500│      │ (optional log)  │        │
│ └───┬────┘         └──────────┘      └─────────────────┘        │
│     │                                                            │
└─────┼──────────────────────────────────────────────────────────--┘
      │  KaZa Protocol (binary, mutual TLS)
      │
┌─────┼─────────────────────────────────────────────────────┐
│     │            Connected Clients                         │
│  ┌──▼──────────┐  ┌─────────────┐  ┌─────────────┐       │
│  │ Linux Client│  │  Android    │  │  Windows    │       │
│  └─────────────┘  └─────────────┘  └─────────────┘       │
└─────────────────────────────────────────────────────────--┘
```

---

## Components

### KaZa Server (`kazad`)

The server is the central piece of the system. It runs as a Linux daemon (`systemd` service) and is the only always-on process. It is designed to run on low-power hardware such as a Raspberry Pi, though any x86\_64 or ARM Linux machine works.

The server has two responsibilities:

**1. Running the user automation QML**

The server embeds a QML engine that loads the integrator's `main.qml` file. This file is where all automation logic lives: plugin instantiation, object bindings, schedulers, database logging. The QML runs continuously for as long as the daemon is alive.

**2. Serving clients**

The server opens two TCP ports:

| Port | Protocol | Purpose |
|------|----------|---------|
| 1756 (configurable) | Binary, mutual TLS | Real-time client connections |
| 43500 (configurable) | Plain TCP, localhost only | Administration and certificate provisioning |

The SSL port carries the KaZa binary protocol and requires mutual TLS: both server and client must present a certificate signed by a shared Certificate Authority. On connection, the server sends the complete current state of all objects to the new client, then streams only value changes.

The control port (43500) is intended for localhost use only. It exposes text commands for querying and setting objects, and a special command that generates signed client certificates on demand (the provisioning flow for new devices).

**Key C++ classes:**

| Class | File | Role |
|-------|------|------|
| `KaZaManager` | `src/kazamanager.h` | Central singleton — owns the QML engine, object registry, and both ports |
| `KaZaObject` | `src/kazaobject.h` | Base class for every automation object. Carries `name`, `value` (QVariant), and `unit` |
| `KzObject` | `src/kzobject.h` | QML reference type — binds to a named `KaZaObject` by string |
| `KaZaElement` | `src/kazaelement.h` | Mandatory root element for user server QML |
| `KaZaConnection` | `src/kazaconnection.h` | Handles one SSL client connection |
| `KaZaRemoteConnection` | `src/kazaremoteconnection.h` | Handles control port commands |
| `KaZaCertificateGenerator` | `src/kazacertificategenerator.h` | OpenSSL C API wrapper for on-demand client certificate generation |
| `Scheduler` | `src/scheduler.h` | Cron-like QML element for time-based automation |

### KaZa Client

The client is a native Qt application compiled for Linux, Windows, or Android. It connects to the server over the SSL port using mutual TLS and keeps a local mirror of all registered objects. When the server pushes a value change the client updates its mirror immediately; when the user acts on the UI the client sends a write frame to the server.

The client is a "shell": it provides the connection logic, the object mirror, and a `manager` singleton exposed to QML. The actual UI — every screen, widget, and navigation flow — comes from the user application's compiled `.rcc` resource bundle, which the server distributes over the SSL connection on first connect. This means deploying a UI update requires only replacing the `.rcc` file on the server; all clients download it automatically on their next connection.

**Supported platforms:** Linux x86\_64, Windows x86\_64, Android arm64.

### KaZa Protocol

A compact binary protocol shared between server and client (the `KaZa-Protocol` submodule). All frames have a 5-byte header: 4 bytes payload length + 1 byte type.

| Frame Type | Direction | Purpose |
|------------|-----------|---------|
| `FRAME_SYSTEM` (0) | Both | Text commands: PING/PONG, POSITION, notifications |
| `FRAME_FILE` (1) | Server→Client | Distribute client UI bundle (`.rcc`) |
| `FRAME_OBJVALUE` (2) | Both | Object value update — most frequent frame |
| `FRAME_DBQUERY` (3) | Client→Server | Execute SQL query on the server database |
| `FRAME_DBRESULT` (4) | Server→Client | Return SQL result set |
| `FRAME_SOCKET_CONNECT` (5) | Client→Server | Open a proxied TCP connection through the server |
| `FRAME_SOCKET_DATA` (6) | Both | Data through a proxied TCP connection |
| `FRAME_SOCKET_STATE` (7) | Both | State of a proxied TCP connection |
| `FRAME_VERSION` (255) | Both | Protocol version negotiation — mandatory first frame |

A `FRAME_OBJVALUE` payload is minimal: 2 bytes for the object ID, the value serialized with Qt's `QDataStream`, and 1 boolean byte for the confirm flag. A typical boolean or integer update is under 10 bytes of payload. Values can be `bool`, `int`, `double`, `QString`, `QDateTime`, or any other type supported by `QDataStream`.

### KaZa Control Panel

A Qt Widgets desktop application (Linux and Windows) for administration and debugging. It connects to the server's control port and displays the live value of every registered object in a table. Values can be inspected and manually overridden. The control panel also provides a GUI for generating SSL client certificates, which removes the need to use the command-line provisioning flow for day-to-day device onboarding.

---

## Security Model

KaZa uses **mutual TLS** for all client connections. Both the server and every client present a certificate signed by a single private Certificate Authority that the integrator creates during initial setup.

- The CA key and certificate live on the server. The CA is never exposed to clients.
- The server generates signed client certificates on request through the control port's `clientconf?` command (or through the Control Panel GUI). The client's private key is encrypted with a user-chosen password before being returned.
- The control port (43500) transmits the admin password in plain text over TCP and should be firewalled to localhost or trusted network segments only.

Certificate files are stored in `/var/lib/kazad/`:

| File | Purpose | Permissions |
|------|---------|-------------|
| `ca.cert.pem` | CA certificate — trust anchor for all clients | 644 |
| `ca.key` | CA private key — keep offline if possible | 600 |
| `server.cert.pem` | Server identity certificate | 644 |
| `server.key` | Server private key | 600 |
| `<user>.cert.pem` | Per-client certificate | 644 |
| `<user>.key` | Per-client private key (DES3-CBC encrypted) | 600 |

---

## Plugin Ecosystem

Plugins are standard Qt QML extension modules. They are installed into the system Qt QML path (e.g. `/usr/lib/qml/org/kazoe/<name>/`) and imported in user QML with a normal `import` statement. Plugins are packaged as Debian `.deb` files and installed alongside the server package.

### KNX (`org.kazoe.knx`)

Integrates a KNX installation via `knxd`. The integrator provides an ETS `.knxproj` export file; the plugin parses it and creates one `KaZaObject` per group address. Group address values flow bidirectionally: a KNX telegram updates the object and propagates to clients; a client write sends a KNX telegram to the bus.

```qml
import org.kazoe.knx 1.0

KnxBus {
    knxd:    "ip:192.168.1.250"
    knxProj: "/etc/kaza/home.knxproj"
}
```

After instantiation, all group addresses from the ETS project are accessible by name as `KzObject` bindings. The object names are taken from the ETS group address names.

**Dependencies:** `knxd` daemon running and reachable at the configured address.

### MQTT (`org.kazoe.mqtt`)

Connects to a Mosquitto (or any compatible MQTT) broker. Each `MqttTopic` child maps a topic to a `KaZaObject`; incoming messages update the object's value; writing to the object publishes to the topic.

```qml
import org.kazoe.mqtt 1.0

MqttClient {
    hostname: "localhost"
    port:     1883
    clientId: "kaza-server"

    MqttTopic { topic: "home/sensors/temperature" }
    MqttTopic { topic: "home/sensors/humidity" }
}
```

**Dependencies:** A running MQTT broker (Mosquitto recommended).

### Helios (`org.kazoe.helios`)

Integrates a **Helios Easycontrol** controlled ventilation unit (VMC/HRV) via its HTTP API. Exposes:
- Fan speed (supply and extract)
- Ventilation mode
- Inside and outside temperature sensors
- Filter status

**Dependencies:** Helios Easycontrol unit accessible on the local network.

### Palazzetti (`org.kazoe.palazzetti`)

Integrates a **Palazzetti** pellet stove via its ConnBox HTTP/JSON interface. Exposes:
- Stove on/off state
- Target temperature
- Fan speed
- Pellet feed status
- Alarm codes

**Dependencies:** Palazzetti ConnBox connected to the stove and accessible on the local network.

---

## Server Installation

### Requirements

- Debian 11+ / Ubuntu 22.04+ / Raspberry Pi OS 64-bit
- Qt 6.2+ runtime libraries
- OpenSSL 1.1+ or 3.0+
- systemd
- PostgreSQL 12+ (optional, for logging and graphs)

### From the Debian Repository

```bash
# Add the KaZa repository
echo "deb https://repo.kazoe.org/kaza stable main" | \
    sudo tee /etc/apt/sources.list.d/kaza.list
sudo apt update

# Install server
sudo apt install kaza-server-bin

# Install plugins as needed
sudo apt install kaza-knx kaza-mqtt kaza-helios kaza-palazzetti
```

### Systemd Service

The package installs a systemd service (`kazad.service`). After configuring `/etc/kazad.conf`, enable and start:

```bash
sudo systemctl enable kazad
sudo systemctl start kazad
sudo journalctl -u kazad -f    # tail logs
```

### Configuration: `/etc/kazad.conf`

```ini
[ssl]
port=1756
keypassword="server_key_password"
hostname="home.example.com"      # Hostname clients will connect to

[control]
port=43500
password="admin_password"
enable=true

[database]                       # Optional — remove section if not used
driver="QPSQL"
hostname="127.0.0.1"
port=5432
dbName="kaza"
username="kaza"
password="db_password"

[qml]
server=/opt/kaza/main.qml        # Integrator's server-side QML
client=/opt/kaza/app.rcc         # Integrator's compiled client bundle
```

### Generating Certificates

```bash
# From the server — generates CA, server cert, and an initial client cert
sudo /usr/share/kazad/make_certificate.sh \
    "home.example.com" \
    "client_key_password" \
    "server_key_password"
```

Generated files are placed in `/var/lib/kazad/`. For additional client devices, use the control port or the KaZa Control Panel.

---

## Packaging and Distribution

All KaZa components are distributed as Debian `.deb` packages targeting Debian 11+ and Ubuntu 22.04+. The build system uses CMake with CPack.

| Package | Contents |
|---------|---------|
| `kaza-server-bin` | Server daemon (`kazad`), `kls` tool, systemd unit |
| `kaza-server-dev` | Headers (`kazaobject.h`, `kazamanager.h`) and `libKaZaLib.so` for plugin development |
| `kaza-knx` | KNX plugin |
| `kaza-mqtt` | MQTT plugin |
| `kaza-helios` | Helios ventilation plugin |
| `kaza-palazzetti` | Palazzetti pellet stove plugin |

**Target platforms:**

| Role | Platform |
|------|---------|
| Server | Linux x86\_64, armhf (Raspberry Pi 2/3), arm64 (Raspberry Pi 3B+/4) |
| Client | Linux x86\_64, Windows x86\_64, Android arm64 |
| Control Panel | Linux x86\_64, Windows x86\_64 |

---

## Real-World Example: KaZaExample

KaZaExample is a production home automation installation that demonstrates the full KaZa stack. It integrates:

- **KNX** — lights, shutters, presence detectors, power meters for 20+ individual circuits, hot water boiler temperature sensors, EDF tariff mode actuators
- **Helios** — controlled ventilation (VMC) with inside temperature monitoring and automation
- **Victron Energy** — solar inverter and battery system (state of charge, grid export/import, solar production)
- **Tesla** — electric vehicle charge state and smart charging control
- **Palazzetti** (via custom HTTP) — swimming pool controller (Ines: water temperature, filtration, pH, robot)
- **HTTP REST** — French electricity Tempo tariff API (next-day tariff color) for smart scheduling
- **Internal objects** — WiFi-based presence detection for household members
- **PostgreSQL** — time-series logging of power consumption per circuit, temperatures, water levels

The server-side QML spans 10 files:

| File | Contents |
|------|---------|
| `main.qml` | Root element; imports sub-components; fetches Tempo tariff data every 15 min |
| `Knx.qml` | KNX bus configuration and per-circuit power logging to database |
| `Helios.qml` | Ventilation system object mapping and automation |
| `Victron.qml` | Solar/battery object mapping (via MQTT) |
| `Tesla.qml` | EV charge state and smart charging control |
| `Program.qml` | Schedules: morning routines, evening mode, detector resets |
| `DataLogger.qml` | Periodic temperature and water level inserts |
| `Piscine.qml` | Pool controller HTTP integration |
| `Wifi.qml` | Network presence detection for household members |
| `Ines.qml` | Additional pool automation |

The client-side QML provides a mobile-friendly UI (360×668 portrait layout) with:

- **Home page** — temperatures, battery level, rain water tank, EDF tariff indicator, mode buttons (TV mode, night mode)
- **Floor plan views** — ground floor and upper floor touch targets for lights and shutters, room by room
- **Energy screens** — power consumption by circuit, solar production history, grid exchange graphs
- **Device screens** — EV charging, ventilation, pool status
- **History screens** — min/average/max trends for any object, selectable time range
- **Debug page** — live list of all object values for troubleshooting
- **Settings** — SSL connection configuration, certificate management

The client widget library (`Widget/`) includes over 15 reusable components: light switches, dimmers, shutter controls, temperature sensors, power meters, battery indicators, tank level gauges, and presence dots.
