Skip to content

SourceK78/ws_online

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

WonderSwan Online

This is a project for online communication between WonderSwans.

This project was created using Claude Code. I assume no responsibility for any damages incurred as a result of using this project.

🎯 WonderSwan Online Features

  • βœ… RESTful API - Access via standard HTTP API
  • βœ… Auto-generated Documentation - Swagger UI / ReDoc automatically generated
  • βœ… High Performance - Async processing with uvicorn
  • βœ… Modern Architecture - Type safety and validation
  • βœ… Static File Serving - Centralized HTML/CSS/JS management

πŸ“¦ Installation

Install Dependencies

pip install -r requirements.txt

Or manually install:

pip install fastapi uvicorn websockets pydantic

Hardware Requirements

To communicate serially between the WonderSwan and your PC, you will need one of the following devices:

Note: The Web Serial API requires Chrome, Edge, or Opera (version 89+)

πŸ“ File Structure

ws_online/
β”œβ”€β”€ models.py                  # Data models (Room, ClientInfo, etc.)
β”œβ”€β”€ relay_manager.py           # WebSocket connection and relay management
β”œβ”€β”€ ws_fastapi_server.py       # Main server application
β”œβ”€β”€ requirements.txt           # Python dependencies
β”œβ”€β”€ .gitignore                 # Git exclusions
└── static/
    β”œβ”€β”€ index.html             # Web UI HTML structure
    β”œβ”€β”€ styles.css             # Web UI styling
    └── app.js                 # Web UI logic (Web Serial & room management)

πŸ”„ Recent Updates (Refactored)

The codebase has been refactored for better maintainability:

  • Modular Architecture: Separated concerns into models.py and relay_manager.py
  • Type Safety: Added comprehensive type hints throughout
  • Better Error Handling: Improved exception handling with logging
  • Documentation: Added docstrings to all classes and functions
  • Code Quality: Removed duplicate code and improved structure

πŸš€ Quick Start

1. Start Server

# Default (localhost:8000)
python ws_fastapi_server.py

Expected output:

============================================================
WonderSwan Relay Server with Room Management
============================================================
🌐 HTTP Server: http://0.0.0.0:8000
🌐 Local access: http://localhost:8000

⚠️  Web Serial API requires HTTPS or localhost!
    For LAN access, generate SSL certificate:
    bash setup_https.sh
============================================================
Press Ctrl+C to stop the server
============================================================

2. Access Web UI

Open a Chrome, Edge, or Opera browser and navigate to:

http://localhost:8000

For detailed setup instructions (connecting your WonderSwan, creating/joining rooms), please refer to the Wiki.

3. HTTPS Setup (For LAN Access)

To use Web Serial API over LAN, you need HTTPS:

# Generate self-signed certificate
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes

The server will automatically detect and use key.pem and cert.pem if present.

Then access via:

https://192.168.x.x:8000

Note: Browsers will show a security warning for self-signed certificates. Click "Advanced" β†’ "Proceed to localhost (unsafe)"

πŸ“– API Documentation

After starting FastAPI, you can access auto-generated API documentation:

Swagger UI

http://localhost:8000/docs

ReDoc

http://localhost:8000/redoc

πŸ”§ REST API Examples

Get Room List

curl http://localhost:8000/api/rooms

Response example:

{
  "rooms": [
    {
      "room_id": "abc123",
      "room_name": "Battle Arena 1",
      "host_client": "player1",
      "guest_client": "player2",
      "status": "playing",
      "created_at": "2025-10-13T10:30:00.123456",
      "started_at": "2025-10-13T10:31:00.123456",
      "max_players": 2,
      "current_players": 2,
      "has_password": false,
      "relay_count": 150
    }
  ]
}

Get Connected Clients

curl http://localhost:8000/api/clients

Response example:

{
  "clients": [
    {
      "client_id": "player1",
      "serial_port": "Web-1234",
      "baudrate": 38400,
      "connected_at": "2025-10-13T10:30:00.123456",
      "current_room": "abc123",
      "status": "in_room"
    }
  ]
}

Get Server Statistics

curl http://localhost:8000/api/stats

Response example:

{
  "total_clients": 2,
  "total_rooms": 1,
  "active_matches": 1,
  "total_relays": 150
}

Create a Room

curl -X POST "http://localhost:8000/api/rooms?client_id=player1" \
  -H "Content-Type: application/json" \
  -d '{
    "room_name": "My Room",
    "password": "optional_password"
  }'

Delete a Room

curl -X DELETE "http://localhost:8000/api/rooms/abc123?client_id=player1"

🌐 WebSocket API

Web UI WebSocket

Endpoint: ws://host:port/ws/web

The web interface automatically connects and receives real-time updates:

  • Client list updates
  • Room list updates
  • Match start/end notifications
  • Data relay events

Message Types (from server):

Client List:

{
  "type": "client_list",
  "clients": [...]
}

Room List:

{
  "type": "room_list",
  "rooms": [...]
}

Match Events:

{
  "type": "match_started",
  "client_id": "player1",
  "opponent_id": "player2",
  "room_id": "abc123"
}

Data Relay:

{
  "type": "data_relay",
  "from": "player1",
  "to": "player2",
  "room_id": "abc123",
  "data": "48656c6c6f",
  "size": 5,
  "timestamp": "2025-10-13T10:30:00"
}

πŸ”’ Production Deployment

HTTPS/WSS Support

Using reverse proxy (nginx):

server {
    listen 443 ssl;
    server_name wonderswan.example.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    
    location / {
        proxy_pass http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
}

systemd Service

/etc/systemd/system/wonderswan.service:

[Unit]
Description=WonderSwan FastAPI Server
After=network.target

[Service]
Type=simple
User=wonderswan
WorkingDirectory=/opt/wonderswan
ExecStart=/usr/bin/python3 ws_fastapi_server.py 0.0.0.0 8000
Restart=always

[Install]
WantedBy=multi-user.target

Start service:

sudo systemctl enable wonderswan
sudo systemctl start wonderswan

🐳 Docker Support

Dockerfile:

FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY models.py relay_manager.py ws_fastapi_server.py ./
COPY static/ ./static/

EXPOSE 8000

CMD ["python", "ws_fastapi_server.py"]

Build and run:

docker build -t wonderswan-server .
docker run -p 8000:8000 wonderswan-server

With SSL certificates:

docker run -p 8000:8000 \
  -v $(pwd)/cert.pem:/app/cert.pem \
  -v $(pwd)/key.pem:/app/key.pem \
  wonderswan-server

πŸ“Š Performance

Recommended Specifications

  • Server: 2+ CPU cores, 512MB+ RAM
  • Concurrent connections: Up to 50 clients
  • Latency: 1-5ms (within LAN)

Benchmark Example

# Test with Apache Bench
ab -n 1000 -c 10 http://localhost:8000/api/clients

πŸ” Troubleshooting

Port 8000 Already in Use

# Check port on Windows
netstat -ano | findstr :8000

# Check port on Linux
lsof -i :8000

Set custom port via environment variable:

PORT=9000 python ws_fastapi_server.py

static/index.html Not Found

Error: FileNotFoundError: [Errno 2] No such file or directory: 'static/index.html'

Solution:

  1. Ensure static/ directory exists in the same location as ws_fastapi_server.py
  2. Verify index.html is inside the static/ directory
  3. Restart server

Web Serial API Not Available

Error: Browser shows "Web Serial API not supported" warning

Solution:

  1. Use Chrome 89+, Edge 89+, or Opera 75+
  2. For LAN access, use HTTPS (see HTTPS Setup section)
  3. For localhost, HTTP works fine

Cannot Connect to Serial Device

Issue: "Connect to Serial Port" button doesn't work

Solutions:

  1. Make sure you're using a supported browser
  2. Check that your serial device is connected
  3. On Windows, check Device Manager for COM port
  4. On Linux, check /dev/ttyUSB* or /dev/ttyACM*
  5. Ensure you have permission to access the serial port (Linux: add user to dialout group)

Room Join Fails

Issue: Cannot join a room that appears available

Solutions:

  1. Room may have filled between listing and join attempt
  2. Check if password is required
  3. Ensure you're not already in another room (leave first)
  4. Refresh the page and try again

πŸ’‘ Features

Room Management System

  • Create Rooms: Set up private or public game rooms
  • Password Protection: Optional password for private matches
  • 1v1 Matches: Automatic matchmaking when a guest joins
  • Real-time Updates: Live room list and status updates

Web Serial Support

  • Browser-based: No external client needed
  • Direct Serial Communication: Connect WonderSwan directly via browser
  • Session Persistence: Auto-restore connections on page reload
  • Multi-device: Connect multiple WonderSwans from different browsers

Data Relay

  • Low Latency: Efficient WebSocket-based relay
  • Binary Data: Hex-encoded data transmission
  • Automatic Routing: Data automatically sent to opponent in same room
  • Statistics Tracking: Monitor relay count and match activity

πŸ“ Architecture

Modular Design

  • models.py: Data structures (Room, ClientInfo, Enums)
  • relay_manager.py: Connection and state management
  • ws_fastapi_server.py: HTTP/WebSocket server endpoints

Technology Stack

  • FastAPI: Modern async web framework
  • WebSockets: Real-time bidirectional communication
  • Web Serial API: Browser-based serial port access
  • Pydantic: Data validation and serialization

Key Features

  • Type-safe with comprehensive type hints
  • Comprehensive error handling and logging
  • Auto-generated API documentation (Swagger UI)
  • CORS enabled for cross-origin requests
  • Graceful shutdown handling

🀝 Contributing

Contributions are welcome! Please feel free to submit pull requests or open issues.

πŸ“„ License

This project was created using Claude Code. I assume no responsibility for any damages incurred as a result of using this project.

πŸ”— Related Projects


For API documentation, visit http://localhost:8000/docs after starting the server!

About

This is a project that allows WonderSwans to communicate with each other online.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors