-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.php
More file actions
87 lines (77 loc) · 2.82 KB
/
Copy pathjson.php
File metadata and controls
87 lines (77 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
* disc-cloud-tracker — latest-measurement-per-device JSON endpoint
*
* Returns, as a JSON array, the most recent row in `mesures` for each
* distinct device (`DISC`).
*
* Note: the `check_disc` SQL view provided in schema.sql does exactly the
* same thing more elegantly. The inline join below keeps this script
* self-contained (no dependency on the view being installed).
*/
// ---------------------------------------------------------------------------
// Fail fast on missing critical environment variables (no placeholder fallback)
// ---------------------------------------------------------------------------
function require_env(string $name): string {
$v = getenv($name);
if ($v === false || $v === '' || $v === 'changeme') {
http_response_code(500);
error_log("FATAL: environment variable $name is not set");
die("Configuration error");
}
return $v;
}
// ---------------------------------------------------------------------------
// Database configuration (from environment variables; DB_PASSWORD is required)
// ---------------------------------------------------------------------------
$DB_HOST = getenv('DB_HOST') ?: 'localhost';
$DB_PORT = (int) (getenv('DB_PORT') ?: 3306);
$DB_NAME = getenv('DB_NAME') ?: 'disc';
$DB_USER = getenv('DB_USER') ?: 'disc';
$DB_PASSWORD = require_env('DB_PASSWORD');
// Connect to MySQL
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME, $DB_PORT);
if ($conn->connect_error) {
http_response_code(500);
die("Database connection failed: " . $conn->connect_error);
}
// Optimised self-join: fetch the latest row per DISC in a single query.
// (Equivalent to the `check_disc` view defined in schema.sql.)
$sql = "SELECT
m1.id AS id,
m1.V1 AS V1,
m1.V2 AS V2,
m1.POW AS POW,
m1.TEMP AS TEMP,
m1.R1 AS R1,
m1.GSM_DATA AS GSM_DATA,
m1.SERIAL_DATA_LATITUDE AS SERIAL_DATA_LATITUDE,
m1.LATITUDE AS LATITUDE,
m1.LONGITUDE AS LONGITUDE,
m1.ACPLUG AS ACPLUG,
m1.DISC AS DISC,
m1.timestamp AS timestamp,
m1.ADRESSE AS ADRESSE
FROM mesures m1
JOIN (
SELECT DISC, MAX(timestamp) AS max_timestamp
FROM mesures
GROUP BY DISC
) m2 ON m1.DISC = m2.DISC AND m1.timestamp = m2.max_timestamp
ORDER BY m1.DISC;";
$result = $conn->query($sql);
if ($result === false) {
http_response_code(500);
die("SQL error: " . $conn->error);
}
header('Content-Type: application/json');
if ($result->num_rows > 0) {
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);
} else {
echo json_encode([]);
}
$conn->close();