Skip to main content
v5.33
operator
manufacturer
Last updated on

Starters

This section provides ready-to-use code examples for interacting with the Charge Controller REST API. These examples show common tasks such as authentication and retrieving settings.

1. Authentication flow

All examples follow the same authentication flow:

  1. Request a token from the /login endpoint
  2. Hash the password with the received token
  3. Send the username and hashed password to authenticate
  4. Use the returned session ID for later API requests

2. Node.js example

2.1. Prerequisites

  • Node.js (v14 or higher)
  • npm (comes with Node.js)

2.2. Installation

  1. Create a new directory for your project
  2. Create a package.json file:
{
"name": "charge-controller-api-client",
"version": "1.0.0",
"description": "A starter script for interacting with the Charge Controller REST API",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"axios": "^1.6.2"
},
"engines": {
"node": ">=14.0.0"
},
"private": true
}
  1. Install dependencies:
npm install
  1. Create an index.js file with the following code:
/**
* Charge Controller REST API Client
*
* This is a starter script for interacting with the Charge Controller REST API.
* It shows how to authenticate and make requests to the API endpoints.
*
* Usage:
* 1. Install Node.js if not already installed
* 2. Run 'npm install axios' to install the required dependency
* 3. Update the configuration variables below with your Charge Controller details
* 4. Run the script with 'node index.js'
*
* The script will:
* - Authenticate with the Charge Controller
* - Fetch data from the settings, system state, and logging messages endpoints
* - Display the complete JSON responses
*/

const axios = require("axios");
const crypto = require("crypto");

// Configuration - Update these values with your Charge Controller details
const BASE_URL = "http://192.168.123.123"; // Replace with your Charge Controller IP or hostname
const USERNAME = "operator"; // Replace with your username
const PASSWORD = "your_password"; // Replace with your password
const API_VERSION = "v1"; // API version

/**
* Get authentication token from the server
* @returns {Promise<string>} Authentication token
*/
async function getToken() {
const url = `${BASE_URL}/${API_VERSION}/login`;
console.log(`Requesting token from: ${url}`);

try {
const response = await axios.get(url, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});

console.log(`Token request successful`);

if (!response.data || !response.data.token) {
throw new Error('Token not found in response');
}

return response.data.token;
} catch (error) {
console.error(`Token request failed: ${error.message}`);
throw error;
}
}

/**
* Hash password using SHA256
* @param {string} password - Plain text password
* @param {string} token - Authentication token
* @returns {string} Hashed password
*/
function hashPassword(password, token) {
return crypto.createHash('sha256').update(password + token).digest('hex');
}

/**
* Login to get session ID
* @param {string} username - Username
* @param {string} hashedPassword - Hashed password
* @returns {Promise<string>} Session ID
*/
async function login(username, hashedPassword) {
const url = `${BASE_URL}/${API_VERSION}/login`;
console.log(`Logging in as: ${username}`);

try {
const response = await axios.post(url, {
username,
password: hashedPassword
}, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});

console.log(`Login successful`);
console.log(`Response:`, JSON.stringify(response.data, null, 2));

if (response.data.session && response.data.session.id) {
return response.data.session.id;
} else {
throw new Error("Session ID not found in response!");
}
} catch (error) {
console.error(`Login failed: ${error.message}`);
throw error;
}
}

/**
* Request API endpoints
* @param {string} sessionId - Session ID for authentication
* @param {string} endpoint - API endpoint path
* @returns {Promise<object>} API response data
*/
async function fetchEndpoint(sessionId, endpoint) {
const url = `${BASE_URL}/${API_VERSION}${endpoint}`;
console.log(`Requesting API endpoint: ${url}`);

try {
const response = await axios.get(url, {
headers: {
'Authorization': sessionId,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});

console.log(`API request successful: ${endpoint}`);
return response.data;
} catch (error) {
console.error(`API request failed: ${endpoint}`);
console.error(`Error: ${error.message}`);
throw error;
}
}

/**
* Main function to run the API requests
*
* You can extend this function to request additional endpoints or implement
* other API operations as needed for your application.
*/
async function main() {
console.log('Starting Charge Controller REST API Client');
console.log(`Base URL: ${BASE_URL}`);
console.log(`API Version: ${API_VERSION}`);

try {
// Step 1: Get authentication token
const token = await getToken();
console.log('Token received successfully');

// Step 2: Hash password with token
const hashedPassword = hashPassword(PASSWORD, token);
console.log('Password hashed successfully');

// Step 3: Login with credentials
const sessionId = await login(USERNAME, hashedPassword);
console.log('Session established successfully');

// Step 4: Request API endpoints
console.log('\nFetching API Data');

// Settings Parameters endpoint
console.log('\nRequesting Settings Parameters:');
const settings = await fetchEndpoint(sessionId, '/settings');
console.log('Settings Parameters data:');
console.log(JSON.stringify(settings, null, 2));

// System State endpoint
console.log('\nRequesting System State:');
const systemState = await fetchEndpoint(sessionId, '/system_state');
console.log('System State data:');
console.log(JSON.stringify(systemState, null, 2));

// Logging Messages endpoint
console.log('\nRequesting Logging Messages:');
const messages = await fetchEndpoint(sessionId, '/messages');
console.log('Logging Messages data:');
console.log(JSON.stringify(messages, null, 2));

console.log('\nAPI requests completed successfully');

} catch (error) {
console.error('\nError occurred during API requests:');
console.error(error.message);
}
}

main();
  1. Run the script:
node index.js

3. Python example

This Python example shows how to authenticate and retrieve data from the settings, system state, and logging messages endpoints.

3.1. Prerequisites

  • Python 3.6 or higher
  • pip (Python package manager)

3.2. Installation

  1. Create a new directory for your project
  2. Create a requirements.txt file:
requests==2.31.0
  1. Install dependencies:
pip install -r requirements.txt
  1. Create a charge_controller_api.py file with the following code:
#!/usr/bin/env python3
"""
Charge Controller REST API Client

This is a starter script for interacting with the Charge Controller REST API.
It shows how to authenticate and make requests to the API endpoints.

Usage:
1. Install Python 3.6 or higher if not already installed
2. Run 'pip install requests' to install the required dependency
3. Update the configuration variables below with your Charge Controller details
4. Run the script with 'python charge_controller_api.py'

The script will:
- Authenticate with the Charge Controller
- Fetch data from the settings, system state, and logging messages endpoints
- Display the complete JSON responses
"""

import hashlib
import json
import requests

# Configuration - Update these values with your Charge Controller details
BASE_URL = "http://192.168.123.123" # Replace with your Charge Controller IP or hostname
USERNAME = "operator" # Replace with your username
PASSWORD = "your_password" # Replace with your password
API_VERSION = "v1" # API version

def get_token():
"""Get authentication token from the server"""
url = f"{BASE_URL}/{API_VERSION}/login"
print(f"Requesting token from: {url}")

try:
response = requests.get(
url,
headers={
"Accept": "application/json",
"Content-Type": "application/json"
}
)
response.raise_for_status()

print("Token request successful")
data = response.json()

if not data or "token" not in data:
raise ValueError("Token not found in response")

return data["token"]
except Exception as e:
print(f"Token request failed: {str(e)}")
raise

def hash_password(password, token):
"""Hash password using SHA256"""
combined = password + token
return hashlib.sha256(combined.encode()).hexdigest()

def login(username, hashed_password):
"""Login to get session ID"""
url = f"{BASE_URL}/{API_VERSION}/login"
print(f"Logging in as: {username}")

try:
response = requests.post(
url,
json={
"username": username,
"password": hashed_password
},
headers={
"Accept": "application/json",
"Content-Type": "application/json"
}
)
response.raise_for_status()

print("Login successful")
data = response.json()
print(f"Response: {json.dumps(data, indent=2)}")

if "session" in data and "id" in data["session"]:
return data["session"]["id"]
else:
raise ValueError("Session ID not found in response!")
except Exception as e:
print(f"Login failed: {str(e)}")
raise

def fetch_endpoint(session_id, endpoint):
"""Request API endpoints"""
url = f"{BASE_URL}/{API_VERSION}{endpoint}"
print(f"Requesting API endpoint: {url}")

try:
response = requests.get(
url,
headers={
"Authorization": session_id,
"Accept": "application/json",
"Content-Type": "application/json"
}
)
response.raise_for_status()

print(f"API request successful: {endpoint}")
return response.json()
except Exception as e:
print(f"API request failed: {endpoint}")
print(f"Error: {str(e)}")
raise

def main():
"""Main function to run the API requests"""
print("Starting Charge Controller REST API Client")
print(f"Base URL: {BASE_URL}")
print(f"API Version: {API_VERSION}")

try:
# Step 1: Get authentication token
token = get_token()
print("Token received successfully")

# Step 2: Hash password with token
hashed_password = hash_password(PASSWORD, token)
print("Password hashed successfully")

# Step 3: Login with credentials
session_id = login(USERNAME, hashed_password)
print("Session established successfully")

# Step 4: Request API endpoints
print("Fetching API Data")

# App Settings endpoint
print("\nRequesting App Settings:")
app_settings = fetch_endpoint(session_id, "/app_settings")
print("App Settings data:")
print(json.dumps(app_settings, indent=2))

# App Dashboard endpoint
print("\nRequesting App Dashboard:")
app_dashboard = fetch_endpoint(session_id, "/app_dashboard")
print("App Dashboard data:")
print(json.dumps(app_dashboard, indent=2))

# Settings Parameters endpoint
print("\nRequesting Settings Parameters:")
settings = fetch_endpoint(session_id, "/settings")
print("Settings Parameters data:")
print(json.dumps(settings, indent=2))

# System State endpoint
print("\nRequesting System State:")
system_state = fetch_endpoint(session_id, "/system_state")
print("System State data:")
print(json.dumps(system_state, indent=2))

# Logging Messages endpoint
print("\nRequesting Logging Messages:")
messages = fetch_endpoint(session_id, "/messages")
print("Logging Messages data:")
print(json.dumps(messages, indent=2))

print("API requests completed successfully")

except Exception as e:
print("Error occurred during API requests:")
print(str(e))

if __name__ == "__main__":
main()
  1. Run the script:
python charge_controller_api.py

4. Next steps

These examples provide a starting point for interacting with the Charge Controller REST API. You can extend them to:

  1. Access additional endpoints
  2. Implement error handling and retries
  3. Create a more robust application with logging and configuration
  4. Integrate with your own systems

For a complete reference of all available endpoints and their parameters, see the REST API Reference.