Datacake Docs
  • Welcome
  • Get Started
  • Changelog
  • Best practices
    • Best practices: Getting started
    • Best practices: Resolution (Timeframe)
    • Best practices: Dashboards
    • Best practices: Reports
    • Best practices: Grouping Devices
  • Datacake LNS
    • Getting Started
    • Gateways
      • Milesight LoRaWAN Gateway - UG6x
      • RAKwireless WisGate Edge Light 2
    • Devices
    • Add Devices without Gateway
  • Device
    • Product
    • Configuration
    • Claiming
    • Historical Data
    • Database
      • Configuration Fields
      • Fields
        • Manual input
        • Field Roles
        • Formulas
        • Mapping Fields
      • Data retention & Datapoints
      • Examples
        • Mapping 4-20mA Signals
        • Converting Units
  • Dashboards
    • Global Dashboards
      • Setting Homepage
    • Device Dashboards
    • Multi-Device Dashboards
    • Widgets
      • Value Widget
      • Chart Widget
      • Image Map
      • Map Widget
      • Text Widget
      • SOS Widget
      • Boolean Widget
      • iFrame Widget
      • Downlink Widget
      • Set Value Widget
      • Measurement List Widget
      • Heatmap Widget
      • Table Widget
      • Image Widget
  • Portal
    • Multi-Tenancy (Workspaces)
    • Reports
      • Energy Report
    • Administrators
    • Members
      • API Users
    • Security & Privacy
    • Billing
      • Support Packages
      • VAT Exemption / Tax ID
      • SMS Credits
      • Access Invoices
      • Unused time and Remaining time in Invoices (Prorations)
      • Codes
    • White Label
    • Rules
      • Legacy Rule Engine
        • Sending notifications via Telegram
      • New Rule Engine
        • Rule Engine Table Overview
        • Copy/Paste and Template Functionality
        • Advanced Rule Engine E-Mail and Webhook Templates
        • Time Restrictions
    • Zones
  • Cake Red
    • Get Started
    • Overview
  • LoRaWAN
    • Get Started
      • CSV Import
      • Custom LoRaWAN Device
    • Configuring LNS
      • The Things Stack (TTN / TTI) Automated Setup
      • The Things Stack (TTN / TTI) Manual Setup
      • Loriot
      • Kerlink Wanesy
      • Helium
      • ChirpStack
      • Tektelic
      • Actility ThingPark
      • Senet
      • Milesight Gateway
      • KPN
    • Downlinks (LoRaWAN)
      • Set Time Frame
    • Securing Webhooks
    • Payload Decoders
      • Location and GPS
      • Access Gateway Metadata
      • Access Measurements
      • Global Variables
    • Using Cayenne LPP
    • Converting Payload
  • Generic API Devices
    • HTTP Downlinks
  • Integrations
    • MQTT
    • Particle
      • Get Started
      • Adding Integrations
      • Decoding Payloads
      • Calling Functions
      • Templates
        • Particle Tracker One
    • Incoming Webhooks
    • Outgoing Webhooks
      • Securing Outgoing Webhooks in Datacake
    • Golioth
    • Blues Wireless Notecard
    • Sigfox
    • Swarm Asset Tracker
    • Grandcentrix Modbus Cloud Connect
    • YuDash LYNX IoT Gateway
    • Dragino NB-IoT
      • Changing NB-IoT Bands
    • Hardwario CHESTER
    • 1NCE OS
  • API
    • Exporting Data
    • Record Measurements via API
    • Node RED to Datacake
    • Generate Access Token
    • Internal MQTT
      • Get Started
      • MQTT Documentation
      • MQTT over WebSocket
      • Example Code
    • GraphQL API
      • Using GraphQL
      • Device Creation
      • Tutorials
        • Read Group via Tags
  • Guides
    • Python
    • Send Slack Notifications
    • Forward Data to Cake Red
    • Multiple Data Feeds
    • Automated Dynamic Downlinks
    • Ingesting JSON Data into Datacake API Devices
    • Working with Default HTTP Decoder on API Devices and Code Examples
    • Accessing Measurements in Decoders
    • Connecting Datacake to Notion Using Zapier
    • How to set up and use location on non-GPS devices
    • How to integrate with AWS IoT Core
    • How to Schedule Mass-Downlinks (Multicast) using Datacake Rule Engine
    • How to Map Sensor Values to Ranges or Booleans, Strings using Mapping Fields
    • Understanding Internal vs. External MQTT Brokers on Datacake
    • Sending UDP Messages between 1NCE OS and Datacake
    • Concepts of LoRaWAN Payload Decoders on Datacake
    • How to check if a value stays above or below limits for given time
Powered by GitBook
On this page
  • Paho MQTT
  • Python
  • Javascript

Was this helpful?

  1. API
  2. Internal MQTT

Example Code

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

Last updated 4 years ago

Was this helpful?

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 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.tls_set()
    client.username_pw_set("yourdatacaketokenhere", password="yourdatacaketokenhere")
    client.connect("mqtt.datacake.co", 8883, 60)
    client.loop_forever()

Javascript

// 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
client.connect({
 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.
  console.log("onConnect");
  client.subscribe("dtck/mqtt-test/06a446aa-6fba-4813-a6ce-b2e3c16f9ebb/+");
  
  message = new Paho.MQTT.Message("23.5");
  message.destinationName = "dtck-pub/mqtt-test/06a446aa-6fba-4813-a6ce-b2e3c16f9ebb/TEMPERATURE";
  client.send(message);
}
 
// 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);
}
Tinkerforge Hardware