Web

Connect Web App to Raspberry Pi via MQTT Real-Time Tables

Step-by-step guide to connect a web app on laptop to Raspberry Pi using MQTT over WebSockets with Mosquitto broker for real-time restaurant table availability. Includes Paho client setup and troubleshooting.

1 answer 1 view

How to connect a web application on a laptop to a Raspberry Pi using MQTT for real-time table availability in a restaurant reservation system?

I have a web application for restaurant reservations running on my laptop. A Raspberry Pi serves as the central hub managing reserved and non-reserved tables. When a customer selects ‘no reservation’ in the web app, it needs to communicate with the Raspberry Pi via MQTT to check available tables and display them. What are the steps to implement this MQTT connection, including client setup on the web app side and broker configuration on the Raspberry Pi?

Connect your web app on the laptop to the Raspberry Pi using MQTT over WebSockets with a Mosquitto broker on the Pi for real-time table availability in your restaurant reservation system. Install and configure Mosquitto on the Raspberry Pi to listen on port 9001 for WebSocket connections, then integrate the Paho MQTT JavaScript client into your web app to subscribe to topics like restaurant/tables/available. This setup lets the Pi publish updates instantly when tables free up, displaying them live as customers select ‘no reservation’.


Contents


Installing Mosquitto MQTT Broker on Raspberry Pi

Getting MQTT up and running on your Raspberry Pi starts with Mosquitto, the go-to open-source broker. It’s lightweight, perfect for a Pi handling restaurant table status without bogging down the system. Fire up your terminal on the Pi—assuming you’re on Raspberry Pi OS (formerly Raspbian)—and run these commands:

sudo apt update
sudo apt install mosquitto mosquitto-clients -y

That pulls in the broker and some handy testing tools like mosquitto_pub and mosquitto_sub. Once installed, Mosquitto starts automatically as a service. Check its status with sudo systemctl status mosquitto. If it’s active (running), you’re good. But why stop there? Enable it to start on boot: sudo systemctl enable mosquitto.

By default, it listens on port 1883 for standard MQTT. For your web app, though, we need WebSockets—browsers can’t connect directly to raw MQTT sockets. That’s where the next step shines. Detailed installation steps like these come straight from guides like this one on SimpleSi, which nails the Pi-specific quirks.


Configuring the MQTT Broker for WebSockets

WebSockets bridge the gap between your laptop’s browser-based web app and the Pi’s MQTT broker. Without this, your JavaScript code hits a wall—browsers block non-WebSocket protocols for security.

Edit the config file: sudo nano /etc/mosquitto/mosquitto.conf. It might be mostly commented out, so add these lines at the end:

listener 1883
protocol mqtt

listener 9001
protocol websockets

Port 1883 handles native MQTT clients (like Python scripts on the Pi), while 9001 is your web app’s gateway. Save, then restart: sudo systemctl restart mosquitto. Tail the logs to confirm: sudo tail -f /var/log/mosquitto/mosquitto.log. Look for “Opening websockets listen socket on port 9001.” Boom—WebSockets enabled.

This dual-listener setup is key, as noted in Raspberry Pi forums discussions. Ever wonder why separate ports? WebSockets wrap MQTT in HTTP-like frames, so they can’t share 1883 without conflicts.


Firewall and Network Setup on Raspberry Pi

Don’t let firewalls kill your MQTT dreams. On the Pi, if UFW is active (sudo ufw status), allow the ports:

sudo ufw allow 1883
sudo ufw allow 9001
sudo ufw reload

Your laptop and Pi need to chat over the local network. Find the Pi’s IP with hostname -I—say it’s 192.168.1.100. From your laptop, ping it to confirm reachability. For restaurant use, consider static IPs or mDNS (like raspberrypi.local) via Avahi: sudo apt install avahi-daemon.

Pro tip: If your router blocks ports, forward them or stick to LAN. Security folks on Stack Overflow emphasize LAN-only for prototypes—expose publicly only with TLS later.


Setting Up the Paho MQTT Client in Your Web App

Time for the web side. Paho MQTT’s JavaScript library is battle-tested for browsers. Add it to your HTML via CDN—no npm fuss needed for a simple reservation app:

html
<script src="https://unpkg.com/paho-mqtt@1.1.0/paho-mqtt.min.js"></script>

In your JavaScript (say, when the ‘no reservation’ button clicks), create the client:

javascript
const client = new Paho.MQTT.Client('192.168.1.100', 9001, 'web_client_' + parseInt(Math.random() * 100, 10));

// Connection options
const connectOptions = {
 onSuccess: onConnect,
 useSSL: false,
 userName: 'optional_username', // Add auth if needed
 password: 'optional_password'
};

client.connect(connectOptions);

The random clientId avoids clashes. onSuccess calls your connection handler. Steve’s MQTT guide demos this exact pattern—plug and play.

What if the Pi’s IP changes? Hardcode for now, or use a domain. And handle disconnects: client.onConnectionLost = onConnectionLost;.


Handling Real-Time Table Availability Messages

Subscriptions make the magic happen. In onConnect, subscribe to your topic:

javascript
function onConnect() {
 console.log('Connected to MQTT broker on Raspberry Pi');
 client.subscribe('restaurant/tables/available');
}

client.onMessageArrived = function(message) {
 const tables = JSON.parse(message.payloadString);
 updateUI(tables); // Your function to show available tables
};

When a customer hits ‘no reservation’, the app fetches live data. The Pi publishes JSON like {"tables": ["1", "3", "5"], "timestamp": "2026-01-04T10:00:00Z"} to that topic. Parse it and light up your UI—green for free tables, maybe with a cheeky “Grab table 1 now!” popup.

Topics keep it organized: restaurant/tables/available, restaurant/tables/status/# for wildcards. This scales if you add floors or zones.


Publishing Table Updates from the Raspberry Pi

The Pi manages tables—sensors, buttons, whatever signals a table’s free. Use a Python script with Paho:

First, pip install paho-mqtt (or sudo apt install python3-paho-mqtt).

python
import paho.mqtt.publish as publish
import json
import time

broker = 'localhost'
port = 1883 # Native MQTT for local scripts

while True:
 available_tables = get_available_tables() # Your logic here
 payload = json.dumps({"tables": available_tables})
 publish.single('restaurant/tables/available', payload, hostname=broker, port=port)
 time.sleep(30) # Poll every 30s, or trigger on events

Run it as a service for always-on reliability. CLI test: mosquitto_pub -h localhost -t restaurant/tables/available -m '{"tables":["2","4"]}'.


Testing the Full MQTT Connection

Verify end-to-end. On Pi: mosquitto_sub -h localhost -t restaurant/tables/available.

In web app: Open dev tools, trigger connection/subscribe. Publish from Pi—message should pop in console and UI.

Cross-network: From laptop, mosquitto_sub -h 192.168.1.100 -p 1883 -t restaurant/tables/available (install clients if needed). For WebSockets, rely on browser logs.

Use MQTT Explorer (desktop app) pointing to Pi:9001 with WebSocket protocol. See subs/pubs live. If green across the board, your reservation system rocks real-time.


Troubleshooting MQTT Issues

Connection refused? Check logs—sudo journalctl -u mosquitto. Port 9001 not opening? Config syntax error; validate with mosquitto -c /etc/mosquitto/mosquitto.conf -v.

Web app errors like “WebSocket connection failed”? Firewall, wrong IP/port, or HTTPS forcing SSL (set useSSL: true if so). ClientId collisions? Randomize as shown.

Forum threads highlight restart after config changes. Slow polls? Switch to QoS 1 for reliability.

Network hiccups? Heartbeats via keepAliveInterval: 60. And on Pi reboots, tables reset? Persist state in SQLite.


Sources

  1. Using MQTT Over WebSockets with Mosquitto
  2. Installing Mosquitto MQTT broker on Raspberry Pi
  3. Websockets and mosquitto - Raspberry Pi Forums
  4. How to connect to a Mosquitto broker on a Raspberry Pi through web sockets?
  5. Websocket for Mosquitto 1.6.8 - Raspberry Pi Forums

Conclusion

You’ve now got a solid MQTT Raspberry Pi setup piping real-time table availability to your web app—customers see free spots instantly on ‘no reservation’ clicks. From Mosquitto WebSockets on port 9001 to Paho client subscriptions, this handles restaurant bustle without breaking a sweat. Scale it with auth, TLS for production, or more topics for orders. Test thoroughly, and watch reservations flow.

Authors
Verified by moderation
Moderation
Connect Web App to Raspberry Pi via MQTT Real-Time Tables