-
Notifications
You must be signed in to change notification settings - Fork 2
/
aJSON.cpp
1279 lines (1201 loc) · 26.4 KB
/
aJSON.cpp
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
/*
Copyright (c) 2001, Interactive Matter, Marcus Nowotny
Based on the cJSON Library, Copyright (C) 2009 Dave Gamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// aJSON
// aJson Library for Arduino.
// This library is suited for Atmega328 based Arduinos.
// The RAM on ATmega168 based Arduinos is too limited
/******************************************************************************
* Includes
******************************************************************************/
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <ctype.h>
#ifdef __AVR__
#include <avr/pgmspace.h>
#elif defined(ARDUINO_ARCH_SAMD)
#include <avr/pgmspace.h>
#else
#include <pgmspace.h>
#endif
#include "include/aJson/aJSON.h"
#include "include/aJson/stringbuffer.h"
/******************************************************************************
* Definitions
******************************************************************************/
//Default buffer sizes - buffers get initialized and grow acc to that size
#define BUFFER_DEFAULT_SIZE 4
//how much digits after . for float
#define FLOAT_PRECISION 5
bool
aJsonStream::available()
{
if (bucket != EOF)
return true;
while (stream()->available())
{
/* Make an effort to skip whitespace. */
int ch = this->getch();
if (ch > 32)
{
this->ungetch(ch);
return true;
}
}
return false;
}
int
aJsonStream::getch()
{
if (bucket != EOF)
{
int ret = bucket;
bucket = EOF;
return ret;
}
// In case input was malformed - can happen, this is the
// real world, we can end up in a situation where the parser
// would expect another character and end up stuck on
// stream()->available() forever, hence the 500ms timeout.
unsigned long i= millis()+500;
while ((!stream()->available()) && (millis() < i)) /* spin with a timeout*/;
return stream()->read();
}
void
aJsonStream::ungetch(char ch)
{
bucket = ch;
}
size_t
aJsonStream::write(uint8_t ch)
{
return stream()->write(ch);
}
size_t
aJsonStream::readBytes(uint8_t *buffer, size_t len)
{
for (size_t i = 0; i < len; i++)
{
int ch = this->getch();
if (ch == EOF)
{
return i;
}
buffer[i] = ch;
}
return len;
}
int
aJsonClientStream::getch()
{
if (bucket != EOF)
{
int ret = bucket;
bucket = EOF;
return ret;
}
while (!stream()->available() && stream()->connected()) /* spin */;
if (!stream()->available()) // therefore, !stream()->connected()
{
stream()->stop();
return EOF;
}
return stream()->read();
}
bool
aJsonStringStream::available()
{
if (bucket != EOF)
return true;
return inbuf_len > 0;
}
int
aJsonStringStream::getch()
{
if (bucket != EOF)
{
int ret = bucket;
bucket = EOF;
return ret;
}
if (!inbuf || !inbuf_len)
{
return EOF;
}
char ch = *inbuf++;
inbuf_len--;
return ch;
}
size_t
aJsonStringStream::write(uint8_t ch)
{
if (!outbuf || outbuf_len <= 1)
{
return 0;
}
*outbuf++ = ch; outbuf_len--;
*outbuf = 0;
return 1;
}
// Internal constructor.
aJsonObject*
aJsonClass::newItem()
{
aJsonObject* node = (aJsonObject*) malloc(sizeof(aJsonObject));
if (node)
memset(node, 0, sizeof(aJsonObject));
return node;
}
// Delete a aJsonObject structure.
void
aJsonClass::deleteItem(aJsonObject *c)
{
aJsonObject *next;
while (c)
{
next = c->next;
if (!(c->type & aJson_IsReference) && c->child)
{
deleteItem(c->child);
}
if ((c->type == aJson_String) && c->valuestring)
{
free(c->valuestring);
}
if (c->name)
{
free(c->name);
}
free(c);
c = next;
}
}
// Parse the input text to generate a number, and populate the result into item.
int
aJsonStream::parseNumber(aJsonObject *item)
{
int i = 0;
int sign = 1;
int in = this->getch();
if (in == EOF)
{
return EOF;
}
// It is easier to decode ourselves than to use sscnaf,
// since so we can easier decide between int & double
if (in == '-')
{
//it is a negative number
sign = -1;
in = this->getch();
if (in == EOF)
{
return EOF;
}
}
if (in >= '0' && in <= '9')
do
{
i = (i * 10) + (in - '0');
in = this->getch();
}
while (in >= '0' && in <= '9'); // Number?
//end of integer part � or isn't it?
if (!(in == '.' || in == 'e' || in == 'E'))
{
item->valueint = i * (int) sign;
item->type = aJson_Int;
}
//ok it seems to be a double
else
{
double n = (double) i;
int scale = 0;
int subscale = 0;
char signsubscale = 1;
if (in == '.')
{
in = this->getch();
do
{
n = (n * 10.0) + (in - '0'), scale--;
in = this->getch();
}
while (in >= '0' && in <= '9');
} // Fractional part?
if (in == 'e' || in == 'E') // Exponent?
{
in = this->getch();
if (in == '+')
{
in = this->getch();
}
else if (in == '-')
{
signsubscale = -1;
in = this->getch();
}
while (in >= '0' && in <= '9')
{
subscale = (subscale * 10) + (in - '0'); // Number?
in = this->getch();
}
}
n = sign * n * pow(10.0, ((double) scale + (double) subscale
* (double) signsubscale)); // number = +/- number.fraction * 10^+/- exponent
item->valuefloat = n;
item->type = aJson_Float;
}
//preserve the last character for the next routine
this->ungetch(in);
return 0;
}
// Render the number nicely from the given item into a string.
int
aJsonStream::printInt(aJsonObject *item)
{
if (item != NULL)
{
return this->print(item->valueint, DEC);
}
//printing nothing is ok
return 0;
}
int
aJsonStream::printFloat(aJsonObject *item)
{
if (item != NULL)
{
double d = item->valuefloat;
if (d<0.0) {
this->print("-");
d=-d;
}
//print the integer part
unsigned long integer_number = (unsigned long)d;
this->print(integer_number, DEC);
this->print(".");
//print the fractional part
double fractional_part = d - ((double)integer_number);
//we do a do-while since we want to print at least one zero
//we just support a certain number of digits after the '.'
int n = FLOAT_PRECISION;
fractional_part += 0.5/pow(10.0, FLOAT_PRECISION);
do {
//make the first digit non fractional(shift it before the '.'
fractional_part *= 10.0;
//create an int out of it
unsigned int digit = (unsigned int) fractional_part;
//print it
this->print(digit, DEC);
//remove it from the number
fractional_part -= (double)digit;
n--;
} while ((fractional_part!=0) && (n>0));
}
//printing nothing is ok
return 0;
}
// Parse the input text into an unescaped cstring, and populate item.
int
aJsonStream::parseString(aJsonObject *item)
{
//we do not need to skip here since the first byte should be '\"'
int in = this->getch();
if (in != '\"')
{
return EOF; // not a string!
}
item->type = aJson_String;
//allocate a buffer & track how long it is and how much we have read
string_buffer* buffer = stringBufferCreate();
if (buffer == NULL)
{
//unable to allocate the string
return EOF;
}
in = this->getch();
if (in == EOF)
{
stringBufferFree(buffer);
return EOF;
}
while (in != EOF)
{
while (in != '\"' && in >= 32)
{
if (in != '\\')
{
stringBufferAdd((char) in, buffer);
}
else
{
in = this->getch();
if (in == EOF)
{
stringBufferFree(buffer);
return EOF;
}
switch (in)
{
case '\\':
stringBufferAdd('\\', buffer);
break;
case '\"':
stringBufferAdd('\"', buffer);
break;
case '/':
stringBufferAdd('/', buffer);
break;
case 'b':
stringBufferAdd('\b', buffer);
break;
case 'f':
stringBufferAdd('\f', buffer);
break;
case 'n':
stringBufferAdd('\n', buffer);
break;
case 'r':
stringBufferAdd('\r', buffer);
break;
case 't':
stringBufferAdd('\t', buffer);
break;
default:
//we do not understand it so we skip it
break;
}
}
in = this->getch();
if (in == EOF)
{
stringBufferFree(buffer);
return EOF;
}
}
//the string ends here
item->valuestring = stringBufferToString(buffer);
return 0;
}
//we should not be here but it is ok
return 0;
}
// Render the cstring provided to an escaped version that can be printed.
int
aJsonStream::printStringPtr(const char *str)
{
this->print("\"");
char* ptr = (char*) str;
if (ptr != NULL)
{
while (*ptr != 0)
{
if ((unsigned char) *ptr > 31 && *ptr != '\"' && *ptr != '\\')
{
this->print(*ptr);
ptr++;
}
else
{
this->print('\\');
switch (*ptr++)
{
case '\\':
this->print('\\');
break;
case '\"':
this->print('\"');
break;
case '/':
this->print('/');
break;
case '\b':
this->print('b');
break;
case '\f':
this->print('f');
break;
case '\n':
this->print('n');
break;
case '\r':
this->print('r');
break;
case '\t':
this->print('t');
break;
default:
break; // eviscerate with prejudice.
}
}
}
}
this->print('\"');
return 0;
}
// Invote print_string_ptr (which is useful) on an item.
int
aJsonStream::printString(aJsonObject *item)
{
return this->printStringPtr(item->valuestring);
}
// Utility to jump whitespace and cr/lf
int
aJsonStream::skip()
{
int in = this->getch();
while (in != EOF && (in <= 32))
{
in = this->getch();
}
if (in != EOF)
{
this->ungetch(in);
return 0;
}
return EOF;
}
// Utility to flush our buffer in case it contains garbage
// since the parser will return the buffer untouched if it
// cannot understand it.
int
aJsonStream::flush()
{
int in = this->getch();
while(in != EOF)
{
in = this->getch();
}
return EOF;
}
// Parse an object - create a new root, and populate.
aJsonObject*
aJsonClass::parse(char *value)
{
aJsonStringStream stringStream(value, NULL);
aJsonObject* result = parse(&stringStream);
return result;
}
// Parse an object - create a new root, and populate.
aJsonObject*
aJsonClass::parse(aJsonStream* stream)
{
return parse(stream, NULL);
}
// Parse an object - create a new root, and populate.
aJsonObject*
aJsonClass::parse(aJsonStream* stream, char** filter)
{
if (stream == NULL)
{
return NULL;
}
aJsonObject *c = newItem();
if (!c)
return NULL; /* memory fail */
stream->skip();
if (stream->parseValue(c, filter) == EOF)
{
deleteItem(c);
return NULL;
}
return c;
}
// Render a aJsonObject item/entity/structure to text.
int
aJsonClass::print(aJsonObject* item, aJsonStream* stream)
{
return stream->printValue(item);
}
char*
aJsonClass::print(aJsonObject* item)
{
char* outBuf = (char*) malloc(PRINT_BUFFER_LEN); /* XXX: Dynamic size. */
if (outBuf == NULL)
{
return NULL;
}
aJsonStringStream stringStream(NULL, outBuf, PRINT_BUFFER_LEN);
print(item, &stringStream);
return outBuf;
}
// Parser core - when encountering text, process appropriately.
int
aJsonStream::parseValue(aJsonObject *item, char** filter)
{
if (this->skip() == EOF)
{
return EOF;
}
//read the first byte from the stream
int in = this->getch();
if (in == EOF)
{
return EOF;
}
this->ungetch(in);
if (in == '\"')
{
return this->parseString(item);
}
else if (in == '-' || (in >= '0' && in <= '9'))
{
return this->parseNumber(item);
}
else if (in == '[')
{
return this->parseArray(item, filter);
}
else if (in == '{')
{
return this->parseObject(item, filter);
}
//it can only be null, false or true
else if (in == 'n')
{
//a buffer to read the value
char buffer[] =
{ 0, 0, 0, 0 };
if (this->readBytes((uint8_t*) buffer, 4) != 4)
{
return EOF;
}
if (!strncmp(buffer, "null", 4))
{
item->type = aJson_NULL;
return 0;
}
else
{
return EOF;
}
}
else if (in == 'f')
{
//a buffer to read the value
char buffer[] =
{ 0, 0, 0, 0, 0 };
if (this->readBytes((uint8_t*) buffer, 5) != 5)
{
return EOF;
}
if (!strncmp(buffer, "false", 5))
{
item->type = aJson_Boolean;
item->valuebool = false;
return 0;
}
}
else if (in == 't')
{
//a buffer to read the value
char buffer[] =
{ 0, 0, 0, 0 };
if (this->readBytes((uint8_t*) buffer, 4) != 4)
{
return EOF;
}
if (!strncmp(buffer, "true", 4))
{
item->type = aJson_Boolean;
item->valuebool = true;
return 0;
}
}
return EOF; // failure.
}
// Render a value to text.
int
aJsonStream::printValue(aJsonObject *item)
{
int result = 0;
if (item == NULL)
{
//nothing to do
return 0;
}
switch (item->type)
{
case aJson_NULL:
result = this->print("null");
break;
case aJson_Boolean:
if(item->valuebool){
result = this->print("true");
}
else{
result = this->print("false");
}
break;
case aJson_Int:
result = this->printInt(item);
break;
case aJson_Float:
result = this->printFloat(item);
break;
case aJson_String:
result = this->printString(item);
break;
case aJson_Array:
result = this->printArray(item);
break;
case aJson_Object:
result = this->printObject(item);
break;
}
return result;
}
// Build an array from input text.
int
aJsonStream::parseArray(aJsonObject *item, char** filter)
{
int in = this->getch();
if (in != '[')
{
return EOF; // not an array!
}
item->type = aJson_Array;
this->skip();
in = this->getch();
//check for empty array
if (in == ']')
{
return 0; // empty array.
}
//now put back the last character
this->ungetch(in);
aJsonObject *child;
char first = -1;
while ((first) || (in == ','))
{
aJsonObject *new_item = aJsonClass::newItem();
if (new_item == NULL)
{
return EOF; // memory fail
}
if (first)
{
item->child = new_item;
first = 0;
}
else
{
child->next = new_item;
new_item->prev = child;
}
child = new_item;
this->skip();
if (this->parseValue(child, filter))
{
return EOF;
}
this->skip();
in = this->getch();
}
if (in == ']')
{
return 0; // end of array
}
else
{
return EOF; // malformed.
}
}
// Render an array to text
int
aJsonStream::printArray(aJsonObject *item)
{
if (item == NULL)
{
//nothing to do
return 0;
}
aJsonObject *child = item->child;
if (this->print('[') == EOF)
{
return EOF;
}
while (child)
{
if (this->printValue(child) == EOF)
{
return EOF;
}
child = child->next;
if (child)
{
if (this->print(',') == EOF)
{
return EOF;
}
}
}
if (this->print(']') == EOF)
{
return EOF;
}
return 0;
}
// Build an object from the text.
int
aJsonStream::parseObject(aJsonObject *item, char** filter)
{
int in = this->getch();
if (in != '{')
{
return EOF; // not an object!
}
item->type = aJson_Object;
this->skip();
//check for an empty object
in = this->getch();
if (in == '}')
{
return 0; // empty object.
}
//preserve the char for the next parser
this->ungetch(in);
aJsonObject* child;
char first = -1;
while ((first) || (in == ','))
{
aJsonObject* new_item = aJsonClass::newItem();
if (new_item == NULL)
{
return EOF; // memory fail
}
if (first)
{
first = 0;
item->child = new_item;
}
else
{
child->next = new_item;
new_item->prev = child;
}
child = new_item;
this->skip();
if (this->parseString(child) == EOF)
{
return EOF;
}
this->skip();
child->name = child->valuestring;
child->valuestring = NULL;
in = this->getch();
if (in != ':')
{
return EOF; // fail!
}
// skip any spacing, get the value.
this->skip();
if (this->parseValue(child, filter) == EOF)
{
return EOF;
}
this->skip();
in = this->getch();
}
if (in == '}')
{
return 0; // end of array
}
else
{
return EOF; // malformed.
}
}
// Render an object to text.
int
aJsonStream::printObject(aJsonObject *item)
{
if (item == NULL)
{
//nothing to do
return 0;
}
aJsonObject *child = item->child;
if (this->print('{') == EOF)
{
return EOF;
}
while (child)
{
if (this->printStringPtr(child->name) == EOF)
{
return EOF;
}
if (this->print(':') == EOF)
{
return EOF;
}
if (this->printValue(child) == EOF)
{
return EOF;
}
child = child->next;
if (child)
{
if (this->print(',') == EOF)
{
return EOF;
}
}
}
if (this->print('}') == EOF)
{
return EOF;
}
return 0;
}
// Get Array size/item / object item.
unsigned char
aJsonClass::getArraySize(aJsonObject *array)
{
aJsonObject *c = array->child;
unsigned char i = 0;
while (c)
i++, c = c->next;
return i;
}
aJsonObject*
aJsonClass::getArrayItem(aJsonObject *array, unsigned char item)
{
aJsonObject *c = array->child;
while (c && item > 0)
item--, c = c->next;
return c;
}
aJsonObject*
aJsonClass::getObjectItem(aJsonObject *object, const char *string)
{
aJsonObject *c = object->child;
while (c && strcasecmp(c->name, string))
c = c->next;
return c;
}
// Utility for array list handling.
void
aJsonClass::suffixObject(aJsonObject *prev, aJsonObject *item)
{
prev->next = item;
item->prev = prev;
}
// Utility for handling references.
aJsonObject*
aJsonClass::createReference(aJsonObject *item)
{
aJsonObject *ref = newItem();
if (!ref)
return 0;
memcpy(ref, item, sizeof(aJsonObject));
ref->name = 0;
ref->type |= aJson_IsReference;
ref->next = ref->prev = 0;
return ref;
}
// Add item to array/object.
void
aJsonClass::addItemToArray(aJsonObject *array, aJsonObject *item)
{
aJsonObject *c = array->child;
if (!item)
return;
if (!c)
{
array->child = item;
}
else
{
while (c && c->next)
c = c->next;
suffixObject(c, item);
}
}
void
aJsonClass::addItemToObject(aJsonObject *object, const char *string,
aJsonObject *item)
{
if (!item)
return;
if (item->name)
free(item->name);
item->name = strdup(string);