first commit
This commit is contained in:
commit
6bc6887969
25 files changed
+14236
No files matched your search
+220
@@ -0,0 +1,220 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[codz]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py.cover
|
||||
*.lcov
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
# Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
# poetry.lock
|
||||
# poetry.toml
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
||||
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
||||
# pdm.lock
|
||||
# pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# pixi
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
||||
# pixi.lock
|
||||
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
||||
# in the .venv directory. It is recommended not to include this directory in version control.
|
||||
.pixi/*
|
||||
!.pixi/config.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule*
|
||||
celerybeat.pid
|
||||
|
||||
# Redis
|
||||
*.rdb
|
||||
*.aof
|
||||
*.pid
|
||||
|
||||
# RabbitMQ
|
||||
mnesia/
|
||||
rabbitmq/
|
||||
rabbitmq-data/
|
||||
|
||||
# ActiveMQ
|
||||
activemq-data/
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.envrc
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
# .idea/
|
||||
|
||||
# Abstra
|
||||
# Abstra is an AI-powered process automation framework.
|
||||
# Ignore directories containing user credentials, local state, and settings.
|
||||
# Learn more at https://abstra.io/docs
|
||||
.abstra/
|
||||
|
||||
# Visual Studio Code
|
||||
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
||||
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
||||
# you could uncomment the following to ignore the entire vscode folder
|
||||
# .vscode/
|
||||
# Temporary file for partial code execution
|
||||
tempCodeRunnerFile.py
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# Marimo
|
||||
marimo/_static/
|
||||
marimo/_lsp/
|
||||
__marimo__/
|
||||
|
||||
# Streamlit
|
||||
.streamlit/secrets.toml
|
||||
@@ -0,0 +1,286 @@
|
||||
# counter_dashboard.py — API Documentation
|
||||
|
||||
## Page
|
||||
|
||||
### `GET /`
|
||||
Renders the main dashboard HTML page (`dashboard.html`).
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### `GET /api/live-video`
|
||||
MJPEG streaming endpoint. Serves live frames from the path configured in `LIVE_STREAM_FRAME_PATH` (default `/dev/shm/feedmill/live_frame.jpg`) as `multipart/x-mixed-replace`.
|
||||
|
||||
**Response:** JPEG stream with `--frame` boundary delimiters.
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/current-batch`
|
||||
Returns the currently active batch's data or idle state with next batch number.
|
||||
|
||||
**Success response (running):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"active": true,
|
||||
"status": "running",
|
||||
"batch_mode": "manual",
|
||||
"counting_date": "2024-01-01",
|
||||
"batch_number": 12,
|
||||
"count": 342,
|
||||
"start_time": "2024-01-01T14:30:00",
|
||||
"last_detection_time": "2024-01-01T14:35:00"
|
||||
}
|
||||
```
|
||||
|
||||
**Stopped response (no active batch, 200):**
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"active": false,
|
||||
"status": "stopped",
|
||||
"batch_mode": "manual",
|
||||
"error": "No active batch",
|
||||
"count": 0,
|
||||
"batch_number": null,
|
||||
"next_batch_number": 13,
|
||||
"counting_date": "2024-01-01"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/batch/start`
|
||||
Manually starts a new batch on the counter engine.
|
||||
|
||||
**Success response (200):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Started Batch #13",
|
||||
"batch_number": 13,
|
||||
"status": "running"
|
||||
}
|
||||
```
|
||||
|
||||
**Error response (503 if engine offline):**
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"error": "Engine counter tidak aktif. Pastikan service feedmill-counter berjalan."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `POST /api/batch/stop`
|
||||
Manually stops the currently active batch, saves records to SQLite (`batches` and `daily_summaries`), and returns state to idle.
|
||||
|
||||
**Success response (200):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Batch #13 stopped (342 sacks)",
|
||||
"batch_number": 13,
|
||||
"count": 342,
|
||||
"persisted": true,
|
||||
"status": "stopped"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/batch/status`
|
||||
Returns real-time status of the counter engine and batch state.
|
||||
|
||||
**Success response (200):**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"active": true,
|
||||
"status": "running",
|
||||
"batch_mode": "manual",
|
||||
"batch_number": 13,
|
||||
"count": 342,
|
||||
"counting_date": "2024-01-01",
|
||||
"engine_alive": true
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/previous-batch`
|
||||
Returns the most recently completed batch from the `batches` database table, with computed `duration_minutes`.
|
||||
|
||||
**Success response:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"date": "2024-01-01",
|
||||
"batch_number": 11,
|
||||
"count": 287,
|
||||
"start_time": "2024-01-01T14:00:00",
|
||||
"end_time": "2024-01-01T14:27:00",
|
||||
"duration_minutes": 27.0
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/summary`
|
||||
Returns today, yesterday, and all-time aggregate statistics plus average per day and best day.
|
||||
|
||||
**Success response:**
|
||||
```json
|
||||
{
|
||||
"today": {
|
||||
"date": "2024-01-01",
|
||||
"total_count": 1500,
|
||||
"total_batches": 8
|
||||
},
|
||||
"yesterday": {
|
||||
"date": "2023-12-31",
|
||||
"total_count": 1342,
|
||||
"total_batches": 7
|
||||
},
|
||||
"all_time": {
|
||||
"grand_total": 50000,
|
||||
"grand_batches": 260,
|
||||
"total_days": 45
|
||||
},
|
||||
"average_per_day": 1111.1,
|
||||
"best_day": {
|
||||
"date": "2023-12-15",
|
||||
"count": 2100
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/daily-data`
|
||||
Returns daily summary rows for charting.
|
||||
|
||||
**Query params:**
|
||||
| Param | Type | Default | Description |
|
||||
|--------|------|---------|---------------------------------|
|
||||
| `days` | int | 30 | Number of days to look back |
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
[
|
||||
{
|
||||
"date": "2024-01-01",
|
||||
"total_count": 1500,
|
||||
"total_batches": 8,
|
||||
"avg_per_batch": 187.5
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/day-detail/<date>`
|
||||
Returns all batch records for a specific `counting_date` along with summary totals.
|
||||
|
||||
**Path params:**
|
||||
| Param | Type | Description |
|
||||
|--------|--------|------------------------|
|
||||
| `date` | string | Date in `YYYY-MM-DD` |
|
||||
|
||||
**Success response:**
|
||||
```json
|
||||
{
|
||||
"date": "2024-01-01",
|
||||
"total_count": 1500,
|
||||
"total_batches": 8,
|
||||
"total_duration_minutes": 216.0,
|
||||
"avg_duration_minutes": 27.0,
|
||||
"batches": [
|
||||
{
|
||||
"batch_number": 1,
|
||||
"count": 187,
|
||||
"start_time": "2024-01-01T08:00:00",
|
||||
"end_time": "2024-01-01T08:27:00",
|
||||
"duration_minutes": 27.0
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/recent-batches`
|
||||
Returns the most recent batches with computed durations.
|
||||
|
||||
**Query params:**
|
||||
| Param | Type | Default | Description |
|
||||
|---------|------|---------|---------------------------------|
|
||||
| `limit` | int | 10 | Max number of batches to return |
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
[
|
||||
{
|
||||
"date": "2024-01-01",
|
||||
"batch_number": 8,
|
||||
"count": 213,
|
||||
"start_time": "2024-01-01T16:30:00",
|
||||
"end_time": "2024-01-01T16:58:00",
|
||||
"duration_minutes": 28.0
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/available-dates`
|
||||
Returns all dates with data from the `daily_summaries` table, ordered by date descending.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
[
|
||||
{
|
||||
"date": "2024-01-01",
|
||||
"total_count": 1500,
|
||||
"total_batches": 8
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Export Endpoints (XLSX)
|
||||
|
||||
### `GET /api/export-daily-csv`
|
||||
Exports batch detail records for the last N days as an `.xlsx` file.
|
||||
|
||||
**Query params:**
|
||||
| Param | Type | Default | Description |
|
||||
|--------|------|---------|-----------------------------|
|
||||
| `days` | int | 30 | Number of days to look back |
|
||||
|
||||
**Response:** XLSX file download with columns: Date, Batch #, Count, Start Time, End Time, Duration (min).
|
||||
|
||||
Filename format: `{SITE_NAME}_daily_records_{timestamp}.xlsx`
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/export-day-csv/<date>`
|
||||
Exports all batch records for a single date as an `.xlsx` file.
|
||||
|
||||
**Path params:**
|
||||
| Param | Type | Description |
|
||||
|--------|--------|----------------------|
|
||||
| `date` | string | Date in `YYYY-MM-DD` |
|
||||
|
||||
**Response:** XLSX file download with columns: Batch Number, Count, Start Time, End Time, Duration (min).
|
||||
|
||||
Filename format: `{SITE_NAME}_day_detail_{date}.xlsx`
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
All endpoints return `{"success": false, "error": "<message>"}` with HTTP 500 on unexpected errors. Database-unavailable errors (`sqlite3.OperationalError`) return HTTP 200 with an empty/default data structure. The `/api/live-video` endpoint returns HTTP 503 if the frame file is not found.
|
||||
@@ -0,0 +1,78 @@
|
||||
# Edge RKNN Deploy
|
||||
|
||||
Production counter: **direct LAN RTSP** + **YOLO RKNN** + **ByteTrack** + SQLite batch store.
|
||||
|
||||
## Quick install
|
||||
|
||||
```bash
|
||||
# 1. Copy this folder to the RK3588 device
|
||||
sudo mkdir -p /opt/feedmill
|
||||
sudo cp -r feedmill/* /opt/feedmill/
|
||||
sudo chown -R $(whoami):$(whoami) /opt/feedmill
|
||||
|
||||
# 2. Configure
|
||||
cd /opt/feedmill
|
||||
cp config.env.example .env
|
||||
nano .env # SOURCE, MODEL_PATH, CAMERA_NAME, etc.
|
||||
sed -i 's/\r$//' .env
|
||||
|
||||
# 3. Venv + services
|
||||
chmod +x setup-venv.sh install-services.sh
|
||||
sudo ./setup-venv.sh
|
||||
sudo ./install-services.sh
|
||||
```
|
||||
|
||||
Dashboard: `http://<ip-device>:7000`
|
||||
|
||||
---
|
||||
|
||||
## Model checklist
|
||||
|
||||
Set `.env` to the exported `.rknn` model path and make sure class order matches:
|
||||
|
||||
1. `COUNTED_CLASS_ID=0` for `sack`
|
||||
2. `NUM_CLASSES=1` (sack-only model)
|
||||
3. `COUNT_AXIS=y`
|
||||
4. `CROSS_DIRECTION=down`
|
||||
|
||||
---
|
||||
|
||||
## Direct camera RTSP
|
||||
|
||||
Set in `.env`:
|
||||
|
||||
```env
|
||||
SOURCE=rtsp://user:pass@192.168.x.x:554/stream1
|
||||
```
|
||||
|
||||
Test before install:
|
||||
|
||||
```bash
|
||||
ffplay -rtsp_transport tcp -t 5 "$SOURCE"
|
||||
nc -zv <camera-ip> 554
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Validation checklist
|
||||
|
||||
```bash
|
||||
sudo systemctl is-active feedmill-counter feedmill-dashboard
|
||||
PYTHONNOUSERSITE=1 /opt/feedmill/venv/bin/python -c "from rknnlite.api import RKNNLite; print('rknn ok')"
|
||||
sudo journalctl -u feedmill-counter -n 20 --no-pager
|
||||
```
|
||||
|
||||
Good signs:
|
||||
|
||||
- `Stream ready!`
|
||||
- `RKNN model loaded: ...`
|
||||
- `Frame 100 | Batch ...`
|
||||
|
||||
---
|
||||
|
||||
## Logs & restart
|
||||
|
||||
```bash
|
||||
sudo journalctl -u feedmill-counter -f
|
||||
sudo systemctl restart feedmill-counter # after .env change
|
||||
```
|
||||
@@ -0,0 +1,59 @@
|
||||
# RKNN Sack Counter (Production)
|
||||
|
||||
RTSP + YOLO RKNN + ByteTrack line-crossing counter for sacks on Rockchip edge hardware.
|
||||
|
||||
## Architecture
|
||||
|
||||
- **Input:** Direct LAN camera RTSP (low latency)
|
||||
- **Inference:** YOLO `.rknn` on RK3588 NPU
|
||||
- **Logic:** Line crossing (`sack` count) via `batch_store.py`
|
||||
- **Output:** `feedmill.db` + `current_batch.json`
|
||||
- **Dashboard:** Flask on port **7000**
|
||||
|
||||
Batch lifecycle:
|
||||
- **Manual Mode (`BATCH_MODE=manual`, default):** Operator triggers **Start Batch** and **Stop Batch** manually via dashboard buttons or API. Sacks passing while stopped are ignored.
|
||||
- **Auto Mode (`BATCH_MODE=auto`):** Auto-creates batch on first sack crossing, closes batch after idle timeout (`BATCH_TIMEOUT_SECONDS=600`).
|
||||
|
||||
## Deploy
|
||||
|
||||
See **[DEPLOY.md](DEPLOY.md)**.
|
||||
|
||||
| Item | Default |
|
||||
|------|---------|
|
||||
| Install path | `/opt/feedmill` |
|
||||
| Venv | `/opt/feedmill/venv` |
|
||||
| DB | `/opt/feedmill/feedmill.db` |
|
||||
| Dashboard | `http://<device-ip>:7000` |
|
||||
| Cutoff | `20:00` |
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `sudo systemctl status feedmill-counter` | Counter running? |
|
||||
| `sudo journalctl -u feedmill-counter -f` | Live logs |
|
||||
| `sudo systemctl restart feedmill-counter` | After `.env` change |
|
||||
| `sudo ./uninstall-services.sh` | Remove services |
|
||||
|
||||
## Key env vars
|
||||
|
||||
| Variable | Purpose |
|
||||
|----------|---------|
|
||||
| `SOURCE` | Direct camera RTSP URL |
|
||||
| `MODEL_PATH` | `.rknn` file path |
|
||||
| `COUNT_AXIS` | `y` for downward sack flow |
|
||||
| `CROSS_DIRECTION` | `down` (default), `up`, `ltr`, `rtl`, or `both` |
|
||||
| `LINE_Y` / `LINE_Y_FRAC` | Counting line position for downward flow |
|
||||
|
||||
## Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `counter_live_rknn.py` | RTSP + RKNN YOLO + ByteTrack line crossing |
|
||||
| `batch_store.py` | SQLite persistence |
|
||||
| `counter_dashboard.py` | Flask UI |
|
||||
| `config.env.example` | Env template |
|
||||
| `feedmill-counter.service` | Counter systemd unit |
|
||||
| `install-services.sh` | Install + disable legacy MQTT counter |
|
||||
|
||||
The active production path is `counter_live_rknn.py`.
|
||||
+7973
File diff suppressed because it is too large.
Load diff
+432
@@ -0,0 +1,432 @@
|
||||
"""
|
||||
Production batch persistence for the edge counter.
|
||||
Persists counted objects grouped into batches (closed by idle timeout or cutoff).
|
||||
"""
|
||||
import json
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class BatchStore:
|
||||
def __init__(
|
||||
self,
|
||||
db_path,
|
||||
state_file,
|
||||
camera_name,
|
||||
object_label='sack',
|
||||
cutoff_time='20:00',
|
||||
batch_timeout=600.0,
|
||||
min_object_per_batch=60,
|
||||
min_duration_per_batch=60,
|
||||
carry_ids=50,
|
||||
batch_mode='manual',
|
||||
logger=print,
|
||||
):
|
||||
self.db_path = db_path
|
||||
self.state_file = Path(state_file)
|
||||
self.camera_name = camera_name
|
||||
self.object_label = object_label
|
||||
self.cutoff_time_str = cutoff_time
|
||||
datetime.strptime(cutoff_time, '%H:%M')
|
||||
|
||||
self.batch_timeout = float(batch_timeout)
|
||||
self.min_object_per_batch = int(min_object_per_batch)
|
||||
self.min_duration_per_batch = int(min_duration_per_batch)
|
||||
self.carry_ids = int(carry_ids)
|
||||
self.batch_mode = str(batch_mode).strip().lower() if batch_mode else 'manual'
|
||||
self.log = logger
|
||||
|
||||
self.state_lock = threading.Lock()
|
||||
self.batch_timer = None
|
||||
self.previous_state = None
|
||||
self.shutdown_event = threading.Event()
|
||||
|
||||
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
self.state_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self.db = sqlite3.connect(db_path, check_same_thread=False)
|
||||
self._init_db()
|
||||
self.current_state = self._load_state()
|
||||
self.previous_state = self.current_state
|
||||
|
||||
def _init_db(self):
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS batches (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
counting_date TEXT NOT NULL,
|
||||
batch_number INTEGER NOT NULL,
|
||||
camera_name TEXT NOT NULL,
|
||||
object_label TEXT NOT NULL,
|
||||
count INTEGER NOT NULL,
|
||||
start_time TEXT NOT NULL,
|
||||
end_time TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(counting_date, batch_number, camera_name, object_label)
|
||||
)
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS daily_summaries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
counting_date TEXT NOT NULL,
|
||||
camera_name TEXT NOT NULL,
|
||||
object_label TEXT NOT NULL,
|
||||
total_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_batches INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(counting_date, camera_name, object_label)
|
||||
)
|
||||
"""
|
||||
)
|
||||
self.db.commit()
|
||||
|
||||
def get_counting_date(self, dt=None):
|
||||
if dt is None:
|
||||
dt = datetime.now()
|
||||
cutoff = datetime.strptime(self.cutoff_time_str, '%H:%M').time()
|
||||
if dt.time() < cutoff:
|
||||
return dt.date().isoformat()
|
||||
return (dt.date() + timedelta(days=1)).isoformat()
|
||||
|
||||
def _normalize_batch_label(self, label=None):
|
||||
raw = str(label or '').strip().lower()
|
||||
if raw in ('box', '1'):
|
||||
return 'box'
|
||||
if raw in ('sack', '0'):
|
||||
return 'sack'
|
||||
default_raw = str(self.object_label or 'sack').split(',')[0].strip().lower()
|
||||
return 'box' if default_raw == 'box' else 'sack'
|
||||
|
||||
def _load_state(self):
|
||||
if not self.state_file.exists():
|
||||
return None
|
||||
try:
|
||||
with open(self.state_file, 'r', encoding='utf-8') as f:
|
||||
state = json.load(f)
|
||||
state['object_label'] = self._normalize_batch_label(state.get('object_label'))
|
||||
current_date = self.get_counting_date()
|
||||
if state.get('counting_date') != current_date:
|
||||
self.log(
|
||||
f"State file belongs to previous counting day ({state.get('counting_date')}). "
|
||||
'Finalizing before fresh start.'
|
||||
)
|
||||
self._insert_batch(
|
||||
state['counting_date'],
|
||||
state['batch_number'],
|
||||
state['count'],
|
||||
state['start_time'],
|
||||
datetime.now().isoformat(),
|
||||
object_label=state.get('object_label'),
|
||||
)
|
||||
self.state_file.unlink(missing_ok=True)
|
||||
return None
|
||||
self.log(
|
||||
f"Resumed batch #{state['batch_number']} ({state['object_label']}) from {state['start_time']} "
|
||||
f"with count={state['count']}"
|
||||
)
|
||||
if self.batch_mode != 'manual':
|
||||
self._reset_batch_timer()
|
||||
return state
|
||||
except Exception as exc:
|
||||
self.log(f'Failed to load state file: {exc}')
|
||||
return None
|
||||
|
||||
def save_state(self):
|
||||
if self.current_state is None:
|
||||
self.state_file.unlink(missing_ok=True)
|
||||
return
|
||||
with open(self.state_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(self.current_state, f, indent=2, ensure_ascii=False)
|
||||
|
||||
def get_next_batch_number(self, counting_date):
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(MAX(batch_number), 0)
|
||||
FROM batches
|
||||
WHERE counting_date = ? AND camera_name = ?
|
||||
""",
|
||||
(counting_date, self.camera_name),
|
||||
)
|
||||
return cur.fetchone()[0] + 1
|
||||
|
||||
def start_new_batch(self, counting_date=None, object_label=None):
|
||||
with self.state_lock:
|
||||
if self.current_state is not None:
|
||||
self.log(f'Batch #{self.current_state["batch_number"]} is already active')
|
||||
return self.current_state['batch_number']
|
||||
if counting_date is None:
|
||||
counting_date = self.get_counting_date()
|
||||
batch_label = self._normalize_batch_label(object_label)
|
||||
batch_number = self.get_next_batch_number(counting_date)
|
||||
now = datetime.now().isoformat()
|
||||
counted_ids = []
|
||||
if (
|
||||
self.previous_state is not None
|
||||
and self.previous_state.get('object_label') == batch_label
|
||||
):
|
||||
try:
|
||||
counted_ids = self.previous_state['counted_event_ids'][-self.carry_ids:]
|
||||
except (KeyError, TypeError):
|
||||
counted_ids = []
|
||||
self.current_state = {
|
||||
'counting_date': counting_date,
|
||||
'batch_number': batch_number,
|
||||
'object_label': batch_label,
|
||||
'count': 0,
|
||||
'start_time': now,
|
||||
'last_detection_time': now,
|
||||
'counted_event_ids': counted_ids,
|
||||
}
|
||||
self.save_state()
|
||||
if self.batch_mode != 'manual':
|
||||
self._reset_batch_timer()
|
||||
self.log(f'Started batch #{batch_number} for {counting_date} ({batch_label}) [mode={self.batch_mode}]')
|
||||
return batch_number
|
||||
|
||||
def _reset_batch_timer(self):
|
||||
if self.batch_timer:
|
||||
self.batch_timer.cancel()
|
||||
self.batch_timer = threading.Timer(self.batch_timeout, self._on_batch_timeout)
|
||||
self.batch_timer.daemon = True
|
||||
self.batch_timer.start()
|
||||
|
||||
def _on_batch_timeout(self):
|
||||
self.log(
|
||||
f'No {self.object_label} line crossing for {self.batch_timeout:.0f}s – '
|
||||
'closing batch (next crossing starts a new batch)'
|
||||
)
|
||||
self.end_batch(closed_by='timeout')
|
||||
|
||||
def record_counted_object_crossing(self, track_id, object_label=None):
|
||||
"""Record one newly counted object crossing."""
|
||||
with self.state_lock:
|
||||
counting_date = self.get_counting_date()
|
||||
started_new = False
|
||||
if self.current_state is None:
|
||||
if self.batch_mode == 'manual':
|
||||
# In manual mode, do not auto-start batch; wait for manual trigger
|
||||
return 0, False
|
||||
self.start_new_batch(counting_date, object_label=object_label)
|
||||
started_new = True
|
||||
elif self.current_state['counting_date'] != counting_date:
|
||||
prev_label = self.current_state.get('object_label')
|
||||
self._end_batch_locked(closed_by='cutoff')
|
||||
if self.batch_mode == 'manual':
|
||||
return 0, False
|
||||
self.start_new_batch(counting_date, object_label=object_label or prev_label)
|
||||
started_new = True
|
||||
|
||||
active_label = self.current_state.get('object_label', 'sack')
|
||||
if object_label is not None and self._normalize_batch_label(object_label) != active_label:
|
||||
return self.current_state['count'], False
|
||||
|
||||
event_key = str(track_id)
|
||||
if event_key not in self.current_state['counted_event_ids']:
|
||||
self.current_state['count'] += 1
|
||||
self.current_state['counted_event_ids'].append(event_key)
|
||||
self.log(
|
||||
f'Counted {active_label} (track {track_id}) | '
|
||||
f'batch #{self.current_state["batch_number"]} '
|
||||
f'total: {self.current_state["count"]}'
|
||||
)
|
||||
|
||||
self.current_state['last_detection_time'] = datetime.now().isoformat()
|
||||
self.save_state()
|
||||
if self.batch_mode != 'manual':
|
||||
self._reset_batch_timer()
|
||||
return self.current_state['count'], started_new
|
||||
|
||||
def record_ayam_crossing(self, track_id):
|
||||
return self.record_counted_object_crossing(track_id)
|
||||
|
||||
def end_batch(self, closed_by='manual'):
|
||||
with self.state_lock:
|
||||
return self._end_batch_locked(closed_by=closed_by)
|
||||
|
||||
def _end_batch_locked(self, closed_by='manual'):
|
||||
if self.current_state is None:
|
||||
return False
|
||||
|
||||
self.previous_state = self.current_state
|
||||
state = self.current_state
|
||||
batch_label = self._normalize_batch_label(state.get('object_label'))
|
||||
|
||||
start_time_obj = datetime.fromisoformat(state['start_time'])
|
||||
end_time_obj = datetime.now()
|
||||
duration_seconds = (end_time_obj - start_time_obj).total_seconds()
|
||||
|
||||
is_manual = (closed_by == 'manual' or self.batch_mode == 'manual')
|
||||
should_discard = False
|
||||
if is_manual:
|
||||
# If closed manually, discard only if 0 objects counted
|
||||
if state['count'] <= 0:
|
||||
should_discard = True
|
||||
else:
|
||||
if (state['count'] < self.min_object_per_batch
|
||||
or duration_seconds < self.min_duration_per_batch):
|
||||
should_discard = True
|
||||
|
||||
if should_discard:
|
||||
self.current_state = None
|
||||
self.save_state()
|
||||
if self.batch_timer:
|
||||
self.batch_timer.cancel()
|
||||
self.batch_timer = None
|
||||
self.log(
|
||||
f'Batch #{state["batch_number"]} ({batch_label}) discarded '
|
||||
f'(count={state["count"]}, duration={duration_seconds:.0f}s, closed_by={closed_by})'
|
||||
)
|
||||
return False
|
||||
|
||||
end_time = end_time_obj.isoformat()
|
||||
try:
|
||||
self._insert_batch(
|
||||
state['counting_date'],
|
||||
state['batch_number'],
|
||||
state['count'],
|
||||
state['start_time'],
|
||||
end_time,
|
||||
object_label=batch_label,
|
||||
)
|
||||
cps = state['count'] / duration_seconds if duration_seconds > 0 else 0
|
||||
self.log(
|
||||
f'Batch #{state["batch_number"]} ({batch_label}) ended | count={state["count"]} | '
|
||||
f'duration={duration_seconds:.0f}s | cps={cps:.3f} | closed_by={closed_by}'
|
||||
)
|
||||
except Exception as exc:
|
||||
self.log(f'Failed to persist batch: {exc}')
|
||||
return False
|
||||
|
||||
self.current_state = None
|
||||
self.save_state()
|
||||
if self.batch_timer:
|
||||
self.batch_timer.cancel()
|
||||
self.batch_timer = None
|
||||
return True
|
||||
|
||||
def _insert_batch(self, counting_date, batch_number, count, start_time, end_time, object_label=None):
|
||||
batch_label = self._normalize_batch_label(object_label) if object_label else self.object_label
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO batches
|
||||
(counting_date, batch_number, camera_name, object_label, count, start_time, end_time)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(counting_date, batch_number, self.camera_name, batch_label, count, start_time, end_time),
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO daily_summaries
|
||||
(counting_date, camera_name, object_label, total_count, total_batches)
|
||||
VALUES (?, ?, ?, ?, 1)
|
||||
ON CONFLICT(counting_date, camera_name, object_label)
|
||||
DO UPDATE SET
|
||||
total_count = total_count + excluded.total_count,
|
||||
total_batches = total_batches + excluded.total_batches,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""",
|
||||
(counting_date, self.camera_name, batch_label, count),
|
||||
)
|
||||
self.db.commit()
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0), COALESCE(SUM(total_batches), 0)
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ? AND camera_name = ?
|
||||
""",
|
||||
(counting_date, self.camera_name),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
self.log(
|
||||
f'Daily totals for {counting_date}: {row[0]} objects across {row[1]} batch(es)'
|
||||
)
|
||||
|
||||
def cutoff_watcher_loop(self):
|
||||
while not self.shutdown_event.is_set():
|
||||
time.sleep(60)
|
||||
with self.state_lock:
|
||||
if self.current_state is None:
|
||||
continue
|
||||
if self.current_state['counting_date'] != self.get_counting_date():
|
||||
self.log('Daily cutoff reached – finalizing batch')
|
||||
self._end_batch_locked(closed_by='cutoff')
|
||||
|
||||
def start_cutoff_watcher(self):
|
||||
t = threading.Thread(target=self.cutoff_watcher_loop, daemon=True)
|
||||
t.start()
|
||||
return t
|
||||
|
||||
@property
|
||||
def current_batch_number(self):
|
||||
if self.current_state is None:
|
||||
return 0
|
||||
return self.current_state['batch_number']
|
||||
|
||||
@property
|
||||
def current_batch_count(self):
|
||||
if self.current_state is None:
|
||||
return 0
|
||||
return self.current_state['count']
|
||||
|
||||
@property
|
||||
def current_batch_object_label(self):
|
||||
if self.current_state is None:
|
||||
return None
|
||||
return self._normalize_batch_label(self.current_state.get('object_label'))
|
||||
|
||||
def get_closed_total_for_day(self, counting_date=None):
|
||||
if counting_date is None:
|
||||
counting_date = self.get_counting_date()
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0)
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ? AND camera_name = ?
|
||||
""",
|
||||
(counting_date, self.camera_name),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return row[0] if row else 0
|
||||
|
||||
def display_total(self):
|
||||
return self.get_closed_total_for_day() + self.current_batch_count
|
||||
|
||||
def get_status(self):
|
||||
with self.state_lock:
|
||||
active = self.current_state is not None
|
||||
cdate = self.get_counting_date()
|
||||
obj_label = (
|
||||
self._normalize_batch_label(self.current_state.get('object_label'))
|
||||
if active
|
||||
else None
|
||||
)
|
||||
return {
|
||||
"active": active,
|
||||
"status": "running" if active else "stopped",
|
||||
"batch_mode": self.batch_mode,
|
||||
"batch_number": self.current_state['batch_number'] if active else None,
|
||||
"object_label": obj_label,
|
||||
"next_batch_number": self.get_next_batch_number(cdate) if not active else None,
|
||||
"count": self.current_state['count'] if active else 0,
|
||||
"counting_date": self.current_state['counting_date'] if active else cdate,
|
||||
"start_time": self.current_state['start_time'] if active else None,
|
||||
"last_detection_time": self.current_state['last_detection_time'] if active else None,
|
||||
}
|
||||
|
||||
def shutdown(self):
|
||||
self.shutdown_event.set()
|
||||
self.end_batch(closed_by='shutdown')
|
||||
if self.batch_timer:
|
||||
self.batch_timer.cancel()
|
||||
self.db.close()
|
||||
Binary file not shown.
@@ -0,0 +1,183 @@
|
||||
# =============================================================================
|
||||
# Edge RK3588 production sack counter + dashboard
|
||||
# Shared config for: counter_live_rknn.py + counter_dashboard.py
|
||||
# System Mode: MANUAL START & END BATCH
|
||||
# Copy to .env on device: cp config.env.example .env && nano .env
|
||||
# =============================================================================
|
||||
|
||||
# --- Core paths ---
|
||||
# Root output directory (logs, DB, video, CSV)
|
||||
OUTPUT_DIR=/opt/feedmill
|
||||
# SQLite database path for batch entries & crossing logs
|
||||
DB_PATH=/opt/feedmill/feedmill.db
|
||||
# JSON file persisting the current active batch state
|
||||
STATE_FILE=/opt/feedmill/bytetrack_current_batch.json
|
||||
|
||||
# --- Input source ---
|
||||
# RTSP / HTTP live stream, or a local video file path
|
||||
SOURCE=rtsp://user:pass@192.168.0.100:554/stream1
|
||||
# FFmpeg capture options passed to cv2.VideoCapture (RTSP low-latency flags)
|
||||
OPENCV_FFMPEG_CAPTURE_OPTIONS=rtsp_transport;tcp|fflags;nobuffer|flags;low_delay
|
||||
|
||||
# --- RKNN model ---
|
||||
# Path to exported .rknn model (YOLO format, e.g. yolo11n.rknn)
|
||||
MODEL_PATH=/opt/models/yolo9t.rknn
|
||||
# Input image size for the model (square, e.g. 320 → 320×320)
|
||||
IMGSZ=320
|
||||
# Use FP16 inference on NPU (true/false); currently unused in ByteTrack variant
|
||||
HALF=false
|
||||
# NPU core mask: 1=core0, 2=core1, 3=core0+core1, 7=all three
|
||||
CORE_MASK=7
|
||||
# Compute device index (reserved; not used at runtime)
|
||||
DEVICE=0
|
||||
|
||||
# --- YOLO decoder ---
|
||||
# Number of object classes the model outputs (1 = sack only)
|
||||
NUM_CLASSES=1
|
||||
# Apply sigmoid to raw class scores (true/false); set true if model head uses BCE logits
|
||||
SCORE_SIGMOID=false
|
||||
|
||||
# --- Detection ---
|
||||
# Default confidence threshold – dipakai jika confidence per objek di bawah dikosongkan
|
||||
CONF=0.3
|
||||
# Confidence threshold khusus per objek (0.0 - 1.0). Kosongkan jika ingin mengikuti CONF di atas.
|
||||
SACK_CONF=0.3
|
||||
BOX_CONF=0.3
|
||||
TRUCK_CONF=0.3
|
||||
|
||||
# --- ByteTrack tracking ---
|
||||
# Counted sack class, index 0
|
||||
# Detections with score ≥ this get priority matching in the first association stage
|
||||
TRACK_HIGH_THRESH_0=0.25
|
||||
# Detections with score between this and TRACK_HIGH_THRESH are matched in the second stage
|
||||
TRACK_LOW_THRESH_0=0.1
|
||||
# IoU threshold for the first-stage association (0–1). Higher = stricter overlap required
|
||||
TRACK_MATCH_THRESH_0=0.3
|
||||
# Frames a track survives without a match before being permanently removed
|
||||
TRACK_BUFFER_0=30
|
||||
# Minimum consecutive (or total) hits needed before a track is considered confirmed
|
||||
TRACK_MIN_HITS_0=3
|
||||
|
||||
# --- ID-switch counting guards ---
|
||||
# When a track's ID changes right at the counting line, one physical object can be
|
||||
# counted twice (two IDs cross) or missed (neither ID sees the full transition).
|
||||
#
|
||||
# Dedup guard (prevents double counting): after a crossing, a second crossing in
|
||||
# the SAME direction within DEDUP_FRAMES frames and DEDUP_PX pixels along the line is
|
||||
# ignored (treated as the same object under a new ID). Set DEDUP_PX=-1 to disable.
|
||||
DEDUP_FRAMES=4
|
||||
DEDUP_PX=35
|
||||
#
|
||||
# Inheritance guard (prevents missed counting): when a brand-new track appears, it
|
||||
# inherits the last position of a recently-seen nearby track (within INHERIT_SEC
|
||||
# seconds and INHERIT_PX pixels) so the crossing is still detected across the ID switch.
|
||||
# Set INHERIT_PX=-1 to disable.
|
||||
INHERIT_SEC=1.0
|
||||
INHERIT_PX=60
|
||||
|
||||
# --- Display ---
|
||||
# Site name shown on the dashboard header (top-right)
|
||||
SITE_NAME=ZenAi
|
||||
|
||||
# --- Object class names ---
|
||||
# Camera / location identifier shown in HUD and stored in DB
|
||||
CAMERA_NAME=ZenAi
|
||||
# Label used for batch grouping in the database
|
||||
OBJECT_LABEL=sack,box,truck
|
||||
# Class name for the counted object (must match NUM_CLASSES order, index 0)
|
||||
CLASS_COUNTED_OBJECT=sack,box,truck
|
||||
# Class IDs that are tracked and counted (0=sack, 1=box)
|
||||
COUNTED_CLASS_IDS=0,1
|
||||
# Class ID for truck detection used to determine the horizontal counting zone (2=truck)
|
||||
TRUCK_CLASS_ID=2
|
||||
|
||||
# --- Horizontal Counting Zone (Full Vertical Height) ---
|
||||
# Mode zona hitung horizontal:
|
||||
# auto = mengikuti posisi X dari deteksi truck (dengan fallback & hold jika deteksi hilang)
|
||||
# manual = selalu menggunakan batas X tetap dari ZONE_X_MIN/MAX atau ZONE_X_MIN_FRAC/MAX_FRAC
|
||||
ZONE_MODE=auto
|
||||
# Batas kiri & kanan zona dalam pixel (kosongkan jika ingin memakai FRAC di bawah)
|
||||
ZONE_X_MIN=
|
||||
ZONE_X_MAX=
|
||||
# Batas kiri & kanan zona dalam rasio lebar frame (0.0 - 1.0). Digunakan saat ZONE_X_MIN/MAX kosong.
|
||||
ZONE_X_MIN_FRAC=0.30
|
||||
ZONE_X_MAX_FRAC=0.80
|
||||
# Tambahan lebar (padding kiri & kanan dalam pixel) pada bounding box truck saat ZONE_MODE=auto
|
||||
TRUCK_ZONE_PAD_X=10
|
||||
# Berapa detik zona truck terakhir dipertahankan saat deteksi truck sempat hilang (ZONE_MODE=auto)
|
||||
TRUCK_ZONE_HOLD_SEC=300
|
||||
|
||||
# --- Line crossing ---
|
||||
# Counting axis: auto | x | y. Use y for sacks moving down across a horizontal line.
|
||||
COUNT_AXIS=y
|
||||
# Direction for counting: down (top-to-bottom) | up | ltr | rtl | both
|
||||
CROSS_DIRECTION=down
|
||||
# Fixed x-coordinate for the counting line (used when COUNT_AXIS=x)
|
||||
LINE_X=
|
||||
# Fraction of frame width where the counting line is drawn (default 0.5 = centre)
|
||||
LINE_X_FRAC=0.5
|
||||
# Fixed y-coordinate for the counting line (used when COUNT_AXIS=y)
|
||||
LINE_Y=
|
||||
# Fraction of frame height where the counting line is drawn (default 0.5 = centre)
|
||||
LINE_Y_FRAC=0.5
|
||||
|
||||
# --- Batch management (MANUAL TRIGGER) ---
|
||||
# Operating mode: manual | auto
|
||||
# manual: Operator clicks "START BATCH" to start counting and "STOP BATCH" to finish
|
||||
BATCH_MODE=manual
|
||||
|
||||
# Internal IPC control server (counter_live_rknn <-> counter_dashboard)
|
||||
COUNTER_CONTROL_HOST=127.0.0.1
|
||||
COUNTER_CONTROL_PORT=5001
|
||||
|
||||
# Daily cutoff time (HH:MM) – batch numbering resets after this time each day
|
||||
DAILY_CUTOFF_TIME=20:00
|
||||
CUTOFF_TIME=20:00
|
||||
# Reset frame counter and ByteTrack track-ID counter back to 0 at daily cutoff
|
||||
RESET_COUNTERS_AT_CUTOFF=true
|
||||
|
||||
# Timeout in seconds without sack line crossings (disabled in manual mode so pauses won't close batch)
|
||||
BATCH_TIMEOUT_SECONDS=600
|
||||
|
||||
# Minimum sacks per batch to persist to database (set to 1 for manual mode)
|
||||
MIN_OBJECT_PER_BATCH=1
|
||||
# Minimum duration in seconds a batch must be open (set to 0 for manual mode)
|
||||
MIN_DURATION_PER_BATCH=0
|
||||
|
||||
# --- CSV export ---
|
||||
# Write per-crossing events to a CSV file (true/false)
|
||||
EXPORT_CSV=true
|
||||
# Path where the crossing CSV is written
|
||||
CROSS_CSV=/opt/feedmill/batch_crossings.csv
|
||||
|
||||
# --- Rate / performance ---
|
||||
# Motion detection pre-filter (true/false)
|
||||
MOTION_DETECTION_ENABLED=false
|
||||
MOTION_THRESHOLD=5.0
|
||||
RATE_WINDOW_SEC=60
|
||||
WARMUP_FRAMES=30
|
||||
RECONNECT_DELAY_SEC=3
|
||||
MAX_RECONNECT_ATTEMPTS=0
|
||||
# Cap stream error messages per outage (0 = unlimited + keep FFmpeg stderr)
|
||||
STREAM_ERROR_LOG_MAX=3
|
||||
FLUSH_EVERY_N_FRAMES=100
|
||||
TRACKED_PRUNE_SEC=300
|
||||
|
||||
# --- Video recording ---
|
||||
RECORD_VIDEO=false
|
||||
VIDEO_SEGMENT_SEC=3600
|
||||
OUTPUT_FPS=15
|
||||
|
||||
# --- Live stream snapshot ---
|
||||
LIVE_STREAM_ENABLED=false
|
||||
LIVE_STREAM_FRAME_PATH=/dev/shm/feedmill/live_frame.jpg
|
||||
LIVE_STREAM_QUALITY=75
|
||||
LIVE_STREAM_EVERY_N=2
|
||||
|
||||
# --- Dashboard (counter_dashboard.py) ---
|
||||
SECRET_KEY=change-me-in-production
|
||||
DASHBOARD_HOST=0.0.0.0
|
||||
# Web access port for users/operators
|
||||
DASHBOARD_PORT=7000
|
||||
FLASK_DEBUG=false
|
||||
CURRENT_BATCH_PATH=/opt/feedmill/bytetrack_current_batch.json
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
Internal lightweight HTTP control server for counter_live_rknn.
|
||||
Exposes endpoints for starting, stopping, and checking manual batches.
|
||||
"""
|
||||
import json
|
||||
import threading
|
||||
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||
|
||||
|
||||
class ControlHandler(BaseHTTPRequestHandler):
|
||||
def log_message(self, format, *args):
|
||||
# Mute standard noisy HTTP console logs
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.path in ("/status", "/api/status"):
|
||||
status = self.server.store.get_status()
|
||||
self._send_json(200, {"success": True, **status})
|
||||
else:
|
||||
self._send_json(404, {"success": False, "error": f"Endpoint {self.path} not found"})
|
||||
|
||||
def _read_json_body(self):
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", "0") or "0")
|
||||
if length > 0:
|
||||
raw = self.rfile.read(length).decode("utf-8")
|
||||
return json.loads(raw) if raw else {}
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
def do_POST(self):
|
||||
clean_path = self.path.split("?", 1)[0].rstrip("/")
|
||||
if clean_path in (
|
||||
"/start",
|
||||
"/start/sack",
|
||||
"/start/box",
|
||||
"/api/start",
|
||||
"/api/start/sack",
|
||||
"/api/start/box",
|
||||
"/api/batch/start",
|
||||
"/api/batch/start/sack",
|
||||
"/api/batch/start/box",
|
||||
):
|
||||
body = self._read_json_body()
|
||||
if clean_path.endswith("/box"):
|
||||
req_label = "box"
|
||||
elif clean_path.endswith("/sack"):
|
||||
req_label = "sack"
|
||||
else:
|
||||
req_label = str(
|
||||
body.get("object_label") or body.get("type") or "sack"
|
||||
).strip().lower()
|
||||
if req_label not in ("sack", "box"):
|
||||
req_label = "sack"
|
||||
|
||||
status = self.server.store.get_status()
|
||||
if status["active"]:
|
||||
cur_label = status.get("object_label") or "sack"
|
||||
self._send_json(200, {
|
||||
"success": True,
|
||||
"message": f"Batch #{status['batch_number']} ({cur_label.upper()}) is already running",
|
||||
"batch_number": status["batch_number"],
|
||||
"object_label": cur_label,
|
||||
"status": "running",
|
||||
})
|
||||
else:
|
||||
batch_num = self.server.store.start_new_batch(object_label=req_label)
|
||||
self._send_json(200, {
|
||||
"success": True,
|
||||
"message": f"Started Batch #{batch_num} ({req_label.upper()})",
|
||||
"batch_number": batch_num,
|
||||
"object_label": req_label,
|
||||
"status": "running",
|
||||
})
|
||||
elif clean_path in ("/stop", "/api/stop", "/api/batch/stop"):
|
||||
self._read_json_body()
|
||||
status = self.server.store.get_status()
|
||||
if not status["active"]:
|
||||
self._send_json(200, {
|
||||
"success": False,
|
||||
"error": "No active batch to stop",
|
||||
"status": "stopped",
|
||||
})
|
||||
else:
|
||||
cur_num = status["batch_number"]
|
||||
cur_count = status["count"]
|
||||
cur_label = status.get("object_label") or "sack"
|
||||
ok = self.server.store.end_batch(closed_by="manual")
|
||||
self._send_json(200, {
|
||||
"success": True,
|
||||
"message": f"Batch #{cur_num} ({cur_label.upper()}) stopped ({cur_count} {cur_label})",
|
||||
"batch_number": cur_num,
|
||||
"object_label": cur_label,
|
||||
"count": cur_count,
|
||||
"persisted": ok,
|
||||
"status": "stopped",
|
||||
})
|
||||
else:
|
||||
self._send_json(404, {"success": False, "error": f"Endpoint {self.path} not found"})
|
||||
|
||||
def _send_json(self, code, payload):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
def start_control_server(store, host="127.0.0.1", port=5001, logger=print):
|
||||
try:
|
||||
server = HTTPServer((host, port), ControlHandler)
|
||||
server.store = store
|
||||
t = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
t.start()
|
||||
logger(f"Internal control server listening on http://{host}:{port}")
|
||||
return server
|
||||
except Exception as e:
|
||||
logger(f"Failed to start internal control server on {host}:{port}: {e}")
|
||||
return None
|
||||
@@ -0,0 +1,735 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Edge RKNN production counter dashboard.
|
||||
Reads the counter database and active batch state for the sack counting flow.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from io import BytesIO
|
||||
from datetime import datetime, timedelta
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
|
||||
from flask import Flask, render_template, jsonify, request, Response
|
||||
from werkzeug.serving import WSGIRequestHandler
|
||||
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
|
||||
|
||||
app = Flask(__name__, template_folder="templates", static_folder="static")
|
||||
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "change-me-in-production")
|
||||
|
||||
_DEFAULT_DIR = "/opt/feedmill"
|
||||
DB_PATH = os.getenv("DB_PATH", f"{_DEFAULT_DIR}/feedmill.db")
|
||||
CURRENT_BATCH_PATH = os.getenv("STATE_FILE", os.getenv("CURRENT_BATCH_PATH", f"{_DEFAULT_DIR}/current_batch.json"))
|
||||
CUTOFF_TIME = os.getenv("CUTOFF_TIME", os.getenv("DAILY_CUTOFF_TIME", "20:00"))
|
||||
|
||||
LIVE_STREAM_FRAME_PATH = os.getenv("LIVE_STREAM_FRAME_PATH", "/dev/shm/feedmill/live_frame.jpg")
|
||||
|
||||
SITE_NAME = os.getenv("SITE_NAME", "LIVE")
|
||||
CAMERA_NAME = os.getenv("CAMERA_NAME", "")
|
||||
STREAM_FPS_DISPLAY = os.getenv("STREAM_FPS_DISPLAY", "30.0")
|
||||
STREAM_RESOLUTION_DISPLAY = os.getenv("STREAM_RESOLUTION_DISPLAY", "1280x720")
|
||||
STREAM_ACCURACY_PCT = os.getenv("STREAM_ACCURACY_PCT", "98")
|
||||
|
||||
DASHBOARD_PORT = int(os.getenv("DASHBOARD_PORT", "5000"))
|
||||
DASHBOARD_HOST = os.getenv("DASHBOARD_HOST", "0.0.0.0")
|
||||
FLASK_DEBUG = os.getenv("FLASK_DEBUG", "false").lower() == "true"
|
||||
|
||||
COUNTER_CONTROL_HOST = os.getenv("COUNTER_CONTROL_HOST", "127.0.0.1")
|
||||
COUNTER_CONTROL_PORT = int(os.getenv("COUNTER_CONTROL_PORT", "5001"))
|
||||
COUNTER_CONTROL_URL = f"http://{COUNTER_CONTROL_HOST}:{COUNTER_CONTROL_PORT}"
|
||||
BATCH_MODE = os.getenv("BATCH_MODE", "manual").strip().lower()
|
||||
|
||||
@app.route("/api/live-video")
|
||||
def api_live_video():
|
||||
if not os.path.isfile(LIVE_STREAM_FRAME_PATH):
|
||||
return jsonify({"success": False, "error": "Live stream frame not available yet"}), 503
|
||||
|
||||
def generate():
|
||||
consecutive_fails = 0
|
||||
MAX_FAILS = 30
|
||||
while True:
|
||||
try:
|
||||
with open(LIVE_STREAM_FRAME_PATH, "rb") as f:
|
||||
jpeg = f.read()
|
||||
if not jpeg or len(jpeg) < 2 or jpeg[:2] != b"\xff\xd8":
|
||||
consecutive_fails += 1
|
||||
if consecutive_fails >= MAX_FAILS:
|
||||
return
|
||||
time.sleep(0.05)
|
||||
continue
|
||||
consecutive_fails = 0
|
||||
yield (b"--frame\r\n"
|
||||
b"Content-Type: image/jpeg\r\n\r\n" + jpeg + b"\r\n")
|
||||
except FileNotFoundError:
|
||||
consecutive_fails += 1
|
||||
if consecutive_fails >= MAX_FAILS:
|
||||
return
|
||||
time.sleep(1.0)
|
||||
continue
|
||||
except Exception:
|
||||
consecutive_fails += 1
|
||||
if consecutive_fails >= MAX_FAILS:
|
||||
return
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
time.sleep(0.05)
|
||||
return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
|
||||
|
||||
|
||||
def _ensure_db():
|
||||
try:
|
||||
from pathlib import Path
|
||||
Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS batches (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
counting_date TEXT NOT NULL,
|
||||
batch_number INTEGER NOT NULL,
|
||||
camera_name TEXT NOT NULL,
|
||||
object_label TEXT NOT NULL,
|
||||
count INTEGER NOT NULL,
|
||||
start_time TEXT NOT NULL,
|
||||
end_time TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(counting_date, batch_number, camera_name, object_label)
|
||||
)
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS daily_summaries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
counting_date TEXT NOT NULL,
|
||||
camera_name TEXT NOT NULL,
|
||||
object_label TEXT NOT NULL,
|
||||
total_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_batches INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(counting_date, camera_name, object_label)
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
except Exception as e:
|
||||
print(f"[Warning] Could not initialize database at {DB_PATH}: {e}")
|
||||
|
||||
_ensure_db()
|
||||
|
||||
|
||||
def get_db():
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
|
||||
def get_counting_date(dt=None, cutoff_str=CUTOFF_TIME):
|
||||
if dt is None:
|
||||
dt = datetime.now()
|
||||
cutoff = datetime.strptime(cutoff_str, "%H:%M").time()
|
||||
if dt.time() < cutoff:
|
||||
return dt.date().isoformat()
|
||||
return (dt.date() + timedelta(days=1)).isoformat()
|
||||
|
||||
|
||||
def get_next_batch_number_db(counting_date=None):
|
||||
try:
|
||||
if counting_date is None:
|
||||
counting_date = get_counting_date()
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT COALESCE(MAX(batch_number), 0) + 1 FROM batches WHERE counting_date = ?",
|
||||
(counting_date,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
return row[0] if row else 1
|
||||
except Exception:
|
||||
return 1
|
||||
|
||||
|
||||
def _send_counter_command(endpoint):
|
||||
url = f"{COUNTER_CONTROL_URL}/{endpoint}"
|
||||
req = urllib.request.Request(url, data=b"", method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=4.0) as resp:
|
||||
return json.loads(resp.read().decode("utf-8")), resp.status
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
return json.loads(e.read().decode("utf-8")), e.code
|
||||
except Exception:
|
||||
return {"success": False, "error": f"HTTP {e.code}"}, e.code
|
||||
except urllib.error.URLError as e:
|
||||
return {
|
||||
"success": False,
|
||||
"error": "Engine counter tidak aktif. Pastikan service feedmill-counter berjalan.",
|
||||
"detail": str(e.reason),
|
||||
}, 503
|
||||
except Exception as e:
|
||||
return {"success": False, "error": str(e)}, 500
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return render_template(
|
||||
"dashboard.html",
|
||||
site_name=SITE_NAME,
|
||||
camera_name=CAMERA_NAME,
|
||||
cutoff_time=CUTOFF_TIME,
|
||||
stream_fps=STREAM_FPS_DISPLAY,
|
||||
stream_resolution=STREAM_RESOLUTION_DISPLAY,
|
||||
stream_accuracy=STREAM_ACCURACY_PCT,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_obj_label(raw_label):
|
||||
val = str(raw_label or "").strip().lower()
|
||||
return "box" if val == "box" else "sack"
|
||||
|
||||
|
||||
@app.route("/api/current-batch")
|
||||
def api_current_batch():
|
||||
cdate = get_counting_date()
|
||||
try:
|
||||
with open(CURRENT_BATCH_PATH, "r") as f:
|
||||
data = json.load(f)
|
||||
return jsonify(
|
||||
{
|
||||
"success": True,
|
||||
"active": True,
|
||||
"status": "running",
|
||||
"batch_mode": BATCH_MODE,
|
||||
"counting_date": data.get("counting_date", cdate),
|
||||
"batch_number": data.get("batch_number"),
|
||||
"object_label": _normalize_obj_label(data.get("object_label")),
|
||||
"count": data.get("count", 0),
|
||||
"start_time": data.get("start_time"),
|
||||
"last_detection_time": data.get("last_detection_time"),
|
||||
}
|
||||
)
|
||||
except FileNotFoundError:
|
||||
next_batch = get_next_batch_number_db(cdate)
|
||||
return jsonify(
|
||||
{
|
||||
"success": False,
|
||||
"active": False,
|
||||
"status": "stopped",
|
||||
"batch_mode": BATCH_MODE,
|
||||
"error": "No active batch",
|
||||
"count": 0,
|
||||
"batch_number": None,
|
||||
"object_label": None,
|
||||
"next_batch_number": next_batch,
|
||||
"counting_date": cdate,
|
||||
}
|
||||
), 200
|
||||
except Exception as e:
|
||||
next_batch = get_next_batch_number_db(cdate)
|
||||
return jsonify(
|
||||
{
|
||||
"success": False,
|
||||
"active": False,
|
||||
"status": "stopped",
|
||||
"batch_mode": BATCH_MODE,
|
||||
"error": str(e),
|
||||
"count": 0,
|
||||
"batch_number": None,
|
||||
"object_label": None,
|
||||
"next_batch_number": next_batch,
|
||||
"counting_date": cdate,
|
||||
}
|
||||
), 500
|
||||
|
||||
|
||||
@app.route("/api/batch/start", methods=["POST"])
|
||||
@app.route("/api/batch/start/<object_label>", methods=["POST"])
|
||||
def api_batch_start(object_label=None):
|
||||
if not object_label:
|
||||
body = request.get_json(silent=True) or {}
|
||||
object_label = body.get("object_label") or request.args.get("object_label") or "sack"
|
||||
obj_type = _normalize_obj_label(object_label)
|
||||
data, code = _send_counter_command(f"start/{obj_type}")
|
||||
return jsonify(data), code
|
||||
|
||||
|
||||
@app.route("/api/batch/stop", methods=["POST"])
|
||||
def api_batch_stop():
|
||||
data, code = _send_counter_command("stop")
|
||||
return jsonify(data), code
|
||||
|
||||
|
||||
@app.route("/api/batch/status", methods=["GET"])
|
||||
def api_batch_status():
|
||||
url = f"{COUNTER_CONTROL_URL}/status"
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=2.0) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
return jsonify(data), 200
|
||||
except Exception:
|
||||
state_data = None
|
||||
if os.path.isfile(CURRENT_BATCH_PATH):
|
||||
try:
|
||||
with open(CURRENT_BATCH_PATH, "r") as f:
|
||||
state_data = json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cdate = get_counting_date()
|
||||
next_batch = get_next_batch_number_db(cdate)
|
||||
|
||||
if state_data:
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"active": True,
|
||||
"status": "running",
|
||||
"batch_mode": BATCH_MODE,
|
||||
"batch_number": state_data.get("batch_number"),
|
||||
"object_label": _normalize_obj_label(state_data.get("object_label")),
|
||||
"count": state_data.get("count", 0),
|
||||
"counting_date": state_data.get("counting_date", cdate),
|
||||
"start_time": state_data.get("start_time"),
|
||||
"last_detection_time": state_data.get("last_detection_time"),
|
||||
"engine_alive": False,
|
||||
}), 200
|
||||
else:
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"active": False,
|
||||
"status": "stopped",
|
||||
"batch_mode": BATCH_MODE,
|
||||
"batch_number": None,
|
||||
"object_label": None,
|
||||
"next_batch_number": next_batch,
|
||||
"count": 0,
|
||||
"counting_date": cdate,
|
||||
"start_time": None,
|
||||
"last_detection_time": None,
|
||||
"engine_alive": False,
|
||||
}), 200
|
||||
|
||||
|
||||
@app.route("/api/previous-batch")
|
||||
def api_previous_batch():
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, batch_number, object_label, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
ORDER BY end_time DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
if row:
|
||||
return jsonify(
|
||||
{
|
||||
"success": True,
|
||||
"date": row["counting_date"],
|
||||
"batch_number": row["batch_number"],
|
||||
"object_label": _normalize_obj_label(row["object_label"]),
|
||||
"count": row["count"],
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": row["duration_minutes"],
|
||||
}
|
||||
)
|
||||
return jsonify({"success": False, "error": "No previous batch"}), 200
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/summary")
|
||||
def api_summary():
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
today = get_counting_date()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0) as total_count,
|
||||
COALESCE(SUM(total_batches), 0) as total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(today,),
|
||||
)
|
||||
today_row = cur.fetchone()
|
||||
yesterday = (datetime.strptime(today, "%Y-%m-%d").date() - timedelta(days=1)).isoformat()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0) as total_count,
|
||||
COALESCE(SUM(total_batches), 0) as total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(yesterday,),
|
||||
)
|
||||
yesterday_row = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0) as grand_total,
|
||||
COALESCE(SUM(total_batches), 0) as grand_batches,
|
||||
COUNT(DISTINCT counting_date) as total_days
|
||||
FROM daily_summaries
|
||||
"""
|
||||
)
|
||||
all_time = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT ROUND(AVG(day_total), 1) as avg_per_day
|
||||
FROM (
|
||||
SELECT SUM(total_count) as day_total
|
||||
FROM daily_summaries
|
||||
GROUP BY counting_date
|
||||
)
|
||||
"""
|
||||
)
|
||||
avg = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, SUM(total_count) as total_count
|
||||
FROM daily_summaries
|
||||
GROUP BY counting_date
|
||||
ORDER BY total_count DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
best = cur.fetchone()
|
||||
conn.close()
|
||||
return jsonify(
|
||||
{
|
||||
"today": {
|
||||
"date": today,
|
||||
"total_count": today_row["total_count"] if today_row else 0,
|
||||
"total_batches": today_row["total_batches"] if today_row else 0,
|
||||
},
|
||||
"yesterday": {
|
||||
"date": yesterday,
|
||||
"total_count": yesterday_row["total_count"] if yesterday_row else 0,
|
||||
"total_batches": yesterday_row["total_batches"] if yesterday_row else 0,
|
||||
},
|
||||
"all_time": {
|
||||
"grand_total": all_time["grand_total"],
|
||||
"grand_batches": all_time["grand_batches"],
|
||||
"total_days": all_time["total_days"],
|
||||
},
|
||||
"average_per_day": avg["avg_per_day"] or 0,
|
||||
"best_day": {
|
||||
"date": best["counting_date"] if best else None,
|
||||
"count": best["total_count"] if best else 0,
|
||||
},
|
||||
}
|
||||
)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}", "today": {"date": datetime.now().date().isoformat(), "total_count": 0, "total_batches": 0}, "yesterday": {"date": "", "total_count": 0, "total_batches": 0}, "all_time": {"grand_total": 0, "grand_batches": 0, "total_days": 0}, "average_per_day": 0, "best_day": {"date": None, "count": 0}}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/daily-data")
|
||||
def api_daily_data():
|
||||
try:
|
||||
days = request.args.get("days", 30, type=int)
|
||||
date_from = (datetime.now() - timedelta(days=days)).date().isoformat()
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date,
|
||||
SUM(total_count) as total_count,
|
||||
SUM(total_batches) as total_batches,
|
||||
ROUND(CAST(SUM(total_count) AS FLOAT) / SUM(total_batches), 1) as avg_per_batch
|
||||
FROM daily_summaries
|
||||
WHERE counting_date >= ?
|
||||
GROUP BY counting_date
|
||||
ORDER BY counting_date ASC
|
||||
""",
|
||||
(date_from,),
|
||||
)
|
||||
daily_data = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"total_count": row["total_count"],
|
||||
"total_batches": row["total_batches"],
|
||||
"avg_per_batch": row["avg_per_batch"] or 0,
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(daily_data)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify([]), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/day-detail/<date>")
|
||||
def api_day_detail(date):
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT batch_number, object_label, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date = ?
|
||||
ORDER BY batch_number ASC
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
batches = []
|
||||
total_duration = 0
|
||||
for row in cur.fetchall():
|
||||
duration = row["duration_minutes"] or 0
|
||||
total_duration += duration
|
||||
batches.append(
|
||||
{
|
||||
"batch_number": row["batch_number"],
|
||||
"object_label": _normalize_obj_label(row["object_label"]),
|
||||
"count": row["count"],
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": duration,
|
||||
}
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0) as total_count,
|
||||
COALESCE(SUM(total_batches), 0) as total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
summary = cur.fetchone()
|
||||
conn.close()
|
||||
return jsonify(
|
||||
{
|
||||
"date": date,
|
||||
"total_count": summary["total_count"] if summary else 0,
|
||||
"total_batches": summary["total_batches"] if summary else 0,
|
||||
"total_duration_minutes": round(total_duration, 1),
|
||||
"avg_duration_minutes": round(total_duration / len(batches), 1) if batches else 0,
|
||||
"batches": batches,
|
||||
}
|
||||
)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"date": date, "total_count": 0, "total_batches": 0, "total_duration_minutes": 0, "avg_duration_minutes": 0, "batches": [], "error": f"Database unavailable: {e}"}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/recent-batches")
|
||||
def api_recent_batches():
|
||||
try:
|
||||
limit = request.args.get("limit", 10, type=int)
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, batch_number, object_label, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
ORDER BY end_time DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(limit,),
|
||||
)
|
||||
batches = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"batch_number": row["batch_number"],
|
||||
"object_label": _normalize_obj_label(row["object_label"]),
|
||||
"count": row["count"],
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": row["duration_minutes"] or 0,
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(batches)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify([]), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/available-dates")
|
||||
def api_available_dates():
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date,
|
||||
SUM(total_count) as total_count,
|
||||
SUM(total_batches) as total_batches
|
||||
FROM daily_summaries
|
||||
GROUP BY counting_date
|
||||
ORDER BY counting_date DESC
|
||||
"""
|
||||
)
|
||||
dates = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"total_count": row["total_count"],
|
||||
"total_batches": row["total_batches"],
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(dates)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify([]), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
def _excel_response(wb, filename):
|
||||
output = BytesIO()
|
||||
wb.save(output)
|
||||
output.seek(0)
|
||||
return Response(
|
||||
output.getvalue(),
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f"attachment; filename={filename}"},
|
||||
)
|
||||
|
||||
|
||||
def _style_header(ws, cols):
|
||||
header_font = Font(bold=True, color="FFFFFF", size=11)
|
||||
header_fill = PatternFill(start_color="2F5496", end_color="2F5496", fill_type="solid")
|
||||
thin_border = Border(
|
||||
left=Side(style="thin"), right=Side(style="thin"),
|
||||
top=Side(style="thin"), bottom=Side(style="thin"),
|
||||
)
|
||||
for col_idx, (col_letter, text) in enumerate(cols, 1):
|
||||
cell = ws.cell(row=1, column=col_idx, value=text)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = Alignment(horizontal="center")
|
||||
cell.border = thin_border
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
|
||||
def _auto_width(ws):
|
||||
for col in ws.columns:
|
||||
max_len = 0
|
||||
col_letter = col[0].column_letter
|
||||
for cell in col:
|
||||
if cell.value is not None:
|
||||
max_len = max(max_len, len(str(cell.value)))
|
||||
ws.column_dimensions[col_letter].width = max_len + 4
|
||||
|
||||
|
||||
@app.route("/api/export-daily-csv")
|
||||
def export_daily_xlsx():
|
||||
try:
|
||||
days = request.args.get("days", 30, type=int)
|
||||
date_from = (datetime.now() - timedelta(days=days)).date().isoformat()
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, batch_number, object_label, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date >= ?
|
||||
ORDER BY counting_date ASC, batch_number ASC
|
||||
""",
|
||||
(date_from,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 503
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Batch Details"
|
||||
_style_header(ws, [("A", "Date"), ("B", "Batch #"), ("C", "Type"), ("D", "Count"), ("E", "Start Time"), ("F", "End Time"), ("G", "Duration (min)")])
|
||||
|
||||
for r_idx, row in enumerate(rows, 2):
|
||||
ws.cell(row=r_idx, column=1, value=row["counting_date"])
|
||||
ws.cell(row=r_idx, column=2, value=row["batch_number"])
|
||||
ws.cell(row=r_idx, column=3, value=_normalize_obj_label(row["object_label"]).upper())
|
||||
ws.cell(row=r_idx, column=4, value=row["count"])
|
||||
ws.cell(row=r_idx, column=5, value=row["start_time"])
|
||||
ws.cell(row=r_idx, column=6, value=row["end_time"])
|
||||
ws.cell(row=r_idx, column=7, value=row["duration_minutes"] or 0)
|
||||
|
||||
_auto_width(ws)
|
||||
filename = f"{SITE_NAME}_daily_records_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
||||
return _excel_response(wb, filename)
|
||||
|
||||
|
||||
@app.route("/api/export-day-csv/<date>")
|
||||
def export_day_xlsx(date):
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT batch_number, object_label, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date = ?
|
||||
ORDER BY batch_number ASC
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 503
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = f"Day {date}"
|
||||
_style_header(ws, [("A", "Batch Number"), ("B", "Type"), ("C", "Count"), ("D", "Start Time"), ("E", "End Time"), ("F", "Duration (min)")])
|
||||
|
||||
for r_idx, row in enumerate(rows, 2):
|
||||
ws.cell(row=r_idx, column=1, value=row["batch_number"])
|
||||
ws.cell(row=r_idx, column=2, value=_normalize_obj_label(row["object_label"]).upper())
|
||||
ws.cell(row=r_idx, column=3, value=row["count"])
|
||||
ws.cell(row=r_idx, column=4, value=row["start_time"])
|
||||
ws.cell(row=r_idx, column=5, value=row["end_time"])
|
||||
ws.cell(row=r_idx, column=6, value=row["duration_minutes"] or 0)
|
||||
|
||||
_auto_width(ws)
|
||||
filename = f"{SITE_NAME}_day_detail_{date}.xlsx"
|
||||
return _excel_response(wb, filename)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
WSGIRequestHandler.protocol_version = "HTTP/1.1"
|
||||
print(f"RKNN counter dashboard at http://{DASHBOARD_HOST}:{DASHBOARD_PORT}")
|
||||
print(f"DB: {DB_PATH}")
|
||||
print(f"State: {CURRENT_BATCH_PATH}")
|
||||
app.run(host=DASHBOARD_HOST, port=DASHBOARD_PORT, debug=FLASK_DEBUG)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,33 @@
|
||||
[Unit]
|
||||
Description=RKNN Sack Counter (RTSP + ByteTrack)
|
||||
Documentation=file:///opt/feedmill/DEPLOY.md
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
|
||||
WorkingDirectory=/opt/feedmill
|
||||
|
||||
EnvironmentFile=/opt/feedmill/.env
|
||||
Environment=PYTHONNOUSERSITE=1
|
||||
Environment=PATH=/opt/feedmill/venv/bin:/usr/local/bin:/usr/bin:/bin
|
||||
|
||||
ExecStart=/opt/feedmill/venv/bin/python counter_live_rknn.py
|
||||
|
||||
TimeoutStopSec=30
|
||||
KillSignal=SIGTERM
|
||||
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
StartLimitInterval=120s
|
||||
StartLimitBurst=5
|
||||
|
||||
NoNewPrivileges=true
|
||||
ProtectHome=true
|
||||
PrivateTmp=false
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,33 @@
|
||||
[Unit]
|
||||
Description=RKNN Counter Dashboard (Flask, port 7000)
|
||||
Documentation=file:///opt/feedmill/DEPLOY.md
|
||||
After=network-online.target feedmill-counter.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
|
||||
WorkingDirectory=/opt/feedmill
|
||||
|
||||
EnvironmentFile=/opt/feedmill/.env
|
||||
Environment=PATH=/opt/feedmill/venv/bin:/usr/local/bin:/usr/bin:/bin
|
||||
Environment=FLASK_DEBUG=false
|
||||
|
||||
ExecStart=/opt/feedmill/venv/bin/python counter_dashboard.py
|
||||
|
||||
TimeoutStopSec=15
|
||||
KillSignal=SIGTERM
|
||||
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
StartLimitInterval=60s
|
||||
StartLimitBurst=3
|
||||
|
||||
NoNewPrivileges=true
|
||||
ProtectHome=true
|
||||
PrivateTmp=false
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install RKNN sack counter + dashboard services.
|
||||
# Run on the target device: sudo ./install-services.sh
|
||||
set -euo pipefail
|
||||
|
||||
INSTALL_DIR="${INSTALL_DIR:-/opt/feedmill}"
|
||||
VENV_DIR="${VENV_DIR:-/opt/feedmill/venv}"
|
||||
SERVICE_USER="${SERVICE_USER:-root}"
|
||||
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
echo "Run as root: sudo ./install-services.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -f "${INSTALL_DIR}/.env" ]]; then
|
||||
echo "Missing ${INSTALL_DIR}/.env"
|
||||
echo " cp ${INSTALL_DIR}/config.env.example ${INSTALL_DIR}/.env && nano ${INSTALL_DIR}/.env"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -x "${VENV_DIR}/bin/python" ]]; then
|
||||
echo "Missing venv: ${VENV_DIR}/bin/python"
|
||||
echo " sudo ./setup-venv.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sed -i 's/\r$//' "${INSTALL_DIR}/.env" 2>/dev/null || true
|
||||
|
||||
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${INSTALL_DIR}"
|
||||
|
||||
# Disable legacy service names
|
||||
for legacy in frigate-counter frigate-counter-dashboard feedmill feedmill-counter-dashboard; do
|
||||
if systemctl is-enabled "${legacy}" &>/dev/null; then
|
||||
systemctl disable --now "${legacy}" || true
|
||||
echo "Disabled legacy ${legacy}"
|
||||
fi
|
||||
done
|
||||
|
||||
for unit in feedmill-counter feedmill-dashboard; do
|
||||
sed -e "s|/opt/feedmill|${INSTALL_DIR}|g" \
|
||||
-e "s|User=root|User=${SERVICE_USER}|g" \
|
||||
-e "s|Group=root|Group=${SERVICE_USER}|g" \
|
||||
"${INSTALL_DIR}/${unit}.service" > "/etc/systemd/system/${unit}.service"
|
||||
echo "Installed /etc/systemd/system/${unit}.service"
|
||||
done
|
||||
|
||||
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${INSTALL_DIR}"
|
||||
|
||||
PYTHONNOUSERSITE=1 "${VENV_DIR}/bin/python" -c "
|
||||
from rknnlite.api import RKNNLite
|
||||
import cv2
|
||||
from flask import Flask
|
||||
print('import ok | rknn + opencv + flask')
|
||||
" || {
|
||||
echo "Import check failed — fix venv before starting services."
|
||||
exit 1
|
||||
}
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl reset-failed feedmill-counter feedmill-dashboard 2>/dev/null || true
|
||||
systemctl enable feedmill-counter feedmill-dashboard
|
||||
systemctl restart feedmill-counter feedmill-dashboard
|
||||
|
||||
echo ""
|
||||
systemctl --no-pager status feedmill-counter feedmill-dashboard || true
|
||||
echo ""
|
||||
echo "Logs: sudo journalctl -u feedmill-counter -f"
|
||||
echo "Dashboard: http://$(hostname -I | awk '{print $1}'):5000"
|
||||
@@ -0,0 +1,6 @@
|
||||
numpy<2
|
||||
rknn-toolkit-lite2
|
||||
opencv-python
|
||||
flask
|
||||
python-dotenv
|
||||
openpyxl
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 980 KiB |
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-time venv for the RKNN sack counter.
|
||||
set -euo pipefail
|
||||
|
||||
INSTALL_DIR="${INSTALL_DIR:-/opt/feedmill}"
|
||||
VENV_DIR="${VENV_DIR:-/opt/feedmill/venv}"
|
||||
SERVICE_USER="${SERVICE_USER:-root}"
|
||||
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
echo "Run as root: sudo ./setup-venv.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
apt-get install -y python3-venv 2>/dev/null || true
|
||||
|
||||
mkdir -p "${INSTALL_DIR}"
|
||||
if [[ ! -x "${VENV_DIR}/bin/python" ]]; then
|
||||
python3 -m venv --system-site-packages "${VENV_DIR}"
|
||||
fi
|
||||
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${INSTALL_DIR}"
|
||||
|
||||
sudo -u "${SERVICE_USER}" "${VENV_DIR}/bin/pip" install --upgrade pip
|
||||
sudo -u "${SERVICE_USER}" "${VENV_DIR}/bin/pip" install -r "${INSTALL_DIR}/requirements.txt"
|
||||
|
||||
sudo -u "${SERVICE_USER}" PYTHONNOUSERSITE=1 "${VENV_DIR}/bin/python" -c "
|
||||
from rknnlite.api import RKNNLite
|
||||
import cv2
|
||||
import flask
|
||||
import dotenv
|
||||
import openpyxl
|
||||
print('venv ok | rknn + opencv + flask + dotenv + openpyxl')
|
||||
"
|
||||
|
||||
echo ""
|
||||
echo "Next: cp config.env.example .env && nano .env && sudo ./install-services.sh"
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg width="100%" height="100%" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
|
||||
<g transform="matrix(1,0,0,1,-15369.154492,-1214.474821)">
|
||||
<g transform="matrix(2.475521,0,0,1,13975.506392,1186.474821)">
|
||||
<g transform="matrix(0.906181,0,0,2.243269,-3748.32663,-602.148875)">
|
||||
<path d="M4914.259,451.079L4899.937,418.342C4890.938,397.773 4896.821,373.725 4914.3,359.634C4931.78,345.543 4956.528,344.897 4974.719,358.056L5091.331,442.412C5110.585,456.34 5118.613,481.126 5111.182,503.698C5103.75,526.269 5082.567,541.437 5058.804,541.202L5050.939,541.125L5073.639,592.72C5084.006,616.282 5076.598,643.883 5055.826,659.087C5035.054,674.292 5006.505,673.01 4987.178,656.006L4879.266,561.062C4859.513,543.682 4852.636,515.859 4862.018,491.278C4870.545,468.936 4890.872,453.546 4914.259,451.079ZM5024.451,523.597L5058.975,523.939C5075.22,524.099 5089.702,513.73 5094.783,498.299C5099.864,482.868 5094.375,465.923 5081.212,456.401L4964.6,372.045C4952.718,363.449 4936.553,363.872 4925.136,373.075C4913.719,382.279 4909.876,397.987 4915.754,411.422L4940.573,468.149L4938.895,468.131L4921.244,467.996C4902.142,467.85 4884.959,479.587 4878.147,497.434C4871.336,515.281 4876.329,535.482 4890.671,548.1L4998.583,643.045C5011.827,654.698 5031.393,655.576 5045.628,645.156C5059.864,634.736 5064.941,615.82 5057.836,599.673L5026.223,527.819L5024.451,523.597ZM4968.825,486.959L4968.329,485.718L4934.424,409.522C4931.427,402.786 4933.334,394.877 4939.071,390.247C4944.809,385.617 4952.942,385.424 4958.893,389.777L5066.605,468.558C5073.63,473.696 5076.548,482.773 5073.834,491.042C5071.119,499.312 5063.389,504.893 5054.686,504.868L4935.094,504.524C4929.238,504.507 4923.97,508.081 4921.821,513.529C4919.672,518.976 4921.081,525.184 4925.371,529.17L4933.661,536.872L4933.813,536.71C4931.614,534.38 4930.948,530.969 4932.148,527.964C4933.414,524.793 4936.498,522.727 4939.912,522.76L4965.007,523.009L4966.208,526.487L4994.023,589.707C4995.219,592.424 4996.967,594.863 4999.156,596.868L5011.424,608.101C5013.105,608.525 5014.94,608.223 5016.431,607.162C5018.776,605.494 5019.627,602.408 5018.468,599.773L4986.687,527.539L4984.872,523.205L5004.848,523.403L5006.718,528.303L5038.39,600.465C5042.406,609.614 5039.521,620.325 5031.454,626.221C5023.387,632.117 5012.306,631.612 5004.809,625.008L4906.732,538.616C4897.389,530.386 4894.151,517.211 4898.615,505.588C4903.08,493.964 4914.304,486.344 4926.755,486.484L4968.825,486.959ZM5010.315,487.427L5009.613,485.749L4990.183,439.967C4988.127,435.122 4984.795,430.926 4980.542,427.825L4965.157,416.607C4963.539,415.428 4961.33,415.49 4959.782,416.759C4958.234,418.027 4957.738,420.181 4958.576,421.999L4986.474,482.492L4988.527,487.181L5010.315,487.427Z" style="fill:white;"/>
|
||||
</g>
|
||||
<g transform="matrix(0.739983,0,0,1.831843,-7379.262587,-607.649374)">
|
||||
<rect x="10733" y="347" width="559" height="559" style="fill:none;"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.3 KiB |
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
# Remove RKNN counter systemd services.
|
||||
# Run on the target device: sudo ./uninstall-services.sh
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
echo "Run as root: sudo ./uninstall-services.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for unit in feedmill-counter feedmill-dashboard feedmill feedmill-counter-dashboard; do
|
||||
systemctl stop "${unit}" 2>/dev/null || true
|
||||
systemctl disable "${unit}" 2>/dev/null || true
|
||||
rm -f "/etc/systemd/system/${unit}.service"
|
||||
done
|
||||
|
||||
systemctl daemon-reload
|
||||
echo "Removed feedmill-counter and feedmill-dashboard services."
|
||||
BIN
Binary file not shown.
Reference in new issue
Block a user