add settings locations
Some checks failed
/ build (push) Has been cancelled

This commit is contained in:
Carsten Graf
2025-09-08 22:30:15 +02:00
parent 55eb062d2c
commit 173b13fcfc
13 changed files with 940 additions and 247 deletions

106
.gitignore vendored
View File

@@ -1,6 +1,104 @@
.pio # PlatformIO
.pio/
.pioenvs/
.piolibdeps/
.platformio/
platformio.ini.bak
# Build directories
build/
.vscode/
# IDE files
*.swp
*.swo
*~
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Node.js (falls du Node.js Tools verwendest)
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Logs
*.log
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
# nyc test coverage
.nyc_output
# Dependency directories
jspm_packages/
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env .env
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json # IDE specific files
.vscode/settings.json
.vscode/launch.json .vscode/launch.json
.vscode/ipch .vscode/extensions.json
.idea/
*.iml
*.ipr
*.iws
# Temporary files
*.tmp
*.temp
# Compiled files
*.o
*.obj
*.exe
*.dll
*.so
*.dylib
# Firmware files (optional - falls du sie nicht versionieren willst)
# *.bin
# *.hex
# Backup files
*.bak
*.backup
# Archive files
*.zip
*.tar.gz
*.rar
# MCP related files (falls nicht benötigt)
gitea-mcp.exe
gitea-mcp.zip
# Local configuration files
config.local.*

4
API.md
View File

@@ -90,6 +90,4 @@ All API endpoints return JSON unless otherwise noted.
--- ---
**All API endpoints return JSON unless otherwise noted. POST requests expect form parameters (not JSON body).** **All API endpoints return JSON unless otherwise noted. POST requests expect form parameters (not JSON body).**
Let me know if you need details on request/response formats

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 The Gitea Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

245
README.md
View File

@@ -1,28 +1,233 @@
# Ninjacross Timer ⏱️ # Gitea MCP Server
Ein präziser, drahtloser Timer für Ninjacross- und Schwimmwettbewerbe. Entwickelt für Trainings- und Wettkampfumgebungen, bei denen Geschwindigkeit, Zuverlässigkeit und Benutzerfreundlichkeit entscheidend sind. [繁體中文](README.zh-tw.md) | [简体中文](README.zh-cn.md)
## 🔧 Funktionen **Gitea MCP Server** is an integration plugin designed to connect Gitea with Model Context Protocol (MCP) systems. This allows for seamless command execution and repository management through an MCP-compatible chat interface.
- **0.1 s Genauigkeit** bei der Zeitmessung [![Install with Docker in VS Code](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}) [![Install with Docker in VS Code Insiders](https://img.shields.io/badge/VS_Code_Insiders-Install_Server-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=gitea&inputs=[{%22id%22:%22gitea_token%22,%22type%22:%22promptString%22,%22description%22:%22Gitea%20Personal%20Access%20Token%22,%22password%22:true}]&config={%22command%22:%22docker%22,%22args%22:[%22run%22,%22-i%22,%22--rm%22,%22-e%22,%22GITEA_ACCESS_TOKEN%22,%22docker.gitea.com/gitea-mcp-server%22],%22env%22:{%22GITEA_ACCESS_TOKEN%22:%22${input:gitea_token}%22}}&quality=insiders)
- **Drahtlose Kommunikation** über ESP-NOW oder Wi-Fi Mesh
- **Mehrere Timer-Zonen** (z.B. Start/Stop für zwei Bahnen)
- **Visualisierung in Echtzeit** auf einem zentralen Raspberry Pi Dashboard
- **Großanzeige** per 7-Segment-Display oder Browseranzeige
- **Einfache Bedienung** über robuste Hardware-Taster
- **Erweiterbar** für mehrere Bahnen und Disziplinen
## 🛠️ Hardware-Komponenten ## Table of Contents
- ESP32 Mikrocontroller (pro Button oder Sensor ein Gerät) - [Gitea MCP Server](#gitea-mcp-server)
- ESP32 Master mit MQTT Broker (zentrale Steuerung und Webserver) - [Table of Contents](#table-of-contents)
- Taster oder Lichtschranken - [What is Gitea?](#what-is-gitea)
- Optional: 7-Segment-Displays oder HDMI-Display - [What is MCP?](#what-is-mcp)
- Stabile WLAN-Verbindung (z.B. Wi-Fi Mesh) - [🚧 Installation](#-installation)
- [Usage with VS Code](#usage-with-vs-code)
- [📥 Download the official binary release](#-download-the-official-binary-release)
- [🔧 Build from Source](#-build-from-source)
- [📁 Add to PATH](#-add-to-path)
- [🚀 Usage](#-usage)
- [✅ Available Tools](#-available-tools)
- [🐛 Debugging](#-debugging)
- [🛠 Troubleshooting](#-troubleshooting)
## 📦 Aufbau ## What is Gitea?
Gitea is a community-managed lightweight code hosting solution written in Go. It is published under the MIT license. Gitea provides Git hosting including a repository viewer, issue tracking, pull requests, and more.
## What is MCP?
Model Context Protocol (MCP) is a protocol that allows for the integration of various tools and systems through a chat interface. It enables seamless command execution and management of repositories, users, and other resources.
## 🚧 Installation
### Usage with VS Code
For quick installation, use one of the one-click install buttons at the top of this README.
For manual installation, add the following JSON block to your User Settings (JSON) file in VS Code. You can do this by pressing `Ctrl + Shift + P` and typing `Preferences: Open User Settings (JSON)`.
Optionally, you can add it to a file called `.vscode/mcp.json` in your workspace. This will allow you to share the configuration with others.
> Note that the `mcp` key is not needed in the `.vscode/mcp.json` file.
```json
{
"mcp": {
"inputs": [
{
"type": "promptString",
"id": "gitea_token",
"description": "Gitea Personal Access Token",
"password": true
}
],
"servers": {
"gitea-mcp": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"GITEA_ACCESS_TOKEN",
"docker.gitea.com/gitea-mcp-server"
],
"env": {
"GITEA_ACCESS_TOKEN": "${input:gitea_token}"
}
}
}
}
}
```
### 📥 Download the official binary release
You can download the official release from [official Gitea MCP binary releases](https://gitea.com/gitea/gitea-mcp/releases).
### 🔧 Build from Source
You can download the source code by cloning the repository using Git:
```bash
git clone https://gitea.com/gitea/gitea-mcp.git
```
Before building, make sure you have the following installed:
- make
- Golang (Go 1.24 or later recommended)
Then run:
```bash
make install
```
### 📁 Add to PATH
After installing, copy the binary gitea-mcp to a directory included in your system's PATH. For example:
```bash
cp gitea-mcp /usr/local/bin/
```
## 🚀 Usage
This example is for Cursor, you can also use plugins in VSCode.
To configure the MCP server for Gitea, add the following to your MCP configuration file:
- **stdio mode**
```json
{
"mcpServers": {
"gitea": {
"command": "gitea-mcp",
"args": [
"-t",
"stdio",
"--host",
"https://gitea.com"
// "--token", "<your personal access token>"
],
"env": {
// "GITEA_HOST": "https://gitea.com",
// "GITEA_INSECURE": "true",
"GITEA_ACCESS_TOKEN": "<your personal access token>"
}
}
}
}
```
- **sse mode**
```json
{
"mcpServers": {
"gitea": {
"url": "http://localhost:8080/sse"
}
}
}
```
- **http mode**
```json
{
"mcpServers": {
"gitea": {
"url": "http://localhost:8080/mcp"
}
}
}
```
**Default log path**: `$HOME/.gitea-mcp/gitea-mcp.log`
> [!NOTE]
> You can provide your Gitea host and access token either as command-line arguments or environment variables.
> Command-line arguments have the highest priority
Once everything is set up, try typing the following in your MCP-compatible chatbox:
```text ```text
[ESP32-Startbutton] --\ list all my repositories
---> WLAN --> [ESP32 Master] --> [Browseranzeige / Display] ```
[ESP32-Stopbutton ] --/
## ✅ Available Tools
The Gitea MCP Server supports the following tools:
| Tool | Scope | Description |
| :--------------------------: | :----------: | :------------------------------------------------------: |
| get_my_user_info | User | Get the information of the authenticated user |
| get_user_orgs | User | Get organizations associated with the authenticated user |
| create_repo | Repository | Create a new repository |
| fork_repo | Repository | Fork a repository |
| list_my_repos | Repository | List all repositories owned by the authenticated user |
| create_branch | Branch | Create a new branch |
| delete_branch | Branch | Delete a branch |
| list_branches | Branch | List all branches in a repository |
| create_release | Release | Create a new release in a repository |
| delete_release | Release | Delete a release from a repository |
| get_release | Release | Get a release |
| get_latest_release | Release | Get the latest release in a repository |
| list_releases | Release | List all releases in a repository |
| create_tag | Tag | Create a new tag |
| delete_tag | Tag | Delete a tag |
| get_tag | Tag | Get a tag |
| list_tags | Tag | List all tags in a repository |
| list_repo_commits | Commit | List all commits in a repository |
| get_file_content | File | Get the content and metadata of a file |
| get_dir_content | File | Get a list of entries in a directory |
| create_file | File | Create a new file |
| update_file | File | Update an existing file |
| delete_file | File | Delete a file |
| get_issue_by_index | Issue | Get an issue by its index |
| list_repo_issues | Issue | List all issues in a repository |
| create_issue | Issue | Create a new issue |
| create_issue_comment | Issue | Create a comment on an issue |
| edit_issue | Issue | Edit a issue |
| edit_issue_comment | Issue | Edit a comment on an issue |
| get_issue_comments_by_index | Issue | Get comments of an issue by its index |
| get_pull_request_by_index | Pull Request | Get a pull request by its index |
| list_repo_pull_requests | Pull Request | List all pull requests in a repository |
| create_pull_request | Pull Request | Create a new pull request |
| search_users | User | Search for users |
| search_org_teams | Organization | Search for teams in an organization |
| search_repos | Repository | Search for repositories |
| get_gitea_mcp_server_version | Server | Get the version of the Gitea MCP Server |
## 🐛 Debugging
To enable debug mode, add the `-d` flag when running the Gitea MCP Server with sse mode:
```sh
./gitea-mcp -t sse [--port 8080] --token <your personal access token> -d
```
## 🛠 Troubleshooting
If you encounter any issues, here are some common troubleshooting steps:
1. **Check your PATH**: Ensure that the `gitea-mcp` binary is in a directory included in your system's PATH.
2. **Verify dependencies**: Make sure you have all the required dependencies installed, such as `make` and `Golang`.
3. **Review configuration**: Double-check your MCP configuration file for any errors or missing information.
4. **Consult logs**: Check the logs for any error messages or warnings that can provide more information about the issue.
Enjoy exploring and managing your Gitea repositories via chat!

78
THIRD_PARTY_LICENSES.md Normal file
View File

@@ -0,0 +1,78 @@
## Third-Party Licenses and Notices
This project uses thirdparty libraries. Below is a summary of their licenses and the key obligations when you distribute firmware/binaries that include them.
### Summary of obligations
- Keep original copyright and license notices.
- Include this file (or equivalent notices) with any distribution.
- For LGPLlicensed components (ESPAsyncWebServer, AsyncTCP):
- You are not required to publish your entire application.
- If you distribute binaries, you must provide a way for users to relink the application with a modified version of the LGPL library (e.g., provide object files of your application or the full source code), publish any changes you made to the LGPL libs, and include the LGPL license text.
- PrettyOTA has a custom permissive license with attribution and no rebranding without a commercial license.
---
### Dependency overview
| Library | Version (as configured) | License | Project | License Text |
|---|---|---|---|---|
| ArduinoJson | ^7.4.1 | MIT | [bblanchon/ArduinoJson](https://github.com/bblanchon/ArduinoJson) | [LICENSE](https://github.com/bblanchon/ArduinoJson/blob/v7.4.1/LICENSE.md) |
| ESPAsyncWebServer (esp32async) | ^3.7.7 | LGPL3.0 | [esp32async/ESPAsyncWebServer](https://github.com/esp32async/ESPAsyncWebServer) | [LICENSE](https://github.com/esp32async/ESPAsyncWebServer/blob/master/LICENSE) |
| AsyncTCP (esp32async) | ^3.4.2 | LGPL3.0 | [esp32async/AsyncTCP](https://github.com/esp32async/AsyncTCP) | [LICENSE](https://github.com/esp32async/AsyncTCP/blob/master/LICENSE) |
| PicoMQTT | ^1.3.0 | MIT | [mlesniew/PicoMQTT](https://github.com/mlesniew/PicoMQTT) | [LICENSE](https://github.com/mlesniew/PicoMQTT/blob/master/LICENSE) |
| MFRC522 | ^1.4.12 | MIT | [miguelbalboa/rfid](https://github.com/miguelbalboa/rfid) | [LICENSE](https://github.com/miguelbalboa/rfid/blob/master/LICENSE) |
| RTClib | ^2.1.4 | MIT | [adafruit/RTClib](https://github.com/adafruit/RTClib) | [LICENSE](https://github.com/adafruit/RTClib/blob/master/license.txt) |
| PrettyOTA (vendored) | included | Custom (see below) | Included in `lib/PrettyOTA` | See “PrettyOTA License” below |
---
### Notes on LGPL3.0 components (ESPAsyncWebServer, AsyncTCP)
If you distribute firmware that statically links these libraries (typical on microcontrollers):
- Provide a method for relinking your application with a modified version of the LGPL library. Practically, either:
- Provide object files (.o/.a) of your application so users can relink against a modified LGPL lib, or
- Publish your full application source code (voluntary but simpler), or
- Replace these libraries with permissive alternatives to avoid LGPL obligations.
- Publish any changes you made to the LGPL libraries themselves.
- Include the full text of the LGPL3.0 license with your distribution.
For many teams, the simplest path is to provide application object files or to switch to a permissively licensed HTTP/WebServer.
---
### PrettyOTA License (full text)
The PrettyOTA component is included under the following license. This license imposes attribution requirements and restricts removing/replacing the name/logo without a separate commercial license.
```
# License
Copyright (c) 2025 Marc Schöndorf
Permission is granted to anyone to use this software for private and commercial applications, to alter it and redistribute it, subject to the following conditions:
1. The origin of this software must not be misrepresented. You must not
claim that you wrote the original software. If you use this Software in a product, acknowledgment in the product documentation or credits is required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. You are not permitted to modify, replace or remove the name "PrettyOTA" or the original logo displayed within the Software's default user interface (if applicable), unless you have obtained a separate commercial license granting you such rights. This restriction applies even when redistributing modified versions of the source code.
4. This license notice must not be removed or altered from any source code distribution.
**Disclaimer:**
The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and non-infringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.
## Commercial Licensing
A separate commercial license is required for specific rights not granted herein, particularly for white-labeling or rebranding (using a different name or logo). Please refer to the README file or contact the copyright holder for details on obtaining a commercial license.
```
---
### Recommended distribution checklist
- Include this `THIRD_PARTY_LICENSES.md` with your firmware or product documentation.
- Include the full LGPL3.0 license text if you distribute firmware using ESPAsyncWebServer/AsyncTCP.
- Provide either application object files for relinking or publish source (to satisfy LGPL).
- Keep all copyright and license notices intact in UI/docs where applicable (e.g., PrettyOTA attribution).

View File

@@ -1,4 +1,4 @@
<!doctype html> <!DOCTYPE html>
<html lang="de"> <html lang="de">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
@@ -124,7 +124,7 @@
// Globale Variablen // Globale Variablen
let rfidData = []; let rfidData = [];
let isLoading = false; let isLoading = false;
let DBUrl = "db.reptilfpv.de:3000"; let DBUrl = "ninja.reptilfpv.de:3000";
var APIKey; var APIKey;
// Maximales Datum auf heute setzen // Maximales Datum auf heute setzen
@@ -166,7 +166,7 @@
ageDisplay.style.display = "none"; ageDisplay.style.display = "none";
if (age < 0) { if (age < 0) {
showErrorMessage( showErrorMessage(
"Das Geburtsdatum kann nicht in der Zukunft liegen!", "Das Geburtsdatum kann nicht in der Zukunft liegen!"
); );
e.target.value = ""; e.target.value = "";
} else { } else {
@@ -203,7 +203,7 @@
const alter = calculateAge(geburtsdatum); const alter = calculateAge(geburtsdatum);
if (alter < 0) { if (alter < 0) {
showErrorMessage( showErrorMessage(
"Das Geburtsdatum kann nicht in der Zukunft liegen!", "Das Geburtsdatum kann nicht in der Zukunft liegen!"
); );
return; return;
} }
@@ -217,6 +217,7 @@
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
...(APIKey && { Authorization: `Bearer ${APIKey}` }),
}, },
body: JSON.stringify({ body: JSON.stringify({
uid: uid, uid: uid,
@@ -243,13 +244,13 @@
} else { } else {
// Fehler anzeigen // Fehler anzeigen
showErrorMessage( showErrorMessage(
result.error || "Fehler beim Speichern der Daten", result.error || "Fehler beim Speichern der Daten"
); );
} }
} catch (error) { } catch (error) {
console.error("Fehler beim Speichern:", error); console.error("Fehler beim Speichern:", error);
showErrorMessage( showErrorMessage(
"Verbindungsfehler zum Server. Bitte versuchen Sie es später erneut.", "Verbindungsfehler zum Server. Bitte versuchen Sie es später erneut."
); );
} finally { } finally {
setLoadingState(false); setLoadingState(false);
@@ -355,6 +356,7 @@
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
...(APIKey && { Authorization: `Bearer ${APIKey}` }),
}, },
}); });
@@ -394,7 +396,7 @@
} catch (error) { } catch (error) {
console.error("Fehler beim Lesen der UID:", error); console.error("Fehler beim Lesen der UID:", error);
showErrorMessage( showErrorMessage(
"Verbindungsfehler zum RFID Reader. Bitte prüfen Sie die Verbindung.", "Verbindungsfehler zum RFID Reader. Bitte prüfen Sie die Verbindung."
); );
// UID Feld rot markieren // UID Feld rot markieren
@@ -412,12 +414,16 @@
async function checkServerStatus() { async function checkServerStatus() {
try { try {
const response = await fetch("/api/health"); const response = await fetch("/api/health", {
headers: {
...(APIKey && { Authorization: `Bearer ${APIKey}` }),
},
});
const data = await response.json(); const data = await response.json();
if (!data.status || data.status !== "connected") { if (!data.status || data.status !== "connected") {
showErrorMessage( showErrorMessage(
"Server nicht verbunden. Einige Funktionen könnten eingeschränkt sein.", "Server nicht verbunden. Einige Funktionen könnten eingeschränkt sein."
); );
return false; return false;
} }
@@ -437,7 +443,7 @@
APIKey = data.licence || ""; APIKey = data.licence || "";
}) })
.catch((error) => .catch((error) =>
showMessage("Fehler beim Laden der Lizenz", "error"), showMessage("Fehler beim Laden der Lizenz", "error")
); );
} }
</script> </script>

View File

@@ -279,33 +279,138 @@
text-align: center; text-align: center;
} }
.status-message { /* Modern Notification Toast */
margin-top: 20px; .notification-toast {
padding: 15px; position: fixed;
border-radius: 10px; top: 24px;
font-weight: 600; right: 24px;
text-align: center; min-width: 320px;
max-width: 400px;
background: rgba(255, 255, 255, 0.98);
border-radius: 16px;
box-shadow:
0 20px 25px -5px rgba(0, 0, 0, 0.1),
0 10px 10px -5px rgba(0, 0, 0, 0.04),
0 0 0 1px rgba(0, 0, 0, 0.05);
backdrop-filter: blur(20px);
z-index: 99999;
display: none; display: none;
align-items: flex-start;
gap: 12px;
padding: 16px;
transform: translateX(100%);
opacity: 0;
transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
pointer-events: auto;
border: 1px solid rgba(255, 255, 255, 0.2);
} }
.status-success { .notification-toast.show {
background: #d4edda; transform: translateX(0);
color: #155724; opacity: 1;
border: 2px solid #c3e6cb;
} }
.status-error { .notification-icon {
background: #f8d7da; flex-shrink: 0;
color: #721c24; width: 40px;
border: 2px solid #f5c6cb; height: 40px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
font-weight: 600;
color: white;
background: linear-gradient(135deg, #10b981, #059669);
} }
.status-info { .notification-body {
background: #cce7ff; flex: 1;
color: #004085; min-width: 0;
border: 2px solid #b3d9ff;
} }
.notification-title {
font-size: 14px;
font-weight: 600;
color: #111827;
margin-bottom: 4px;
line-height: 1.2;
}
.notification-message {
font-size: 13px;
color: #6b7280;
line-height: 1.4;
word-wrap: break-word;
}
.notification-close {
flex-shrink: 0;
width: 32px;
height: 32px;
border: none;
background: none;
color: #9ca3af;
cursor: pointer;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
margin-top: -4px;
margin-right: -4px;
}
.notification-close:hover {
background: rgba(0, 0, 0, 0.05);
color: #374151;
}
.notification-close:active {
transform: scale(0.95);
}
/* Toast Types */
.notification-toast.success .notification-icon {
background: linear-gradient(135deg, #10b981, #059669);
}
.notification-toast.error .notification-icon {
background: linear-gradient(135deg, #ef4444, #dc2626);
}
.notification-toast.info .notification-icon {
background: linear-gradient(135deg, #3b82f6, #2563eb);
}
.notification-toast.warning .notification-icon {
background: linear-gradient(135deg, #f59e0b, #d97706);
}
/* Animation */
@keyframes slideInRight {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOutRight {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(100%);
opacity: 0;
}
}
.learning-mode { .learning-mode {
display: none; display: none;
text-align: center; text-align: center;
@@ -417,4 +522,14 @@
border-right: none; border-right: none;
border-bottom: 1px solid #e9ecef; border-bottom: 1px solid #e9ecef;
} }
/* Mobile notification bubble adjustments */
.notification-bubble {
top: 10px;
right: 10px;
left: 10px;
max-width: none;
font-size: 14px;
padding: 12px 16px;
}
} }

View File

@@ -11,6 +11,22 @@
<title>Ninjacross Timer - Einstellungen</title> <title>Ninjacross Timer - Einstellungen</title>
</head> </head>
<body> <body>
<!-- Modern Notification Toast -->
<div id="notificationBubble" class="notification-toast" style="display: none;">
<div class="notification-icon">
<span id="notificationIcon"></span>
</div>
<div class="notification-body">
<div class="notification-title" id="notificationTitle">Erfolg</div>
<div class="notification-message" id="notificationText">Bereit</div>
</div>
<button class="notification-close" onclick="hideNotification()">
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
<path d="M8 8.707l3.646 3.647.708-.707L8.707 8l3.647-3.646-.707-.708L8 7.293 4.354 3.646l-.707.708L7.293 8l-3.646 3.646.707.708L8 8.707z"/>
</svg>
</button>
</div>
<div class="container"> <div class="container">
<!-- Header Section --> <!-- Header Section -->
<div class="header"> <div class="header">
@@ -25,9 +41,6 @@
<a href="/rfid" class="nav-button">📡 RFID</a> <a href="/rfid" class="nav-button">📡 RFID</a>
</div> </div>
<!-- Status Message Container -->
<div id="statusMessage" class="status-message"></div>
<!-- Date & Time Section --> <!-- Date & Time Section -->
<div class="section"> <div class="section">
<h2>🕐 Datum & Uhrzeit</h2> <h2>🕐 Datum & Uhrzeit</h2>
@@ -595,7 +608,7 @@
.then((response) => response.json()) .then((response) => response.json())
.then((data) => { .then((data) => {
document.getElementById("licencekey").value = data.licence || ""; document.getElementById("licencekey").value = data.licence || "";
loadLocations(); loadLocationsFromBackend();
}) })
.catch((error) => .catch((error) =>
showMessage("Fehler beim Laden der Lizenz", "error") showMessage("Fehler beim Laden der Lizenz", "error")
@@ -1004,44 +1017,84 @@
//location functions //location functions
// Locations laden und Dropdown befüllen // Locations laden und Dropdown befüllen
function loadLocations() { function loadLocationsFromBackend() {
const licence = document.getElementById("licencekey").value; // Get the licence key from the input field const select = document.getElementById("locationSelect");
fetch("http://db.reptilfpv.de:3000/api/location/", {
method: "GET",
headers: {
Authorization: `Bearer ${licence}`, // Add Bearer token using licenkey
},
})
.then((response) => response.json())
.then((data) => {
const select = document.getElementById("locationSelect");
// Vorhandene Optionen löschen (außer der ersten "Bitte wählen...") // Vorhandene Optionen löschen (außer der ersten "Bitte wählen...")
while (select.children.length > 1) { while (select.children.length > 1) {
select.removeChild(select.lastChild); select.removeChild(select.lastChild);
} }
// Neue Optionen aus Backend-Response hinzufügen // Fallback: Statische Standorte falls API nicht verfügbar ist
// Neue Optionen aus Backend-Response hinzufügen const staticLocations = [
data.forEach((location) => { { id: "1", name: "Hauptstandort" },
const option = document.createElement("option"); { id: "2", name: "Standort A" },
option.value = location.id; { id: "3", name: "Standort B" },
option.textContent = location.name; { id: "4", name: "Teststandort" }
select.appendChild(option); ];
});
// Versuche zuerst die echte API zu verwenden
// Aktuell gespeicherten Standort laden const licence = document.getElementById("licencekey").value;
loadCurrentLocation(); if (licence && licence.trim() !== "") {
fetch("https://ninja.reptilfpv.de/api/v1/private/locations", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${licence}`,
},
}) })
.catch((error) => { .then((response) => {
console.log("Locations konnten nicht geladen werden:", error); if (!response.ok) {
showMessage("Fehler beim Laden der Locations", "error"); throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
})
.then((data) => {
if (data.success && data.data) {
// API erfolgreich - verwende echte Daten
data.data.forEach((location) => {
const option = document.createElement("option");
option.value = location.id;
option.textContent = location.name;
select.appendChild(option);
});
showMessage("Standorte erfolgreich von API geladen", "success");
} else {
throw new Error("Ungültige API-Response");
}
// Aktuell gespeicherten Standort laden
loadSavedLocation();
})
.catch((error) => {
console.log("API nicht verfügbar, verwende statische Daten:", error);
// API fehlgeschlagen - verwende statische Daten als Fallback
staticLocations.forEach((location) => {
const option = document.createElement("option");
option.value = location.id;
option.textContent = location.name;
select.appendChild(option);
});
showMessage("Standorte geladen (statische Daten - API nicht verfügbar)", "warning");
// Aktuell gespeicherten Standort laden
loadSavedLocation();
});
} else {
// Kein Lizenz-Key - verwende statische Daten
staticLocations.forEach((location) => {
const option = document.createElement("option");
option.value = location.id;
option.textContent = location.name;
select.appendChild(option);
}); });
showMessage("Standorte geladen (statische Daten - kein Lizenz-Key)", "warning");
// Aktuell gespeicherten Standort laden
loadSavedLocation();
}
} }
// Aktuell gespeicherten Standort laden // Aktuell gespeicherten Standort laden
function loadCurrentLocation() { function loadSavedLocation() {
fetch("/api/get-location") fetch("/api/get-local-location")
.then((response) => response.json()) .then((response) => response.json())
.then((data) => { .then((data) => {
if (data.locationId) { if (data.locationId) {
@@ -1114,7 +1167,7 @@
} }
// Standort an Backend senden // Standort an Backend senden
fetch("/api/set-location", { fetch("/api/set-local-location", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
@@ -1132,18 +1185,90 @@
.catch((error) => showMessage("Verbindungsfehler", "error")); .catch((error) => showMessage("Verbindungsfehler", "error"));
}); });
// Status-Nachricht anzeigen // Moderne Notification anzeigen
function showMessage(message, type) { function showMessage(message, type = 'info') {
const statusDiv = document.getElementById("statusMessage"); console.log("showMessage called:", message, type);
statusDiv.textContent = message; const toast = document.getElementById("notificationBubble");
statusDiv.className = `status-message status-${type}`; const icon = document.getElementById("notificationIcon");
statusDiv.style.display = "block"; const title = document.getElementById("notificationTitle");
const text = document.getElementById("notificationText");
if (!toast || !icon || !title || !text) {
console.error("Notification elements not found!");
return;
}
// Clear any existing timeout
if (window.notificationTimeout) {
clearTimeout(window.notificationTimeout);
}
// Set content
text.textContent = message;
// Set type-specific styling and content
toast.className = "notification-toast";
switch(type) {
case 'success':
toast.classList.add('success');
icon.textContent = '✓';
title.textContent = 'Erfolg';
break;
case 'error':
toast.classList.add('error');
icon.textContent = '✕';
title.textContent = 'Fehler';
break;
case 'info':
toast.classList.add('info');
icon.textContent = '';
title.textContent = 'Information';
break;
case 'warning':
toast.classList.add('warning');
icon.textContent = '⚠';
title.textContent = 'Warnung';
break;
default:
toast.classList.add('info');
icon.textContent = '';
title.textContent = 'Information';
}
// Show toast with animation
toast.style.display = "flex";
// Force reflow
toast.offsetHeight;
// Add show class after a small delay to ensure display is set
setTimeout(() => { setTimeout(() => {
statusDiv.style.display = "none"; toast.classList.add('show');
}, 10);
// Auto-hide after 5 seconds
window.notificationTimeout = setTimeout(() => {
hideNotification();
}, 5000); }, 5000);
} }
// Notification verstecken mit Animation
function hideNotification() {
const toast = document.getElementById("notificationBubble");
if (!toast) return;
// Clear timeout if exists
if (window.notificationTimeout) {
clearTimeout(window.notificationTimeout);
}
// Remove show class for animation
toast.classList.remove('show');
// Hide after animation completes
setTimeout(() => {
toast.style.display = "none";
}, 400); // Match CSS transition duration
}
// System-Info alle 30 Sekunden aktualisieren // System-Info alle 30 Sekunden aktualisieren
setInterval(loadSystemInfo, 30000); setInterval(loadSystemInfo, 30000);
</script> </script>

View File

@@ -2,10 +2,13 @@
#include "master.h" #include "master.h"
#include <Arduino.h> #include <Arduino.h>
#include <HTTPClient.h> #include <HTTPClient.h>
#include <preferencemanager.h>
const char *BACKEND_SERVER = "http://db.reptilfpv.de:3000"; const char *BACKEND_SERVER = "https://ninja.reptilfpv.de";
extern String licence; // Declare licence as an external variable defined elsewhere extern String
String BACKEND_TOKEN = licence; // Use the licence as the token for authentication licence; // Declare licence as an external variable defined elsewhere
String BACKEND_TOKEN =
licence; // Use the licence as the token for authentication
bool backendOnline() { bool backendOnline() {
@@ -17,7 +20,7 @@ bool backendOnline() {
} }
HTTPClient http; HTTPClient http;
http.begin(String(BACKEND_SERVER) + "/api/health"); http.begin(String(BACKEND_SERVER) + "/v1/private/health");
http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN); http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN);
int httpCode = http.GET(); int httpCode = http.GET();
@@ -53,7 +56,7 @@ UserData checkUser(const String &uid) {
} }
HTTPClient http; HTTPClient http;
http.begin(String(BACKEND_SERVER) + "/api/users/find"); http.begin(String(BACKEND_SERVER) + "/v1/private/users/find");
http.addHeader("Content-Type", "application/json"); http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN); http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN);
@@ -95,17 +98,16 @@ bool enterUserData(const String &uid, const String &firstname,
} }
HTTPClient http; HTTPClient http;
http.begin(String(BACKEND_SERVER) + "/api/users/insert"); http.begin(String(BACKEND_SERVER) + "/v1/private/create-player");
http.addHeader("Content-Type", "application/json"); http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN); http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN);
// Create JSON payload // Create JSON payload
StaticJsonDocument<256> requestDoc; StaticJsonDocument<256> requestDoc;
requestDoc["uid"] = uid; requestDoc["rfiduid"] = uid;
requestDoc["vorname"] = firstname; requestDoc["firstname"] = firstname;
requestDoc["nachname"] = lastname; requestDoc["lastname"] = lastname;
requestDoc["geburtsdatum"] = geburtsdatum; requestDoc["birthdate"] = geburtsdatum;
requestDoc["alter"] = alter;
String requestBody; String requestBody;
serializeJson(requestDoc, requestBody); serializeJson(requestDoc, requestBody);
@@ -133,7 +135,7 @@ JsonDocument getAllLocations() {
} }
HTTPClient http; HTTPClient http;
http.begin(String(BACKEND_SERVER) + "/api/location/"); http.begin(String(BACKEND_SERVER) + "/v1/private/locations");
http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN); http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN);
int httpCode = http.GET(); int httpCode = http.GET();
@@ -185,5 +187,36 @@ void setupBackendRoutes(AsyncWebServer &server) {
request->send(200, "application/json", result); request->send(200, "application/json", result);
}); });
server.on("/api/set-local-location", HTTP_POST,
[](AsyncWebServerRequest *request) {
Serial.println("/api/set-local-location called");
String locationId;
if (request->hasParam("locationId", true)) {
locationId = request->getParam("locationId", true)->value();
}
if (locationId.length() > 0) {
saveLocationIdToPrefs(locationId);
DynamicJsonDocument doc(64);
doc["success"] = true;
String result;
serializeJson(doc, result);
request->send(200, "application/json", result);
} else {
request->send(400, "application/json", "{\"success\":false}");
}
});
server.on("/api/get-local-location", HTTP_GET,
[](AsyncWebServerRequest *request) {
String locationId = getLocationIdFromPrefs();
DynamicJsonDocument doc(64);
doc["locationId"] = locationId;
String result;
serializeJson(doc, result);
request->send(200, "application/json", result);
// Andere Logik wie in getBestLocs
});
// Add more routes as needed // Add more routes as needed
} }

View File

@@ -31,26 +31,26 @@ void triggerAction(const char *action, int press, int lane,
void IndividualMode(const char *action, int press, int lane, void IndividualMode(const char *action, int press, int lane,
uint64_t timestamp) { uint64_t timestamp) {
if (action == "start" && press == 2 && lane == 1) { if (action == "start" && press == 2 && lane == 1) {
if (!timerData.isRunning1 && timerData.isReady1) { if (!timerData1.isRunning && timerData1.isReady) {
timerData.isReady1 = false; timerData1.isReady = false;
timerData.startTime1 = (timestamp > 0) ? timestamp : millis(); timerData1.startTime = (timestamp > 0) ? timestamp : millis();
timerData.localStartTime1 = millis(); // Set local start time timerData1.localStartTime = millis(); // Set local start time
timerData.isRunning1 = true; timerData1.isRunning = true;
timerData.endTime1 = 0; timerData1.endTime = 0;
timerData.isArmed1 = false; // Reset armed status timerData1.isArmed = false; // Reset armed status
publishLaneStatus(1, "running"); publishLaneStatus(1, "running");
Serial.println("Bahn 1 gestartet"); Serial.println("Bahn 1 gestartet");
} }
} }
if (action == "stop" && press == 1 && lane == 1) { if (action == "stop" && press == 1 && lane == 1) {
if (timerData.isRunning1) { if (timerData1.isRunning) {
timerData.endTime1 = (timestamp > 0) ? timestamp : millis(); timerData1.endTime = (timestamp > 0) ? timestamp : millis();
timerData.finishedSince1 = millis(); // Set finished time timerData1.finishedSince = millis(); // Set finished time
timerData.isRunning1 = false; timerData1.isRunning = false;
uint64_t currentTime = timerData.endTime1 - timerData.startTime1; uint64_t currentTime = timerData1.endTime - timerData1.startTime;
if (timerData.bestTime1 == 0 || currentTime < timerData.bestTime1) { if (timerData1.bestTime == 0 || currentTime < timerData1.bestTime) {
timerData.bestTime1 = currentTime; timerData1.bestTime = currentTime;
saveBestTimes(); saveBestTimes();
} }
publishLaneStatus(1, "stopped"); publishLaneStatus(1, "stopped");
@@ -59,26 +59,26 @@ void IndividualMode(const char *action, int press, int lane,
} }
} }
if (action == "start" && press == 2 && lane == 2) { if (action == "start" && press == 2 && lane == 2) {
if (!timerData.isRunning2 && timerData.isReady2) { if (!timerData2.isRunning && timerData2.isReady) {
timerData.isReady2 = false; timerData2.isReady = false;
timerData.startTime2 = (timestamp > 0) ? timestamp : millis(); timerData2.startTime = (timestamp > 0) ? timestamp : millis();
timerData.localStartTime2 = millis(); // Set local start time timerData2.localStartTime = millis(); // Set local start time
timerData.isRunning2 = true; timerData2.isRunning = true;
timerData.endTime2 = 0; timerData2.endTime = 0;
timerData.isArmed2 = false; // Reset armed status timerData2.isArmed = false; // Reset armed status
publishLaneStatus(2, "running"); publishLaneStatus(2, "running");
Serial.println("Bahn 2 gestartet"); Serial.println("Bahn 2 gestartet");
} }
} }
if (action == "stop" && press == 1 && lane == 2) { if (action == "stop" && press == 1 && lane == 2) {
if (timerData.isRunning2) { if (timerData2.isRunning) {
timerData.endTime2 = (timestamp > 0) ? timestamp : millis(); timerData2.endTime = (timestamp > 0) ? timestamp : millis();
timerData.finishedSince2 = millis(); // Set finished time timerData2.finishedSince = millis(); // Set finished time
timerData.isRunning2 = false; timerData2.isRunning = false;
uint64_t currentTime = timerData.endTime2 - timerData.startTime2; uint64_t currentTime = timerData2.endTime - timerData2.startTime;
if (timerData.bestTime2 == 0 || currentTime < timerData.bestTime2) { if (timerData2.bestTime == 0 || currentTime < timerData2.bestTime) {
timerData.bestTime2 = currentTime; timerData2.bestTime = currentTime;
saveBestTimes(); saveBestTimes();
} }
publishLaneStatus(2, "stopped"); publishLaneStatus(2, "stopped");
@@ -102,18 +102,18 @@ void CompetitionMode(const char *action, int press, int lane,
int armTimeout = 10000; // Zeit in Millisekunden, die die Bahn armiert bleibt int armTimeout = 10000; // Zeit in Millisekunden, die die Bahn armiert bleibt
if (action == "start" && press == 2 && lane == 1) { if (action == "start" && press == 2 && lane == 1) {
if (!timerData.isRunning1 && timerData.isReady1) { if (!timerData1.isRunning && timerData1.isReady) {
timerData.isReady1 = false; timerData1.isReady = false;
timerData.isArmed1 = true; // Set Bahn 1 as armed timerData1.isArmed = true; // Set Bahn 1 as armed
publishLaneStatus(1, "armed"); publishLaneStatus(1, "armed");
Serial.println("Bahn 1 armiert"); Serial.println("Bahn 1 armiert");
armedAtTime1 = millis(); // Set armed time for Bahn 1 armedAtTime1 = millis(); // Set armed time for Bahn 1
} }
} }
if (action == "start" && press == 2 && lane == 2) { if (action == "start" && press == 2 && lane == 2) {
if (!timerData.isRunning2 && timerData.isReady2) { if (!timerData2.isRunning && timerData2.isReady) {
timerData.isReady2 = false; timerData2.isReady = false;
timerData.isArmed2 = true; // Set Bahn 2 as armed timerData2.isArmed = true; // Set Bahn 2 as armed
publishLaneStatus(2, "armed"); publishLaneStatus(2, "armed");
Serial.println("Bahn 2 armiert"); Serial.println("Bahn 2 armiert");
armedAtTime2 = millis(); // Set armed time for Bahn 2 armedAtTime2 = millis(); // Set armed time for Bahn 2
@@ -121,34 +121,32 @@ void CompetitionMode(const char *action, int press, int lane,
} }
if (armedAtTime1 > armedAtTime1 + armTimeout) { if (armedAtTime1 > armedAtTime1 + armTimeout) {
timerData.isArmed1 = false; // Reset Bahn 1 if armed time exceeded timerData1.isArmed = false; // Reset Bahn 1 if armed time exceeded
timerData.isReady1 = true; // Set Bahn 1 back to ready timerData1.isReady = true; // Set Bahn 1 back to ready
Serial.println("Bahn 1 automatisch zurückgesetzt (armiert)"); Serial.println("Bahn 1 automatisch zurückgesetzt (armiert)");
publishLaneStatus(1, "ready"); publishLaneStatus(1, "ready");
} }
if (armedAtTime2 > armedAtTime2 + armTimeout) { if (armedAtTime2 > armedAtTime2 + armTimeout) {
timerData.isArmed2 = false; // Reset Bahn 2 if armed time exceeded timerData2.isArmed = false; // Reset Bahn 2 if armed time exceeded
timerData.isReady2 = true; // Set Bahn 2 back to ready timerData2.isReady = true; // Set Bahn 2 back to ready
Serial.println("Bahn 2 automatisch zurückgesetzt (armiert)"); Serial.println("Bahn 2 automatisch zurückgesetzt (armiert)");
publishLaneStatus(2, "ready"); publishLaneStatus(2, "ready");
} }
if (timerData.isArmed1 && timerData.isArmed2) { if (timerData1.isArmed && timerData2.isArmed) {
sendMQTTMessage("aquacross/competition/toSignal", "armed"); sendMQTTMessage("aquacross/competition/toSignal", "armed");
} }
if ((action == "stop" && press == 1 && lane == 1)) { if ((action == "stop" && press == 1 && lane == 1)) {
if (timerData.isRunning1) { if (timerData1.isRunning) {
timerData.endTime1 = (timestamp > 0) ? timestamp : millis(); timerData1.endTime = (timestamp > 0) ? timestamp : millis();
timerData.finishedSince1 = millis(); // Set finished time timerData1.finishedSince = millis(); // Set finished time
timerData.isRunning1 = false; timerData1.isRunning = false;
uint64_t currentTime1 = timerData.endTime1 - timerData.startTime1; uint64_t currentTime1 = timerData1.endTime - timerData1.startTime;
if (timerData.bestTime1 == 0 || currentTime1 < timerData.bestTime1) { if (timerData1.bestTime == 0 || currentTime1 < timerData1.bestTime) {
timerData.bestTime1 = currentTime1; timerData1.bestTime = currentTime1;
saveBestTimes(); saveBestTimes();
} }
publishLaneStatus(1, "stopped"); publishLaneStatus(1, "stopped");
@@ -157,14 +155,14 @@ void CompetitionMode(const char *action, int press, int lane,
} }
} }
if (action == "stop" && press == 1 && lane == 2) { if (action == "stop" && press == 1 && lane == 2) {
if (timerData.isRunning2) { if (timerData2.isRunning) {
timerData.endTime2 = (timestamp > 0) ? timestamp : millis(); timerData2.endTime = (timestamp > 0) ? timestamp : millis();
timerData.finishedSince2 = millis(); // Set finished time timerData2.finishedSince = millis(); // Set finished time
timerData.isRunning2 = false; timerData2.isRunning = false;
uint64_t currentTime2 = timerData.endTime2 - timerData.startTime2; uint64_t currentTime2 = timerData2.endTime - timerData2.startTime;
if (timerData.bestTime2 == 0 || currentTime2 < timerData.bestTime2) { if (timerData2.bestTime == 0 || currentTime2 < timerData2.bestTime) {
timerData.bestTime2 = currentTime2; timerData2.bestTime = currentTime2;
saveBestTimes(); saveBestTimes();
} }
publishLaneStatus(2, "stopped"); publishLaneStatus(2, "stopped");
@@ -175,28 +173,28 @@ void CompetitionMode(const char *action, int press, int lane,
} }
void runCompetition() { void runCompetition() {
if (timerData.isArmed1 && timerData.isArmed2 && startCompetition) { if (timerData1.isArmed && timerData2.isArmed && startCompetition) {
timerData.isReady1 = false; timerData1.isReady = false;
uint64_t startNow = getCurrentTimestampMs(); uint64_t startNow = getCurrentTimestampMs();
timerData.startTime1 = startNow; timerData1.startTime = startNow;
timerData.localStartTime1 = millis(); // Set local start time timerData1.localStartTime = millis(); // Set local start time
timerData.isRunning1 = true; timerData1.isRunning = true;
timerData.endTime1 = 0; // Reset end time for Bahn 1 timerData1.endTime = 0; // Reset end time for Bahn 1
timerData.isArmed1 = false; // Reset Bahn 1 armed status timerData1.isArmed = false; // Reset Bahn 1 armed status
publishLaneStatus(1, "running"); publishLaneStatus(1, "running");
Serial.println("Bahn 1 gestartet"); Serial.println("Bahn 1 gestartet");
timerData.isReady2 = false; timerData2.isReady = false;
timerData.startTime2 = startNow; timerData2.startTime = startNow;
timerData.localStartTime2 = millis(); // Set local start time timerData2.localStartTime = millis(); // Set local start time
timerData.isRunning2 = true; timerData2.isRunning = true;
timerData.endTime2 = 0; // Reset end time for Bahn 2 timerData2.endTime = 0; // Reset end time for Bahn 2
timerData.isArmed2 = false; // Reset Bahn 2 armed status timerData2.isArmed = false; // Reset Bahn 2 armed status
publishLaneStatus(2, "running"); publishLaneStatus(2, "running");
Serial.println("Bahn 2 gestartet"); Serial.println("Bahn 2 gestartet");
} } else {
else { Serial.println(
Serial.println("Bahn 1 und Bahn 2 müssen armiert sein, um den Wettkampf zu starten."); "Bahn 1 und Bahn 2 müssen armiert sein, um den Wettkampf zu starten.");
} }
} }
@@ -204,13 +202,13 @@ void checkAutoReset() {
unsigned long currentTime = millis(); unsigned long currentTime = millis();
if (gamemode == 0) { // Individual Mode: Bahnen unabhängig zurücksetzen if (gamemode == 0) { // Individual Mode: Bahnen unabhängig zurücksetzen
if (!timerData.isRunning1 && timerData.endTime1 > 0 && if (!timerData1.isRunning && timerData1.endTime > 0 &&
timerData.finishedSince1 > 0) { timerData1.finishedSince > 0) {
if (currentTime - timerData.finishedSince1 > maxTimeDisplay) { if (currentTime - timerData1.finishedSince > maxTimeDisplay) {
timerData.startTime1 = 0; timerData1.startTime = 0;
timerData.endTime1 = 0; timerData1.endTime = 0;
timerData.finishedSince1 = 0; timerData1.finishedSince = 0;
timerData.isReady1 = true; timerData1.isReady = true;
JsonDocument messageDoc; JsonDocument messageDoc;
messageDoc["firstname"] = ""; messageDoc["firstname"] = "";
messageDoc["lastname"] = ""; messageDoc["lastname"] = "";
@@ -222,13 +220,13 @@ void checkAutoReset() {
Serial.println("Bahn 1 automatisch auf 'Bereit' zurückgesetzt"); Serial.println("Bahn 1 automatisch auf 'Bereit' zurückgesetzt");
} }
} }
if (!timerData.isRunning2 && timerData.endTime2 > 0 && if (!timerData2.isRunning && timerData2.endTime > 0 &&
timerData.finishedSince2 > 0) { timerData2.finishedSince > 0) {
if (currentTime - timerData.finishedSince2 > maxTimeDisplay) { if (currentTime - timerData2.finishedSince > maxTimeDisplay) {
timerData.startTime2 = 0; timerData2.startTime = 0;
timerData.endTime2 = 0; timerData2.endTime = 0;
timerData.finishedSince2 = 0; timerData2.finishedSince = 0;
timerData.isReady2 = true; timerData2.isReady = true;
JsonDocument messageDoc; JsonDocument messageDoc;
messageDoc["firstname"] = ""; messageDoc["firstname"] = "";
messageDoc["lastname"] = ""; messageDoc["lastname"] = "";
@@ -242,30 +240,30 @@ void checkAutoReset() {
} }
} else if (gamemode == } else if (gamemode ==
1) { // Competition Mode: Beide Bahnen gemeinsam zurücksetzen 1) { // Competition Mode: Beide Bahnen gemeinsam zurücksetzen
bool bothStopped = !timerData.isRunning1 && !timerData.isRunning2 && bool bothStopped = !timerData1.isRunning && !timerData2.isRunning &&
timerData.endTime1 > 0 && timerData.endTime2 > 0 && timerData1.endTime > 0 && timerData2.endTime > 0 &&
timerData.finishedSince1 > 0 && timerData1.finishedSince > 0 &&
timerData.finishedSince2 > 0; timerData2.finishedSince > 0;
unsigned long latestFinish = unsigned long latestFinish =
timerData.finishedSince1 > timerData.finishedSince2 timerData1.finishedSince > timerData2.finishedSince
? timerData.finishedSince1 ? timerData1.finishedSince
: timerData.finishedSince2; : timerData2.finishedSince;
if (bothStopped && (currentTime - latestFinish > maxTimeDisplay)) { if (bothStopped && (currentTime - latestFinish > maxTimeDisplay)) {
// Bahn 1 zurücksetzen // Bahn 1 zurücksetzen
timerData.startTime1 = 0; timerData1.startTime = 0;
timerData.endTime1 = 0; timerData1.endTime = 0;
timerData.finishedSince1 = 0; timerData1.finishedSince = 0;
timerData.isReady1 = true; timerData1.isReady = true;
publishLaneStatus(1, "ready"); publishLaneStatus(1, "ready");
Serial.println("Bahn 1 automatisch auf 'Bereit' zurückgesetzt"); Serial.println("Bahn 1 automatisch auf 'Bereit' zurückgesetzt");
// Bahn 2 zurücksetzen // Bahn 2 zurücksetzen
timerData.startTime2 = 0; timerData2.startTime = 0;
timerData.endTime2 = 0; timerData2.endTime = 0;
timerData.finishedSince2 = 0; timerData2.finishedSince = 0;
timerData.isReady2 = true; timerData2.isReady = true;
publishLaneStatus(2, "ready"); publishLaneStatus(2, "ready");
Serial.println("Bahn 2 automatisch auf 'Bereit' zurückgesetzt"); Serial.println("Bahn 2 automatisch auf 'Bereit' zurückgesetzt");
@@ -288,13 +286,13 @@ String getTimerDataJSON() {
unsigned long currentTime = millis(); unsigned long currentTime = millis();
// Bahn 1 // Bahn 1
if (timerData.isRunning1) { if (timerData1.isRunning) {
doc["time1"] = (currentTime - timerData.localStartTime1) / 1000.0; doc["time1"] = (currentTime - timerData1.localStartTime) / 1000.0;
doc["status1"] = "running"; doc["status1"] = "running";
} else if (timerData.endTime1 > 0) { } else if (timerData1.endTime > 0) {
doc["time1"] = (timerData.endTime1 - timerData.startTime1) / 1000.0; doc["time1"] = (timerData1.endTime - timerData1.startTime) / 1000.0;
doc["status1"] = "finished"; doc["status1"] = "finished";
} else if (timerData.isArmed1) { } else if (timerData1.isArmed) {
doc["time1"] = 0; doc["time1"] = 0;
doc["status1"] = "armed"; // Status für Bahn 1, wenn sie armiert ist doc["status1"] = "armed"; // Status für Bahn 1, wenn sie armiert ist
} else { } else {
@@ -303,13 +301,13 @@ String getTimerDataJSON() {
} }
// Bahn 2 // Bahn 2
if (timerData.isRunning2) { if (timerData2.isRunning) {
doc["time2"] = (currentTime - timerData.localStartTime2) / 1000.0; doc["time2"] = (currentTime - timerData2.localStartTime) / 1000.0;
doc["status2"] = "running"; doc["status2"] = "running";
} else if (timerData.endTime2 > 0) { } else if (timerData2.endTime > 0) {
doc["time2"] = (timerData.endTime2 - timerData.startTime2) / 1000.0; doc["time2"] = (timerData2.endTime - timerData2.startTime) / 1000.0;
doc["status2"] = "finished"; doc["status2"] = "finished";
} else if (timerData.isArmed2) { } else if (timerData2.isArmed) {
doc["time2"] = 0; doc["time2"] = 0;
doc["status2"] = "armed"; // Status für Bahn 2, wenn sie armiert ist doc["status2"] = "armed"; // Status für Bahn 2, wenn sie armiert ist
} else { } else {
@@ -318,8 +316,8 @@ String getTimerDataJSON() {
} }
// Beste Zeiten // Beste Zeiten
doc["best1"] = timerData.bestTime1 / 1000.0; doc["best1"] = timerData1.bestTime / 1000.0;
doc["best2"] = timerData.bestTime2 / 1000.0; doc["best2"] = timerData2.bestTime / 1000.0;
// Lernmodus // Lernmodus
doc["learningMode"] = learningMode; doc["learningMode"] = learningMode;

View File

@@ -11,24 +11,28 @@ const char *passwordAP = nullptr;
char *ssidSTA = nullptr; char *ssidSTA = nullptr;
char *passwordSTA = nullptr; char *passwordSTA = nullptr;
// Timer Struktur // Timer Struktur für Bahn 1
struct TimerData { struct TimerData1 {
unsigned long startTime1 = 0; unsigned long startTime = 0;
unsigned long startTime2 = 0; unsigned long localStartTime = 0;
unsigned long localStartTime1 = 0; unsigned long finishedSince = 0;
unsigned long localStartTime2 = 0; unsigned long endTime = 0;
unsigned long finishedSince1 = 0; unsigned long bestTime = 0;
unsigned long finishedSince2 = 0; bool isRunning = false;
unsigned long endTime1 = 0; bool isReady = true; // Status für Bahn 1
unsigned long endTime2 = 0; bool isArmed = false; // Status für Bahn 1 (armiert/nicht armiert)
unsigned long bestTime1 = 0; };
unsigned long bestTime2 = 0;
bool isRunning1 = false; // Timer Struktur für Bahn 2
bool isRunning2 = false; struct TimerData2 {
bool isReady1 = true; // Status für Bahn 1 unsigned long startTime = 0;
bool isReady2 = true; // Status für Bahn 2 unsigned long localStartTime = 0;
bool isArmed1 = false; // Status für Bahn 1 (armiert/nicht armiert) unsigned long finishedSince = 0;
bool isArmed2 = false; // Status für Bahn 2 (armiert/nicht armiert) unsigned long endTime = 0;
unsigned long bestTime = 0;
bool isRunning = false;
bool isReady = true; // Status für Bahn 2
bool isArmed = false; // Status für Bahn 2 (armiert/nicht armiert)
}; };
// Button Konfiguration // Button Konfiguration
@@ -50,7 +54,8 @@ struct ButtonConfigs {
extern const char *firmwareversion; extern const char *firmwareversion;
// Globale Variablen // Globale Variablen
TimerData timerData; TimerData1 timerData1;
TimerData2 timerData2;
ButtonConfigs buttonConfigs; ButtonConfigs buttonConfigs;
bool learningMode = false; bool learningMode = false;
int learningStep = 0; // 0=Start1, 1=Stop1, 2=Start2, 3=Stop2 int learningStep = 0; // 0=Start1, 1=Stop1, 2=Start2, 3=Stop2

View File

@@ -24,15 +24,15 @@ void loadButtonConfig() {
// Persist and load best times // Persist and load best times
void saveBestTimes() { void saveBestTimes() {
preferences.begin("times", false); preferences.begin("times", false);
preferences.putULong("best1", timerData.bestTime1); preferences.putULong("best1", timerData1.bestTime);
preferences.putULong("best2", timerData.bestTime2); preferences.putULong("best2", timerData2.bestTime);
preferences.end(); preferences.end();
} }
void loadBestTimes() { void loadBestTimes() {
preferences.begin("times", true); preferences.begin("times", true);
timerData.bestTime1 = preferences.getULong("best1", 0); timerData1.bestTime = preferences.getULong("best1", 0);
timerData.bestTime2 = preferences.getULong("best2", 0); timerData2.bestTime = preferences.getULong("best2", 0);
preferences.end(); preferences.end();
} }
@@ -93,4 +93,15 @@ int checkLicence() {
return tier; return tier;
} }
void saveLocationIdToPrefs(const String &locationId) {
preferences.begin("locationid", false);
preferences.putString("locationid", locationId);
preferences.end();
}
String getLocationIdFromPrefs() {
preferences.begin("locationid", true);
String locationId = preferences.getString("locationid", "");
preferences.end();
return locationId;
}

View File

@@ -53,8 +53,8 @@ void setupRoutes() {
server.on("/api/reset-best", HTTP_POST, [](AsyncWebServerRequest *request) { server.on("/api/reset-best", HTTP_POST, [](AsyncWebServerRequest *request) {
Serial.println("/api/reset-best called"); Serial.println("/api/reset-best called");
timerData.bestTime1 = 0; timerData1.bestTime = 0;
timerData.bestTime2 = 0; timerData2.bestTime = 0;
saveBestTimes(); saveBestTimes();
DynamicJsonDocument doc(64); DynamicJsonDocument doc(64);
doc["success"] = true; doc["success"] = true;