· 9 years ago · Nov 03, 2016, 01:16 PM
1<?php
2
3
4include_once('SabreezApi_LifeCycle.php');
5
6class SabreezApi_Plugin extends SabreezApi_LifeCycle {
7
8 /**
9 * See: http://plugin.michael-simpson.com/?page_id=31
10 * @return array of option meta data.
11 */
12 public function getOptionMetaData() {
13 // http://plugin.michael-simpson.com/?page_id=31
14 return array(
15 //'_version' => array('Installed Version'), // Leave this one commented-out. Uncomment to test upgrades.
16 'ApiKey_Input' => array(__('API Key', 'my-awesome-plugin')),
17 'ErrorEmail' => array(__('Error email', 'sabreez-api-plugin-email')),
18 );
19 }
20
21// protected function getOptionValueI18nString($optionValue) {
22// $i18nValue = parent::getOptionValueI18nString($optionValue);
23// return $i18nValue;
24// }
25
26 protected function initOptions() {
27 $options = $this->getOptionMetaData();
28 if (!empty($options)) {
29 foreach ($options as $key => $arr) {
30 if (is_array($arr) && count($arr > 1)) {
31 $this->addOption($key, $arr[1]);
32 }
33 }
34 }
35 }
36
37 public function getPluginDisplayName() {
38 return 'Sabreez API';
39 }
40
41 protected function getMainPluginFileName() {
42 return 'sabreez-api.php';
43 }
44
45 /**
46 * See: http://plugin.michael-simpson.com/?page_id=101
47 * Called by install() to create any database tables if needed.
48 * Best Practice:
49 * (1) Prefix all table names with $wpdb->prefix
50 * (2) make table names lower case only
51 * @return void
52 */
53 protected function installDatabaseTables() {
54 // global $wpdb;
55 // $tableName = $this->prefixTableName('mytable');
56 // $wpdb->query("CREATE TABLE IF NOT EXISTS `$tableName` (
57 // `id` INTEGER NOT NULL");
58 }
59
60 /**
61 * See: http://plugin.michael-simpson.com/?page_id=101
62 * Drop plugin-created tables on uninstall.
63 * @return void
64 */
65 protected function unInstallDatabaseTables() {
66 // global $wpdb;
67 // $tableName = $this->prefixTableName('mytable');
68 // $wpdb->query("DROP TABLE IF EXISTS `$tableName`");
69 }
70
71
72 /**
73 * Perform actions when upgrading from version X to version Y
74 * See: http://plugin.michael-simpson.com/?page_id=35
75 * @return void
76 */
77 public function upgrade() {
78 }
79
80 public function file_get_contents_curl($url) {
81 $ch = curl_init();
82
83 curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
84 curl_setopt($ch, CURLOPT_HEADER, 0);
85 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Token b59c3e2d7715504a41d0784e0645812f64ffd80f'));
86 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
87 curl_setopt($ch, CURLOPT_URL, $url);
88 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
89
90 $data = curl_exec($ch);
91 curl_close($ch);
92
93 return $data;
94 }
95
96 public function addDataToDB($time, $wind, $solar, $solarpv, $thermal){
97 global $wpdb;
98
99 $table_name = $this->prefixTableName("data");
100
101 $generatedID = strtotime($time);
102 $generateWindNumber = number_format($wind / $thermal * 100, 0);
103
104 $wpdb->insert(
105 $table_name,
106 array(
107 'id' => $generatedID,
108 'time' => $time,
109 'wind' => $wind,
110 'solar' => $solar,
111 'solarpv' => $solarpv,
112 'thermal' => $thermal,
113 'wind_number' => $generateWindNumber,
114 ),
115 array(
116 '%d',
117 '%s',
118 '%d',
119 '%d',
120 '%d',
121 '%d',
122 '%d',
123 )
124 );
125
126 if($wpdb->insert != false){
127 return true;
128 }
129 }
130
131 public function getDataFromApi(){
132 $url = "https://api.watttime.org/api/v1/datapoints/?ba=CAISO&market=RTHR&page_size=24&format=json";
133
134 $json = $this->file_get_contents_curl($url);
135 $obj = json_decode($json);
136
137 foreach($obj->results as $r){
138
139 $time = $r->timestamp;
140
141 foreach($r->genmix as $g) {
142 if($g->fuel == "wind"){
143 $wind = $g->gen_MW;
144 }
145 if($g->fuel == "solarth"){
146 $solar = $g->gen_MW;
147 }
148 if($g->fuel == "solarpv"){
149 $solarpv = $g->gen_MW;
150 }
151 if($g->fuel == "thermal"){
152 $thermal = $g->gen_MW;
153 }
154 }
155
156 $this->addDataToDB($time, $wind, $solar, $solarpv, $thermal);
157 }
158 }
159
160 public function getDataFromDB(){
161 global $wpdb;
162 $table_name = $this->prefixTableName("data");
163 $data = $wpdb->get_results( "SELECT * FROM $table_name ORDER BY `time` DESC LIMIT 40");
164
165 return $data;
166 }
167
168 public function theLatestWindNumber(){
169 global $wpdb;
170
171 $table_name = $this->prefixTableName("latest_wn");
172
173 $data = $wpdb->get_row( "SELECT * FROM $table_name ORDER BY id DESC");
174
175 if($data->time < time()-60*10 ){
176 $this->getLatestWindNumberAPI();
177 }
178
179 $data = $wpdb->get_row( "SELECT * FROM $table_name ORDER BY id DESC");
180
181 $wind = $data->wind;
182 $other_fuel = $data->other_fuel;
183
184 $avg_nuclear = $this->getYesterdaysNuclear();
185 $avg_hydro = $this->getYesterdaysHydro();
186
187 $round = 0.4;
188
189 $estWindNumber = $wind/($other_fuel-$avg_nuclear-$avg_hydro)/$round*100;
190 $estWindNumber = round($estWindNumber, 0);
191
192 echo "<br><br>";
193 echo "<br>Wind: ", $wind;
194 echo "<br>Other fuel: ", $other_fuel;
195 echo "<br>Average Nuclear Yesterday: ", $avg_nuclear;
196 echo "<br>Average Hydro Yesterday: ", $avg_hydro;
197
198 echo "<br>Round number: ", $round;
199 echo "<br><br>";
200 echo "<br>Calculation: " . $wind . "/(" . $other_fuel . "-" . $avg_nuclear . "-" . $avg_hydro . ")/" . $round . "*100";
201 echo "<br><b>Estimated Wind Number:</b> ", $estWindNumber;
202 echo "<br><br>";
203 }
204 public function getLatestWindNumber(){
205 global $wpdb;
206
207 $table_name = $this->prefixTableName("latest_wn");
208
209 $data = $wpdb->
210 get_row( "SELECT * FROM $table_name ORDER BY id DESC");
211
212 if($data->time < time()-60*10 ){
213 $this->getLatestWindNumberAPI();
214 }
215
216 $data = $wpdb->
217 get_row( "SELECT * FROM $table_name ORDER BY id DESC");
218
219 $wind = $data->wind;
220 $other_fuel = $data->other_fuel;
221
222 $avg_nuclear = $this->getYesterdaysNuclear();
223 $avg_hydro = $this->getYesterdaysHydro();
224
225 $round = 0.4;
226
227 $estWindNumber = $wind/($other_fuel-$avg_nuclear-$avg_hydro)/$round*100;
228 $estWindNumber = round($estWindNumber, 0);
229 echo $estWindNumber;
230
231 }
232
233 public function getLatestWindNumberAPI(){
234
235 global $wpdb;
236
237 $url = "https://api.watttime.org/api/v1/datapoints/?ba=CAISO&market=RT5M&page_size=1&page=1&format=json";
238
239 $json = $this->file_get_contents_curl($url);
240
241 $obj = json_decode($json);
242
243 foreach($obj->results as $r){
244
245
246 foreach($r->genmix as $g) {
247 if($g->fuel == "wind"){
248 $wind = $g->gen_MW;
249 }
250 if($g->fuel == "other"){
251 $other_fuel = $g->gen_MW;
252 }
253 }
254 }
255
256 $table_name = $this->prefixTableName("latest_wn");
257
258 $wpdb->query("TRUNCATE TABLE $table_name");
259
260 $wpdb->insert(
261 $table_name,
262 array(
263 'time' => time(),
264 'wind' => $wind,
265 'other_fuel' => $other_fuel,
266 ),
267 array(
268 '%d',
269 '%d',
270 '%d',
271 )
272 );
273
274
275
276 }
277
278 public function getYesterdaysNuclear(){
279 $today = date("Y-m-d", time());
280 $yesterday = date("Y-m-d", time() - 60 * 60 * 24);
281 $url = "https://api.watttime.org/api/v1/datapoints/?ba=CAISO&market=RTHR&start_at=" . $yesterday . "&end_at=" . $today . "&format=json";
282
283 $json = $this->file_get_contents_curl($url);
284 $obj = json_decode($json);
285
286 $nuclear = 0;
287
288 foreach($obj->results as $r){
289
290 foreach($r->genmix as $g) {
291 if($g->fuel == "nuclear"){
292 $nuclear = $nuclear+$g->gen_MW;
293 }
294 }
295 }
296
297 $nuclear = $nuclear/25;
298 return $nuclear;
299
300 }
301 public function getYesterdaysHydro(){
302 $today = date("Y-m-d", time());
303 $yesterday = date("Y-m-d", time() - 60 * 60 * 24);
304 $url = "https://api.watttime.org/api/v1/datapoints/?ba=CAISO&market=RTHR&start_at=" . $yesterday . "&end_at=" . $today . "&format=json";
305
306 $json = $this->file_get_contents_curl($url);
307 $obj = json_decode($json);
308
309 $hydro = 0;
310
311 foreach($obj->results as $r){
312
313 foreach($r->genmix as $g) {
314 if($g->fuel == "hydro"){
315 $hydro = $hydro+$g->gen_MW;
316 }
317 }
318 }
319
320 $hydro = $hydro/25;
321
322 return $hydro;
323
324 }
325 public function getYesterdaysPeak(){
326 global $wpdb;
327 $table_name = $this->prefixTableName("data");
328
329 $date = new DateTime();
330 $date->sub(new DateInterval('P1D'));
331 $yesterday =$date->format('Y-m-d');
332
333 $data = $wpdb->get_row( "SELECT * FROM $table_name
334 WHERE time < SUBDATE(CURDATE(),0)
335 AND time > SUBDATE(CURDATE(),1)
336 ORDER BY wind_number DESC");
337
338 if(isset($data)){
339 echo $data->wind_number;
340 } else {
341 echo "No data";
342 }
343
344 }
345
346 public function displayData(){ ?>
347 <table style="width:100%">
348 <tr>
349 <th align="left">Time</th>
350 <th align="left">Wind MW</th>
351
352 <th align="left">Thermal MW</th>
353 <th align="left">Solar total MW</th>
354 <th align="left">WindNumber</th>
355 </tr>
356 <?php
357 $data = $this->getDataFromDB();
358 foreach($data as $d){?>
359
360 <tr>
361 <td><?php echo $d->time ?></td>
362 <td><?php echo $d->wind ?></td>
363
364 <td><?php echo $d->thermal ?></td>
365 <td><?php echo $d->solar + $d->solarpv ?></td>
366 <td> <?php echo number_format($d->wind / $d->thermal * 100, 0); ?></td>
367 </tr>
368
369 <?php } ?>
370 </table>
371
372
373 <?php
374 }
375
376 public function scrapeData(){
377
378 if(!isset($page)){
379 $page = 1;
380 }
381 echo "Scraped page: ", $page;
382
383 $url = "https://api.watttime.org/api/v1/datapoints/?ba=CAISO&market=RTHR&page=" . $page . "&page_size=500&format=json";
384
385 $json = $this->file_get_contents_curl($url);
386 $obj = json_decode($json);
387
388 foreach($obj->results as $r){
389
390 $time = $r->timestamp;
391
392 foreach($r->genmix as $g) {
393 if($g->fuel == "wind"){
394 $wind = $g->gen_MW;
395 }
396 if($g->fuel == "solarth"){
397 $solar = $g->gen_MW;
398 }
399 if($g->fuel == "solarpv"){
400 $solarpv = $g->gen_MW;
401 }
402 if($g->fuel == "thermal"){
403 $thermal = $g->gen_MW;
404 }
405 }
406
407 $this->addDataToDB($time, $wind, $solar, $solarpv, $thermal);
408 }
409 }
410
411
412
413 public function addActionsAndFilters() {
414
415 // Add options administration page
416 // http://plugin.michael-simpson.com/?page_id=47
417 add_action('admin_menu', array(&$this, 'addSettingsSubMenuPage'));
418
419
420 // Example adding a script & style just for the options administration page
421 // http://plugin.michael-simpson.com/?page_id=47
422 // if (strpos($_SERVER['REQUEST_URI'], $this->getSettingsSlug()) !== false) {
423 // wp_enqueue_script('my-script', plugins_url('/js/my-script.js', __FILE__));
424 // wp_enqueue_style('my-style', plugins_url('/css/my-style.css', __FILE__));
425 // }
426
427
428 // Add Actions & Filters
429 // http://plugin.michael-simpson.com/?page_id=37
430
431
432 // Adding scripts & styles to all pages
433 // Examples:
434 // wp_enqueue_script('jquery');
435 // wp_enqueue_style('my-style', plugins_url('/css/my-style.css', __FILE__));
436 // wp_enqueue_script('my-script', plugins_url('/js/my-script.js', __FILE__));
437
438
439 // Register short codes
440 // http://plugin.michael-simpson.com/?page_id=39
441 add_shortcode('api-display-data-table', array($this, 'displayData'));
442 add_shortcode('api-display-latest-windnumber', array($this, 'getLatestWindNumber'));
443 add_shortcode('api-display-yesterdays-peak', array($this, 'getYesterdaysPeak'));
444 add_shortcode('api-scrape-data', array($this, 'scrapeData'));
445
446
447
448 // Register AJAX hooks
449 // http://plugin.michael-simpson.com/?page_id=41
450
451 // Register REST fields
452
453 add_action( 'rest_api_init', function () {
454 register_rest_route( 'wp/v2', '/sabreez/windnumber/current', array(
455 'methods' => 'GET',
456 'callback' => 'wind_current',
457 ) );
458 } );
459
460 function wind_current( WP_REST_Request $request ) {
461 header('Content-Type: application/json');
462 return do_shortcode('[api-display-latest-windnumber]');
463 }
464
465
466 add_action( 'rest_api_init', function () {
467 register_rest_route( 'wp/v2', '/sabreez/windnumber/yesterday', array(
468 'methods' => 'GET',
469 'callback' => 'wind_yesterday',
470 ) );
471 } );
472
473 function wind_yesterday( WP_REST_Request $request ) {
474 header('Content-Type: application/json');
475 return do_shortcode('[api-display-yesterdays-peak]');
476 }
477
478
479 add_action( 'rest_api_init', function () {
480 register_rest_route( 'wp/v2', '/sabreez/windnumber/forecast', array(
481 'methods' => 'GET',
482 'callback' => 'wind_forecast',
483 ) );
484 } );
485
486 function wind_forecast( WP_REST_Request $request ) {
487 header('Content-Type: application/json');
488 return 30;
489 }
490 }
491
492
493
494
495}