98 lines
2.8 KiB
PHP
98 lines
2.8 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
# ---------- Settings ----------
|
||
date_default_timezone_set('America/Los_Angeles');
|
||
$api_host = 'http://172.20.20.51';
|
||
$api_port = 5001; // drive‑health API
|
||
$api_path = '/details'; // endpoint that returns the JSON you showed
|
||
|
||
# ---------- Helper: JSON fetch ----------
|
||
function fetch_json(string $url): ?array
|
||
{
|
||
$ctx = stream_context_create([
|
||
'http' => ['timeout' => 2]
|
||
]);
|
||
$raw = @file_get_contents($url, false, $ctx);
|
||
if ($raw === false) {
|
||
return null;
|
||
}
|
||
$data = json_decode($raw, true);
|
||
return is_array($data) ? $data : null;
|
||
}
|
||
|
||
# ---------- Load data ----------
|
||
$api_url = "$api_host:$api_port$api_path";
|
||
$payload = fetch_json($api_url);
|
||
foreach ($payload['sensors'] as $s){
|
||
echo $s;
|
||
}
|
||
# ---------- Render ----------
|
||
?>
|
||
<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<title>Sensor Dashboard</title>
|
||
<link rel="stylesheet" href="src/styles.css">
|
||
<style>
|
||
.card { max-width: 550px;}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="card">
|
||
<h1>Sensor Dashboard</h1>
|
||
|
||
<?php if ($payload === null): ?>
|
||
<p style="color:red;">⚠️ Could not fetch data from the API.</p>
|
||
<?php else: ?>
|
||
<table id="sensor-table">
|
||
<thead>
|
||
<tr>
|
||
<th>Device</th>
|
||
<th>Comment</th>
|
||
<th>Temp (°C)</th>
|
||
<th>Humidity %</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<?php foreach ($payload['sensors'] as $s): ?>
|
||
<?php
|
||
$temp = $hum = '';
|
||
foreach ($s['data']['data'] as $d) {
|
||
if ($d['name'] === 'temp') $temp = $d['value'];
|
||
if ($d['name'] === 'humidity') $hum = $d['value'];
|
||
}
|
||
?>
|
||
<tr>
|
||
<td><?= htmlspecialchars($s['name']) ?></td>
|
||
<td><?= htmlspecialchars($s['comment'] ?? '') ?></td>
|
||
<td><?= htmlspecialchars($temp) ?></td>
|
||
<td><?= htmlspecialchars($hum) ?></td>
|
||
</tr>
|
||
<?php endforeach; ?>
|
||
</tbody>
|
||
</table>
|
||
<?php endif; ?>
|
||
</div>
|
||
<!-- Socket.io client -->
|
||
<script src="/socket.io/socket.io.js"></script>
|
||
<script>
|
||
const socket = io();
|
||
|
||
// Receive updated rows from Redis
|
||
socket.on('temp_hum', data => {
|
||
// `data` has the same structure as the API response
|
||
const tbody = document.querySelector('#sensor-table tbody');
|
||
tbody.innerHTML = ''; // clear existing rows
|
||
data.sensors.forEach(s => {
|
||
const temp = s.data.data.find(d => d.name==='temp')?.value ?? '';
|
||
const hum = s.data.data.find(d => d.name==='humidity')?.value ?? '';
|
||
const row = document.createElement('tr');
|
||
row.innerHTML = `<td>${s.name}</td><td>${s.comment}</td><td>${temp}</td><td>${hum}</td>`;
|
||
tbody.appendChild(row);
|
||
});
|
||
});
|
||
</script>
|
||
</body>
|
||
</html>
|