Last updated

Epic-Charging API Use Cases & Examples

Welcome to the Epic-Charging API use cases and examples documentation. Here you'll find common use cases and code samples to help you get started quickly with our API.

Basic Use Cases

1. Monitoring Charger Status

One of the most common use cases is monitoring the status of your chargers. This allows you to see which chargers are available, in use, or experiencing issues.

import requests

api_key = "your_api_key_here"
headers = {"Token-Authorization": api_key}

# Get the status of all chargers
response = requests.get(
    "https://{{tenant}}.epiccharging.com/api/external/v1/report/charger-status/",
    headers=headers
)

# Check the response
if response.status_code == 200:
    chargers = response.json()["results"]
    for charger in chargers:
        print(f"Charger ID: {charger['id']}")
        print(f"Status: {charger['status']}")
        print(f"Location: {charger['location']}")
        print("Ports:")
        for port in charger['ports']:
            print(f"  - Port {port['connector_id']}: {port['status']}")
        print("---")
else:
    print(f"Error: {response.status_code}")
    print(response.text)

2. Starting a Charging Session

To remotely start a charging session on a specific charger port:

import requests

api_key = "your_api_key_here"
headers = {
    "Token-Authorization": api_key,
    "Content-Type": "application/json"
}

port_id = "123e4567-e89b-12d3-a456-426614174000"  # Replace with your port ID

# Start a charging session
response = requests.patch(
    f"https://{{tenant}}.epiccharging.com/api/external/v1/charger-port/{port_id}/start/",
    headers=headers,
    json={}
)

# Check the response
if response.status_code == 200:
    result = response.json()
    print(f"Result: {result['result']}")
else:
    print(f"Error: {response.status_code}")
    print(response.text)

3. Generating Charging Reports

To generate a report of charging sessions within a specific date range:

import requests
from datetime import datetime, timedelta

api_key = "your_api_key_here"
headers = {"Token-Authorization": api_key}

# Define date range (last 7 days)
end_date = datetime.now().isoformat()
start_date = (datetime.now() - timedelta(days=7)).isoformat()

# Get charging session report
params = {
    "plug_in_start_datetime__gte": start_date,
    "plug_in_start_datetime__lte": end_date
}

response = requests.get(
    "https://{{tenant}}.epiccharging.com/api/external/v1/report/charging-session/",
    headers=headers,
    params=params
)

# Check the response
if response.status_code == 200:
    sessions = response.json()["results"]
    total_energy = sum(session.get("energy_delivered_to_electric_vehicle_kwh", 0) for session in sessions)
    
    print(f"Total sessions: {len(sessions)}")
    print(f"Total energy delivered: {total_energy} kWh")
    
    for session in sessions:
        print(f"Session ID: {session['session_id']}")
        print(f"Start: {session['charging_start_datetime']}")
        print(f"End: {session['charging_end_datetime']}")
        print(f"Energy: {session.get('energy_delivered_to_electric_vehicle_kwh', 'N/A')} kWh")
        print("---")
else:
    print(f"Error: {response.status_code}")
    print(response.text)

Advanced Use Cases

1. Reserving a Charger Port

To reserve a charger port for a future charging session:

import requests
from datetime import datetime, timedelta

api_key = "your_api_key_here"
headers = {
    "Token-Authorization": api_key,
    "Content-Type": "application/json"
}

port_id = "123e4567-e89b-12d3-a456-426614174000"  # Replace with your port ID

# Set reservation expiry to 1 hour from now
expiry_time = (datetime.now() + timedelta(hours=1)).isoformat()

# Reserve the port
response = requests.patch(
    f"https://{{tenant}}.epiccharging.com/api/external/v1/charger-port/{port_id}/reserve_now/",
    headers=headers,
    json={
        "expiry_date_time": expiry_time,
        "id_tag": "user_rfid_tag",
        "reservation_id": 12345  # A unique identifier for this reservation
    }
)

# Check the response
if response.status_code == 200:
    result = response.json()
    print(f"Reservation result: {result['result']}")
else:
    print(f"Error: {response.status_code}")
    print(response.text)

2. Monitoring Faults

To monitor system faults and issues with your charging infrastructure:

import requests
from datetime import datetime, timedelta

api_key = "your_api_key_here"
headers = {"Token-Authorization": api_key}

# Get faults from the last 30 days
thirty_days_ago = (datetime.now() - timedelta(days=30)).isoformat()

params = {
    "created_at__gte": thirty_days_ago
}

response = requests.get(
    "https://{{tenant}}.epiccharging.com/api/external/v1/report/faults/",
    headers=headers,
    params=params
)

# Check the response
if response.status_code == 200:
    faults = response.json()["results"]
    print(f"Total faults: {len(faults)}")
    
    # Group faults by charger
    charger_faults = {}
    for fault in faults:
        charger_id = fault["charger_id"]
        if charger_id not in charger_faults:
            charger_faults[charger_id] = []
        charger_faults[charger_id].append(fault)
    
    # Print fault summary by charger
    for charger_id, faults in charger_faults.items():
        print(f"Charger {charger_id}: {len(faults)} faults")
        for fault in faults:
            print(f"  - {fault['created_at']}: {fault['error_code']} - {fault['error_info']}")
else:
    print(f"Error: {response.status_code}")
    print(response.text)

Integration Examples

1. Integrating with a Building Management System

This example shows how to integrate Epic-Charging API with a building management system to manage charging based on building power capacity:

import requests
import time

api_key = "your_api_key_here"
headers = {
    "Token-Authorization": api_key,
    "Content-Type": "application/json"
}

# Function to get building power consumption from your BMS
def get_building_power_consumption():
    # Replace with your actual BMS API call
    return 75.0  # Example: 75 kW

# Function to get available power for EV charging
def get_available_charging_power(building_power, max_power=100.0):
    return max(0, max_power - building_power)

# Function to get all active charging ports
def get_active_charging_ports():
    response = requests.get(
        "https://{{tenant}}.epiccharging.com/api/external/v1/charger-port/",
        headers=headers,
        params={"status__in": "CHARGING"}
    )
    if response.status_code == 200:
        return response.json()["results"]
    return []

# Function to adjust charging power for a port
def set_charging_power(port_id, power):
    response = requests.patch(
        f"https://{{tenant}}.epiccharging.com/api/external/v1/charger-port/{port_id}/",
        headers=headers,
        json={"charging_speed": power}
    )
    return response.status_code == 200

# Main loop
while True:
    # Get building power consumption
    building_power = get_building_power_consumption()
    
    # Calculate available power for EV charging
    available_power = get_available_charging_power(building_power)
    
    # Get active charging ports
    active_ports = get_active_charging_ports()
    
    if active_ports:
        # Distribute available power among active ports
        power_per_port = available_power / len(active_ports)
        
        # Adjust power for each port
        for port in active_ports:
            set_charging_power(port["id"], min(power_per_port, port["max_power"]))
        
        print(f"Adjusted power for {len(active_ports)} ports to {power_per_port:.2f} kW each")
    
    # Wait for 5 minutes before checking again
    time.sleep(300)

2. Mobile App Integration

Example of API interaction from a mobile app allowing users to start/stop charging:

// Example using JavaScript/TypeScript for a mobile app

const API_BASE_URL = 'https://{{tenant}}.epiccharging.com/api/external/v1';
const API_KEY = 'your_api_key_here';

// Get list of chargers
async function getChargers() {
  try {
    const response = await fetch(`${API_BASE_URL}/charger/`, {
      method: 'GET',
      headers: {
        'Token-Authorization': API_KEY
      }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    return data.results;
  } catch (error) {
    console.error('Error fetching chargers:', error);
    return [];
  }
}

// Start charging on a specific port
async function startCharging(portId) {
  try {
    const response = await fetch(`${API_BASE_URL}/charger-port/${portId}/start/`, {
      method: 'PATCH',
      headers: {
        'Token-Authorization': API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({})
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    return data.result;
  } catch (error) {
    console.error('Error starting charging:', error);
    throw error;
  }
}

// Stop charging on a specific port
async function stopCharging(portId) {
  try {
    const response = await fetch(`${API_BASE_URL}/charger-port/${portId}/stop/`, {
      method: 'PATCH',
      headers: {
        'Token-Authorization': API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({})
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    return data.result;
  } catch (error) {
    console.error('Error stopping charging:', error);
    throw error;
  }
}

// Example usage in React Native component
function ChargingScreen() {
  const [chargers, setChargers] = useState([]);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    async function loadChargers() {
      const chargersData = await getChargers();
      setChargers(chargersData);
      setLoading(false);
    }
    
    loadChargers();
  }, []);
  
  async function handleStartCharging(portId) {
    try {
      setLoading(true);
      const result = await startCharging(portId);
      alert(`Charging started: ${result}`);
    } catch (error) {
      alert(`Error starting charging: ${error.message}`);
    } finally {
      setLoading(false);
    }
  }
  
  // Component rendering code...
}