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
  • Intro
  • Setting Up HTTP Downlinks
  • Video
  • Creating a New HTTP Downlink
  • Configuring the HTTP Request
  • Saving and Applying the Downlink
  • HTTP Downlink Examples
  • Overview
  • HTTP POST Request Downlink
  • GET Request Downlink Examples
  • Advanced Topics
  • Triggering HTTP Downlinks Based on Measurements
  • Using the "Trigger on Measurements" Feature
  • Integrating HTTP Downlinks into Dashboards
  • Adding a Downlink Widget to the Dashboard
  • Viewing Downlink Status and Debugging
  • Using HTTP Downlinks in the Rule Engine
  • Setting Up Rules for HTTP Downlinks
  • Configuring the Rule Action
  • Saving and Activating the Rule

Was this helpful?

  1. Generic API Devices

HTTP Downlinks

How to send HTTP Post or Get Requests as Downlinks and how to configure those.

Last updated 7 months ago

Was this helpful?

Intro

This documentation explains how to set up HTTP downlinks on the Datacake platform for API devices. The document will walk you through configuring downlinks, triggering downlinks based on measurements, and integrating these downlinks into dashboards and the rule engine. The HTTP downlink feature is designed to work with devices that are connected to Datacake via HTTP and MQTT integrations.

Setting Up HTTP Downlinks

Video

Learn everything about HTTP Downlinks in the following video:

Creating a New HTTP Downlink

  1. Access the Device Settings: Navigate to your API device settings on the Datacake platform.

  2. Add a New Downlink: In the downlink configuration section, click "Add Downlink."

  3. Name and Describe the Downlink: Provide a name and description. For example, "My first HTTP downlink" and a description like "This downlink sends HTTP requests to a specified URL."

  4. Choose the Downlink Type: Select "HTTP Downlink" as the downlink type.

Configuring the HTTP Request

  1. Define the HTTP Method and URL:

    • In the downlink editor, define the HTTP method (e.g., POST, GET) and provide the URL to which the downlink should send requests.

  2. Set Up Optional Parameters:

    • Configure additional settings such as query parameters, headers, and the request body. For example:

      {
        "method": "POST",
        "url": "https://example-webhook.com",
        "headers": {
          "Content-Type": "application/json", 
          "Authentication": "Bearer 9239424392"
        },
        "body": {"name": "John Doe", "platform": "Datacake"}
      }
  3. Testing the HTTP Downlink:

    • Use the "Try Decoder" feature to test the downlink configuration. This simulates sending a request and displays the method, URL, headers, and body structure that will be sent.

Saving and Applying the Downlink

  1. Save the Downlink Configuration: Click "Save" to create the downlink.

  2. Verify Downlink Creation: The platform will notify you once the downlink has been successfully created.

  3. Trigger the Downlink: You can trigger the downlink manually from the device's interface or use conditions such as measurements and time-based scheduling.

HTTP Downlink Examples

This section provides super simple examples of how to create downlinks that make POST and GET requests to a third-party API. These examples show how to utilize the given Encoder function without accessing any measurement data, making it easy to understand and use as a template.

You can copy and paste those code examples into the Downlink Encoder view.

Overview

The Encoder function can be used to create POST and GET requests. Below are basic examples that demonstrate how to:

  1. Call a POST request without utilizing any measurement data.

  2. Call a GET request with custom query parameters.

HTTP POST Request Downlink

Plain POST Request without Measurements

function Encoder(device, measurements) {
    return {
        method: "POST",
        url: 'https://api.example.com/device-data',
        headers: {
            "content-type": "application/json",
        },
        body: {
            device_id: device.id,
            device_name: device.name,
            // Measurements are not included in this example
        }
    };
}

POST Request using Measurements

function Encoder(device, measurements) {
    return {
        method: "POST",
        url: 'https://api.example.com/device-data',
        headers: {
            "content-type": "application/json",
        },
        body: {
            device_id: device.id,
            device_name: device.name,
            measurements: measurements
        }
    };
}

POST Request using selected device data

This example demonstrates how to safely access a database field called TEMPERATURE and how to include it in the POST request. The try...catch block ensures that any errors in accessing the measurement field are handled gracefully.

function Encoder(device, measurements) {
    var temperatureValue = null;

    // Safely access the TEMPERATURE measurement field using try...catch
    try {
        // Attempt to access the TEMPERATURE value from measurements
        temperatureValue = measurements["TEMPERATURE"].value;
    } catch (error) {
        // Log an error message if the field is not found or an error occurs
        console.log("Error accessing TEMPERATURE measurement:", error);
    }

    // Return the POST request with temperature included in the body if available
    return {
        method: "POST",
        url: 'https://api.example.com/device-data',
        headers: {
            "content-type": "application/json",
            "Authorization": "Bearer your_token_here" // If needed ...
        },
        body: {
            device_id: device.id,
            device_name: device.name,
            measurements: {
                temperature: temperatureValue // Include temperature in the body
            }
        }
    };
}

POST Request with Authentication

function Encoder(device, measurements) {
    return {
        method: "POST",
        url: 'https://api.example.com/protected-endpoint',
        headers: {
            "content-type": "application/json",
            "Authorization": "Bearer your_token_here" // Replace with your actual token
        },
        body: {
            message: "This is a POST request with Bearer Token authentication",
            user: "example_user",
            timestamp: new Date().toISOString()
        }
    };
}

Produces the following output:

{
  "method": "POST",
  "url": "https://api.example.com/protected-endpoint",
  "headers": {
    "content-type": "application/json",
    "Authorization": "Bearer your_token_here"
  },
  "body": {
    "message": "This is a POST request with Bearer Token authentication",
    "user": "example_user",
    "timestamp": "2024-09-30T11:00:00.000Z"
  }
}

GET Request Downlink Examples

The following example shows you how to create a downlink to call the following URL as GET-Request using query-parameters:

  • URL: https://api.example.com/device-status?device_id=018097a2-26dd-436e-9460-8492b848b481&device_name=Datacake-Device&status=active&type=sensor

function Encoder(device, measurements) {
    return {
        method: "GET",
        url: 'https://api.example.com/device-status',
        queryParameters: {
            device_id: device.id,
            device_name: device.name,
            status: "active", // Custom query parameter
            type: "sensor"    // Custom query parameter
        }
    };
}

Advanced Topics

For sure, it is possible that using the downlink encoder, which gets executed every time the user sends a downlink, the rule engine triggers a downlink, or writing into a field automatically triggers a downlink.

So this code snippet gets executed. That means you could use the code snippet to check against measurement while in use, but also use other techniques, code functionalities like time checks or counters if the downlink really needs to be sent.

Example

function Encoder(device, measurements) {
    var temperatureValue = null;

    // Safely access the TEMPERATURE measurement field using try...catch
    try {
        // Attempt to access the TEMPERATURE value from measurements
        temperatureValue = measurements["TEMPERATURE"].value;
    } catch (error) {
        // Log an error message if the field is not found or an error occurs
        console.log("Error accessing TEMPERATURE measurement:", error);
        return null; // Return null if error occurs
    }

    // Check if the temperature value is greater than 20°C
    if (temperatureValue > 20) {
        // Return the POST request if the condition is met
        return {
            method: "POST",
            url: 'https://api.example.com/device-data',
            headers: {
                "content-type": "application/json",
            },
            body: {
                device_id: device.id,
                device_name: device.name,
                measurements: {
                    temperature: temperatureValue // Include temperature in the body
                }
            }
        };
    } else {
        // Log a message if temperature is not greater than 20°C
        console.log("Temperature is below or equal to 20°C. No request sent.");
        return null; // Return null if condition is not met
    }
}

If you need any assistance in writing code, please reach out to us. We are happy to help.

Triggering HTTP Downlinks Based on Measurements

Downlinks can be automatically triggered upon receiving a measurement on the device. This functionality enables automatic responses based on real-time data, such as checking if a measurement falls within the desired target range or validating if the device's configuration matches expected values. This is particularly useful for scenarios where an immediate action is required, such as sending a configuration update when certain conditions are met.

If you want to know more about this feature, we have a detailed "how to" available on our documentation for you:

Automated Dynamic Downlinks

Using the "Trigger on Measurements" Feature

  1. Enable Measurement-Based Triggers: In the downlink editor, enable the "Trigger on Measurements" option.

  2. Define the Measurement Field: Specify which measurement field (e.g., temperature, humidity) will trigger the downlink. This field should correspond to a measurement being recorded by the device.

  3. Accessing Measurement Values:

    • Use the measurements object to access recorded values. For example, to access a temperature value, use:

      {
        "temperature": measurements.temperature.value
      }
  4. Testing the Downlink with Measurements: Use the "Try Decoder" feature to validate that the downlink correctly includes the measurement values.

Integrating HTTP Downlinks into Dashboards

Adding a Downlink Widget to the Dashboard

  1. Edit the Dashboard: Navigate to the device's dashboard and click "Edit Dashboard."

  2. Add a New Widget: Select the "Downlink Widget" from the list of available widgets.

  3. Select the Downlink: Choose the HTTP downlink you created and configure the widget’s name, appearance, and color settings as needed.

  4. Save and Test the Widget: Save the changes and test triggering the downlink directly from the dashboard widget.

Viewing Downlink Status and Debugging

  1. Access Debug Information: After triggering the downlink, access the "Debug" tab to view detailed information about the HTTP request.

  2. Review the Response: Check the status code and any returned data to verify successful execution.

Using HTTP Downlinks in the Rule Engine

HTTP downlinks are fully compatible with our new rule engine. This will allow you, for example, to send a downlink based on a measurement. If the same device or any other device in your workspace has met or reached a threshold, you can send a downlink to a different device.

Our new rule engine also allows you to send downlinks via a schedule. For example, you can create a single rule to send a downlink at 9 a.m. to hundreds of devices.

If you are interested to learn more about Downlink Scheduling, here's a great how-to guide for you:

How to Schedule Mass-Downlinks (Multicast) using Datacake Rule Engine

Setting Up Rules for HTTP Downlinks

  1. Open the Rule Engine: Navigate to the Rule Engine section of the Datacake platform.

  2. Create a New Rule: Click "Add Rule" and choose the device you want to configure.

  3. Choose a Trigger Type:

    • Time-Based Triggers: Set the rule to trigger the downlink at specific times (e.g., every day at 9:00 AM).

    • Measurement-Based Triggers: Configure the rule to send a downlink when a measurement (e.g., temperature) reaches a certain value.

Configuring the Rule Action

  1. Select the Downlink: Choose the HTTP downlink created earlier as the action for this rule.

  2. Define Additional Conditions: Add any additional conditions, such as sending the downlink only when the device is online.

Saving and Activating the Rule

  1. Save the Rule: Once all configurations are complete, save the rule.

  2. Activate the Rule: Ensure the rule is activated so that the downlink is triggered automatically based on the defined conditions.