This repository has been archived by the owner on Nov 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
farmosnws.module
319 lines (268 loc) · 10.5 KB
/
farmosnws.module
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<?php
/**
* @file
* Code for the FarmOS NWS module
*/
/**
* Implements hook_menu()
*
* @return Array of menu links
*/
function farmosnws_menu() {
$items = array();
$items['admin/config/farm/farmosnws'] = array(
'title' => t('FarmOS NWS'),
'description' => t('Configure data feeds to be pulled by FarmOS NWS.'),
'page callback' => 'drupal_get_form',
'page arguments' => array('farmosnws_admin_form'),
'access arguments' => array('access administration pages'),
'file' => 'farmosnws.admin.inc',
);
$items['admin/config/farm/farmosnws/force'] = array(
'title' => t('Force Feed Pull'),
'desecription' => t('Bypass cron feed pull and pull latest feed from NWS.'),
'page callback' => 'drupal_get_form',
'page arguments' => array('farmosnws_admin_force_feed_form'),
'access arguments' => array('access administration pages'),
'type' => MENU_LOCAL_ACTION,
'file' => 'farmosnws.admin.inc',
);
return $items;
}
/**
* Implements hook_cron()
*/
function farmosnws_cron() {
// get the last cron time.
$last_cron = variable_get('farmosnws_cron_last', 0);
$next_cron = $last_cron + 3600 - 30;
// if it is time to pull the next feed, then pull it.
if (REQUEST_TIME >= $next_cron) {
farmosnws_get_xml();
}
else {
farmosnws_display_status("Cron ran. Skipping feed pull.", FALSE);
}
}
/**
* Check and create if necessary the path where the weather feeds will be stored.
*
* @param string feedpath
* String to the path that contains the feeds
*
* @return Returns whether the directory exists or not.
*/
function farmosnws_create_feed_dir($feedpath) {
$mkdirsuccess = NULL;
// check to see if the feeds directory exists. If not attempt to create it.
if (is_dir($feedpath) == FALSE) {
$mkdirsuccess = mkdir($feedpath, 755);
// verify directory exists
if ($feedpath == FALSE) {
farmosnws_display_error("Unable to create weather feed directory", TRUE);
$mkdirsuccess = FALSE;
}
else {
farmosnws_display_status("Created weather feed directory.", FALSE);
} // end if
}
else {
// skipping actions
$mkdirsuccess = TRUE;
} // end if
return $mkdirsuccess;
}
/**
* Displays an error message on the page and in the log.
*
* @param string $errmessage The error message to be displayed on the screen
* and written to the log/watchdog.
* @param boolean $display Whether or not to display the message to the
* user or only log it.
*/
function farmosnws_display_error($errmessage, $display=FALSE) {
if ($display == TRUE) {
drupal_set_message(t($errmessage), 'error', FALSE);
}
watchdog('farmosnws', t($errmessage), array(), WATCHDOG_ERROR, NULL);
}
/**
* Displays a warning message on the page and in the log.
*
* @param string $warnmessage The warning message to be displayed on the
* screen and written to the log/watchdog.
* @param boolean $display Whether or not to display the message to the
* user or only log it.
*/
function farmosnws_display_warning($warnmessage, $display=FALSE) {
if ($display == TRUE) {
drupal_set_message(t($warnmessage), 'warning', FALSE);
}
watchdog('farmosnws', t($warnmessage), array(), WATCHDOG_WARNING, NULL);
}
/**
* Displays a status message on the page and in the log.
*
* @param string $statusmessage The status message to be displayed on the
* screen and written to the log/watchdog.
* @param boolean $display Whether or not to display the message to the user
* or only log it.
*/
function farmosnws_display_status($statusmessage, $display=FALSE) {
if ($display == TRUE) {
drupal_set_message(t($statusmessage), 'warning', FALSE);
}
watchdog('farmosnws', t($statusmessage), array(), WATCHDOG_INFO, NULL);
}
/**
* Get the weather data from the NWS
*
* @TODO add converter for schema to actual path
*/
function farmosnws_get_xml() {
$weatherfeedsdir = variable_get('farmosnws_weather_feeds_dir');
$locations = variable_get('farmosnws_locations', '');
$location_array = explode(",", $locations);
foreach ($location_array as $loc) {
// remove carriage returns and new lines
$loc = str_replace(" ", "", str_replace("\r", "", str_replace("\n", "", $loc)));
// build URL to connect to NWS
$weather_feed_name = $weatherfeedsdir . '/' . uniqid($loc, FALSE) . '.xml';
$url = "http://w1.weather.gov/xml/current_obs/" . $loc . ".xml";
watchdog('farmosnws', $url, array(), WATCHDOG_DEBUG, NULL);
farmosnws_display_status("Getting weather data for " . $loc, FALSE);
// pull the data
$response = drupal_http_request($url, array());
// if error occurs when performing the request
if (isset($response->error)) {
farmosnws_display_error($response->error, TRUE);
}
else {
// if no errors occur when performing the request
farmosnws_display_status("Response code: " . $response->code, FALSE);
// if the directory doesnt exist, then create it with 755 permissions
$direxist = farmosnws_create_feed_dir($weatherfeedsdir);
if ($direxist == TRUE) {
// save the contents retrieved
file_put_contents($weather_feed_name, $response->data);
farmosnws_display_status("Weather data saved to " . $weather_feed_name, FALSE);
farmosnws_convert_xml_2_csv($weather_feed_name);
// update the last feed pull time
variable_set("farmosnws_cron_last", REQUEST_TIME);
}
else {
farmosnws_display_error("Feed could not be downloaded because the directory does not exist. Please verify that Drupal has write access and try again.", TRUE);
}
} // end else
} // end foreach
} // end function
/**
* Check the cron frequency. If not set to 1 hour, then warn of the impact.
*/
function farmosnws_check_cron_time() {
$crontime = variable_get('cron_safe_threshold', 0);
if ($crontime != "3600") {
farmosnws_display_warning("Cron is not set to 1 hour. It is recommended that cron runs hourly to load new NWS data feeds as they are published.", TRUE);
}
}
/**
* Check that the units of measurement have been set in the FarmOS configuration.
* If the value has not been set then display a warning.
*/
function farmosnws_check_farmos_measurements() {
$units = variable_get('farm_quantity_unit_system', 0);
if ($units == "0") {
farmosnws_display_warning("Units of measurement is not set. Set this value in the " . l("Farm OS configuration.", "admin/config/farm/quantity"), TRUE);
}
}
/**
* Convert the xml file to csv file.
*
* @TODO Default to metric units if value is not set.
*
* @param string $feedfilename
* string File name that will be split into smaller feeds
*/
function farmosnws_convert_xml_2_csv($feedfilename) {
// read the files in the unprocessed directory
$csvfilename = $feedfilename . '.csv';
$notes = "";
try {
$csvfile = fopen($csvfilename, "w");
// throw exception if file cannot be opened
if ($csvfile === FALSE) {
throw new Exception("Could not open CSV file for writing");
}
// write header
fputcsv($csvfile, array("Done", "Date", "Name", "Notes", "Value", "Unit"));
// load the xml file
$xml = simplexml_load_file($feedfilename);
// load the units configuration
$measure_units = variable_get('farm_quantity_unit_system', 'metric');
// log the metric units
if ($measure_units == 'metric') {
if (variable_get('farmosnws_log_temperature', 1) == 1) {
// temperature in C
fputcsv($csvfile, array(1, $xml->observation_time_rfc822, $xml->location . ' Temperature', $notes, $xml->temp_c, "Celsius"));
}
if (variable_get('farmosnws_log_pressure', 1) == 1) {
// log the barametric pressure
fputcsv($csvfile, array(1, $xml->observation_time_rfc822, $xml->location . ' Barometric Pressure', $notes, $xml->pressure_mb, "Millibars"));
}
if (variable_get('farmosnws_log_windspeed', 1) == 1) {
// log wind speed in kph
$kph_speed = $xml->wind_mph * 1.60934;
fputcsv($csvfile, array(1, $xml->observation_time_rfc822, $xml->location . ' Wind Speed', $notes, $kph_speed, "KPH"));
}
if (variable_get('farmosnws_log_visibility', 1) == 1) {
// log the visibility in KM
$kms = $xml->visibility_mi * 1.60934;
fputcsv($csvfile, array(1, $xml->observation_time_rfc822, $xml->location . ' Visibility', $notes, $kms, "Kilometers"));
}
} // end if metric units
// log the US, standard units
if ($measure_units == 'us') {
if (variable_get('farmosnws_log_temperature', 1) == 1) {
// temperature in F
fputcsv($csvfile, array(1, $xml->observation_time_rfc822, $xml->location . ' Temperature', $notes, $xml->temp_f, "Fahrenheit"));
}
if (variable_get('farmosnws_log_pressure', 1) == 1) {
// log the barametric pressure
fputcsv($csvfile, array(1, $xml->observation_time_rfc822, $xml->location . ' Barometric Pressure', $notes, $xml->pressure_in, "Inches"));
}
if (variable_get('farmosnws_log_windspeed', 1) == 1) {
// log the wind speed
fputcsv($csvfile, array("1", $xml->observation_time_rfc822, $xml->location . ' Wind Speed', $notes, $xml->wind_mph, "MPH"));
}
if (variable_get('farmosnws_log_visibility', 1) == 1) {
// log the visibility
fputcsv($csvfile, array("1", $xml->observation_time_rfc822, $xml->location . ' Visibility', $notes, $xml->visibility_mi, "Miles"));
}
} // end if US units
if (variable_get('farmosnws_log_humidity', 1) == 1) {
// log the relative humidity
fputcsv($csvfile, array("1", $xml->observation_time_rfc822, $xml->location . ' Humidity', $notes, $xml->relative_humidity, "Percent"));
}
if (variable_get('farmosnws_log_winddirection', 1) == 1) {
// log the wind direction
fputcsv($csvfile, array("1", $xml->observation_time_rfc822, $xml->location . ' Wind Direction', $xml->wind_dir, $xml->wind_degrees, "Degrees"));
}
if (variable_get('farmosnws_log_weather', 1) == 1) {
// log the weather string
fputcsv($csvfile, array("1", $xml->observation_time_rfc822, $xml->location . ' Weather', $xml->weather, "", ""));
}
// close the file
fclose($csvfile);
// remove feed file
if (variable_get('farmosnws_delete_xml', "no") == "yes") {
$removefeed = unlink($feedfilename);
if ($removefeed == FALSE) {
throw new Exception("Unable to remove XML feed file " . $feedfilename);
}
}
}
catch(Exception $e) {
// handle the exception
farmosnws_display_error($e->getMessage(), TRUE);
}
}