Setting Up Datacake HTTP Connections

This comprehensive guide simplifies deploying a Datacake HTTP client on ALPON X4, enabling seamless cloud data transfer with clear setup and testing steps.

The HTTP API offers a simple and efficient way to send device data to the cloud, enabling seamless integration with the Datacake platform for real-time monitoring and visualization. This guide walks you through deploying a Datacake HTTP client on your ALPON X4 device to publish messages, complete with setup instructions, code, and testing steps.


Prerequisites

Before you begin, ensure you have the following ready:

  • ALPON X4 Device: Your device should be powered on, fully operational, and connected to ALPON Cloud.
  • Datacake Account: Sign up for a Datacake account to access the HTTP API integration features.
  • Datacake Integration Token: Generate this token in your Datacake account under the HTTP API integration settings for secure authentication.

For detailed API options, refer to the Datacake HTTP API documentation.



Setting Up the Containerized Environment

To enable Datacake HTTP communication, you’ll create a containerized environment with a custom Python script. Follow these steps to set it up:

  1. Create a Dockerfile
    On your local machine, create a file named Dockerfile with the following content to set up a lightweight environment with necessary tools:

    FROM alpine:latest
    
    RUN apk update && apk add \
        curl \
        python3 \
        py3-pip \
        bash
    
    RUN pip3 install requests
    
    WORKDIR /app
    
    COPY datacake_http_client.py /app/
    
    CMD ["python3", "/app/datacake_http_client.py"]
    

  2. Create the Datacake HTTP Client Script
    Create a Python file named datacake_http_client.py to handle data transmission to Datacake:

    import requests
    import time
    import json
    import random
    import os
    
    # Datacake HTTP API configuration
    api_endpoint = os.environ.get("DATACAKE_API_ENDPOINT", "your-datacake-http-endpoint")
    device_serial = os.environ.get("DEVICE_SERIAL", "your-device-serial")
    
    # Datacake data format
    def create_datacake_payload(device_serial, temperature, humidity):
        data = {
            "device": device_serial,
            "temperature": temperature,
            "humidity": humidity
        }
        return data
    
    # Function to send HTTP POST request to Datacake
    def send_to_datacake(payload):
        try:
            response = requests.post(api_endpoint, json=payload)
            print(f"Status Code: {response.status_code}")
            print(f"Response: {response.text}")
            return response.status_code == 200
        except Exception as e:
            print(f"Error sending data to Datacake: {e}")
            return False
    
    # Publish messages every 10 seconds
    try:
        print(f"Starting Datacake HTTP client for device: {device_serial}")
        while True:
            # Create sample data
            temperature = round(random.uniform(20, 30), 2)
            humidity = round(random.uniform(40, 60), 2)
            
            # Create Datacake formatted payload
            payload = create_datacake_payload(device_serial, temperature, humidity)
            print(f"Sending data: Temperature: {temperature}°C, Humidity: {humidity}%")
            
            # Send data to Datacake
            success = send_to_datacake(payload)
            if success:
                print("Data sent successfully to Datacake!")
            else:
                print("Failed to send data to Datacake.")
            
            # Wait before next reading
            time.sleep(10)
    
    except KeyboardInterrupt:
        print("Exiting...")
    

  3. Build the Docker Image
    In your terminal, navigate to the directory containing the Dockerfile and datacake_http_client.py, then build the image on your local machine:

    docker build --platform=linux/arm64 -t datacake-http-alpon-x4:latest .
    
  4. Upload the Container to Sixfab Registry

    • Log in to the Sixfab Connect platform, navigate to the Sixfab Registry page
    • Click on + Add Container and follow the prompts to push container to Sixfab registry.

      📘

      Manage and Deploy Applications

      Visit the Manage & Deploy Applications page for all the necessary details on pushing your container image to the Sixfab Registry.

  5. Configuration

    • Go to the Application section of your asset on Sixfab Connect.

    • Click the + Deploy button to configure and deploy the container.

    • In the Deploy Container window, use the following settings:

      • Container Name: datacake-http-client

      • Image: Select the Datacake image and tag pushed to the Sixfab Registry.

      • Environment: Click "+ Add More" in the environment section and add the following values:

        KeyValue
        DATACAKE_API_ENDPOINTyour-datacake-endpoint
        DATACAKE_INTEGRATION_TOKENyour-integration-token
        DEVICE_SERIALyour-device-serial

      • Click the "+ Deploy" button to deploy Datacake.

Configuring the Datacake Decoder

To process incoming data in Datacake, configure a decoder function in your account:

  1. Log in to your Datacake account and navigate to your device.
  2. Go to the Configuration tab and locate the HTTP Payload Decoder section.
  3. Add the following JavaScript decoder function to parse and process the incoming data:
    function Decoder(request) {
        var payload = JSON.parse(request.body)
        var serialNumber = payload.device
        try {
            var datacakeUUID = deviceSerialToId[serialNumber]
            var temperatureInDatabase = measurements[datacakeUUID]["TEMPERATURE"].value
            var temperatureInPayload = payload["temperature"]
            if (temperatureInPayload > temperatureInDatabase) {
                payload["temperature_higher"] = true
            }
        } catch (e) {
            console.log(JSON.stringify(e))
            console.log("Error reading measurement from the device. Does the field exist?")
        }
        try {
            var datacakeUUID = deviceSerialToId[serialNumber]
            var temperatureLimit = configurationValues[datacakeUUID]["TEMPERATURE_LIMIT"]
            if (payload["temperature"] > temperatureLimit) {
                payload["temperature_limit_reached"] = true
            }
        } catch (e) {
            console.log(JSON.stringify(e))
            console.log("Error parsing Configuration Field")
        }
        var timestamp = Math.floor(Date.now() / 1000);
        var result = Object.keys(payload).map(function(key) {
          if (key !== "device") {
            return {
              device: payload.device,
              field: key.toUpperCase(),
              value: payload[key],
              timestamp: timestamp
            };
          }
        });
        return result
    }
    
  4. Save the decoder and note the HTTP Endpoint URL provided by Datacake, as you’ll use it in the environment variables.


Testing the Integration with cURL

To verify your Datacake HTTP API setup, test it manually using cURL from your terminal:

curl -X POST -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-integration-token" \
  -d '{"device":"your-device-serial","temperature":25.4,"humidity":48.3}' \
  your-datacake-endpoint

A successful response will look like this:

{
    "method": "POST",
    "GET": {},
    "POST": {},
    "body": "{\"device\":\"your-device-serial\",\"temperature\":25.4,\"humidity\":48.3}",
    "headers": {
        "Content-Length": "68",
        "Content-Type": "application/json"
    },
    "path": "/integrations/api/your-integration-token"
}


Final Steps

Once deployed, your ALPON X4 will begin sending temperature and humidity data to Datacake every 10 seconds. Log in to your Datacake account to view the data in your dashboards or configure alerts.

With your Datacake HTTP client running on ALPON X4, you’re ready to monitor and analyze your device data effortlessly. Happy data collecting!