0

Hey I'm read the status of the lamp with $status. Now I want the color of the button to change depending on whether the lamp is on or off. For that the variable $status needs to be updated continuously, but I don't know how to do this. I tried with a while(true) loop but then the website keeps loading and loading. Hope you can help me :)

<?php
    
if (isset($_POST['lampe1'])){
$status= exec('gpio -g read 23');
    if($status==0){
        shell_exec("gpio -g write 23 1"); //switching lamp on   
    }else{
        shell_exec("gpio -g write 23 0"); //switching lamp of
    }
}

?>

<html>
<body>
    <form method="post">
    <p>
        <button name="lampe1" style="<?php $status= exec('gpio -g read 23'); if($status==0){echo" color:black;"}?>";>Switch</button>
        //changes button color depending on $status :)
        //but when the button will be clicked on any other device/tab, it will be out of date :(
    </p>
    </form>
</body>
</html>
Felix
  • 1
  • 2
  • Does this answer your question? [Using setInterval() to do simplistic continuous polling](https://stackoverflow.com/questions/8682622/using-setinterval-to-do-simplistic-continuous-polling) – Progman Dec 30 '21 at 22:53
  • 1
    I would suggest using [Server Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) - establish the connection once and let the background PHP (or other) script work withoutout blocking the main thread. Long polling is not a great solution and WebSockets is more than is required. [Another example I wrote a few years ago](https://stackoverflow.com/questions/29480791/while-loops-for-server-sent-events-are-causing-page-to-freeze/29893054#29893054) might help – Professor Abronsius Dec 30 '21 at 22:58
  • The client (web page) invokes the PHP script that can poll the lamp to discover it's on/off status. Messages get sent back every N seconds and action is taken as appropriate – Professor Abronsius Dec 30 '21 at 23:02
  • Hey thanks for your answers. I tried to solve my problem with Server Sent Events but I wasn't able to get it to work. It would be great if you could help me with that. – Felix Dec 31 '21 at 11:10

0 Answers0