-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathirp_classes.php
2735 lines (2721 loc) · 115 KB
/
irp_classes.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
/*
irp_classes - This is an 'execution process' for IRPs, extended to encode and decode IR remote commands.
Copyright (c) 2017 Marco Sillano. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// This classes was designed for applications using IR remote control, like home control, and not for analysing or
// IR protocols reverse-engineering, because for that they are many better applications (IRremote, IrScrutinizer etc..).
// The scenario is: having some HW to receive/transmit IR (my favourite is an Arduino), we want an application to
// manage many devices in a room. We will use a DataBase to store informations about all devices and protocols,
// and a WEB user interface: to control all devices we must implement a learning task with UI (if IRP missed) and
// a sending task with UI. This design allows WiFi control (smartphone) and also remote control (Internet).
// The HW for the web server (WAMP, LAMP...) can be as little as an Arduino Yun or a TVBOX.
//
// This class implements the core algorithms required for working with IR remote control, i.e. encode and decode
// IR commands. For that, you must known the IR Protocol (IRP: http://www.hifi-remote.com/wiki/index.php?title=IRP_Notation)
// of your devices. If you don't known the IRP, you still can store and send RAW streams.
// To store and retrieve IR commands we have many options:
// RAW: big size but not requires IRP (like RAW-0 or the compressed versions: RAW-1,RAW-2 see full-test.php page)
// HEX: small, but requires IRP (like BIN-1 or BIN-2 in full-test.php page)
// DATA SET: smallest (like $JVC_data ='{D=7,F=0x3F}', see full-test.php).
// In some cases we can have 2 DATA set: the <device-parameters> and the <protocol-parameters>: this class can process both.
// (see $Fujitsu_Aircon and $Fujitsu_Aircon_modified in full-test.php )
// My preferences are:
// RAW-0 to receive from Arduino, because it requires less code.
// RAW-1 to send to Arduino, because it is complete and minimizes RAM occupation on Arduino board.
// If <device-parameters> are knowns, I found more natural to store and work using it.
// If <device-parameters> are unknowns, i.e. if we must implement and use a 'learning' phase, and the
// reverse engineering of the IRP and <device-parameters> is too complex, then the simplest way is to use the
// RAW format (compressed: RAW-1).
//
// Features
// a) Recursive implementation (uses 3 classes)
// b) Uses protocol definitions (valid IRP)
// c) Repetitions and dittos as defined in IRP, or required by user.
// d) captured RAW stream can be dynamically normalized.
// e) input/output in many formats (4 RAW and 4 BIN)
// f) optional data permanence (as required by some IRP)
// g) many test and debug functions
// h) normalization and compression of RAW stream without IRP
//
// ENCODE
// - See method encodeRaw(value-set, repetitions)
// - Requires a values-set and the number of repetitions to produce a RAW IRstream
// - The <values-set> can be:
// 1) a php associative array, like: $data['D']=7; $data['F']=0x3F;
// 2) a string <protocol-parameters> or <device-parameters>, format like Expressions in IRP: '{D=7,F=0x3F}'
// 3) a HEX string, like: 'E0FC'. This string can be build by RAWprocess() using the BIN output of ENCODE/DECODE.
// - Accepts integer values in decimal or hex or octal (php standards: 16 or 0x10 or 020). You must use '.' as decimal separator.
// OUTPUT (see setOutputBin()/setOutputRaw()):
// RAW: if $outMode = 'raw', output is the complete timing for an IRstream in microseconds (+ mark, - space), it
// includes repetitions and dittos. Ready to send (production) e.g.: '210|-760|210|-760|-1632|210|-760|-408'
// RAW format is required to transmit IR commands using ad-hoc hardware (e.g. Arduino).
// BIN: if $outMode = 'bin', output is a pure data bit-stream ('1' or '0'),
// without any fixed duration (no header, trailer etc.). eg: '1110000011111100'
// BIN format is for test and to get the 'HEX string' data-set format using RAWprocess().
// In case of IRP errors, a '+++ WARNING....' message is send to output.
// - This two basic outputs can be processed by RAWprocess() to get a total of 8 output formats.
// - No size limitation: ok for air conditioner protocols, repetitions etc.
//
// DECODE
// - see method decodeRaw(RAWdata)
// - Requires a complete plain RAW IR signal using '|' as separator e.g.: '210|-760|210|-760|-1632|210|-760|-408'
// or any RAW compressed format build by RAWprocess() (accepts RAW, RAW-0, RAW-1, RAW-2: see full-test.php)
// (note: RAW-0 is like the signal coming from an IR receiver, RAW-1 is my favorite in applications)
// - The input RAW stream can be processed 'as is' or it can be normalized before processing to get better results.
// OUTPUT (see setOutputBin()/setOutputRaw()):
// RAW: if $outMode = 'raw', output is <protocol-parameters> as string (format like Expressions): '{D=7,F=0x3F}':
// BIN: if $outMode = 'bin', output is a data bit-stream ('1' or '0'), without any fixed duration: like ENCODE BIN.
// In case of RAW data error, it returns an error message starting '*** ERROR...', and $this->isError() returns true.
// - The BIN output can be processed by RAWprocess() to get HEX string
// - After calling decodeRaw() you can call the dataVerify() method to process <device-parameters> (if any) and verify Expressions.
// - No size limitation, decodes repeated complete steams.
//
// DECODE - NORMALIZATION
// The hardware of the IR input device uses an integrator/smith-trigger. If the IR signal is low or with interferences
// this circuit can under-estimate mark times (and over-estimate spaces).
// In Lib2 (basic Arduino IR RX/TX library) exists a fixed compensation (see DEFAULT_MARK_EXCESS in IRLibRecvBase.h)
// but for better decodes here I use a method, arrayNormalize(), that does a dynamic normalization of the raw signals against
// a (note) IRP. The irp_classes uses it by default, but the user can change this behaviour using setNormalize(false).
// Also the method RAWnormalize(RAWdata) does a normalization of <RAWdata>, but without IRP.
// It can fail with some unusual protocols, in this case the output is equal to input. (see decode_test.php)
//
// MORE METHODS
// - setOutputRaw() option: output is a RAW stream (encode) or a <protocol-parameters> string (decode). Default.
// - setOutputBin() option: output is a BIT stream (use it before encode and decode)
// - setNormalize(true|false) option: if true decodeRaw() does a normalization in RAW input. Default true.
// - setDataPermanence() option: set true doDataPermanence. Default false. (before encode and decode)
// - resetData(), to clean data in DataPermanence mode, e.g. before a re-run.
// - dataVerify(true|false) method to test decode results, in verbose (true) or terse modes (after decode).
// - getNormRAW() to get the normalized RAW stream (after decode, for test and debug).
// - toString() infos on IRP (after constructor, for test and debug).
// next methods don't uses IRP, so they can be used also to handle RAW stream from unknown protocols:
// - RAWnormalize(RAWdata) Try Normalization of a plain RAW stream (accepts RAW, RAW-0).
// - RAWprocess(RAWdata, 0|1|2, [frequence]) to process RAW (from HW or encode) or BIN (from encode/decode) streams.
// If the parameter 'frequence' is absent or NULL it uses IRP data, else it don't uses IRP.
// errors:
// - isError() returns true in case of decoding errors. (also: test the decode output char[0] != '*')
// - getNormError() returns false or normalization error message (Normalize fails silent, original RAW stream is processed)
//
// MORE FUNCTIONS
// - irp_getRMatchBrace($text, $braceOpen, $pos, $braceClose)
// - irp_getLMatchBrace($text, $braceOpen, $pos, $braceClose)
// - irp_onion($text, $lbrace, $rbrace)
// - irp_explodeVerify($result)
// - irp_explodeRAW1($raw1)
// - irp_implodeRAW1($rawArray)
//
// Limits in this implementation
// 1) Do not accepts ? or ?? or ??? in IRP
// 2) Many different errors in case of not well formed IRP or bad values-set (limited diagnostic)
// 3) In case of many commands in a raw stream, decodeRaw() returns last results in RAW mode, all results in BIN mode.
// 4) dataVerify() requires a well formed IRP, read comments in code.
// 5) Data permanence is implemented saving data in a file.
// 6) RAWnormalize() (without IRP) can fails with some protocols (better if min_mark_length == min_space_length)
// 7) This is an experimental version, so many 'echo' for debug are still in place but commented.
//
// Extensions to standard IRP, as defined in http://www.hifi-remote.com/wiki/index.php?title=IRP_Notation:
// 1) Repeats: accepts )+; )*; )3; )2+; )X; )X+; single digit numbers, or single letter variable (extension), no expressions.
// 2) Accepts(bad IRP): {36k,268}<-1,1|1,-1>[T=1][T=0](7,-6,3,D:4,1:1,T:1,1:2,F:8,C:4,-79m)+
// and processes it as: {36k,268}<-1,1|1,-1>([T=1][T=0],7,-6,3,D:4,1:1,T:1,1:2,F:8,C:4,-79m)+
//
// usage with IRP:
// step 1) create an irp_protocol object using a valid IRP:
// $aProtocol = new irp_protocol($IRP);
// step 2) call $aProtocol->setOutputBin() | $aProtocol->setOutputRaw() to set output style
// step 3a) call $aProtocol->encodeRaw() with a data-set, and optionally $aProtocol->RAWprocess() to filter result.
// step 3b) call $aProtocol->decodeRaw() with a RAW stream, and optionally $aProtocol->dataVerify() to get more infos.
// see full-test.php, decode-test.php (in dir phpIRPlib)
//
// usage without IRP:
// step 1) create an irp_protocol object using NULL:
// $aProtocol = new irp_protocol(NULL);
// step 2a) call $aProtocol->RAWnormalize($CAPTURE_RAW ) to normalise CAPTURED
// step 2b) call $aProtocol->RAWprocess($NORMALISED_RAW, 1, 38) to compress it in RAW-1
//
// see also remoteDB (https://github.com/msillano/remoteDB) a MySQL application using irp_classes
// ---------------------------------------------------------------------------------------
define('IRP_RAW_WIDE', 0); // $mode values for RAWprocess()
define('IRP_RAW_PACK', 1);
define('IRP_RAW_BYTE', 2);
/*
* Main class
*/
class irp_protocol
{
// config
// on/off to store data on file to get data permanence (It is required by some IRP)
// note: if $doDataPermanence = true the warnings:
// '+++ WARNING: Variable X not found!' and
// '+++ WARNING: var X not set! (uses default 0)'
// are suppressed: it uses quiet the default 0.
// note: changing protocols, data permanence can give bad results. Use resetData()
// to clear all data in case of re-run or protocol change.
public $doDataPermanence = false;
// file to store permanent data
const DATAFILE = '/dataStore.txt'; // used with dirname(__FILE__)
// --------------------------------------------------------------------
// internal use
const CHAR_LIST = '|'; // RAW separator
const CHAR_EXTRA = '§'; // internal use, any char not allowed in IRP
//
const TIME_FACTOR_DELTA = 3; // div factor for decode - do not change
const TIME_FACTOR_ERR = 6; // div factor for RAWprocess - do not change
//
const OUT_RAW = 'raw'; //internal, - use: $this->setOutputRaw()
const OUT_BIN = 'bin'; //internal, - use: $this->setOutputBin()
//
public $BMASK = array(0, 0x000001, 0x000003, 0x000007, 0x00000F, 0x00001F, 0x00003F, 0x00007F, 0x0000FF, 0x0001FF, 0x0003FF, 0x0007FF, 0x000FFF, 0x001FFF, 0x003FFF, 0x007FFF, 0x00FFFF, 0x01FFFF, 0x03FFFF, 0x07FFFF, 0x0FFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF, 0xFFFFFF); // 0..24 bit mask
// ---- GeneralSpec IRP
public $baseBSpec = null;
public $frequence = 0;
public $tBase = 1;
public $order = 'lsb';
public $IRP = '';
private $isNull = false;
//---- encode
private $mode = 'decode'; // decode|encode, internal use
private $outMode = 'raw'; // OUT_RAW|OUT_BIN see setOutputBin()/setOutputRaw()
private $inMode = 'raw'; // OUT_RAW|OUT_BIN, internal use
private $bitData = '';
private $bitptr = 0;
//---- decode
public $ukRaw = ''; // input RAW data
public $ukNorm = array(); // Normalized RAW data
public $storeNorm = array();
public $ukExtra = 0;
public $ukptr = 0;
public $ukdata = '';
public $uk2data = '';
public $dataDecoded = array();
public $bitDecoded = '';
public $decodePtr = 0;
public $errPosition = -1;
public $deltaTime = 0;
public $prtTime = 0;
//---- normalization
private $doRAWnormalization = true; // decodeeRaw uses arrayNormalize().
public $minM = 0; // the minimum Mark in usec, set by irp_bitSpec constructor
public $minS = 0; // the minimum Space in usec, set by irp_bitSpec constructor
private $delta = 0;
private $deltaM = 0;
private $deltaS = 0;
private $avgM = 0;
private $avgS = 0;
private $normmsg = ''; // error message by arrayNormalize()
var $environ = array(); //---- var store
/*
* Constructor, requires a valid IRP (string) or NULL
*/
function __construct($newIRP = NULL)
{
if ($newIRP == NULL)
{
$this->isNull = true;
$newIRP = '{38k,800,lsb}<1,-1|1,-3>(0:1,1:1,D:8,F:8,30m)+'; // dummy, fake
}
else
$this->isNull = false;
$tmp = $this->IRP = str_replace(' ', '', $newIRP); // no spaces
$tmp = $this->IRP = str_replace("\t", '', $tmp); // no tabs
$tmp = $this->IRP = str_replace("\n", '', $tmp); // no
$tmp = $this->IRP = str_replace("\r", '', $tmp); // no
// GeneralSpec
// echo 'irp = ',$tmp.'<br>';
$e = 0;
if ($k = irp_getRMatchBrace($tmp, '{', 0, '}'))
{
$this->setGeneralSpec(substr($tmp, 1, $k - 1));
$e = ++$k;
} //$k = irp_getRMatchBrace($tmp, '{', 0, '}')
$tmp = trim(substr($tmp, $e));
// BitSpec
$e = 0;
if ($k = irp_getRMatchBrace($tmp, '<', 0, '>'))
{
$this->baseBSpec = new irp_bitSpec($this, null, substr($tmp, 1, $k - 1));
$e = ++$k;
} //$k = irp_getRMatchBrace($tmp, '<', 0, '>')
//last = IRStream + [Definitions]
$last = trim(substr($tmp, $e));
// echo 'last = '.$last.'<br>';
// Definitions
$pieces = split('[{}]', $last); // here explode don't works (?)
if (isset($pieces[1]))
$this->setDefinitions(trim($pieces[1]));
// IRstream
// correction of a common error: <variations> out the IRstrem.
// this is not correct, but common:
// {36.0k,268,msb}<-1,1|1,-1>[T=1][T=0](7,-6,3,D:4,1:1,T:1,1:2,0:8,F:8,15:4,C:4,-79m)+
// this is correct:
// {36.0k,268,msb}<-1,1|1,-1>([T=1][T=0],7,-6,3,D:4,1:1,T:1,1:2,0:8,F:8,15:4,C:4,-79m)+
if (($pieces[0][0]) == '[')
{
$this->IRStream = str_replace('](', '],', '(' . trim($pieces[0]));
} //($pieces[0][0]) == '['
else
$this->IRStream = trim($pieces[0]);
// Persistence
if ($this->doDataPermanence)
{
$oldData = $this->restoreData();
$this->setValues($oldData, 'raw');
}
if ($this->baseBSpec == NULL)
echo "*** ERROR: code can't parse the IRP[" . $this->IRP . "]. Verify.\n\r<br>";
}
//
function __destruct()
{
if ($this->doDataPermanence)
{
$this->saveData();
}
else
@unlink(dirname(__FILE__) . self::DATAFILE);
}
/*
* ENCODE function: builds a RAW IR command using
* - value-set: an array like: '$data_DirectTV['D']= 7; $data_DirectTV['F']= 37;'
* or a string like Expressions: '{D=0x3A, F=37}'
* or a HEX string like 'A25E'
* - rrepeat (1...n) (uses dittos or Variation as defined in IRP)
* output is BIT (only data) or RAW (microsec., complete)
*/
// common <device-parameters> in IRP
// D = Device code
// S = Subdevice code
// F = Function code (otherwise called OBC or Original Button Code)
// C = Checksum
// T = Toggle (for repetitions)
public function encodeRaw($values, $rrepeat)
{
// set values
if ($this->isNull)
return '*** ENCODE unavailable. Protocol NULL';
$this->mode = 'encode';
$this->errPosition = -1;
$this->inMode = self::OUT_RAW;
if (gettype($values) == 'string')
{
if (strpos($values, "=") === false)
{
$this->setValuesHEX($values);
} //strpos($values, "=") === false
else
$this->setValues($values, 'raw');
} //gettype($values) == 'string'
if (gettype($values) == 'array')
{
foreach ($values as $key => $val)
$this->environ[$key] = $val;
} //gettype($values) == 'array'
// processes IRstream
$mainStream = new irp_bitStream($this, $this->baseBSpec, $this->IRStream, $rrepeat);
return $mainStream->analyzeRaw();
}
/*
* DECODE function: returns the found data.
* Requires only received RAW data.
* Returns a value-set as string (raw) or as bitstream (bin)
*/
public function decodeRaw($dataRaw)
{
if ($this->isNull)
return '*** unavailable. Protocol NULL';
// initialize
$store = array();
unset($this->ukNorm);
$this->storeNorm = NULL;
$this->mode = 'decode';
$this->inMode = self::OUT_RAW; // reset, required by Verify
$this->ukptr = 0;
$this->dataDecoded = array();
$this->bitDecoded = '';
$this->errPosition = -1;
$this->decodePtr = 0;
// set unknown raw
$err = 0;
$this->deltaTime = 999999;
$this->ukRaw = trim($dataRaw);
$errmsg = '';
if ($this->ukRaw[0] == '{')
{
// format RAW-1, RAW-2
$parts = explode('}', $this->ukRaw);
$tmp = explode(',', trim($parts[0]));
$factor = trim($tmp[1]);
$count = $tmp[2];
$times = explode(self::CHAR_LIST, trim($parts[1])); // compressed RAW mode
if (count($times) != $count)
{
$this->errPosition = 1;
return "*** ERROR: found " . count($times) . ' RAW data, required ' . $count . '<br>';
}
for ($i = 0; $i < count($times); $i++)
{
if (trim($times[$i]) === '')
$err++;
while ((($i + 1) < count($times)) && ($times[$i] * $times[$i + 1] > 0))
{
$times[$i + 1] += $times[$i]; // merges sequential mark/spaces (RAW-2 -> RAW-1 -> RAW-0)
$i++;
}
$small = round($times[$i] * $factor);
if ($small == 0)
{
$this->errPosition = $i;
// echo "error 3 <br>";
$errmsg = '*** ERROR: bad RAW value:[' . $times[$i] . '] @';
$err++;
}
if ($err > 0)
$errmsg .= self::CHAR_LIST . $times[$i];
if ((abs($small) > 1) && (abs($small) < $this->deltaTime))
$this->deltaTime = abs($small);
$this->ukNorm[] = $small;
} //$times as $t
}
else
{
// format RAW, RAW-0
$times = explode(self::CHAR_LIST, $dataRaw); // plain RAW mode
for ($i = 0; $i < count($times); $i++)
{
if (trim($times[$i]) === '')
$err++;
while ((($i + 1) < count($times)) && ($times[$i] * $times[$i + 1] > 0))
{
$times[$i + 1] += $times[$i]; // merges sequential mark/spaces (RAW -> RAW-0)
$i++;
}
$small = round($times[$i]);
if ($small == 0) // empty/0 not allowed
{
// echo "error 4 <br>";
$this->errPosition = $i;
$errmsg = '*** ERROR: bad RAW value:[' . $times[$i] . '] @';
$err++;
}
if ($err > 0)
$errmsg .= self::CHAR_LIST . $times[$i];
if ((abs($small) > 1) && (abs($small) < $this->deltaTime))
$this->deltaTime = abs($small);
$this->ukNorm[] = $small;
} //$times as $t
}
if ($err > 0)
return ($errmsg . ' >> Check data <br>');
// normalization
if ($this->doRAWnormalization)
$this->storeNorm = $this->ukNorm = $this->arrayNormalize($this->ukNorm);
// processes IRstream
$store = $this->environ; // saves environ
$this->prtTime = 0;
$this->environ = array(); // void
// used as base for time error in decoding, must exist > 1
// if exist, better $this->tBase
if ($this->tBase > 1)
$this->deltaTime = $this->tBase;
$mainStream = new irp_bitStream($this, $this->baseBSpec, $this->IRStream, 1);
$mainStream->analyzeRaw();
$this->environ = $store; // restore environ
if ($this->errPosition >= 0)
{
return ('*** ERROR: decoder fails near RAW[' . strval((int) $this->errPosition + 1) . ']');
}
// update S from S:4:4
foreach ($this->dataDecoded as $key => $value)
{
if (!ctype_alnum($key))
{
$pars = explode(':', $key);
// print_r($pars); echo ' from '.$key.'<br>';
if (count($pars) == 3)
{
$val = 0;
switch ($pars[0][0])
{
case '~':
$pars[0] = substr($pars[0], 1);
$val = ~$value & $this->BMASK[$pars[1]];
$val <<= $pars[2];
break;
case '-':
$pars[0] = substr($pars[0], 1);
$val = -$value & $this->BMASK[$pars[1]];
$val <<= $pars[2];
break;
default:
if (ctype_alpha($pars[0]))
{
$val = $value & $this->BMASK[$pars[1]];
$val <<= $pars[2];
}
else
continue;
}
// echo ' pars[0] now'.$pars[0].'<br>';
if (isset($this->dataDecoded[$pars[0]]))
$this->dataDecoded[$pars[0]] += $val;
else
$this->dataDecoded[$pars[0]] = $val;
}
if (count($pars) == 2)
{
}
}
}
// echo ' DataDECODED after: <br>';
// print_r ($this->dataDecoded); echo '<br>';
if ($this->isOutputRaw())
{
$tmp = '';
foreach ($this->dataDecoded as $key => $value)
{
if (!(gettype($key) == 'integer' || ctype_digit($key))) // skips numeric constants
if (!isset($this->environ['_def_'][$key]) || !$this->isFunction($this->dataDecoded, $this->environ['_def_'][$key]))
if (!$this->isVariation($key) && ctype_alpha($key))
$tmp .= $key . '=' . $value . ',';
} //$this->dataDecoded as $key => $value
$tmp = '{' . rtrim($tmp, ',') . '}';
return $tmp;
} //$this->isOutputRaw()
else
{
return $this->bitDecoded;
}
}
/*
* RAWprocess($raw, $mode, [$frequence])
* This utility processes a RAW|BIN stream (captured by HW sensor or from encode/decode).
* 1) RAW: Unifies double marks or double spaces
* BIN: Add spaces every 8 bit, right padded with zeros.
* If mode IRP_RAW_WIDE (0) returns
* 2) RAW: Finds a BASEtime giving a time error less than (deltaTime/TIME_FACTOR_ERR), and adds some infos
* required to send the IR: {freq,BASEtime,data-num} To receive this format is required an integer array.
* BIN: Transforms in HEXSTRING (can be used with encodeRaw()) right padded with zeros.
* If mode IRP_RAW_PACK (1) returns
* 3) RAW: Any data value>127 (or <-127) is split in many fields, so all fields are BYTES. Adds {freq,BASEtime,data-num}
* This format will reduce the RAM used because to receive this format is required an byte array.
* BIN: Transforms in HEXBYTE, if required right padded with zeros.
* If mode IRP_RAW_BYTE (2) returns
* Note: if the parameter 'frequence' is present, this don't uses IRP: this function can be uses with any RAW stream.
*/
public function RAWprocess($raw, $mode, $frequence = NULL)
{
if ($raw[0] == '*')
return;
if (strpos($raw, irp_protocol::CHAR_LIST) === false) // data in BIN mode
{
$new = '';
$copies = explode(' ', $raw); // repetitions
foreach ($copies as $sended)
{
if ($sended == '')
continue;
if ($mode == IRP_RAW_WIDE)
{
for ($i = 0; $i < strlen($sended); $i += 8)
{
$part = substr($sended, $i, 8);
$part .= '00000000';
$part = substr($part, 0, 8);
$new .= $part . ' ';
} //$i = 0; $i < strlen($sended); $i += 8
$new .= ' ';
} //$mode == IRP_RAW_WIDE
if ($mode == IRP_RAW_PACK)
{
for ($i = 0; $i < strlen($sended); $i += 16)
{
$part = substr($sended, $i, 16);
$part .= '0000000000000000';
$part = substr($part, 0, 16);
$new .= sprintf('%04X', bindec($part));
} //$i = 0; $i < strlen($sended); $i += 16
$new .= ' ';
} //$mode == IRP_RAW_PACK
if ($mode == IRP_RAW_BYTE)
{
for ($i = 0; $i < strlen($sended); $i += 8)
{
$part = substr($sended, $i, 8);
$part .= '00000000';
$part = substr($part, 0, 8);
$new .= sprintf('%02X', bindec($part)) . ' ';
} //$i = 0; $i < strlen($sended); $i += 8
$new .= ' ';
} //$mode == IRP_RAW_BYTE
} //$copies as $sended
return trim($new);
} //!(strpos($raw, irp_protocol::CHAR_LIST))
// RAW mode -----------------
$useF = $frequence;
if ($frequence == NULL)
$useF = round($this->frequence); // uses frequence from IRP
$times = explode(irp_protocol::CHAR_LIST, $raw);
// merge and clean-up data
$min = abs($times[2]);
$imax = count($times) - 2; // because the unset(), count($times) will change, $imax not
for ($i = 0; $i <= $imax; $i++)
{
if (($times[$i] * $times[$i + 1]) > 0) //add if same sign
{
$times[$i + 1] += $times[$i];
unset($times[$i]);
} //(($times[$i] * $times[$i + 1]) > 0)
if (($min > abs($times[$i + 1])) and ($times[$i + 1] != 0))
{
$min = abs($times[$i + 1]); // set $min
} //($min > abs($times[$i + 1])) and ($times[$i + 1] != 0)
if (isset($times[$i]) && ($times[$i] == 0))
unset($times[$i]); // eliminates zeros
} //$i = 0; $i < $imax; $i++
// restore index
$times = array_values($times);
// RAW processing 0 ------------
if ($mode == IRP_RAW_WIDE)
return implode(irp_protocol::CHAR_LIST, $times);
// try to found a good deltaTime (also if $this->tBase == 1)
// get average of shorts values
$min = round($min * 1.33); // tolerance +/- 1/3
$ssum = 0;
$n = 0;
$totTime = 0;
$last = 0;
// excludes first and last times from totTime.
$skipfirst = 4;
$skiplast = 8;
for ($i = $skipfirst; $i < count($times) - $skiplast; $i++)
{
$x = abs($times[$i]);
$totTime += $x;
if (($x <= $min) && ($x > 0))
{
$ssum += $x;
$n++;
}
}
// uses $this->tBase or average ( case not IRP)
if (($frequence != NULL) || ($this->tBase == 1)) // alone
{
$this->deltaTime = round($ssum / $n);
}
else
$this->deltaTime = $this->tBase; // uses IRP data
// round errors reduction
$factor = array(
1.0,
2.0,
3.0,
4.0,
5.0,
6.0,
8.0,
10.0,
12.0,
15.0,
20.0,
25.0,
50.0,
100.0
);
//
$delta = $this->deltaTime / irp_protocol::TIME_FACTOR_ERR; // required precision in compress process
// trims $this->deltaTime on (max error > $delta)
$ntest = 0;
$errpos = 0;
while (true)
{
$step = round($this->deltaTime / $factor[$ntest]); //
$err = 0.0;
// echo 'step = '.$step.'<br>';
if ($step == 0)
return;
for ($i = $skipfirst; $i < count($times) - $skiplast; $i++)
{
$t = $times[$i];
if ($t != 0)
{
$v = round($t / $step);
$e = ($t - $v * $step); // absolute
if (abs($e) > $err)
{
$err = abs($e);
$errpos = $i;
}
} //$t != 0
} //$times as $t
// echo 'step = '.$step.' MaxError = '.$err.' @pos = '.$errpos.'<br>';
if ($err > $delta) // no good
{
$ntest++; // loops using a big factor[]
continue;
} //$err > $delta
if ($step < 1)
$step = 1; // just in case
// now trims step on total time
while (true)
{
$newTot = 0;
$b = array_values($times);
$c = array();
for ($i = 0; $i < count($b); $i++)
{
// normalize last space to 10 (last value can change)
if ($i == (count($b) - 1))
{
$raw = -10 * ceil(abs($b[$i]) / ($step * 10));
}
else
{
$raw = round($b[$i] / $step);
}
if ($i >= $skipfirst && $i < count($times) - $skiplast)
$newTot += abs($raw * $step);
$b[$i] = $raw;
while ($raw > 127)
{
$c[] = 127;
$raw -= 127;
} //$raw > 127
while ($raw < -127)
{
$c[] = -127;
$raw += 127;
} //$raw < -127
$c[] = $raw;
} //$i = 0; $i < count($b); $i++
// echo "Old tot = $totTime newTot = $newTot <br>";
if (($frequence != NULL) || ($this->tBase == 1)) // case alone
{
$step2 = round($step * $totTime / $newTot); // loops if newTot <<>> totTime
// echo "Old step = $step new step = $step2 <br>";
if ($step2 == $step)
break;
$step = $step2;
}
else
break; // with IRP don't trim: ok, so forces 'exact' timing
}
// now $b[], $c[], and $step are ok
// normalize last space
// RAW processing 1 ------------
if ($mode == IRP_RAW_PACK)
return '{' . $useF . ',' . $step . ',' . count($b) . '}' . implode(irp_protocol::CHAR_LIST, $b);
// RAW processing 2 ------------
if ($mode == IRP_RAW_BYTE)
return '{' . $useF . ',' . $step . ',' . count($c) . '}' . implode(irp_protocol::CHAR_LIST, $c);
echo 'ERROR: bad mode value, only 0,1,2 ! <br>';
return;
} //true
}
/*
* In function of IR signal straight, the integrator/smith trigger, in the IR detector,
* can under-estimate mark times (and over-estimate spaces).
* This try normalization of RAW data without use the IRP.
*/
public function RAWnormalize($RAWdata)
{
$array1 = explode(irp_protocol::CHAR_LIST, $RAWdata); // plain RAW mode, RAW-0 or RAW-1
$array2 = $this->arrayNormalize($array1, false);
return implode(irp_protocol::CHAR_LIST, $array2);
}
// This function try a dynamic normalization of the raw signal (as array).
// Uses different algorithms if useIRP = true|false
private function arrayNormalize($dataArray, $useIRP = true)
{
$this->normmsg = '';
// echo 'expected - mark: '.$this->minM.' space: '.$this->minS.'<br>';
// test condition, usually ok after __constructor, ever ok after first decode
if ($useIRP && (!(($this->minM > 0) && ($this->minS < 0))))
{
$this->normmsg = 'NO RAW NORMALIZATION because min/max code not set';
return $dataArray; // can't normalize
}
$rawminM = 99999999;
$rawminS = -99999999;
// find min
foreach ($dataArray as $time1)
{
if ($time1 > 0 && ($time1 < (int) $rawminM))
$rawminM = $time1;
if ($time1 < 0 && ($time1 > (int) $rawminS))
$rawminS = $time1;
}
// echo 'minimun - mark: '.$rawminM.' space: '.$rawminS.'<br>';
// limit min values to do averages
$rawminM = round($rawminM * 1.33);
$rawminS = round($rawminS * 1.33);
// echo ' test-min - mark: '.$rawminM.' space: '.$rawminS.'<br>';
// average of low times
$sumM = 0;
$countM = 0;
$sumS = 0;
$countS = 0;
foreach ($dataArray as $time1)
{
if ($time1 > 0 && $time1 < $rawminM)
{
$sumM += $time1;
$countM++;
}
if ($time1 < 0 && $time1 > $rawminS)
{
$sumS += $time1;
$countS++;
}
}
if (($countM == 0) || ($countS == 0))
{
$this->normmsg = 'NO RAW NORMALIZATION because internal error';
return $dataArray; // don't normalize
}
$this->avgM = round($sumM / $countM);
$this->avgS = round($sumS / $countS);
// correction average vs expected
if ($useIRP == true)
{
$this->deltaM = $this->minM - $this->avgM;
$this->deltaS = $this->minS - $this->avgS;
// using same value for M and S, preserves total time
$this->delta = round(($this->deltaM + $this->deltaS) / 2);
// echo ' Marks - required: '.$this->minM.' average: '.$this->avgM.' delta: '.$this->deltaM.'<br>';
// echo ' Spaces - required: '.$this->minS. ' average: '.$this->avgS. ' delta: '.$this->deltaS.' adjust: '. $this->delta.'<br>';
}
else
{
$factor = round(-$this->avgS / $this->avgM);
$this->delta = round((-$factor * $this->avgM - $this->avgS) / ($factor + 1));
// echo ' Marks - average: '.$this->avgM.' becomes: '.($this->avgM+$this->delta).'<br>';
// echo ' Spaces - average: '.$this->avgS. ' becomes: '.($this->avgS+$this->delta).' adjust: '. $this->delta.'<br>';
}
// more safety check
if ($useIRP)
if (($this->deltaM > $this->minM / 3) || (abs($this->deltaS) > abs($this->minS) / 3))
{
// some gone bad, no normalization
$this->normmsg = 'NO RAW NORMALIZATION because security check';
return $dataArray;
}
if (!$useIRP)
if (($this->deltaM > $this->avgM / 3) || (abs($this->deltaS) > abs($this->avgS) / 3))
{
// some gone bad, no normalization
$this->normmsg = 'NO RAW NORMALIZATION because security check';
return $dataArray;
}
$norm = array();
foreach ($dataArray as $time1)
{
$norm[] = $time1 + $this->delta;
}
return $norm;
}
/*
* Utility to test data from decode (if possible)
* OUTPUT:
* if $verbose = false
* a string: <protocol-parameters>|<device-parameters>|<verify-result> like: {D=10,F=37}|{}|true
* if $verbose = true
* a string with max 4 sections:
* RAW NORMALIZED, DECODED VARIABLES, CALCULATED VARIABLES, VERIFIED VARIABLES (see full-test.php)
*/
// notes on IRP notation
//
// 1) To verify the decoded value against an Expressions, verify that the value used in the IRstream and the value given
// by the expression have same number of bit. If not, add some like ':4' or '&15' (limits to 4 bit) to Expression.
// Example: see decode-test.php:
// $XMP='{38k,136,msb}<210u,-760u>(<0:1|0:1,-1|0:1,-2|0:1,-3|0:1,-4|0:1,-5|0:1,-6|0:1,-7|0:1,-8|0:1,-9|0:1,-10|0:1,
// -11|0:1, -12|0:1,-13|0:1,-14|0:1,-15>(T=0,(S:4:4,C1:4,S:4,15:4,OEM:8,D:8,210u,-13.8m,S:4:4,C2:4,T:4,S:4,
// F:16,210u,-80.4m,T=8)+)){C1=-(15+S+S::4+15+OEM+OEM::4+D+D::4),C2=-(15+S+S:4+T+F+F::4+F::8+F::12)}';
// modify the IRP so: ....{C1=-(15+S+S::4+15+OEM+OEM::4+D+D::4):4,C2=-(15+S+S:4+T+F+F::4+F::8+F::12)&15},
// because in IRstrem we found 'C1:4' and 'C2:4'
//
// 2) Sometime we have 2 sets of values: the first set are <device-parameters'> the second set are <protocol-parameters>
// and the Expressions in IRP allows to calculate the second set from the first.
// It is possible and useful to add at IRP also the inverse Expressions.
// Example: see full-test.php
// $Fujitsu_Aircon='{38.4k,413}<1,-1|1,-3>(8,-4,20:8,99:8,0:8,16:8,16:8,254:8,9:8,48:8,H:8,J:8,K:8, L:8, M:8,N:8,
// 32:8,Z:8,1,-104.3m)+ {H=16*A + wOn, J=16*C + B, K=16*E:4 + D:4, L=tOff:8, M=tOff:3:8+fOff*8+16*tOn:4,
// N=tOn:7:8+128*fOn,Z=256-(H+J+K+L+M+N+80)%256}';
// with [A:0..15,wOn:0..1,B:0..15, C:0..15,D:0..15,E:0..15,tOff:0..1024,tOn:0..1024,fOff:0..1,fOn:0..1]
// The Expressions in IRP allows to calculate H,J,K,L,M,N and Z (protocol-parameters) from A,wOn,B,C,D,E,tOff,tOn,fOff,
// fOn (device-parameters) and they are used in ENCODING phase.
// On decoding, we need inverse expressions, calculating A,wOn,B,C,D,E,tOff,tOn,fOff,fOn from H,J,K,L,M,N,Z.
// We can add these Expressions to IRP, and that will not influence the ENCODE phase (values have precedence on
// expressions) but in DECODE phase we can get from RAW not only H,J,K,L,M,N,Z but also the device parameters
// A,wOn,B,C,D,E,tOff,tOn,fOff,fOn.
// See $Fujitsu_Aircon_modified.
//
// 3) Typing mistakes are not rare in public IRP. If ENCODE/DECODE/VERIFY crashes look with care to IRP.
//
public function dataVerify($verbose)
{
if ($this->isNull)
return '*** unavailable. Protocol NULL';
if (strlen($this->bitDecoded) == 0)
{
echo '+++ WARNING: dataVerify() must be called only after decodeRaw() <br>';
return;
} //strlen($this->bitDecoded) == 0
if ($this->isError()) // in case of error
{
if (!$verbose)
return '{}|{}|false';
$out1 = '';
$out2 = '';
$msg = '<br>------------- ERROR @item[' . ($this->errPosition + 1) . '] / ' . count($this->ukNorm) . ' <br>';
$copies = explode(' ', $this->bitDecoded); // repetitions
foreach ($copies as $sended)
{
for ($i = 0; $i < strlen($sended); $i += 8)
{
$part = substr($sended, $i, 8);
$part .= '00000000';
$part = substr($part, 0, 8);
$out1 .= $part . ' ';
} //$i = 0; $i < strlen($sended); $i += 8
for ($i = 0; $i < strlen($sended); $i += 16)
{
$part = substr($sended, $i, 16);
$part .= '0000000000000000';
$part = substr($part, 0, 16);
$out2 .= sprintf('%04X', bindec($part));
} //$i = 0; $i < strlen($sended); $i += 16
$out1 .= '- ';
$out2 .= ' - ';
} //$copies as $sended
$msg .= 'BIN-0 = ' . rtrim($out1, ' -') . '<br>';
$msg .= 'BIN-1 = ' . rtrim($out2, ' -') . '<br>';
return trim($msg);
}
$store = $this->environ;
$this->environ = $this->dataDecoded;
$mainStream = new irp_bitStream($this, $this->baseBSpec, $this->IRStream, 1);
// list of data_found
$data_found = array();
$var_name = array();
foreach ($this->dataDecoded as $key => $value)
{
$tmp = explode(':', $key);
if (!(gettype($tmp[0]) == 'integer' || ctype_digit($tmp[0])))
// if (ctype_alpha($key[0]) && ctype_alnum($key)) // only simple variables
$data_found[] = $key;
$var_name[$tmp[0]] = $key;
}
// list of calculated
// list of verify
$calc_expression = array();
$verify_expression = array();
if (isset($store['_def_']))
foreach ($store['_def_'] as $var => $expression)
{
// if(! array_key_exists ($var,$this->dataDecoded ))
if (!array_key_exists($var, $var_name))
{
$calc_expression[] = $var;
}
}
// list of verify2
$verify_data = array();
foreach ($this->dataDecoded as $key => $value)
{
$tmp = explode(':', $key);
if (!(gettype($tmp[0]) == 'integer' || ctype_digit($tmp[0])))
if (!ctype_alnum($tmp[0]))
{
$verify_data[] = $key;
}
}
// echo ' LIST DataDECODED: <br>';
// print_r ($this->dataDecoded); echo '<br>';
// building output
if ($verbose)
{
$result = 'Processed ' . $this->ukptr . ' data. <br>';
// if ($this->doRAWnormalization){
$result .= '<br>------------- RAW NORMALIZED <br>';
$result .= ' Marks - required: ' . $this->minM . ' average: ' . $this->avgM . ' delta: ' . $this->deltaM . '<br>';
$result .= ' Spaces - required: ' . $this->minS . ' average: ' . $this->avgS . ' delta: ' . $this->deltaS . ' adjust: ' . $this->delta . '<br>';
if ($this->getNormError() !== false)
$result .= ' WARNING ' . $this->getNormError() . '<br>';
// }
$result .= '<br>------------- DECODED VARIABLES <br>';
}
else
$result = '{';
foreach ($data_found as $key)
{
if ($verbose)
$result .= $key . ' = ' . $this->xd($this->environ[$key]) . '<br>';
else if (!isset($store['_def_'][$key]) || !$this->isFunction($this->environ, $store['_def_'][$key]))
if (!$this->isVariation($key) && ctype_alpha($key[0]) && ctype_alnum($key)) // only simple variables
$result .= $key . '=' . $this->environ[$key] . ',';
}
if ($verbose)
{
if (count($calc_expression) > 0)
$result .= '<br>------------- CALCULATED VARIABLES <br>';
}
else
$result = rtrim($result, ',') . '}|{';
foreach ($calc_expression as $key)
{
$v = $mainStream->evalExp($store['_def_'][$key]);
$this->environ[$key] = $v;
if ($verbose)
$result .= $key . ' = ' . $store['_def_'][$key] . ' = ' . $this->xd($v) . '<br>';
else
$result .= $key . '=' . $v . ',';
}
if (isset($store['_def_']))
foreach ($store['_def_'] as $var => $expression)
{
// if(array_key_exists ($var,$this->dataDecoded ))
if (array_key_exists($var, $var_name))
if ($this->isFunction($this->environ, $expression))
$verify_expression[] = $var;
}
if ($verbose)
{
if ((count($verify_expression) + count($verify_data)) > 0)
$result .= '<br>------------- VERIFIED VARIABLES <br>';
}