diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..ef9e9a0
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,11 @@
+# Server Configuration
+PORT=3002
+
+# OpenWeatherMap API Key
+# Get your API key from: https://openweathermap.org/api
+OPENWEATHERMAP_API_KEY=your_openweathermap_api_key_here
+
+# Default Location (Stockholm, Sweden)
+DEFAULT_LATITUDE=59.3293
+DEFAULT_LONGITUDE=18.0686
+DEFAULT_LOCATION_NAME=Stockholm
diff --git a/.gitignore b/.gitignore
index 0d3dd35..8a9366d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -56,3 +56,6 @@ pids
# User-specific files
config.local.js
+
+# Archive directory (legacy/development files)
+archive/
\ No newline at end of file
diff --git a/README.md b/README.md
index d344fe2..4848116 100644
--- a/README.md
+++ b/README.md
@@ -64,15 +64,35 @@ A modern digital signage system for displaying real-time transit departures and
cd SignageHTML
```
-2. **Start the server**
+2. **Install dependencies**
```bash
- node server.js
+ npm install
```
-3. **Open in browser**
+3. **Configure environment variables**
+
+ Create a `.env` file in the root directory (or copy from `.env.example` if it exists):
+ ```bash
+ PORT=3002
+ OPENWEATHERMAP_API_KEY=your_openweathermap_api_key_here
+ DEFAULT_LATITUDE=59.3293
+ DEFAULT_LONGITUDE=18.0686
+ DEFAULT_LOCATION_NAME=Stockholm
+ ```
+
+ Get your OpenWeatherMap API key from [openweathermap.org](https://openweathermap.org/api).
+
+4. **Start the server**
+ ```bash
+ npm start
+ # or for development with auto-reload:
+ npm run dev
+ ```
+
+5. **Open in browser**
Navigate to: `http://localhost:3002`
-The server will start on port 3002 by default. The application will automatically load and begin fetching transit and weather data.
+The server will start on port 3002 by default (or the port specified in `.env`). The application will automatically load and begin fetching transit and weather data.
## Configuration
@@ -95,19 +115,24 @@ The server will start on port 3002 by default. The application will automaticall
2. Enter the Site Name and Site ID
3. Enable/disable the site as needed
-### Changing Weather Location
+### Environment Variables
-Weather location is configured in `weather.js`. Update the default coordinates:
+The application uses environment variables for configuration. Create a `.env` file in the root directory:
-```javascript
-window.weatherManager = new WeatherManager({
- latitude: 59.3293, // Stockholm default
- longitude: 18.0686,
- apiKey: 'your-api-key'
-});
+```bash
+# Server port (default: 3002)
+PORT=3002
+
+# OpenWeatherMap API key (required for weather features)
+OPENWEATHERMAP_API_KEY=your_api_key_here
+
+# Default location coordinates (Stockholm, Sweden)
+DEFAULT_LATITUDE=59.3293
+DEFAULT_LONGITUDE=18.0686
+DEFAULT_LOCATION_NAME=Stockholm
```
-Or use the settings panel to configure it through the UI.
+**Note**: The OpenWeatherMap API key is injected into the HTML at runtime by the server. You can also configure the weather location through the settings panel in the UI.
### Screen Orientation
@@ -138,10 +163,10 @@ git clone http://192.168.68.53:3000/kyle/SignageHTML.git
cd SignageHTML
# Make the setup script executable
-chmod +x raspberry-pi-setup.sh
+chmod +x scripts/raspberry-pi-setup.sh
# Run the setup script as root
-sudo ./raspberry-pi-setup.sh
+sudo ./scripts/raspberry-pi-setup.sh
# Reboot to apply all changes
sudo reboot
@@ -155,33 +180,44 @@ The system consists of the following components:
1. **Node.js Server** (`server.js`)
- Handles API proxying (SL Transport API, OpenWeatherMap)
- - Serves static files
+ - Serves static files from `public/` directory
- Manages site configuration
+ - Route handlers organized in `server/routes/`:
+ - `departures.js` - Transit departure data endpoints
+ - `sites.js` - Site search and nearby sites
+ - `config.js` - Configuration management endpoints
-2. **Configuration Manager** (`config.js`)
+2. **Configuration Manager** (`public/js/components/ConfigManager.js`)
- Manages system settings and UI customization
- Handles site selection and map integration
- Persists settings to localStorage
-3. **Weather Component** (`weather.js`)
+3. **Weather Component** (`public/js/components/WeatherManager.js`)
- Displays weather data from OpenWeatherMap
- Manages dark mode based on sunrise/sunset
- Shows hourly forecasts
-4. **Clock Component** (`clock.js`)
+4. **Clock Component** (`public/js/components/Clock.js`)
- Shows current time and date
- Swedish locale formatting
- Updates every second
-5. **Departures Component** (`departures.js`)
+5. **Departures Component** (`public/js/components/DeparturesManager.js`)
- Fetches and displays transit departure information
- Groups departures by line number
- Handles direction indicators and timing
-6. **Main UI** (`index.html`)
+6. **Utilities** (`public/js/utils/`)
+ - `constants.js` - Application constants and configuration
+ - `logger.js` - Centralized logging utility
+
+7. **Main UI** (`index.html`)
- Responsive layout with multiple orientation support
- CSS Grid-based landscape optimization
- Modern styling with animations
+ - External CSS in `public/css/`:
+ - `main.css` - Base styles, dark mode, orientation styles
+ - `components.css` - Component-specific styles
## API Integration
@@ -196,7 +232,7 @@ Weather data is fetched from OpenWeatherMap:
- Provides current conditions and hourly forecasts
- Used for dark mode timing calculations
-For detailed API response documentation, see [API_RESPONSE_DOCUMENTATION.md](API_RESPONSE_DOCUMENTATION.md).
+For detailed API response documentation, see [docs/API_RESPONSE_DOCUMENTATION.md](docs/API_RESPONSE_DOCUMENTATION.md).
## UI Settings
@@ -251,10 +287,13 @@ Settings are automatically saved to localStorage and persist across sessions.
- Verify sites are configured in settings
3. **Weather data not loading**
- - Check OpenWeatherMap API key in `weather.js`
+ - Check OpenWeatherMap API key in `.env` file
+ - Ensure `.env` file exists in the root directory
+ - Verify the API key is correctly set: `OPENWEATHERMAP_API_KEY=your_key_here`
+ - Restart the server after changing `.env` file
- Verify internet connection
- Look for errors in browser console (F12)
- - Check API key quota/limits
+ - Check API key quota/limits on openweathermap.org
4. **Map not loading**
- Ensure internet connection is active
@@ -271,15 +310,38 @@ Settings are automatically saved to localStorage and persist across sessions.
### Project Structure
```
SignageHTML/
-├── index.html # Main HTML file with UI and styles
-├── server.js # Node.js server for API proxying
-├── config.js # Configuration management
-├── clock.js # Clock component
-├── weather.js # Weather component
-├── departures.js # Departures component
-├── sites-config.json # Persistent site configuration
-├── package.json # Node.js dependencies
-└── README.md # This file
+├── index.html # Main HTML file
+├── server.js # Node.js server entry point
+├── server/
+│ └── routes/ # API route handlers
+│ ├── departures.js # Departure data endpoints
+│ ├── sites.js # Site search endpoints
+│ └── config.js # Configuration endpoints
+├── public/ # Static assets
+│ ├── css/
+│ │ ├── main.css # Base styles, dark mode, orientations
+│ │ └── components.css # Component-specific styles
+│ └── js/
+│ ├── main.js # Application initialization
+│ ├── components/ # Component classes
+│ │ ├── Clock.js
+│ │ ├── ConfigManager.js
+│ │ ├── DeparturesManager.js
+│ │ └── WeatherManager.js
+│ └── utils/ # Utility modules
+│ ├── constants.js
+│ └── logger.js
+├── config/
+│ └── sites.json # Persistent site configuration
+├── docs/
+│ └── API_RESPONSE_DOCUMENTATION.md # API response documentation
+├── scripts/
+│ └── raspberry-pi-setup.sh # Raspberry Pi deployment script
+├── package.json # Node.js dependencies
+├── .env # Environment variables (create from .env.example)
+├── .env.example # Environment variable template
+├── archive/ # Archived legacy files (see archive/README.md)
+└── README.md # This file
```
### Contributing
diff --git a/card.JPG b/card.JPG
deleted file mode 100644
index 32fb7eb..0000000
Binary files a/card.JPG and /dev/null differ
diff --git a/sites-config.json b/config/sites.json
similarity index 94%
rename from sites-config.json
rename to config/sites.json
index 4bc9ae0..0921c11 100644
--- a/sites-config.json
+++ b/config/sites.json
@@ -2,7 +2,7 @@
"orientation": "normal",
"darkMode": "auto",
"backgroundImage": "https://images.unsplash.com/photo-1509356843151-3e7d96241e11?q=80&w=1000",
- "backgroundOpacity": 0.3,
+ "backgroundOpacity": 0.45,
"sites": [
{
"id": "1411",
diff --git a/create-deployment-package.sh b/create-deployment-package.sh
deleted file mode 100644
index 55a3af5..0000000
--- a/create-deployment-package.sh
+++ /dev/null
@@ -1,52 +0,0 @@
-#!/bin/bash
-# Script to create a deployment package for Raspberry Pi
-
-echo "Creating deployment package for SL Transport Departures Display..."
-
-# Create a temporary directory
-TEMP_DIR="deployment-package"
-mkdir -p $TEMP_DIR
-
-# Copy necessary files
-echo "Copying files..."
-cp index.html $TEMP_DIR/
-cp server.js $TEMP_DIR/
-cp clock.js $TEMP_DIR/
-cp config.js $TEMP_DIR/
-cp weather.js $TEMP_DIR/
-cp ticker.js $TEMP_DIR/
-cp package.json $TEMP_DIR/
-cp README.md $TEMP_DIR/
-cp documentation.md $TEMP_DIR/
-cp raspberry-pi-setup.sh $TEMP_DIR/
-cp .gitignore $TEMP_DIR/
-
-# Copy any image files if they exist
-if [ -d "images" ]; then
- mkdir -p $TEMP_DIR/images
- cp -r images/* $TEMP_DIR/images/
-fi
-
-# Create a version file with timestamp
-echo "Creating version file..."
-DATE=$(date +"%Y-%m-%d %H:%M:%S")
-echo "SL Transport Departures Display" > $TEMP_DIR/version.txt
-echo "Packaged on: $DATE" >> $TEMP_DIR/version.txt
-echo "Version: 1.0.0" >> $TEMP_DIR/version.txt
-
-# Create a ZIP archive
-echo "Creating ZIP archive..."
-ZIP_FILE="sl-departures-display-$(date +"%Y%m%d").zip"
-zip -r $ZIP_FILE $TEMP_DIR
-
-# Clean up
-echo "Cleaning up..."
-rm -rf $TEMP_DIR
-
-echo "Deployment package created: $ZIP_FILE"
-echo "To deploy to Raspberry Pi:"
-echo "1. Transfer the ZIP file to your Raspberry Pi"
-echo "2. Unzip the file: unzip $ZIP_FILE"
-echo "3. Navigate to the directory: cd deployment-package"
-echo "4. Make the setup script executable: chmod +x raspberry-pi-setup.sh"
-echo "5. Run the setup script: sudo ./raspberry-pi-setup.sh"
diff --git a/departures.js b/departures.js
deleted file mode 100644
index 539b949..0000000
--- a/departures.js
+++ /dev/null
@@ -1,766 +0,0 @@
-// Calculate minutes until arrival using expected time (or scheduled if expected not available)
-function calculateMinutesUntilArrival(departure) {
- const now = new Date();
- // Use expected time if available (accounts for delays), otherwise use scheduled
- const arrivalTime = departure.expected ? new Date(departure.expected) : new Date(departure.scheduled);
- return Math.round((arrivalTime - now) / (1000 * 60));
-}
-
-// Get the time to display (expected if available, otherwise scheduled)
-function getDepartureTime(departure) {
- return departure.expected || departure.scheduled;
-}
-
-// Get transport icon based on transport mode
-function getTransportIcon(transportMode) {
- // Default to bus if not specified
- const mode = transportMode ? transportMode.toLowerCase() : 'bus';
-
- // Special case for line 7 - it's a tram
- if (arguments.length > 1 && arguments[1] && arguments[1].designation === '7') {
- return '';
- }
-
- // SVG icons for different transport modes
- const icons = {
- bus: '',
- metro: '',
- train: '',
- tram: '',
- ship: ''
- };
-
- return icons[mode] || icons.bus;
-}
-
-// Create a departure card element
-function createDepartureCard(departure) {
- const departureCard = document.createElement('div');
- departureCard.dataset.journeyId = departure.journey.id;
-
- const displayTime = departure.display;
- const departureTime = getDepartureTime(departure);
- const timeDisplay = formatDateTime(departureTime);
-
- // Check if departure is within the next hour
- const departureTimeDate = new Date(departureTime);
- const now = new Date();
- const diffMinutes = Math.round((departureTimeDate - now) / (1000 * 60));
- const isWithinNextHour = diffMinutes <= 60;
-
- // Add condensed class if within next hour
- departureCard.className = isWithinNextHour ? 'departure-card condensed' : 'departure-card';
-
- // Calculate minutes until arrival using expected time (accounts for delays)
- const minutesUntil = calculateMinutesUntilArrival(departure);
- let countdownText = displayTime;
- let countdownClass = '';
-
- // Determine color class based on minutesUntil, regardless of displayTime format
- if (minutesUntil <= 0 || displayTime === 'Nu' || displayTime.toLowerCase() === 'nu') {
- countdownText = 'Nu';
- countdownClass = 'now';
- } else if (minutesUntil < 5) {
- // Less than 5 minutes - red
- const minMatch = displayTime.match(/(\d+)\s*min/i);
- if (minMatch) {
- countdownText = minutesUntil === 1 ? '1 min' : `${minutesUntil} min`;
- } else {
- countdownText = minutesUntil === 1 ? '1 min' : `${minutesUntil} min`;
- }
- countdownClass = 'urgent'; // Red: less than 5 minutes
- } else {
- // 5+ minutes - white
- const isTimeOnly = /^\d{1,2}:\d{2}$/.test(displayTime);
- if (isTimeOnly) {
- countdownText = `${minutesUntil} min`;
- } else {
- // Use displayTime as-is (e.g., "5 min", "8 min")
- countdownText = displayTime;
- }
- // No class = white (default)
- }
-
- // Get transport icon based on transport mode and line
- const transportIcon = getTransportIcon(departure.line?.transportMode, departure.line);
-
- // Create card based on time and display format
- departureCard.innerHTML = `
-
- `;
-
- return departureCard;
-}
-
-// Display departures grouped by line number - New card-based layout
-function displayGroupedDeparturesByLine(groups, container) {
- groups.forEach(group => {
- // Create a card for this line number
- const groupCard = document.createElement('div');
- groupCard.className = 'departure-card line-card';
-
- // Get transport mode for styling - ensure we use the API value
- const apiTransportMode = group.line?.transportMode || '';
- const transportMode = apiTransportMode.toLowerCase();
-
- // Create large line number box on the left
- const lineNumberBox = document.createElement('div');
- lineNumberBox.className = `line-number-box ${transportMode}`;
-
- // Get transport icon instead of text label
- const transportIcon = getTransportIcon(group.line?.transportMode, group.line);
-
- lineNumberBox.innerHTML = `
-
${transportIcon}
-
${group.lineNumber}
- `;
- groupCard.appendChild(lineNumberBox);
-
- // Create directions wrapper on the right
- const directionsWrapper = document.createElement('div');
- directionsWrapper.className = 'directions-wrapper';
-
- // Process each direction (up to 2 directions side-by-side)
- const maxDirections = 2;
- group.directions.slice(0, maxDirections).forEach(direction => {
- // Sort departures by expected time (or scheduled if expected not available)
- direction.departures.sort((a, b) => {
- const timeA = getDepartureTime(a);
- const timeB = getDepartureTime(b);
- return new Date(timeA) - new Date(timeB);
- });
-
- // Create a row for this direction
- const directionRow = document.createElement('div');
- directionRow.className = 'direction-row';
-
- // Add direction info (arrow + destination)
- const directionInfo = document.createElement('div');
- directionInfo.className = 'direction-info';
-
- // Determine direction arrow and styling from API data
- // Get direction from the first departure in this direction group
- const firstDep = direction.departures[0];
- if (!firstDep) return; // Skip if no departures
-
- // Use direction_code from API: 1 = going TO that direction, 2 = going FROM that direction
- // For arrows: direction_code 1 = left arrow, direction_code 2 = right arrow
- const directionCode = firstDep.direction_code !== undefined ? firstDep.direction_code :
- firstDep.directionCode !== undefined ? firstDep.directionCode :
- null;
-
- // Map direction_code to arrow direction
- // direction_code 1 = left arrow (←), direction_code 2 = right arrow (→)
- const isRight = directionCode === 2;
-
- if (directionCode === null || directionCode === undefined) {
- console.warn('No direction_code found for:', direction.destination, firstDep);
- }
-
- const arrowBox = document.createElement('div');
- arrowBox.className = `direction-arrow-box ${isRight ? 'right' : 'left'}`;
- arrowBox.textContent = isRight ? '→' : '←';
-
- const destinationSpan = document.createElement('span');
- destinationSpan.className = 'direction-destination';
- destinationSpan.textContent = direction.destination;
-
- directionInfo.appendChild(arrowBox);
- directionInfo.appendChild(destinationSpan);
- directionRow.appendChild(directionInfo);
-
- // Add times container
- const timesContainer = document.createElement('div');
- timesContainer.className = 'times-container';
-
- // Get first two departures for time range
- const firstDeparture = direction.departures[0];
- const secondDeparture = direction.departures[1];
-
- if (firstDeparture) {
- const displayTime = firstDeparture.display;
- const departureTime = getDepartureTime(firstDeparture);
- const timeDisplay = formatDateTime(departureTime);
-
- // Calculate minutes until arrival using expected time (accounts for delays)
- const minutesUntil = calculateMinutesUntilArrival(firstDeparture);
- let countdownText = displayTime;
- let countdownClass = '';
-
- // Determine color class based on minutesUntil, regardless of displayTime format
- if (minutesUntil <= 0 || displayTime === 'Nu' || displayTime.toLowerCase() === 'nu') {
- countdownText = 'Nu';
- countdownClass = 'now';
- } else if (minutesUntil < 5) {
- // Use the number from displayTime if it's "X min", otherwise use calculated minutesUntil
- const minMatch = displayTime.match(/(\d+)\s*min/i);
- if (minMatch) {
- countdownText = `${minMatch[1]}`;
- } else {
- countdownText = `${minutesUntil}`;
- }
- countdownClass = 'urgent'; // Red: less than 5 minutes
- } else {
- // 5+ minutes - use displayTime as-is or calculate
- const minMatch = displayTime.match(/(\d+)\s*min/i);
- if (minMatch) {
- countdownText = `${minMatch[1]}`;
- } else if (/^\d{1,2}:\d{2}$/.test(displayTime)) {
- countdownText = `${minutesUntil}`;
- } else {
- countdownText = displayTime;
- }
- // No class = white (default)
- }
-
- // Create time display element
- const timeDisplayElement = document.createElement('div');
- timeDisplayElement.className = 'time-display';
-
- const countdownSpan = document.createElement('span');
- countdownSpan.className = `countdown-large ${countdownClass}`;
- countdownSpan.textContent = countdownText;
-
- timeDisplayElement.appendChild(countdownSpan);
-
- // Add time range (show expected times)
- const timeRangeSpan = document.createElement('span');
- timeRangeSpan.className = 'time-range';
- if (secondDeparture) {
- const secondTime = formatDateTime(getDepartureTime(secondDeparture));
- timeRangeSpan.textContent = `${timeDisplay} - ${secondTime}`;
- } else {
- timeRangeSpan.textContent = timeDisplay;
- }
- timeDisplayElement.appendChild(timeRangeSpan);
-
- timesContainer.appendChild(timeDisplayElement);
- }
-
- directionRow.appendChild(timesContainer);
- directionsWrapper.appendChild(directionRow);
- });
-
- groupCard.appendChild(directionsWrapper);
-
- // Add to container
- container.appendChild(groupCard);
- });
-}
-
-// Display grouped departures (legacy function)
-function displayGroupedDepartures(groups, container) {
- groups.forEach(group => {
- // Sort departures by expected time (or scheduled if expected not available)
- group.departures.sort((a, b) => {
- const timeA = getDepartureTime(a);
- const timeB = getDepartureTime(b);
- return new Date(timeA) - new Date(timeB);
- });
-
- // Create a card for this group
- const groupCard = document.createElement('div');
- groupCard.className = 'departure-card';
-
- // Create card header
- const header = document.createElement('div');
- header.className = 'departure-header';
-
- // Get transport icon based on transport mode and line
- const transportIcon = getTransportIcon(group.line?.transportMode, group.line);
-
- // Add line number with transport icon and destination
- const lineNumber = document.createElement('span');
- lineNumber.className = 'line-number';
- lineNumber.innerHTML = `${transportIcon} ${group.line.designation} ${group.destination}`;
- header.appendChild(lineNumber);
-
- // Add times container
- const timesContainer = document.createElement('div');
- timesContainer.className = 'times-container';
- timesContainer.style.display = 'flex';
- timesContainer.style.flexDirection = 'column';
- timesContainer.style.alignItems = 'flex-end';
-
- // Add up to 3 departure times
- const maxTimes = 3;
- group.departures.slice(0, maxTimes).forEach((departure, index) => {
- const timeElement = document.createElement('span');
- timeElement.className = 'time';
- timeElement.style.fontSize = index === 0 ? '1.1em' : '0.9em';
- timeElement.style.marginBottom = '2px';
-
- const displayTime = departure.display;
- const departureTime = getDepartureTime(departure);
- const timeDisplay = formatDateTime(departureTime);
-
- // Calculate minutes until arrival using expected time (accounts for delays)
- const minutesUntil = calculateMinutesUntilArrival(departure);
- let countdownText = displayTime;
- let countdownClass = '';
-
- // Determine color class based on minutesUntil, regardless of displayTime format
- if (minutesUntil <= 0 || displayTime === 'Nu' || displayTime.toLowerCase() === 'nu') {
- countdownText = 'Nu';
- countdownClass = 'now';
- } else if (minutesUntil < 5) {
- // Less than 5 minutes - red
- const minMatch = displayTime.match(/(\d+)\s*min/i);
- if (minMatch) {
- countdownText = minutesUntil === 1 ? '1 min' : `${minutesUntil} min`;
- } else {
- countdownText = minutesUntil === 1 ? '1 min' : `${minutesUntil} min`;
- }
- countdownClass = 'urgent'; // Red: less than 5 minutes
- } else {
- // 5+ minutes - white
- const isTimeOnly = /^\d{1,2}:\d{2}$/.test(displayTime);
- if (isTimeOnly) {
- countdownText = `${minutesUntil} min`;
- } else {
- // Use displayTime as-is (e.g., "5 min", "8 min")
- countdownText = displayTime;
- }
- // No class = white (default)
- }
-
- timeElement.innerHTML = `${scheduledTime} (${countdownText})`;
-
- timesContainer.appendChild(timeElement);
- });
-
- // If there are more departures, show a count
- if (group.departures.length > maxTimes) {
- const moreElement = document.createElement('span');
- moreElement.style.fontSize = '0.8em';
- moreElement.style.color = '#666';
- moreElement.textContent = `+${group.departures.length - maxTimes} more`;
- timesContainer.appendChild(moreElement);
- }
-
- header.appendChild(timesContainer);
- groupCard.appendChild(header);
-
- // No need to add destination and direction separately as they're now in the header
-
- // Add to container
- container.appendChild(groupCard);
- });
-}
-
-// Format date and time
-function formatDateTime(dateTimeString) {
- const date = new Date(dateTimeString);
- return date.toLocaleTimeString('sv-SE', { hour: '2-digit', minute: '2-digit' });
-}
-
-// Format relative time (e.g., "in 5 minutes")
-function formatRelativeTime(dateTimeString) {
- const departureTime = new Date(dateTimeString);
- const now = new Date();
- const diffMinutes = Math.round((departureTime - now) / (1000 * 60));
-
- if (diffMinutes <= 0) {
- return 'Nu';
- } else if (diffMinutes === 1) {
- return 'In 1 minute';
- } else if (diffMinutes < 60) {
- return `In ${diffMinutes} minutes`;
- } else {
- const hours = Math.floor(diffMinutes / 60);
- const minutes = diffMinutes % 60;
- if (minutes === 0) {
- return `In ${hours} hour${hours > 1 ? 's' : ''}`;
- } else {
- return `In ${hours} hour${hours > 1 ? 's' : ''} and ${minutes} minute${minutes > 1 ? 's' : ''}`;
- }
- }
-}
-
-// Group departures by line number
-function groupDeparturesByLineNumber(departures) {
- const groups = {};
-
- departures.forEach(departure => {
- const lineNumber = departure.line.designation;
-
- if (!groups[lineNumber]) {
- groups[lineNumber] = {
- line: departure.line,
- directions: {}
- };
- }
-
- // Get direction_code from API: 1 = going TO that direction, 2 = going FROM that direction
- const departureDirection = departure.direction_code !== undefined ? departure.direction_code :
- departure.directionCode !== undefined ? departure.directionCode :
- departure.direction !== undefined ? departure.direction :
- 1; // Default to 1 (left arrow) if not found
-
- const directionKey = `${departureDirection}-${departure.destination}`;
-
- if (!groups[lineNumber].directions[directionKey]) {
- groups[lineNumber].directions[directionKey] = {
- direction: departureDirection,
- destination: departure.destination,
- departures: []
- };
- }
-
- groups[lineNumber].directions[directionKey].departures.push(departure);
- });
-
- // Convert to array format and sort directions by direction_code (1 first, then 2)
- return Object.entries(groups).map(([lineNumber, data]) => {
- // Sort directions: direction 1 first, then direction 2
- const directionsArray = Object.values(data.directions);
- directionsArray.sort((a, b) => {
- // Sort by direction_code: 1 comes before 2
- const dirA = a.direction || 1;
- const dirB = b.direction || 1;
- return dirA - dirB;
- });
-
- return {
- lineNumber: lineNumber,
- line: data.line,
- directions: directionsArray
- };
- });
-}
-
-// Group departures by direction (legacy function kept for compatibility)
-function groupDeparturesByDirection(departures) {
- const groups = {};
-
- departures.forEach(departure => {
- const key = `${departure.line.designation}-${departure.direction}-${departure.destination}`;
-
- if (!groups[key]) {
- groups[key] = {
- line: departure.line,
- direction: departure.direction,
- destination: departure.destination,
- departures: []
- };
- }
-
- groups[key].departures.push(departure);
- });
-
- return Object.values(groups);
-}
-
-// Store the current departures data for comparison
-let currentDepartures = [];
-
-// Display departures in the UI with smooth transitions
-function displayDepartures(departures) {
- if (!departures || departures.length === 0) {
- departuresContainer.innerHTML = '
No departures found
';
- return;
- }
-
- // If this is the first load, just display everything
- if (currentDepartures.length === 0) {
- departuresContainer.innerHTML = '';
-
- departures.forEach(departure => {
- const departureCard = createDepartureCard(departure);
- departuresContainer.appendChild(departureCard);
- });
- } else {
- // Update only what has changed
- updateExistingCards(departures);
- }
-
- // Update the current departures for next comparison
- currentDepartures = JSON.parse(JSON.stringify(departures));
-}
-
-// Update existing cards or add new ones
-function updateExistingCards(newDepartures) {
- // Get all current cards
- const currentCards = departuresContainer.querySelectorAll('.departure-card');
- const currentCardIds = Array.from(currentCards).map(card => card.dataset.journeyId);
-
- // Process each new departure
- newDepartures.forEach((departure, index) => {
- const journeyId = departure.journey.id;
- const existingCardIndex = currentCardIds.indexOf(journeyId.toString());
-
- if (existingCardIndex !== -1) {
- // Update existing card
- const existingCard = currentCards[existingCardIndex];
- updateCardContent(existingCard, departure);
- } else {
- // This is a new departure, add it
- const newCard = createDepartureCard(departure);
-
- // Add with fade-in effect
- newCard.style.opacity = '0';
-
- if (index === 0) {
- // Add to the beginning
- departuresContainer.prepend(newCard);
- } else if (index >= departuresContainer.children.length) {
- // Add to the end
- departuresContainer.appendChild(newCard);
- } else {
- // Insert at specific position
- departuresContainer.insertBefore(newCard, departuresContainer.children[index]);
- }
-
- // Trigger fade-in
- setTimeout(() => {
- newCard.style.transition = 'opacity 0.5s ease-in';
- newCard.style.opacity = '1';
- }, 10);
- }
- });
-
- // Remove cards that are no longer in the new data
- const newDepartureIds = newDepartures.map(d => d.journey.id.toString());
- currentCards.forEach(card => {
- if (!newDepartureIds.includes(card.dataset.journeyId)) {
- // Fade out and remove
- card.style.transition = 'opacity 0.5s ease-out';
- card.style.opacity = '0';
- setTimeout(() => {
- if (card.parentNode) {
- card.parentNode.removeChild(card);
- }
- }, 500);
- }
- });
-}
-
-// Update only the content that has changed in an existing card
-function updateCardContent(card, departure) {
- const displayTime = departure.display;
- const departureTime = getDepartureTime(departure);
-
- // Calculate minutes until arrival using expected time (accounts for delays)
- const minutesUntil = calculateMinutesUntilArrival(departure);
- let countdownText = displayTime;
- let countdownClass = '';
-
- // Determine color class based on minutesUntil, regardless of displayTime format
- if (minutesUntil <= 0 || displayTime === 'Nu' || displayTime.toLowerCase() === 'nu') {
- countdownText = 'Nu';
- countdownClass = 'now';
- } else if (minutesUntil < 5) {
- // Less than 5 minutes - red
- const minMatch = displayTime.match(/(\d+)\s*min/i);
- if (minMatch) {
- countdownText = minutesUntil === 1 ? '1 min' : `${minutesUntil} min`;
- } else {
- countdownText = minutesUntil === 1 ? '1 min' : `${minutesUntil} min`;
- }
- countdownClass = 'urgent'; // Red: less than 5 minutes
- } else {
- // 5+ minutes - white
- const isTimeOnly = /^\d{1,2}:\d{2}$/.test(displayTime);
- if (isTimeOnly) {
- countdownText = `${minutesUntil} min`;
- } else {
- // Use displayTime as-is (e.g., "5 min", "8 min")
- countdownText = displayTime;
- }
- // No class = white (default)
- }
-
- // Only update the countdown time which changes frequently
- const countdownElement = card.querySelector('.countdown');
-
- // Update class for "now" and "urgent" states
- if (countdownElement) {
- // Remove all state classes first
- countdownElement.classList.remove('now', 'urgent');
-
- // Add the appropriate class
- if (countdownClass === 'now') {
- countdownElement.classList.add('now');
- } else if (countdownClass === 'urgent') {
- countdownElement.classList.add('urgent');
- }
-
- // Update with subtle highlight effect for changes
- if (countdownElement.textContent !== `(${countdownText})`) {
- countdownElement.textContent = `(${countdownText})`;
- highlightElement(countdownElement);
- }
- }
-}
-
-// Add a subtle highlight effect to show updated content
-function highlightElement(element) {
- element.style.transition = 'none';
- element.style.backgroundColor = 'rgba(255, 255, 0, 0.3)';
-
- setTimeout(() => {
- element.style.transition = 'background-color 1.5s ease-out';
- element.style.backgroundColor = 'transparent';
- }, 10);
-}
-
-// Display multiple sites
-function displayMultipleSites(sites) {
- // Get configuration
- const config = getConfig();
- const enabledSites = config.sites.filter(site => site.enabled);
-
- // Clear the container
- departuresContainer.innerHTML = '';
-
- // Process each site
- sites.forEach(site => {
- // Check if this site is enabled in the configuration
- const siteConfig = enabledSites.find(s => s.id === site.siteId);
- if (!siteConfig) return;
-
- // Create a site container
- const siteContainer = document.createElement('div');
- siteContainer.className = 'site-container';
-
- // Add site header with white tab
- const siteHeader = document.createElement('div');
- siteHeader.className = 'site-header';
- siteHeader.innerHTML = `${site.siteName || siteConfig.name}`;
- siteContainer.appendChild(siteHeader);
-
- // Process departures for this site
- if (site.data && site.data.departures) {
- // Group departures by line number using the existing function
- const lineGroups = groupDeparturesByLineNumber(site.data.departures);
-
- // Use the new card-based layout function
- displayGroupedDeparturesByLine(lineGroups, siteContainer);
- } else if (site.error) {
- // Display error for this site
- const errorElement = document.createElement('div');
- errorElement.className = 'error';
- errorElement.textContent = `Error loading departures for ${site.siteName}: ${site.error}`;
- siteContainer.appendChild(errorElement);
- }
-
- // Add the site container to the main container
- departuresContainer.appendChild(siteContainer);
- });
-}
-
-// Get configuration
-function getConfig() {
- // Default configuration
- const defaultConfig = {
- combineSameDirection: true,
- sites: [
- {
- id: '1411',
- name: 'Ambassaderna',
- enabled: true
- }
- ]
- };
-
- // If we have a ConfigManager instance, use its config
- if (window.configManager && window.configManager.config) {
- return {
- combineSameDirection: window.configManager.config.combineSameDirection !== undefined ?
- window.configManager.config.combineSameDirection : defaultConfig.combineSameDirection,
- sites: window.configManager.config.sites || defaultConfig.sites
- };
- }
-
- return defaultConfig;
-}
-
-// Fetch departures from our proxy server
-async function fetchDepartures() {
- try {
- // Don't show loading status to avoid layout disruptions
- // statusElement.textContent = 'Loading departures...';
-
- const response = await fetch(API_URL);
- if (!response.ok) {
- throw new Error(`HTTP error! Status: ${response.status}`);
- }
-
- const data = await response.json();
-
- if (data.sites && Array.isArray(data.sites)) {
- // Process multiple sites
- displayMultipleSites(data.sites);
-
- const now = new Date();
- lastUpdatedElement.textContent = `Last updated: ${now.toLocaleTimeString('sv-SE')}`;
- } else if (data.departures) {
- // Legacy format - single site
- displayDepartures(data.departures);
-
- const now = new Date();
- lastUpdatedElement.textContent = `Last updated: ${now.toLocaleTimeString('sv-SE')}`;
- } else if (data.error) {
- throw new Error(data.error);
- } else {
- throw new Error('Invalid response format from server');
- }
-
- } catch (error) {
- console.error('Error fetching departures:', error);
- // Don't update status element to avoid layout disruptions
- // statusElement.textContent = '';
- departuresContainer.innerHTML = `
-
-
Failed to load departures. Please try again later.
-
Error: ${error.message}
-
Make sure the Node.js server is running: node server.js
-
- `;
- }
-}
-
-// Set up auto-refresh
-function setupAutoRefresh() {
- // Clear any existing timer
- if (refreshTimer) {
- clearInterval(refreshTimer);
- }
-
- // Set up new timer
- refreshTimer = setInterval(fetchDepartures, REFRESH_INTERVAL);
-}
-
-// Initialize departures functionality
-function initDepartures() {
- // API endpoint (using our local proxy server)
- window.API_URL = 'http://localhost:3002/api/departures';
-
- // DOM elements
- window.departuresContainer = document.getElementById('departures');
- window.statusElement = document.getElementById('status');
- window.lastUpdatedElement = document.getElementById('last-updated');
-
- // Auto-refresh interval (in milliseconds) - 5 seconds
- window.REFRESH_INTERVAL = 5000;
- window.refreshTimer = null;
-
- // Initial fetch and setup
- fetchDepartures();
- setupAutoRefresh();
-}
-
-// Initialize when the DOM is loaded
-document.addEventListener('DOMContentLoaded', function() {
- initDepartures();
-});
diff --git a/API_RESPONSE_DOCUMENTATION.md b/docs/API_RESPONSE_DOCUMENTATION.md
similarity index 100%
rename from API_RESPONSE_DOCUMENTATION.md
rename to docs/API_RESPONSE_DOCUMENTATION.md
diff --git a/documentation.md b/documentation.md
deleted file mode 100644
index 589cef4..0000000
--- a/documentation.md
+++ /dev/null
@@ -1,275 +0,0 @@
-# SL Transport Departures Display System Documentation
-
-## System Overview
-
-This is a comprehensive digital signage system designed to display transit departures and weather information. The system is built with a modular architecture, making it easy to maintain and extend. It's specifically designed to work well on a Raspberry Pi for dedicated display purposes.
-
-## Architecture
-
-The system consists of the following components:
-
-1. **Node.js Server** - Handles API proxying and serves static files
-2. **Configuration Manager** - Manages system settings and UI customization
-3. **Weather Component** - Displays weather data and manages dark mode
-4. **Clock Component** - Shows current time and date
-5. **Departures Component** - Displays transit departure information
-6. **Main UI** - Responsive layout with multiple orientation support
-
-## File Structure
-
-- `index.html` - Main HTML file containing the UI structure and inline JavaScript
-- `server.js` - Node.js server for API proxying and static file serving
-- `config.js` - Configuration management module
-- `weather.js` - Weather display and dark mode management
-- `clock.js` - Time and date display
-- `departures.js` - Transit departure display component
-
-## Detailed Component Documentation
-
-### 1. Node.js Server (server.js)
-
-The server component acts as a proxy for external APIs and serves the static files for the application.
-
-#### Key Features:
-
-- **Port**: Runs on port 3002
-- **API Proxying**:
- - `/api/departures` - Proxies requests to SL Transport API
-- **Error Handling**: Provides structured error responses
-- **Static File Serving**: Serves HTML, CSS, JavaScript, and image files
-- **CORS Support**: Allows cross-origin requests
-
-#### API Endpoints:
-
-- `GET /api/departures` - Returns transit departure information
-- `GET /` or `/index.html` - Serves the main application
-- `GET /*.js|css|png|jpg|jpeg|gif|ico` - Serves static assets
-
-#### Implementation Details:
-
-The server handles malformed JSON responses from the SL Transport API by implementing custom JSON parsing and fixing. It also provides fallback data when API requests fail.
-
-### 2. Configuration Manager (config.js)
-
-The Configuration Manager handles all system settings and provides a UI for changing them.
-
-#### Key Features:
-
-- **Screen Orientation**: Controls display rotation (0°, 90°, 180°, 270°, landscape)
-- **Dark Mode**: Automatic (based on sunrise/sunset), always on, or always off
-- **Background Image**: Custom background with opacity control
-- **Settings Persistence**: Saves settings to localStorage
-- **Configuration UI**: Modal-based interface with live previews
-
-#### Configuration Options:
-
-- `orientation`: Screen orientation (`normal`, `vertical`, `upsidedown`, `vertical-reverse`, `landscape`)
-- `darkMode`: Dark mode setting (`auto`, `on`, `off`)
-- `backgroundImage`: URL or data URL of background image
-- `backgroundOpacity`: Opacity value between 0 and 1
-
-#### Implementation Details:
-
-The ConfigManager class creates a gear icon button that opens a modal dialog for changing settings. It applies settings immediately and dispatches events to notify other components of changes.
-
-### 3. Weather Component (weather.js)
-
-The Weather component displays current weather conditions, forecasts, and manages dark mode based on sunrise/sunset times.
-
-#### Key Features:
-
-- **Current Weather**: Temperature, condition, and icon
-- **Hourly Forecast**: Weather predictions for upcoming hours
-- **Sunrise/Sunset**: Calculates and displays sun times
-- **Dark Mode Control**: Automatically switches between light/dark based on sun position
-- **API Integration**: Uses OpenWeatherMap API
-- **Fallback Data**: Provides default weather data when API is unavailable
-
-#### Implementation Details:
-
-The WeatherManager class fetches data from OpenWeatherMap API and updates the UI. It calculates sunrise/sunset times and uses them to determine if dark mode should be enabled. It dispatches events when dark mode changes.
-
-### 4. Clock Component (clock.js)
-
-The Clock component displays the current time and date.
-
-#### Key Features:
-
-- **Time Display**: Shows current time in HH:MM:SS format
-- **Date Display**: Shows current date with weekday, month, day, and year
-- **Timezone Support**: Configured for Stockholm timezone
-- **Auto-Update**: Updates every second
-- **Optional Time Sync**: Can synchronize with WorldTimeAPI
-
-#### Implementation Details:
-
-The Clock class creates and updates time and date elements. It uses the browser's Date object with the specified timezone and formats the output using toLocaleTimeString and toLocaleDateString.
-
-### 5. Departures Component (departures.js)
-
-The Departures component displays transit departure information from the SL Transport API.
-
-#### Key Features:
-
-- **Real-time Updates**: Fetches departure data periodically
-- **Multiple Sites**: Supports displaying departures from multiple transit stops
-- **Grouped Display**: Groups departures by line and direction
-- **Countdown Timers**: Shows time until departure
-
-### 6. Main UI (index.html)
-
-The main UI integrates all components and provides responsive layouts for different screen orientations.
-
-#### Key Features:
-
-- **Responsive Design**: Adapts to different screen sizes and orientations
-- **Dark Mode Support**: Changes colors based on dark mode setting
-- **Departure Cards**: Displays transit departures with line numbers, destinations, and times
-- **Weather Widget**: Shows current conditions and forecast
-- **Auto-Refresh**: Periodically updates departure information
-
-#### Implementation Details:
-
-The HTML file contains the structure and styling for the application. It initializes all components and sets up event listeners for updates. The JavaScript in the file handles fetching and displaying departure information.
-
-## Setup Instructions
-
-### Prerequisites:
-
-- Node.js installed
-- Internet connection for API access
-- Browser with CSS3 support
-
-### Installation Steps:
-
-1. Clone or download all files to a directory
-2. Run `node server.js` to start the server
-3. Access the application at `http://localhost:3002`
-
-### Raspberry Pi Setup:
-
-1. Install Node.js on Raspberry Pi
-2. Copy all files to a directory on the Pi
-3. Set up auto-start for the server:
- ```
- # Create a systemd service file
- sudo nano /etc/systemd/system/sl-departures.service
-
- # Add the following content
- [Unit]
- Description=SL Departures Display
- After=network.target
-
- [Service]
- ExecStart=/usr/bin/node /path/to/server.js
- WorkingDirectory=/path/to/directory
- Restart=always
- User=pi
-
- [Install]
- WantedBy=multi-user.target
- ```
-4. Enable and start the service:
- ```
- sudo systemctl enable sl-departures
- sudo systemctl start sl-departures
- ```
-5. Configure Raspberry Pi to auto-start Chromium in kiosk mode:
- ```
- # Edit autostart file
- mkdir -p ~/.config/autostart
- nano ~/.config/autostart/kiosk.desktop
-
- # Add the following content
- [Desktop Entry]
- Type=Application
- Name=Kiosk
- Exec=chromium-browser --kiosk --disable-restore-session-state http://localhost:3002
- ```
-
-## Troubleshooting
-
-### Common Issues:
-
-1. **Server won't start**
- - Check if port 3002 is already in use
- - Ensure Node.js is installed correctly
-
-2. **No departures displayed**
- - Verify internet connection
- - Check server console for API errors
- - Ensure the site ID is correct (currently set to 9636)
-
-3. **Weather data not loading**
- - Check OpenWeatherMap API key
- - Verify internet connection
- - Look for errors in browser console
-
- - Look for JavaScript errors in console
-
-5. **Screen orientation issues**
- - Ensure the content wrapper is properly created
- - Check for CSS conflicts
- - Verify browser supports CSS transforms
-
-## Customization Guide
-
-### Changing Transit Stop:
-
-To display departures for a different transit stop, modify the API_URL in server.js:
-
-```javascript
-const API_URL = 'https://transport.integration.sl.se/v1/sites/YOUR_SITE_ID/departures';
-```
-
-### Changing Weather Location:
-
-To display weather for a different location, modify the latitude and longitude in index.html:
-
-```javascript
-window.weatherManager = new WeatherManager({
- latitude: YOUR_LATITUDE,
- longitude: YOUR_LONGITUDE
-});
-```
-
-### Adding Custom Styles:
-
-Add custom CSS to the style section in index.html to modify the appearance.
-
-## System Architecture Diagram
-
-```
-+---------------------+ +----------------------+
-| | | |
-| Browser Interface |<----->| Node.js Server |
-| (index.html) | | (server.js) |
-| | | |
-+---------------------+ +----------------------+
- ^ ^
- | |
- v v
-+---------------------+ +----------------------+
-| | | |
-| UI Components | | External APIs |
-| - Clock | | - SL Transport API |
-| - Weather | | - OpenWeatherMap |
-| - Departures | | |
-| - Config Manager | | |
-+---------------------+ +----------------------+
-```
-
-## Component Interaction Flow
-
-1. User loads the application in a browser
-2. Node.js server serves the HTML, CSS, and JavaScript files
-3. Browser initializes all components (Clock, Weather, Config, Departures)
-4. Components make API requests through the Node.js server
-5. Server proxies requests to external APIs and returns responses
-6. Components update their UI based on the data
-7. User can change settings through the Config Manager
-8. Settings are applied immediately and saved to localStorage
-
-## Conclusion
-
-This documentation provides a comprehensive overview of the SL Transport Departures Display System. With this information, you should be able to understand, maintain, and recreate the system if needed.
diff --git a/index.html b/index.html
index aa2891c..dc3eb78 100644
--- a/index.html
+++ b/index.html
@@ -1,1618 +1,38 @@
-
+
SL Transport Departures - Ambassaderna (1411)
-
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -1648,7 +68,7 @@
Clear
-
7.1 °C
+
7.1 °C
@@ -1656,53 +76,53 @@
-
7.1 °C
+
7.1 °C
19:00
-
6.8 °C
+
6.8 °C
20:00
-
6.5 °C
+
6.5 °C
21:00
-
6.2 °C
+
6.2 °C
22:00
-
6.0 °C
+
6.0 °C
23:00
-
5.8 °C
+
5.8 °C
00:00
-
5.5 °C
+
5.5 °C
- ☀️ Sunrise: 06:45 AM | 🌙 Sunset: 05:32 PM
+ â˜€ï¸ Sunrise: 06:45 AM | 🌙 Sunset: 05:32 PM