Advanced IoT & Networking

MQTT in WebVB Studio

Connect to any MQTT broker and build real-time IoT dashboards with live gauges, charts, and data visualizations — all from your browser using VB6 or Python.

What is MQTT?

MQTT (Message Queuing Telemetry Transport) is the industry-standard lightweight messaging protocol for IoT. It enables devices, sensors, and software to communicate in real time with minimal bandwidth and low latency. MQTT uses a publish/subscribe model — clients publish data to topics, and subscribers receive updates instantly.

🔌

Lightweight

Minimal overhead — ideal for constrained devices and networks

Real-Time

Instant message delivery via publish/subscribe pattern

🌍

Universal

Works with any MQTT broker — Mosquitto, HiveMQ, EMQX, and more

How MQTT Works in WebVB Studio

WebVB Studio includes a built-in MQTT client that connects to MQTT brokers over WebSockets (WSS/WS). You can subscribe to topics, publish messages, and bind incoming data directly to visual controls like Gauges, Charts, Labels, and Grids — all without writing complex networking code.

Architecture Overview

🔌
IoT Devices Sensors, inverters,
smart home, PLCs
📡
MQTT Broker Mosquitto, HiveMQ,
Venus OS, EMQX
🖥️
WebVB Studio Gauges, Charts,
Dashboards, Alerts
WebSocket Connection: WebVB Studio connects to MQTT brokers via WebSocket (ws:// or wss://). Most modern brokers support this out of the box. For Mosquitto, enable the WebSocket listener on port 9001.

Quick Start: Build an MQTT Dashboard

Follow these steps to build a real-time IoT dashboard in WebVB Studio that subscribes to MQTT topics and displays live data on Gauge controls.

1

Set Up the Form

Open WebVB Studio and add these controls to your form:

📝
TextBoxtxtBroker Broker URL (e.g. ws://broker.hivemq.com:8000/mqtt)
📝
TextBoxtxtTopic Topic to subscribe (e.g. sensor/temperature)
🔘
CommandButtoncmdConnect Connect/Disconnect button
📊
GaugegaugeValue Displays live numeric values
🏷️
LabellblStatus Connection status indicator
📋
ListBoxlstMessages Message log for incoming MQTT messages
2

Write the MQTT Code

Double-click the form and add this code. Choose VB6 or Python:

Visual Basic 6
Dim mqtt As Object
Dim connected As Boolean

Private Sub cmdConnect_Click()
    If connected Then
        mqtt.Disconnect
        cmdConnect.Caption = "Connect"
        lblStatus.Caption = "Disconnected"
        lblStatus.ForeColor = vbRed
        connected = False
        Exit Sub
    End If
    
    Set mqtt = Inet1.MqttConnect( _
        txtBroker.Text, _
        "webvb-client-" & Int(Rnd * 9999))
    
    mqtt.Subscribe txtTopic.Text
    
    cmdConnect.Caption = "Disconnect"
    lblStatus.Caption = "Connected"
    lblStatus.ForeColor = vbGreen
    connected = True
End Sub

Private Sub mqtt_OnMessage(topic, message)
    Dim value As Double
    value = Val(message)
    
    gaugeValue.Value = value
    lstMessages.AddItem _
        Time & " [" & topic & "] " & message
End Sub

Private Sub mqtt_OnError(errMsg)
    lblStatus.Caption = "Error: " & errMsg
    lblStatus.ForeColor = vbRed
    connected = False
    cmdConnect.Caption = "Connect"
End Sub
Python
import random, time

mqtt = None
connected = False

def cmdConnect_Click():
    global mqtt, connected
    if connected:
        mqtt.Disconnect()
        cmdConnect.Caption = "Connect"
        lblStatus.Caption = "Disconnected"
        lblStatus.ForeColor = "red"
        connected = False
        return
    
    client_id = f"webvb-{random.randint(0,9999)}"
    mqtt = Inet1.MqttConnect(
        txtBroker.Text, client_id)
    
    mqtt.Subscribe(txtTopic.Text)
    
    cmdConnect.Caption = "Disconnect"
    lblStatus.Caption = "Connected"
    lblStatus.ForeColor = "green"
    connected = True

def mqtt_OnMessage(topic, message):
    value = float(message)
    gaugeValue.Value = value
    lstMessages.AddItem(
        f"{time.strftime('%H:%M:%S')} [{topic}] {message}")

def mqtt_OnError(errMsg):
    global connected
    lblStatus.Caption = f"Error: {errMsg}"
    lblStatus.ForeColor = "red"
    connected = False
    cmdConnect.Caption = "Connect"
3

Run and Test

Press F5 to run. Enter your broker URL and topic, click Connect, and watch live data flow into your Gauge and message log.

Free Public Broker for Testing: Use ws://broker.hivemq.com:8000/mqtt with any topic like test/webvb/temperature. Publish test messages using any MQTT client (MQTTX, mosquitto_pub, etc.).

MQTT Features in WebVB Studio

Subscribe to Multiple Topics

Subscribe to any number of topics with wildcards (+ and #) for flexible topic filtering.

Publish Messages

Send commands and data back to devices. Control relays, set thresholds, trigger actions on your IoT devices.

QoS Levels 0, 1, 2

Control message delivery guarantees — from fire-and-forget (QoS 0) to exactly-once delivery (QoS 2).

Secure Connections

Connect using WSS (WebSocket Secure) with username/password authentication for production deployments.

JSON Message Parsing

Automatically parse JSON payloads from MQTT messages and extract values for display in controls.

Visual Gauge Controls

Bind MQTT data directly to beautiful gauge, chart, and meter controls for real-time visualization.

MQTT Use Cases

WebVB Studio's MQTT integration opens up a huge range of IoT and automation possibilities:

Victron Energy Monitoring

Connect to Victron's Venus OS MQTT broker to monitor battery SOC, solar yield, inverter load, and grid consumption in real time. Build custom dashboards tailored to your installation.

Learn more about Victron integration

Smart Home Automation

Monitor and control Home Assistant, Tasmota, Zigbee2MQTT, and other smart home devices. Build a central control panel for lights, thermostats, door sensors, and cameras.

Industrial IoT & SCADA

Monitor PLCs, temperature sensors, pressure gauges, and production line status. Build lightweight HMI panels for factory floor monitoring.

Weather Stations & Agriculture

Collect data from ESP32/Arduino weather stations via MQTT. Visualize temperature, humidity, soil moisture, and wind speed in real-time dashboards.

Fleet & Asset Tracking

Track GPS coordinates, vehicle status, and telemetry data from MQTT-enabled devices. Display on maps and charts within your WebVB application.

Example: Victron Energy MQTT Dashboard

Victron Energy's Venus OS (GX device / Cerbo GX) publishes all system data via MQTT. WebVB Studio can connect directly to your Venus OS device and display live solar, battery, and grid data. Here's a practical example:

Victron Venus OS — Common MQTT Topics
' Battery State of Charge
N/{portalId}/system/0/Batteries/Dc/0/Soc

' Battery Voltage
N/{portalId}/system/0/Dc/Battery/Voltage

' Battery Current
N/{portalId}/system/0/Dc/Battery/Current

' Battery Power
N/{portalId}/system/0/Dc/Battery/Power

' PV/Solar Yield (Watts)
N/{portalId}/system/0/Dc/Pv/Power

' Grid Power (import/export)
N/{portalId}/system/0/Ac/Grid/L1/Power

' AC Consumption
N/{portalId}/system/0/Ac/Consumption/L1/Power

' Inverter State
N/{portalId}/vebus/276/State
VB6 — Victron Dashboard Example
Dim mqtt As Object
Dim portalId As String

Private Sub Form_Load()
    portalId = "your_portal_id"
    txtBroker.Text = "ws://venus.local:9001"
End Sub

Private Sub cmdConnect_Click()
    Set mqtt = Inet1.MqttConnect( _
        txtBroker.Text, "webvb-victron")
    
    ' Subscribe to key Victron topics
    mqtt.Subscribe "N/" & portalId & "/system/0/Dc/Battery/Soc"
    mqtt.Subscribe "N/" & portalId & "/system/0/Dc/Battery/Voltage"
    mqtt.Subscribe "N/" & portalId & "/system/0/Dc/Battery/Power"
    mqtt.Subscribe "N/" & portalId & "/system/0/Dc/Pv/Power"
    mqtt.Subscribe "N/" & portalId & "/system/0/Ac/Grid/L1/Power"
    
    ' Keep-alive: required by Venus OS
    mqtt.Publish "R/" & portalId & "/system/0/Serial", ""
    
    lblStatus.Caption = "Connected to Venus OS"
    lblStatus.ForeColor = vbGreen
End Sub

Private Sub mqtt_OnMessage(topic As String, message As String)
    Dim value As Double
    ' Venus OS sends JSON: {"value": 85.3}
    value = Val(Mid(message, InStr(message, ":") + 1))
    
    If InStr(topic, "Soc") > 0 Then
        gaugeBattery.Value = value
        lblBattery.Caption = value & "%"
    ElseIf InStr(topic, "Pv/Power") > 0 Then
        gaugeSolar.Value = value
        lblSolar.Caption = value & " W"
    ElseIf InStr(topic, "Grid") > 0 Then
        gaugeGrid.Value = value
        lblGrid.Caption = value & " W"
    ElseIf InStr(topic, "Battery/Power") > 0 Then
        lblBattPower.Caption = value & " W"
    ElseIf InStr(topic, "Voltage") > 0 Then
        lblVoltage.Caption = Format(value, "0.0") & " V"
    End If
End Sub
Venus OS MQTT Setup: Enable MQTT on your Cerbo GX / Venus OS: go to Settings → Services → MQTT, and enable it. Also enable the WebSocket listener (MQTT on WebSocket) on port 9001 for browser-based connections.

Publishing MQTT Messages

Besides subscribing to data, you can also publish messages to control devices, send commands, or trigger automations:

VB6
' Publish a simple value
mqtt.Publish "home/livingroom/light", "ON"

' Publish JSON data
mqtt.Publish "device/config", _
    "{""threshold"": 75, ""unit"": ""C""}"

' Publish with QoS
mqtt.Publish "alerts/critical", _
    "Temperature too high!", 2

' Victron: Write a value
mqtt.Publish "W/" & portalId & _
    "/settings/0/Settings/CGwacs" & _
    "/MaxDischargePower", _
    "{""value"": 5000}"
Python
# Publish a simple value
mqtt.Publish("home/livingroom/light", "ON")

# Publish JSON data
import json
data = {"threshold": 75, "unit": "C"}
mqtt.Publish("device/config",
    json.dumps(data))

# Publish with QoS
mqtt.Publish("alerts/critical",
    "Temperature too high!", 2)

# Victron: Write a value
mqtt.Publish(
    f"W/{portal_id}/settings/0"
    "/Settings/CGwacs/MaxDischargePower",
    '{"value": 5000}')

Tips & Best Practices

Use a Unique Client ID

MQTT brokers disconnect existing sessions when a new client connects with the same ID. Use random or timestamped client IDs to avoid conflicts.

Handle Disconnections Gracefully

Implement the mqtt_OnError event to detect connection loss and provide visual feedback. Add a reconnect button or auto-reconnect logic.

Throttle High-Frequency Data

If a topic publishes data very frequently (e.g. every 100ms), use a Timer control to update the UI at a fixed interval instead of on every message to keep the UI responsive.

Parse JSON Payloads

Many MQTT devices send JSON. Use WebVB's built-in JSON parsing functions or Python's json.loads() to extract specific fields from complex payloads.

Use Topic Wildcards for Efficiency

Subscribe to N/{portalId}/system/0/# to receive all system data with a single subscription, then filter by topic in your OnMessage handler.

📡

Try the MQTT IoT Dashboard Example

Open the ready-made MQTT IoT Dashboard example in WebVB Studio and start monitoring your devices in seconds.