# HTTP Downlinks

## 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:

{% embed url="<https://www.youtube.com/watch?v=A52bFvBXWJY>" %}

### Creating a New HTTP Downlink

<figure><img src="/files/451T63C4XxnABbP1txvp" alt=""><figcaption></figcaption></figure>

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:

     ```json
     {
       "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

```javascript
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

```javascript
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.

```javascript
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

```javascript
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:

```json
{
  "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`

```javascript
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

```javascript
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.

{% hint style="info" %}
If you want to know more about this feature, we have a detailed "how to" available on our documentation for you:

[Automated Dynamic Downlinks](/lorawan/downlinks/automated-dynamic-downlinks.md)
{% endhint %}

### 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:

     ```json
     {
       "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.

{% hint style="info" %}
If you are interested to learn more about Downlink Scheduling, here's a great how-to guide for you:

[Schedule Mass-Downlinks (Multicast)](/portal/rule-engine/new-rule-engine/actions/schedule-mass-downlinks-multicast.md)
{% endhint %}

### 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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.datacake.de/generic-api-devices/http-downlinks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
