#!/bin/bash

impulse_per_watthour=2
ms_per_hour=3600000000000
gpio=$(gpiofind SCL1)

while gpiomon --num-events=1 --falling-edge $gpio 2&> /dev/null
do
    last_timestamp=$timestamp
    timestamp=$(date --utc +%s%N)

    [ -z $last_timestamp ] && continue

    delay=$(expr $timestamp - $last_timestamp)
    impulse_per_hour=$(expr $ms_per_hour / $delay)
    watt=$(expr $impulse_per_hour / $impulse_per_watthour)
    
    echo "$delay $impulse_per_hour: $watt watts"
    
    curl "https://${influxdb_domain}/api/v2/write?org=${influxdb_org}&bucket=${influxdb_bucket}&precision=ns" ${'\\'}
      -X POST ${'\\'}
      --header "Authorization: Token ${influxdb_token}" ${'\\'}
      --header "Content-Type: text/plain; charset=utf-8" ${'\\'}
      --header "Accept: application/json" ${'\\'}
      --data-binary "powermeter,host=${node_name} watts=$watt $timestamp" ${'\\'}
      2&> /dev/null &
    
    # workaround: s0 seems to flicker some times
    sleep 0.1
done
