From 7e3e759713c33ab9cb7fb4c619e92c7dc3614ba3 Mon Sep 17 00:00:00 2001 From: Mendel Mobach Date: Wed, 20 May 2026 10:38:26 +0200 Subject: [PATCH] Fix voor #19 --- www/all.js | 53 ++++++++++++++++++++++++++++++++++++++++++-------- www/stream.php | 15 ++++++++++++-- 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/www/all.js b/www/all.js index cbe9c6c..216b98e 100644 --- a/www/all.js +++ b/www/all.js @@ -549,14 +549,51 @@ $( document ).ready(function() { break; } } - var source = new EventSource('stream.php?session='+session); - source.onmessage = function(event) { - var msg=JSON.parse(event.data); - var path=msg[0]; - var msg=msg[1]; - //if(path=="startup") postmsg('startup',1); - runmsg(path,msg); - } + var source = null; + var streamReconnectTimer = null; + var streamReconnectDelay = 1000; + + function scheduleStreamReconnect() { + if(streamReconnectTimer) return; + if(source) { + source.close(); + source = null; + } + streamReconnectTimer = setTimeout(function() { + streamReconnectTimer = null; + connectStream(); + }, streamReconnectDelay); + streamReconnectDelay = Math.min(streamReconnectDelay * 2, 30000); + } + + function connectStream() { + source = new EventSource('stream.php?session='+encodeURIComponent(session)+'&t='+(new Date()).getTime()); + source.onopen = function() { + streamReconnectDelay = 1000; + }; + source.onmessage = function(event) { + if(event.data == "closed") { + scheduleStreamReconnect(); + return; + } + var data; + try { + data=JSON.parse(event.data); + } catch(error) { + console.log("Invalid stream message", event.data, error); + return; + } + var path=data[0]; + var msg=data[1]; + //if(path=="startup") postmsg('startup',1); + runmsg(path,msg); + }; + source.onerror = function() { + scheduleStreamReconnect(); + }; + } + + connectStream(); $('#body').append($('
',{id: 'Firstscreen'})); $('#body').append($('
',{id: 'Secondscreen'})); diff --git a/www/stream.php b/www/stream.php index b0f45bf..3fe91c1 100644 --- a/www/stream.php +++ b/www/stream.php @@ -1,6 +1,7 @@ 0, "function"=>"procmsg"); $mqtt->subscribe($topics,0); +echo "retry: 1000\n"; echo "data: ".json_encode(array("startup","1"))."\n\n"; @flush(); @ob_flush(); +$last_ping = time(); while($mqtt->proc()){ - + if (connection_aborted()) { + break; + } + if ($last_ping < time() - 15) { + echo ": keepalive\n\n"; + @flush(); + @ob_flush(); + $last_ping = time(); + } } -echo "data: closed\n\n"; +echo ": closed\n\n"; $mqtt->close(); ?>