add_shortcode('esp32_visualizza', 'esp32_render_dati');
function esp32_render_dati() {
if (!isset($_GET['id'])) return 'ID dispositivo mancante.';
$device_id = intval($_GET['id']);
global $wpdb;
$device = $wpdb->get_row("SELECT * FROM devices WHERE id = $device_id");
if (!$device || $device->user_id != get_current_user_id()) return "Accesso negato.";
$dati = $wpdb->get_results("SELECT * FROM sensor_data WHERE device_id = $device_id ORDER BY timestamp DESC LIMIT 100");
$labels = [];
$temp = [];
$hum = [];
$peso = [];
foreach (array_reverse($dati) as $row) {
$labels[] = $row->timestamp;
$temp[] = $row->temperature;
$hum[] = $row->humidity;
$peso[] = $row->weight;
}
ob_start();
?>
<h2>Dati per dispositivo <?php echo $device->mac_address; ?></h2>
<canvas id="chart" width="600" height="300"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('chart').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels: <?php echo json_encode($labels); ?>,
datasets: [
{
label: 'Temperatura',
data: <?php echo json_encode($temp); ?>,
borderColor: 'red',
fill: false
},
{
label: 'Umidità ',
data: <?php echo json_encode($hum); ?>,
borderColor: 'blue',
fill: false
},
{
label: 'Peso',
data: <?php echo json_encode($peso); ?>,
borderColor: 'green',
fill: false
}
]
}
});
</script>
<?php
return ob_get_clean();
}