Example Code

Example code to connect popular MQTT libraries to the Datacake MQTT broker

In this section, you will find some examples of how to use some of the many available MQTT libraries and software functions to connect your Device to Datacake using MQTT.



The following code snippet shows you a very basic implementation on how to send Data from your devices to Datacake using Python, Paho MQTT Library.

For this example, we have been using Tinkerforge Hardware to generate real data.

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_particulate_matter import BrickletParticulateMatter
import time
import paho.mqtt.client as mqtt
client = mqtt.Client()
HOST = "localhost"
PORT = 4223
UID = "FX5"
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
def cb_pm_concentration(pm10, pm25, pm100):
client.publish("dtck-pub/balena-fin-cellular-demo/0e5d7891-7b73-4377-a7f9-f837a12df327/PM25", pm25)
client.publish("dtck-pub/balena-fin-cellular-demo/0e5d7891-7b73-4377-a7f9-f837a12df327/PM10", pm100)
if __name__ == "__main__":
ipcon = IPConnection()
pm = BrickletParticulateMatter(UID, ipcon)
ipcon.connect(HOST, PORT)
pm.register_callback(pm.CALLBACK_PM_CONCENTRATION, cb_pm_concentration)
pm.set_pm_concentration_callback_configuration(60000, False)
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set("yourdatacaketokenhere", password="yourdatacaketokenhere")
client.connect("mqtt.datacake.co", 8883, 60)


// Create a client instance
client = new Paho.MQTT.Client("mqtt.datacake.co", 9001, "clientId");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
onSuccess: onConnect,
useSSL: true,
userName: "API TOKEN",
password: "API TOKEN"
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
message = new Paho.MQTT.Message("23.5");
message.destinationName = "dtck-pub/mqtt-test/06a446aa-6fba-4813-a6ce-b2e3c16f9ebb/TEMPERATURE";
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:" + message.payloadString);