Skip to content

IEEERASPESU/ReRo-Website

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

18 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

ReRo Website - Modular Slot Booking System with Arduino Device Management

A comprehensive, full-stack web application for real-time slot booking with integrated Arduino device management. Features a modular React frontend with dark mode, real-time WebSocket updates, and a FastAPI backend with Arduino code compilation and upload capabilities.

πŸ”₯ Key Features

🎨 Frontend Features

  • οΏ½ Dark Mode Theme: Professional dark UI with Material-UI and Tailwind CSS
  • πŸ—οΈ Modular Architecture: 16+ reusable components across auth, booking, and home modules
  • ⚑ Real-time WebSocket: Instant slot updates across all connected clients
  • πŸ“± Responsive Design: Mobile-first design that works on all screen sizes
  • πŸ” Authentication Flow: Complete login/register with form validation and error handling
  • 🎯 Color-coded Slots: Visual indicators (🟒 Available, πŸ”΄ Booked, πŸ”΅ Your booking)
  • πŸ”„ Live Connection Status: Real-time WebSocket connection indicators
  • πŸ“Š Interactive Slot Grid: 24 time slots (24-hour coverage) with one-click booking/cancellation
  • 🎭 Smooth Animations: Material-UI transitions and loading states
  • οΏ½ Client-side Routing: React Router for SPA navigation
  • ⚑ Hot Reload: Vite development server with instant updates
  • πŸ§ͺ TypeScript: Full type safety across all components

βš™οΈ Backend Features

  • πŸ”Œ Arduino Device Management: Full hardware integration with 10+ supported device types
  • οΏ½ Real-time Serial Reading: Live WebSocket streams for Arduino serial output monitoring
  • οΏ½πŸš€ FastAPI Framework: Modern async Python API with automatic OpenAPI docs
  • πŸ” Local Authentication: bcrypt password hashing with secure user management
  • πŸ’Ύ SQLite Database: Persistent storage with automatic schema management
  • 🌐 Dual WebSocket System: Slot booking + device serial communication endpoints
  • πŸ›‘οΈ Security: Slot-based authorization, input validation, and SQL injection protection
  • πŸ“Š Device Detection: Automatic Arduino Uno, Mega, and ESP32 recognition
  • ⚑ Code Compilation: arduino-cli integration for multi-board compilation
  • οΏ½ Secure Code Upload: Authentication + slot validation for device programming
  • πŸ”„ Serial Port Management: Exclusive access handling for upload/read operations
  • οΏ½πŸ“ File Management: Automatic temporary file cleanup and project management
  • πŸ“ˆ Health Monitoring: System statistics and connection monitoring
  • 🎯 Thread-Safe Operations: Concurrent serial reading with broadcast messaging
  • πŸ”„ CORS Support: Cross-origin resource sharing for frontend-backend communication
  • πŸ“ Comprehensive Logging: Structured logging with different levels across all modules

πŸ› οΈ Tech Stack

Frontend

  • React 19 with TypeScript
  • Material-UI + Tailwind CSS
  • Vite build tool
  • WebSocket for real-time updates

Backend

  • FastAPI with Python 3.8+
  • SQLite database
  • WebSocket support (dual endpoints)
  • PySerial for Arduino communication
  • arduino-cli for device management
  • bcrypt for password security
  • Threading for concurrent operations

πŸš€ Quick Start

Prerequisites

  • Node.js 18+ (for frontend)
  • Python 3.8+ (for backend)
  • arduino-cli (for device management)

Installation

  1. Clone the repository:

    git clone <repository-url>
    cd ReRo-Website
  2. Backend Setup:

    cd backend
    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    pip install -r requirements.txt
  3. Frontend Setup:

    cd frontend
    npm install
  4. Install Arduino CLI (for device management):

    # Linux/macOS
    curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | sh
    
    # Or download from: https://arduino.github.io/arduino-cli/

Running the Application

  1. Start Backend:
    cd backend
    python main.py
    # Server runs on http://localhost:8000

Environment Variables:

VITE_BACKEND_URL=http://localhost:8000
  1. Start Frontend:
    cd frontend
    npm run dev
    # App runs on http://localhost:5173

πŸ—οΈ Architecture Overview

🎨 Frontend Architecture & Components

The frontend features a completely modular React architecture with 16+ specialized components:

frontend/src/
β”œβ”€β”€ pages/                  # Main page components (4 pages)
β”‚   β”œβ”€β”€ Home.tsx           # Landing page with hero and features
β”‚   β”œβ”€β”€ SlotBooking.tsx    # Main booking interface
β”‚   β”œβ”€β”€ Login.tsx          # User authentication
β”‚   └── Register.tsx       # User registration
β”œβ”€β”€ components/             # Modular component library (16+ components)
β”‚   β”œβ”€β”€ auth/              # Authentication UI components (6 components)
β”‚   β”‚   β”œβ”€β”€ LoginHeader.tsx     # Login page branding
β”‚   β”‚   β”œβ”€β”€ LoginForm.tsx       # Login form with validation
β”‚   β”‚   β”œβ”€β”€ LoginFooter.tsx     # Login page footer/links
β”‚   β”‚   β”œβ”€β”€ RegisterHeader.tsx  # Registration page branding
β”‚   β”‚   β”œβ”€β”€ RegisterForm.tsx    # Registration form with validation
β”‚   β”‚   └── RegisterFooter.tsx  # Registration page footer/links
β”‚   β”œβ”€β”€ booking/           # Slot booking components (5 components)
β”‚   β”‚   β”œβ”€β”€ AppHeader.tsx       # Navigation bar with user info
β”‚   β”‚   β”œβ”€β”€ BookingHeader.tsx   # Booking page title and info
β”‚   β”‚   β”œβ”€β”€ SlotCard.tsx        # Individual slot component with actions
β”‚   β”‚   β”œβ”€β”€ SlotsGrid.tsx       # 12-slot grid layout manager
β”‚   β”‚   └── StatusAlerts.tsx    # Connection and error status displays
β”‚   β”œβ”€β”€ home/              # Home page components (3 components)
β”‚   β”‚   β”œβ”€β”€ HeroSection.tsx     # Main landing banner
β”‚   β”‚   β”œβ”€β”€ FeaturesSection.tsx # Feature highlights grid
β”‚   β”‚   └── TimeSlotsInfo.tsx   # Available time slots information
β”‚   └── index.ts           # Centralized component exports
β”œβ”€β”€ contexts/              # React Context providers
β”‚   β”œβ”€β”€ AuthContext.tsx    # User authentication state management
β”‚   └── StateContext.tsx   # Global application state
β”œβ”€β”€ shared/                # Shared utilities and types
β”‚   └── types.tsx          # TypeScript type definitions
└── assets/                # Static assets and images
    └── ieeeras.png        # Organization logo

🎨 Frontend Technology Features

  • Material-UI Components: AppBar, Container, Grid, Card, Button, TextField, Alert
  • Tailwind CSS Classes: Custom styling with utility-first approach
  • React 19: Latest React with concurrent features and automatic batching
  • TypeScript: Full type safety with interfaces for props and state
  • React Router v6: Modern client-side routing with lazy loading
  • WebSocket Integration: Real-time communication with automatic reconnection
  • Context API: Global state management for authentication and app state
  • Responsive Grid: CSS Grid and Flexbox for mobile-first design
  • Form Validation: Real-time input validation with error feedback
  • Dark Theme: Comprehensive dark mode with custom color palette

βš™οΈ Backend Architecture & Modules

The backend follows a clean, modular FastAPI architecture with 10+ specialized modules:

backend/
β”œβ”€β”€ main.py                # πŸš€ FastAPI application entry point
β”œβ”€β”€ requirements.txt       # πŸ“‹ Python dependencies (15+ packages)
β”œβ”€β”€ data/                  # πŸ’Ύ Database and file storage
β”‚   β”œβ”€β”€ rero.db           # SQLite database file
β”‚   └── arduino_projects/ # Temporary Arduino project directories
β”œβ”€β”€ core/                  # βš™οΈ Core application modules (5 modules)
β”‚   β”œβ”€β”€ config.py         # Configuration management and logging setup
β”‚   β”œβ”€β”€ models.py         # Pydantic data models and response schemas
β”‚   β”œβ”€β”€ slot_manager.py   # Slot booking business logic
β”‚   β”œβ”€β”€ state.py          # Global application state management
β”‚   └── __init__.py
β”œβ”€β”€ auth/                  # πŸ” Authentication system (1 module)
β”‚   β”œβ”€β”€ local_auth.py     # Local user management with bcrypt
β”‚   └── __init__.py
β”œβ”€β”€ database/              # πŸ’Ύ Database operations (1 module)
β”‚   β”œβ”€β”€ operations.py     # SQLite CRUD operations and schema management
β”‚   └── __init__.py
β”œβ”€β”€ routes/                # πŸ›£οΈ HTTP API endpoints (3 route modules)
β”‚   β”œβ”€β”€ main.py           # Core API routes (slots, stats, health)
β”‚   β”œβ”€β”€ auth.py           # Authentication routes (login, register)
β”‚   β”œβ”€β”€ devices.py        # Arduino device management routes
β”‚   └── __init__.py
β”œβ”€β”€ websocket/             # πŸ”Œ Real-time communication (4 modules)
β”‚   β”œβ”€β”€ endpoints.py      # Slot booking WebSocket endpoint
β”‚   β”œβ”€β”€ device_endpoints.py # Device serial reading WebSocket endpoint
β”‚   β”œβ”€β”€ handlers.py       # WebSocket message processing
β”‚   β”œβ”€β”€ manager.py        # Connection and broadcast management
β”‚   └── __init__.py
└── device_handler/       # πŸ”Œ Arduino integration (4 modules)
    β”œβ”€β”€ get_devices.py    # Hardware device detection and listing
    β”œβ”€β”€ serial_manager.py # Real-time serial communication management
    β”œβ”€β”€ utils.py          # Board configurations and file management
    └── __init__.py

βš™οΈ Backend Technology Features

  • FastAPI Framework: Async Python with automatic OpenAPI/Swagger docs
  • SQLite Database: Lightweight, file-based database with ACID compliance
  • Dual WebSocket Support: Slot booking + device serial communication endpoints
  • PySerial Integration: Real-time Arduino serial communication at 9600 baud
  • Thread-Safe Operations: Concurrent serial reading with broadcast messaging
  • bcrypt Security: Password hashing with salt and secure verification
  • arduino-cli Integration: Command-line interface for Arduino compilation/upload
  • Serial Port Management: Exclusive access handling for upload/read operations
  • Pydantic Models: Data validation and serialization with type hints
  • CORS Middleware: Cross-origin resource sharing for web clients
  • Structured Logging: Multi-level logging across all modules
  • Modular Design: Separation of concerns with clean interfaces
  • Error Handling: Comprehensive exception handling and user feedback
  • Resource Cleanup: Automatic connection and file management

πŸ”Œ Arduino Device Management

πŸ”§ Supported Hardware

  • Arduino Uno (Official boards: 2341:0043, 2341:0243)
  • Arduino Mega (Official boards: 2341:0010, 2341:0042)
  • CH340 Clones (1a86:7523 - Uno/Mega compatible)
  • ESP32 Variants (Multiple chip types):
    • CP2102 USB-to-Serial (10c4:ea60)
    • CP2105 Dual UART (10c4:ea70)
    • CH9102 newer clones (1a86:55d4)
    • FTDI-based boards (0403:6001)
    • ESP32-S2 native USB (303a:1001)

πŸ“‘ Device API Endpoints

1. πŸ“‹ List Connected Devices

GET /devices

Response Example:

{
  "success": true,
  "devices": [
    {
      "model": "uno",
      "port": "/dev/ttyUSB0",
      "description": "USB Serial", 
      "manufacturer": null,
      "serial_number": null,
      "vid": "1a86",
      "pid": "7523"
    },
    {
      "model": "esp32",
      "port": "/dev/ttyACM0",
      "description": "USB Single Serial",
      "manufacturer": null, 
      "serial_number": "5574010494",
      "vid": "1a86",
      "pid": "55d4"
    }
  ],
  "count": 2,
  "supported_models": ["uno", "mega", "esp32"]
}

2. βš™οΈ Compile Arduino Code

POST /devices/compile
Content-Type: application/json

{
  "code": "void setup() {\n  Serial.begin(9600);\n  pinMode(LED_BUILTIN, OUTPUT);\n}\n\nvoid loop() {\n  digitalWrite(LED_BUILTIN, HIGH);\n  delay(1000);\n  digitalWrite(LED_BUILTIN, LOW);\n  delay(1000);\n}"
}

Response Example:

{
  "success": true,
  "compile_results": {
    "uno": {
      "success": true,
      "stdout": "Sketch uses 1634 bytes (5%) of program storage space. Maximum is 32256 bytes.\nGlobal variables use 200 bytes (9%) of dynamic memory, leaving 1848 bytes for local variables. Maximum is 2048 bytes.\n",
      "stderr": ""
    },
    "mega": {
      "success": true, 
      "stdout": "Sketch uses 1634 bytes (0%) of program storage space. Maximum is 253952 bytes.\nGlobal variables use 200 bytes (2%) of dynamic memory, leaving 7992 bytes for local variables. Maximum is 8192 bytes.\n",
      "stderr": ""
    },
    "esp32": {
      "success": true,
      "stdout": "Sketch uses 221465 bytes (16%) of program storage space. Maximum is 1310720 bytes.\nGlobal variables use 13428 bytes (4%) of dynamic memory, leaving 314252 bytes for local variables. Maximum is 327680 bytes.\n", 
      "stderr": ""
    }
  },
  "message": "Code compiled successfully for all boards",
  "project_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}

3. πŸ“€ Upload Code to Device

POST /devices/upload/{device_number}
Content-Type: application/json

{
  "code": "void setup() {\n  Serial.begin(9600);\n  Serial.println(\"Hello, ReRo!\");\n}\n\nvoid loop() {\n  Serial.println(\"Running...\");\n  delay(2000);\n}",
  "email": "[email protected]",
  "password": "securepassword123"
}

Security & Validation Features:

  • βœ… User Authentication: Validates email/password credentials
  • βœ… Slot Authorization: Ensures user has booked the current time slot
  • βœ… Device Validation: Confirms target device exists and is available
  • βœ… Board Compatibility: Automatically selects correct FQBN for device type
  • βœ… Automatic Cleanup: Removes temporary project files after upload
  • βœ… Error Handling: Comprehensive error reporting for all failure modes

Response Example (Success):

{
  "success": true,
  "message": "Code uploaded successfully to device 0",
  "device_info": {
    "model": "uno",
    "port": "/dev/ttyUSB0"
  },
  "upload_details": {
    "compile_success": true,
    "upload_success": true,
    "project_id": "uuid-here"
  }
}

Response Example (Error):

{
  "success": false,
  "message": "Upload failed: User does not have current slot booked",
  "error_type": "slot_validation_error",
  "details": {
    "current_slot": 9,
    "user_email": "[email protected]",
    "slot_booked": false
  }
}

⚑ Arduino Integration Features

  • πŸ”„ Auto-detection: Scans for connected devices on startup and refresh
  • 🎯 Multi-board Support: Compiles for Uno, Mega, and ESP32 simultaneously
  • πŸ›‘οΈ Secure Operations: All uploads require authentication and slot validation
  • πŸ“ Project Management: Creates temporary Arduino projects with proper structure
  • 🧹 Cleanup: Automatic removal of temporary files for security
  • ⚑ Fast Compilation: Uses arduino-cli for efficient build process
  • πŸ“Š Detailed Feedback: Memory usage, compile errors, upload status
  • πŸ” Device Validation: Ensures hardware exists before attempting operations

πŸ“‘ Real-time Device Serial Communication

🌐 WebSocket Endpoint for Device Reading

/devices/read/{device_number}

Real-time serial output monitoring - Connect to Arduino devices and receive live serial data at 9600 baud.

Features:

  • βœ… Authentication Required: Email/password validation
  • βœ… Slot-based Authorization: Must have current time slot booked
  • βœ… Real-time Updates: Instant serial output broadcasting
  • βœ… Multi-client Support: Multiple users can read from same device
  • βœ… Automatic Cleanup: Connections properly managed

πŸ“± Usage Examples

JavaScript WebSocket Client

const deviceNumber = 0;
const ws = new WebSocket(`ws://localhost:8000/devices/read/${deviceNumber}`);

ws.onopen = () => {
    // Send authentication
    ws.send(JSON.stringify({
        email: "[email protected]",
        password: "password123"
    }));
};

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    
    switch(data.type) {
        case 'error':
            console.error('Error:', data.message);
            break;
        case 'connection_established':
            console.log('Connected to:', data.device_info);
            break;
        case 'serial_output':
            console.log('Device output:', data.output);
            break;
    }
};

Python AsyncIO Client

import asyncio
import websockets
import json

async def read_device_serial():
    uri = "ws://localhost:8000/devices/read/0"
    
    async with websockets.connect(uri) as websocket:
        # Authenticate
        await websocket.send(json.dumps({
            "email": "[email protected]",
            "password": "password123"
        }))
        
        # Listen for serial output
        async for message in websocket:
            data = json.loads(message)
            if data['type'] == 'serial_output':
                print(f"Device {data['device_number']}: {data['output']}")

asyncio.run(read_device_serial())

πŸ“¨ WebSocket Message Types

Client β†’ Server (Authentication)

{
    "email": "[email protected]",
    "password": "password123"
}

Server β†’ Client Messages

Connection Established:

{
    "type": "connection_established",
    "device_number": 0,
    "device_info": {
        "model": "uno",
        "port": "/dev/ttyUSB0"
    },
    "message": "Connected to device 0 (uno on /dev/ttyUSB0)"
}

Serial Output:

{
    "type": "serial_output",
    "device_number": 0,
    "output": "Hello from Arduino!\nLED ON\nLED OFF\n",
    "timestamp": "2025-07-29T12:34:56.789Z"
}

Error Messages:

{
    "type": "error",
    "message": "Authentication failed"
}

πŸ›‘οΈ Security & Access Control

Error Conditions:

  • Invalid Device: Device number doesn't exist β†’ Immediate error + close
  • Authentication Failed: Invalid credentials β†’ Error + close
  • No Slot Booked: User hasn't booked current time slot β†’ Error + close
  • Device Busy: Serial port in use by upload β†’ Graceful handling

⚑ Integration with Code Upload

When code is uploaded via /devices/upload/{device_number}:

  1. Serial reading automatically stops (prevents port conflicts)
  2. Device output reset to empty (fresh start)
  3. New code execution begins
  4. Serial reading can be restarted via WebSocket connection

πŸ”§ Arduino Code for Serial Output

void setup() {
    Serial.begin(9600);
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.println("Device started!");
    Serial.println("Running ReRo demo code");
}

void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.println("LED ON");
    delay(1000);
    
    digitalWrite(LED_BUILTIN, LOW);
    Serial.println("LED OFF");
    delay(1000);
    
    Serial.print("Uptime: ");
    Serial.print(millis() / 1000);
    Serial.println(" seconds");
}

πŸ“Š Performance Characteristics

  • Baud Rate: 9600 (configurable)
  • Buffer Size: 10,000 characters per device
  • Latency: Sub-second real-time delivery
  • Concurrent Connections: Multiple users per device
  • Memory Usage: Bounded by buffer limits
  • Thread Safety: Full concurrent operation support

πŸ” Authentication & Security

πŸ”’ User Management System

  • πŸ†• Self-Registration: Users create accounts with email/password
  • πŸ” Secure Login: bcrypt password hashing with salt (12 rounds)
  • πŸ“§ Email-based Identity: Each user identified by unique email address
  • πŸ›‘οΈ Password Security: No plain-text storage, secure verification
  • πŸ”„ Session Management: Stateless authentication for API requests
  • πŸ‘€ User Profiles: Profile information with creation timestamps

πŸ›‘οΈ Security Features

  • πŸ”’ bcrypt Hashing: Industry-standard password protection
  • 🎯 Slot-based Access: Users can only upload during their booked time slots
  • πŸ” Device Validation: Hardware existence verification before upload attempts
  • 🚫 SQL Injection Protection: Parameterized queries throughout database layer
  • πŸ“ Input Validation: Pydantic models for request/response validation
  • πŸ” Credential Verification: Secure authentication for all sensitive operations
  • 🧹 Automatic Cleanup: Temporary file removal for security
  • ⚑ Rate Limiting: Built-in FastAPI protections against abuse

πŸ“Š Database Schema

πŸ‘₯ Users Table

CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    email TEXT UNIQUE NOT NULL,           -- Unique email identifier
    password_hash TEXT NOT NULL,          -- bcrypt hashed password (60 chars)
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_login DATETIME DEFAULT NULL     -- Track user activity
);

πŸ• Slots Table

CREATE TABLE slots (
    id INTEGER PRIMARY KEY,               -- Slot ID (3-14 for 3AM-3PM)
    start_time TEXT NOT NULL,             -- Start time format: "09:00"
    end_time TEXT NOT NULL,               -- End time format: "10:00"
    is_booked BOOLEAN DEFAULT FALSE,      -- Booking status flag
    booked_by TEXT DEFAULT NULL,          -- User email who booked slot
    booked_at DATETIME DEFAULT NULL,      -- Timestamp when slot was booked
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

πŸ”‘ Authentication Workflow

  1. Registration:

    • Email uniqueness validation
    • Password strength requirements
    • bcrypt hash generation and storage
    • User profile creation
  2. Login:

    • Email/password credential verification
    • bcrypt password comparison
    • User session establishment
    • Last login timestamp update
  3. Protected Operations:

    • Authentication token validation
    • User permission verification
    • Slot booking authorization
    • Device upload access control

⚑ Real-time Features & Slot Management

🌐 WebSocket Communication

  • πŸ“‘ Dual WebSocket Endpoints: Slot booking + device serial communication
  • πŸ”„ Auto-reconnection: Automatic reconnection on connection loss
  • πŸ“Š Connection Monitoring: Live connection count and status tracking
  • 🎯 Instant Updates: Real-time slot status + serial output delivery
  • πŸ’¬ Message Broadcasting: Efficient distribution to connected clients
  • πŸ” Connection Management: Add/remove connections with cleanup
  • ⚑ Low Latency: Sub-second update delivery across the network
  • πŸ›‘οΈ Authenticated Streams: Secure access to both slot and device data
  • 🎯 Instant Updates: Immediate slot status propagation to all clients
  • πŸ’¬ Message Broadcasting: Efficient message distribution to connected clients
  • πŸ” Connection Management: Add/remove connections with cleanup
  • ⚑ Low Latency: Sub-second update delivery across the network

πŸ• Slot Management System

  • πŸ“… 24 Time Slots: Complete 24-hour coverage (00:00 - 23:59) with 1-hour intervals
  • 🎨 Visual Status Indicators:
    • 🟒 Available - Open for booking
    • πŸ”΄ Booked by Others - Unavailable
    • πŸ”΅ Your Booking - Booked by current user
    • βšͺ Loading - Status being updated
  • ⚑ One-click Operations: Simple booking and cancellation interface
  • πŸ”„ Real-time Sync: Instant updates across all connected devices
  • πŸ“Š Booking Analytics: Track booking patterns and usage statistics
  • πŸ›‘οΈ Conflict Prevention: Atomic booking operations prevent race conditions

πŸ“‹ API Endpoints for Slot Management

πŸ• Get All Slots

GET /slots

Response:

{
  "success": true,
  "slots": [
    {
      "id": 3,
      "start_time": "03:00", 
      "end_time": "04:00",
      "is_booked": false,
      "booked_by": null,
      "booked_at": null
    },
    {
      "id": 9,
      "start_time": "09:00",
      "end_time": "10:00", 
      "is_booked": true,
      "booked_by": "[email protected]",
      "booked_at": "2025-07-29T09:15:30.123Z"
    }
  ],
  "total_slots": 12,
  "available_slots": 10,
  "booked_slots": 2
}

πŸ“Š System Statistics

GET /stats

Response:

{
  "success": true,
  "active_connections": 5,
  "database": {
    "total_users": 25,
    "total_slots": 12,
    "booked_slots": 3,
    "available_slots": 9,
    "database_size": "256 KB"
  },
  "uptime": "2h 45m 12s",
  "arduino_devices": 2
}

πŸ₯ Health Check

GET /health  

Response:

{
  "status": "healthy",
  "timestamp": "2025-07-29T12:34:56.789Z",
  "active_connections": 5,
  "booked_slots_count": 3,
  "database": {
    "status": "connected",
    "total_users": 25,
    "total_slots": 12
  },
  "arduino_cli": "available",
  "version": "1.0.0"
}

πŸ”„ WebSocket Message Types

οΏ½ Slot Booking Endpoint (/slot-booking)

Client β†’ Server Messages:

// Book a slot
{
  "type": "book_slot",
  "slot_id": 9,
  "user_email": "[email protected]", 
  "password": "securepassword"
}

// Cancel a booking
{
  "type": "cancel_slot",
  "slot_id": 9,
  "user_email": "[email protected]",
  "password": "securepassword"
}

Server β†’ Client Messages:

// Slot status update
{
  "type": "slot_update",
  "slot_id": 9,
  "is_booked": true,
  "booked_by": "[email protected]",
  "timestamp": "2025-07-29T12:34:56.789Z"
}

// Booking confirmation
{
  "type": "booking_success",
  "slot_id": 9,
  "message": "Slot booked successfully",
  "booked_at": "2025-07-29T12:34:56.789Z"
}

// Error notification
{
  "type": "error",
  "message": "Slot is already booked",
  "error_code": "SLOT_UNAVAILABLE"
}

πŸ“‘ Device Serial Endpoint (/devices/read/{device_number})

Client β†’ Server Messages:

// Authentication (sent immediately after connection)
{
  "email": "[email protected]",
  "password": "securepassword"
}

Server β†’ Client Messages:

// Connection established
{
  "type": "connection_established",
  "device_number": 0,
  "device_info": {"model": "uno", "port": "/dev/ttyUSB0"},
  "message": "Connected to device 0"
}

// Real-time serial output
{
  "type": "serial_output",
  "device_number": 0,
  "output": "LED ON\nLED OFF\nUptime: 45 seconds\n",
  "timestamp": "2025-07-29T12:34:56.789Z"
}

// Error responses
{
  "type": "error",
  "message": "Authentication failed"
}

⚑ Performance Features

  • πŸš€ Async Operations: Non-blocking database operations
  • πŸ”„ Connection Pooling: Efficient database connection management
  • πŸ“Š Real-time Metrics: Live performance monitoring
  • 🎯 Optimized Queries: Indexed database queries for fast responses
  • πŸ“ Structured Logging: Performance tracking and debugging
  • πŸ›‘οΈ Error Recovery: Graceful error handling with user feedback

🎨 Frontend Components & UI Features

πŸ—οΈ Modular Component Architecture Benefits

  • πŸ”§ Single Responsibility: Each component has a focused, specific purpose
  • ♻️ High Reusability: Components can be shared across multiple pages
  • πŸ§ͺ Easy Testing: Smaller components are simpler to unit test
  • πŸ“– Better Readability: Clean, focused page components with clear structure
  • ⚑ Tree-shaking: Better code splitting and bundle optimization
  • πŸ”„ Hot Reload: Fast development with component-level updates

🎨 Material-UI & Theming Features

  • πŸŒ™ Dark Theme: Comprehensive dark mode with custom color palette
  • πŸ“± Responsive Components: Mobile-first responsive design system
  • 🎯 Consistent Styling: Unified design language across all components
  • ⚑ Performance: Optimized component rendering with minimal re-renders
  • 🎭 Smooth Animations: Material Design transitions and micro-interactions

🎨 Custom Theme Configuration

const theme = createTheme({
  palette: {
    mode: 'dark',
    primary: { main: '#60a5fa' },      // Light blue
    secondary: { main: '#34d399' },    // Light green  
    background: {
      default: '#0f172a',             // Dark slate
      paper: '#1e293b'                // Lighter dark for cards
    },
    text: {
      primary: '#f1f5f9',             // Light text
      secondary: '#cbd5e1'            // Muted light text
    }
  },
  typography: {
    fontFamily: '"Inter", "Roboto", "Arial", sans-serif'
  }
});

πŸ”§ Component Examples & Usage

πŸ“Š Slot Grid Component

// Clean, modular slot grid with real-time updates
<SlotsGrid 
  slotsData={slotsData}
  userEmail={user?.email}
  loading={loading}
  onSlotAction={handleSlotAction}
/>

🎯 Slot Card Component

// Individual slot with visual status and actions
<SlotCard
  slot={slot}
  isUserSlot={slot.booked_by === userEmail}
  onBook={() => onSlotAction('book', slot.id)}
  onCancel={() => onSlotAction('cancel', slot.id)}
/>

🚨 Status Alert Component

// Real-time connection and error status
<StatusAlerts 
  error={error}
  isConnected={isConnected}
  reconnecting={reconnecting}
/>

πŸ“± Responsive Design Features

  • πŸ“± Mobile-first: Optimized for mobile devices with touch-friendly interfaces
  • πŸ’» Desktop Enhanced: Rich desktop experience with hover states and larger layouts
  • πŸ–₯️ Tablet Optimized: Perfect tablet experience with intermediate layouts
  • πŸ“ Flexible Grid: CSS Grid and Flexbox for adaptive layouts
  • 🎯 Touch Targets: Properly sized buttons and interactive elements
  • πŸ“ Breakpoint System: Material-UI breakpoints for consistent responsive behavior

⚑ Frontend Performance Features

  • πŸš€ Vite Build System: Lightning-fast development and production builds
  • πŸ“¦ Code Splitting: Automatic route-based code splitting with React.lazy
  • πŸ”„ Hot Module Replacement: Instant updates during development
  • πŸ—œοΈ Asset Optimization: Automatic image and asset optimization
  • πŸ“Š Bundle Analysis: Built-in bundle size analysis and optimization
  • ⚑ Tree Shaking: Dead code elimination for smaller bundles

πŸ”„ State Management

  • 🎯 React Context: Global state management for authentication and app state
  • πŸ“Š Local State: Component-level state for UI interactions
  • πŸ”„ WebSocket State: Real-time data synchronization with backend
  • πŸ’Ύ Persistent State: Local storage for user preferences
  • πŸ” Error Boundaries: Graceful error handling and recovery

πŸ”§ Development Commands

Frontend

npm run dev          # Start development server
npm run build        # Build for production
npm run preview      # Preview production build
npm run lint         # Run ESLint

Backend

python main.py       # Start development server
uvicorn main:app --reload  # Alternative start command

πŸš€ Production Deployment

Frontend Build

cd frontend
npm run build
# Deploy dist/ folder to web server

Backend Setup

cd backend
pip install -r requirements.txt
uvicorn main:app --host 0.0.0.0 --port 8000

πŸ“Š API Documentation

When running the backend, visit:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

πŸ§ͺ Testing & API Documentation

πŸ“Š API Documentation Access

When running the backend, comprehensive API documentation is available:

  • πŸ“– Swagger UI: http://localhost:8000/docs - Interactive API explorer
  • πŸ“‹ ReDoc: http://localhost:8000/redoc - Clean, readable API documentation
  • πŸ” OpenAPI Schema: http://localhost:8000/openapi.json - Machine-readable API specification

πŸ”§ Development Testing

πŸ› οΈ Backend API Testing

# Health check
curl http://localhost:8000/health

# List all slots
curl http://localhost:8000/slots

# Get system statistics
curl http://localhost:8000/stats

# List connected Arduino devices
curl http://localhost:8000/devices

# Test Arduino code compilation
curl -X POST "http://localhost:8000/devices/compile" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "void setup() {\n  Serial.begin(9600);\n  pinMode(LED_BUILTIN, OUTPUT);\n}\n\nvoid loop() {\n  digitalWrite(LED_BUILTIN, HIGH);\n  delay(1000);\n  digitalWrite(LED_BUILTIN, LOW);\n  delay(1000);\n}"
  }'

# Test user registration
curl -X POST "http://localhost:8000/auth/register" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "securepassword123"
  }'

# Test user login
curl -X POST "http://localhost:8000/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]", 
    "password": "securepassword123"
  }'

# Test code upload (requires authentication and slot booking)
curl -X POST "http://localhost:8000/devices/upload/0" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "void setup(){Serial.begin(9600);}\nvoid loop(){Serial.println(\"Test\");delay(1000);}",
    "email": "[email protected]",
    "password": "securepassword123"
  }'

🎨 Frontend Testing

# Start development server with hot reload
npm run dev

# Build for production and check for errors
npm run build

# Preview production build locally
npm run preview

# Run ESLint for code quality
npm run lint

# Type checking with TypeScript
npx tsc --noEmit

πŸ“‘ Device WebSocket Testing

Comprehensive Test Suite:

cd backend
python test_websocket_device.py  # Full automated testing

Manual WebSocket Testing:

cd backend
python test_websocket_client.py  # Interactive testing

Browser Console Testing:

// Test device serial WebSocket in browser console
const ws = new WebSocket('ws://localhost:8000/devices/read/0');
ws.onopen = () => ws.send(JSON.stringify({
  email: '[email protected]', 
  password: 'testpassword123'
}));
ws.onmessage = e => console.log(JSON.parse(e.data));

Test Coverage:

  • βœ… Device authentication and authorization
  • βœ… Serial output reading and broadcasting
  • βœ… Connection management and cleanup
  • βœ… Error handling for all edge cases
  • βœ… Integration with code upload functionality

πŸ” WebSocket Testing

πŸ“‘ Using Browser Developer Tools

Slot Booking WebSocket:

// Connect to slot booking WebSocket
const ws = new WebSocket('ws://localhost:8000/slot-booking');

// Listen for messages
ws.onmessage = (event) => {
  console.log('Received:', JSON.parse(event.data));
};

// Book a slot
ws.send(JSON.stringify({
  type: 'book_slot',
  slot_id: 9,
  user_email: '[email protected]',
  password: 'securepassword123'
}));

// Cancel a slot
ws.send(JSON.stringify({
  type: 'cancel_slot', 
  slot_id: 9,
  user_email: '[email protected]',
  password: 'securepassword123'
}));

Device Serial WebSocket:

// Connect to device serial WebSocket
const deviceWs = new WebSocket('ws://localhost:8000/devices/read/0');

// Send authentication
deviceWs.onopen = () => {
  deviceWs.send(JSON.stringify({
    email: '[email protected]',
    password: 'securepassword123'
  }));
};

// Listen for serial output
deviceWs.onmessage = (event) => {
  const data = JSON.parse(event.data);
  if (data.type === 'serial_output') {
    console.log('Arduino output:', data.output);
  }
};

πŸ”Œ Using wscat (WebSocket client)

# Install wscat
npm install -g wscat

# Connect to slot booking endpoint
wscat -c ws://localhost:8000/slot-booking

# Send booking message
{"type":"book_slot","slot_id":9,"user_email":"[email protected]","password":"securepassword123"}

# Connect to device serial endpoint
wscat -c ws://localhost:8000/devices/read/0

# Send authentication
{"email":"[email protected]","password":"securepassword123"}

πŸ› Debugging & Logging

πŸ“ Backend Logging Levels

# Configure logging in core/config.py
logging.basicConfig(
    level=logging.INFO,  # Change to DEBUG for verbose logging
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

πŸ” Frontend Development Tools

  • React Developer Tools: Component inspection and state debugging
  • Browser DevTools: Network monitoring and WebSocket message inspection
  • Vite DevTools: Build analysis and performance monitoring
  • Material-UI DevTools: Theme and component debugging

⚑ Performance Testing

πŸ“Š Backend Performance

# Install Apache Bench
sudo apt-get install apache2-utils

# Load test API endpoints
ab -n 1000 -c 10 http://localhost:8000/health
ab -n 500 -c 5 http://localhost:8000/slots
ab -n 100 -c 2 http://localhost:8000/devices

🎯 Frontend Performance

# Lighthouse CLI for performance audit
npm install -g lighthouse
lighthouse http://localhost:5173 --output html --output-path ./lighthouse-report.html

# Bundle analyzer
npm run build
npx vite-bundle-analyzer dist

πŸ“ Recent Changes

πŸ†• Device Serial Reading WebSocket (Latest)

  • Real-time Serial Communication: New /devices/read/{device_number} WebSocket endpoint
  • Live Arduino Output: Stream serial data at 9600 baud to authenticated users
  • Secure Access Control: Authentication + slot validation for device access
  • Concurrent Multi-user Support: Multiple users can read from same device
  • Integration with Upload: Automatic serial disconnect during code upload
  • Thread-safe Operations: Concurrent serial reading with broadcast messaging
  • Comprehensive Testing: Full test suite with automated and manual testing tools

✨ Frontend Refactoring

  • Modular Components: Split large page components into focused, reusable modules
  • Improved Maintainability: Better code organization and separation of concerns
  • Enhanced Reusability: Components can be easily shared across pages
  • Better Testing: Smaller components are easier to unit test

πŸ”Œ Backend Device Management

  • Arduino Integration: Complete device detection and management system
  • Code Compilation: Support for Uno, Mega, and ESP32 boards
  • Secure Uploads: Authentication and slot validation for device uploads
  • Automatic Cleanup: Temporary file management for security

πŸ›‘οΈ Security Enhancements

  • Dual WebSocket Security: Authentication required for both slot and device endpoints
  • Slot-based Access Control: Users can only upload/read during booked slots
  • Device Validation: Ensures target devices exist before operations
  • Serial Port Management: Exclusive access handling prevents conflicts
  • Credential Verification: Secure authentication for all sensitive operations

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes following the modular architecture
  4. Test thoroughly (frontend build + backend endpoints)
  5. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License.


Built with ❀️ for the ReRo community

Modern web technology meets Arduino development in a secure, real-time slot booking system.

About

Public Repo to the IEEE RAS ReRo Webapp

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 52.0%
  • TypeScript 46.2%
  • Shell 1.4%
  • Other 0.4%