# Tutorial — MQTT Mosquitto Installation (Secure Setup)

Environment used for this guide:

- Hardware: Raspberry Pi 5
- Operating System: Ubuntu Server 25.10 (64-bit)
- Network: Local home network setup
- Services installed: Mosquitto

## 1. Install Mosquitto

```bash
sudo apt install mosquitto mosquitto-clients -y
```

Enable autostart:

```bash
sudo systemctl enable mosquitto
```

---

## 2. Configure authentication

Create config file:

```bash
sudo nano /etc/mosquitto/conf.d/default.conf
```

Insert:

```
listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwd
```

---

## 3. Create MQTT user

```bash
sudo mosquitto_passwd -c /etc/mosquitto/passwd mqttuser
```

Secure permissions:

```bash
sudo chown mosquitto:mosquitto /etc/mosquitto/passwd
sudo chmod 600 /etc/mosquitto/passwd
```

Restart service:

```bash
sudo systemctl restart mosquitto
```

---

## 4. Test MQTT connection

Subscriber:

```bash
mosquitto_sub -h localhost -t test -u mqttuser -P PASSWORD
```

Publisher:

```bash
mosquitto_pub -h localhost -t test -m "hello world" -u mqttuser -P PASSWORD
```

## 5. Connect to the broker from another device in the network

First determine the Raspberry Pi IP address:
```bash
hostname -I
```
Example:

192.168.178.41

Now connect from another computer in the same network.

Subscriber:

mosquitto_sub -h 192.168.178.41 -t test -u mqttuser -P PASSWORD

Publisher:

mosquitto_pub -h 192.168.178.41 -t test -m "hello from laptop" -u mqttuser -P PASSWORD

If everything works correctly, the message appears instantly in the subscriber terminal.


## 6. Send structured data to the broker (example IoT payloads)

MQTT topics are structured like folders:

home/livingroom/temperature
home/kitchen/light
home/garden/humidity

Example: send temperature data

mosquitto_pub \
-h 192.168.178.41 \
-t home/livingroom/temperature \
-m "22.4" \
-u mqttuser \
-P PASSWORD

Example: receive temperature data

mosquitto_sub \
-h 192.168.178.41 \
-t home/livingroom/temperature \
-u mqttuser \
-P PASSWORD

Example: send JSON sensor data

mosquitto_pub \
-h 192.168.178.41 \
-t home/weatherstation \
-m '{"temperature":21.8,"humidity":48}' \
-u mqttuser \
-P PASSWORD

Receive JSON stream:

mosquitto_sub \
-h 192.168.178.41 \
-t home/weatherstation \
-u mqttuser \
-P PASSWORD

Example: listen to all MQTT traffic (debugging mode)

mosquitto_sub \
-h 192.168.178.41 \
-t "#" \
-u mqttuser \
-P PASSWORD

The # wildcard subscribes to all topics.
