Subscribing to Data

Receive variable values in real time over MQTT — no polling required.

Subscribing to data

Similar to an HTTP GET, subscribing lets you receive values from Surfact. The key difference: you don't have to continuously poll the server. When a variable's value changes, Surfact notifies you automatically.

This saves data requests, processing time on your device, battery life, and cost — making MQTT ideal for controlling actuators and real-time device interactions.

Topic structure

Subscribe to variables using this topic pattern:

/v2.0/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}
/v1.6/devices/{DEVICE_LABEL}/{VARIABLE_LABEL}
ParameterDescription
{DEVICE_LABEL}Your device's unique label
{VARIABLE_LABEL}The variable you want to monitor

Examples

Python (paho-mqtt)

import paho.mqtt.client as mqtt

token = "your-surfact-token"
device_label = "smart-door"
variable_label = "lock-status"

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    topic = f"/v2.0/devices/{device_label}/{variable_label}"
    client.subscribe(topic)

def on_message(client, userdata, msg):
    print(f"Received: {msg.payload.decode()} on topic {msg.topic}")

client = mqtt.Client(client_id="my-device-12345678901234567890")
client.username_pw_set(username=token, password="")
client.on_connect = on_connect
client.on_message = on_message
client.connect("api.surfact.com", 8883)
client.loop_forever()

JavaScript (mqtt.js)

const mqtt = require('mqtt');

const token = 'your-surfact-token';
const deviceLabel = 'smart-door';
const variableLabel = 'lock-status';

const client = mqtt.connect('mqtts://api.surfact.com:8883', {
  username: token,
  password: '',
  clientId: 'my-device-12345678901234567890'
});

client.on('connect', () => {
  const topic = `/v2.0/devices/${deviceLabel}/${variableLabel}`;
  client.subscribe(topic, (err) => {
    if (!err) console.log(`Subscribed to ${topic}`);
  });
});

client.on('message', (topic, message) => {
  console.log(`Received: ${message.toString()} on topic ${topic}`);
});

Subscribing to multiple variables

Subscribe to several variables by calling subscribe for each topic:

topics = [
    f"/v2.0/devices/{device_label}/temperature",
    f"/v2.0/devices/{device_label}/humidity",
    f"/v2.0/devices/{device_label}/pressure",
]
for topic in topics:
    client.subscribe(topic)

Choosing a topic

There are two ways to subscribe to a single variable, depending on what you need back:

TopicReturnsImmediate value on connectUpdates
/v2.0/devices/{device}/{variable}/lvValue only✅ Yes✅ Yes
/v2.0/devices/{device}/{variable}Full JSON dot (value, timestamp, context)✅ Yes✅ Yes

For monitoring many variables or devices at once, see Subscribing with Wildcards.


Did this page help you?