# OpenSky Network API Integration - ANATL Portal

## 🎯 Overview

Integrasi **OpenSky Network API** untuk menampilkan real-time flight tracking data. OpenSky adalah platform non-profit yang mengumpulkan data ADS-B dari volunteer receivers di seluruh dunia.

### **Keuntungan:**
- ✅ **100% Free** - Tanpa API key diperlukan
- ✅ **Real-time Data** - Update setiap 10 detik
- ✅ **Unlimited** - Tidak ada rate limit untuk free tier
- ✅ **Global Coverage** - Data dari seluruh dunia
- ✅ **Reliable** - Non-profit, stabil sejak 2013

### **Kekurangan:**
- Data hanya untuk aircraft dengan ADS-B transponder
- Update delay 10+ detik
- Limited historical data (1 week free)

---

## 📡 **Cara Kerja:**

```
OpenSky Network (Volunteer ADS-B Receivers)
                    ↓
            OpenSky API Server
                    ↓
        ANATL Portal (PHP)
                    ↓
        Live Flights Display (Browser)
```

---

## 🔧 **Implementasi:**

### **File-file yang Ditambahkan:**

1. **`includes/opensky-api.php`** - PHP SDK wrapper untuk OpenSky API
   - Method: `getStateVectors()` - Ambil flights dalam bounding box
   - Method: `getFlightsBycallsign()` - Cari flights by callsign
   - Method: `getTrack()` - Ambil track detail pesawat
   - Utility: `getBoundingBox()` - Generate bounding box dari koordinat

2. **`live-flights.php`** - Halaman display live flights
   - Tampil real-time flights dalam radius Dili (220km)
   - Update otomatis via refresh page
   - Show altitude, velocity, track data

### **Dili Airport Coordinates:**
```
Latitude:  -8.5211
Longitude: 125.0329
```

---

## 📊 **API Endpoints yang Digunakan:**

### **1. Get State Vectors (Flights in Bounding Box)**
```
GET https://api.opensky-network.org/api/states/all
Parameters:
  - lamin: min latitude
  - lomin: min longitude
  - lamax: max latitude
  - lomax: max longitude
  - begin: timestamp (optional, untuk range query)

Response:
{
  "time": 1234567890,
  "states": [
    [
      "icao24",          // aircraft ICAO address
      "callsign",        // flight callsign
      "origin_country",  // origin country
      "time_position",   // timestamp of position
      "last_contact",    // timestamp last contact
      "longitude",       // longitude
      "latitude",        // latitude
      "altitude",        // altitude in meters
      "on_ground",       // boolean
      "velocity",        // velocity m/s
      "true_track",      // heading in degrees
      "vertical_rate",   // climb rate m/s
      "sensors",         // sensor IDs
      "geo_altitude",    // geometric altitude
      "squawk",          // transponder squawk
      "spi",             // special position indication
      "position_source", // source of position
      "category"         // aircraft category
    ]
  ]
}
```

### **2. Get Flights by Callsign**
```
GET https://api.opensky-network.org/api/flights/search
Parameters:
  - callsigns: comma-separated callsigns
  - begin: begin timestamp
  - end: end timestamp

Response: Array of flights matching criteria
```

### **3. Get Track (Full Trajectory)**
```
GET https://api.opensky-network.org/api/tracks/all
Parameters:
  - icao24: aircraft ICAO address
  - time: timestamp

Response: Full waypoint track dari aircraft
```

---

## 💻 **Cara Menggunakan di PHP:**

### **Contoh 1: Get Live Flights Near Dili**

```php
<?php
require_once 'includes/opensky-api.php';

$api = new OpenSkyAPI();

// Dili coordinates
$bounds = OpenSkyAPI::getBoundingBox(-8.5211, 125.0329, 2); // 2 degree radius

$data = $api->getStateVectors(
    $bounds['lamin'],
    $bounds['lomin'],
    $bounds['lamax'],
    $bounds['lomax']
);

if ($data && isset($data['states'])) {
    foreach ($data['states'] as $state) {
        $flight = OpenSkyAPI::formatFlight($state);
        echo $flight['callsign'] . " at " . $flight['altitude'] . "m\n";
    }
}
?>
```

### **Contoh 2: Search Flights by Callsign**

```php
<?php
$api = new OpenSkyAPI();

// Cari Garuda Indonesia flights
$flights = $api->getFlightsBycallsign(['GAR*'], time() - 3600);

foreach ($flights as $flight) {
    echo $flight['callsign'] . ": " . $flight['origin'] . " → " . $flight['destination'] . "\n";
}
?>
```

### **Contoh 3: Get Track Detail**

```php
<?php
$api = new OpenSkyAPI();

$track = $api->getTrack('a2d819', time() - 3600);

if ($track) {
    echo "Total waypoints: " . count($track['path']) . "\n";
    foreach ($track['path'] as $point) {
        echo "At " . date('H:i:s', $point['time']) . " - ";
        echo "Altitude: " . $point['altitude'] . "m\n";
    }
}
?>
```

---

## 🌐 **Live Flights Page:**

Akses: `http://localhost:8888/bdr/anatl/live-flights.php`

**Fitur:**
- ✅ Real-time display flights dalam radius Dili
- ✅ Sortir by altitude
- ✅ Show detailed flight info (lat/lon/altitude/velocity/heading)
- ✅ Status on_ground vs flying
- ✅ Refresh untuk update data

---

## 📈 **Data Fields Dijelaskan:**

| Field | Deskripsi | Unit |
|-------|-----------|------|
| **Callsign** | Flight identification (e.g., GA101) | String |
| **ICAO24** | Unique aircraft code | Hex |
| **Latitude** | Aircraft latitude | Degrees |
| **Longitude** | Aircraft longitude | Degrees |
| **Altitude** | Height above sea level | Feet |
| **Velocity** | Speed through air | m/s |
| **Track** | Heading direction | Degrees (0-359) |
| **Vertical Rate** | Climb/descent rate | m/s |
| **On Ground** | Aircraft at airport | Boolean |

---

## ⚠️ **Limitations:**

1. **Coverage**: Hanya aircraft dengan ADS-B transponder aktif
2. **Delay**: Data cache 10 detik
3. **History**: Hanya 1 minggu data gratis
4. **Accuracy**: Tergantung receiver coverage
5. **Update**: Need manual page refresh untuk real-time

---

## 🚀 **Untuk Production:**

Jika ingin real-time updates tanpa refresh:

### **Option 1: JavaScript Polling**
```js
setInterval(() => {
  fetch('/api/live-flights')
    .then(r => r.json())
    .then(data => updateFlightsTable(data));
}, 10000); // Every 10 seconds
```

### **Option 2: WebSocket (Advanced)**
```js
const ws = new WebSocket('wss://api.opensky-network.org/socket.io/?transport=websocket');
ws.onmessage = (event) => {
  updateFlightsTable(JSON.parse(event.data));
};
```

---

## 📚 **Referensi:**

- **Website**: https://opensky-network.org
- **API Docs**: https://openskynetwork.github.io/opensky-api/
- **Status**: https://status.opensky-network.org
- **Twitter**: @OpenSkyNetwork

---

## 🎓 **Use Cases untuk Demo:**

1. **Live FIDS** - Replace sample data dengan real flights
2. **Route Tracking** - Track specific aircraft path
3. **Airport Statistics** - Show arrivals/departures real-time
4. **Flight Search** - Search by callsign/ICAO
5. **Heatmap** - Show aircraft density by altitude

---

## ✅ **Checklist Setup:**

- [x] Download OpenSky SDK
- [x] Create `opensky-api.php` wrapper
- [x] Create `live-flights.php` display page
- [x] Add navigation link in header
- [x] Test with real data
- [x] Document integration

---

**Website ANATL Portal sudah siap dengan live flight tracking! 🛫**
