User Tools

Site Tools


influxdb

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
influxdb [2023/05/07 11:45] – external edit 127.0.0.1influxdb [2025/11/15 23:12] (current) – [Zaehlerständeim Haus] lars
Line 45: Line 45:
 </WRAP> </WRAP>
  
 +==== Zaehlerständeim Haus ====
 +=== Import aus ECAS ===
 +Bis 2025 hat Lars die Zählerstände in einer App Namens ECAS auf seinem Handy erfasst. 
 +Die ist aber nicht länger im PlayStore zu bekommen.
 +Man kann in der App die Daten exportieren, und bekommt eine SQlite-Datenbank.
 +Der letzte Stand ist hier zu finden: {{ :2025-11-15-ecas-export.7z | ecas-export vom 25.11.2025 }}
  
 +Die Daten aus der Datenbank habe ich per Script nach InfluxDB überführt.
 +Das Script hat ChatGPT für mich geschrieben.
 +<code bash>
 +sqlite3 ./2025-11-15-ecas-export.db -readonly -csv \
 +"SELECT meterid, date, value, comment FROM reading" \
 +| tail -n +2 \
 +| awk -F',' '
 +function map_meter(id, datetime) {
 +  if (id == 1) return "strom1";
 +  if (id == 2) return "gas1";
 +  if (id == 3) {
 +    swap_time = "2021-05-27T08:30:00";
 +    if (datetime >= swap_time) return "wasser2";
 +    else return "wasser1";
 +  }
 +  return "unbekannt";
 +}
 +function map_unit(id) {
 +  if (id == 1) return "kwh";
 +  if (id == 2) return "m3";
 +  if (id == 3) return "m3";
 +  return "unknown";
 +}
 +function to_ns(datetime) {
 +  cmd = "date -d \"" datetime "\" +%s"
 +  cmd | getline seconds
 +  close(cmd)
 +  return seconds "000000000"
 +}
 +{
 +  meter = map_meter($1, $2);
 +  unit  = map_unit($1);
 +  ts_ns = to_ns($2);
 +  value = $3;
 +  comment = $4;
 +
 +  # SQLite liefert "" für leere Kommentare → ignorieren
 +  if (comment == "\"\"") comment = "";
 +
 +  # Zeile mit oder ohne Bemerkung
 +  if (comment != "") {
 +    printf("zaehlerstand,zaehler=%s,einheit=%s wert=%s,Bemerkung=%s %s\n", meter, unit, value, comment, ts_ns);
 +  } else {
 +    printf("zaehlerstand,zaehler=%s,einheit=%s wert=%s %s\n", meter, unit, value, ts_ns);
 +  }
 +
 +  # Gas (ursprünglich meterid=2) zusätzlich kWh
 +  if ($1 == 2) {
 +    kwh = value * 9.76608;
 +    if (comment != "") {
 +      printf("zaehlerstand,zaehler=%s,einheit=kwh wert=%.5f,Bemerkung=%s %s\n", meter, kwh, comment, ts_ns);
 +    } else {
 +      printf("zaehlerstand,zaehler=%s,einheit=kwh wert=%.5f %s\n", meter, kwh, ts_ns);
 +    }
 +  }
 +}'
 +</code>
 +Diverse Besonderheiten werden darin bearbeitet wie etwa die Umrechnung der eingelesenen Gaszaehlerwerte in m³ in kWh (x9,76608) oder der Austausch des Wasserzaehlers am 27.05.2021.
 +
 +Die Übertragung von ECAS  nach InfluxDB hat am 15.11.2025 stattgefunden.
 +
 +=== Eingabe via Webseite ===
 +
 +Mit ChatGPT und einiger eigener Arbeit ist diese PHP-Seite herausgekommen, die in die InfluxDB schreibt.
 +Damit kann ich neue Werte aufnehmen.
 +<code php>
 +<?php
 +?>
 +<!DOCTYPE html>
 +<html lang="de">
 +<head>
 +<meta charset="UTF-8">
 +<title>Zählerstand erfassen</title>
 +<style>
 +body { font-family: sans-serif; margin: 2rem; background: #f7f7f7; }
 +h1 { text-align: center; }
 +form { max-width: 420px; margin: auto; background: white; padding: 2rem; border-radius: 1rem; box-shadow: 0 4px 12px rgba(0,0,0,0.1); display: flex; flex-direction: column; gap: 1rem; }
 +input, select, button { padding: 0.7rem; font-size: 1rem; border: 1px solid #ccc; border-radius: 0.6rem; }
 +button { background: #007bff; border: none; color: white; cursor: pointer; transition: background 0.2s; }
 +button:hover { background: #0056c8; }
 +.info { text-align: center; color: #555; margin-bottom: 1rem; }
 +.success { color: green; text-align: center; }
 +.error { color: red; text-align: center; }
 +</style>
 +</head>
 +<body>
 +<h1>Zählerstand erfassen</h1>
 +<?php
 +// --- CONFIG ---
 +$influx_url = "http://192.168.17.22:10003";
 +$org = "larshome";
 +$bucket = "zaehlerstaende_manuell";
 +$token = "w5DXjsqJbEL7DgAOLXszsZ_IXoGp5MbNQq1bPkOOlXuXt4Qbrq8EOVn9EMIriNgmbXfHdRiZmT9o1NJOVZLSug==";
 +
 +function query_influx_selected() {
 +    global $influx_url, $org, $token, $bucket;
 +    $zaehler_list = ['strom1','gas1','wasser2'];
 +    $results = [];
 +
 +    foreach ($zaehler_list as $z) {
 +        $flux = <<<FLUX
 +from(bucket: "$bucket")
 +  |> range(start: -5y)
 +  |> filter(fn: (r) => r._measurement == "zaehlerstand")
 +  |> filter(fn: (r) => r["_field"] != "Bemerkung")
 +FLUX;
 +
 +        // Gas: nur Einträge ohne Einheit kWh
 +        if ($z === 'gas1') {
 +            $flux .= "\n  |> filter(fn: (r) => r[\"einheit\"] != \"kwh\")";
 +        }
 +
 +        $flux .= "\n  |> filter(fn: (r) => r[\"zaehler\"] == \"$z\")";
 +        $flux .= "\n  |> last()";
 + $flux .= "\n  |> keep(columns: [\"_time\", \"_value\", \"zaehler\", \"_field\"])";
 +
 +        $curl = curl_init();
 +        curl_setopt_array($curl, [
 +            CURLOPT_URL => "$influx_url/api/v2/query?org=$org",
 +            CURLOPT_RETURNTRANSFER => true,
 +            CURLOPT_POST => true,
 +            CURLOPT_HTTPHEADER => [
 +                "Authorization: Token $token",
 +                "Content-Type: application/vnd.flux"
 +            ],
 +            CURLOPT_POSTFIELDS => $flux
 + ]);
 + /*
 + print "<!-- <?= ";
 +    print $flux;
 + print " ?> -->";
 + print PHP_EOL;
 + */
 +
 +        $resp = curl_exec($curl);
 +        curl_close($curl);
 +
 +        $results[$z] = null;
 +        $lines = explode("\n", $resp);
 + foreach ($lines as $line) {
 +    /*
 +     print "<!-- <?= ";
 +     print $line;
 +     print " ?> -->";
 +     print PHP_EOL;
 +     */
 +            if (strpos($line, '_value') !== false) continue;
 +     $parts = str_getcsv($line, ',', '"', '\\');
 +     /*
 +     print "<!-- <?= ";
 +     print count($parts);
 +     print implode(" and ",$parts);
 +     print " ?> -->";
 +     print PHP_EOL;
 +      */
 +            if (count($parts) < 6) continue;
 +     /*
 +     print "<!-- <?= ";
 +     print "value: $parts[4] ";
 +     print "time: $parts[3] ";
 +     print " ?> -->";
 +     print PHP_EOL;
 +      */
 +            $value = $parts[4] ?? null;
 +            $time = $parts[3] ?? null;
 +            if ($value !== null) {
 +                $results[$z] = ['value'=>$value, 'time'=>$time, 'raw_lines'=>$lines];
 +            }
 +        }
 +    }
 +    return $results;
 +}
 +
 +$latest_selected = query_influx_selected();
 +?>
 +<!-- Letzte Werte aus InfluxDB -->
 +<?php foreach ($latest_selected as $k => $v): ?>
 +<!-- <?= $k ?>: <?= $v ? $v['value'].' @ '.$v['time'] : 'Keine Daten' ?> -->
 +<?php endforeach; ?>
 +<div class="info" id="latestInfo"></div>
 +<form method="POST" action="" id="meterForm">
 +  <label>Zähler
 +    <select name="zaehler" id="zaehlerSelect" required>
 +      <option value="strom1">Strom</option>
 +      <option value="gas1">Gas</option>
 +      <option value="wasser2">Wasser</option>
 +    </select>
 +  </label>
 +  <label>Zeitpunkt
 +    <input type="datetime-local" name="zeit" required value="<?= date('Y-m-d\TH:i') ?>" />
 +  </label>
 +  <label>Wert
 +    <input type="number" step="0.0001" name="wert" required />
 +  </label>
 +  <label>Bemerkung (optional)
 +    <input type="text" name="bemerkung" />
 +  </label>
 +  <button type="submit">Senden</button>
 +</form>
 +<script>
 +const latestAll = <?= json_encode($latest_selected) ?>;
 +const latestInfo = document.getElementById('latestInfo');
 +const zaehlerSelect = document.getElementById('zaehlerSelect');
 +function updateLatest() {
 +    const selected = zaehlerSelect.value;
 +    const data = latestAll[selected];
 +    if (data) {
 +        latestInfo.textContent = `Letzter Wert: ${data.value} — Datum: ${data.time}`;
 +    } else {
 +        latestInfo.textContent = 'Keine Daten vorhanden.';
 +    }
 +}
 +zaehlerSelect.addEventListener('change', updateLatest);
 +updateLatest();
 +</script>
 +<?php
 +if ($_SERVER['REQUEST_METHOD'] === 'POST') {
 +    $z = $_POST['zaehler'];
 +    $zeit = $_POST['zeit'];
 +    $wert = $_POST['wert'];
 +    $bem = trim($_POST['bemerkung']);
 +    $ts = strtotime($zeit) * 1000000000;
 +
 +    $lines_to_write = [];
 +
 +    // Gas: m³ mit tag "einheit=m3", zusätzlich kWh mit tag "einheit=kwh"
 +    if ($z === 'gas1') {
 +        $lines_to_write[] = "zaehlerstand,zaehler=gas1,einheit=m3 wert=$wert" . ($bem !== '' ? ",Bemerkung=\"".str_replace(" ","\\ ",$bem)."\"" : '') . "\" $ts";
 +        $kwh = $wert * 9.76608;
 +        $lines_to_write[] = "zaehlerstand,zaehler=gas1,einheit=kwh wert=$kwh $ts";
 +    } elseif ($z==='strom1') {
 +        $lines_to_write[] = "zaehlerstand,zaehler=$z,einheit=kwh wert=$wert" . ($bem !== '' ? ",Bemerkung=\"".str_replace(" ","\\ ",$bem)."\"" : '') . "\" $ts";
 +    } elseif ($z==='wasser2') {
 +        $lines_to_write[] = "zaehlerstand,zaehler=$z,einheit=m3 wert=$wert" . ($bem !== '' ? ",Bemerkung=\"".str_replace(" ","\\ ",$bem)."\"" : '') . " $ts";
 +    } else {
 +        $lines_to_write[] = "zaehlerstand,zaehler=$z wert=$wert" . ($bem !== '' ? ",Bemerkung=\"".str_replace(" ","\\ ",$bem) : '') . "\" $ts";
 +    }
 +
 +    foreach ($lines_to_write as $line) {
 +        $curl = curl_init();
 +        curl_setopt_array($curl, [CURLOPT_URL => "$influx_url/api/v2/write?org=$org&bucket=$bucket&precision=ns", CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => ["Authorization: Token $token","Content-Type: text/plain; charset=utf-8"], CURLOPT_POSTFIELDS => $line]);
 +        $response = curl_exec($curl);
 +        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
 +        curl_close($curl);
 +        if ($status >=200 && $status<300) echo "<p>Erfolgreich gespeichert: $line</p>";
 +        else echo "<p>Fehler: $response</p>";
 +    }
 +}
 +?>
 +</body>
 +</html>
 +</code>
 +
 +Die Seite ist im webserver auf inuk gehostet. Die URL ist [[http://inuk:10025/zaehlerstandeingabe.php]].
influxdb.1683452723.txt.gz · Last modified: by 127.0.0.1