Skip to content

AsobaCloud/sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Ona SDK

Introduction

The Ona SDK enables seamless integration with the Ona Energy AI Platform, allowing users to:

  • Upload large historical datasets for interpolation, model training, and forecasting.
  • Retrieve pre-signed URLs for secure file uploads to AWS S3.
  • Interact programmatically with Asoba’s APIs for energy forecasting, dispatching, and analysis.

This SDK provides support for JavaScript (Node.js & Browser) and Python, making it easy for developers to integrate Ona into third-party applications.

Key Features

βœ” Pre-Signed URL Generation – Secure and efficient file uploads to AWS S3.
βœ” Historical Data Upload – Enable seamless ingestion of large energy datasets.
βœ” Dual SDK Support – Use in both JavaScript and Python applications.
βœ” Error Handling – Detailed API responses and logging for debugging.
βœ” Future Compatibility – Support for forecasting & dispatch APIs (coming soon!)


Installation

Prerequisites

Before installing, ensure you have:

  • Node.js 14+ (for JavaScript SDK)
  • Python 3.7+ (for Python SDK)
  • AWS Credentials configured in .env
  • API Key for secure authentication

JavaScript Installation

npm install asoba-sdk
or manually:

sh
Copy
Edit
mkdir asoba-sdk && cd asoba-sdk
npm init -y
npm install axios dotenv

Python Installation

pip install requests python-dotenv
or manually:

sh
Copy
Edit
mkdir asoba_sdk && cd asoba_sdk
python -m venv venv && source venv/bin/activate
pip install requests python-dotenv

Environment Setup

Create a .env file with:

ASOBA_API_URL=https://yn058ezh38.execute-api.af-south-1.amazonaws.com/test
ASOBA_API_KEY=your-api-key-here

Usage Examples

JavaScript SDK

require("dotenv").config();
const axios = require("axios");
const fs = require("fs");

class AsobaUploader {
    constructor() {
        this.apiUrl = process.env.ASOBA_API_URL;
        this.apiKey = process.env.ASOBA_API_KEY;

        if (!this.apiUrl || !this.apiKey) {
            throw new Error("Missing API URL or API Key. Set ASOBA_API_URL and ASOBA_API_KEY in .env.");
        }
    }

    async getPresignedUrl(customer_id, region, location, manufacturer, filename) {
        const url = `${this.apiUrl}/upload_train`;
        const headers = { "x-api-key": this.apiKey };

        try {
            const response = await axios.get(url, {
                params: { customer_id, region, location, manufacturer, filename },
                headers,
            });
            return response.data;
        } catch (error) {
            console.error("Error fetching pre-signed URL:", error);
            throw error;
        }
    }

    async uploadFile(filePath, presignedUrl) {
        try {
            const fileData = fs.readFileSync(filePath);
            await axios.put(presignedUrl, fileData, { headers: { "Content-Type": "text/csv" } });
            console.log("File uploaded successfully!");
        } catch (error) {
            console.error("Error uploading file:", error);
            throw error;
        }
    }

    async uploadToS3(filePath, customer_id, region, location, manufacturer) {
        const filename = filePath.split("/").pop();
        console.log("Fetching Pre-Signed URL...");
        const { presigned_url } = await this.getPresignedUrl(customer_id, region, location, manufacturer, filename);
        console.log("Uploading to S3...");
        await this.uploadFile(filePath, presigned_url);
        console.log(`Upload completed: ${presigned_url}`);
    }
}

// Example Usage
(async () => {
    const uploader = new AsobaUploader();
    await uploader.uploadToS3("sample.csv", "280001", "af-south-1", "CapeTown", "lux");
})();

Python SDK

import os
import requests
import datetime

class OnaUploader:
    def __init__(self):
        """Initialize SDK with API URL and API Key from environment variables."""
        self.api_upload_url = os.getenv("ONA_API_UPLOAD_URL")
        self.api_train_url = os.getenv("ONA_API_UPLOAD_URL")
        self.api_key = os.getenv("ONA_API_KEY")
       

    def get_presigned_url(self, customer_id, region, location, manufacturer, filename):
        """Step 1: Request a pre-signed URL from the Ona API."""
        params = {
            "customer_id": customer_id,
            "region": region,
            "location": location,
            "manufacturer": manufacturer,
            "filename": filename,
        }

        url = f"{self.api_upload_url}/upload_train"
        headers = {"x-api-key": self.api_key, "Content-Type": "application/json"}
        print(url)
        print(f"Headers being sent: {headers}") #Print the headers being sent
        
        try:
            response = requests.post(url, params=params, headers=headers)
            response.raise_for_status()
            temp = response.json()
            return temp
        except requests.exceptions.RequestException as e:
            print(f"Error fetching pre-signed URL: {e}")
            raise



    def upload_file(self, file_path, presigned_url):
        """Step 2: Upload a file to S3 using the pre-signed URL."""
        try:
            with open(file_path, "rb") as file:
                headers = {"Content-Type": "text/csv"}  # Enforce correct MIME type
                response = requests.put(presigned_url, data=file, headers=headers)
                response.raise_for_status()
                print("File uploaded successfully!")
        except requests.exceptions.RequestException as e:
            print(f"Error uploading file to S3: {e}")
            raise



    def upload_file_to_s3(self, file_path, customer_id, region, location, manufacturer):
        """Combined function: Requests a pre-signed URL and uploads a file."""
        filename = os.path.basename(file_path)
        timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # Get current timestamp
        new_filename = f"{timestamp}_{filename}"  # Create new filename with timestamp

        try:
            print("Requesting pre-signed URL...")
            presigned_data = self.get_presigned_url(customer_id, region, location, manufacturer, new_filename)

            presigned_url = presigned_data.get("presigned_url")            
            if not presigned_url:
                raise ValueError("No presigned URL returned from API.")

            print("Uploading file to S3...")
            self.upload_file(file_path, presigned_url)

            return presigned_url
        except Exception as e:
            print(f"Error in file upload process: {e}")
            raise
            
            
    def train_forecaster(self, customer_id, region, location, manufacturer, serial_number, testing):
        """Step 1: Request a pre-signed URL from the Ona API."""
        params = {
            "customer_id": customer_id,
            "location": location,
            "manufacturer": manufacturer,
            "region": region,
            "serial_number": serial_number,
            "testing": testing
        }

        url = f"{self.api_train_url}/upload_train"
        headers = {"x-api-key": self.api_key, "Content-Type": "application/json"}
        print(url)
        print(f"Headers being sent: {headers}") #Print the headers being sent
        
        try:
            response = requests.post(url, params=params, headers=headers)
            response.raise_for_status()
            temp = response.json()
            return temp
        except requests.exceptions.RequestException as e:
            print(f"Error training model: {e}")
            raise

# Example Usage
if __name__ == "__main__":
    uploader = AsobaUploader();
    uploader.upload_to_s3("sample.csv", "280001", "af-south-1", "CapeTown", "lux")

API Reference

πŸ”Ή getPresignedUrl(customer_id, region, location, manufacturer, filename)
Returns: A pre-signed S3 URL to upload historical energy data.
Usage:

  • JavaScript: uploader.getPresignedUrl("280001", "af-south-1", "CapeTown", "lux", "data.csv")
  • Python: uploader.get_presigned_url("280001", "af-south-1", "CapeTown", "lux", "data.csv")

πŸ”Ή uploadFile(filePath, presignedUrl)
Uploads a file to the S3 bucket using the generated pre-signed URL.
Usage:

  • JavaScript: uploader.uploadFile("sample.csv", presigned_url)
  • Python: uploader.upload_file("sample.csv", presigned_url)

πŸ”Ή uploadToS3(filePath, customer_id, region, location, manufacturer)
Fetches a pre-signed URL and uploads a file to S3 in one step.
Usage:

  • JavaScript: uploader.uploadToS3("sample.csv", "280001", "af-south-1", "CapeTown", "lux")
  • Python: uploader.upload_to_s3("sample.csv", "280001", "af-south-1", "CapeTown", "lux")

πŸ”Ή train_forecaster(self, customer_id, region, location, manufacturer, serial_number, testing)
Fetches a pre-signed URL and uploads a file to S3 in one step.
Usage:

  • JavaScript: uploader.train_forecaster(customer_id = "Reyn-Lux", region = "af-south-1", location = "CapeTown", manufacturer = "lux", serial_number = "2303053195-2443053096", testing = "True")
  • Python: uploader.train_forecaster(customer_id = "Reyn-Lux", region = "af-south-1", location = "CapeTown", manufacturer = "lux", serial_number = "2303053195-2443053096", testing = "True")

Troubleshooting

403 Forbidden? Ensure your API key is valid.
SignatureDoesNotMatch? Verify your .env settings.
Connection Timeout? Check your internet connection and retry.

Future Enhancements

πŸ“Š Model Training & Forecasting API Integration
πŸ”„ Data Synchronization for Real-Time Dispatch
πŸ›  Webhooks for Asynchronous Processing

Support

For support, reach out to [email protected]

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published