# Stations Trouble Shooting Monitor (STS)

**Stations Trouble Shooting Monitor (STS)** is a high-performance PHP/MySQL monitoring and troubleshooting web application built specifically for Wireless Internet Service Providers (WISPs) and Network Operations Centers (NOCs).

STS connects to multiple MikroTik Access Points, retrieves connected wireless clients from their Wireless Registration Tables, evaluates link quality using a multi-factor wireless health engine, ranks the worst/problematic clients first, and presents them on a single, centralized dashboard refreshed every ~1 second.

---

## 1. System Architecture

STS operates on a **strict two-stage architecture**:

```
 ┌──────────────────────┐   ┌──────────────────────┐   ┌──────────────────────┐
 │  MikroTik AP 1 (Reg) │   │  MikroTik AP 2 (Reg) │   │  MikroTik AP N (Reg) │
 └──────────┬───────────┘   └──────────┬───────────┘   └──────────┬───────────┘
            │                          │                          │
            └───────────┬──────────────┴──────────────┬───────────┘
                        │ Concurrent Non-Blocking     │ (1.5s per-AP timeout)
                        ▼                             ▼
                     ┌──────────────────────────────────┐
                     │ STAGE 1: Server-Side Poller      │
                     │ (bin/poller.php CLI / daemon)    │
                     └─────────────────┬────────────────┘
                                       │ (Upsert current snapshot ONLY)
                                       ▼
                     ┌──────────────────────────────────┐
                     │ MySQL Database                   │
                     │ (aps, current_clients, settings) │
                     └─────────────────┬────────────────┘
                                       │ (Read current worst clients)
                                       ▼
                     ┌──────────────────────────────────┐
                     │ STAGE 2: Read-Only Web API       │
                     │ (/api/clients.php)               │
                     └─────────────────┬────────────────┘
                                       │ (JSON data read every ~1s)
                                       ▼
                     ┌──────────────────────────────────┐
                     │ STS Central NOC Dashboard        │
                     │ (index.php + Vanilla JS UI)      │
                     └──────────────────────────────────┘
```

- **Stage 1 (Server-side Polling)**: `bin/poller.php` runs continuously in the background on the server. It connects to enabled MikroTik APs via RouterOS API socket with non-blocking 1.5s timeouts, normalizes metrics, calculates health scores, and updates `current_clients` in MySQL. **The browser NEVER connects to MikroTik APs or triggers polling.**
- **Stage 2 (Web Presentation)**: The dashboard reads current state from `current_clients` via read-only API `/api/clients.php` and updates the NOC display approximately every 1 second.

---

## 2. Directory Structure

```
sts/
├── config/
│   ├── database.php             # Database credentials & PDO wrapper
│   ├── thresholds.php           # Default wireless health thresholds & weights
│   └── .installed               # Automatic security lockfile created post-setup
├── includes/
│   ├── RouterOsApi.php          # Native PHP RouterOS API socket client (v6 MD5 & v7 plain)
│   ├── HealthEvaluator.php      # Multi-factor Wireless Health Evaluation Engine
│   └── ApPoller.php             # Stage 1 AP Poller & current_clients engine
├── bin/
│   └── poller.php               # Stage 1 CLI Poller Daemon script
├── api/
│   ├── clients.php              # Stage 2 read-only data API (worst clients first)
│   ├── aps.php                  # AP CRUD management endpoint
│   └── thresholds.php           # Wireless threshold configuration endpoint
├── sql/
│   └── install.sql              # Complete MySQL installation schema
├── css/
│   └── style.css                # ISP/NOC dark theme stylesheet
├── js/
│   └── app.js                   # Stage 2 dashboard frontend application script
├── tests/
│   └── test_health_evaluator.php# Health Evaluator unit test script
├── index.php                    # STS Central Trouble Shooting Dashboard
├── aps.php                      # AP Management & Threshold Tuning UI
├── setup.php                    # Web-based database installer with security lock
└── README.md                    # System documentation
```

---

## 3. Installation Guide

### Deployment Location
Deploy project files to your web root:
`/var/www/html/sts`

### Step 1: Database Setup & Schema Installation
You can initialize the database using either the Web Installer or MySQL CLI:

#### Option A: Web Installer (`setup.php`)
1. Open `https://sts.takchgroup.com/setup.php` in your browser.
2. Enter your MySQL host, port, database name, and credentials.
3. Click **Install Database Schema**.
4. The installer creates the schema and automatically generates the security lockfile (`config/.installed`). Once locked, `setup.php` will refuse further access.

#### Option B: MySQL CLI
```bash
mysql -u root -p < /var/www/html/sts/sql/install.sql
```

---

## 4. Stage 1 Poller Execution (CLI Daemon)

The Stage 1 Poller must run continuously on the server to keep `current_clients` populated in real time.

### Single-Pass Test
```bash
php /var/www/html/sts/bin/poller.php --once
```

### Continuous CLI Runner
```bash
php /var/www/html/sts/bin/poller.php
```

### Running as a Background Daemon (systemd service)
Create `/etc/systemd/system/sts-poller.service`:

```ini
[Unit]
Description=STS MikroTik AP Stage 1 Poller Daemon
After=network.target mysql.service

[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/html/sts
ExecStart=/usr/bin/php /var/www/html/sts/bin/poller.php
Restart=always
RestartSec=2

[Install]
WantedBy=multi-user.target
```

Enable and start the service:
```bash
sudo systemctl daemon-reload
sudo systemctl enable sts-poller
sudo systemctl start sts-poller
sudo systemctl status sts-poller
```

---

## 5. Wireless Health Evaluation Algorithm

The Wireless Health Engine evaluates clients using **multi-factor indicators**:

1. **Primary Indicator**: Signal Strength (45% default weight)
2. **Corroborating Indicators**:
   - SNR (Signal-to-Noise Ratio) (30% default weight)
   - TX/RX CCQ (Wireless Frame Delivery Efficiency) (25% default weight)

### Corroboration & Rule Override Logic
- **Rule A (Severe Signal Weakness)**: Signal $\le -84\text{ dBm}$ hard-caps health score to $\le 35$ (`CRITICAL`), regardless of SNR/CCQ.
- **Rule B (Severe Noise Floor / Low SNR)**: SNR $\le 10\text{ dB}$ hard-caps health score to $\le 35$ (`CRITICAL`) even if Signal is $-60\text{ dBm}$.
- **Rule C (Severe Frame Retries)**: CCQ $\le 35\%$ hard-caps health score to $\le 35$ (`CRITICAL`).
- **Rule D (Compounding Risk)**: Multiple moderately degraded metrics (e.g. Signal $-75\text{ dBm}$ + SNR $18\text{ dB}$ + CCQ $68\%$) trigger a compounding severity penalty.

### Severity Classification Levels
- **CRITICAL** (Red): Score $< 40$ or severe single metric failure.
- **BAD** (Orange): Score $40 - 59$ or bad metric.
- **WARNING** (Yellow): Score $60 - 74$ or moderate drop.
- **HEALTHY** (Green): Score $75 - 100$.

---

## 6. Security Features

- **No Public Passwords**: MikroTik credentials and database passwords remain strictly server-side. Passwords are never sent to the browser in API responses.
- **Setup Locking**: `setup.php` creates `config/.installed` post-setup. Unauthenticated web users cannot re-trigger installation or modify database schema.
- **Prepared Statements**: All database operations use PDO prepared statements to protect against SQL injection.
- **Read-Only Browser API**: The web browser communicates ONLY with `/api/clients.php` and can never initiate raw network connections to network hardware.
