Skip to main content

MQTT

Before getting started

To follow the steps below you need to have followed the steps in :

  1. auth section to get tenant-id and token
  2. getting started to get a point-id

MQTT Credentials

The mqtt credentials are valid at tenantlevel, and will be the same for any device on that tenant.

Query

query GET_MQTT_CREDENTIALS {
tenant {
settings {
mqtt {
url
port
username
password
}
}
}
}
# headers
{"x-tenant-id": "<tenant>"}
Response
{
"data": {
"tenant": {
"settings": {
"mqtt": {
"url": "mqtt://mqtt.dimensionfour.io:1883",
"port": "1883",
"username": "d4-mqtt-tenant-username",
"password": "njfK4P93KMns3aH2"
}
}
}
}
}

Send signals

MQTT Connection

  1. Server: mqtt.dimensionfour.io
  2. Username from query response
  3. Password from query response
  4. ClientId must be unique

Topic

"POINT/PUSH"

Payload

{
"pointId":"507f1f77bcf86cd799439011",
"tenantId":"my-tenant-name",
"tenantKey":"abcd123abcd123abcd123",
"signals":[
{
"value":"22.23",
"unit":"CELSIUS_DEGREES",
"type":"Temperature",
"timestamp":"2017-07-12T12:53:27+00:00"
}
]
}

Example

Bash

export POINTID=pointid
export TENANTID=tenantid
export TENANTKEY=tenantid
export MQTTUNAME=mqttusername
export MQTTPWORD=mqttpassword

Requirements

mosquitto_pub (Comes with mosquitto CLI. Tested with 1.6.9)

echo "
{
\"pointId\":\"${POINTID}\",
\"tenantId\":\"${TENANTID}\",
\"tenantKey\":\"${TENANTKEY}\",
\"signals\":[
{
\"value\":\"22.23\",
\"unit\":\"CELSIUS_DEGREES\",
\"type\":\"Temperature\",
\"timestamp\":\"2019-07-12T12:53:27+00:00\"
}
]
}
" | tr -d '\n' | mosquitto_pub -l -h mqtt.dimensionfour.io -t POINT/PUSH -u ${MQTTUNAME} -P ${MQTTPWORD}

Python

Requirements

paho-mqtt (tested with v1.5.1)

pip install paho-mqtt

Code

# send_signal.py
# Environment variables:
# TENANT_ID, TENANT_KEY, POINT_ID, MQTT_USERNAME, MQTT_PASSWORD
# Set them prior to running or when running script:
# $ TENANT_ID=myid (+ the others) python send_signal.py

import paho.mqtt.client as mqtt
import json
import datetime
import random
import os

POINT_ID = os.environ["POINT_ID"]
TENANT_ID = os.environ["TENANT_ID"]
TENANT_KEY = os.environ["TENANT_KEY"]
MQTT_USERNAME = os.environ["MQTT_USERNAME"]
MQTT_PASSWORD = os.environ["MQTT_PASSWORD"]
MQTT_ADDRESS = "mqtt.dimensionfour.io"
MQTT_PORT = 1883

mqttc = mqtt.Client()
mqttc.username_pw_set(username=MQTT_USERNAME, password=MQTT_PASSWORD)
mqttc.connect(MQTT_ADDRESS, MQTT_PORT, 60)
mqttc.loop_start()

print("Sending data to dimensionfour.io:")
payload = {
"pointId": POINT_ID,
"tenantId": TENANT_ID,
"tenantKey": TENANT_KEY,
"signals": [
{
"value": str(round((random.randint(1800, 2200) / 100.0), 2)),
"unit": "CELSIUS_DEGREES",
"type": "Temperature",
"timestamp": datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
+ "+00:00",
}
],
}

print(json.dumps(payload, indent=2, ensure_ascii=False))
(rc, mid) = mqttc.publish("POINT/PUSH", json.dumps(payload, ensure_ascii=False), qos=2)
print("Publish result: ", rc)
print("Message id: ", str(mid))

mqttc.loop_stop()
mqttc.disconnect()

Javascript (node.js)

Requirements

mqtt (tested with v4.3.7)

npm install mqtt

Code

/*
send_signal.js
Environment variables:
TENANT_ID, TENANT_KEY, POINT_ID, MQTT_USERNAME, MQTT_PASSWORD
Set them prior to running or when running script:
$ TENANT_ID=myid (+ the others) node send_signal.js
*/

const mqtt = require("mqtt");

const POINT_ID = process.env.POINT_ID;
const TENANT_ID = process.env.TENANT_ID;
const TENANT_KEY = process.env.TENANT_KEY;
const MQTT_USERNAME = process.env.MQTT_USERNAME;
const MQTT_PASSWORD = process.env.MQTT_PASSWORD;
const MQTT_ADDRESS = "mqtt://mqtt.dimensionfour.io";
const MQTT_PORT = "1883";
const CONNECTION_URL = `${MQTT_ADDRESS}:${MQTT_PORT}`;
const CLIENT_ID = `${Math.random().toString(16).slice(3)}`;

const client = mqtt.connect(CONNECTION_URL, {
CLIENT_ID,
clean: true,
connectTimeout: 4000,
username: MQTT_USERNAME,
password: MQTT_PASSWORD,
reconnectPeriod: 1000,
});

let payload = JSON.stringify({
pointId: POINT_ID,
tenantId: TENANT_ID,
tenantKey: TENANT_KEY,
signals: [
{
value: Math.random().toString().slice(3, 5),
unit: "CELSIUS_DEGREES",
type: "Temperature",
timestamp: new Date().toISOString(),
},
],
});

client.on("connect", () => {
console.log("Connected");
console.log("Sending payload: ", payload);

client.publish("POINT/PUSH", payload, { qos: 0, retain: false }, (error) => {
if (error) {
console.log("ERROR: ", error);
}
});

});

Arduino / C++ (ESP32)

Requirements

Arduino IDE (tested with v1.8.16)
PubSubClient ESP32 (tested with Adafruit Huzzah32)
arduino-esp32
ArduinoJson (tested with v6.18.5)

Code

// secrets.h
#define WIFI_SSID_SECRET "somestring"
#define WIFI_PASSWORD_SECRET "somestring"
#define MQTT_BROKER_ADDRESS_SECRET "somestring"
#define MQTT_BROKER_USERNAME_SECRET "somestring"
#define MQTT_BROKER_PASSWORD "somestring"
#define MQTT_BROKER_PORT_SECRET 1883

#define DEVICE_ID_SECRET "somestring"
#define TENANT_ID_SECRET "somestring"
#define TENANT_KEY_SECRET "somestring"
// main.cpp / main.ino
// Uncomment if not using Arduino IDE
// #include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <time.h>
#include <secrets.h>

const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 0;
const int daylightOffset_sec = 0;

const char *SSID = WIFI_SSID_SECRET;
const char *WIFIPASS = WIFI_PASSWORD_SECRET;

const char *MQTT_BROKER_ADDRESS = MQTT_BROKER_ADDRESS_SECRET;
const char *MQTT_BROKER_USERNAME = MQTT_BROKER_USERNAME_SECRET;
const char *MQTT_BROKER_PASSWORD = MQTT_BROKER_PASSWORD_SECRET;
const int MQTT_BROKER_PORT = MQTT_BROKER_PORT_SECRET;

const char *DEVICE_ID = DEVICE_ID_SECRET;
const char *TENANT_ID = TENANT_ID_SECRET;
const char *TENANT_KEY = TENANT_KEY_SECRET;

struct tm timeinfo;

WiFiClient wifiClient;
PubSubClient psClient(wifiClient);


void sendData() {
Serial.println("Sending data to DimensionFour.io:");

StaticJsonDocument<200> doc;
doc["deviceId"] = DEVICE_ID;
doc["tenantId"] = TENANT_ID;
doc["tenantKey"] = TENANT_KEY;

JsonArray jar = doc.createNestedArray("signals");
JsonObject sig1 = jar.createNestedObject();

float measuredtemp = random(1800,2200) / 100.0;
char temp[32];
dtostrf(measuredtemp, 0, 2, temp);

sig1["value"] = temp;
sig1["unit"] = "CELSIUS_DEGREES";
sig1["type"] = "Temperature";

getLocalTime(&timeinfo);
char time[100];
strftime(time, 100, "%FT%T+00:00", &timeinfo);
sig1["timestamp"] = time;

serializeJsonPretty(doc, Serial);

char payload[200];
serializeJson(doc, payload);
psClient.publish("POINT/PUSH", payload);
}


void reconnectMQTT()
{
while (!psClient.connected())
{
Serial.print("Attempting MQTT connection...");

String clientId = "D4_ESP32_";
clientId += String(random(0xffff), HEX);

if (psClient.connect(clientId.c_str(), MQTT_BROKER_USERNAME, MQTT_BROKER_PASSWORD))
{
Serial.println("connected");
}
else
{
Serial.print("failed, rc=");
Serial.print(psClient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}


void setup() {
Serial.begin(115200);
delay(500);

Serial.print("Connecting to Wifi: ");
WiFi.begin(SSID, WIFIPASS);

while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}

Serial.println("Success!");

configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

if(!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time!");
}

Serial.print("Current time: ");
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
psClient.setServer(MQTT_BROKER_ADDRESS, MQTT_BROKER_PORT);
}

void loop() {
reconnectMQTT();
sendData();
delay(1000);
}