Skip to content

RF QUANTUM SCYTHE – WebSocket Server Documentation

# RF QUANTUM SCYTHE - WebSocket Server Documentation

## Overview

The RF QUANTUM SCYTHE WebSocket server provides real-time communication between the backend analytics engine and frontend visualization interfaces. It supports authentication, channel-based subscriptions, and bidirectional messaging for live RF signal analysis and visualization updates.

## 🚀 Quick Start

### Starting the WebSocket Server

**For page2.html compatibility (Recommended):**
```bash
# Use the provided startup script
./start_websocket_for_page2.sh

# Or manually:
source /home/bgilbert/rf_quantum_env/bin/activate
cd /home/bgilbert/RF_QUANTUM_SCYTHE_GITHUB
python websocket_server.py --port 5001 --debug
```

**For general use:**
```bash
python websocket_server.py --port 5800 --debug
```

### Connecting from page2.html

1. Open page2.html in your browser
2. Navigate to the "WebSocket API" section
3. Ensure URL is set to: `ws://localhost:5001/ws`
4. Click "Connect"
5. Use "Authenticate" for secured endpoints (if --auth flag is used)

## 📡 WebSocket Endpoints

### Primary Endpoints

| Endpoint | Purpose | Description |
|----------|---------|-------------|
| `/ws` | General WebSocket | Main connection for API testing and general communication |
| `/ws/geo` | Geolocation Data | Specialized endpoint for RF signal location and mapping data |

### REST API Endpoints

| Endpoint | Method | Purpose |
|----------|---------|----------|
| `/` | GET | Server info and documentation links |
| `/api/status` | GET | Server status, uptime, and connection statistics |
| `/docs` | GET | FastAPI auto-generated documentation |

## 🔐 Authentication System

### Authentication Flow

1. **Connect** to WebSocket endpoint
2. **Send authentication message**:
   ```json
   {
     "type": "auth", 
     "api_key": "your_api_key_here"
   }
   ```
3. **Receive confirmation**:
   ```json
   {
     "type": "system",
     "subtype": "auth_success", 
     "message": "Authentication successful"
   }
   ```

### Demo Token
For testing purposes, use: `rf_quantum_scythe_demo_token`

## 📢 Message Types

### Client → Server Messages

#### Authentication
```json
{
  "type": "auth",
  "api_key": "rf_quantum_scythe_demo_token"
}
```

#### Subscription
```json
{
  "type": "subscribe",
  "topics": ["signal_detected", "packet_detected", "signal_classification_updated"]
}
```

#### Custom Messages
```json
{
  "type": "custom",
  "data": {
    "command": "get_signal_data",
    "parameters": {"frequency_range": "2.4-2.5GHz"}
  }
}
```

### Server → Client Messages

#### System Messages
```json
{
  "type": "system",
  "subtype": "auth_required|auth_success|auth_failure|error",
  "message": "Human-readable message",
  "timestamp": 1691668800.123
}
```

#### Real-time Updates
```json
{
  "type": "signal_update",
  "data": {
    "frequency": 2.4e9,
    "power": -45.2,
    "location": {"lat": 40.7589, "lng": -73.9851},
    "classification": "WiFi_802.11n"
  },
  "timestamp": 1691668800.456
}
```

#### Location Updates
```json
{
  "type": "location_update", 
  "data": [
    {
      "id": "sdr_001",
      "lat": 40.7589,
      "lng": -73.9851,
      "altitude": 10.5,
      "status": "active"
    }
  ]
}
```

## 📊 Subscription Topics

### Available Topics

| Topic | Description | Data Type |
|-------|-------------|-----------|
| `signal_detected` | New RF signal detection | Signal metadata and characteristics |
| `packet_detected` | Network packet analysis | Packet headers and classification |
| `signal_classification_updated` | ML classification results | AI/ML analysis results |
| `location_update` | SDR location changes | GPS coordinates and status |
| `alert_triggered` | Security alerts | Threat detection notifications |
| `spectrum_data` | Real-time spectrum | FFT and waterfall data |

### Subscribing to Topics
```json
{
  "type": "subscribe",
  "topics": ["signal_detected", "alert_triggered"]
}
```

## 🛠 Configuration Options

### Command Line Arguments

```bash
python websocket_server.py [OPTIONS]

Options:
  --port PORT     Port to run server on (default: 5800)
  --debug         Enable debug mode with auto-reload
  --auth          Require token authentication for all connections
  -h, --help      Show help message
```

### Port Configuration

- **Port 5001**: Recommended for page2.html compatibility
- **Port 5800**: Default port for general use
- **Port 8000**: Alternative port (avoid conflicts with other services)

## 📈 Monitoring & Statistics

### Connection Statistics
Access real-time statistics at: `http://localhost:5001/api/status`

```json
{
  "status": "online",
  "uptime": 3600.45,
  "connected_clients": {
    "total": 3,
    "channels": {
      "general": 2,
      "geo": 1,
      "admin": 0
    }
  },
  "signals_count": 1247,
  "locations_count": 5
}
```

### Logging
- **Console**: Real-time connection and message logs
- **File**: `logs/websocket_server.log` (auto-created)
- **Level**: INFO (standard), DEBUG (with --debug flag)

## 🔧 Integration Examples

### JavaScript Client (page2.html)
```javascript
const ws = new WebSocket('ws://localhost:5001/ws');

ws.onopen = () => {
    console.log('Connected to WebSocket');
    // Authenticate
    ws.send(JSON.stringify({
        type: 'auth',
        api_key: 'rf_quantum_scythe_demo_token'
    }));
};

ws.onmessage = (event) => {
    const message = JSON.parse(event.data);
    console.log('Received:', message);
};
```

### Python Client
```python
import asyncio
import websockets
import json

async def client():
    uri = "ws://localhost:5001/ws"
    async with websockets.connect(uri) as websocket:
        # Authenticate
        auth_msg = {"type": "auth", "api_key": "rf_quantum_scythe_demo_token"}
        await websocket.send(json.dumps(auth_msg))
        
        # Subscribe to topics
        sub_msg = {"type": "subscribe", "topics": ["signal_detected"]}
        await websocket.send(json.dumps(sub_msg))
        
        # Listen for messages
        async for message in websocket:
            data = json.loads(message)
            print(f"Received: {data}")

asyncio.run(client())
```

## 🚨 Troubleshooting

### Common Issues

1. **Connection Refused**
   - Ensure WebSocket server is running
   - Check port number (5001 for page2.html)
   - Verify firewall settings

2. **Authentication Failures** 
   - Use correct demo token: `rf_quantum_scythe_demo_token`
   - Ensure --auth flag is set if required
   - Check message format

3. **No Data Received**
   - Subscribe to relevant topics first
   - Check if simulation is enabled
   - Verify channel subscription

4. **Port Already in Use**
   ```bash
   # Kill existing process
   sudo lsof -ti:5001 | xargs kill -9
   
   # Or use different port
   python websocket_server.py --port 5002
   ```

### Debug Mode
Run with `--debug` for detailed logging:
```bash
python websocket_server.py --port 5001 --debug
```

## 📝 Development Notes

### Server Features
- ✅ FastAPI-based WebSocket server
- ✅ Multi-channel support (general, geo, admin)
- ✅ Token-based authentication
- ✅ CORS enabled for cross-origin requests
- ✅ Connection management and cleanup
- ✅ Real-time broadcasting
- ✅ Error handling and recovery

### Future Enhancements
- [ ] Database integration for persistent data
- [ ] Advanced authentication (JWT tokens)
- [ ] Rate limiting and connection throttling
- [ ] SSL/TLS support for production
- [ ] Message queuing for offline clients

---

## 📞 Support

For issues or questions:
1. Check the console/log output for error messages
2. Test connection with the provided test scripts
3. Verify virtual environment is activated
4. Ensure all dependencies are installed

**Last Updated**: August 10, 2025  
**Version**: 1.0.0  
**Compatible with**: page2.html, RF QUANTUM SCYTHE API Tester

Leave a Reply

Your email address will not be published. Required fields are marked *