· 5 years ago · Aug 23, 2020, 03:48 PM
1<?php
2// Define your zip code and openweather API key here:
3 $zipcode = "12345";
4 $apikey = "12345abc12345abc";
5
6// Define where the sh files are located here, include trailing /:
7 $filedir = "/home/pi/freezer/";
8
9// Define temperatures you want the plug to turn off and on at
10// E.g. if you turn the plug off at 0 and the temp is -1, it'll turn off and stay off until
11// the temperature gets above the temp_to_turn_on_at.
12 $temp_to_turn_off_at = 0;
13 $temp_to_turn_on_at = 10;
14
15// Read the current temperature from openweathermap and convert it to F:
16 $query = "http://api.openweathermap.org/data/2.5/weather?zip=".$zipcode."&appid=".$apikey;
17 $json = file_get_contents($query);
18 $json_array = json_decode($json);
19 $main = $json_array->main;
20 $temp_k = $main->temp;
21 $temp_f = k_to_f($temp_k);
22
23 $final_result = "NO CHANGE WAS MADE AT ".$temp_f."F";
24 if(is_numeric($temp_f)) {
25
26// A valid temp was found from openweathermap, check the plug status and determine whether to change it:
27 $plug_status = plug_status($filedir);
28 if($plug_status == "ON" || $plug_status == "OFF") {
29 if($temp_f > $temp_to_turn_on_at && $plug_status == "OFF") {
30 shell_exec("sh ".$filedir."plugon.sh");
31 $final_result = "PLUG WAS TURNED ON AT ".$temp_f."F";
32 }
33 if($temp_f < $temp_to_turn_off_at && $plug_status == "ON") {
34 shell_exec("sh ".$filedir."plugoff.sh");
35 $final_result = "PLUG WAS TURNED OFF AT ".$temp_f."F";
36 }
37 } else {
38 $final_result = "COULD NOT DETERMINE PLUG STATUS!";
39 }
40 } else {
41 $final_result = "COULD NOT DETERMINE CURRENT TEMPERATURE!";
42 }
43
44 $current_timestamp = date("Y-m-d H:i:s");
45 $log_entry = $current_timestamp." - ".$final_result;
46 echo log_result($filedir."log.txt", $log_entry);
47
48function log_result($filename, $log_entry) {
49// Simple function to write a log entry to a log file, return an error if it couldn't be
50// written to, probably need to create the file and chmod it first.
51 $file = fopen($filename, "a");
52 if($file == FALSE) {
53 return "COULD NOT OPEN LOG FILE!\r\n\r\n".$log_entry;
54 } else {
55 fwrite($file, $log_entry."\r\n");
56 fclose($file);
57 return $log_entry;
58 }
59}
60
61function plug_status($filedir) {
62// Read the current on/off state of the plug and return it as "ON" or "OFF":
63 $status = shell_exec("sh ".$filedir."plugstatus.sh 2<&1");
64 if(strpos($status, "ON")>0) { $result = "ON"; }
65 if(strpos($status, "OFF")>0) { $result = "OFF"; }
66 return $result;
67}
68
69function k_to_f($temp) {
70// Thanks to: http://scottnelle.com/592/convert-openweathermaps-kelvin-temperatures-php/
71 if ( !is_numeric($temp) ) { return false; }
72 return round((($temp - 273.15) * 1.8) + 32);
73}
74?>
75