#!/usr/bin/perl

$temp_file = "/sys/bus/iio/devices/iio:device0/in_temp_input";
$hum_file = "/sys/bus/iio/devices/iio:device0/in_humidityrelative_input";

while (1) {
    if (open ($th,"<",$temp_file)) {
        $temp = <$th>;
        close $th;
        if (!defined($temp)) {
            sleep(1);
            next;
        }
        chomp $temp;
        if (open ($hh,"<",$hum_file)) {
            $hum = <$hh>;
            close $hh;
            if (!defined($hum)) {
                sleep(1);
                next;
            }
            chomp $hum;
    
            $tempC = sprintf "%.1f",$temp / 1000.0;
            $tempF = sprintf "%.1f",$tempC * 9.0 / 5.0 + 32.0;
            $hum = sprintf "%.1f",$hum / 1000.0;

            print_html();

            last;
        }
    }
    sleep(1);
}

sub print_html {
    print <<EOT;
Content-Type: text/html;

<!DOCTYPE=html>
<html lang="en_US">
    <head>
        <title>DHT11/22 Web Page</title>
        <meta charset="UTF-8">
        <meta http-equiv="refresh" content="60">
        <style>
            h1 { text-align: center; }
            body {
                font-family: sans-serif;
                color: #E30B5C;
            }
            table {
                margin: 0 auto;
                border-collapse: collapse;
            }
            th, td {
                border: 2px solid #E30B5C;
                padding: 20px;
                text-align: center;
                font-size: larger;
            }
        </style>
    </head>
    <body>
        <h1>DHT11/22 Temperature/Humidity</h1>
        <table>
            <tr><th colspan="2">Temperature</th><th>Humidity</th>
            <tr><td>$tempC&deg;C</td><td>$tempF&deg;F</td><td>$hum&#37;</td>
        </table>
    </body>
</html>
EOT
    return;
}