diff --git a/.github/workflows/build-0313-beta.yml b/.github/workflows/build-0313-beta.yml index bc6fdc1..2a5795f 100644 --- a/.github/workflows/build-0313-beta.yml +++ b/.github/workflows/build-0313-beta.yml @@ -1,9 +1,9 @@ -name: Build Raptor Link 0.3.13 beta +name: Build Raptor Link 0.3.14 beta on: push: branches: - - release/0.3.13-classic + - release/0.3.14-classic workflow_dispatch: jobs: @@ -54,34 +54,34 @@ jobs: Remove-Item ".\raptor-build\payload" -Recurse -Force -ErrorAction SilentlyContinue Copy-Item ".\RaptorLink" ".\raptor-build\payload" -Recurse Push-Location ".\raptor-build" - & "C:\Program Files (x86)\NSIS\makensis.exe" "/DAPPDIR=payload" "/DOUTPUT=..\Raptor-Link-Setup-0.3.13.exe" ".\installer.nsi" + & "C:\Program Files (x86)\NSIS\makensis.exe" "/DAPPDIR=payload" "/DOUTPUT=..\Raptor-Link-Setup-0.3.14.exe" ".\installer.nsi" Pop-Location Remove-Item ".\raptor-build\payload" -Recurse -Force -ErrorAction SilentlyContinue - if (!(Test-Path ".\Raptor-Link-Setup-0.3.13.exe")) { throw "Installer was not generated" } + if (!(Test-Path ".\Raptor-Link-Setup-0.3.14.exe")) { throw "Installer was not generated" } - name: Build complete project ZIP shell: powershell run: | - $stage = Join-Path $env:RUNNER_TEMP "Raptor-Link-0.3.13-Projet" + $stage = Join-Path $env:RUNNER_TEMP "Raptor-Link-0.3.14-Projet" Remove-Item $stage -Recurse -Force -ErrorAction SilentlyContinue New-Item -ItemType Directory -Path $stage | Out-Null Copy-Item ".\RaptorLink" (Join-Path $stage "RaptorLink") -Recurse Copy-Item ".\raptor-build" (Join-Path $stage "raptor-build") -Recurse Get-ChildItem $stage -Directory -Recurse -Filter "__pycache__" | Remove-Item -Recurse -Force - $zip = Join-Path (Get-Location) "Raptor-Link-0.3.13-Projet.zip" + $zip = Join-Path (Get-Location) "Raptor-Link-0.3.14-Projet.zip" Compress-Archive -Path $stage -DestinationPath $zip -CompressionLevel Optimal -Force if (!(Test-Path $zip)) { throw "Project ZIP was not generated" } - name: Upload installer uses: actions/upload-artifact@v4 with: - name: Raptor-Link-Setup-0.3.13 - path: Raptor-Link-0.3.4-Projet/Raptor-Link-Setup-0.3.13.exe + name: Raptor-Link-Setup-0.3.14 + path: Raptor-Link-0.3.4-Projet/Raptor-Link-Setup-0.3.14.exe if-no-files-found: error - name: Upload complete project uses: actions/upload-artifact@v4 with: - name: Raptor-Link-0.3.13-Projet - path: Raptor-Link-0.3.4-Projet/Raptor-Link-0.3.13-Projet.zip + name: Raptor-Link-0.3.14-Projet + path: Raptor-Link-0.3.4-Projet/Raptor-Link-0.3.14-Projet.zip if-no-files-found: error diff --git a/.github/workflows/build-0314-beta.yml b/.github/workflows/build-0314-beta.yml new file mode 100644 index 0000000..a35ea93 --- /dev/null +++ b/.github/workflows/build-0314-beta.yml @@ -0,0 +1,87 @@ +name: Build Raptor Link 0.3.14 beta + +on: + push: + branches: + - release/0.3.14-startup-stability + workflow_dispatch: + +jobs: + build: + runs-on: windows-latest + defaults: + run: + working-directory: Raptor-Link-0.3.4-Projet + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up MSVC + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + - name: Build native MSI helper + shell: cmd + run: | + if not exist RaptorLink\native mkdir RaptorLink\native + cl /nologo /std:c++17 /O2 /EHsc /MT /utf-8 /Fe:RaptorLink\native\msi_bridge.exe RaptorLink\native\msi_bridge.cpp ole32.lib oleaut32.lib + if not exist RaptorLink\native\msi_bridge.exe exit /b 1 + + - name: Run Python regression tests + shell: powershell + run: | + & ".\RaptorLink\runtime\python.exe" -m unittest discover -s raptor-build -p "test_*.py" + + - name: Check Python syntax + shell: powershell + run: | + & ".\RaptorLink\runtime\python.exe" -m py_compile ".\RaptorLink\app.py" ".\RaptorLink\engine.py" ".\RaptorLink\support.py" ".\RaptorLink\icue_worker.py" ".\RaptorLink\openrgb_source.py" ".\RaptorLink\msi_sdk.py" ".\RaptorLink\msi_source.py" ".\RaptorLink\msi_worker.py" + + - name: Check JavaScript syntax + shell: powershell + run: | + node --check ".\RaptorLink\web\ui.js" + node --check ".\RaptorLink\web\extras.js" + + - name: Install NSIS + shell: powershell + run: choco install nsis -y --no-progress + + - name: Build installer + shell: powershell + run: | + Remove-Item ".\raptor-build\payload" -Recurse -Force -ErrorAction SilentlyContinue + Copy-Item ".\RaptorLink" ".\raptor-build\payload" -Recurse + Push-Location ".\raptor-build" + & "C:\Program Files (x86)\NSIS\makensis.exe" "/DAPPDIR=payload" "/DOUTPUT=..\Raptor-Link-Setup-0.3.14.exe" ".\installer.nsi" + Pop-Location + Remove-Item ".\raptor-build\payload" -Recurse -Force -ErrorAction SilentlyContinue + if (!(Test-Path ".\Raptor-Link-Setup-0.3.14.exe")) { throw "Installer was not generated" } + + - name: Build complete project ZIP + shell: powershell + run: | + $stage = Join-Path $env:RUNNER_TEMP "Raptor-Link-0.3.14-Projet" + Remove-Item $stage -Recurse -Force -ErrorAction SilentlyContinue + New-Item -ItemType Directory -Path $stage | Out-Null + Copy-Item ".\RaptorLink" (Join-Path $stage "RaptorLink") -Recurse + Copy-Item ".\raptor-build" (Join-Path $stage "raptor-build") -Recurse + Get-ChildItem $stage -Directory -Recurse -Filter "__pycache__" | Remove-Item -Recurse -Force + $zip = Join-Path (Get-Location) "Raptor-Link-0.3.14-Projet.zip" + Compress-Archive -Path $stage -DestinationPath $zip -CompressionLevel Optimal -Force + if (!(Test-Path $zip)) { throw "Project ZIP was not generated" } + + - name: Upload installer + uses: actions/upload-artifact@v4 + with: + name: Raptor-Link-Setup-0.3.14 + path: Raptor-Link-0.3.4-Projet/Raptor-Link-Setup-0.3.14.exe + if-no-files-found: error + + - name: Upload complete project + uses: actions/upload-artifact@v4 + with: + name: Raptor-Link-0.3.14-Projet + path: Raptor-Link-0.3.4-Projet/Raptor-Link-0.3.14-Projet.zip + if-no-files-found: error diff --git a/.github/workflows/build-040-core2.yml b/.github/workflows/build-040-core2.yml new file mode 100644 index 0000000..086e232 --- /dev/null +++ b/.github/workflows/build-040-core2.yml @@ -0,0 +1,87 @@ +name: Build Raptor Link 0.4.1 WLED recovery beta + +on: + push: + branches: + - release/0.4.1-core2 + workflow_dispatch: + +jobs: + build: + runs-on: windows-latest + defaults: + run: + working-directory: Raptor-Link-0.3.4-Projet + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up MSVC + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + - name: Build native MSI helper + shell: cmd + run: | + if not exist RaptorLink\native mkdir RaptorLink\native + cl /nologo /std:c++17 /O2 /EHsc /MT /utf-8 /Fe:RaptorLink\native\msi_bridge.exe RaptorLink\native\msi_bridge.cpp ole32.lib oleaut32.lib + if not exist RaptorLink\native\msi_bridge.exe exit /b 1 + + - name: Run Python regression tests + shell: powershell + run: | + & ".\RaptorLink\runtime\python.exe" -m unittest discover -s raptor-build -p "test_*.py" + + - name: Check Python syntax + shell: powershell + run: | + & ".\RaptorLink\runtime\python.exe" -m py_compile ".\RaptorLink\app.py" ".\RaptorLink\engine.py" ".\RaptorLink\features.py" ".\RaptorLink\support.py" ".\RaptorLink\diagnostics.py" ".\RaptorLink\wled_worker.py" ".\RaptorLink\icue_worker.py" ".\RaptorLink\openrgb_source.py" ".\RaptorLink\msi_sdk.py" ".\RaptorLink\msi_source.py" ".\RaptorLink\msi_worker.py" + + - name: Check JavaScript syntax + shell: powershell + run: | + node --check ".\RaptorLink\web\ui.js" + node --check ".\RaptorLink\web\extras.js" + + - name: Install NSIS + shell: powershell + run: choco install nsis -y --no-progress + + - name: Build installer + shell: powershell + run: | + Remove-Item ".\raptor-build\payload" -Recurse -Force -ErrorAction SilentlyContinue + Copy-Item ".\RaptorLink" ".\raptor-build\payload" -Recurse + Push-Location ".\raptor-build" + & "C:\Program Files (x86)\NSIS\makensis.exe" "/DAPPDIR=payload" "/DOUTPUT=..\Raptor-Link-Setup-0.4.1.exe" ".\installer.nsi" + Pop-Location + Remove-Item ".\raptor-build\payload" -Recurse -Force -ErrorAction SilentlyContinue + if (!(Test-Path ".\Raptor-Link-Setup-0.4.1.exe")) { throw "Installer was not generated" } + + - name: Build complete project ZIP + shell: powershell + run: | + $stage = Join-Path $env:RUNNER_TEMP "Raptor-Link-0.4.1-Projet" + Remove-Item $stage -Recurse -Force -ErrorAction SilentlyContinue + New-Item -ItemType Directory -Path $stage | Out-Null + Copy-Item ".\RaptorLink" (Join-Path $stage "RaptorLink") -Recurse + Copy-Item ".\raptor-build" (Join-Path $stage "raptor-build") -Recurse + Get-ChildItem $stage -Directory -Recurse -Filter "__pycache__" | Remove-Item -Recurse -Force + $zip = Join-Path (Get-Location) "Raptor-Link-0.4.1-Projet.zip" + Compress-Archive -Path $stage -DestinationPath $zip -CompressionLevel Optimal -Force + if (!(Test-Path $zip)) { throw "Project ZIP was not generated" } + + - name: Upload installer + uses: actions/upload-artifact@v4 + with: + name: Raptor-Link-Setup-0.4.1 + path: Raptor-Link-0.3.4-Projet/Raptor-Link-Setup-0.4.1.exe + if-no-files-found: error + + - name: Upload complete project + uses: actions/upload-artifact@v4 + with: + name: Raptor-Link-0.4.1-Projet + path: Raptor-Link-0.3.4-Projet/Raptor-Link-0.4.1-Projet.zip + if-no-files-found: error diff --git a/.github/workflows/build-041-wled-recovery.yml b/.github/workflows/build-041-wled-recovery.yml new file mode 100644 index 0000000..5b32477 --- /dev/null +++ b/.github/workflows/build-041-wled-recovery.yml @@ -0,0 +1,90 @@ +name: Build Raptor Link 0.4.2 stability beta + +on: + push: + branches: + - release/0.4.1-wled-recovery + pull_request: + branches: + - main + workflow_dispatch: + +jobs: + build: + runs-on: windows-latest + defaults: + run: + working-directory: Raptor-Link-0.3.4-Projet + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up MSVC + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + - name: Build native MSI helper + shell: cmd + run: | + if not exist RaptorLink\native mkdir RaptorLink\native + cl /nologo /std:c++17 /O2 /EHsc /MT /utf-8 /Fe:RaptorLink\native\msi_bridge.exe RaptorLink\native\msi_bridge.cpp ole32.lib oleaut32.lib + if not exist RaptorLink\native\msi_bridge.exe exit /b 1 + + - name: Run Python regression tests + shell: powershell + run: | + & ".\RaptorLink\runtime\python.exe" -m unittest discover -s raptor-build -p "test_*.py" + + - name: Check Python syntax + shell: powershell + run: | + & ".\RaptorLink\runtime\python.exe" -m py_compile ".\RaptorLink\app.py" ".\RaptorLink\engine.py" ".\RaptorLink\features.py" ".\RaptorLink\support.py" ".\RaptorLink\diagnostics.py" ".\RaptorLink\wled_worker.py" ".\RaptorLink\icue_worker.py" ".\RaptorLink\openrgb_source.py" ".\RaptorLink\msi_sdk.py" ".\RaptorLink\msi_source.py" ".\RaptorLink\msi_worker.py" + + - name: Check JavaScript syntax + shell: powershell + run: | + node --check ".\RaptorLink\web\ui.js" + node --check ".\RaptorLink\web\extras.js" + + - name: Install NSIS + shell: powershell + run: choco install nsis -y --no-progress + + - name: Build installer + shell: powershell + run: | + Remove-Item ".\raptor-build\payload" -Recurse -Force -ErrorAction SilentlyContinue + Copy-Item ".\RaptorLink" ".\raptor-build\payload" -Recurse + Push-Location ".\raptor-build" + & "C:\Program Files (x86)\NSIS\makensis.exe" "/DAPPDIR=payload" "/DOUTPUT=..\Raptor-Link-Setup-0.4.2.exe" ".\installer.nsi" + Pop-Location + Remove-Item ".\raptor-build\payload" -Recurse -Force -ErrorAction SilentlyContinue + if (!(Test-Path ".\Raptor-Link-Setup-0.4.2.exe")) { throw "Installer was not generated" } + + - name: Build complete project ZIP + shell: powershell + run: | + $stage = Join-Path $env:RUNNER_TEMP "Raptor-Link-0.4.2-Projet" + Remove-Item $stage -Recurse -Force -ErrorAction SilentlyContinue + New-Item -ItemType Directory -Path $stage | Out-Null + Copy-Item ".\RaptorLink" (Join-Path $stage "RaptorLink") -Recurse + Copy-Item ".\raptor-build" (Join-Path $stage "raptor-build") -Recurse + Get-ChildItem $stage -Directory -Recurse -Filter "__pycache__" | Remove-Item -Recurse -Force + $zip = Join-Path (Get-Location) "Raptor-Link-0.4.2-Projet.zip" + Compress-Archive -Path $stage -DestinationPath $zip -CompressionLevel Optimal -Force + if (!(Test-Path $zip)) { throw "Project ZIP was not generated" } + + - name: Upload installer + uses: actions/upload-artifact@v4 + with: + name: Raptor-Link-Setup-0.4.2 + path: Raptor-Link-0.3.4-Projet/Raptor-Link-Setup-0.4.2.exe + if-no-files-found: error + + - name: Upload complete project + uses: actions/upload-artifact@v4 + with: + name: Raptor-Link-0.4.2-Projet + path: Raptor-Link-0.3.4-Projet/Raptor-Link-0.4.2-Projet.zip + if-no-files-found: error diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bd7612..1eb0b1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,50 @@ All notable changes to Raptor Link can be documented here. The format is based on a simple version history intended for GitHub Releases. +## 0.4.2 Core 2 Stability Beta + +- Automatically detects WLED controller reboots by monitoring the controller uptime in a separate health thread that never blocks realtime UDP streaming. +- If a controller reboots or loses WLED realtime mode while Raptor Link is streaming, its worker explicitly releases stale realtime state, restores ON/brightness and resumes RGB output automatically. +- Entering realtime mode now prepares WLED even when Raptor Link did not previously switch it off, fixing controllers that return after a power cut with brightness/state inconsistent with the running stream. +- Health checks are deliberately lightweight and independent. One HTTP timeout is tolerated so controllers with a fragile web API can continue receiving UDP normally. +- Diagnostics now expose WLED reachability, uptime, realtime live/mode/source fields, automatic recoveries, reboot state, RGB frame-change count and representative RGB samples. +- iCUE diagnostics now count successful color reads and actual color changes, making it possible to distinguish a frozen source from a WLED output problem. +- Added a per-device **Restart this WLED** command and a **Restart all WLEDs** command in the Windows tray menu, plus individual WLED restart entries. +- Added an 8-second per-device RGB diagnostic sequence: red, green, blue, then white. +- Fixed the single-window lifecycle: launching Raptor Link again focuses the existing dashboard instead of creating another one, and **Quit** from the tray closes the dashboard window as well as the engine. +- Added regression coverage for window lifecycle, WLED reboot/recovery and RGB generation. + +## 0.4.1 Core 2 Beta + +- Fixed the first real-hardware issue found with autonomous WLED presets: some controllers could remain stuck in realtime UDP mode and stop answering the web/HTTP API. +- Before every autonomous preset, OFF or restore command, Raptor Link now sends an explicit WLED realtime-release packet even if the current Raptor Link process did not start the realtime session. +- Added a second control path using WLED's JSON API over UDP. If the HTTP API times out or returns 503, the requested preset/ON/OFF state is sent through the notifier UDP port instead of hammering the web server for minutes. +- HTTP failure no longer blocks a realtime iCUE stream from waking and resuming. +- Added an HTTP circuit breaker: after a timeout/503, that WLED is no longer hammered every few seconds. Retries back off from 15 s to 30 s and then 60 s while the other WLED workers continue normally. +- UDP fallback is now treated as fire-and-forget rather than falsely confirmed. Raptor Link keeps a pending confirmation and converges the requested OFF/preset/restore state when the controller comes back online. +- Recovery probes are lightweight and only happen after the cooldown. If the WLED already has the requested state, Raptor Link does not restart the preset unnecessarily. +- Diagnostics now expose the control path, HTTP retry countdown, pending confirmation, fallback batch count, release packet count and UDP state-command count. +- Added regression coverage for forced realtime release, HTTP-to-UDP fallback, circuit-breaker suppression and automatic HTTP recovery. +- Hardware validation is required before merge. + +## 0.4.0 Core 2 Beta + +- Introduced one independent output worker per WLED controller. +- Removed periodic WLED HTTP polling from active realtime streaming. +- Added autonomous WLED preset mode for effects that do not need PC-side frame generation. +- Added persistent asynchronous diagnostics with selectable levels, retention limits and a one-click copyable support report. +- Kept iCUE/screen/audio sources in realtime mode while allowing simple effects to run directly on WLED. + +## 0.3.14 Beta + +- Fixed slow and unstable synchronization immediately after Windows startup. +- WLED health probes are now strictly read-only: Raptor Link no longer switches a strip off while checking its HTTP API. +- Realtime UDP output no longer waits for the WLED HTTP API to answer; colors can start as soon as the controller accepts UDP. +- Failed startup probes retry quickly in the background without interrupting an already running realtime stream. +- Raptor Link now waits for iCUE/screen source data before replacing the current WLED effect with black. +- During a short source interruption, the last valid frame is kept instead of flashing black. +- Increased the WLED realtime hold timeout from 2 s to 5 s to tolerate short Windows/iCUE/network stalls without visible blinking. + ## 0.3.13 Beta - Restored the classic Raptor Link experience: the normal UI is again centered on **Corsair iCUE** and Raptor Link's own direct sources (screen, audio and local effects). diff --git a/README.md b/README.md index 7c20a75..36891f8 100644 --- a/README.md +++ b/README.md @@ -264,6 +264,10 @@ These connectors are experimental, limited and may require extra vendor software Raptor Link keeps an in-app feedback center for questions, bugs, suggestions, comments and ratings. Users can prepare questions, bug reports, suggestions, ratings and hardware compatibility reports without exposing a GitHub token inside the application. The final report opens on GitHub pre-filled so the user can review it before submitting. +### Startup stability + +Raptor Link starts its realtime WLED stream independently from the WLED HTTP API. This avoids long startup delays when Windows, Wi-Fi, iCUE or a WLED controller become ready at different times. Health checks stay read-only, and temporary source interruptions keep the last valid frame instead of flashing black. + ## 🐛 Bugs, ideas and feedback Found a problem? Have an idea that would make Raptor Link better? diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/LISEZ-MOI.txt b/Raptor-Link-0.3.4-Projet/RaptorLink/LISEZ-MOI.txt index 6a63666..bf87159 100644 --- a/Raptor-Link-0.3.4-Projet/RaptorLink/LISEZ-MOI.txt +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/LISEZ-MOI.txt @@ -182,3 +182,12 @@ VERSION 0.3.13 — Retour Ă  l'expĂ©rience Raptor Link classique - Le centre Aide & retours est conservĂ© : questions, commentaires, bugs et suggestions. - La demande facultative de note aprĂšs environ une heure reste prĂ©sente et n'est demandĂ©e qu'une fois aprĂšs validation. - La vĂ©rification des nouvelles versions au dĂ©marrage reste disponible. + + +VERSION 0.3.14 — DĂ©marrage Windows et stabilitĂ© WLED +- Les vĂ©rifications HTTP WLED ne coupent plus jamais l'Ă©clairage. +- L'envoi UDP temps rĂ©el n'attend plus que l'API HTTP WLED rĂ©ponde. +- Au dĂ©marrage de Windows, les contrĂŽleurs WLED sont retentĂ©s rapidement en arriĂšre-plan. +- Raptor Link ne remplace plus l'effet WLED en cours par du noir pendant qu'iCUE ou la capture Ă©cran dĂ©marrent. +- Une courte perte de source conserve la derniĂšre trame valide pour Ă©viter les extinctions/rallumages. +- Le dĂ©lai de maintien temps rĂ©el WLED passe de 2 Ă  5 secondes afin de mieux absorber les petits blocages rĂ©seau ou systĂšme. diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/app.py b/Raptor-Link-0.3.4-Projet/RaptorLink/app.py index 4922662..3d982ca 100644 --- a/Raptor-Link-0.3.4-Projet/RaptorLink/app.py +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/app.py @@ -63,8 +63,12 @@ def __init__(self): startup(self.engine.config['settings']['startup']) self.server=ThreadingHTTPServer(('127.0.0.1',0),self.handler()) self.url='http://127.0.0.1:'+str(self.server.server_port)+'/#'+self.token - from window import WindowController,focus_window - self.window=WindowController(lambda:focus_window('Raptor Link · '+str(self.server.server_port)) if sys.platform=='win32' and not DEMO else False,self.launch_window) + from window import WindowController,focus_window,close_windows + self.window_title='Raptor Link · '+str(self.server.server_port) + self.window=WindowController( + lambda:focus_window(self.window_title) if sys.platform=='win32' and not DEMO else False, + self.launch_window, + close=lambda:close_windows(self.window_title) if sys.platform=='win32' and not DEMO else False) INSTANCE.write_text(json.dumps({'port':self.server.server_port,'token':self.token,'pid':os.getpid()})) if self.engine.config['settings'].get('check_updates',True) and not DEMO: threading.Thread(target=self.check_for_updates,daemon=True,name='RaptorLink-update-check').start() @@ -156,6 +160,9 @@ def do_POST(self): app.engine.save(data) if data['settings']['startup']!=previous: startup(data['settings']['startup']) elif self.path=='/api/test':app.engine.identify(data['ip']) + elif self.path=='/api/color-test':result=app.engine.color_diagnostic(data['ip']) + elif self.path=='/api/reboot-wled':result=app.engine.reboot_wled(data['ip']) + elif self.path=='/api/reboot-all-wled':result=app.engine.reboot_all_wled() elif self.path=='/api/profile':app.engine.select_profile(data['index']) elif self.path=='/api/tutorial': with app.engine.lock: @@ -202,6 +209,10 @@ def do_POST(self): app.engagement.never_rating();result={'ok':True} else:raise ValueError('Action de notation inconnue.') elif self.path=='/api/feedback':result=app.open_feedback(data) + elif self.path=='/api/diagnostic-report': + minutes=int(data.get('minutes',30)) + if minutes not in [5,30,120,1440,0]:raise ValueError('DurĂ©e de rapport invalide.') + result={'text':app.engine.diagnostic_report(minutes)} elif self.path=='/api/check-update': if app.engine.config['settings'].get('check_updates',True): app.update_info=find_update(APP_VERSION) @@ -227,6 +238,11 @@ def run(self): pystray.MenuItem('Profils',pystray.Menu(lambda: tuple(pystray.MenuItem(p['name'],(lambda index: lambda:self.engine.select_profile(index))(i)) for i,p in enumerate(self.engine.config.get('profiles',[]))))), pystray.MenuItem('DĂ©marrer',lambda:setattr(self.engine,'want_run',True)), pystray.MenuItem('ArrĂȘter la synchronisation',lambda:self.engine.stop()), + pystray.MenuItem('RedĂ©marrer tous les WLED',lambda:self.engine.reboot_all_wled()), + pystray.MenuItem('WLED',pystray.Menu(lambda: tuple( + pystray.MenuItem(t['name']+' · redĂ©marrer',(lambda ip: lambda:self.engine.reboot_wled(ip))(t['ip'])) + for t in self.engine.config.get('targets',[]) + ))), pystray.MenuItem('Garder allumĂ© (inactivitĂ©)',lambda:setattr(self.engine,'keep_awake',not self.engine.keep_awake),checked=lambda item:self.engine.keep_awake), pystray.MenuItem('Quitter',lambda:self.done.set()))) threading.Thread(target=self.tray.run,daemon=True).start() @@ -241,7 +257,7 @@ def run(self): self.tray.update_menu();tray_revision=self.engine.revision except KeyboardInterrupt:pass finally: - self.engagement.close();self.engine.shutdown();self.server.shutdown() + self.engagement.close();self.window.close();self.engine.shutdown();self.server.shutdown() if self.tray:self.tray.stop() INSTANCE.unlink(missing_ok=True) diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/build-source/installer.nsi b/Raptor-Link-0.3.4-Projet/RaptorLink/build-source/installer.nsi index a7823ad..0b0bb91 100644 --- a/Raptor-Link-0.3.4-Projet/RaptorLink/build-source/installer.nsi +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/build-source/installer.nsi @@ -6,7 +6,7 @@ Name "Raptor Link" !define APPDIR "../RaptorLink" !endif !ifndef OUTPUT -!define OUTPUT "../Raptor-Link-Setup-0.3.13.exe" +!define OUTPUT "../Raptor-Link-Setup-0.4.2.exe" !endif OutFile "${OUTPUT}" InstallDir "$LOCALAPPDATA\Programs\RaptorLink" @@ -15,10 +15,10 @@ RequestExecutionLevel user SetCompressor /SOLID lzma Icon "${APPDIR}/icon.ico" UninstallIcon "${APPDIR}/icon.ico" -VIProductVersion "0.3.13.0" +VIProductVersion "0.4.2.0" VIAddVersionKey "ProductName" "Raptor Link" VIAddVersionKey "FileDescription" "Raptor Link - installation Windows" -VIAddVersionKey "FileVersion" "0.3.13" +VIAddVersionKey "FileVersion" "0.4.2" VIAddVersionKey "LegalCopyright" "Application independante - 2026" !define MUI_ABORTWARNING !define MUI_WELCOMEPAGE_TITLE "Bienvenue dans Raptor Link" @@ -61,7 +61,7 @@ Section "Raptor Link" WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "DisplayName" "Raptor Link" WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "UninstallString" '"$INSTDIR\Desinstaller.exe"' WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "DisplayIcon" "$INSTDIR\icon.ico" - WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "DisplayVersion" "0.3.13 beta" + WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "DisplayVersion" "0.4.2 beta" WriteRegDWORD HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "NoModify" 1 WriteRegDWORD HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "NoRepair" 1 SectionEnd diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/diagnostics.py b/Raptor-Link-0.3.4-Projet/RaptorLink/diagnostics.py new file mode 100644 index 0000000..2ca3d63 --- /dev/null +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/diagnostics.py @@ -0,0 +1,136 @@ +"""Persistent, low-overhead diagnostics for Raptor Link Core 2.""" +from __future__ import annotations +import datetime as _dt +import json +import os +import queue +import threading +import time +from pathlib import Path + +_LEVELS={"off":0,"normal":1,"detailed":2,"trace":3} + +class Diagnostics: + def __init__(self, root: Path, level="normal", keep_days=7, max_mb=50): + self.root=Path(root) + self.root.mkdir(parents=True,exist_ok=True) + self.level=str(level) if str(level) in _LEVELS else "normal" + self.keep_days=max(1,min(30,int(keep_days))) + self.max_bytes=max(5,min(500,int(max_mb)))*1024*1024 + self.q=queue.Queue(maxsize=5000) + self.done=threading.Event() + self.dropped=0 + self.thread=threading.Thread(target=self._loop,daemon=True,name="RaptorLink-diagnostics") + self.thread.start() + + def configure(self, level=None, keep_days=None, max_mb=None): + if level is not None: + self.level=str(level) if str(level) in _LEVELS else self.level + if keep_days is not None: + self.keep_days=max(1,min(30,int(keep_days))) + if max_mb is not None: + self.max_bytes=max(5,min(500,int(max_mb)))*1024*1024 + + def enabled(self, level="normal"): + return _LEVELS.get(self.level,1)>=_LEVELS.get(level,1) and self.level!="off" + + def event(self, level, category, message, **fields): + if not self.enabled(level): + return + item={ + "ts":time.time(), + "level":level, + "category":str(category)[:40], + "message":str(message)[:1000], + "fields":{str(k)[:60]:self._safe(v) for k,v in fields.items()}, + } + try:self.q.put_nowait(item) + except queue.Full:self.dropped+=1 + + def _safe(self, value): + if isinstance(value,(str,int,float,bool)) or value is None:return value + if isinstance(value,(list,tuple)):return [self._safe(v) for v in value[:100]] + if isinstance(value,dict):return {str(k)[:60]:self._safe(v) for k,v in list(value.items())[:100]} + return str(value)[:500] + + def _path_for(self, ts): + day=_dt.datetime.fromtimestamp(ts).strftime("%Y-%m-%d") + return self.root/f"raptor-link-{day}.log" + + def _format(self, item): + stamp=_dt.datetime.fromtimestamp(item["ts"]).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] + fields=" ".join(f"{k}={json.dumps(v,ensure_ascii=False,separators=(',',':'))}" for k,v in item["fields"].items()) + return f"{stamp} [{item['level'].upper()}] [{item['category']}] {item['message']}{(' | '+fields) if fields else ''}\n" + + def _loop(self): + last_cleanup=0.0 + while not self.done.is_set() or not self.q.empty(): + try:item=self.q.get(timeout=.5) + except queue.Empty:item=None + if item is not None: + try: + p=self._path_for(item["ts"]) + with p.open("a",encoding="utf-8",buffering=1) as f:f.write(self._format(item)) + except OSError:pass + now=time.time() + if now-last_cleanup>300: + last_cleanup=now + self._cleanup(now) + + def _cleanup(self, now=None): + now=time.time() if now is None else now + files=sorted(self.root.glob("raptor-link-*.log"),key=lambda p:p.stat().st_mtime if p.exists() else 0) + cutoff=now-self.keep_days*86400 + for p in files: + try: + if p.stat().st_mtimemax_lines:lines=lines[-max_lines:] + except OSError:pass + return lines[-max_lines:] + + def report(self, minutes=30, context=None): + context=context or {} + head=[ + "RAPTOR LINK — RAPPORT DIAGNOSTIC CORE 2", + "="*44, + f"GĂ©nĂ©rĂ© : {_dt.datetime.now().isoformat(sep=' ',timespec='seconds')}", + f"Niveau journal : {self.level}", + f"RĂ©tention : {self.keep_days} jour(s) / {self.max_bytes//1024//1024} Mo", + f"ÉvĂ©nements perdus (file pleine) : {self.dropped}", + "", + "ÉTAT ACTUEL", + "-"*44, + ] + for k,v in context.items(): + head.append(f"{k}: {v}") + head+=["","CHRONOLOGIE","-"*44] + return "\n".join(head+self.recent_lines(minutes)) + + def close(self): + self.done.set() + self.thread.join(timeout=2) diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/engine.py b/Raptor-Link-0.3.4-Projet/RaptorLink/engine.py index a492fe4..6da8368 100644 --- a/Raptor-Link-0.3.4-Projet/RaptorLink/engine.py +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/engine.py @@ -21,9 +21,11 @@ from cue_base import Cue, Device, Filter, Position, Color, check, Idle, sources from openrgb_source import OpenRGBWorker from msi_source import MsiWorker, install_official_sdk, sdk_status +from wled_worker import WledWorker +from diagnostics import Diagnostics HTTP=urllib.request.build_opener(urllib.request.ProxyHandler({})) -DEFAULT={'version':1,'settings':{'idle_seconds':300,'fps':25,'lock_off':True,'auto_sync':False,'startup':False,'language':'fr','check_updates':True,'experimental_rgb':False},'targets':[]} +DEFAULT={'version':1,'settings':{'idle_seconds':300,'fps':25,'lock_off':True,'auto_sync':False,'startup':False,'language':'fr','check_updates':True,'experimental_rgb':False,'diagnostic_level':'normal','diagnostic_days':7,'diagnostic_max_mb':50},'targets':[]} def address(value): ip=ipaddress.ip_address(value) @@ -47,6 +49,10 @@ def validate(raw): if not lo<=s[key]<=hi: raise ValueError('RĂ©glage hors limites : '+key) for k in ['lock_off','auto_sync','startup','check_updates','experimental_rgb']: s[k]=bool(s.get(k,True if k=='check_updates' else False)) if s['language'] not in ['fr','en']: s['language']='fr' + s['diagnostic_level']=str(s.get('diagnostic_level','normal')) + if s['diagnostic_level'] not in ['off','normal','detailed','trace']:s['diagnostic_level']='normal' + s['diagnostic_days']=max(1,min(30,int(s.get('diagnostic_days',7)))) + s['diagnostic_max_mb']=max(5,min(500,int(s.get('diagnostic_max_mb',50)))) targets=raw.get('targets',[]) if not isinstance(targets,list) or len(targets)>32: raise ValueError('32 Ă©clairages maximum') seen=set() @@ -105,7 +111,7 @@ def render_target(target,colors): gain=target['brightness']/100 return [tuple(round(v*gain) for v in c) for c in pixels] -def packets(pixels,timeout=2): +def packets(pixels,timeout=5): if len(pixels)<=490: return [bytes([2,timeout])+bytes(v for c in pixels for v in c)] output=[] @@ -119,8 +125,10 @@ def probe_target(t,initialize=False,demo=False): info=http(t['ip'],'/json/info') if info.get('leds',{}).get('count')!=t['count']:raise ValueError('Nombre de LED diffĂ©rent : utilisez VĂ©rifier.') if not initialize:return None + # Capture the state for a later restore, but never switch WLED off while + # probing. At Windows startup the network can be late and repeated probes + # must remain read-only or the strip visibly blinks. st=http(t['ip'],'/json/state') - http(t['ip'],'/json/state',{'on':False,'transition':0}) return {k:st[k] for k in ['on','bri','transition','mainseg','seg'] if k in st} class GenericCue(Cue): @@ -155,6 +163,7 @@ def __init__(self,logger,command=None): self.log=logger;self.lock=threading.RLock();self.done=threading.Event();self.process=None self.required=set();self.force_scan=True;self.interval=1/25;self.devices=[];self.colors={};self.error='' self.busy_since=None;self.operation='';self.last_progress=time.monotonic();self.last_ok=0;self.restarts=0 + self.color_updates=0;self.color_changes=0;self.last_color_change=0.0 self.command=command or self._default_command() self.thread=threading.Thread(target=self.loop,daemon=True,name='RaptorLink-iCUE-bridge');self.thread.start() def _default_command(self): @@ -175,7 +184,9 @@ def snapshot(self): kill=self.process state={'devices':copy.deepcopy(self.devices),'colors':copy.deepcopy(self.colors),'error':self.error, 'stalled':stalled,'operation':self.operation if stalled else '', - 'age':max(0,now-self.last_progress),'last_ok':self.last_ok,'restarts':self.restarts} + 'age':max(0,now-self.last_progress),'last_ok':self.last_ok,'restarts':self.restarts, + 'color_updates':self.color_updates,'color_changes':self.color_changes, + 'color_change_age':None if not self.last_color_change else max(0,now-self.last_color_change)} if kill is not None: try:kill.kill() except Exception:pass @@ -208,7 +219,12 @@ def _publish(self,data=None,error=None): with self.lock: if data is not None: self.devices=copy.deepcopy(data.get('devices',[])) - self.colors={str(dev):{int(k):tuple(v) for k,v in vals.items()} for dev,vals in data.get('colors',{}).items()} + new_colors={str(dev):{int(k):tuple(v) for k,v in vals.items()} for dev,vals in data.get('colors',{}).items()} + if data.get('ok'): + self.color_updates+=1 + if new_colors and new_colors!=self.colors: + self.color_changes+=1;self.last_color_change=time.monotonic() + self.colors=new_colors self.error=str(data.get('error',''));self.last_ok=time.monotonic() if data.get('ok') else self.last_ok if error is not None:self.error=str(error) self.last_progress=time.monotonic() @@ -263,29 +279,65 @@ def __init__(self,path,demo=False): self.config=validate(DEFAULT);self.devices=[];self.colors={};self.logs=[];self.active=[];self.original={} self.want_run=False;self.running=False;self.keep_awake=False;self.status='DĂ©marrage';self.icue=None;self.msi=None;self.openrgb=None;self.icue_notice=False;self.msi_notice=False;self.openrgb_notice=False;self.loop_heartbeat=time.monotonic() self.plan_ip='';self.plan_frame=[];self.preview_device='';self.idle=0;self.is_locked=False;self.target_status={};self.revision=0;self.scan_requested=True + config_error='' try: if path.exists(): self.config=validate(json.loads(path.read_text(encoding='utf-8'))) - except Exception as e: self.log('Configuration non chargĂ©e : '+str(e)) + except Exception as e: config_error='Configuration non chargĂ©e : '+str(e) + ds=self.config['settings'] + self.diag=Diagnostics(path.parent/'diagnostics',ds.get('diagnostic_level','normal'),ds.get('diagnostic_days',7),ds.get('diagnostic_max_mb',50)) + self.wled_workers={} self.want_run=self.config['settings']['auto_sync'] - self.tests={};self.fades={};self.history={};self.frames={};self.alarm_seen={};self.alarms={};self.previews={} + self.tests={};self.color_tests={};self.fades={};self.history={};self.frames={};self.alarm_seen={};self.alarms={};self.previews={};self.gate_states={} + if config_error:self.log(config_error,'CONFIG') try:self.alarm_seen=json.loads(path.with_name('alarms-fired.json').read_text()) except Exception:pass + self.diag.event('normal','ENGINE','Raptor Link Core 2 dĂ©marrĂ©',demo=self.demo,auto_sync=self.want_run) self.thread=threading.Thread(target=self.loop,daemon=True);self.thread.start() - def log(self,msg): + def log(self,msg,category='ENGINE',level='normal',**fields): with self.lock: self.logs.append(time.strftime('%H:%M:%S')+' '+str(msg));self.logs=self.logs[-80:] + try:self.diag.event(level,category,str(msg),**fields) + except Exception:pass + def worker(self,target): + ip=target['ip'] + w=self.wled_workers.get(ip) + if w is None and not self.demo: + w=WledWorker(target,self.log,self.diag);self.wled_workers[ip]=w + self.log(target['name']+' : worker WLED Core 2 créé','WLED-STATE','detailed',ip=ip) + elif w is not None:w.update_target(target) + return w def snapshot(self): with self.lock: + workers={ip:w.snapshot() for ip,w in self.wled_workers.items()} return copy.deepcopy({'devices':self.devices,'colors':self.colors,'running':self.running,'requested':self.want_run, 'status':self.status,'logs':self.logs[-15:],'idle':int(self.idle),'locked':self.is_locked,'keep_awake':self.keep_awake, - 'plan_ip':self.plan_ip,'plan_frame':self.plan_frame,'targets':self.target_status,'demo':self.demo,'revision':self.revision,'audio_level':self.capture.level if hasattr(self,'capture') else 0,'frames':self.previews,'engine_age':max(0,time.monotonic()-self.loop_heartbeat),'icue':self.icue.snapshot() if self.icue else {},'msi':self.msi.snapshot() if self.msi else {},'openrgb':self.openrgb.snapshot() if self.openrgb else {},'capture_error':' ; '.join(filter(None,[getattr(getattr(self,'capture',None),'error',''),getattr(getattr(self,'capture',None),'screen_error','')]))}) + 'plan_ip':self.plan_ip,'plan_frame':self.plan_frame,'targets':self.target_status,'demo':self.demo,'revision':self.revision,'audio_level':self.capture.level if hasattr(self,'capture') else 0,'frames':self.previews,'engine_age':max(0,time.monotonic()-self.loop_heartbeat),'icue':self.icue.snapshot() if self.icue else {},'msi':self.msi.snapshot() if self.msi else {},'openrgb':self.openrgb.snapshot() if self.openrgb else {},'wled_workers':workers,'capture_error':' ; '.join(filter(None,[getattr(getattr(self,'capture',None),'error',''),getattr(getattr(self,'capture',None),'screen_error','')]))}) + def diagnostic_report(self,minutes=30): + state=self.snapshot() + context={ + 'running':state['running'], + 'requested':state['requested'], + 'status':state['status'], + 'idle_seconds':state['idle'], + 'locked':state['locked'], + 'keep_awake':state['keep_awake'], + 'icue_stalled':bool(state.get('icue',{}).get('stalled')), + 'icue_restarts':state.get('icue',{}).get('restarts',0), + 'icue_color_updates':state.get('icue',{}).get('color_updates',0), + 'icue_color_changes':state.get('icue',{}).get('color_changes',0), + 'icue_color_change_age':state.get('icue',{}).get('color_change_age'), + 'targets':json.dumps(state.get('targets',{}),ensure_ascii=False), + 'wled_workers':json.dumps(state.get('wled_workers',{}),ensure_ascii=False), + } + return self.diag.report(int(minutes),context) def save(self,cfg): cfg=validate(cfg) with self.lock: self.want_run=False temp=self.path.with_suffix('.tmp');temp.write_text(json.dumps(cfg,indent=2,ensure_ascii=False),encoding='utf-8');os.replace(temp,self.path) self.config=cfg;self.revision+=1 - self.log('Configuration enregistrĂ©e. Relancez la synchronisation pour appliquer les associations.') + ds=cfg['settings'];self.diag.configure(ds.get('diagnostic_level'),ds.get('diagnostic_days'),ds.get('diagnostic_max_mb')) + self.log('Configuration enregistrĂ©e. Relancez la synchronisation pour appliquer les associations.','CONFIG') def msi_status(self): base=sdk_status(self.path.parent) if self.msi: @@ -321,25 +373,69 @@ def stop(self): self.want_run=False def shutdown(self): self.want_run=False;self.done.set();self.thread.join(timeout=15) + # restore() is requested by the engine loop during shutdown. Give the + # per-WLED workers enough time to leave realtime mode and apply OFF / + # preset / restore before terminating them. + if self.wled_workers:time.sleep(2.4) + for w in list(self.wled_workers.values()): + try:w.close() + except Exception:pass + self.wled_workers.clear() + try:self.diag.close() + except Exception:pass def restore(self): + now=datetime.datetime.now() for t in self.active: - if self.demo or t['ip'] not in self.original: continue + if self.demo:continue try: - self.udp.sendto(bytes([2,0]),(t['ip'],t['port'])) - if not window(t['schedule'],datetime.datetime.now()): payload={'on':False,'transition':0} - elif t['on_stop']=='restore': payload=self.original.get(t['ip'],{'on':False}) - elif t['on_stop']=='preset': payload={'ps':t['preset']} - else: payload={'on':False,'transition':0} - http(t['ip'],'/json/state',payload) - except Exception as e: self.log(t['name']+' : restauration impossible ('+str(e)+')') - self.active=[];self.original={};self.running=False;self.target_status={} + w=self.worker(t) + if not window(t['schedule'],now): + w.off('Hors horaires Ă  l’arrĂȘt',0) + elif t['on_stop']=='restore': + w.restore(self.original.get(t['ip'],{'on':False}),'RĂ©tablissement de l’état initial') + elif t['on_stop']=='preset': + w.preset(t['preset'],'Preset WLED Ă  l’arrĂȘt',0) + else: + w.off('ArrĂȘt de la synchronisation',0) + except Exception as e:self.log(t['name']+' : restauration impossible ('+str(e)+')','WLED-STATE') + self.active=[];self.original={};self.running=False;self.target_status={};self.gate_states={} def prepare(self): with self.lock: cfg=copy.deepcopy(self.config); revision=self.revision self.active=[t for t in cfg['targets'] if t['enabled']] self.run_revision=revision;self.run_settings=cfg['settings'];self.running=True - self.fades={};self.history={};self.frames={};self.target_status={};self.alarms={} - self.log('Synchronisation dĂ©marrĂ©e : chaque Ă©clairage est traitĂ© indĂ©pendamment.') + self.fades={};self.history={};self.frames={};self.target_status={};self.alarms={};self.gate_states={} + for t in self.active: + if not self.demo:self.worker(t).hold('PrĂ©paration de la synchronisation') + self.log('Synchronisation Core 2 dĂ©marrĂ©e : un worker indĂ©pendant par WLED.','ENGINE') + def reboot_wled(self,ip,reason="RedĂ©marrage manuel"): + with self.lock:t=next((copy.deepcopy(t) for t in self.config['targets'] if t['ip']==ip),None) + if not t:raise ValueError('WLED inconnu.') + if self.demo:return {'ok':True,'queued':True,'name':t['name']} + queued=self.worker(t).reboot(reason) + self.log(t['name']+' : redĂ©marrage WLED demandĂ©','WLED-STATE','normal',ip=t['ip']) + return {'ok':True,'queued':bool(queued),'name':t['name']} + + def reboot_all_wled(self): + with self.lock:targets=copy.deepcopy(self.config['targets']) + if self.demo:return {'ok':True,'count':len(targets)} + def sequence(): + for t in targets: + if self.done.is_set():break + try:self.worker(t).reboot('RedĂ©marrage global demandĂ©') + except Exception as e:self.log(t['name']+' : redĂ©marrage impossible ('+str(e)+')','WLED-STATE') + self.done.wait(.6) + threading.Thread(target=sequence,daemon=True,name='RaptorLink-WLED-reboot-all').start() + self.log('RedĂ©marrage de tous les WLED demandĂ© ('+str(len(targets))+')','WLED-STATE') + return {'ok':True,'count':len(targets)} + + def color_diagnostic(self,ip): + t=next((t for t in self.active if t['ip']==ip),None) + if not self.running or not t:raise ValueError('DĂ©marrez la synchronisation avant le diagnostic couleurs.') + now=time.monotonic();self.color_tests[ip]=(now,now+8.0) + self.log(t['name']+' : diagnostic couleurs rouge/vert/bleu/blanc dĂ©marrĂ©','WLED-STATE','normal',ip=ip) + return {'ok':True,'duration':8} + def identify(self,ip): t=next((t for t in self.config['targets'] if t['ip']==ip),None) if not t:raise ValueError('Enregistrez cet Ă©clairage avant le test.') @@ -382,7 +478,7 @@ def demo_scan(self): def loop(self): import colorsys self.udp=socket.socket(socket.AF_INET,socket.SOCK_DGRAM);self.udp.settimeout(.2) - pool=ThreadPoolExecutor(max_workers=8);pending={};health={};next_probe={} + pool=ThreadPoolExecutor(max_workers=4);pending={};restore_probe_done=set() self.capture=Capture();last_frame=time.monotonic();last_error='' if not self.demo: self.icue=IcueWorker(self.log) @@ -406,7 +502,7 @@ def loop(self): self.openrgb.close();self.openrgb=None;self.openrgb_notice=False if self.running and (not self.want_run or self.run_revision!=self.revision): for f in pending.values():f.cancel() - pending={};self.restore();health={};next_probe={} + pending={};restore_probe_done=set();self.restore() cue_state={};msi_state={};openrgb_state={} if not self.demo: self.idle=idle.seconds();self.is_locked=idle.locked() @@ -486,56 +582,102 @@ def loop(self): states={};frames={};self.plan_frame=[] if self.running: for t in self.active: - ip=t['ip'] - # A slow/unreachable WLED never blocks another one's UDP stream. - if ip in pending and pending[ip].done(): + ip=t['ip'];worker=None if self.demo else self.worker(t) + + # The normal realtime path performs no periodic HTTP health + # polling. Only targets configured to restore their previous + # state get one best-effort snapshot at the beginning. + if t['on_stop']=='restore' and ip in pending and pending[ip].done(): try: original=pending.pop(ip).result() - if original is not None and ip not in self.original:self.original[ip]=original - if health.get(ip)!='ok':self.fades[ip]=Fade() - health[ip]='ok' + if original is not None:self.original[ip]=original + self.log(t['name']+' : Ă©tat initial mĂ©morisĂ©','WLED-HTTP','detailed',ip=ip) except Exception as e: - msg=str(e) - if health.get(ip)!=msg:self.log(t['name']+' : '+msg) - health[ip]=msg - next_probe[ip]=start+8 - if ip not in pending and start>=next_probe.get(ip,0):pending[ip]=pool.submit(probe_target,t,health.get(ip)!='ok',self.demo) - if health.get(ip)!='ok': - states[ip]='Reconnexion
' if ip not in health else health[ip];continue - errors=[] + pending.pop(ip,None) + self.log(t['name']+' : Ă©tat initial indisponible ('+str(e)+')','WLED-HTTP','detailed',ip=ip) + if not self.demo and t['on_stop']=='restore' and ip not in self.original and ip not in pending and ip not in restore_probe_done: + restore_probe_done.add(ip);pending[ip]=pool.submit(probe_target,t,True,False) + + errors=[];source_missing=False for i,r in enumerate(t['routes']): if r['source'] in ('msi','openrgb') and not experimental: - errors.append('Association '+str(i+1)+' : source RGB expĂ©rimentale dĂ©sactivĂ©e') + errors.append('Association '+str(i+1)+' : source RGB expĂ©rimentale dĂ©sactivĂ©e');source_missing=True elif r['source'] in ('icue','msi','openrgb') and (not r['ids'] or any(x not in colors.get(r['device'],{}) for x in r['ids'])): - errors.append('Association '+str(i+1)+' : appareil ou LED indisponibles') - if not self.demo and on_screen_missing(t,self.capture):errors.append('Écran indisponible : vĂ©rifiez la sĂ©lection dans la zone') + errors.append('Association '+str(i+1)+' : appareil ou LED indisponibles');source_missing=True + if not self.demo and on_screen_missing(t,self.capture): + errors.append('Écran indisponible : vĂ©rifiez la sĂ©lection dans la zone');source_missing=True if not t['routes']:errors.append('Ajoutez une association') + due=due_alarm(t,now,self.alarm_seen) if due is not None: try: alarm_file=self.path.with_name('alarms-fired.json');tmp=alarm_file.with_suffix('.tmp');tmp.write_text(json.dumps(self.alarm_seen));os.replace(tmp,alarm_file) - except OSError as e:self.log('MĂ©morisation du rĂ©veil : '+str(e)) + except OSError as e:self.log('MĂ©morisation du rĂ©veil : '+str(e),'AUTOMATION') if window(t['schedule'],now):self.alarms[ip]=(start+due['duration'],copy.deepcopy(due)) - end,alarm=self.alarms.get(ip,(0,None)) - alarm_on=start0:frame=self.frames.get(ip,frame) frame=[tuple(round(v*gain) for v in c) for c in frame] - if not self.demo: - try: - for packet in packets(frame):self.udp.sendto(packet,(ip,t['port'])) - except OSError as e:health[ip]=str(e);next_probe[ip]=0 - states[ip]=('; '.join(errors) if errors and on and not alarm_on else label) + + if worker: + if on or gain>0: + worker.stream(frame,self.run_settings.get('fps',25),label) + else: + worker.off(label,0) + ws=worker.snapshot() + states[ip]=('; '.join(errors) if errors and on and not alarm_on else label)+' · '+ws['state'] + else: + states[ip]=('; '.join(errors) if errors and on and not alarm_on else label) + if ip==self.plan_ip:self.plan_frame=frame frames[ip]=frame[::max(1,len(frame)//200)] self.target_status=states;self.previews=frames diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/features.py b/Raptor-Link-0.3.4-Projet/RaptorLink/features.py index 1b1c4b3..0ab85ed 100644 --- a/Raptor-Link-0.3.4-Projet/RaptorLink/features.py +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/features.py @@ -47,7 +47,7 @@ def extras(cfg,raw): if alarm.get('effect') not in ['rainbow','breathe','chase','solid']:raise ValueError('Effet rĂ©veil invalide') for r in t['routes']: r['source']=r.get('source','icue') - if r['source'] not in ['icue','msi','openrgb','rainbow','breathe','chase','solid','screen','audio']:raise ValueError('Source inconnue') + if r['source'] not in ['icue','msi','openrgb','rainbow','breathe','chase','solid','screen','audio','wled_preset']:raise ValueError('Source inconnue') r['rgb_ecosystem']=str(r.get('rgb_ecosystem','openrgb'))[:32] if r['rgb_ecosystem'] not in ['openrgb','msi','gigabyte','asus','razer','logitech','steelseries']:r['rgb_ecosystem']='openrgb' # 0.3.7 represented MSI through OpenRGB. From 0.3.8, migrate that @@ -71,6 +71,7 @@ def extras(cfg,raw): r['color']=r.get('color',[255,100,20]) if not isinstance(r['color'],list) or len(r['color'])!=3:raise ValueError('Couleur invalide') r['color']=[int(number(c,0,255,'Couleur')) for c in r['color']] + r['wled_preset']=int(number(r.get('wled_preset',1),1,250,'Preset WLED')) pts=r.get('points',[[.05,.5],[.95,.5]]) if not isinstance(pts,list) or not 2<=len(pts)<=64:raise ValueError('Le tracĂ© demande 2 Ă  64 points') r['points']=[[number(p[0],0,1,'Position'),number(p[1],0,1,'Position')] for p in pts] @@ -80,6 +81,13 @@ def extras(cfg,raw): if any(not isinstance(c,int) or isinstance(c,bool) or c<0 for c in counts):raise ValueError('Nombre de LED par segment : entier positif ou nul') if sum(counts)!=r['end']-r['start']+1:raise ValueError(t['name']+' : le total des LED du plan doit correspondre Ă  la plage de la zone') r['path_counts']=counts + autonomous=[r for r in t['routes'] if r.get('source')=='wled_preset'] + if autonomous: + if len(t['routes'])!=1: + raise ValueError(t['name']+' : un preset WLED autonome doit ĂȘtre la seule source de cet Ă©clairage') + r=autonomous[0] + if r['start']!=1 or r['end']!=t['count']: + raise ValueError(t['name']+' : le preset WLED autonome doit couvrir tout le ruban') cfg['profiles']=copy.deepcopy(raw.get('profiles',[])) if not isinstance(cfg['profiles'],list) or len(cfg['profiles'])>20:raise ValueError('20 profils maximum') diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/support.py b/Raptor-Link-0.3.4-Projet/RaptorLink/support.py index 8b88931..a571e6b 100644 --- a/Raptor-Link-0.3.4-Projet/RaptorLink/support.py +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/support.py @@ -10,7 +10,7 @@ import urllib.request from pathlib import Path -APP_VERSION = "0.3.13" +APP_VERSION = "0.4.2" REPOSITORY = "Inter-Raptor/Raptor-Link" RELEASES_API = f"https://api.github.com/repos/{REPOSITORY}/releases?per_page=10" ISSUES_NEW = f"https://github.com/{REPOSITORY}/issues/new" diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/web/extras.js b/Raptor-Link-0.3.4-Projet/RaptorLink/web/extras.js index fa2aa02..4cff917 100644 --- a/Raptor-Link-0.3.4-Projet/RaptorLink/web/extras.js +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/web/extras.js @@ -2,24 +2,24 @@ const extraTitles={plan:['Correspondance Ă©cran → LED.','Visualisez chaque LED et choisissez les couleurs qu’elle doit suivre.'],profiles:['Une ambiance, un clic.','Enregistrez vos Ă©clairages, associations et horaires ensemble.']}; const baseHeader=renderHeader;renderHeader=function(){if(extraTitles[page]){$('page-title').textContent=extraTitles[page][0];$('page-sub').textContent=extraTitles[page][1];$('crumb').textContent=page.toUpperCase();}else baseHeader();}; const baseShow=showPage;showPage=function(p){baseShow(p);if(p==='plan')drawPlan();if(p==='profiles')drawProfiles();}; -const baseRoutes=renderRoutes;renderRoutes=function(){baseRoutes();const t=currentTarget();if(t)document.querySelectorAll('[data-route]').forEach((b,i)=>{const r=t.routes[i];if(r?.source&& !['icue','msi','openrgb'].includes(r.source)){b.children[0].textContent=`LED ${r.start}–${r.end}`;b.children[1].textContent=({screen:'Raptor Link · Couleurs Ă©cran',audio:'Raptor Link · RĂ©action audio',rainbow:'Raptor Link · Arc-en-ciel',breathe:'Raptor Link · Respiration',chase:'Raptor Link · ComĂšte',solid:'Raptor Link · Couleur fixe'})[r.source];}else if(r?.source==='msi'){b.children[1].textContent=experimentalEnabled()?'MSI Mystic Light · ExpĂ©rimental':'Source expĂ©rimentale dĂ©sactivĂ©e';}else if(r?.source==='openrgb'){const labels={openrgb:'OpenRGB',msi:'MSI via OpenRGB',gigabyte:'Gigabyte RGB Fusion',asus:'ASUS Aura / Armoury Crate',razer:'Razer Chroma',logitech:'Logitech G HUB',steelseries:'SteelSeries GG / Prism'};b.children[1].textContent=experimentalEnabled()?(labels[r.rgb_ecosystem||'openrgb']||'OpenRGB')+' · ExpĂ©rimental':'Source expĂ©rimentale dĂ©sactivĂ©e';}});}; +const baseRoutes=renderRoutes;renderRoutes=function(){baseRoutes();const t=currentTarget();if(t)document.querySelectorAll('[data-route]').forEach((b,i)=>{const r=t.routes[i];if(r?.source&& !['icue','msi','openrgb'].includes(r.source)){b.children[0].textContent=`LED ${r.start}–${r.end}`;b.children[1].textContent=({screen:'Raptor Link · Couleurs Ă©cran',audio:'Raptor Link · RĂ©action audio',rainbow:'Raptor Link · Arc-en-ciel',breathe:'Raptor Link · Respiration',chase:'Raptor Link · ComĂšte',solid:'Raptor Link · Couleur fixe',wled_preset:'WLED autonome · Preset '+(r.wled_preset||1)})[r.source];}else if(r?.source==='msi'){b.children[1].textContent=experimentalEnabled()?'MSI Mystic Light · ExpĂ©rimental':'Source expĂ©rimentale dĂ©sactivĂ©e';}else if(r?.source==='openrgb'){const labels={openrgb:'OpenRGB',msi:'MSI via OpenRGB',gigabyte:'Gigabyte RGB Fusion',asus:'ASUS Aura / Armoury Crate',razer:'Razer Chroma',logitech:'Logitech G HUB',steelseries:'SteelSeries GG / Prism'};b.children[1].textContent=experimentalEnabled()?(labels[r.rgb_ecosystem||'openrgb']||'OpenRGB')+' · ExpĂ©rimental':'Source expĂ©rimentale dĂ©sactivĂ©e';}});}; const baseEditor=renderEditor;renderEditor=function(){baseEditor();if($('zone-source'))fillExtra();}; const baseSettings=settingsUI;settingsUI=function(){baseSettings();if($('fade-in')){const s=config.settings;$('fade-in').value=s.fade_in??3;$('fade-out').value=s.fade_out??2;$('logo-motion').checked=s.logo_animation!==false;}}; const basePreviews=renderPreviews;renderPreviews=function(){basePreviews();const t=currentTarget();if(t&&state.running&&!dirty&&state.frames?.[t.ip])strip($('output-preview'),state.frames[t.ip]);if($('effect-preview')&&t){strip($('effect-preview'),state.frames?.[t.ip]||Array(32).fill([35,65,78]));}}; -function defaults(t){t.schedule??={enabled:false,start:'08:00',end:'23:00',mode:'active',days:[0,1,2,3,4,5,6]};t.alarms??=t.alarm?[{...t.alarm,id:'legacy',name:'RĂ©veil 1'}]:[];delete t.alarm;for(const r of t.routes){r.source??='icue';r.brightness??=100;r.offset??=0;r.smooth??=0;r.speed??=1;r.color??=[255,100,20];r.points??=[[.1,.5],[.9,.5]];}} +function defaults(t){t.schedule??={enabled:false,start:'08:00',end:'23:00',mode:'active',days:[0,1,2,3,4,5,6]};t.alarms??=t.alarm?[{...t.alarm,id:'legacy',name:'RĂ©veil 1'}]:[];delete t.alarm;for(const r of t.routes){r.source??='icue';r.brightness??=100;r.offset??=0;r.smooth??=0;r.speed??=1;r.color??=[255,100,20];r.wled_preset??=1;r.points??=[[.1,.5],[.9,.5]];}} function field(id,label,type,value,attrs=''){return ``;} function days(id,values){return ['L','M','M','J','V','S','D'].map((d,i)=>``).join('');} function sourceOptions(r){ - const normal=``; + const normal=``; let hidden=''; if(!experimentalEnabled()&&['msi','openrgb'].includes(r?.source))hidden=''; const experimental=experimentalEnabled()?``:''; return hidden+normal+experimental; } function fillExtra(){const t=currentTarget(),r=currentRoute();if(!t)return;defaults(t); -$('zone-source').innerHTML=sourceOptions(r);if(!experimentalEnabled()&&['msi','openrgb'].includes(r?.source))$('zone-source').value='__experimental_current';else $('zone-source').value=r?.source==='openrgb'?'openrgb:'+(r.rgb_ecosystem||'openrgb'):(r?.source||'icue');$('zone-bright').value=r?.brightness??100;$('zone-offset').value=r?.offset??0;$('zone-smooth').value=r?.smooth??0;$('zone-speed').value=r?.speed??1;$('zone-color').value='#'+(r?.color||[255,100,20]).map(x=>x.toString(16).padStart(2,'0')).join(''); +$('zone-source').innerHTML=sourceOptions(r);if(!experimentalEnabled()&&['msi','openrgb'].includes(r?.source))$('zone-source').value='__experimental_current';else $('zone-source').value=r?.source==='openrgb'?'openrgb:'+(r.rgb_ecosystem||'openrgb'):(r?.source||'icue');$('zone-bright').value=r?.brightness??100;$('zone-offset').value=r?.offset??0;$('zone-smooth').value=r?.smooth??0;$('zone-speed').value=r?.speed??1;$('zone-color').value='#'+(r?.color||[255,100,20]).map(x=>x.toString(16).padStart(2,'0')).join('');if($('zone-wled-preset')){$('zone-wled-preset').value=r?.wled_preset??1;$('wled-preset-options').hidden=r?.source!=='wled_preset';} $('zone-spatial').checked=!!r?.spatial;$('zone-axis').value=r?.axis||'x'; -const external=(!r||r.source==='icue'||(experimentalEnabled()&&['msi','openrgb'].includes(r.source)));document.querySelector('.source-panel')?.classList.toggle('local-effect',!external);const deviceLabel=$('source-device')?.closest('label')?.querySelector('span');if(deviceLabel)deviceLabel.textContent=r?.source==='icue'?'Appareil iCUE':(['msi','openrgb'].includes(r?.source)?'Appareil expĂ©rimental':'Appareil source');renderRoutes();document.querySelectorAll('.source-panel>.fields,.source-panel>.mode-toolbar,.source-panel>.canvas-wrap,#selection-hint').forEach(e=>e.classList.toggle('hidden',!external));if(!r||r.source==='icue')$('alternate-info').innerHTML='iCUE · TESTÉ & VALIDÉ Copie les couleurs des LED Corsair vers votre WLED.';else if(r.source==='msi')$('alternate-info').innerHTML=experimentalEnabled()?'EXPÉRIMENTAL · LIMITÉ Mystic Light est encore en dĂ©veloppement. Le SDK MSI expose surtout des zones logiques et ne permet pas de recopier correctement toutes les animations adressables.':'SOURCE EXPÉRIMENTALE MASQUÉE Activez le laboratoire RGB dans RĂ©glages avancĂ©s pour continuer ce test.';else if(r.source==='openrgb')$('alternate-info').innerHTML=experimentalEnabled()?'EXPÉRIMENTAL · VIA OPENRGB Fonction non finalisĂ©e pouvant nĂ©cessiter des manipulations supplĂ©mentaires.':'SOURCE EXPÉRIMENTALE MASQUÉE Activez le laboratoire RGB dans RĂ©glages avancĂ©s pour continuer ce test.';else $('alternate-info').textContent=r.source==='screen'?'Raptor Link prĂ©lĂšve directement les couleurs de l’écran suivant votre tracĂ©.':r.source==='audio'?'Raptor Link gĂ©nĂšre directement les couleurs Ă  partir du son sĂ©lectionnĂ© dans RĂ©glages.':'Animation gĂ©nĂ©rĂ©e directement par Raptor Link, sans logiciel RGB tiers.'; +const external=(!r||r.source==='icue'||(experimentalEnabled()&&['msi','openrgb'].includes(r.source)));document.querySelector('.source-panel')?.classList.toggle('local-effect',!external);const deviceLabel=$('source-device')?.closest('label')?.querySelector('span');if(deviceLabel)deviceLabel.textContent=r?.source==='icue'?'Appareil iCUE':(['msi','openrgb'].includes(r?.source)?'Appareil expĂ©rimental':'Appareil source');renderRoutes();document.querySelectorAll('.source-panel>.fields,.source-panel>.mode-toolbar,.source-panel>.canvas-wrap,#selection-hint').forEach(e=>e.classList.toggle('hidden',!external));if(!r||r.source==='icue')$('alternate-info').innerHTML='iCUE · TESTÉ & VALIDÉ Copie les couleurs des LED Corsair vers votre WLED.';else if(r.source==='wled_preset')$('alternate-info').innerHTML='WLED AUTONOME · RECOMMANDÉ Raptor Link lance le preset une seule fois puis WLED anime lui-mĂȘme. Aucun flux RGB continu : plus lĂ©ger et beaucoup plus robuste pour les effets autonomes.';else if(r.source==='msi')$('alternate-info').innerHTML=experimentalEnabled()?'EXPÉRIMENTAL · LIMITÉ Mystic Light est encore en dĂ©veloppement. Le SDK MSI expose surtout des zones logiques et ne permet pas de recopier correctement toutes les animations adressables.':'SOURCE EXPÉRIMENTALE MASQUÉE Activez le laboratoire RGB dans RĂ©glages avancĂ©s pour continuer ce test.';else if(r.source==='openrgb')$('alternate-info').innerHTML=experimentalEnabled()?'EXPÉRIMENTAL · VIA OPENRGB Fonction non finalisĂ©e pouvant nĂ©cessiter des manipulations supplĂ©mentaires.':'SOURCE EXPÉRIMENTALE MASQUÉE Activez le laboratoire RGB dans RĂ©glages avancĂ©s pour continuer ce test.';else $('alternate-info').textContent=r.source==='screen'?'Raptor Link prĂ©lĂšve directement les couleurs de l’écran suivant votre tracĂ©.':r.source==='audio'?'Raptor Link gĂ©nĂšre directement les couleurs Ă  partir du son sĂ©lectionnĂ© dans RĂ©glages.':'Animation gĂ©nĂ©rĂ©e directement par Raptor Link, sans logiciel RGB tiers.'; $('schedule-enabled').checked=!!t.schedule.enabled;$('schedule-start').value=t.schedule.start;$('schedule-end').value=t.schedule.end;$('schedule-mode').value=t.schedule.mode;$('schedule-days').innerHTML=days('schedule',t.schedule.days); drawAlarms();drawScreenOptions(); } @@ -27,14 +27,14 @@ function setupExtras(){ api('window-ready',{}).catch(()=>{}); document.title='Raptor Link · '+location.port;document.querySelector('.brand').innerHTML='
RAPTORLINK / PAR VIVIEN
'; document.querySelector('header .eyebrow').firstChild.textContent='RAPTOR LINK / '; - document.querySelector('.side-bottom>span').textContent='VERSION 0.3.13 · BÊTA'; + document.querySelector('.side-bottom>span').textContent='VERSION 0.4.2 · CORE 2 BÊTA'; document.querySelector('.sidebar nav').insertAdjacentHTML('beforeend',''); document.querySelectorAll('.nav').forEach(b=>b.onclick=()=>showPage(b.dataset.page)); document.querySelector('footer').insertAdjacentHTML('beforebegin',``); $('page-lights').insertAdjacentHTML('afterbegin','
VOTRE ESPACE. VOTRE SIGNATURE.

La lumiĂšre prend vie.

Du clavier au bureau, une mĂȘme Ă©nergie.

'); $('editor').insertAdjacentHTML('afterbegin','
'); - $('probe').parentElement.insertAdjacentHTML('afterend',''); - document.querySelector('.source-panel').insertAdjacentHTML('afterbegin',`

`); + $('probe').parentElement.insertAdjacentHTML('afterend','
'); + document.querySelector('.source-panel').insertAdjacentHTML('afterbegin',`

`); document.querySelector('.route-settings').insertAdjacentHTML('beforeend',`
RĂ©glages avancĂ©s de la zone${field('zone-bright','LuminositĂ© de la zone (%)','number',100,'min="0" max="100"')}${field('zone-offset','DĂ©calage (LED)','number',0,'min="-10000" max="10000"')}${field('zone-smooth','Fondu entre couleurs (secondes)','number',0,'min="0" max="60" step="0.1"')}${field('zone-speed','Vitesse de l’effet','number',1,'min="0.05" max="10" step="0.1"')}${field('zone-color','Couleur de l’effet','color','#ff6414')}

0 = instantané. Exemple : 1 s pour passer du bleu au rose. Si la couleur change avant la fin, le fondu repart de la couleur affichée. Une durée longue adoucit aussi les animations rapides.

`); document.querySelector('.source-panel').insertAdjacentHTML('beforeend','
APERÇU DU FLUX ENVOYÉ

Démarrez la synchronisation pour voir les couleurs. La vitesse, la couleur et le lissage sont dans les réglages avancés de la zone.

'); $('editor').insertAdjacentHTML('beforeend',`
HORAIRES DE CET ÉCLAIRAGE

La bonne lumiĂšre, au bon moment.

${field('schedule-start','De','time','08:00')}${field('schedule-end','À','time','23:00')}

En dehors : extinction immédiate prioritaire. Une plage peut traverser minuit. Deux heures identiques = 24 h sur les jours cochés.

RÉVEILS LUMINEUX

Vos rendez-vous en couleur.

${field('alarm-name','Nom','text','', 'maxlength="60"')}
${field('alarm-time','Heure','time','09:00')}${field('alarm-duration','Durée (secondes)','number',30,'min="1" max="3600"')}

Chaque rĂ©veil possĂšde ses jours, son heure et sa durĂ©e. Puis retour au fonctionnement normal. Un nouveau rĂ©veil remplace celui en cours ; Ă  heure identique, le dernier de la liste est prioritaire. Respecte les horaires et le verrouillage. Le PC doit ĂȘtre Ă©veillĂ© et la synchronisation lancĂ©e ; aucun rattrapage.

`); @@ -43,8 +43,11 @@ function setupExtras(){ $('page-settings').insertAdjacentHTML('afterbegin',`

Votre signature visuelle

Raptor Link · Un projet de Vivien Jardot.
Votre logo, animĂ© uniquement dans l’interface.

Source audio locale

Choisissez directement une sortie (haut-parleurs, casque ou HDMI), ou une entrée microphone. La sortie par défaut est choisie au lancement de la capture. Aucun enregistrement conservé. Active uniquement avec une zone audio synchronisée.

`); $('profile-new').onclick=handle(async()=>{const name=prompt('Nom de l’ambiance (Jeu, Travail, DĂ©tente
)');if(!name?.trim())return;config.profiles??=[];if(config.profiles.length>=20)throw Error('20 profils maximum');config.profiles.push({name:name.trim(),targets:structuredClone(config.targets)});mark();await save();drawProfiles();}); $('test-light').onclick=handle(async()=>{if(dirty)await save();await api('test',{ip:currentTarget().ip});toast('Test demandĂ© : trois secondes de clignotement.');}); + $('color-test-light').onclick=handle(async()=>{if(dirty)await save();await api('color-test',{ip:currentTarget().ip});toast('Diagnostic RGB : rouge → vert → bleu → blanc, 2 secondes par couleur.');}); + $('reboot-light').onclick=handle(async()=>{const t=currentTarget();if(!t||!confirm('RedĂ©marrer « '+t.name+' » ? La lumiĂšre sera indisponible quelques secondes.'))return;if(dirty)await save();await api('reboot-wled',{ip:t.ip});toast('RedĂ©marrage de '+t.name+' demandĂ©. Raptor Link reprendra le flux automatiquement.');}); for(const [id,key] of [['zone-bright','brightness'],['zone-offset','offset'],['zone-smooth','smooth'],['zone-speed','speed']])$(id).onchange=()=>{if(currentRoute()){currentRoute()[key]=Number($(id).value);mark();}}; - $('zone-source').onchange=()=>{const r=currentRoute();if(!r)return;const value=$('zone-source').value;if(value==='__experimental_current')return;if(value.startsWith('openrgb:')){r.source='openrgb';r.rgb_ecosystem=value.split(':')[1]||'openrgb';}else if(value==='msi'){r.source='msi';r.rgb_ecosystem='msi';}else{r.source=value;r.rgb_ecosystem='openrgb';}r.device='';r.ids=[];group='all';mark();fillExtra();populateDevices();renderMap();}; + $('zone-source').onchange=()=>{const r=currentRoute(),t=currentTarget();if(!r)return;const value=$('zone-source').value;if(value==='__experimental_current')return;if(value==='wled_preset'&&t.routes.length>1){toast('Un preset WLED autonome doit ĂȘtre la seule association de cet Ă©clairage. Supprimez les autres zones avant de l’activer.');fillExtra();return;}if(value.startsWith('openrgb:')){r.source='openrgb';r.rgb_ecosystem=value.split(':')[1]||'openrgb';}else if(value==='msi'){r.source='msi';r.rgb_ecosystem='msi';}else{r.source=value;r.rgb_ecosystem='openrgb';}if(value==='wled_preset'){r.start=1;r.end=t.count;r.wled_preset??=1;}r.device='';r.ids=[];group='all';mark();fillExtra();populateDevices();renderMap();}; + $('zone-wled-preset').onchange=()=>{const r=currentRoute();if(r){r.wled_preset=Math.max(1,Math.min(250,Number($('zone-wled-preset').value)||1));mark();renderRoutes();}}; $('zone-spatial').onchange=()=>{if(currentRoute()){currentRoute().spatial=$('zone-spatial').checked;mark();}}; $('zone-axis').onchange=()=>{if(currentRoute()){currentRoute().axis=$('zone-axis').value;mark();}}; $('zone-color').oninput=()=>{if(currentRoute()){currentRoute().color=$('zone-color').value.slice(1).match(/../g).map(c=>parseInt(c,16));mark();}}; @@ -73,7 +76,7 @@ function setupExtras(){ $('alarm-delete').onclick=()=>{const t=currentTarget(),a=currentAlarm();if(a&&confirm('Supprimer « '+a.name+' » ?')){t.alarms=t.alarms.filter(x=>x.id!==a.id);mark();drawAlarms();}}; settingsUI();fillExtra();animateBrand(); if((config.settings.tutorial||'ask')==='ask')tutorialPrompt(); - setInterval(()=>{if($('target-diagnostic')&¤tTarget()){const t=currentTarget(),seconds=t.idle_seconds??config.settings.idle_seconds;$('target-diagnostic').textContent='État : '+(state.targets[t.ip]||'À l’arrĂȘt')+' · InactivitĂ© dĂ©tectĂ©e : '+(state.idle||0)+' s · DĂ©lai appliquĂ© : '+(seconds===0?'dĂ©sactivĂ©':seconds+' s');}if($('capture-error'))$('capture-error').textContent=state.capture_error||'';if($('audio-meter'))$('audio-meter').value=state.audio_level||0;if($('activity-info'))$('activity-info').textContent='Sans activitĂ© dĂ©tectĂ©e : '+(state.idle||0)+' s · Session '+(state.locked?'verrouillĂ©e':'active')+' · Bougez la souris : le compteur doit revenir Ă  0.';},1500); + setInterval(()=>{if($('target-diagnostic')&¤tTarget()){const t=currentTarget(),seconds=t.idle_seconds??config.settings.idle_seconds,w=state.wled_workers?.[t.ip];const health=!w?'non testĂ©':w.health_online===false?'HTTP indisponible':w.health_online===true?'en ligne':'en cours';const live=w?.realtime_live===true?'realtime reçu':w?.realtime_live===false?'realtime absent':'realtime inconnu';$('target-diagnostic').textContent='État : '+(state.targets[t.ip]||'À l’arrĂȘt')+' · WLED : '+health+' / '+live+(w?' · trames RGB modifiĂ©es : '+(w.frame_changes||0):'')+' · InactivitĂ© : '+(state.idle||0)+' s · DĂ©lai : '+(seconds===0?'dĂ©sactivĂ©':seconds+' s');}if($('capture-error'))$('capture-error').textContent=state.capture_error||'';if($('audio-meter'))$('audio-meter').value=state.audio_level||0;if($('activity-info'))$('activity-info').textContent='Sans activitĂ© dĂ©tectĂ©e : '+(state.idle||0)+' s · Session '+(state.locked?'verrouillĂ©e':'active')+' · Bougez la souris : le compteur doit revenir Ă  0.';},1500); } async function loadAudio(){const ds=await api('audio-devices');$('audio-device').innerHTML=''+(ds.outputs||[]).map(d=>``).join('')+''+(ds.inputs||[]).map(d=>``).join('')+'';const desired=(config.settings.audio_mode||((config.settings.audio_device??-1)>=0?'input':'output'))==='output'?'out:'+(config.settings.audio_output||'default'):String(config.settings.audio_device??-1);if(![...$('audio-device').options].some(o=>o.value===desired))$('audio-device').add(new Option('Appareil enregistrĂ© absent',desired));$('audio-device').value=desired;if(ds.error)toast(ds.error);} @@ -104,7 +107,7 @@ function modal(html){document.querySelector('#extra-dialog')?.remove();const d=d function tutorialPrompt(){const d=modal('BIENVENUE DANS RAPTOR LINK

Un petit tour ensemble ?

Découvrez les appareils, les associations et les automatismes avec des bulles guidées.

');$('tour-yes').onclick=()=>{d.close();tour(0);};$('tour-later').onclick=()=>d.close();$('tour-never').onclick=handle(async()=>{await api('tutorial',{value:'never'});config.settings.tutorial='never';d.close();});} const steps=[['lights','wizard','Ajoutez votre WLED','L’assistant demande son adresse IP, vĂ©rifie le nombre de LED puis vous aide Ă  choisir une source.'],['lights','target-cards','Vos Ă©clairages','Chaque fiche peut ĂȘtre activĂ©e sĂ©parĂ©ment. Un appareil absent ne bloque pas les autres.'],['lights','editor','Les associations','Choisissez un appareil iCUE puis cliquez une ligne horizontale, verticale ou des LED libres. Chaque zone a sa plage de destination.'],['plan','desk-plan','OĂč prendre les couleurs ?','Avec une source Ă©cran, placez les LED sur les endroits de l’image Ă  suivre. RĂ©glez leur nombre entre les points. Avec iCUE normal ou un effet autonome, ce plan sert Ă  visualiser le ruban.'],['profiles','profile-new','Gardez vos ambiances','Enregistrez vos configurations sous un nom. Vous pourrez les retrouver aussi prĂšs de l’horloge Windows.'],['automation','fade-in','Des transitions douces','RĂ©glez les fondus, l’inactivitĂ© et le lancement Windows. Les plages horaires et les rĂ©veils se rĂšglent dans chaque fiche WLED.'],['settings','tutorial-open','L’aide reste disponible','Vous pouvez toujours relancer ce tutoriel ici.'],['lights','save','Enregistrez, puis dĂ©marrez','Enregistrer applique votre configuration au prochain dĂ©marrage de la synchronisation. La croix ferme la fenĂȘtre ; Quitter arrĂȘte l’application.']]; function tour(i){document.querySelector('.tour-bubble')?.remove();document.querySelector('.tour-focus')?.classList.remove('tour-focus');if(i>=steps.length){api('tutorial',{value:'done'}).catch(()=>{});config.settings.tutorial='done';return;}const [p,id,title,body]=steps[i];showPage(p);const el=$(id);if(el&&el.getClientRects().length){el.classList.add('tour-focus');el.scrollIntoView({block:'center',behavior:'instant'});}const bubble=document.createElement('div');bubble.className='tour-bubble';bubble.setAttribute('role','dialog');bubble.innerHTML=`DÉCOUVERTE ${i+1} / ${steps.length}

${title}

${body}

`;document.body.append(bubble);$('tour-prev').onclick=()=>tour(i-1);$('tour-next').onclick=()=>tour(i+1);$('tour-stop').onclick=()=>{bubble.remove();document.querySelector('.tour-focus')?.classList.remove('tour-focus');};$('tour-next').focus();} -function wizard(){const d=modal(`

Ajout guidĂ© d’un Ă©clairage

Étape 1 — Connectez votre WLED au mĂȘme rĂ©seau que le PC.

${field('wiz-ip','Adresse IP du WLED','text','192.168.1.')}

`);$('wiz-cancel').onclick=()=>d.close();$('wiz-next').onclick=handle(async()=>{try{const ip=$('wiz-ip').value.trim();if(config.targets.some(t=>t.ip===ip))throw Error('Cet appareil existe déjà. Ouvrez sa fiche.');const j=await api('probe',{ip});addTarget({ip,name:j.name,count:j.count});d.close();showPage('lights');const next=modal(`

Étape 2 — Votre source

${esc(j.name)} : ${j.count} LED détectées. Choisissez une source, puis ajustez la sélection sur la fiche.

`);$('wiz-finish').onclick=()=>{const v=$('wiz-source').value,r=currentRoute();if(['rainbow','screen'].includes(v))r.source=v;else{r.source='icue';r.device=v;const device=state.devices.find(d=>d.id===v);r.source=experimentalEnabled()?(device?.provider==='msi'?'msi':device?.provider==='openrgb'?'openrgb':'icue'):'icue';r.rgb_ecosystem=device?.provider==='openrgb'?deviceEcosystem(device):r.source==='msi'?'msi':'openrgb';r.device_model=device?.model||'';r.device_serial=device?.serial||'';r.ids=[];}mark();renderEditor();next.close();toast(['icue','msi','openrgb'].includes(r.source)?'Étape 3 : cliquez les LED Ă  copier, puis Enregistrer et DĂ©marrer.':'VĂ©rifiez l’aperçu, puis Enregistrer et DĂ©marrer.');};}catch(e){$('wiz-error').textContent=e.message;}});} +function wizard(){const d=modal(`

Ajout guidĂ© d’un Ă©clairage

Étape 1 — Connectez votre WLED au mĂȘme rĂ©seau que le PC.

${field('wiz-ip','Adresse IP du WLED','text','192.168.1.')}

`);$('wiz-cancel').onclick=()=>d.close();$('wiz-next').onclick=handle(async()=>{try{const ip=$('wiz-ip').value.trim();if(config.targets.some(t=>t.ip===ip))throw Error('Cet appareil existe déjà. Ouvrez sa fiche.');const j=await api('probe',{ip});addTarget({ip,name:j.name,count:j.count});d.close();showPage('lights');const next=modal(`

Étape 2 — Votre source

${esc(j.name)} : ${j.count} LED détectées. Choisissez une source, puis ajustez la sélection sur la fiche.

`);$('wiz-finish').onclick=()=>{const v=$('wiz-source').value,r=currentRoute();if(['rainbow','screen','wled_preset'].includes(v)){r.source=v;if(v==='wled_preset')r.wled_preset=1;}else{r.source='icue';r.device=v;const device=state.devices.find(d=>d.id===v);r.source=experimentalEnabled()?(device?.provider==='msi'?'msi':device?.provider==='openrgb'?'openrgb':'icue'):'icue';r.rgb_ecosystem=device?.provider==='openrgb'?deviceEcosystem(device):r.source==='msi'?'msi':'openrgb';r.device_model=device?.model||'';r.device_serial=device?.serial||'';r.ids=[];}mark();renderEditor();next.close();toast(['icue','msi','openrgb'].includes(r.source)?'Étape 3 : cliquez les LED Ă  copier, puis Enregistrer et DĂ©marrer.':'VĂ©rifiez l’aperçu, puis Enregistrer et DĂ©marrer.');};}catch(e){$('wiz-error').textContent=e.message;}});} // Preserve the original geometry. Animate only the colored connected pieces in canvas. async function animateBrand(){try{const response=await fetch('/logo.svg');if(!response.ok)throw Error('Logo indisponible');const doc=new DOMParser().parseFromString(await response.text(),'image/svg+xml');for(const id of ['hero-logo','brand-logo']){const old=$(id);if(old){const svg=document.importNode(doc.documentElement,true);svg.id=id;old.replaceWith(svg);}}const update=()=>document.querySelectorAll('.raptor-logo').forEach(svg=>svg.classList.toggle('is-static',config?.settings.logo_animation===false));update();setInterval(update,250);}catch(e){toast(e.message);}} diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/web/index.html b/Raptor-Link-0.3.4-Projet/RaptorLink/web/index.html index 1ca84b2..fc257af 100644 --- a/Raptor-Link-0.3.4-Projet/RaptorLink/web/index.html +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/web/index.html @@ -23,6 +23,6 @@ +
Réglages avancés · laboratoire RGB
Fonctions expĂ©rimentales. À activer uniquement pour tester Mystic Light, OpenRGB ou d’autres marques. Ces connecteurs sont limitĂ©s, compliquĂ©s et pas encore finalisĂ©s.
Diagnostics Core 2
Rapport persistant et copiable. Le journal dĂ©taillĂ© permet de retrouver exactement pourquoi un Ă©clairage s’est arrĂȘtĂ©, s’est rĂ©veillĂ© ou a perdu une source. Le niveau « DĂ©sactivĂ© » coupe l’écriture disque.

Le rapport inclut l’état du moteur, iCUE, l’inactivitĂ©, chaque worker WLED et la chronologie enregistrĂ©e.

CONFIGURATION

Gardez vos associations.

Exportez vos rĂ©glages ou importez une configuration. Les appareils devront ĂȘtre rĂ©associĂ©s sur un autre PC.

Activité

Raptor Link 0.4.2
CONÇU POUR VOTRE ESPACE · PROPULSÉ PAR VOS COULEURSLOCAL / WINDOWS

Votre avis sur Raptor Link ?

Vous l'utilisez depuis environ une heure. Une note rapide aide Ă  savoir si le projet va dans la bonne direction.

Facultatif : vous pourrez ajouter un commentaire ensuite.

Éclairages dĂ©tectĂ©s

diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/web/ui.js b/Raptor-Link-0.3.4-Projet/RaptorLink/web/ui.js index bbed787..680b9a7 100644 --- a/Raptor-Link-0.3.4-Projet/RaptorLink/web/ui.js +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/web/ui.js @@ -50,7 +50,7 @@ function strip(el,colors){if(el.children.length!==colors.length)el.innerHTML=col function renderPreviews(){const r=currentRoute(),t=currentTarget();const src=state.colors[r?.device]||{};$('selection-count').textContent=(r?.ids.length||0)+' LED';$('selection-order').textContent=r?`${r.start} → ${r.end}`:'';strip($('source-preview'),(r?.ids||[]).map(id=>src[id]));if(!t)return;const max=300,n=Math.min(t.count,max),out=[];for(let sample=0;sampleled>=a.start&&led<=a.end);if(!route?.ids.length){out.push(null);continue;}const ids=route.reverse?[...route.ids].reverse():route.ids;const j=led-route.start,k=route.mapping==='repeat'?j%ids.length:Math.min(ids.length-1,Math.floor(j*ids.length/(route.end-route.start+1)));const color=state.colors[route.device]?.[ids[k]];out.push(color?color.map(v=>Math.round(v*t.brightness/100)):null);}strip($('output-preview'),out);$('output-count').textContent=t.count+' LED'+(t.count>max?tr(' · aperçu rĂ©duit',' · reduced preview'):'');$('output-last').textContent=t.count;} function updateColors(){const r=currentRoute(),src=state.colors[r?.device]||{};document.querySelectorAll('#led-map circle').forEach(e=>e.setAttribute('fill',rgb(src[e.dataset.led])));renderPreviews();} function renderSources(){const icons={1:'⌹',2:'◉',32:'âœș',64:'▰',128:'â–„',256:'âœș'},devices=state.devices.filter(d=>experimentalEnabled()||(d.provider||'icue')==='icue');$('source-cards').innerHTML=devices.length?devices.map(d=>`
${icons[d.type]||'▩'}
${esc(providerLabel(d))}

${esc(d.model)}

${d.positions.length} LED · ${[...new Set(d.positions.map(p=>p.group))].length} ${tr('zones','zones')}

${d.positions.slice(0,65).map(()=>'').join('')}
`).join(''):`

${tr('Aucun appareil iCUE dĂ©tectĂ©. VĂ©rifiez qu’iCUE est ouvert et que Raptor Link est autorisĂ© dans les rĂ©glages SDK.','No iCUE device detected. Check that iCUE is open and Raptor Link is allowed in SDK settings.')}

`;updateExperimentalVisibility();} -function settingsUI(){const s=config.settings;$('setting-startup').checked=s.startup;$('setting-auto').checked=s.auto_sync;$('setting-idle').value=s.idle_seconds/60;$('setting-lock').checked=s.lock_off;$('setting-fps').value=s.fps;$('setting-language').value=s.language;if($('setting-updates'))$('setting-updates').checked=s.check_updates!==false;if($('setting-experimental-rgb'))$('setting-experimental-rgb').checked=!!s.experimental_rgb;updateExperimentalVisibility();} +function settingsUI(){const s=config.settings;$('setting-startup').checked=s.startup;$('setting-auto').checked=s.auto_sync;$('setting-idle').value=s.idle_seconds/60;$('setting-lock').checked=s.lock_off;$('setting-fps').value=s.fps;$('setting-language').value=s.language;if($('setting-updates'))$('setting-updates').checked=s.check_updates!==false;if($('setting-experimental-rgb'))$('setting-experimental-rgb').checked=!!s.experimental_rgb;if($('setting-diagnostic-level'))$('setting-diagnostic-level').value=s.diagnostic_level||'normal';if($('setting-diagnostic-days'))$('setting-diagnostic-days').value=String(s.diagnostic_days||7);if($('setting-diagnostic-max'))$('setting-diagnostic-max').value=String(s.diagnostic_max_mb||50);updateExperimentalVisibility();} const RGB_ECOSYSTEMS=[ ['Corsair iCUE','integrated'], @@ -121,7 +121,7 @@ $('source-device').onchange=handle(async()=>{const r=currentRoute();r.device=$(' document.querySelectorAll('[data-mode]').forEach(e=>e.onclick=()=>{mode=e.dataset.mode;document.querySelectorAll('[data-mode]').forEach(b=>b.classList.toggle('active',b===e));renderMap();});$('led-map').onclick=e=>{const c=e.target.closest('[data-led]');if(c)selectLed(+c.dataset.led);};$('select-all').onclick=()=>{const r=currentRoute();if(!r)return;r.ids=positions().sort((a,b)=>mode==='vertical'?(a.y-b.y||a.x-b.x||a.id-b.id):(a.x-b.x||a.y-b.y||a.id-b.id)).map(p=>p.id);mark();renderRoutes();renderMap();};$('select-none').onclick=()=>{if(currentRoute())currentRoute().ids=[];mark();renderRoutes();renderMap();}; $('probe').onclick=handle(async()=>{const b=$('probe');b.disabled=true;try{const t=currentTarget(),j=await api('probe',{ip:t.ip});const old=t.count;t.count=j.count;if(t.routes.length===1&&t.routes[0].end===old)t.routes[0].end=j.count;mark();renderCards();renderEditor();toast(`${j.name} · ${j.count} LED · WLED ${j.version}`);}finally{b.disabled=false;}}); $('discover').onclick=handle(async()=>{const b=$('discover');b.disabled=true;try{const list=await api('discover',{});$('discovery-results').innerHTML=list.length?list.map((d,i)=>`
${esc(d.name)}

${esc(d.ip)} · ${d.count} LED

`).join(''):`

${tr('Aucun appareil trouvé par mDNS. Vous pouvez ajouter son adresse IP manuellement.','No device found via mDNS. You can add its IP address manually.')}

`;$('discovery-results').onclick=e=>{const b=e.target.closest('[data-found]');if(b){const d=list[+b.dataset.found];if(config.targets.some(t=>t.ip===d.ip))return toast(tr('Cet appareil est déjà ajouté.','This device is already added.'));addTarget(d);$('discovery-dialog').close();}};$('discovery-dialog').showModal();}finally{b.disabled=false;}});$('close-discovery').onclick=()=>$('discovery-dialog').close();$('refresh').onclick=handle(async()=>{await api('refresh',{});toast(tr('Recherche iCUE demandée.','iCUE refresh requested.'));}); -for(const[id,key]of [['setting-startup','startup'],['setting-auto','auto_sync'],['setting-lock','lock_off'],['setting-updates','check_updates']])$(id).onchange=()=>{config.settings[key]=$(id).checked;mark();};if($('setting-experimental-rgb'))$('setting-experimental-rgb').onchange=()=>{config.settings.experimental_rgb=$('setting-experimental-rgb').checked;mark();updateExperimentalVisibility();renderSources();renderEditor();renderEcosystems();};$('setting-idle').oninput=()=>{config.settings.idle_seconds=Math.round(Number($('setting-idle').value)*60);mark();};$('setting-fps').onchange=()=>{config.settings.fps=Number($('setting-fps').value);mark();};$('setting-language').onchange=()=>{lang=$('setting-language').value;config.settings.language=lang;mark();applyLanguage();renderCards();renderEditor();renderSources();};$('awake').onchange=handle(async()=>{await api('awake',{enabled:$('awake').checked});}); +for(const[id,key]of [['setting-startup','startup'],['setting-auto','auto_sync'],['setting-lock','lock_off'],['setting-updates','check_updates']])$(id).onchange=()=>{config.settings[key]=$(id).checked;mark();};if($('setting-experimental-rgb'))$('setting-experimental-rgb').onchange=()=>{config.settings.experimental_rgb=$('setting-experimental-rgb').checked;mark();updateExperimentalVisibility();renderSources();renderEditor();renderEcosystems();};$('setting-idle').oninput=()=>{config.settings.idle_seconds=Math.round(Number($('setting-idle').value)*60);mark();};$('setting-fps').onchange=()=>{config.settings.fps=Number($('setting-fps').value);mark();};$('setting-language').onchange=()=>{lang=$('setting-language').value;config.settings.language=lang;mark();applyLanguage();renderCards();renderEditor();renderSources();};if($('setting-diagnostic-level'))$('setting-diagnostic-level').onchange=()=>{config.settings.diagnostic_level=$('setting-diagnostic-level').value;mark();};if($('setting-diagnostic-days'))$('setting-diagnostic-days').onchange=()=>{config.settings.diagnostic_days=Number($('setting-diagnostic-days').value);mark();};if($('setting-diagnostic-max'))$('setting-diagnostic-max').onchange=()=>{config.settings.diagnostic_max_mb=Number($('setting-diagnostic-max').value);mark();};if($('diagnostic-copy'))$('diagnostic-copy').onclick=handle(async()=>{const minutes=Number($('diagnostic-range').value),reply=await api('diagnostic-report',{minutes}),text=reply.text||'';try{await navigator.clipboard.writeText(text);}catch(e){const area=document.createElement('textarea');area.value=text;document.body.append(area);area.select();document.execCommand('copy');area.remove();}$('diagnostic-copy-status').textContent='Rapport copié · '+text.split('\n').length+' lignes. Collez-le directement dans ChatGPT ou une Issue GitHub.';toast('Rapport diagnostic copié.');});$('awake').onchange=handle(async()=>{await api('awake',{enabled:$('awake').checked});}); $('export').onclick=()=>{const blob=new Blob([JSON.stringify(config,null,2)],{type:'application/json'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='Raptor-Link-configuration.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};$('import').onclick=()=>$('import-file').click();$('import-file').onchange=handle(async()=>{const f=$('import-file').files[0];if(!f)return;let j=JSON.parse(await f.text());if(!Array.isArray(j.targets)||!j.settings)throw Error(tr('Fichier de configuration invalide.','Invalid configuration file.'));if(!confirm(tr('Remplacer la configuration affichée ? Le démarrage automatique importé sera désactivé.','Replace the current setup? Imported startup options will be disabled.')))return;j.settings.startup=false;j.settings.auto_sync=false;j=await api('validate',j);config=j;lang=j.settings.language||'fr';targetIndex=routeIndex=0;mark();applyLanguage();renderCards();renderEditor();settingsUI();toast(tr('Importé. Vérifiez les appareils et enregistrez.','Imported. Check the devices and save.'));}); window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue='';}}); } diff --git a/Raptor-Link-0.3.4-Projet/RaptorLink/window.py b/Raptor-Link-0.3.4-Projet/RaptorLink/window.py index 22910da..694bc31 100644 --- a/Raptor-Link-0.3.4-Projet/RaptorLink/window.py +++ b/Raptor-Link-0.3.4-Projet/RaptorLink/window.py @@ -1,40 +1,74 @@ -"""Bring the existing Windows dashboard forward instead of opening duplicates.""" +"""Manage the single Raptor Link dashboard window on Windows.""" import ctypes as C from ctypes import wintypes as W import threading import time -def focus_window(title): +WM_CLOSE=0x0010 + + +def _matching_windows(title): + """Return visible top-level windows belonging to this Raptor Link instance. + + Chromium may append the browser name using different separators. The + instance title contains the local server port, so a substring match is both + robust and specific enough to avoid touching unrelated browser windows. + """ user=C.WinDLL('user32',use_last_error=True) callback=C.WINFUNCTYPE(W.BOOL,W.HWND,W.LPARAM) user.EnumWindows.argtypes=[callback,W.LPARAM] user.GetWindowTextLengthW.argtypes=[W.HWND];user.GetWindowTextLengthW.restype=C.c_int user.GetWindowTextW.argtypes=[W.HWND,W.LPWSTR,C.c_int] user.IsWindowVisible.argtypes=[W.HWND];user.IsWindowVisible.restype=W.BOOL - user.IsIconic.argtypes=[W.HWND];user.IsIconic.restype=W.BOOL - user.ShowWindow.argtypes=[W.HWND,C.c_int] - user.SetForegroundWindow.argtypes=[W.HWND];user.SetForegroundWindow.restype=W.BOOL found=[] @callback def visit(hwnd,_): length=user.GetWindowTextLengthW(hwnd) if length and user.IsWindowVisible(hwnd): text=C.create_unicode_buffer(length+1);user.GetWindowTextW(hwnd,text,length+1) - if text.value==title or text.value.startswith(title+' - '): - found.append(hwnd);return False + if title and title in text.value: + found.append(hwnd) return True user.EnumWindows(visit,0) + return user,found + + +def focus_window(title): + user,found=_matching_windows(title) if not found:return False + user.IsIconic.argtypes=[W.HWND];user.IsIconic.restype=W.BOOL + user.ShowWindow.argtypes=[W.HWND,C.c_int] + user.SetForegroundWindow.argtypes=[W.HWND];user.SetForegroundWindow.restype=W.BOOL + user.PostMessageW.argtypes=[W.HWND,W.UINT,W.WPARAM,W.LPARAM];user.PostMessageW.restype=W.BOOL hwnd=found[0] if user.IsIconic(hwnd):user.ShowWindow(hwnd,9) user.SetForegroundWindow(hwnd) + # Old releases could leave several dashboard windows open. As soon as the + # user reopens Raptor Link, keep one and close only the duplicate dashboards. + for duplicate in found[1:]: + try:user.PostMessageW(duplicate,WM_CLOSE,0,0) + except Exception:pass return True +def close_windows(title): + """Close every dashboard window for this instance, not the browser itself.""" + user,found=_matching_windows(title) + if not found:return False + user.PostMessageW.argtypes=[W.HWND,W.UINT,W.WPARAM,W.LPARAM];user.PostMessageW.restype=W.BOOL + closed=False + for hwnd in found: + try:closed=bool(user.PostMessageW(hwnd,WM_CLOSE,0,0)) or closed + except Exception:pass + return closed + + class WindowController: - def __init__(self,focus,launch,clock=time.monotonic): - self.focus=focus;self.launch=launch;self.clock=clock + def __init__(self,focus,launch,clock=time.monotonic,close=None): + # clock remains the third positional argument for compatibility with + # the existing window lifecycle tests and older callers. + self.focus=focus;self.launch=launch;self.close_window=close;self.clock=clock self.pending_until=0;self.lock=threading.Lock() def ready(self): with self.lock:self.pending_until=0 @@ -44,5 +78,11 @@ def open(self): self.pending_until=0;return if self.clock()>8,start&255])+bytes(v for c in pixels[start:start+480] for v in c)) + return out + +class WledWorker: + RELEASE_SETTLE_SECONDS=0.18 + HTTP_TIMEOUT_SECONDS=1.2 + HTTP_RETRY_BASE_SECONDS=15.0 + HTTP_RETRY_MAX_SECONDS=60.0 + HEALTH_INTERVAL_SECONDS=15.0 + HEALTH_OFFLINE_SECONDS=5.0 + HEALTH_REBOOT_SECONDS=2.0 + HEALTH_TIMEOUT_SECONDS=0.7 + RESYNC_MIN_INTERVAL_SECONDS=12.0 + + def __init__(self,target,logger,diagnostics=None): + self.lock=threading.RLock() + self.done=threading.Event() + self.log=logger + self.diag=diagnostics + self.target=copy.deepcopy(target) + self.desired={"mode":"hold","reason":"démarrage","frame":None,"preset":None,"fps":25,"transition":0,"restore":None} + self.desired_rev=0 + self.applied_rev=-1 + self.state="HOLD" + self.detail="En attente" + self.last_udp=0.0 + self.last_http_ok=0.0 + self.last_http_error="" + self.last_udp_error="" + self.packets_sent=0 + self.transitions=0 + self.retries=0 + self.commanded_off=False + self.next_http_try=0.0 + self.pending_confirmation=False + self.fallback_batches=0 + self.released_rev=-1 + self.release_packets=0 + self.udp_commands=0 + self.control_path="" + self.health_online=None + self.health_error="" + self.health_failures=0 + self.last_health_ok=0.0 + self.health_uptime=None + self.health_live=None + self.health_lm=None + self.health_lip="" + self.reboots_detected=0 + self.recoveries=0 + self.resync_requested=False + self.last_resync=0.0 + self.reboot_requested=False + self.reboot_pending=False + self.reboot_requested_at=0.0 + self.reboot_reason="" + self.last_frame_signature=None + self.frame_changes=0 + self.last_frame_change=0.0 + self.health_wake=threading.Event() + self.udp=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) + self.udp.settimeout(.2) + self.http=urllib.request.build_opener(urllib.request.ProxyHandler({})) + self.health_http=urllib.request.build_opener(urllib.request.ProxyHandler({})) + self.thread=threading.Thread(target=self._loop,daemon=True,name="RaptorLink-WLED-"+self.target["ip"]) + self.health_thread=threading.Thread(target=self._health_loop,daemon=True,name="RaptorLink-WLED-health-"+self.target["ip"]) + self.thread.start();self.health_thread.start() + + def update_target(self,target): + with self.lock:self.target=copy.deepcopy(target) + + def _set(self,mode,reason="",**kwargs): + with self.lock: + changed=mode!=self.desired.get("mode") + payload=dict(self.desired) + payload.update(mode=mode,reason=str(reason)[:200],**kwargs) + # Frame refreshes should not cause a state transition/revision. + if mode=="stream" and self.desired.get("mode")=="stream": + self.desired=payload + return + if payload!=self.desired: + self.desired=payload + self.desired_rev+=1 + self.pending_confirmation=False + if changed:self.transitions+=1 + if changed:self._event("detailed","WLED-STATE",f"{self.target['name']} -> {mode}",reason=reason,ip=self.target["ip"]) + + def stream(self,frame,fps=25,reason="Synchronisé"): + self._set("stream",reason,frame=[tuple(c) for c in frame],fps=max(1,min(40,int(fps))),preset=None,restore=None) + + def preset(self,preset,reason="Preset WLED",transition=0): + self._set("preset",reason,preset=max(1,min(250,int(preset))),transition=max(0,min(65,float(transition))),frame=None,restore=None) + + def off(self,reason="Inactivité",transition=0): + self._set("off",reason,transition=max(0,min(65,float(transition))),frame=None,preset=None,restore=None) + + def hold(self,reason="En attente"): + self._set("hold",reason,frame=None,preset=None,restore=None) + + def restore(self,state,reason="Restauration"): + self._set("restore",reason,restore=copy.deepcopy(state or {"on":False}),frame=None,preset=None) + + def snapshot(self): + with self.lock: + return { + "state":self.state, + "detail":self.detail, + "desired":self.desired.get("mode"), + "reason":self.desired.get("reason",""), + "packets_sent":self.packets_sent, + "last_udp":self.last_udp, + "last_http_ok":self.last_http_ok, + "last_http_error":self.last_http_error, + "last_udp_error":self.last_udp_error, + "transitions":self.transitions, + "retries":self.retries, + "commanded_off":self.commanded_off, + "control_path":self.control_path, + "http_retry_in":round(max(0.0,self.next_http_try-time.monotonic()),2), + "pending_confirmation":self.pending_confirmation, + "fallback_batches":self.fallback_batches, + "release_packets":self.release_packets, + "udp_commands":self.udp_commands, + "health_online":self.health_online, + "health_error":self.health_error, + "health_failures":self.health_failures, + "health_seen_ago":None if not self.last_health_ok else round(max(0.0,time.time()-self.last_health_ok),1), + "wled_uptime":self.health_uptime, + "realtime_live":self.health_live, + "realtime_mode":self.health_lm, + "realtime_source":self.health_lip, + "reboots_detected":self.reboots_detected, + "recoveries":self.recoveries, + "reboot_pending":self.reboot_pending, + "resync_requested":self.resync_requested, + "frame_changes":self.frame_changes, + "frame_change_age":None if not self.last_frame_change else round(max(0.0,time.monotonic()-self.last_frame_change),2), + "frame_sample":list(self.last_frame_signature[1]) if self.last_frame_signature else [], + } + + def _event(self,level,category,message,**fields): + if self.diag is not None: + try:self.diag.event(level,category,message,**fields) + except Exception:pass + + def reboot(self,reason="Redémarrage manuel"): + """Queue a WLED reboot without blocking the UI or another controller.""" + with self.lock: + if self.reboot_pending or self.reboot_requested:return False + self.reboot_requested=True + self.reboot_pending=True + self.reboot_requested_at=time.monotonic() + self.reboot_reason=str(reason)[:200] + self.health_wake.set() + self._event("normal","WLED-STATE",f"{self.target['name']} redémarrage demandé",ip=self.target["ip"]) + return True + + def _health_probe(self): + """Probe WLED out-of-band so realtime UDP can never be blocked by HTTP.""" + target=copy.deepcopy(self.target) + req=urllib.request.Request("http://"+target["ip"]+"/json/info") + try: + with self.health_http.open(req,timeout=self.HEALTH_TIMEOUT_SECONDS) as r: + info=json.load(r) + if not isinstance(info,dict):info={} + now=time.monotonic() + uptime=info.get("uptime") + try:uptime=int(uptime) if uptime is not None else None + except Exception:uptime=None + live=info.get("live") + live=bool(live) if live is not None else None + lm=info.get("lm") + lip=str(info.get("lip") or "") + with self.lock: + previous_online=self.health_online + previous_uptime=self.health_uptime + was_pending=self.reboot_pending + self.health_online=True + self.health_error="" + self.health_failures=0 + self.last_health_ok=time.time() + self.health_uptime=uptime + self.health_live=live + self.health_lm=lm + self.health_lip=lip + desired_mode=self.desired.get("mode") + rebooted=previous_uptime is not None and uptime is not None and uptime+2=1.0 and (rebooted or recovered or (uptime is not None and uptime<60)) + need_live_repair=(desired_mode=="stream" and live is False and self.last_udp and now-self.last_udp<5 and now-self.last_resync>=self.RESYNC_MIN_INTERVAL_SECONDS) + if rebooted or manual_ready or need_live_repair: + self.resync_requested=desired_mode=="stream" + self.last_resync=now + if manual_ready: + self.reboot_pending=False + self.recoveries+=1 + if rebooted: + self._event("normal","WLED-STATE",f"{target['name']} redémarrage détecté",ip=target["ip"],uptime=uptime) + elif previous_online is False: + self._event("normal","WLED-STATE",f"{target['name']} revenu sur le réseau",ip=target["ip"],uptime=uptime) + if need_live_repair: + self._event("normal","WLED-STATE",f"{target['name']} mode realtime absent malgré le flux ; resynchronisation",ip=target["ip"],live=live,lm=lm,lip=lip) + return True + except Exception as exc: + msg=str(exc) + with self.lock: + previous_online=self.health_online + self.health_failures+=1 + self.health_error=msg + # One timeout is tolerated because some ESPs have a fragile web + # server while UDP realtime remains perfectly healthy. + if self.health_failures>=2 or self.reboot_pending:self.health_online=False + if previous_online is not False and (self.health_failures>=2 or self.reboot_pending): + self._event("normal","WLED-STATE",f"{target['name']} contrÎle HTTP indisponible ; flux UDP maintenu",ip=target["ip"],error=msg) + return False + + def _health_loop(self): + # Do not add load during application startup; then use a very light + # independent probe. Reboot recovery gets a short temporary cadence. + if self.health_wake.wait(2.0): + self.health_wake.clear() + while not self.done.is_set(): + self._health_probe() + with self.lock: + pending=self.reboot_pending + online=self.health_online + mode=self.desired.get("mode") + interval=self.HEALTH_REBOOT_SECONDS if pending else self.HEALTH_OFFLINE_SECONDS if online is False else 30.0 if mode=="hold" else self.HEALTH_INTERVAL_SECONDS + self.health_wake.wait(interval);self.health_wake.clear() + + def _perform_reboot(self,reason): + target=copy.deepcopy(self.target) + self.state="REBOOTING";self.detail=reason or "Redémarrage WLED" + self._release_realtime() + accepted=False + try: + self._http({"rb":True},timeout=.8) + accepted=True;self.control_path="http-reboot" + except Exception: + # A reboot can cut the HTTP response before it reaches the PC. Send + # the same command over WLED's JSON UDP notifier as a best effort. + accepted=self._udp_state({"rb":True}) + self.control_path="udp-reboot" if accepted else self.control_path + with self.lock: + self.health_online=False + self.health_failures=max(2,self.health_failures) + self.health_error="Redémarrage en cours" + self.reboot_requested_at=time.monotonic() + self.health_wake.set() + self._event("normal","WLED-STATE",f"{target['name']} redémarrage envoyé",ip=target["ip"],accepted=accepted,path=self.control_path) + + def _resync_stream(self): + target=copy.deepcopy(self.target) + self.state="RECOVERING";self.detail="Réinitialisation du mode temps réel" + self._release_realtime() + # Raptor Link scales its own RGB values, so WLED must not remain at + # brightness 0 after a reboot/power cut. + self._udp_state({"live":False,"on":True,"bri":255,"tt":0}) + with self.lock: + self.resync_requested=False + self.commanded_off=False + self.pending_confirmation=False + self.recoveries+=1 + self.last_resync=time.monotonic() + self._event("normal","WLED-STATE",f"{target['name']} resynchronisé aprÚs redémarrage/perte realtime",ip=target["ip"]) + + def _http_success(self): + with self.lock: + self.last_http_ok=time.time() + self.last_http_error="" + self.retries=0 + self.next_http_try=0.0 + + def _http_failure(self,exc): + msg=str(exc) + with self.lock: + self.last_http_error=msg + self.retries+=1 + delay=min(self.HTTP_RETRY_MAX_SECONDS,self.HTTP_RETRY_BASE_SECONDS*(2**min(8,self.retries-1))) + self.next_http_try=time.monotonic()+delay + return msg,delay + + def _http(self,payload,timeout=None): + target=copy.deepcopy(self.target) + timeout=self.HTTP_TIMEOUT_SECONDS if timeout is None else max(.2,float(timeout)) + req=urllib.request.Request( + "http://"+target["ip"]+"/json/state", + data=json.dumps(payload,separators=(",",":")).encode(), + headers={"Content-Type":"application/json"}, + ) + try: + with self.http.open(req,timeout=timeout) as r: + data=json.load(r) + self._http_success() + self._event("detailed","WLED-HTTP",f"{target['name']} commande OK",ip=target["ip"],payload=payload) + return data + except Exception as exc: + msg,delay=self._http_failure(exc) + self._event("normal","WLED-HTTP",f"{target['name']} erreur HTTP",ip=target["ip"],error=msg,payload=payload,retry_in=round(delay,1)) + raise + + def _http_state(self,timeout=.8): + """Lightweight recovery probe used only after the HTTP circuit cooldown.""" + target=copy.deepcopy(self.target) + req=urllib.request.Request("http://"+target["ip"]+"/json/state") + try: + with self.http.open(req,timeout=max(.2,float(timeout))) as r: + data=json.load(r) + self._http_success() + return data if isinstance(data,dict) else {} + except Exception as exc: + msg,delay=self._http_failure(exc) + self._event("normal","WLED-HTTP",f"{target['name']} toujours indisponible",ip=target["ip"],error=msg,retry_in=round(delay,1)) + raise + + def _matches_desired(self,mode,payload,state): + if not isinstance(state,dict):return False + if mode=="off": + return state.get("on") is False + if mode=="preset": + try:return bool(state.get("on")) and int(state.get("ps",-1))==int(payload.get("ps",-2)) + except Exception:return False + if mode=="restore": + if "on" in payload and bool(state.get("on"))!=bool(payload.get("on")):return False + if "bri" in payload: + try: + if int(state.get("bri",-1))!=int(payload.get("bri")):return False + except Exception:return False + # Segment/transition restoration is richer than a cheap equality test. + return "seg" not in payload + return False + + def _apply_control(self,payload): + """Apply one state change without ever hammering a sick WLED web server.""" + if time.monotonic()>=self.next_http_try: + try: + self._http(payload) + self.control_path="http" + return "http" + except Exception: + # Keep the circuit open even if a future/custom HTTP transport + # raises before _http_failure() can record the failure. + with self.lock: + if self.next_http_try<=time.monotonic(): + self.next_http_try=time.monotonic()+self.HTTP_RETRY_BASE_SECONDS + pass + if self._udp_state(payload): + self.control_path="udp-json-fallback" + return "udp" + return "" + + def _command_payload(self,d): + transition=max(0,min(650,int(round(float(d.get("transition",0))*10)))) + mode=d["mode"] + if mode=="off": + return {"live":False,"on":False,"tt":transition} + if mode=="preset": + return {"live":False,"on":True,"ps":int(d["preset"]),"tt":transition} + if mode=="restore": + payload=copy.deepcopy(d.get("restore") or {"on":False}) + payload["live"]=False + return payload + return {"live":False} + + def _send_frame(self,frame): + target=copy.deepcopy(self.target) + # Keep a tiny RGB fingerprint in diagnostics. It tells us whether the + # source itself is moving even when the physical strip is not. + step=max(1,len(frame)//4) + sample=tuple(tuple(x) for x in frame[::step][:5]) + signature=(len(frame),sample) + if signature!=self.last_frame_signature: + self.last_frame_signature=signature + self.frame_changes+=1 + self.last_frame_change=time.monotonic() + try: + for packet in _packets(frame,2): + self.udp.sendto(packet,(target["ip"],int(target.get("port",21324)))) + self.packets_sent+=1 + self.last_udp=time.monotonic();self.last_udp_error="" + return True + except OSError as exc: + self.last_udp_error=str(exc) + self._event("normal","WLED-UDP",f"{target['name']} erreur UDP",ip=target["ip"],error=str(exc)) + return False + + def _release_realtime(self): + """Force WLED out of UDP realtime mode, even if this process did not start it.""" + target=copy.deepcopy(self.target) + ok=True + for _ in range(3): + try: + self.udp.sendto(bytes([2,0]),(target["ip"],int(target.get("port",21324)))) + self.release_packets+=1 + except OSError as exc: + ok=False;self.last_udp_error=str(exc) + time.sleep(.025) + self._event("detailed","WLED-UDP",f"{target['name']} sortie realtime demandée",ip=target["ip"],packets=3,ok=ok) + return ok + + def _udp_state(self,payload): + """Fallback to WLED's JSON API over the notifier UDP port when HTTP is unavailable.""" + target=copy.deepcopy(self.target) + data=json.dumps(payload,separators=(",",":"),ensure_ascii=False).encode("utf-8") + ok=True + self.fallback_batches+=1 + for _ in range(3): + try: + self.udp.sendto(data,(target["ip"],int(target.get("port",21324)))) + self.udp_commands+=1 + except OSError as exc: + ok=False;self.last_udp_error=str(exc) + time.sleep(.03) + if ok: + self.control_path="udp-json-fallback" + self._event("normal","WLED-UDP",f"{target['name']} commande JSON envoyée par UDP (secours)",ip=target["ip"],payload=payload) + return ok + + def _loop(self): + next_udp=0.0 + next_trace=0.0 + previous_mode="hold" + while not self.done.is_set(): + with self.lock: + d=copy.deepcopy(self.desired);rev=self.desired_rev + now=time.monotonic() + mode=d["mode"] + with self.lock: + reboot_now=self.reboot_requested + if reboot_now:self.reboot_requested=False + resync_now=self.resync_requested + if reboot_now: + self._perform_reboot(self.reboot_reason) + previous_mode=mode + self.done.wait(.15) + continue + if mode=="stream" and resync_now: + self._resync_stream() + previous_mode="hold" + self.done.wait(.12) + continue + + if mode=="hold": + if previous_mode!="hold": + self.state="HOLD";self.detail=d.get("reason","En attente") + previous_mode="hold" + self.done.wait(.05) + continue + + if mode=="stream": + frame=d.get("frame") + # Entering realtime always prepares WLED once, even when the ESP + # rebooted outside Raptor Link. This fixes the case where WLED + # comes back with on=false or brightness=0 and UDP frames merely + # produce a faint flicker. + if self.commanded_off or previous_mode!="stream": + self.state="WAKING";self.detail="Préparation du mode temps réel" + self._release_realtime() + self._udp_state({"live":False,"on":True,"bri":255,"tt":0}) + self.pending_confirmation=False + self.commanded_off=False + self.applied_rev=rev + if frame: + interval=1/max(1,int(d.get("fps",25))) + if now>=next_udp: + if self._send_frame(frame): + if self.state!="STREAMING": + self._event("detailed","WLED-STATE",f"{self.target['name']} streaming actif",ip=self.target["ip"]) + with self.lock:reboot_pending=self.reboot_pending + self.state="REBOOTING" if reboot_pending else "STREAMING" + self.detail="Redémarrage WLED en cours" if reboot_pending else d.get("reason","Synchronisé") + if now>=next_trace: + self._event("trace","WLED-UDP",f"{self.target['name']} flux vivant",ip=self.target["ip"],packets=self.packets_sent,fps=d.get("fps",25),frame_leds=len(frame)) + next_trace=now+1 + next_udp=now+interval + self.applied_rev=rev + else: + self.state="WAIT_SOURCE";self.detail="Aucune trame disponible" + previous_mode="stream" + self.done.wait(.005) + continue + + # Autonomous preset / OFF / restore: force-release realtime first. + # This is done even if *this* process did not start realtime mode, which + # also recovers a WLED left in live mode by an older Raptor Link session. + if rev!=self.applied_rev and self.released_rev!=rev: + self.state="RELEASING";self.detail="Sortie forcée du mode temps réel" + self._release_realtime() + self.released_rev=rev + previous_mode=mode + self.done.wait(self.RELEASE_SETTLE_SECONDS) + continue + + if rev!=self.applied_rev: + payload=self._command_payload(d) + self.state="APPLYING";self.detail=d.get("reason","Commande WLED") + path=self._apply_control(payload) + if not path: + self.state="CONTROL_ERROR";self.detail=self.last_http_error or "Commande WLED impossible" + self.done.wait(1) + previous_mode=mode + continue + used_fallback=path!="http" + self.pending_confirmation=used_fallback + self.applied_rev=rev + if mode=="off": + self.commanded_off=True;self.state="OFF_UDP" if used_fallback else "OFF" + elif mode=="preset": + self.commanded_off=False;self.state="AUTONOMOUS_UDP" if used_fallback else "AUTONOMOUS" + else: + self.commanded_off=not bool(payload.get("on",True));self.state="RESTORED_UDP" if used_fallback else "RESTORED" + self.detail=d.get("reason","") + + # UDP fallback is fire-and-forget. If the controller was actually offline, + # resend the desired state only after an exponential cooldown and confirm + # it through HTTP when the web server becomes healthy again. + if rev==self.applied_rev and self.pending_confirmation and mode in ("off","preset","restore") and now>=self.next_http_try: + payload=self._command_payload(d) + try: + self.state="VERIFYING";self.detail="Vérification de la récupération WLED" + remote=self._http_state(.8) + if not self._matches_desired(mode,payload,remote): + self._http(payload) + self.pending_confirmation=False + self.control_path="http-recovered" + if mode=="off":self.state="OFF" + elif mode=="preset":self.state="AUTONOMOUS" + else:self.state="RESTORED" + self.detail=d.get("reason","") + self._event("normal","WLED-HTTP",f"{self.target['name']} communication HTTP rétablie",ip=self.target["ip"]) + except Exception: + # One UDP refresh per cooldown keeps the desired state convergent + # without recreating the old 2-second HTTP retry storm. + self._udp_state(payload) + self.control_path="udp-json-fallback" + if mode=="off":self.state="OFF_UDP" + elif mode=="preset":self.state="AUTONOMOUS_UDP" + else:self.state="RESTORED_UDP" + self.detail=d.get("reason","")+" · secours UDP" + previous_mode=mode + self.done.wait(.05) + + try:self.udp.close() + except Exception:pass + + def close(self): + self.done.set();self.health_wake.set() + self.thread.join(timeout=3);self.health_thread.join(timeout=2) diff --git a/Raptor-Link-0.3.4-Projet/raptor-build/README-BUILD.md b/Raptor-Link-0.3.4-Projet/raptor-build/README-BUILD.md index 31debd7..072504d 100644 --- a/Raptor-Link-0.3.4-Projet/raptor-build/README-BUILD.md +++ b/Raptor-Link-0.3.4-Projet/raptor-build/README-BUILD.md @@ -42,3 +42,8 @@ Remove-Item ".\raptor-build\payload" -Recurse -Force ``` User configuration is stored outside the installation directory in `%LOCALAPPDATA%\AuroraWLED`. + + +## 0.3.14 + +Patch de stabilité au démarrage Windows : sondes WLED en lecture seule, UDP non bloqué par l'API HTTP et conservation de la derniÚre trame pendant le démarrage d'iCUE. diff --git a/Raptor-Link-0.3.4-Projet/raptor-build/installer.nsi b/Raptor-Link-0.3.4-Projet/raptor-build/installer.nsi index 7805451..ac2f5f6 100644 --- a/Raptor-Link-0.3.4-Projet/raptor-build/installer.nsi +++ b/Raptor-Link-0.3.4-Projet/raptor-build/installer.nsi @@ -6,7 +6,7 @@ Name "Raptor Link" !define APPDIR "../RaptorLink" !endif !ifndef OUTPUT -!define OUTPUT "../Raptor-Link-Setup-0.3.13.exe" +!define OUTPUT "../Raptor-Link-Setup-0.4.2.exe" !endif OutFile "${OUTPUT}" InstallDir "$LOCALAPPDATA\Programs\RaptorLink" @@ -15,10 +15,10 @@ RequestExecutionLevel user SetCompressor /SOLID lzma Icon "${APPDIR}\\icon.ico" UninstallIcon "${APPDIR}\\icon.ico" -VIProductVersion "0.3.13.0" +VIProductVersion "0.4.2.0" VIAddVersionKey "ProductName" "Raptor Link" VIAddVersionKey "FileDescription" "Raptor Link - installation Windows" -VIAddVersionKey "FileVersion" "0.3.13" +VIAddVersionKey "FileVersion" "0.4.2" VIAddVersionKey "LegalCopyright" "Application independante - 2026" !define MUI_ABORTWARNING !define MUI_WELCOMEPAGE_TITLE "Bienvenue dans Raptor Link" @@ -61,7 +61,7 @@ Section "Raptor Link" WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "DisplayName" "Raptor Link" WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "UninstallString" '"$INSTDIR\Desinstaller.exe"' WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "DisplayIcon" "$INSTDIR\icon.ico" - WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "DisplayVersion" "0.3.13 beta" + WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "DisplayVersion" "0.4.2 beta" WriteRegDWORD HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "NoModify" 1 WriteRegDWORD HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AuroraWLED" "NoRepair" 1 SectionEnd diff --git a/Raptor-Link-0.3.4-Projet/raptor-build/test_connection.py b/Raptor-Link-0.3.4-Projet/raptor-build/test_connection.py index 10ccdb2..4f95571 100644 --- a/Raptor-Link-0.3.4-Projet/raptor-build/test_connection.py +++ b/Raptor-Link-0.3.4-Projet/raptor-build/test_connection.py @@ -2,8 +2,9 @@ from pathlib import Path from unittest.mock import patch sys.path.insert(0,str(Path('RaptorLink').resolve())) -from engine import probe_target +from engine import probe_target,packets from features import Fade,gate,extras + class Connection(unittest.TestCase): def test_regular_checks_never_switch_off(self): t={'ip':'192.168.1.175','count':257};calls=[] @@ -13,8 +14,14 @@ def fake(ip,path,payload=None): with patch('engine.http',fake): self.assertEqual(probe_target(t,True)['bri'],128) for _ in range(20):self.assertIsNone(probe_target(t,False)) - self.assertEqual(sum(p is not None for _,p in calls),1) - self.assertTrue(all(p is None for _,p in calls[3:])) + self.assertTrue(all(payload is None for _,payload in calls)) + self.assertEqual([path for path,_ in calls[:2]],['/json/info','/json/state']) + + def test_realtime_packet_keeps_wled_alive_for_short_gaps(self): + packet=packets([(1,2,3)])[0] + self.assertEqual(packet[0],2) + self.assertEqual(packet[1],5) + def test_fade_recovers_after_idle(self): f=Fade() for _ in range(100):f.step(True,.04,3,2) @@ -23,4 +30,5 @@ def test_fade_recovers_after_idle(self): self.assertEqual(f.value,0) for _ in range(100):f.step(True,.04,3,2) self.assertEqual(f.value,1) + if __name__=='__main__':unittest.main() diff --git a/Raptor-Link-0.3.4-Projet/raptor-build/test_core2.py b/Raptor-Link-0.3.4-Projet/raptor-build/test_core2.py new file mode 100644 index 0000000..693198e --- /dev/null +++ b/Raptor-Link-0.3.4-Projet/raptor-build/test_core2.py @@ -0,0 +1,219 @@ +import sys +import tempfile +import time +import unittest +from pathlib import Path +from unittest.mock import patch + +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str((ROOT/'RaptorLink').resolve())) + +from diagnostics import Diagnostics +from engine import validate +from features import effect +from wled_worker import WledWorker +from window import WindowController + +def target(): + return {'name':'Logo','ip':'192.168.1.80','count':12,'port':21324} + +def wait_for(predicate, timeout=1.0): + end=time.monotonic()+timeout + while time.monotonic()1)) + self.assertGreater(len(sent),1) + self.assertEqual(calls,[]) + finally:w.close() + + def test_worker_releases_stream_before_preset_and_off(self): + calls=[];sent=[] + with patch.object(WledWorker,'_http',lambda self,payload,timeout=2:calls.append(payload.copy()) or {'success':True}), \ + patch.object(WledWorker,'_send_frame',lambda self,frame:sent.append(frame) or setattr(self,'last_udp',time.monotonic()) or True): + w=WledWorker(target(),lambda *a,**k:None,None) + try: + w.RELEASE_SETTLE_SECONDS=.03 + w.stream([(10,20,30)]*12,25,'stream') + self.assertTrue(wait_for(lambda:len(sent)>0)) + w.preset(12,'autonome',1) + self.assertTrue(wait_for(lambda:any(p.get('ps')==12 and p.get('live') is False for p in calls))) + w.off('idle',2) + self.assertTrue(wait_for(lambda:any(p.get('on') is False and p.get('live') is False for p in calls))) + finally:w.close() + + def test_http_failure_uses_udp_json_fallback_once(self): + http_calls=[];udp_payloads=[];releases=[] + def broken_http(self,payload,timeout=2): + http_calls.append(payload.copy()) + self.last_http_error='timed out' + raise TimeoutError('timed out') + with patch.object(WledWorker,'_http',broken_http), \ + patch.object(WledWorker,'_release_realtime',lambda self:releases.append(True) or True), \ + patch.object(WledWorker,'_udp_state',lambda self,payload:udp_payloads.append(payload.copy()) or setattr(self,'control_path','udp-json-fallback') or True): + w=WledWorker(target(),lambda *a,**k:None,None) + try: + w.RELEASE_SETTLE_SECONDS=.02 + w.preset(9,'autonome',0) + self.assertTrue(wait_for(lambda:len(udp_payloads)==1)) + snap=w.snapshot() + self.assertEqual(len(http_calls),1) + self.assertEqual(len(udp_payloads),1) + self.assertTrue(releases) + self.assertEqual(udp_payloads[0]['ps'],9) + self.assertEqual(snap['state'],'AUTONOMOUS_UDP') + finally:w.close() + + def test_http_circuit_breaker_skips_repeat_calls(self): + http_calls=[];udp_payloads=[] + with patch.object(WledWorker,'_http',lambda self,payload,timeout=None:http_calls.append(payload.copy()) or {'success':True}), \ + patch.object(WledWorker,'_udp_state',lambda self,payload:udp_payloads.append(payload.copy()) or setattr(self,'control_path','udp-json-fallback') or True): + w=WledWorker(target(),lambda *a,**k:None,None) + try: + w.RELEASE_SETTLE_SECONDS=.02 + w.next_http_try=time.monotonic()+60 + w.preset(11,'autonome',0) + self.assertTrue(wait_for(lambda:len(udp_payloads)==1)) + snap=w.snapshot() + self.assertEqual(http_calls,[]) + self.assertEqual(len(udp_payloads),1) + self.assertTrue(snap['pending_confirmation']) + self.assertGreater(snap['http_retry_in'],50) + self.assertEqual(snap['state'],'AUTONOMOUS_UDP') + finally:w.close() + + def test_udp_fallback_is_confirmed_when_http_recovers(self): + probes=[];udp_payloads=[] + with patch.object(WledWorker,'_http',lambda self,payload,timeout=None:(_ for _ in ()).throw(AssertionError('HTTP POST should not be needed when state already matches'))), \ + patch.object(WledWorker,'_http_state',lambda self,timeout=.8:probes.append(True) or {'on':True,'ps':9}), \ + patch.object(WledWorker,'_udp_state',lambda self,payload:udp_payloads.append(payload.copy()) or setattr(self,'control_path','udp-json-fallback') or True): + w=WledWorker(target(),lambda *a,**k:None,None) + try: + w.RELEASE_SETTLE_SECONDS=.02 + w.next_http_try=time.monotonic()+60 + w.preset(9,'autonome',0) + self.assertTrue(wait_for(lambda:len(udp_payloads)==1)) + with w.lock:w.next_http_try=time.monotonic() + self.assertTrue(wait_for(lambda:bool(probes))) + snap=w.snapshot() + self.assertEqual(len(udp_payloads),1) + self.assertTrue(probes) + self.assertFalse(snap['pending_confirmation']) + self.assertEqual(snap['control_path'],'http-recovered') + self.assertEqual(snap['state'],'AUTONOMOUS') + finally:w.close() + + def test_stream_entry_wakes_wled_with_full_global_brightness(self): + controls=[];sent=[] + with patch.object(WledWorker,'_release_realtime',lambda self:True), \ + patch.object(WledWorker,'_udp_state',lambda self,payload:controls.append(payload.copy()) or True), \ + patch.object(WledWorker,'_send_frame',lambda self,frame:sent.append(frame) or True): + w=WledWorker(target(),lambda *a,**k:None,None) + try: + w.stream([(20,30,40)]*12,25,'test') + self.assertTrue(wait_for(lambda:bool(sent))) + self.assertTrue(any(p.get('on') is True and p.get('bri')==255 for p in controls)) + finally:w.close() + + def test_resync_after_wled_reboot_restores_realtime_baseline(self): + controls=[];releases=[] + with patch.object(WledWorker,'_release_realtime',lambda self:releases.append(True) or True), \ + patch.object(WledWorker,'_udp_state',lambda self,payload:controls.append(payload.copy()) or True): + w=WledWorker(target(),lambda *a,**k:None,None) + try: + with w.lock:w.resync_requested=True + w._resync_stream() + snap=w.snapshot() + self.assertTrue(releases) + self.assertTrue(any(p.get('on') is True and p.get('bri')==255 for p in controls)) + self.assertFalse(snap['resync_requested']) + self.assertGreaterEqual(snap['recoveries'],1) + finally:w.close() + + def test_manual_wled_reboot_uses_reboot_command(self): + http=[];udp=[];releases=[] + with patch.object(WledWorker,'_release_realtime',lambda self:releases.append(True) or True), \ + patch.object(WledWorker,'_http',lambda self,payload,timeout=None:http.append(payload.copy()) or {}), \ + patch.object(WledWorker,'_udp_state',lambda self,payload:udp.append(payload.copy()) or True): + w=WledWorker(target(),lambda *a,**k:None,None) + try: + self.assertTrue(w.reboot('test')) + self.assertTrue(wait_for(lambda:any(p.get('rb') is True for p in http))) + self.assertTrue(releases) + self.assertEqual(udp,[]) + finally:w.close() + + def test_rainbow_effect_contains_multiple_primary_dominances(self): + frame=effect('rainbow',120,0) + self.assertTrue(any(r>200 and g<100 and b<100 for r,g,b in frame)) + self.assertTrue(any(g>200 and r<100 and b<100 for r,g,b in frame)) + self.assertTrue(any(b>200 and r<100 and g<100 for r,g,b in frame)) + + def test_diagnostics_persistent_copyable_report(self): + with tempfile.TemporaryDirectory() as tmp: + d=Diagnostics(Path(tmp),'detailed',7,10) + try: + d.event('normal','ENGINE','démarrage') + d.event('detailed','PRESENCE','Logo : Inactivité',idle=300) + time.sleep(.15) + report=d.report(30,{'version':'0.4.2'}) + self.assertIn('RAPTOR LINK',report) + self.assertIn('Logo : Inactivité',report) + self.assertIn('version: 0.4.2',report) + finally:d.close() + + def test_diagnostics_off_skips_writes(self): + with tempfile.TemporaryDirectory() as tmp: + d=Diagnostics(Path(tmp),'off',7,10) + try: + d.event('normal','ENGINE','should not exist') + time.sleep(.1) + self.assertEqual(d.recent_lines(30),[]) + finally:d.close() + +class WindowLifecycle(unittest.TestCase): + def test_window_controller_blocks_duplicate_launch_while_starting(self): + launches=[];now=[100.0] + w=WindowController(lambda:False,lambda:launches.append(True),clock=lambda:now[0]) + w.open();w.open() + self.assertEqual(len(launches),1) + now[0]=131.0 + w.open() + self.assertEqual(len(launches),2) + + def test_window_controller_focuses_existing_window_without_launching(self): + launches=[] + w=WindowController(lambda:True,lambda:launches.append(True)) + w.open() + self.assertEqual(launches,[]) + + def test_window_controller_closes_dashboard_on_app_quit(self): + closes=[] + w=WindowController(lambda:False,lambda:None,close=lambda:closes.append(True) or True) + self.assertTrue(w.close()) + self.assertEqual(closes,[True]) + +if __name__=='__main__': + unittest.main() diff --git a/Raptor-Link-0.3.4-Projet/raptor-build/test_support.py b/Raptor-Link-0.3.4-Projet/raptor-build/test_support.py index 56d17d0..c502125 100644 --- a/Raptor-Link-0.3.4-Projet/raptor-build/test_support.py +++ b/Raptor-Link-0.3.4-Projet/raptor-build/test_support.py @@ -11,18 +11,18 @@ class Support(unittest.TestCase): def test_version_parser(self): - self.assertEqual(version_tuple('v0.3.13'), (0,3,13)) - self.assertEqual(version_tuple('0.4.0-beta'), (0,4,0)) + self.assertEqual(version_tuple('v0.4.1'), (0,4,1)) + self.assertEqual(version_tuple('0.4.1-beta'), (0,4,1)) self.assertIsNone(version_tuple('latest')) def test_feedback_url_is_prefilled(self): - url=issue_url('compatibility','Mystic Light','Test message',5,{'raptor_link':'0.3.13'},'MSI Mystic Light') + url=issue_url('compatibility','Mystic Light','Test message',5,{'raptor_link':'0.4.1'},'MSI Mystic Light') self.assertEqual(urlparse(url).netloc,'github.com') q=parse_qs(urlparse(url).query) self.assertIn('[Compatibility]',q['title'][0]) self.assertIn('MSI Mystic Light',q['body'][0]) self.assertIn('5/5',q['body'][0]) - self.assertIn('0.3.13',q['body'][0]) + self.assertIn('0.4.1',q['body'][0]) def test_rating_is_only_due_once(self): with tempfile.TemporaryDirectory() as tmp: