Files
zenai-apc-ngoro/docs/API_GUIDE.md
T
2026-10-21 10:01:25 +07:00

12 KiB

ZenAI APC Ngoro — API Guide (for new developers)

This guide explains how to call the dashboard HTTP API on NanoPi 1. You do not need to know Flask or the counter internals to get started.


1. Quick start

Item Value
Local base URL http://127.0.0.1:5000
Public base URL https://ngoro.apc.zenai.id
Auth None (LAN / tunnel trust — do not expose write endpoints blindly)
Default JSON Content-Type: application/json
Service apc-ngoro-dashboard (gunicorn on port 5000)

Replace BASE in examples with either URL above.

export BASE=http://127.0.0.1:5000
# or: export BASE=https://ngoro.apc.zenai.id

2. First 5 minutes

# Is the API up?
curl -s "$BASE/api/health" | python3 -m json.tool

# Today / yesterday / all-time numbers
curl -s "$BASE/api/summary" | python3 -m json.tool

# Live batch (IDLE when nothing is counting)
curl -s "$BASE/api/current-batch" | python3 -m json.tool

Expected health response (shape may vary slightly):

{
  "success": true,
  "service": "apc-ngoro-dashboard",
  "site_name": "NGORO",
  "db": "ok",
  "state_file": "missing",
  "time": "2026-09-29T14:46:37"
}
  • db: "ok" → SQLite is readable.
  • state_file: "missing" → no active live batch file (normal when idle).
  • state_file: "ok" → counter has written current_batch.json.

3. Endpoint catalog

3.1 Dashboard reads

GET /api/health

Readiness probe for monitoring / load balancers.

Status Meaning
200 DB OK
500 DB unreachable (db: "error", optional db_error)

GET /api/current-batch

Live counter state from the edge state file.

{
  "success": false,
  "error": "No active batch",
  "count": 0,
  "batch_number": null,
  "counting_date": null,
  "status": "IDLE"
}

When a batch is running you also get start_time, last_detection_time, and status: "RUNNING".

Note: “no active batch” still returns HTTP 200 with success: false. Check success / status, not only the status code.

GET /api/previous-batch

Last finished batch in the DB.

{
  "success": true,
  "date": "2026-09-29",
  "batch_number": 22,
  "count": 1667,
  "start_time": "2026-09-29T03:27:30.136003",
  "end_time": "2026-09-29T03:44:34.630252",
  "duration_minutes": 17.1
}

GET /api/summary

Dashboard KPI tiles.

{
  "site_name": "NGORO",
  "cutoff_time": "19:00",
  "today": {
    "date": "2026-09-29",
    "total_count": 34227,
    "total_batches": 22,
    "trend_pct": 1.6,
    "vs_avg_pct": 9.7
  },
  "yesterday": {
    "date": "2026-09-28",
    "total_count": 33683,
    "total_batches": 21,
    "is_last_active": true
  },
  "average_per_day": 31208.3,
  "best_day": { "date": "2026-09-29", "count": 34227 },
  "all_time": {
    "grand_total": 499333,
    "grand_batches": 345,
    "total_days": 16,
    "avg_per_batch": 1447.3
  }
}

GET /api/daily-data

Daily summary rows for charts / tables.

Query Description Default
days Look back N calendar days from today 30
date From-date YYYY-MM-DD (inclusive). If set, overrides days —
curl -s "$BASE/api/daily-data?days=7"
curl -s "$BASE/api/daily-data?date=2026-09-28"
[
  {
    "date": "2026-09-28",
    "total_count": 33683,
    "total_batches": 21,
    "avg_per_batch": 1604.0
  }
]

GET /api/day-detail/<date>

One counting day + every batch that day.

curl -s "$BASE/api/day-detail/2026-09-29" | python3 -m json.tool

Each batch object includes:

Field Notes
batch_number, count, start_time, end_time, duration_minutes Always present
camera_name, object_label Camera / label used for counting
recount_count, recount_delta null if never recounted
video_url Source video URL when available

GET /api/recent-batches

Newest finished batches.

Query Description Default
limit Max rows 10
curl -s "$BASE/api/recent-batches?limit=1"
[
  {
    "date": "2026-09-29",
    "batch_number": 22,
    "count": 1667,
    "start_time": "2026-09-29T03:27:30.136003",
    "end_time": "2026-09-29T03:44:34.630252",
    "duration_minutes": 17.1,
    "camera_name": "CC1",
    "object_label": "ayam-potong",
    "recount_count": null,
    "recount_delta": null,
    "video_url": "http://192.168.192.251:8090/files/2026-09-29-22"
  }
]

GET /api/available-dates

Dates that have daily summaries (newest first).

[
  { "date": "2026-09-29", "total_batches": 22, "total_count": 34227 },
  { "date": "2026-09-28", "total_batches": 21, "total_count": 33683 }
]

3.2 Recount API (/api/v1/recount/...)

Recount re-runs counting on a recorded batch video (proxied to NanoPi 2).

Batch IDs look like: YYYY-MM-DD-N e.g. 2026-09-29-22.

GET /api/v1/recount/batches

Batches grouped by date (UI “Riwayat”).

{
  "days": 3,
  "groups": [
    {
      "date": "2026-09-29",
      "batches": [
        {
          "batch_id": "2026-09-29-22",
          "batch_number": 22,
          "original_count": 1667,
          "start_time": "...",
          "end_time": "...",
          "recount_count": null,
          "delta": null,
          "video_url": "/api/v1/recount/source/2026-09-29-22",
          "recount_video_url": null
        }
      ]
    }
  ]
}

GET /api/v1/recount/status

Current recount job (in-memory on this dashboard).

{
  "success": true,
  "stub": false,
  "status": "PROCESSING",
  "progress": 32,
  "current_count": 566,
  "recount_count": null,
  "delta": null,
  "batch_id": "2026-09-29-1",
  "original_count": 1783,
  "video_url": null,
  "error": null
}

status values: IDLE | PROCESSING | COMPLETED (+ possible error string).

POST /api/v1/recount/start

curl -s -X POST "$BASE/api/v1/recount/start" \
  -H "Content-Type: application/json" \
  -d '{"batch_id":"2026-09-29-22"}'
HTTP Meaning
200 Started
400 Invalid batch_id
404 Batch not in DB
409 Another recount already PROCESSING

Invalid body example:

{ "success": false, "error": "batch_id tidak valid (format: YYYY-MM-DD-N)" }

POST /api/v1/recount/stop

curl -s -X POST "$BASE/api/v1/recount/stop"

Asks the job to cancel / stop. Returns JSON with current status.

Media helpers

Endpoint Type Notes
GET /api/v1/recount/live-frame image/jpeg Single annotated frame from NanoPi 2
GET /api/v1/recount/live-video MJPEG stream Prefer this in UI (<img src="...">)
GET /api/v1/recount/source/<batch_id> video Source MP4 for a batch
GET /api/v1/recount/video/<filename> video Recount output file on NanoPi 2
POST/GET /api/v1/recount/warm-source/<batch_id> JSON Warm preview cache

If NanoPi 2 is down, these may return 502 / 503.


3.3 Live streams

GET /api/stream — Server-Sent Events (SSE)

Long-lived connection. Prefer this over polling /api/current-batch.

Events:

Event name Payload
current-batch Same shape as /api/current-batch
recount-status Same fields as /api/v1/recount/status (without wrapping extras)

Heartbeat: comment line : ping about every 15 seconds (keeps proxies happy).

# Watch the stream (Ctrl+C to stop)
curl -N "$BASE/api/stream"

Browser example:

const es = new EventSource('/api/stream');

es.addEventListener('current-batch', (e) => {
  const data = JSON.parse(e.data);
  console.log('batch', data.status, data.count);
});

es.addEventListener('recount-status', (e) => {
  const data = JSON.parse(e.data);
  console.log('recount', data.status, data.progress);
});

es.onerror = () => {
  // Browser auto-reconnects while CONNECTING.
  // Only fall back to polling if readyState === EventSource.CLOSED.
  if (es.readyState === EventSource.CLOSED) {
    es.close();
    // e.g. setInterval(() => fetch('/api/current-batch'), 2000);
  }
};

GET /api/live-video — operational MJPEG

<img src="/api/live-video" alt="Live feed" />

Content-Type: multipart/x-mixed-replace; boundary=frame


3.4 Exports (Excel)

Despite historical -csv names, these endpoints return XLSX.

Preferred (alias) Legacy (still works)
GET /api/export-daily-xlsx?days=30 GET /api/export-daily-csv?days=30
GET /api/export-day-xlsx/<date> GET /api/export-day-csv/<date>
curl -OJ "$BASE/api/export-daily-xlsx?days=7"
curl -OJ "$BASE/api/export-day-xlsx/2026-09-28"

Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet


3.5 Admin

POST /api/reset

Deletes live state files and signals the counter to reset.

curl -s -X POST "$BASE/api/reset"

Warning: Destructive and unauthenticated. Only use on trusted networks / during maintenance.


4. Errors

Standard JSON error shape

{ "success": false, "error": "Not found", "path": "/api/nonexistent" }
HTTP When
400 Bad request (e.g. invalid batch_id)
404 Unknown path or batch not found
405 Wrong HTTP method (e.g. POST /api/summary)
409 Conflict (recount already running)
500 Server / DB failure
502 / 503 Upstream (NanoPi 2 / MotionEye) or DB unavailable

Gotcha: HTTP 200 + success: false

Several read endpoints (notably /api/current-batch when idle) return 200 with success: false. Always read the JSON body.

405 example:

{
  "success": false,
  "error": "Method not allowed",
  "path": "/api/summary",
  "method": "POST"
}

5. Gotchas (read this)

  1. Export “csv” ≠ CSV — files are .xlsx. Prefer /api/export-*-xlsx.
  2. /api/daily-data?date= is a from-date filter, not “only this day”. Use /api/day-detail/<date> for a single day.
  3. Recount depends on NanoPi 2 — status may stay stuck / live-frame may fail if NANOPI2_URL is unreachable.
  4. No auth — treat write endpoints (start, stop, reset) as internal.
  5. Counting date ≠ calendar midnight — site uses a cutoff (cutoff_time in summary, often evening). A “day” can span late evening into the next morning.
  6. SSE vs polling — do not poll /api/current-batch every 200ms; use /api/stream.

6. Data model (short glossary)

Table batches

One finished counting run.

Column Meaning
counting_date Business day (YYYY-MM-DD)
batch_number Sequence within that day
camera_name / object_label Source camera / class
count Final live count
start_time / end_time ISO timestamps
video_url / video_filename Recorded video
recount_count / recount_delta Optional recount result

Batch id used by recount UI: {counting_date}-{batch_number} → 2026-09-29-22.

Table daily_summaries

Per-day rollup: total_count, total_batches for chart / KPI.

Live state file

Path from env STATE_FILE / CURRENT_BATCH_PATH (default /tmp/apc_ngoro_current_batch.json). Written by the live counter process; read by /api/current-batch and SSE.


7. Suggested client flow

1. GET /api/health          → abort if not 200
2. GET /api/summary         → paint KPI tiles
3. EventSource /api/stream  → live count + recount progress
4. GET /api/available-dates + /api/day-detail/<date>  → history
5. (optional) POST /api/v1/recount/start with batch_id

Questions about routes live in counter_dashboard.py (@app.route).