{"id":31044810,"url":"https://github.com/agungferdi/smart_farming","last_synced_at":"2025-09-14T16:51:50.633Z","repository":{"id":311300561,"uuid":"1043203607","full_name":"agungferdi/Smart_Farming","owner":"agungferdi","description":"A comprehensive IoT-based smart farming system featuring ESP32 microcontrollers, environmental monitoring sensors, automated irrigation control, and real-time web dashboard.","archived":false,"fork":false,"pushed_at":"2025-09-10T07:14:00.000Z","size":2302,"stargazers_count":8,"open_issues_count":0,"forks_count":2,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-09-10T10:57:51.049Z","etag":null,"topics":["cpp","esp32","hono","mqtt","nextjs","postgresql","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/agungferdi.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-08-23T11:01:44.000Z","updated_at":"2025-09-10T03:40:19.000Z","dependencies_parsed_at":"2025-09-10T09:12:40.353Z","dependency_job_id":"e27d8d9d-49cb-417d-8088-088b379b0034","html_url":"https://github.com/agungferdi/Smart_Farming","commit_stats":null,"previous_names":["agungferdi/smart_farming"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/agungferdi/Smart_Farming","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agungferdi%2FSmart_Farming","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agungferdi%2FSmart_Farming/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agungferdi%2FSmart_Farming/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agungferdi%2FSmart_Farming/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/agungferdi","download_url":"https://codeload.github.com/agungferdi/Smart_Farming/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agungferdi%2FSmart_Farming/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":275136699,"owners_count":25411709,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-14T02:00:10.474Z","response_time":75,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cpp","esp32","hono","mqtt","nextjs","postgresql","typescript"],"created_at":"2025-09-14T16:51:46.087Z","updated_at":"2025-09-14T16:51:50.616Z","avatar_url":"https://github.com/agungferdi.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Smart Farming IoT System\n\nA comprehensive IoT-based smart farming system featuring ESP32 microcontrollers, environmental monitoring sensors, automated irrigation control, and real-time web dashboard. The system uses MQTT communication via HiveMQ Cloud for real-time data exchange and remote control capabilities.\n\n## 🏗️ System Architecture\n\n```\nESP32 (Publisher) → HiveMQ Cloud → Backend (Subscriber) → Supabase PostgreSQL\n                ↘               ↗\nFrontend (Publisher) → Relay Commands → ESP32 (Subscriber)\n```\n\n![System Design](assets/System_Design.png)\n\n### **Core Components**\n\n1. **ESP32 IoT Device** - Environmental monitoring and actuator control\n2. **HiveMQ Cloud** - MQTT broker for real-time communication\n3. **Backend API** - Data processing and MQTT subscription (Deployed on Northflank)\n4. **Frontend Dashboard** - Real-time monitoring and control interface\n5. **Supabase PostgreSQL** - Database for sensor data and logs\n\n## 📱 Technology Stack\n\n### **IoT Device (ESP32)**\n\n- **Platform**: PlatformIO with Arduino Framework\n- **Microcontroller**: ESP32 DevKit v1\n- **Connectivity**: SIM7670C 4G LTE Module\n- **Protocols**: MQTT\n- **Libraries**: PubSubClient, DHT sensor, OneWire, U8g2\n\n### **Backend API**\n\n- **Runtime**: Node.js with TypeScript\n- **Framework**: Hono\n- **Database**: Supabase PostgreSQL with Prisma ORM\n- **MQTT Client**: Custom implementation for HiveMQ Cloud\n- **Deployment**: Northflank for the MQTT service and Vercel (Serverless) for the REST API\n- **Authentication**: API key-based security\n\n### **Frontend Dashboard**\n\n- **Framework**: Next.js 14 with App Router\n- **Language**: TypeScript\n- **Styling**: Tailwind CSS with shadcn/ui components\n- **State Management**: TanStack Query (React Query)\n- **Charts**: Recharts for data visualization\n- **MQTT**: Web-based MQTT client for real-time relay control\n- **Deployment**: Vercel\n\n### **Database \u0026 Communication**\n\n- **Database**: Supabase PostgreSQL\n- **MQTT Broker**: HiveMQ Cloud\n- **ORM**: Prisma with TypeScript\n- **Real-time**: MQTT for bidirectional communication\n\n## Hardware Components\n\n### Main Controller\n\n- **ESP32 DevKit**: Main microcontroller with WiFi capability\n- **SIM7670C GSM Module**: 4G LTE cellular connectivity for remote monitoring\n\n### Sensors\n\n- **DHT22/DHT11**: Temperature and humidity sensor\n- **Capacitive Soil Moisture Sensor v1.2**: Analog soil moisture detection with corrosion resistance\n- **Rain Detector**: Weather monitoring with digital output\n- **DS18B20 Soil Temperature Probe**: Waterproof soil temperature sensor\n- **Water Level Sensor**: monitoring to prevent dry running\n\n### Actuators \u0026 Output\n\n- **5V Relay Module**: Water pump control switching\n- **Water Pump**: 12V submersible or surface pump\n- **SSD1306 OLED Display**: 128x64 I2C display for essential system status\n\n### Communication \u0026 Power\n\n- **Power Supply Module**: Voltage regulation and distribution via breadboard connection\n- **Breadboard**: Prototype connections and signal distribution\n\n## Pin Configuration\n\n| Component                  | ESP32 Pin  | Connection Type      |\n| -------------------------- | ---------- | -------------------- |\n| DHT22 Sensor               | GPIO16     | Digital              |\n| Soil Moisture              | GPIO35     | Analog               |\n| Rain Detector              | GPIO18     | Digital              |\n| Relay Control              | GPIO17     | Digital Output       |\n| Water Pump 12V             | Relay      | Switched Load        |\n| OLED SDA                   | GPIO21     | I2C                  |\n| OLED SCL                   | GPIO22     | I2C                  |\n| Soil Temperature (DS18B20) | GPIO23     | OneWire              |\n| SIM7670C GSM RX            | GPIO25     | UART                 |\n| SIM7670C GSM TX            | GPIO26     | UART                 |\n| Water Level                | GPIO34     | Analog               |\n| Power Supply Module        | Breadboard | VCC/GND Distribution |\n\n## Wiring Diagram\n\n![Wiring Schematic](assets/Wiring_ESP32.png)\n\n_Complete schematic showing ESP32 connections to sensors (DHT22, soil moisture, rain detector, soil temperature probe), actuators (relay-controlled water pump), display (OLED), SIM7670C GSM module, and power distribution system._\n\n## System Features\n\n### Environmental Monitoring\n\n- Real-time temperature and humidity measurement\n- Soil moisture level tracking with capacitive sensor\n- Weather monitoring with rain detection\n- Soil temperature profiling with waterproof probe\n- Water reservoir level monitoring\n\n### Automated Control\n\n- Smart irrigation based on soil moisture thresholds\n- Temperature-compensated watering schedules\n- Rain detection with automatic irrigation override\n- Pump dry-run protection with water level sensing\n- Manual override capabilities via web interface\n\n### Data \u0026 Connectivity\n\n- Local OLED display for essential system status\n- 4G LTE communication via SIM7670C for remote installations\n- MQTT real-time communication with HiveMQ Cloud\n- Cloud database integration with Supabase PostgreSQL\n- RESTful API for third-party integrations\n\n### User Interface\n\n- Modern responsive web dashboard built with Next.js\n- Real-time data visualization with Recharts\n- Historical data analysis and trends\n- Remote pump control via MQTT commands\n- Mobile-friendly interface design\n- System alerts and notifications\n\n## 🔌 MQTT Communication Details\n\n### **ESP32 Device Communication**\n\n```cpp\n// MQTT Topics Used by ESP32\n#define SENSOR_TOPIC \"sf/esp32-01/sensor\"      // Publishes sensor data\n#define RELAY_TOPIC \"sf/esp32-01/relay\"        // Publishes relay status\n#define COMMAND_TOPIC \"sf/devices/relay/command\" // Subscribes to commands\n#define STATUS_TOPIC \"sf/esp32-01/status\"      // Publishes device status\n```\n\n### **Sensor Data Payload** (ESP32 → Backend)\n\n```json\n{\n  \"device_id\": \"esp32-01\",\n  \"timestamp\": \"2024-01-15T10:30:00Z\",\n  \"soil_moisture\": 65.2,\n  \"soil_temperature\": 22.5,\n  \"air_temperature\": 28.3,\n  \"humidity\": 70.1,\n  \"rain_detected\": false,\n  \"water_level\": 85.0\n}\n```\n\n### **Relay Command Payload** (Frontend → ESP32)\n\n```json\n{\n  \"device_id\": \"esp32-01\",\n  \"command\": \"toggle_relay\",\n  \"relay_id\": 1,\n  \"state\": \"on\",\n  \"duration\": 300,\n  \"timestamp\": \"2024-01-15T10:30:00Z\"\n}\n```\n\n## API Endpoints\n\n### **Backend REST API**\n\n#### **General Endpoints**\n\n- `GET /api/health` - API health check with database connection status\n- `GET /api/db-test` - Database connection test\n- `GET /api/info` - API information and endpoint documentation\n\n#### **Sensor Data Endpoints**\n\n- `POST /api/sensor-data` - Create new sensor data entry\n- `GET /api/sensor-data` - Retrieve sensor data with pagination\n- `GET /api/sensor-data/latest` - Get latest sensor readings\n- `GET /api/sensor-data/stats` - Get sensor data statistics\n- `GET /api/sensor-data/health` - Sensor data service health check\n- `GET /api/sensor-data/:id` - Get specific sensor data by ID\n- `DELETE /api/sensor-data/cleanup` - Cleanup old sensor data records\n\n#### **Relay Log Endpoints**\n\n- `POST /api/relay-log` - Create new relay log entry\n- `GET /api/relay-log` - Retrieve relay logs with pagination\n- `GET /api/relay-log/latest` - Get latest relay log entry\n- `GET /api/relay-log/status` - Get current relay status\n- `GET /api/relay-log/stats` - Get relay operation statistics\n- `GET /api/relay-log/duration` - Get relay operation duration metrics\n- `GET /api/relay-log/health` - Relay log service health check\n- `POST /api/relay-log/state-change` - Log relay state change event\n- `GET /api/relay-log/:id` - Get specific relay log by ID\n- `DELETE /api/relay-log/cleanup` - Cleanup old relay log records\n\n#### **MQTT Endpoints**\n\n- `GET /api/mqtt/health` - MQTT connection status and health\n- `POST /api/mqtt/publish` - Publish message to specific MQTT topic\n\n### **Real-time Features**\n\n- MQTT subscription for live sensor data updates\n- WebSocket-like real-time dashboard updates\n- Push notifications for critical alerts\n- Live relay control with immediate feedback\n\n## Project Structure\n\n```\nsmart-farming-iot/\n├── README.md\n├── assets/\n│   └── Wiring_ESP32.png\n├── iot-backend/           # Node.js Backend API\n│   ├── src/\n│   │   ├── controllers/   # API route handlers\n│   │   ├── services/      # Business logic \u0026 MQTT\n│   │   ├── repositories/  # Database operations\n│   │   ├── routes/        # Express routes\n│   │   └── schemas/       # Validation schemas\n│   ├── prisma/           # Database schema \u0026 migrations\n│   └── package.json\n├── iot-dashboard/        # Next.js Frontend\n│   ├── src/\n│   │   ├── app/          # App router pages\n│   │   ├── components/   # React components\n│   │   ├── hooks/        # Custom React hooks\n│   │   └── lib/          # Utilities \u0026 API client\n│   └── package.json\n└── iot-devices/          # ESP32 PlatformIO Project\n    ├── src/              # Main application code\n    ├── include/          # Header files\n    ├── lib/              # Custom libraries\n    └── platformio.ini    # Platform configuration\n```\n\n## Power Requirements\n\n- **ESP32**: 3.3V (via onboard regulator from 5V)\n- **Sensors**: 3.3V-5V depending on module\n- **Relay**: 5V control, switched load up to 250V/10A\n- **Water Pump**: 12V DC (via relay switching)\n- **OLED Display**: 3.3V I2C\n- **SIM7670C GSM**: 3.3V-4.2V via power supply module\n- **Power Supply Module**: Breadboard-mounted voltage regulation\n\n## Getting Started\n\n### **ESP32 Setup**\n\n```bash\n# Install PlatformIO\npip install platformio\n\n# Navigate to device folder\ncd iot-devices\n\n# Upload to ESP32\npio run --target upload\n```\n\n### **Backend Setup**\n\n```bash\ncd iot-backend\nnpm install\nnpm run dev\n```\n\n### **Frontend Setup**\n\n```bash\ncd iot-dashboard\nnpm install\nnpm run dev\n```\n\n## Environment Configuration\n\n### Backend Environment Variables (.env)\n\nThe backend requires several environment variables for database connection, MQTT configuration, and other settings:\n\n```properties\n# Supabase Database Configuration\n# Connect to Supabase via connection pooling\nDATABASE_URL=\"postgresql://[username]:[password]@[host]:[port]/[database]?pgbouncer=true\"\n# Direct connection to the database. Used for migrations\nDIRECT_URL=\"postgresql://[username]:[password]@[host]:[port]/[database]\"\n\n# MQTT Configuration\nMQTT_PORT=8883\nMQTT_PROTOCOL=\"mqtts\"\nMQTT_HOST=\"[your-hivemq-cloud-instance].s1.eu.hivemq.cloud\"\nMQTT_USERNAME=\"[your-mqtt-username]\"\nMQTT_PASSWORD=\"[your-mqtt-password]\"\nENABLE_MQTT=1\n\n# MQTT topic subscriptions (comma-separated lists supported)\n# Wildcards: + for single level, # for multi-level\nMQTT_SENSOR_TOPICS=\"sf/+/sensor\"\nMQTT_RELAY_TOPICS=\"sf/+/relay\"\n```\n\n### Frontend Environment Variables (.env.local)\n\nThe frontend requires configuration for API and MQTT service endpoints:\n\n```bash\nNEXT_PUBLIC_API_BASE_URL='https://[your-backend-api-url]/api'\nNEXT_PUBLIC_MQTT_SERVICE_BASE_URL='https://[your-mqtt-service-url]/api'\n```\n\n### ESP32 Device Configuration (config.h)\n\nCreate a `config.h` file in the `include` directory with the following settings:\n\n```cpp\n#ifndef CONFIG_H\n#define CONFIG_H\n\n// WiFi Configuration\n#define WIFI_SSID \"YourWiFiSSID\"\n#define WIFI_PASSWORD \"YourWiFiPassword\"\n\n// MQTT Configuration\n#define MQTT_SERVER \"ee769d47a04a469da8fe04f0427dfd0b.s1.eu.hivemq.cloud\"\n#define MQTT_PORT 8883\n#define MQTT_USERNAME \"smart_farming_iot\"\n#define MQTT_PASSWORD \"YourMQTTPassword\"\n#define CLIENT_ID \"ESP32_SmartFarming_01\"\n\n// MQTT Topics\n#define SENSOR_TOPIC \"sf/esp32-01/sensor\"\n#define RELAY_TOPIC \"sf/esp32-01/relay\"\n#define COMMAND_TOPIC \"sf/devices/relay/command\"\n#define STATUS_TOPIC \"sf/esp32-01/status\"\n\n// Pin Configuration\n#define DHT_PIN 16\n#define SOIL_MOISTURE_PIN 35\n#define RAIN_SENSOR_PIN 18\n#define RELAY_PIN 17\n#define ONE_WIRE_BUS 23\n#define WATER_LEVEL_PIN 34\n\n#endif // CONFIG_H\n```\n\n## Safety Considerations\n\n- Water pump electrical connections must be properly insulated\n- Use GFCI protection for outdoor electrical connections\n- Ensure proper grounding of all metal components\n- Regular inspection of waterproof seals and connections\n- Emergency manual shutoff should be accessible\n\n## Closing\n\nThis project showcases a complete IoT solution for smart farming, integrating hardware, software, and cloud services. It is designed for scalability and adaptability to various agricultural scenarios. Contributions and improvements are welcome!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fagungferdi%2Fsmart_farming","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fagungferdi%2Fsmart_farming","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fagungferdi%2Fsmart_farming/lists"}