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.

Paho MQTT

Python

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.
1
from tinkerforge.ip_connection import IPConnection
2
from tinkerforge.bricklet_particulate_matter import BrickletParticulateMatter
3
import time
4
import paho.mqtt.client as mqtt
5
6
client = mqtt.Client()
7
8
HOST = "localhost"
9
PORT = 4223
10
UID = "FX5"
11
12
def on_connect(client, userdata, flags, rc):
13
print("Connected with result code "+str(rc))
14
15
def on_message(client, userdata, msg):
16
print(msg.topic+" "+str(msg.payload))
17
18
def cb_pm_concentration(pm10, pm25, pm100):
19
client.publish("dtck-pub/balena-fin-cellular-demo/0e5d7891-7b73-4377-a7f9-f837a12df327/PM25", pm25)
20
client.publish("dtck-pub/balena-fin-cellular-demo/0e5d7891-7b73-4377-a7f9-f837a12df327/PM10", pm100)
21
22
if __name__ == "__main__":
23
24
ipcon = IPConnection()
25
pm = BrickletParticulateMatter(UID, ipcon)
26
27
ipcon.connect(HOST, PORT)
28
29
pm.register_callback(pm.CALLBACK_PM_CONCENTRATION, cb_pm_concentration)
30
pm.set_pm_concentration_callback_configuration(60000, False)
31
32
client.on_connect = on_connect
33
client.on_message = on_message
34
35
client.tls_set()
36
client.username_pw_set("yourdatacaketokenhere", password="yourdatacaketokenhere")
37
client.connect("mqtt.datacake.co", 8883, 60)
38
client.loop_forever()
Copied!

Javascript

1
// Create a client instance
2
client = new Paho.MQTT.Client("mqtt.datacake.co", 9001, "clientId");
3
4
// set callback handlers
5
client.onConnectionLost = onConnectionLost;
6
client.onMessageArrived = onMessageArrived;
7
8
// connect the client
9
client.connect({
10
onSuccess: onConnect,
11
useSSL: true,
12
userName: "API TOKEN",
13
password: "API TOKEN"
14
});
15
16
17
// called when the client connects
18
function onConnect() {
19
// Once a connection has been made, make a subscription and send a message.
20
console.log("onConnect");
21
client.subscribe("dtck/mqtt-test/06a446aa-6fba-4813-a6ce-b2e3c16f9ebb/+");
22
23
message = new Paho.MQTT.Message("23.5");
24
message.destinationName = "dtck-pub/mqtt-test/06a446aa-6fba-4813-a6ce-b2e3c16f9ebb/TEMPERATURE";
25
client.send(message);
26
}
27
28
// called when the client loses its connection
29
function onConnectionLost(responseObject) {
30
if (responseObject.errorCode !== 0) {
31
console.log("onConnectionLost:" + responseObject.errorMessage);
32
}
33
}
34
35
// called when a message arrives
36
function onMessageArrived(message) {
37
console.log("onMessageArrived:" + message.payloadString);
38
}
Copied!
Last modified 1yr ago
Export as PDF
Copy link