Fix spurious state inversion on rapid clicks in Click mode#22
Open
Foroxon wants to merge 1 commit into
Open
Conversation
MegaD sends HTTP notifications sequentially and waits for a 200 response before sending the next one. Awaiting _turn_off_state (which contains asyncio.sleep(0.5)) inside the HTTP handler blocked the response for 500ms, causing MegaD to queue all subsequent notifications. Relay state change notifications then arrived out of order and incorrectly inverted the relay state in HA. Replacing `await` with `async_create_task` runs the auto-reset as a background task, allowing HA to respond to MegaD immediately (~5-40ms) and preventing notification queue buildup. Fixes MihVS#21
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #21
Problem
When a physical switch is pressed twice quickly, or two switches are pressed in rapid succession, the last triggered relay state is spuriously inverted ~500ms later.
_turn_off_stateusesawait asyncio.sleep(0.5)inside the HTTP request handler. MegaD firmware sends notifications sequentially and waits for HTTP 200 before sending the next one. This 500ms block causes MegaD to queue all subsequent notifications, which then arrive out of order — relay state change notifications (pt=N&v=X) land after the delay and incorrectly flip relay state in HA.Fix
async_create_taskruns the auto-reset as a background coroutine. HA responds to MegaD in ~5–40ms instead of 500ms, preventing notification queuing. The 500ms sensor state reset still happens correctly — just without blocking the HTTP handler.Evidence
Before fix — 502ms gap reveals MegaD was blocked:
After fix — immediate response, no spurious inversions:
Tested with MegaD firmware 4.59b9, integration v2026.5.1, HA 2026.5.4.