Documentation
Complete documentation for setting up, configuring, and using the Cannabis Grow Management System.
Getting Started
Quick start guide for setting up the Cannabis Grow Management System.
System Requirements
- Operating System: Linux, macOS, or Windows with WSL2
- Docker: Docker Engine 20.10+ and Docker Compose 2.0+
- Hardware: Minimum 4GB RAM (8GB recommended), 20GB disk space
- Network: Internet access for package installation, local network for MQTT
- Ports: 3000 (backend), 3001 (WebSocket), 5173 (frontend), 1883 (MQTT), 27017 (MongoDB), 9000 (Portainer)
Prerequisites
- Docker and Docker Compose installed and running
- Sudo/administrator access (required for Docker on Linux)
- Git for cloning the repository
- Text editor for editing configuration files
Quick Setup
- Clone the repository:
git clone https://github.com/[your-username]/Canna_Projects.git cd Canna_Projects - Configure environment variables:
Edit the `.env` files and set strong passwords.cp backend/.env.example backend/.env cp docker/compose/.env.example docker/compose/.env - Start services:
sudo docker compose -f docker/compose/docker-compose.yml up -d - Create admin user:
sudo docker compose -f docker/compose/docker-compose.yml exec backend node scripts/create-admin.js - Access the application:
- Frontend: http://localhost:5173
- Backend API: http://localhost:3000
- Portainer: http://localhost:9000
ESP32 Setup Guide
Complete guide for setting up ESP32 sensor devices.
Hardware Requirements
- ESP32 development board (ESP32-WROOM-32 recommended)
- DHT22 or DHT11 temperature/humidity sensor
- Analog soil moisture sensor
- Breadboard and jumper wires
- 10kΩ resistor (for DHT sensor pull-up)
- USB cable or external power supply
Wiring Instructions
See the Hardware Setup Guide for detailed wiring diagrams and pin connections.
Firmware Installation
- Install PlatformIO or Arduino IDE
- Navigate to firmware directory:
cd backend/firmware/source/esp32/sensor-v1.0.0 - Configure WiFi and MQTT credentials in `config.h`
- Build and upload firmware:
pio run --target upload
Device Registration
- Access the Sensor Devices page in the web interface
- Click "Register New Device"
- Enter device ID, name, type (ESP32), and location
- MQTT credentials are automatically generated
- Update device firmware with MQTT credentials
API Documentation
RESTful API endpoints for programmatic access to the system. All endpoints return JSON responses.
Base URL
API base URL depends on deployment:
- Local development:
http://localhost:3000/api - Docker Compose:
http://localhost:3000/api - Traefik routing:
http://yourdomain.com/api
Authentication
All API endpoints require JWT authentication via HTTP-only cookies. The token is automatically included in requests from the frontend.
POST /api/auth/login
Content-Type: application/json
Body: {
"email": "user@example.com",
"password": "password"
}
Response: {
"success": true,
"data": {
"user": { ... },
"token": "jwt_token_here"
}
}
Sets HTTP-only cookie with JWT token
Response Format
All API responses follow a consistent format:
// Success Response
{
"success": true,
"data": { ... },
"message": "Operation successful"
}
// Error Response
{
"success": false,
"error": "Error message",
"code": "ERROR_CODE",
"details": { ... }
}
Pagination
List endpoints support pagination with query parameters:
page- Page number (default: 1)limit- Items per page (default: 20, max: 100)sort- Sort field (default: createdAt)order- Sort order: asc or desc (default: desc)
GET /api/plants?page=1&limit=20&sort=plantingDate&order=desc
Response: {
"success": true,
"data": [...],
"pagination": {
"page": 1,
"limit": 20,
"total": 100,
"pages": 5
}
}
Core Endpoints
Grows
GET /api/grows- List all grows (paginated, filtered by user)POST /api/grows- Create new grow (requires: name, growType, location)GET /api/grows/:id- Get grow details with statisticsPUT /api/grows/:id- Update grow (name, description, status, etc.)DELETE /api/grows/:id- Delete grow (cascades to plants and devices)GET /api/grows/:id/statistics- Get grow statistics (plants, devices, environmental data)
Plants
GET /api/plants- List all plants (filtered by growId, phase, status)POST /api/plants- Create new plant (requires: name, seedId, growId)GET /api/plants/:id- Get plant details with phase historyPUT /api/plants/:id- Update plant (name, notes, status)POST /api/plants/:id/phase- Update plant phase (phase, notes, conditions)GET /api/plants/:id/phases- Get plant phase historyPOST /api/plants/:id/harvest- Record harvest data (yield, quality metrics)
Environmental Data
GET /api/environmental- Query environmental dataPOST /api/environmental- Create environmental readingGET /api/environmental/statistics- Get statistics
Devices
GET /api/sensors- List sensor devicesPOST /api/sensors- Register new devicePUT /api/sensors/:id- Update deviceGET /api/sensors/:id/status- Get device status
Automation
GET /api/automation- List automation rules (filtered by growId, plantId, status)POST /api/automation- Create automation rule (name, conditions, actions, priority, cooldown)GET /api/automation/:id- Get automation rule detailsPUT /api/automation/:id- Update rule (all fields)DELETE /api/automation/:id- Delete rulePOST /api/automation/:id/trigger- Manually trigger rule (for testing)GET /api/automation/:id/statistics- Get rule execution statistics
Device Control
POST /api/devices/:id/control- Send control command (command, value, duration)POST /api/devices/:id/light/on- Turn light onPOST /api/devices/:id/light/off- Turn light offPOST /api/devices/:id/light/set_brightness- Set light brightness (0-100%)POST /api/devices/:id/pump/on- Turn pump onPOST /api/devices/:id/pump/off- Turn pump offPOST /api/devices/:id/pump/set_speed- Set pump speed (0-100%)POST /api/devices/:id/fan/on- Turn fan onPOST /api/devices/:id/fan/off- Turn fan offPOST /api/devices/:id/fan/set_speed- Set fan speed (0-100%)POST /api/devices/bulk-control- Control multiple devices (deviceIds, command, value)POST /api/devices/:id/override- Set manual override (enabled, duration)POST /api/grows/:growId/emergency-stop- Emergency stop all devices in grow
Response Format
All API responses use JSON format:
{
"success": true,
"data": { ... },
"message": "Operation successful"
}
Error Handling
Error responses include detailed information:
{
"success": false,
"error": "Error message",
"code": "ERROR_CODE",
"details": {
"field": "validation error details"
}
}
Common Error Codes
UNAUTHORIZED- Authentication required or invalid tokenFORBIDDEN- Insufficient permissionsNOT_FOUND- Resource not foundVALIDATION_ERROR- Request validation failedDUPLICATE_ENTRY- Resource already existsSERVER_ERROR- Internal server error
Rate Limiting
API endpoints are rate-limited to prevent abuse:
- General endpoints: 100 requests per 15 minutes per IP
- Authentication endpoints: 5 login attempts per 15 minutes per IP
- Rate limit headers included in responses:
X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset
MQTT Topics
MQTT topic structure for IoT device communication.
Sensor Data Topics
sensors/{growId}/{plantId}/data - Complete sensor payload
sensors/{growId}/{plantId}/temperature - Individual temperature reading
sensors/{growId}/{plantId}/humidity - Individual humidity reading
sensors/{growId}/{plantId}/soilMoisture - Soil moisture reading
sensors/{growId}/{plantId}/pH - pH reading
sensors/{growId}/{plantId}/ec - EC reading
sensors/{growId}/{plantId}/light - Light intensity reading
sensors/{growId}/{plantId}/co2 - COâ‚‚ reading
Device Topics
devices/{deviceId}/status - Device status/heartbeat
devices/{deviceId}/config - Device configuration updates (from server)
devices/{deviceId}/ota/status - OTA update progress
devices/{deviceId}/control - Device control commands
Message Format
Sensor data messages use JSON format:
{
"deviceId": "esp32-001",
"timestamp": "2024-01-01T00:00:00Z",
"growId": "507f1f77bcf86cd799439011",
"plantId": "507f191e810c19729de860ea",
"metrics": {
"temperature": 72.5,
"humidity": 65.0,
"pH": 6.5,
"co2": 400,
"ec": 1.2,
"soilMoisture": 45
}
}
OTA Firmware Updates
Over-the-air firmware updates for ESP32 and ESP8266 devices.
Prerequisites
- Device must be connected to WiFi
- Device must be registered in the system
- Firmware version must be uploaded to the system
Update Process
- Generate firmware from template or upload custom firmware
- Select target devices for update
- Initiate OTA update via web interface
- Monitor update progress via device status
- Device automatically reboots after successful update
Firmware Templates
Firmware templates are stored in backend/firmware/templates/ and are processed to inject device-specific configuration.
Troubleshooting
Common issues and solutions.
Device Connection Issues
- Device not connecting to WiFi: Check SSID and password, ensure 2.4GHz network
- MQTT connection fails: Verify MQTT broker credentials and network connectivity
- Sensor readings not appearing: Check MQTT topic structure and message format
Backend Issues
- MongoDB connection fails: Verify MongoDB credentials in .env file
- JWT errors: Ensure JWT_SECRET is set in backend/.env
- CORS errors: Check CORS_ORIGIN configuration
Frontend Issues
- API connection fails: Verify API URL configuration
- WebSocket not connecting: Check WebSocket URL and port
- Build errors: Clear node_modules and reinstall dependencies
Docker Issues
- Container won't start: Check logs with
docker compose logs - Port conflicts: Change port mappings in docker-compose.yml
- Network issues: Verify Docker network configuration
Configuration
System configuration options and environment variables.
Backend Environment Variables
| Variable | Required | Default | Description |
|---|---|---|---|
NODE_ENV |
No | development | Environment mode: development or production |
PORT |
No | 3000 | API server port |
MONGODB_URI |
Yes (Production) | - | MongoDB connection string with credentials |
JWT_SECRET |
Yes | - | JWT signing secret (min 32 characters recommended) |
MQTT_BROKER_URL |
No | mqtt://mosquitto:1883 | MQTT broker URL |
MQTT_BROKER_USERNAME |
Yes (Production) | mqtt_user | MQTT broker username |
MQTT_BROKER_PASSWORD |
Yes (Production) | - | MQTT broker password |
WEBSOCKET_PORT |
No | 3001 | WebSocket server port |
CORS_ORIGIN |
No | * | Allowed CORS origins (comma-separated) |
LOG_LEVEL |
No | info | Pino log level: debug, info, warn, error |
Frontend Environment Variables
VITE_API_URL- API base URL (optional, auto-detected from hostname for Traefik routing)VITE_WS_URL- WebSocket URL (optional, auto-detected from hostname)
Docker Compose Environment Variables
MONGO_INITDB_ROOT_USERNAME- MongoDB root username (default: admin)MONGO_INITDB_ROOT_PASSWORD- MongoDB root password (required, must match MONGODB_URI)MONGO_INITDB_DATABASE- MongoDB database name (default: cannabis_grow)MQTT_BROKER_USERNAME- MQTT broker username (default: mqtt_user)MQTT_BROKER_PASSWORD- MQTT broker password (required, must match backend config)
Security
Security best practices and recommendations.
Authentication
- JWT tokens stored in HTTP-only cookies
- Session tracking in MongoDB
- Login attempt rate limiting
- Password hashing with bcrypt
Network Security
- Use HTTPS in production
- Secure MQTT with TLS/SSL
- Firewall rules for exposed ports
- VPN for remote access
Data Security
- User-scoped data access
- Input validation and sanitization
- SQL injection prevention (MongoDB)
- Regular security updates