Почему мой доступ к базе данных Sqlite3 через Php чрезвычайно медленный (Raspberry Pi 3 B +) - PullRequest
0 голосов
/ 23 октября 2018

Я пытаюсь создать некоторый серверный код, который будет непрерывно запрашивать базу данных Sqlite3, работающую на том же устройстве (Rasp Pi 3B +), которая используется для обнаружения изменений в одном кортеже в базе данных и для обновления index.htmlстраница соответственно.

Вот index.html:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Caldera Dartcast </title>
    </head>
    <body bgcolor="white">
        <h1 style="color:#000000;"> Caldera Dartcast </h1>
        <!--here is where the text from the server -->
        <div id="serverData">
            <iframe
                    scrolling="no"
                    width="800" height="600" <img src = http://10.0.0.172:8085/stream_simple.html" />
            stream=BoardOne" frameborder="0" allowfullscreen>
            </iframe>
            <iframe
                    scrolling="no"
                    width="500" height="600" <img src = http://10.0.0.172:8086/stream_simple.html" />
            stream=PlayerOne" frameborder="0" allowfullscreen>
            </iframe>
        </div>
        <div id="serverTestDiv" >

        </div>

        <script>
            //check for browser support
            if(typeof(EventSource)!=="undefined") {

                //create an object, passing it the name and location of the server side script
                var eSource = new EventSource('ViewController.php');
                console.log(eSource.withCredentials);
                console.log(eSource.readyState);
                console.log(eSource.url);
                eSource.onopen = function() {
                    console.log("Connection to server opened.");
                };
                //detect message receipt
                eSource.onmessage = function(event) {
                    //write the received data to the page
                    //window.alert("Boo");
                    document.getElementById("serverTestDiv").innerHTML = event.data;
                    console.log("esource.onmessage called!");
                };
                // window.alert("Ok, we're here 2.");

            }
            else {
                document.getElementById("serverTestDiv").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
            }
        </script>
    </body>
</html>

На данный момент все, что я действительно хочу сделать, - это отправить некоторый текст в div с именем "serverTestDiv".И это работает - я могу.Проблема в том, что когда я загружаю index.html, иногда требуется более 5 минут, чтобы распечатать начальное «Не обнаружено изменений в базе данных» - что не сработает.Он должен уметь обнаруживать изменения базы данных довольно быстро (задержка в 5 секунд вполне подойдет), потому что я планирую иметь дополнительный PHP для записи обновлений в тот же кортеж, который, я надеюсь, я могу каскадировать для внешнего пользователяв виде обновленного макета.

Вот Php.Опять же, это похоже на работу, просто очень медленно.Я подозреваю, что проблема с моим PDO соглашением, но часы поиска в Google ничего не дали.

<?php
date_default_timezone_set("America/Los_Angeles");
header("Cache-Control: no-cache");
header("Content-Type: text/event-stream");
//stream new webpages to the main view
//if the value for the active page has changed
//initialize $myPDO to point at our database
$myPDO = new PDO('sqlite:/home/pi/pi_DB.sqlite3');
$previousQuery = $myPDO->query("SELECT ValueInt FROM Configuration WHERE Name = 'IndexPage'");
$previousQueryResult = $previousQuery->fetch(PDO::FETCH_ASSOC);
$previousQueryValue = $previousQueryResult['ValueInt'];
$currentPDO = new PDO('sqlite:/home/pi/pi_DB.sqlite3');

while (1) {



    //query the database again
    $currentQuery = $currentPDO->query("SELECT ValueInt FROM Configuration WHERE Name = 'IndexPage'");
    $currentQueryResult = $currentQuery->fetch(PDO::FETCH_ASSOC);
    $currentQueryValue = $currentQueryResult['ValueInt'];

    if ($currentQueryValue == $previousQueryValue) { //if the new result is equal to our current result, do nothing
        also: echo "data: No database change detected. \n\n";
    } else {
        //there is a new value in our index entry,
        // so we need to to signal index.html to reload itself with updated layout
        echo "data: " . $currentQueryValue . "\n\n";
        $previousQueryValue = $currentQueryValue;
    }
    flush();

    //need to add some html to indicate when a command has been received by the
    //page viewswitcher.html that will show us our updated perspective.

    sleep(1);

}

Эти четыре языка (HTML, Php, Javascript и SQL) все для меня очень новые, и большая часть моего кода была взята из примеров.Я ценю любую помощь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...