-
Notifications
You must be signed in to change notification settings - Fork 517
/
Copy pathPHPFina.php
1438 lines (1170 loc) · 51.6 KB
/
PHPFina.php
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This timeseries engine implements:
// Fixed Interval No Averaging
// engine_methods interface in shared_helper.php
include_once dirname(__FILE__) . '/shared_helper.php';
class PHPFina implements engine_methods
{
private $dir = "/var/lib/phpfina/";
private $log;
private $writebuffer = array();
private $lastvalue_cache = array();
private $maxpadding = 3153600; // 1 year @ 10s
/**
* Constructor.
*
* @api
*/
public function __construct($settings)
{
if (isset($settings['datadir'])) $this->dir = $settings['datadir'];
$this->log = new EmonLogger(__FILE__);
}
// #### \/ Below are required methods
/**
* Create feed
*
* @param integer $feedid The id of the feed to be created
* @param array $options for the engine
*/
public function create($feedid,$options)
{
$feedid = (int)$feedid;
$interval = (int) $options['interval'];
if ($interval<5) $interval = 5;
// Check to ensure we dont overwrite an existing feed
$feedname = "$feedid.meta";
if (!file_exists($this->dir.$feedname)) {
// Set initial feed meta data
$meta = new stdClass();
$meta->interval = $interval;
$meta->start_time = 0;
$meta->npoints = 0;
// Save meta data
$msg=$this->create_meta($feedid,$meta);
if ($msg !== true) {
return $msg;
}
$fh = @fopen($this->dir.$feedid.".dat", 'c+');
if (!$fh) {
$error = error_get_last();
$msg = "could not create meta data file ".$error['message'];
$this->log->error("create() ".$msg);
return $msg;
}
fclose($fh);
$this->log->info("create() feedid=$feedid");
}
if (file_exists($this->dir.$feedname)) {
return true;
} else {
$msg = "create failed, could not find meta data file '".$this->dir.$feedname."'";
$this->log->error("create() ".$msg);
return $msg;
}
}
/**
* Delete feed
*
* @param integer $feedid The id of the feed to be created
*/
public function delete($feedid)
{
$feedid = (int)$feedid;
if (!$meta = $this->get_meta($feedid)) return false;
unlink($this->dir.$feedid.".meta");
unlink($this->dir.$feedid.".dat");
}
/**
* Gets engine metadata
*
* @param integer $feedid The id of the feed to be created
*/
public function get_meta($feedid)
{
$feedid = (int) $feedid;
$feedname = "$feedid.meta";
if (!file_exists($this->dir.$feedname)) {
$this->log->warn("get_meta() meta file does not exist '".$this->dir.$feedname."'");
return false;
}
// Open and read meta data file
// The start_time and interval are saved as two consecutive unsigned integers
$meta = new stdClass();
$metafile = fopen($this->dir.$feedname, 'rb');
fseek($metafile,8);
$tmp = unpack("I",fread($metafile,4));
$meta->interval = $tmp[1];
$tmp = unpack("I",fread($metafile,4));
$meta->start_time = $tmp[1];
fclose($metafile);
$meta->npoints = $this->get_npoints($feedid);
if ($meta->start_time>0 && $meta->npoints==0) {
$this->log->warn("PHPFina:get_meta start_time already defined but npoints is 0");
return false;
}
return $meta;
}
/**
* Returns engine occupied size in bytes
*
* @param integer $feedid The id of the feed to be created
*/
public function get_feed_size($feedid)
{
if (!$meta = $this->get_meta($feedid)) return false;
return (16 + filesize($this->dir.$feedid.".dat"));
}
/**
* Adds a data point to the feed
*
* @param integer $feedid The id of the feed to add to
* @param integer $time The unix timestamp of the data point, in seconds
* @param float $value The value of the data point
* @param array $arg optional padding mode argument
*/
public function post($id,$timestamp,$value,$padding_mode=null)
{
$this->log->info("post() id=$id timestamp=$timestamp value=$value padding=$padding_mode");
$id = (int) $id;
$timestamp = (int) $timestamp;
$value = (float) $value;
$now = time();
$start = $now-(3600*24*365*5); // 5 years in past
$end = $now+(3600*48); // 48 hours in future
if ($timestamp<$start || $timestamp>$end) {
$this->log->warn("post() timestamp out of range");
return false;
}
// If meta data file does not exist then exit
if (!$meta = $this->get_meta($id)) {
$this->log->warn("post() failed to fetch meta id=$id");
return false;
}
$meta->npoints = $this->get_npoints($id);
// Calculate interval that this datapoint belongs too
$timestamp = floor($timestamp / $meta->interval) * $meta->interval;
// If this is a new feed (npoints == 0) then set the start time to the current datapoint
if ($meta->npoints == 0 && $meta->start_time==0) {
$meta->start_time = $timestamp;
$this->create_meta($id,$meta);
}
if ($timestamp < $meta->start_time) {
$this->log->warn("post() timestamp older than feed start time id=$id");
return false; // in the past
}
// Calculate position in base data file of datapoint
$pos = floor(($timestamp - $meta->start_time) / $meta->interval);
$last_pos = $meta->npoints - 1;
$fh = fopen($this->dir.$id.".dat", 'c+');
if (!$fh) {
$this->log->warn("post() could not open data file id=$id");
return false;
}
// Write padding
$padding = ($pos - $last_pos)-1;
if ($padding>$this->maxpadding) {
$this->log->warn("post() padding max block size exeeded id=$id, $padding dp");
return false;
}
if ($padding>0) {
$padding_value = NAN;
if ($last_pos>=0 && $padding_mode!=null) {
fseek($fh,$last_pos*4);
$val = unpack("f",fread($fh,4));
$last_val = (float) $val[1];
$padding_value = $last_val;
$div = ($value - $last_val) / ($padding+1);
}
$buffer = "";
for ($i=0; $i<$padding; $i++) {
if ($padding_mode=="join") $padding_value += $div;
$buffer .= pack("f",$padding_value);
}
fseek($fh,4*$meta->npoints);
fwrite($fh,$buffer);
}
// Write new datapoint
fseek($fh,4*$pos);
if (!is_nan($value)) fwrite($fh,pack("f",$value)); else fwrite($fh,pack("f",NAN));
// Close file
fclose($fh);
return $value;
}
/**
* Updates a data point in the feed
*
* @param integer $feedid The id of the feed to add to
* @param integer $time The unix timestamp of the data point, in seconds
* @param float $value The value of the data point
*/
public function update($feedid,$timestamp,$value)
{
if (isset($this->writebuffer[$feedid]) && strlen($this->writebuffer[$feedid]) > 0) {
$this->post_bulk_save();// if data on buffer, flush buffer now, then update it
$this->log->info("update() $feedid with buffer");
}
return $this->post($feedid,$timestamp,$value); //post can also update
}
/**
* scale a portion of a feed
* added by Alexandre CUER - january 2019
*
* @param integer $feedid The id of the feed
* @param integer $start unix time stamp in ms of the start of the data range
* @param integer $end unix time stamp in ms of the end of the data rage
* @param float $scale : numeric value for the scaling
*/
public function scalerange($id,$start,$end,$scale){
//echo("test on $scale not started");
//case1: NAN
if(preg_match("/^NAN$/i",$scale)){
$this->log->warn("scale_range() : going to erase data range with NAN");
$scale = NAN;
//case2: scaling value - possible to use a fraction
} else if(preg_match("/^(1\/|-1\/|-)?([0-9]+((\.|,)[0-9]+)?)$/",$scale,$a)){
$this->log->warn("scale_range() : being given a float scale parameter");
$scale = (float) $a[2];
if ($a[1]=="1/")$scale = 1/$scale;
else if ($a[1]=="-1/") $scale = -1/$scale;
else if ($a[1]=="-") $scale = -$scale;
//print_r($a);
//case3: absolute value
} else if(preg_match("/^abs\(x\)$/i",$scale)){
$this->log->warn("scale_range() : conversion to absolute values on the data range");
$scale="abs(x)";
} else return false;
//echo("test finished>");
//echo("<br>$scale");
//echo("<br>$start and $end");
$id = (int) $id;
$start = intval($start/1000);
$end = intval($end/1000);
//echo("<br>$start and $end");
if(!$meta=$this->get_meta($id)){
$this->log->warn("scale_range() failed to fetch meta id = $id");
return false;
}
$this->log->warn("scale_range() successfully fetched meta id = $id");
//integrity checks
$start=floor($start/$meta->interval)*$meta->interval;
$end=floor($end/$meta->interval)*$meta->interval;
//debug
//echo("<br>$start and $end");
if($start>$end) {
$this->log->warn("scale_range() : start should not be greater than end");
return false;
}
if($start<$meta->start_time) $start=$meta->start_time;
$end_time=$this->lastvalue($id)['time'];
if($end>$end_time) $end=$end_time;
//calculates address in dat file and number of values to write
$pos_start=4*floor(($start-$meta->start_time)/$meta->interval);
$pos_end=4*floor(($end-$meta->start_time)/$meta->interval);
$nbwrites=($pos_end-$pos_start)/4;
//echo("<br>$nbwrites");
//open the dat file
$fh = fopen ($this->dir.$id.".dat","c+");
if (!$fh){
$this->log->warn("scale_range() : unable to open data file with id=$id");
return false;
}
$this->log->warn("scale_range() : going to write $nbwrites values from address $pos_start to $pos_end");
//fetch the values to process
fseek($fh,$pos_start);
$values=unpack("f$nbwrites",fread($fh,4*$nbwrites));
//print_r($values);
//create a buffer with the processed values
$buffer="";
for($i=1;$i<=$nbwrites;$i++) {
if($scale==NAN) $val=NAN;
else if($scale=="abs(x)") $val=abs($values[$i]);
else $val=$values[$i]*$scale;
$buffer.=pack("f",$val);
}
//write the processed buffer to the dat file
fseek($fh,$pos_start);
if(!$written_bytes = fwrite($fh,$buffer)){
$this->log->warn("scale_range() : unable to write to the file with id=$id");
fclose($fh);
return false;
}
$this->log->warn("scale_range() : wrote $written_bytes bytes");
fclose($fh);
return $written_bytes;
}
/**
* Get array with last time and value from a feed
*
* @param integer $feedid The id of the feed
*/
public function lastvalue($feedid)
{
$feedid = (int)$feedid;
$this->log->info("lastvalue() $feedid");
// If meta data file does not exist exit
if (!$meta = $this->get_meta($feedid)) return false;
$meta->npoints = $this->get_npoints($feedid);
if ($meta->npoints>0) {
$fh = fopen($this->dir.$feedid.".dat", 'rb');
$size = filesize($this->dir.$feedid.".dat");
fseek($fh,$size-4);
$d = fread($fh,4);
fclose($fh);
$value = null;
$val = unpack("f",$d);
$time = $meta->start_time + ($meta->interval * $meta->npoints);
if (!is_nan($val[1])) {
$value = (float) $val[1];
}
return array('time'=>(int)$time, 'value'=>$value);
}
return false;
}
/**
* Return the data for the given timerange - cf shared_helper.php
*
*/
public function get_data($name,$start,$end,$interval,$skipmissing,$limitinterval)
{
$skipmissing = (int) $skipmissing;
$limitinterval = (int) $limitinterval;
$start = intval($start/1000);
$end = intval($end/1000);
$interval= (int) $interval;
// Minimum interval
if ($interval<1) $interval = 1;
// End must be larger than start
if ($end<=$start) return array('success'=>false, 'message'=>"request end time before start time");
// Maximum request size
$req_dp = round(($end-$start) / $interval);
if ($req_dp>8928) return array('success'=>false, 'message'=>"Request datapoint limit reached (8928), increase request interval or time range, requested datapoints = $req_dp");
// If meta data file does not exist exit
if (!$meta = $this->get_meta($name)) return array('success'=>false, 'message'=>"Error reading meta data feedid=$name");
$meta->npoints = $this->get_npoints($name);
if ($limitinterval && $interval<$meta->interval) $interval = $meta->interval;
$this->log->info("get_data() feed=$name st=$start end=$end int=$interval sk=$skipmissing lm=$limitinterval pts=$meta->npoints st=$meta->start_time");
$data = array();
$time = 0; $i = 0;
$numdp = 0;
// The datapoints are selected within a loop that runs until we reach a
// datapoint that is beyond the end of our query range
$fh = fopen($this->dir.$name.".dat", 'rb');
while($time<=$end)
{
$time = $start + ($interval * $i);
$pos = round(($time - $meta->start_time) / $meta->interval);
$value = null;
if ($pos>=0 && $pos < $meta->npoints)
{
// read from the file
fseek($fh,$pos*4);
$val = unpack("f",fread($fh,4));
// add to the data array if its not a nan value
if (!is_nan($val[1])) {
$value = (float) $val[1];
} else {
$value = null;
}
//$this->log->info("get_data() ". ($pos*4) ." time=$time value=$value");
}
if ($value!==null || $skipmissing===0) {
// see https://openenergymonitor.org/emon/node/11260
$data[] = array($time*1000,$value);
}
$i++;
}
return $data;
}
public function get_data_DMY($id,$start,$end,$mode,$timezone)
{
if ($mode!="daily" && $mode!="weekly" && $mode!="monthly") return false;
$start = intval($start/1000);
$end = intval($end/1000);
// If meta data file does not exist exit
if (!$meta = $this->get_meta($id)) return array('success'=>false, 'message'=>"Error reading meta data feedid=$name");
$meta->npoints = $this->get_npoints($id);
$data = array();
$fh = fopen($this->dir.$id.".dat", 'rb');
$date = new DateTime();
if ($timezone===0) $timezone = "UTC";
$date->setTimezone(new DateTimeZone($timezone));
$date->setTimestamp($start);
$date->modify("midnight");
$increment="+1 day";
if ($mode=="weekly") { $date->modify("this monday"); $increment="+1 week"; }
if ($mode=="monthly") { $date->modify("first day of this month"); $increment="+1 month"; }
$n = 0;
while($n<10000) // max iterations
{
$time = $date->getTimestamp();
if ($time>$end) break;
$pos = round(($time - $meta->start_time) / $meta->interval);
$value = null;
if ($pos>=0 && $pos < $meta->npoints)
{
// read from the file
fseek($fh,$pos*4);
$val = unpack("f",fread($fh,4));
// add to the data array if its not a nan value
if (!is_nan($val[1])) {
$value = $val[1];
} else {
$value = null;
}
}
if ($time>=$start) {
$data[] = array($time*1000,$value);
}
$date->modify($increment);
$n++;
}
fclose($fh);
return $data;
}
public function get_data_DMY_time_of_day($id,$start,$end,$mode,$timezone,$split)
{
if ($mode!="daily" && $mode!="weekly" && $mode!="monthly") return false;
$start = intval($start/1000);
$end = intval($end/1000);
$split = json_decode($split);
if (gettype($split)!="array") return false;
if (count($split)>48) return false;
// If meta data file does not exist exit
if (!$meta = $this->get_meta($id)) return array('success'=>false, 'message'=>"Error reading meta data feedid=$name");
$meta->npoints = $this->get_npoints($id);
$data = array();
/* Open file */
$fh = fopen($this->dir.$id.".dat", 'rb');
$date = new DateTime();
if ($timezone===0) $timezone = "UTC";
$date->setTimezone(new DateTimeZone($timezone));
$date->setTimestamp($start);
$date->modify("midnight");
if ($mode=="weekly") $date->modify("this monday");
if ($mode=="monthly") $date->modify("first day of this month");
$n = 0;
while($n<10000) // max iterations allows for approx 7 months with 1 day granularity
{
$time = $date->getTimestamp();
if ($time>$end) break;
$value = null;
$split_values = array();
foreach ($split as $splitpoint)
{
//Fix issue with rounding to nearest 30 minutes
$split_offset = (int) (((float)$splitpoint) * 3600.0);
$pos = round((($time+$split_offset) - $meta->start_time) / $meta->interval);
$value = null;
if ($pos>=0 && $pos < $meta->npoints)
{
// read from the file
fseek($fh,$pos*4);
$val = unpack("f",fread($fh,4));
// add to the data array if its not a nan value
if (!is_nan($val[1])) {
$value = $val[1];
} else {
$value = null;
}
}
$split_values[] = $value;
}
if ($time>=$start && $time<$end) {
$data[] = array($time*1000,$split_values);
}
if ($mode=="daily") $date->modify("+1 day");
if ($mode=="weekly") $date->modify("+1 week");
if ($mode=="monthly") $date->modify("+1 month");
$n++;
}
fclose($fh);
return $data;
}
public function export($id,$start)
{
$id = (int) $id;
$start = (int) $start;
$feedname = $id.".dat";
// If meta data file does not exist exit
if (!$meta = $this->get_meta($id)) {
$this->log->warn("PHPFina:post failed to fetch meta id=$id");
return false;
}
$meta->npoints = $this->get_npoints($id);
// There is no need for the browser to cache the output
header("Cache-Control: no-cache, no-store, must-revalidate");
// Tell the browser to handle output as a csv file to be downloaded
header('Content-Description: File Transfer');
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename={$feedname}");
header("Expires: 0");
header("Pragma: no-cache");
// Write to output stream
$fh = @fopen( 'php://output', 'w' );
$primary = fopen($this->dir.$feedname, 'rb');
$primarysize = filesize($this->dir.$feedname);
$localsize = $start;
$localsize = intval($localsize / 4) * 4;
if ($localsize<0) $localsize = 0;
// Get the first point which will be updated rather than appended
if ($localsize>=4) $localsize = $localsize - 4;
fseek($primary,$localsize);
$left_to_read = $primarysize - $localsize;
if ($left_to_read>0){
do
{
if ($left_to_read>8192) $readsize = 8192; else $readsize = $left_to_read;
$left_to_read -= $readsize;
$data = fread($primary,$readsize);
fwrite($fh,$data);
}
while ($left_to_read>0);
}
fclose($primary);
fclose($fh);
exit;
}
public function csv_export($feedid,$start,$end,$outinterval,$usertimezone)
{
global $csv_decimal_places, $csv_decimal_place_separator, $csv_field_separator;
require_once "Modules/feed/engine/shared_helper.php";
$helperclass = new SharedHelper();
$feedid = (int) $feedid;
$start = (int) $start;
$end = (int) $end;
$outinterval = (int) $outinterval;
// If meta data file does not exist exit
if (!$meta = $this->get_meta($feedid)) return false;
$meta->npoints = $this->get_npoints($feedid);
if ($outinterval<$meta->interval) $outinterval = $meta->interval;
$dp = ceil(($end - $start) / $outinterval);
$end = $start + ($dp * $outinterval);
// $dpratio = $outinterval / $meta->interval;
if ($dp<1) return false;
// The number of datapoints in the query range:
$dp_in_range = ($end - $start) / $meta->interval;
// Divided by the number we need gives the number of datapoints to skip
// i.e if we want 1000 datapoints out of 100,000 then we need to get one
// datapoints every 100 datapoints.
$skipsize = round($dp_in_range / $dp);
if ($skipsize<1) $skipsize = 1;
// Calculate the starting datapoint position in the timestore file
if ($start>$meta->start_time){
$startpos = ceil(($start - $meta->start_time) / $meta->interval);
} else {
$start = ceil($meta->start_time / $outinterval) * $outinterval;
$startpos = ceil(($start - $meta->start_time) / $meta->interval);
}
$data = array();
$time = 0; $i = 0;
// There is no need for the browser to cache the output
header("Cache-Control: no-cache, no-store, must-revalidate");
// Tell the browser to handle output as a csv file to be downloaded
header('Content-Description: File Transfer');
header("Content-type: application/octet-stream");
$filename = $feedid.".csv";
header("Content-Disposition: attachment; filename={$filename}");
header("Expires: 0");
header("Pragma: no-cache");
// Write to output stream
$exportfh = @fopen( 'php://output', 'w' );
// The datapoints are selected within a loop that runs until we reach a
// datapoint that is beyond the end of our query range
$fh = fopen($this->dir.$feedid.".dat", 'rb');
while($time<=$end)
{
// $position steps forward by skipsize every loop
$pos = ($startpos + ($i * $skipsize));
// Exit the loop if the position is beyond the end of the file
if ($pos > $meta->npoints-1) break;
// read from the file
fseek($fh,$pos*4);
$val = unpack("f",fread($fh,4));
// calculate the datapoint time
$time = $meta->start_time + $pos * $meta->interval;
$timenew = $helperclass->getTimeZoneFormated($time,$usertimezone);
// add to the data array if its not a nan value
if (!is_nan($val[1])) fwrite($exportfh, $timenew.$csv_field_separator.number_format($val[1],$csv_decimal_places,$csv_decimal_place_separator,'')."\n");
$i++;
}
fclose($exportfh);
exit;
}
// #### /\ Above are required methods
// #### \/ Below are buffer write methods
// Insert data in post write buffer, parameters like post()
public function post_bulk_prepare($feedid,$timestamp,$value,$padding_mode)
{
$feedid = (int) $feedid;
$timestamp = (int) $timestamp;
$value = (float) $value;
$this->log->info("post_bulk_prepare() feedid=$feedid timestamp=$timestamp value=$value");
// Check timestamp range
$now = time();
$start = $now-(3600*24*365*5); // 5 years in past
$end = $now+(3600*48); // 48 hours in future
if ($timestamp<$start || $timestamp>$end) {
$this->log->warn("post_bulk_prepare() timestamp out of range");
return false;
}
// Check meta data file exists
if (!$meta = $this->get_meta($feedid)) {
$this->log->warn("post_bulk_prepare() failed to fetch meta feedid=$feedid");
return false;
}
$meta->npoints = $this->get_npoints($feedid);
// Calculate interval that this datapoint belongs too
$timestamp = floor($timestamp / $meta->interval) * $meta->interval;
// If this is a new feed (npoints == 0) then set the start time to the current datapoint
if ($meta->start_time==0) {
if ($meta->npoints == 0) {
$meta->start_time = $timestamp;
$this->create_meta($feedid,$meta);
$this->log->info("post_bulk_prepare() start_time=0 setting meta start_time=$timestamp");
} else {
$this->log->error("post_bulk_prepare() start_time=0, npoints>0");
return false;
}
}
if ($timestamp < $meta->start_time) {
$this->log->warn("post_bulk_prepare() timestamp=$timestamp older than feed starttime=$meta->start_time feedid=$feedid");
return false; // in the past
}
// Calculate position in base data file of datapoint
$pos = floor(($timestamp - $meta->start_time) / $meta->interval);
$last_pos = $meta->npoints - 1;
$this->log->info("post_bulk_prepare() pos=$pos last_pos=$last_pos timestampinterval=$timestamp");
if ($pos>$last_pos) {
$npadding = ($pos - $last_pos)-1;
if ($npadding>$this->maxpadding) {
$this->log->warn("post() padding max block size exeeded id=$feedid, $npadding dp");
return false;
}
if (!isset($this->writebuffer[$feedid])) {
$this->writebuffer[$feedid] = "";
}
if ($npadding>0) {
$padding_value = NAN;
if ($padding_mode!=null) {
if (!isset($this->lastvalue_cache[$feedid])) { // Not set, cache it from file data
$lastvalue = $this->lastvalue($feedid);
$this->lastvalue_cache[$feedid] = $lastvalue['value'];
}
$div = ($value - $this->lastvalue_cache[$feedid]) / ($npadding+1);
$padding_value = $this->lastvalue_cache[$feedid];
}
for ($n=0; $n<$npadding; $n++)
{
if ($padding_mode!=null) $padding_value += $div;
$this->writebuffer[$feedid] .= pack("f",$padding_value);
//$this->log->info("post_bulk_prepare() ##### paddings ". ((4*$meta->npoints) + (4*$n)) ." $n $padding_mode $padding_value");
}
}
$this->writebuffer[$feedid] .= pack("f",$value);
$this->lastvalue_cache[$feedid] = $value; // cache last value
//$this->log->info("post_bulk_prepare() ##### value saved $value");
} else {
// if data is in past, its not supported, could call update here to fix on file before continuing
// but really this should not happen for past data has process_feed_buffer uses update for that.
// so this must be data posted in less time of the feed interval and can be ignored
// This error crouds out the log's but is behaviour expected if data is coming in at a quicker interval than the feed interval
// EmonPi posts at 5s where feed engine default size is 10s which means a log entry for every datapoint with this uncommented
// $this->log->warn("post_bulk_prepare() data in past or before next interval, nothing saved. Posting too fast? slot=$meta->interval feedid=$feedid timestamp=$timestamp pos=$pos last_pos=$last_pos value=$value");
}
return $value;
}
// Saves post buffer to engine in bulk
// Writing data in larger blocks saves reduces disk write load
public function post_bulk_save()
{
$byteswritten = 0;
foreach ($this->writebuffer as $feedid=>$data) {
// Auto-correction if something happens to the datafile, it gets partitally written to
// this will correct the file size to always be an integer number of 4 bytes.
$filename = $this->dir.$feedid.".dat";
clearstatcache($filename);
if (@filesize($filename)%4 != 0) {
$npoints = floor(filesize($filename)/4.0);
$fh = fopen($filename,"c");
if (!$fh) {
$this->log->warn("post_bulk_save() could not open data file '$filename'");
return false;
}
fseek($fh,$npoints*4.0);
fwrite($fh,$data);
fclose($fh);
print "PHPFINA: FIXED DATAFILE WITH INCORRECT LENGHT '$filename'\n";
$this->log->warn("post_bulk_save() FIXED DATAFILE WITH INCORRECT LENGHT '$filename'");
}
else
{
$fh = fopen($filename,"ab");
if (!$fh) {
$this->log->warn("save() could not open data file '$filename'");
return false;
}
fwrite($fh,$data);
fclose($fh);
}
$byteswritten += strlen($data);
}
$this->writebuffer = array(); // clear buffer
return $byteswritten;
}
// #### \/ Below engine specific methods
// #### \/ Bellow are engine private methods
private function create_meta($feedid, $meta)
{
$feedname = $feedid . ".meta";
$metafile = @fopen($this->dir.$feedname, 'wb');
if (!$metafile) {
$error = error_get_last();
$msg = "could not write meta data file ".$error['message'];
$this->log->error("create_meta() ".$msg);
return $msg;
}
if (!flock($metafile, LOCK_EX)) {
$msg = "meta data file '".$this->dir.$feedname."' is locked by another process";
$this->log->error("create_meta() ".$msg);
fclose($metafile);
return $msg;
}
fwrite($metafile,pack("I",0));
fwrite($metafile,pack("I",0));
fwrite($metafile,pack("I",$meta->interval));
fwrite($metafile,pack("I",$meta->start_time));
fclose($metafile);
return true;
}
private function get_npoints($feedid)
{
$bytesize = 0;
if (file_exists($this->dir.$feedid.".dat")) {
clearstatcache($this->dir.$feedid.".dat");
$bytesize += filesize($this->dir.$feedid.".dat");
}
if (isset($this->writebuffer[$feedid]))
$bytesize += strlen($this->writebuffer[$feedid]);
return floor($bytesize / 4.0);
}
// -----------------------------------------------------------------------------------
// Post processed average layer
// -----------------------------------------------------------------------------------
/*
Averaging (mean)
The standard data request method returns the value of the data point at the specified timestamp
this works well for most data requests and is the required method for extracting accumulating kWh data
However its useful for many applicaitons to be able to extract the average value for a given period
An example would be requesting hourly temperature over number of days and wanting to see the average temperature for each hour
rather than the temperature at the start of each hour.
Emoncms initially did this with a dedicated feed engine called PHPFiwa the implementation of that engine calculated the average
values on the fly as the data came in which is not a particularly write efficient method as each average layer is opened for every
update and only one 4 byte float is appended.
A better approach is to post process the average layers when the data request is made and to cache the calculated averages at this
point. This significantly reduces the write load and converts the averaged layers into a recompilable cached property rather than
and integral part of the core engine.
*/
public function get_average($id,$start,$end,$interval)
{
$start = intval($start/1000);
$end = intval($end/1000);
$interval= (int) $interval;
// Minimum interval
if ($interval<1) $interval = 1;
// Maximum request size
$req_dp = round(($end-$start) / $interval);
if ($req_dp>8928) return array('success'=>false, 'message'=>"Request datapoint limit reached (8928), increase request interval or time range, requested datapoints = $req_dp");
$layer_interval = 0;
//if ($interval>=600) $layer_interval = 600;
//if ($interval>=3600) $layer_interval = 3600;
// Only return an average if the $interval is more than a layer interval
// and check that the interval is an integer number of layer intervals
if ($layer_interval>0 && $interval%$layer_interval==0) {
//if (!$this->calculate_average($id,$layer_interval)) {
// return $this->get_data($id,$start*1000,$end*1000,$interval,0,0);
// return array('success'=>false);
//}
}
$dir = $this->dir;
//if ($layer_interval>0) $dir = $dir."averages/$layer_interval/";
$meta = new stdClass();
$metafile = fopen($dir.$id.".meta", 'rb');
fseek($metafile,8);
$tmp = unpack("I",fread($metafile,4));
$meta->interval = $tmp[1];
$tmp = unpack("I",fread($metafile,4));
$meta->start_time = $tmp[1];
fclose($metafile);
$meta->npoints = floor(filesize($dir.$id.".dat") / 4.0);
if ((($end-$start) / $meta->interval)>69120) {
return $this->get_data($id,$start*1000,$end*1000,$interval,0,0);
}
if ($interval % $meta->interval !=0) return array('success'=>false, 'message'=>"Request interval is not an integer multiple of the layer interval");
$dp_to_read = $interval / $meta->interval;
$data = array();
$time = 0; $i = 0;
$numdp = 0;
$total_read_count = 0;
// The datapoints are selected within a loop that runs until we reach a
// datapoint that is beyond the end of our query range
$fh = fopen($dir.$id.".dat", 'rb');
while($time<=$end)
{
$time = $start + ($interval * $i);
$pos = round(($time - $meta->start_time) / $meta->interval);
$average = null;