Příklady
Příklady kódu
VeřejnéTyp obsahu: Reference
Praktické ukázky volání MyBox API v cURL, Pythonu a JavaScriptu — seznam zařízení, autentizace přes Basic Auth a zpracování odpovědí.
Praktické příklady integrace MyBox API v různých programovacích jazycích.
Získání seznamu zařízení
curl -X GET "https://cloud.mybox.pro/admin-panel/v1/external/device" \
-u "API_KEY:API_SECRET" \
-H "Accept: application/json"import requests
from requests.auth import HTTPBasicAuth
API_KEY = "váš_api_key"
API_SECRET = "váš_api_secret"
BASE_URL = "https://cloud.mybox.pro/admin-panel/v1"
response = requests.get(
f"{BASE_URL}/external/device",
auth=HTTPBasicAuth(API_KEY, API_SECRET),
headers={"Accept": "application/json"}
)
if response.status_code == 200:
devices = response.json()
for device in devices.get('data', []):
print(f"Zařízení: {device['title']} ({device['identifier']})")
else:
print(f"Chyba: {response.status_code}")const API_KEY = 'váš_api_key';
const API_SECRET = 'váš_api_secret';
const BASE_URL = 'https://cloud.mybox.pro/admin-panel/v1';
async function getDevices() {
const auth = btoa(`${API_KEY}:${API_SECRET}`);
const response = await fetch(`${BASE_URL}/external/device`, {
method: 'GET',
headers: {
'Authorization': `Basic ${auth}`,
'Accept': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
console.log('Zařízení:', data.data);
return data.data;
} else {
console.error('Chyba:', response.status);
}
}
getDevices();Automatizovaný billing podle RFID karet
Kompletní příklad, jak automatizovat vyúčtování nabíjené energie na jednotlivé uživatele podle jejich RFID karet. API vrací pro každou nabíjecí relaci pole user_id (číslo RFID karty) a user_tag_title (jméno uživatele přiřazené ke kartě).
import requests
from requests.auth import HTTPBasicAuth
from datetime import datetime, timedelta, timezone
from collections import defaultdict
import csv
API_KEY = "váš_api_key"
API_SECRET = "váš_api_secret"
BASE_URL = "https://cloud.mybox.pro/admin-panel/v1"
AUTH = HTTPBasicAuth(API_KEY, API_SECRET)
def get_all_devices():
"""Získá seznam všech nabíjecích stanic."""
response = requests.get(
f"{BASE_URL}/external/device",
auth=AUTH,
headers={"Accept": "application/json"}
)
response.raise_for_status()
return response.json()['data']
def get_charging_reports(device_id, start_date, end_date):
"""Získá všechny charging reporty pro zařízení s automatickým stránkováním."""
all_reports = []
offset = 0
limit = 100
while True:
response = requests.get(
f"{BASE_URL}/external/charging-reports/device/{device_id}",
auth=AUTH,
params={
'startDate': start_date,
'endDate': end_date,
'limit': limit,
'offset': offset
},
headers={"Accept": "application/json"}
)
response.raise_for_status()
data = response.json()
reports = data['data']
total = data['meta']['totalCount']
all_reports.extend(reports)
if len(all_reports) >= total:
break
offset += limit
return all_reports
def generate_billing(months_back=1):
"""
Vygeneruje billing report za zadané období.
Seskupí spotřebu podle RFID karet napříč všemi stanicemi.
"""
end = datetime.now(timezone.utc)
start = end - timedelta(days=months_back * 30)
start_str = start.strftime('%Y-%m-%dT00:00:00Z')
end_str = end.strftime('%Y-%m-%dT23:59:59Z')
billing = defaultdict(lambda: {
'name': '',
'sessions': 0,
'energy_kwh': 0.0,
'cost': 0.0,
'currency': '',
'devices': set()
})
devices = get_all_devices()
print(f"Nalezeno {len(devices)} zařízení")
for device in devices:
device_id = device['identifier']
reports = get_charging_reports(device_id, start_str, end_str)
for r in reports:
if r['status'] != 'Finished':
continue
rfid = r.get('user_id', 'unknown')
billing[rfid]['name'] = r.get('user_tag_title', 'Neznámý')
billing[rfid]['sessions'] += 1
billing[rfid]['energy_kwh'] += float(r.get('energy_delivered', 0) or 0)
billing[rfid]['cost'] += float(r.get('cost', 0) or 0)
billing[rfid]['currency'] = r.get('currency', 'CZK')
billing[rfid]['devices'].add(device_id)
return billing
def print_billing(billing):
"""Vypíše billing report do konzole."""
print(f"\n{'RFID karta':<20} {'Jméno':<25} {'Relací':>8} "
f"{'Energie (kWh)':>15} {'Náklady':>12} {'Stanic':>8}")
print("-" * 92)
total_energy = 0
total_cost = 0
for rfid, info in sorted(billing.items(), key=lambda x: x[1]['energy_kwh'], reverse=True):
currency = info['currency']
print(f"{rfid:<20} {info['name']:<25} {info['sessions']:>8} "
f"{info['energy_kwh']:>15.2f} {info['cost']:>10.2f} {currency} "
f"{len(info['devices']):>7}")
total_energy += info['energy_kwh']
total_cost += info['cost']
print("-" * 92)
print(f"{'CELKEM':<20} {'':<25} {sum(b['sessions'] for b in billing.values()):>8} "
f"{total_energy:>15.2f} {total_cost:>10.2f} {currency}")
def export_billing_csv(billing, filename='billing_report.csv'):
"""Exportuje billing do CSV souboru."""
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow([
'RFID karta', 'Jméno', 'Počet relací',
'Dodaná energie (kWh)', 'Náklady', 'Měna', 'Počet stanic'
])
for rfid, info in sorted(billing.items(), key=lambda x: x[1]['energy_kwh'], reverse=True):
writer.writerow([
rfid, info['name'], info['sessions'],
f"{info['energy_kwh']:.2f}", f"{info['cost']:.2f}",
info['currency'], len(info['devices'])
])
print(f"\nCSV export: {filename}")
# Spuštění - billing za poslední měsíc
billing = generate_billing(months_back=1)
print_billing(billing)
export_billing_csv(billing)const axios = require('axios');
const fs = require('fs');
const API_KEY = 'váš_api_key';
const API_SECRET = 'váš_api_secret';
const BASE_URL = 'https://cloud.mybox.pro/admin-panel/v1';
const api = axios.create({
baseURL: BASE_URL,
auth: { username: API_KEY, password: API_SECRET },
headers: { 'Accept': 'application/json' }
});
async function getAllDevices() {
const { data } = await api.get('/external/device');
return data.data;
}
async function getChargingReports(deviceId, startDate, endDate) {
const allReports = [];
let offset = 0;
const limit = 100;
while (true) {
const { data } = await api.get(
`/external/charging-reports/device/${deviceId}`,
{ params: { startDate, endDate, limit, offset } }
);
allReports.push(...data.data);
if (allReports.length >= data.meta.totalCount) break;
offset += limit;
}
return allReports;
}
async function generateBilling(monthsBack = 1) {
const endDate = new Date().toISOString();
const startDate = new Date(
Date.now() - monthsBack * 30 * 24 * 60 * 60 * 1000
).toISOString();
const billing = {};
const devices = await getAllDevices();
console.log(`Nalezeno ${devices.length} zařízení`);
for (const device of devices) {
const reports = await getChargingReports(
device.identifier, startDate, endDate
);
for (const r of reports) {
if (r.status !== 'Finished') continue;
const rfid = r.user_id || 'unknown';
if (!billing[rfid]) {
billing[rfid] = {
name: '', sessions: 0, energyKwh: 0,
cost: 0, currency: '', devices: new Set()
};
}
billing[rfid].name = r.user_tag_title || 'Neznámý';
billing[rfid].sessions++;
billing[rfid].energyKwh += parseFloat(r.energy_delivered || 0);
billing[rfid].cost += parseFloat(r.cost || 0);
billing[rfid].currency = r.currency || 'CZK';
billing[rfid].devices.add(device.identifier);
}
}
return billing;
}
function printBilling(billing) {
console.log('\nRFID karta Jméno Relací Energie (kWh) Náklady');
console.log('-'.repeat(85));
const sorted = Object.entries(billing)
.sort(([, a], [, b]) => b.energyKwh - a.energyKwh);
for (const [rfid, info] of sorted) {
console.log(
`${rfid.padEnd(20)} ${info.name.padEnd(25)} ` +
`${String(info.sessions).padStart(6)} ` +
`${info.energyKwh.toFixed(2).padStart(13)} ` +
`${info.cost.toFixed(2).padStart(10)} ${info.currency}`
);
}
}
function exportCsv(billing, filename = 'billing_report.csv') {
const header = 'RFID karta,Jméno,Počet relací,Dodaná energie (kWh),Náklady,Měna\n';
const rows = Object.entries(billing)
.sort(([, a], [, b]) => b.energyKwh - a.energyKwh)
.map(([rfid, info]) =>
`${rfid},${info.name},${info.sessions},` +
`${info.energyKwh.toFixed(2)},${info.cost.toFixed(2)},${info.currency}`
)
.join('\n');
fs.writeFileSync(filename, header + rows, 'utf-8');
console.log(`\nCSV export: ${filename}`);
}
// Spuštění
generateBilling(1).then(billing => {
printBilling(billing);
exportCsv(billing);
});Příklad výstupu:
Nalezeno 5 zařízení
RFID karta Jméno Relací Energie (kWh) Náklady Stanic
--------------------------------------------------------------------------------------------
F41682BF Michal Fojtík 22 170.41 1320.23 CZK 2
0A896C4E Jan Novák 7 60.41 342.38 CZK 1
A3B5C7D9 Petr Svoboda 5 58.63 183.98 CZK 1
E2F4A6B8 Marie Dvořáková 10 55.55 840.67 CZK 3
--------------------------------------------------------------------------------------------
CELKEM 44 345.00 2687.26 CZK
CSV export: billing_report.csvJak to funguje
Každá nabíjecí relace v API obsahuje:
user_id-- číslo RFID karty (např.F41682BF)user_tag_title-- jméno přiřazené ke kartě (např.Jan Novák)energy_delivered-- dodaná energie v kWhcost-- náklady za relaci
Skript projde všechna zařízení, stáhne reporty a seskupí je podle RFID karty.
Live data - aktuální stav nabíjení
def get_live_data(device_id):
"""Získá aktuální data ze zařízení."""
url = f"{BASE_URL}/external/live/device/{device_id}"
response = requests.get(
url,
auth=HTTPBasicAuth(API_KEY, API_SECRET),
headers={"Accept": "application/json"}
)
if response.status_code == 200:
data = response.json()['data']
print(f"Stav: {data.get('state', 'neznámý')}")
if 'telemetries' in data:
for telemetry in data['telemetries']:
if telemetry['id'] == 'charging_state':
print(f"Nabíjení: {telemetry['value']}")
elif telemetry['id'] == 'power':
print(f"Výkon: {telemetry['value']} W")
elif telemetry['id'] == 'session_energy':
print(f"Nabito: {telemetry['value']} kWh")
return data
else:
print(f"Chyba: {response.status_code}")
return None
live_data = get_live_data("abc1-def2-ghi3-jkl4")const axios = require('axios');
class MyBoxAPI {
constructor(apiKey, apiSecret) {
this.apiKey = apiKey;
this.apiSecret = apiSecret;
this.baseURL = 'https://cloud.mybox.pro/admin-panel/v1';
}
async getLiveData(deviceId) {
const response = await axios.get(
`${this.baseURL}/external/live/device/${deviceId}`,
{
auth: { username: this.apiKey, password: this.apiSecret },
headers: { 'Accept': 'application/json' }
}
);
const data = response.data.data;
const telemetry = {};
if (data.telemetries) {
data.telemetries.forEach(t => {
telemetry[t.id] = { value: t.value, unit: t.unit };
});
}
return { state: data.state, telemetry, raw: data };
}
}
const api = new MyBoxAPI('API_KEY', 'API_SECRET');
api.getLiveData('abc1-def2-ghi3-jkl4').then(data => {
console.log('Stav:', data.state);
if (data.telemetry.power) {
console.log('Výkon:', data.telemetry.power.value, 'W');
}
});Snapshot - kompletní stav všech senzorů
async function getDeviceSnapshot(deviceId) {
const url = `${BASE_URL}/external/history/snapshot/${deviceId}`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Basic ${btoa(`${API_KEY}:${API_SECRET}`)}`,
'Accept': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
const snapshot = data.data;
console.log('=== SNAPSHOT ===');
console.log(`Čas: ${snapshot.timestamp}`);
console.log(`Stav: ${snapshot.state}`);
if (snapshot.nodes) {
snapshot.nodes.forEach(node => {
console.log(`\nModul: ${node.name} (${node.id})`);
node.sensors?.forEach(s => console.log(` ${s.name}: ${s.value} ${s.unit}`));
node.telemetries?.forEach(t => console.log(` ${t.name}: ${t.value} ${t.unit}`));
});
}
return snapshot;
}
}Pomocné funkce
Retry logic s exponential backoff
async function apiCallWithRetry(fn, maxRetries = 3) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (error.response?.status === 429) {
const delay = Math.pow(2, i) * 1000;
console.log(`Rate limit, čekám ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
throw lastError;
}Další příklady
Pokročilé funkce nabíjení
- Dynamic Load Management (DLM) - Inteligentní řízení zátěže pro více nabíjecích stanic
- Nabíjení podle spotových cen - Optimalizace nákladů podle cen elektřiny
- Monitoring spotřeby energie - Detailní analýza a monitoring
Tipy pro vývoj
- Vždy používejte HTTPS
- Implementujte error handling s retry logikou
- Cachujte statická data (informace o zařízení)
- Respektujte rate limits (100 req/min)
- Používejte
meta.totalCountpro stránkování