Kode Isi File ai-processing.php

Kode Isi File  ai-processing.php


Bantu buatkan kode isi file ai-processing.php


Berikut adalah kode lengkap untuk file ai-processing.php yang menangani pemrosesan data dengan AI, analisis prediktif, dan generasi rekomendasi cerdas untuk FarmerSmartAI:


```php

<?php

/**

 * ai-processing.php

 * API untuk pemrosesan AI dan analisis data FarmerSmartAI

 * Endpoint: 

 * - POST: /ai-processing.php?action=analyze (analisis data sensor)

 * - GET:  /ai-processing.php?action=recommendations (rekomendasi tanaman)

 * - POST: /ai-processing.php?action=disease_detection (deteksi penyakit)

 */


header('Content-Type: application/json');

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

header('Access-Control-Allow-Headers: Content-Type');


// Handle preflight OPTIONS request

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    exit(0);

}


// Konfigurasi database

$config = [

    'host' => 'localhost',

    'dbname' => 'farmersmartai',

    'username' => 'root',

    'password' => '',

    'charset' => 'utf8mb4'

];


class AIProcessingHandler {

    private $pdo;

    private $response;

    

    // Database tanaman dan kondisi ideal

    private $cropDatabase;

    private $diseaseDatabase;


    public function __construct($config) {

        $this->response = ['status' => 'error', 'message' => ''];

        $this->connectDatabase($config);

        $this->initializeAIDatabases();

    }


    private function connectDatabase($config) {

        try {

            $dsn = "mysql:host={$config['host']};dbname={$config['dbname']};charset={$config['charset']}";

            $this->pdo = new PDO($dsn, $config['username'], $config['password']);

            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch (PDOException $e) {

            $this->response['message'] = "Database connection failed: " . $e->getMessage();

            $this->sendResponse();

        }

    }


    private function initializeAIDatabases() {

        // Database tanaman dan kondisi ideal

        $this->cropDatabase = [

            'paddy' => [ 

                'soilMoisture' => ['min' => 80, 'max' => 90],

                'ph' => ['min' => 5.5, 'max' => 6.5],

                'temperature' => ['min' => 20, 'max' => 35],

                'rainfall' => ['min' => 150, 'max' => 300],

                'baseYield' => 5.0

            ],

            'corn' => [

                'soilMoisture' => ['min' => 60, 'max' => 80],

                'ph' => ['min' => 6.0, 'max' => 6.8],

                'temperature' => ['min' => 18, 'max' => 30],

                'rainfall' => ['min' => 50, 'max' => 150],

                'baseYield' => 7.0

            ],

            'tomato' => [

                'soilMoisture' => ['min' => 60, 'max' => 85],

                'ph' => ['min' => 5.5, 'max' => 6.8],

                'temperature' => ['min' => 15, 'max' => 28],

                'rainfall' => ['min' => 25, 'max' => 75],

                'baseYield' => 20.0

            ],

            'soybean' => [

                'soilMoisture' => ['min' => 50, 'max' => 70],

                'ph' => ['min' => 6.0, 'max' => 7.0],

                'temperature' => ['min' => 20, 'max' => 30],

                'rainfall' => ['min' => 40, 'max' => 100],

                'baseYield' => 2.5

            ]

        ];


        // Database penyakit tanaman

        $this->diseaseDatabase = [

            'paddy' => [

                [

                    'name' => "Blight (Hawar Daun)",

                    'symptoms' => ["brown-spots", "yellowing-leaves", "wilting"],

                    'treatment' => [

                        'organic' => "Gunakan larutan daun nimba dan perbaiki drainase",

                        'chemical' => "Fungisida berbahan aktif tembaga oxychloride"

                    ],

                    'prevention' => [

                        "Gunakan benih unggul tahan penyakit",

                        "Jaga jarak tanam yang cukup",

                        "Rotasi tanaman dengan kacang-kacangan"

                    ]

                ],

                [

                    'name' => "Rice Blast",

                    'symptoms' => ["diamond-spots", "neck-rot", "white-powder"],

                    'treatment' => [

                        'organic' => "Semprotkan ekstrak bawang putih dan minyak nimba",

                        'chemical' => "Fungisida sistemik seperti tricyclazole"

                    ],

                    'prevention' => [

                        "Hindari pemupukan nitrogen berlebihan",

                        "Jaga kelembaban tidak terlalu tinggi",

                        "Sanitasi lahan dari sisa tanaman sakit"

                    ]

                ]

            ],

            'tomato' => [

                [

                    'name' => "Early Blight",

                    'symptoms' => ["dark-spots", "yellowing-leaves", "concentric-rings"],

                    'treatment' => [

                        'organic' => "Semprotkan campuran baking soda dan minyak nimba",

                        'chemical' => "Gunakan fungisida mengandung chlorothalonil"

                    ],

                    'prevention' => [

                        "Rotasi tanaman minimal 3 tahun",

                        "Pangkas daun bagian bawah",

                        "Hindari penyiraman dari atas"

                    ]

                ]

            ]

        ];

    }


    public function handleRequest() {

        try {

            $action = $_GET['action'] ?? '';


            switch ($_SERVER['REQUEST_METHOD']) {

                case 'POST':

                    $this->handlePost($action);

                    break;

                case 'GET':

                    $this->handleGet($action);

                    break;

                default:

                    $this->response['message'] = 'Method not allowed';

                    $this->sendResponse();

            }

        } catch (Exception $e) {

            $this->response['message'] = $e->getMessage();

            $this->sendResponse();

        }

    }


    private function handlePost($action) {

        $input = json_decode(file_get_contents('php://input'), true);

        

        if (!$input) {

            $this->response['message'] = 'Invalid JSON data';

            $this->sendResponse();

        }


        switch ($action) {

            case 'analyze':

                $this->analyzeSensorData($input);

                break;

            case 'disease_detection':

                $this->detectDisease($input);

                break;

            case 'yield_prediction':

                $this->predictYield($input);

                break;

            case 'fertilizer_recommendation':

                $this->recommendFertilization($input);

                break;

            default:

                $this->response['message'] = 'Invalid action specified';

                $this->sendResponse();

        }

    }


    private function handleGet($action) {

        switch ($action) {

            case 'recommendations':

                $this->getCropRecommendations();

                break;

            case 'health_status':

                $this->getFarmHealthStatus();

                break;

            case 'ai_insights':

                $this->getAIIntights();

                break;

            default:

                $this->response['message'] = 'Invalid action specified';

                $this->sendResponse();

        }

    }


    /**

     * ANALISIS DATA SENSOR

     */

    private function analyzeSensorData($input) {

        $sensorId = $input['sensor_id'] ?? null;

        $days = $input['days'] ?? 7;


        if (!$sensorId) {

            $this->response['message'] = 'Sensor ID is required';

            $this->sendResponse();

        }


        // Ambil data sensor terbaru

        $sensorData = $this->getRecentSensorData($sensorId, $days);

        

        if (empty($sensorData)) {

            $this->response['message'] = 'No sensor data found';

            $this->sendResponse();

        }


        // Analisis trend data

        $analysis = $this->analyzeDataTrends($sensorData);

        

        // Deteksi anomali

        $anomalies = $this->detectAnomalies($sensorData);

        

        // Rekomendasi berdasarkan analisis

        $recommendations = $this->generateRecommendations($analysis, $anomalies);


        $this->response['status'] = 'success';

        $this->response['analysis'] = $analysis;

        $this->response['anomalies'] = $anomalies;

        $this->response['recommendations'] = $recommendations;

        $this->response['data_points'] = count($sensorData);

        $this->sendResponse();

    }


    private function getRecentSensorData($sensorId, $days) {

        $sql = "SELECT 

            temperature, humidity, soil_moisture, soil_ph, 

            light_intensity, rainfall, wind_speed, created_at

            FROM sensor_data 

            WHERE sensor_id = :sensor_id 

            AND created_at >= DATE_SUB(NOW(), INTERVAL :days DAY)

            ORDER BY created_at ASC";


        $stmt = $this->pdo->prepare($sql);

        $stmt->execute([':sensor_id' => $sensorId, ':days' => $days]);

        return $stmt->fetchAll(PDO::FETCH_ASSOC);

    }


    private function analyzeDataTrends($sensorData) {

        $analysis = [

            'temperature' => $this->calculateTrend($sensorData, 'temperature'),

            'humidity' => $this->calculateTrend($sensorData, 'humidity'),

            'soil_moisture' => $this->calculateTrend($sensorData, 'soil_moisture'),

            'soil_ph' => $this->calculateTrend($sensorData, 'soil_ph'),

            'overall_health' => 'good'

        ];


        // Hitung skor kesehatan keseluruhan

        $healthScore = $this->calculateHealthScore($analysis);

        $analysis['health_score'] = $healthScore;

        $analysis['overall_health'] = $this->getHealthStatus($healthScore);


        return $analysis;

    }


    private function calculateTrend($data, $field) {

        $values = array_column($data, $field);

        $count = count($values);

        

        if ($count < 2) {

            return ['trend' => 'stable', 'avg' => $values[0] ?? 0];

        }


        $firstHalf = array_slice($values, 0, ceil($count/2));

        $secondHalf = array_slice($values, floor($count/2));

        

        $avgFirst = array_sum($firstHalf) / count($firstHalf);

        $avgSecond = array_sum($secondHalf) / count($secondHalf);

        

        $trend = 'stable';

        $difference = $avgSecond - $avgFirst;

        

        if (abs($difference) > 2) {

            $trend = $difference > 0 ? 'increasing' : 'decreasing';

        }


        return [

            'trend' => $trend,

            'current_avg' => round(array_sum($values) / $count, 2),

            'change_rate' => round($difference, 2)

        ];

    }


    private function calculateHealthScore($analysis) {

        $score = 100;


        // Penalty untuk trend negatif

        foreach ($analysis as $key => $data) {

            if (isset($data['trend']) && $data['trend'] === 'decreasing') {

                $score -= 5;

            }

        }


        // Penalty untuk nilai ekstrem

        if ($analysis['soil_moisture']['current_avg'] < 30 || $analysis['soil_moisture']['current_avg'] > 90) {

            $score -= 15;

        }


        if ($analysis['soil_ph']['current_avg'] < 5.0 || $analysis['soil_ph']['current_avg'] > 8.0) {

            $score -= 20;

        }


        return max(0, $score);

    }


    private function getHealthStatus($score) {

        if ($score >= 80) return 'excellent';

        if ($score >= 60) return 'good';

        if ($score >= 40) return 'fair';

        return 'poor';

    }


    /**

     * DETEKSI ANOMALI

     */

    private function detectAnomalies($sensorData) {

        $anomalies = [];

        

        foreach ($sensorData as $index => $data) {

            $anomaly = $this->checkDataAnomaly($data, $index);

            if ($anomaly) {

                $anomalies[] = $anomaly;

            }

        }


        return $anomalies;

    }


    private function checkDataAnomaly($data, $index) {

        $anomalies = [];


        // Deteksi suhu ekstrem

        if ($data['temperature'] < 10 || $data['temperature'] > 40) {

            $anomalies[] = [

                'type' => 'extreme_temperature',

                'value' => $data['temperature'],

                'timestamp' => $data['created_at'],

                'severity' => 'high',

                'message' => "Suhu ekstrem: {$data['temperature']}°C"

            ];

        }


        // Deteksi kelembaban tanah kritis

        if ($data['soil_moisture'] < 20) {

            $anomalies[] = [

                'type' => 'low_soil_moisture',

                'value' => $data['soil_moisture'],

                'timestamp' => $data['created_at'],

                'severity' => 'medium',

                'message' => "Kelembaban tanah sangat rendah: {$data['soil_moisture']}%"

            ];

        }


        // Deteksi pH tidak optimal

        if ($data['soil_ph'] && ($data['soil_ph'] < 4.5 || $data['soil_ph'] > 8.5)) {

            $anomalies[] = [

                'type' => 'extreme_ph',

                'value' => $data['soil_ph'],

                'timestamp' => $data['created_at'],

                'severity' => 'medium',

                'message' => "pH tanah tidak optimal: {$data['soil_ph']}"

            ];

        }


        return empty($anomalies) ? null : $anomalies;

    }


    /**

     * REKOMENDASI TANAMAN

     */

    private function getCropRecommendations() {

        $sensorId = $_GET['sensor_id'] ?? null;

        

        if (!$sensorId) {

            // Gunakan data rata-rata jika tidak ada sensor spesifik

            $soilData = [

                'moisture' => 65,

                'ph' => 6.2,

                'nitrogen' => 0.18,

                'phosphorus' => 0.12

            ];

            

            $weatherData = [

                'temperature' => 25,

                'rainfall' => 180

            ];

        } else {

            // Ambil data aktual dari sensor

            $recentData = $this->getRecentSensorData($sensorId, 30);

            if (empty($recentData)) {

                $this->response['message'] = 'No sensor data available for recommendations';

                $this->sendResponse();

            }

            

            $soilData = $this->calculateAverageSoilData($recentData);

            $weatherData = $this->calculateAverageWeatherData($recentData);

        }


        $recommendations = $this->recommendCrops($soilData, $weatherData);


        $this->response['status'] = 'success';

        $this->response['soil_data'] = $soilData;

        $this->response['weather_data'] = $weatherData;

        $this->response['recommendations'] = $recommendations;

        $this->sendResponse();

    }


    private function recommendCrops($soilData, $weatherData) {

        $suitableCrops = [];


        foreach ($this->cropDatabase as $crop => $requirements) {

            $soilScore = $this->calculateSoilScore($soilData, $requirements);

            $weatherScore = $this->calculateWeatherScore($weatherData, $requirements);

            $confidence = ($soilScore + $weatherScore) / 2;


            if ($confidence >= 70) {

                $suitableCrops[] = [

                    'name' => $crop,

                    'confidence' => $confidence,

                    'soil_score' => $soilScore,

                    'weather_score' => $weatherScore,

                    'expected_yield' => $this->predictCropYield($crop, $soilData, $weatherData),

                    'planting_season' => $this->getPlantingSeason($crop)

                ];

            }

        }


        // Urutkan berdasarkan confidence tertinggi

        usort($suitableCrops, function($a, $b) {

            return $b['confidence'] <=> $a['confidence'];

        });


        return $suitableCrops;

    }


    private function calculateSoilScore($soilData, $requirements) {

        $score = 0;


        // Penilaian kelembaban tanah (40%)

        if ($soilData['moisture'] >= $requirements['soilMoisture']['min'] && 

            $soilData['moisture'] <= $requirements['soilMoisture']['max']) {

            $score += 40;

        }


        // Penilaian pH tanah (40%)

        if ($soilData['ph'] >= $requirements['ph']['min'] && 

            $soilData['ph'] <= $requirements['ph']['max']) {

            $score += 40;

        }


        // Bonus nutrisi (20%)

        if (isset($soilData['nitrogen']) && $soilData['nitrogen'] > 0.15) $score += 10;

        if (isset($soilData['phosphorus']) && $soilData['phosphorus'] > 0.10) $score += 10;


        return min($score, 100);

    }


    private function calculateWeatherScore($weatherData, $requirements) {

        $score = 0;


        // Penilaian suhu (50%)

        if ($weatherData['temperature'] >= $requirements['temperature']['min'] && 

            $weatherData['temperature'] <= $requirements['temperature']['max']) {

            $score += 50;

        }


        // Penilaian curah hujan (50%)

        if ($weatherData['rainfall'] >= $requirements['rainfall']['min'] && 

            $weatherData['rainfall'] <= $requirements['rainfall']['max']) {

            $score += 50;

        }


        return $score;

    }


    /**

     * PREDIKSI HASIL PANEN

     */

    private function predictYield($input) {

        $cropType = $input['crop_type'] ?? null;

        $sensorId = $input['sensor_id'] ?? null;


        if (!$cropType || !$sensorId) {

            $this->response['message'] = 'Crop type and sensor ID are required';

            $this->sendResponse();

        }


        $recentData = $this->getRecentSensorData($sensorId, 60); // 60 hari terakhir

        $soilData = $this->calculateAverageSoilData($recentData);

        $weatherData = $this->calculateAverageWeatherData($recentData);


        $prediction = $this->predictCropYield($cropType, $soilData, $weatherData);


        $this->response['status'] = 'success';

        $this->response['crop_type'] = $cropType;

        $this->response['predicted_yield'] = $prediction;

        $this->response['confidence'] = 85;

        $this->response['factors'] = [

            'soil_quality' => $this->calculateSoilQuality($soilData),

            'weather_conditions' => $this->calculateWeatherSuitability($weatherData, $cropType)

        ];

        $this->sendResponse();

    }


    private function predictCropYield($cropType, $soilData, $weatherData) {

        if (!isset($this->cropDatabase[$cropType])) {

            return 0;

        }


        $baseYield = $this->cropDatabase[$cropType]['baseYield'];

        $prediction = $baseYield;


        // Faktor koreksi kondisi tanah

        $soilQuality = $this->calculateSoilQuality($soilData);

        $prediction *= $soilQuality;


        // Faktor koreksi cuaca

        $weatherSuitability = $this->calculateWeatherSuitability($weatherData, $cropType);

        $prediction *= $weatherSuitability;


        return round($prediction, 2);

    }


    private function calculateSoilQuality($soilData) {

        $quality = 1.0;


        // Optimal soil moisture: 40-80%

        if ($soilData['moisture'] < 30 || $soilData['moisture'] > 85) {

            $quality *= 0.7;

        }


        // Optimal pH: 5.5-7.0

        if ($soilData['ph'] < 5.0 || $soilData['ph'] > 7.5) {

            $quality *= 0.8;

        }


        return $quality;

    }


    private function calculateWeatherSuitability($weatherData, $cropType) {

        $suitability = 1.0;

        $requirements = $this->cropDatabase[$cropType];


        // Suhu optimal

        $optimalTemp = ($requirements['temperature']['min'] + $requirements['temperature']['max']) / 2;

        $tempDiff = abs($weatherData['temperature'] - $optimalTemp);

        if ($tempDiff > 5) {

            $suitability *= 0.9;

        }


        // Curah hujan optimal

        $optimalRain = ($requirements['rainfall']['min'] + $requirements['rainfall']['max']) / 2;

        $rainDiff = abs($weatherData['rainfall'] - $optimalRain) / $optimalRain;

        if ($rainDiff > 0.5) {

            $suitability *= 0.85;

        }


        return $suitability;

    }


    /**

     * DETEKSI PENYAKIT TANAMAN

     */

    private function detectDisease($input) {

        $cropType = $input['crop_type'] ?? null;

        $symptoms = $input['symptoms'] ?? [];


        if (!$cropType || empty($symptoms)) {

            $this->response['message'] = 'Crop type and symptoms are required';

            $this->sendResponse();

        }


        $detectedDiseases = $this->findMatchingDiseases($cropType, $symptoms);


        $this->response['status'] = 'success';

        $this->response['crop_type'] = $cropType;

        $this->response['detected_diseases'] = $detectedDiseases;

        $this->response['symptoms_provided'] = $symptoms;

        $this->sendResponse();

    }


    private function findMatchingDiseases($cropType, $symptoms) {

        if (!isset($this->diseaseDatabase[$cropType])) {

            return [];

        }


        $matchingDiseases = [];

        $cropDiseases = $this->diseaseDatabase[$cropType];


        foreach ($cropDiseases as $disease) {

            $matchingSymptoms = array_intersect($disease['symptoms'], $symptoms);

            $matchPercentage = (count($matchingSymptoms) / count($disease['symptoms'])) * 100;


            if ($matchPercentage >= 50) { // Minimal 50% gejala cocok

                $matchingDiseases[] = [

                    'disease_name' => $disease['name'],

                    'match_percentage' => round($matchPercentage),

                    'matched_symptoms' => array_values($matchingSymptoms),

                    'treatment' => $disease['treatment'],

                    'prevention' => $disease['prevention']

                ];

            }

        }


        // Urutkan berdasarkan persentase kecocokan tertinggi

        usort($matchingDiseases, function($a, $b) {

            return $b['match_percentage'] <=> $a['match_percentage'];

        });


        return $matchingDiseases;

    }


    /**

     * REKOMENDASI PEMUPUKAN

     */

    private function recommendFertilization($input) {

        $sensorId = $input['sensor_id'] ?? null;

        $cropType = $input['crop_type'] ?? null;


        if (!$sensorId || !$cropType) {

            $this->response['message'] = 'Sensor ID and crop type are required';

            $this->sendResponse();

        }


        $recentData = $this->getRecentSensorData($sensorId, 30);

        $soilData = $this->calculateAverageSoilData($recentData);


        $recommendations = $this->generateFertilizerRecommendations($soilData, $cropType);


        $this->response['status'] = 'success';

        $this->response['crop_type'] = $cropType;

        $this->response['soil_analysis'] = $soilData;

        $this->response['fertilizer_recommendations'] = $recommendations;

        $this->sendResponse();

    }


    private function generateFertilizerRecommendations($soilData, $cropType) {

        $recommendations = [];


        // Rekomendasi berdasarkan kebutuhan tanaman dan kondisi tanah

        $cropNeeds = $this->getCropNutrientNeeds($cropType);


        // Nitrogen

        if ($soilData['nitrogen'] < $cropNeeds['nitrogen']) {

            $deficiency = $cropNeeds['nitrogen'] - $soilData['nitrogen'];

            $recommendations[] = [

                'nutrient' => 'Nitrogen',

                'deficiency_level' => round($deficiency, 3),

                'recommendation' => "Aplikasi Urea: " . round($deficiency * 200, 2) . " kg/hektar",

                'schedule' => "2 minggu sebelum tanam dan 4 minggu setelah tanam",

                'urgency' => $deficiency > 0.1 ? 'high' : 'medium'

            ];

        }


        // Fosfor

        if ($soilData['phosphorus'] < $cropNeeds['phosphorus']) {

            $deficiency = $cropNeeds['phosphorus'] - $soilData['phosphorus'];

            $recommendations[] = [

                'nutrient' => 'Phosphorus',

                'deficiency_level' => round($deficiency, 3),

                'recommendation' => "Aplikasi SP-36: " . round($deficiency * 150, 2) . " kg/hektar",

                'schedule' => "Saat tanam sebagai pupuk dasar",

                'urgency' => $deficiency > 0.08 ? 'high' : 'medium'

            ];

        }


        // pH adjustment

        if ($soilData['ph'] < 5.5) {

            $recommendations[] = [

                'nutrient' => 'pH Adjustment',

                'deficiency_level' => 5.5 - $soilData['ph'],

                'recommendation' => "Aplikasi Kapur Pertanian: 2-4 ton/hektar",

                'schedule' => "2-4 minggu sebelum tanam",

                'urgency' => 'medium'

            ];

        } elseif ($soilData['ph'] > 7.5) {

            $recommendations[] = [

                'nutrient' => 'pH Adjustment',

                'deficiency_level' => $soilData['ph'] - 7.5,

                'recommendation' => "Aplikasi Belerang: 1-2 ton/hektar",

                'schedule' => "2-4 minggu sebelum tanam",

                'urgency' => 'medium'

            ];

        }


        return $recommendations;

    }


    private function getCropNutrientNeeds($cropType) {

        $needs = [

            'paddy' => ['nitrogen' => 0.25, 'phosphorus' => 0.18],

            'corn' => ['nitrogen' => 0.30, 'phosphorus' => 0.20],

            'tomato' => ['nitrogen' => 0.35, 'phosphorus' => 0.25],

            'soybean' => ['nitrogen' => 0.20, 'phosphorus' => 0.15]

        ];


        return $needs[$cropType] ?? ['nitrogen' => 0.25, 'phosphorus' => 0.18];

    }


    /**

     * INSIGHTS DAN HEALTH STATUS

     */

    private function getFarmHealthStatus() {

        $sensorId = $_GET['sensor_id'] ?? null;

        

        if (!$sensorId) {

            $this->response['message'] = 'Sensor ID is required';

            $this->sendResponse();

        }


        $recentData = $this->getRecentSensorData($sensorId, 7);

        $analysis = $this->analyzeDataTrends($recentData);

        $anomalies = $this->detectAnomalies($recentData);


        $healthStatus = [

            'overall_score' => $analysis['health_score'],

            'status' => $analysis['overall_health'],

            'trends' => $analysis,

            'alerts' => count($anomalies),

            'critical_alerts' => array_filter($anomalies, function($anomaly) {

                return $anomaly['severity'] === 'high';

            })

        ];


        $this->response['status'] = 'success';

        $this->response['health_status'] = $healthStatus;

        $this->sendResponse();

    }


    private function getAIIntights() {

        $sensorId = $_GET['sensor_id'] ?? null;

        

        if (!$sensorId) {

            $this->response['message'] = 'Sensor ID is required';

            $this->sendResponse();

        }


        $recentData = $this->getRecentSensorData($sensorId, 30);

        $analysis = $this->analyzeDataTrends($recentData);


        $insights = $this->generateAIInsights($analysis, $recentData);


        $this->response['status'] = 'success';

        $this->response['ai_insights'] = $insights;

        $this->sendResponse();

    }


    private function generateAIInsights($analysis, $sensorData) {

        $insights = [];


        // Insight suhu

        if ($analysis['temperature']['trend'] === 'increasing') {

            $insights[] = [

                'type' => 'temperature_trend',

                'message' => "Suhu menunjukkan trend meningkat, pertimbangkan tanaman yang toleran panas",

                'impact' => 'medium',

                'suggestion' => "Monitor suhu harian dan siapkan sistem penyiraman tambahan"

            ];

        }


        // Insight kelembaban tanah

        if ($analysis['soil_moisture']['current_avg'] < 40) {

            $insights[] = [

                'type' => 'low_moisture',

                'message' => "Kelembaban tanah berada di level rendah",

                'impact' => 'high',

                'suggestion' => "Tingkatkan frekuensi penyiraman atau pertimbangkan sistem irigasi tetes"

            ];

        }


        // Insight pH

        if ($analysis['soil_ph']['current_avg'] < 5.5) {

            $insights[] = [

                'type' => 'acidic_soil',

                'message' => "Tanah terlalu asam untuk kebanyakan tanaman",

                'impact' => 'high',

                'suggestion' => "Aplikasi kapur pertanian untuk menaikkan pH tanah"

            ];

        }


        return $insights;

    }


    /**

     * HELPER FUNCTIONS

     */

    private function calculateAverageSoilData($sensorData) {

        $total = count($sensorData);

        $averages = [

            'moisture' => 0,

            'ph' => 0,

            'nitrogen' => 0.15, // Default value

            'phosphorus' => 0.10 // Default value

        ];


        foreach ($sensorData as $data) {

            $averages['moisture'] += $data['soil_moisture'];

            $averages['ph'] += $data['soil_ph'] ?? 6.5;

        }


        $averages['moisture'] = round($averages['moisture'] / $total, 2);

        $averages['ph'] = round($averages['ph'] / $total, 2);


        return $averages;

    }


    private function calculateAverageWeatherData($sensorData) {

        $total = count($sensorData);

        $averages = [

            'temperature' => 0,

            'rainfall' => 0

        ];


        foreach ($sensorData as $data) {

            $averages['temperature'] += $data['temperature'];

            $averages['rainfall'] += $data['rainfall'] ?? 0;

        }


        $averages['temperature'] = round($averages['temperature'] / $total, 2);

        $averages['rainfall'] = round($averages['rainfall'] / $total, 2);


        return $averages;

    }


    private function generateRecommendations($analysis, $anomalies) {

        $recommendations = [];


        // Rekomendasi berdasarkan health score

        if ($analysis['health_score'] < 60) {

            $recommendations[] = [

                'type' => 'general_improvement',

                'priority' => 'high',

                'action' => 'Perbaiki kondisi tanah dan optimalkan penyiraman',

                'reason' => 'Skor kesehatan lahan rendah'

            ];

        }


        // Rekomendasi berdasarkan anomali

        foreach ($anomalies as $anomaly) {

            if ($anomaly['type'] === 'low_soil_moisture') {

                $recommendations[] = [

                    'type' => 'irrigation',

                    'priority' => 'high',

                    'action' => 'Tingkatkan frekuensi penyiraman',

                    'reason' => 'Kelembaban tanah kritis'

                ];

            }

        }


        return $recommendations;

    }


    private function getPlantingSeason($crop) {

        $seasons = [

            'paddy' => 'Musim Hujan (Oktober-Maret)',

            'corn' => 'Musim Kemarau (April-September)',

            'tomato' => 'Sepanjang Tahun (dengan pengairan memadai)',

            'soybean' => 'Musim Kemarau (April-September)'

        ];


        return $seasons[$crop] ?? 'Tergantung kondisi lokal';

    }


    private function sendResponse() {

        echo json_encode($this->response, JSON_PRETTY_PRINT);

        exit;

    }

}


// Initialize and handle request

try {

    $handler = new AIProcessingHandler($config);

    $handler->handleRequest();

} catch (Exception $e) {

    $response = [

        'status' => 'error',

        'message' => 'Server error: ' . $e->getMessage()

    ];

    echo json_encode($response, JSON_PRETTY_PRINT);

}

?>

```


Cara Penggunaan API AI Processing:


1. Analisis Data Sensor (POST):


```javascript

// Contoh request untuk analisis data sensor

fetch('/ai-processing.php?action=analyze', {

    method: 'POST',

    headers: {

        'Content-Type': 'application/json',

    },

    body: JSON.stringify({

        sensor_id: 'sensor_001',

        days: 7

    })

})

.then(response => response.json())

.then(data => console.log(data));

```


2. Rekomendasi Tanaman (GET):


```javascript

// Contoh request untuk rekomendasi tanaman

fetch('/ai-processing.php?action=recommendations&sensor_id=sensor_001')

.then(response => response.json())

.then(data => console.log(data));

```


3. Deteksi Penyakit (POST):


```javascript

// Contoh request untuk deteksi penyakit

fetch('/ai-processing.php?action=disease_detection', {

    method: 'POST',

    headers: {

        'Content-Type': 'application/json',

    },

    body: JSON.stringify({

        crop_type: 'tomato',

        symptoms: ['dark-spots', 'yellowing-leaves']

    })

})

.then(response => response.json())

.then(data => console.log(data));

```


4. Prediksi Hasil Panen (POST):


```javascript

// Contoh request untuk prediksi hasil

fetch('/ai-processing.php?action=yield_prediction', {

    method: 'POST',

    headers: {

        'Content-Type': 'application/json',

    },

    body: JSON.stringify({

        crop_type: 'paddy',

        sensor_id: 'sensor_001'

    })

})

.then(response => response.json())

.then(data => console.log(data));

```


5. Rekomendasi Pemupukan (POST):


```javascript

// Contoh request untuk rekomendasi pupuk

fetch('/ai-processing.php?action=fertilizer_recommendation', {

    method: 'POST',

    headers: {

        'Content-Type': 'application/json',

    },

    body: JSON.stringify({

        crop_type: 'corn',

        sensor_id: 'sensor_001'

    })

})

.then(response => response.json())

.then(data => console.log(data));

```


Contoh Response AI Processing:


Response Rekomendasi Tanaman:


```json

{

    "status": "success",

    "soil_data": {

        "moisture": 65.5,

        "ph": 6.2,

        "nitrogen": 0.15,

        "phosphorus": 0.10

    },

    "weather_data": {

        "temperature": 25.5,

        "rainfall": 180.2

    },

    "recommendations": [

        {

            "name": "paddy",

            "confidence": 85,

            "soil_score": 90,

            "weather_score": 80,

            "expected_yield": 4.8,

            "planting_season": "Musim Hujan (Oktober-Maret)"

        },

        {

            "name": "tomato",

            "confidence": 75,

            "soil_score": 70,

            "weather_score": 80,

            "expected_yield": 18.5,

            "planting_season": "Sepanjang Tahun (dengan pengairan memadai)"

        }

    ]

}

```


Response Deteksi Penyakit:


```json

{

    "status": "success",

    "crop_type": "tomato",

    "detected_diseases": [

        {

            "disease_name": "Early Blight",

            "match_percentage": 85,

            "matched_symptoms": ["dark-spots", "yellowing-leaves"],

            "treatment": {

                "organic": "Semprotkan campuran baking soda dan minyak nimba",

                "chemical": "Gunakan fungisida mengandung chlorothalonil"

            },

            "prevention": [

                "Rotasi tanaman minimal 3 tahun",

                "Pangkas daun bagian bawah",

                "Hindari penyiraman dari atas"

            ]

        }

    ],

    "symptoms_provided": ["dark-spots", "yellowing-leaves"]

}

```


Fitur AI yang Tersedia:


1. Analisis Trend Data - Monitor perubahan kondisi lahan

2. Deteksi Anomali - Identifikasi kondisi abnormal

3. Rekomendasi Tanaman - Saran tanaman berdasarkan kondisi

4. Prediksi Hasil Panen - Estimasi produktivitas

5. Deteksi Penyakit - Diagnosis penyakit berdasarkan gejala

6. Rekomendasi Pemupukan - Saran pupuk berdasarkan analisis tanah

7. Health Scoring - Skor kesehatan lahan secara keseluruhan

8. AI Insights - Wawasan cerdas untuk pengambilan keputusan


File ini siap digunakan untuk memberikan kecerdasan buatan yang powerful untuk aplikasi FarmerSmartAI! 🧠🌱



Bersambung ke:  





Comments

Popular posts from this blog

Aplikasi FarmerSmartAI:

icon-generator.html