HTTP Downlinks

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

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.

Video

Learn everything about HTTP Downlinks in the following video:

  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.

  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.

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"
  }
}

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.

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.

  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.

  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.

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

  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.

Last updated