首页 > 解决方案 > 自动刷新 Justgage 中的值

问题描述

在此处输入图像描述

  <!doctype html>
<html>

<head>
    <title>Machine Learning Data Dashboard</title>
    <link rel="stylesheet" href='../static/style.css'/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <style>
        body {
            text-align: center;
        }
        #g1,
        #g2,
        #g3,
        #g4 {
            width: 350px;
            height: 260px;
            display: inline-block;
            margin: 4em;
        }
    </style>
</head>

<body>
    <h1>Machine Learning Data Dashboard</h1>
    <div id="g1"></div>
    <div id="g2"></div>
    <div id="g3"></div>
    <div id="g4"></div>
    <hr>
    <h3> Last Sensors Reading: {{ time }} ==> <a href="/"class="button">REFRESH</a></h3>    
    <hr>
    <h3> HISTORICAL DATA </h3>
        <p> Enter number of samples to retrieve:
        <form method="POST">
            <input name="numSamples" value= {{numSamples}}>
            <input type="submit">
        </form></p>
        <hr>
        <img src="/plot/temp" alt="Image Placeholder" width="22%">
        <img src="/plot/hum" alt="Image Placeholder" width="22%">
        <img src="/plot/nois" alt="Image Placeholder" width="22%">
        <img src="/plot/pres" alt="Image Placeholder" width="22%">
    <p> @2018 Developed by MJRoBot.org</p>

    <script src="../static/raphael-2.1.4.min.js"></script>
    <script src="../static/justgage.js"></script>
    <script>
        var g1, g2, g3, g4;
        document.addEventListener("DOMContentLoaded", function(event) {
            g1 = new JustGage({
                id: "g1",
                value: {{temp}},
                valueFontColor: "yellow",
                titleFontColor: "yellow",
                pointer: true,
                min: -10,
                max: 50,
                pointer: true,
                    pointerOptions: {
                      stroke_width: -1,
                      stroke_linecap: 'round'
                    },
                title: "Temperature",
                label: "°C"
            });
            g2 = new JustGage({
                id: "g2",
                value: {{hum}},
                valueFontColor: "yellow",
                titleFontColor: "yellow",
                donut: true,
                pointer: true,
                    gaugeWidthScale: 0.4,
                min: 0,
                max: 100,
                title: "Humidity",
                label: "%"
            });
            g3 = new JustGage({
                id: "g3",
                value: {{nois}},
                valueFontColor: "yellow",
                titleFontColor: "yellow",
                donut: true,
                pointer: true,
                    gaugeWidthScale: 0.4,
                min: 0,
                max: 100,
                title: "Noise",
                label: "dB"
            });
            g4 = new JustGage({
                id: "g4",
                value: {{pres}},
                valueFontColor: "yellow",
                titleFontColor: "yellow",
                min: 0,
                max: 100,
                pointer: true,
                    pointerOptions: {
                      toplength: 8,
                      bottomlength: -20,
                      bottomwidth: 6,
                      stroke_width: 3,
                      stroke_linecap: 'round'
                    },
                gaugeWidthScale: 0.1,
                title: "Pressure",
                label: "Pa"
            });

            setInterval(function() {
                  g1.refresh();
                  g2.refresh;
                  g3.refresh;
                  g4.refresh;
                }, 2500);



        });
    </script>
</body>

</html>

我试图让项目中的量具值自动更新,而不是通过当前单击 REFRESH 按钮来更新。

有一个 Justgage 示例显示自动刷新,如下代码:

 setInterval(function() {
      g1.refresh(getRandomInt(50, 100));
      g2.refresh(getRandomInt(50, 100));
      g3.refresh(getRandomInt(0, 50));
      g4.refresh(getRandomInt(0, 50));
    }, 2500);

这里使用的是随机数,但是我的 4 个 VARiables 是由数据库的数据更新的,所以我不需要随机部分。

任何人都可以建议我应该如何编写这部分代码来自动刷新量具?

设置间隔?设置超时?还是需要 Ajax?

我的Javascript很差,谢谢。

标签: javascripthtmlajaxsetintervaljustgage

解决方案


刷新仪表的最佳方法是使用 FCM (firebase)。

https://firebase.google.com/docs/cloud-messaging?hl=pt-br

在每次更改中,您都会为 firebase 发送通知,当返回响应 firebase 时,您会调用该函数。

如果您使用 PHP,您可以使用 curl 发送通知。喜欢:

public function sendNotification($title, $body, $token)
 {
    $url = 'https://fcm.googleapis.com/fcm/send';
    $headers = [
        'Authorization: key=GET_THE_AUTORIZATION_AND_PUT_HERE',
        'Content-type: application/json'
    ];
    $notification = [
        'title' => $title,
        'body'  => $body
    ];

    $request = [
        'notification' => $notification,
        "registration_ids" => array($token)
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request));

    $res = curl_exec($ch);
    return $res;

    curl_close($ch);
 }

在 Firebase 中注册后,您将获得信息并输入您的代码 js。应该是这样的:

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
    apiKey: "this information is filled by firebase",
    authDomain: "this information is filled by firebase",
    projectId: "this information is filled by firebase",
    storageBucket: "this information is filled by firebase",
    messagingSenderId: "this information is filled by firebase",
    appId: "this information is filled by firebase",
    measurementId: "this information is filled by firebase"
};
 // Initialize Firebase
 firebase.initializeApp(firebaseConfig);

 let token;
 const fcm = firebase.messaging();
 fcm.getToken({
 vapidkey: 'IN HERE YOU PUT KEY PAIR' // yout get in settings > cloudmessaging - in the firebase
 }).then((currentToken) => {
if (currentToken) {
    token = currentToken;
    console.log(currentToken);
} else {
    // Show permission request UI
    console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
    console.log('An error occurred while retrieving token. ', err);
 });

 fcm.onMessage((data) => {
     // in here you call
     g1.refresh(getRandomInt(50, 100));
     g2.refresh(getRandomInt(50, 100));
     g3.refresh(getRandomInt(0, 50));
     g4.refresh(getRandomInt(0, 50));
 }

推荐阅读