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.
- οΏ½ 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
- π 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
- React 19 with TypeScript
- Material-UI + Tailwind CSS
- Vite build tool
- WebSocket for real-time updates
- 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
- Node.js 18+ (for frontend)
- Python 3.8+ (for backend)
- arduino-cli (for device management)
-
Clone the repository:
git clone <repository-url> cd ReRo-Website
-
Backend Setup:
cd backend python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -r requirements.txt
-
Frontend Setup:
cd frontend npm install -
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/
- Start Backend:
cd backend python main.py # Server runs on http://localhost:8000
Environment Variables:
VITE_BACKEND_URL=http://localhost:8000- Start Frontend:
cd frontend npm run dev # App runs on http://localhost:5173
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
- 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
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
- 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 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)
- CP2102 USB-to-Serial (
GET /devicesResponse 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"]
}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"
}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
}
}- π 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 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
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;
}
};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()){
"email": "[email protected]",
"password": "password123"
}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"
}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
When code is uploaded via /devices/upload/{device_number}:
- Serial reading automatically stops (prevents port conflicts)
- Device output reset to empty (fresh start)
- New code execution begins
- Serial reading can be restarted via WebSocket connection
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");
}- 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
- π 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
- π 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
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
);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
);-
Registration:
- Email uniqueness validation
- Password strength requirements
- bcrypt hash generation and storage
- User profile creation
-
Login:
- Email/password credential verification
- bcrypt password comparison
- User session establishment
- Last login timestamp update
-
Protected Operations:
- Authentication token validation
- User permission verification
- Slot booking authorization
- Device upload access control
- π‘ 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
- π 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
GET /slotsResponse:
{
"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
}GET /statsResponse:
{
"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
}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"
}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"
}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"
}- π 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
- π§ 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
- π 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
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'
}
});// Clean, modular slot grid with real-time updates
<SlotsGrid
slotsData={slotsData}
userEmail={user?.email}
loading={loading}
onSlotAction={handleSlotAction}
/>// 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)}
/>// Real-time connection and error status
<StatusAlerts
error={error}
isConnected={isConnected}
reconnecting={reconnecting}
/>- π± 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
- π 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
- π― 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
npm run dev # Start development server
npm run build # Build for production
npm run preview # Preview production build
npm run lint # Run ESLintpython main.py # Start development server
uvicorn main:app --reload # Alternative start commandcd frontend
npm run build
# Deploy dist/ folder to web servercd backend
pip install -r requirements.txt
uvicorn main:app --host 0.0.0.0 --port 8000When running the backend, visit:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
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
# 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"
}'# 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 --noEmitComprehensive Test Suite:
cd backend
python test_websocket_device.py # Full automated testingManual WebSocket Testing:
cd backend
python test_websocket_client.py # Interactive testingBrowser 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
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);
}
};# 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"}# 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'
)- 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
# 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# 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- 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
- 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
- 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
- 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
- Fork the repository
- Create a feature branch
- Make your changes following the modular architecture
- Test thoroughly (frontend build + backend endpoints)
- Submit a pull request
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.