-
Notifications
You must be signed in to change notification settings - Fork 1
/
XBMCMain.usp
executable file
·5990 lines (5289 loc) · 156 KB
/
XBMCMain.usp
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
/*******************************************************************************************
SIMPL+ Module Information
(Fill in comments below)
*******************************************************************************************/
/*
Module Name: XBMCMain
Module Version: 1.0
Programmer: Neil Carthy (arduino@scpgwiki.com)
Comments:
Module Sections:
1) Constants
2) Signals
3) Parameters
4) Global Variables
5) "StoredStrings" - A temporary storage of json strings received from Xbmc.
6) "Jsmn" - Pronounced 'jasmine'. Low level JSON parsing. Populates Tokens array.
7) "JsonReader" - Combines StoredStrings and Tokens to generate meaningful data.
8) ListContext - Functions to manage Browse lists with 'Back' functionality
9) Socket Functions - Socket IO, except the SocketReceive event.
10) XBMC Response logic - functions that handle Xbmc queries and responses and UI stuff
11) Eventhandlers - PUSH, RELEASE, CHANGE event handlers including SocketReceive
12) Function Main()
***** License *****
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***** ******* *****
***** Jsmn License *****
Copyright (c) 2010 Serge A. Zaitsev
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.
***** ******* *****
A note on the replacement of '%d}' and '%s}' with '%d }' and '%s }'
(NOTE THE SPACE) in MAKESTRING function calls.
There is a bug in the Series 3 firmware that is having issue with the curly brackets
in MAKESTRING. It has been confirmed with TB Support. It can be worked around
by replacing instances of a format specifier and a '}' with
format specifier a space and then a '}.
This has been confirmed on the following
CP3, firmware version 1.005.0015
MC3, firmware version unknown
Reported by Josh Haskell.
*/
#SYMBOL_NAME "XBMCMain"
#CATEGORY "41" // Remote System Interface
#HINT "Use the XBMC JSON-RPC interface to Browse/Control XBMC."
/////////////////////Compiler Directives
#PRINT_TO_TRACE
#ENABLE_DYNAMIC
#DEFAULT_VOLATILE
#ENABLE_STACK_CHECKING
#ENABLE_TRACE
#OUTPUT_SHIFT 7 // Shift the outputs down 7 lines on the SIMPL window
/***** DEFINE NEW CONSTANTS *******/
#DEFINE_CONSTANT DEBUG 1 // Uncomment this to see debug messages
#DEFINE_CONSTANT MAX_FILENAME_LENGTH 250
#DEFINE_CONSTANT MAX_SERIAL_STRING_LENGTH 250 // (equals 255 minus 5 characters for a delimiter)
#DEFINE_CONSTANT BUFFER_SIZE 20000 // Socket buffer size
#DEFINE_CONSTANT STORED_STRING_SIZE 1000 // Size of each string in the temporary string store
#DEFINE_CONSTANT STORED_STRING_RET_SIZE 10000 // The maximum size of strings that can be outputted from the store
//Useful characters that we'll need in parsing metadata
#DEFINE_CONSTANT CR 0x0D // Carriage return
#DEFINE_CONSTANT LF 0x0A // Linefeed
#DEFINE_CONSTANT TAB 0x09 // Tab
#DEFINE_CONSTANT SPACE 0x20 // Space
#DEFINE_CONSTANT DBLQUOTE 0x22 // "
#DEFINE_CONSTANT BACKSLASH 0x5C // \
// Request IDs
#DEFINE_CONSTANT REQUESTID_GETACTIVEPLAYERS 1
#DEFINE_CONSTANT REQUESTID_PLAYER_GETITEM 2
#DEFINE_CONSTANT REQUESTID_PLAYER_GETITEMEXTENDED 3
#DEFINE_CONSTANT REQUESTID_PLAYER_GETPROPERTIES 4
#DEFINE_CONSTANT REQUESTID_VIDEOLIBRARY_GETMOVIES 20
#DEFINE_CONSTANT REQUESTID_VIDEOLIBRARY_GETMOVIEDETAILS 21
#DEFINE_CONSTANT REQUESTID_VIDEOLIBRARY_GETTVSHOWS 22
#DEFINE_CONSTANT REQUESTID_VIDEOLIBRARY_GETTVSEASONS 23
#DEFINE_CONSTANT REQUESTID_VIDEOLIBRARY_GETTVEPISODES 24
#DEFINE_CONSTANT REQUESTID_VIDEOLIBRARY_GETEPISODEDETS 25
#DEFINE_CONSTANT REQUESTID_AUDIOLIBRARY_GETARTISTS 26
#DEFINE_CONSTANT REQUESTID_AUDIOLIBRARY_GETALBUMS 27
#DEFINE_CONSTANT REQUESTID_AUDIOLIBRARY_GETSONGS 28
#DEFINE_CONSTANT REQUESTID_AUDIOLIBRARY_GETSONGDETAILS 29
#DEFINE_CONSTANT REQUESTID_AUDIOLIBRARY_GETARTISTALBUMS 30
#DEFINE_CONSTANT REQUESTID_AUDIOLIBRARY_GETGENRES 31
#DEFINE_CONSTANT REQUESTID_AUDIOLIBRARY_GETGENREARTISTS 32
#DEFINE_CONSTANT REQUESTID_PLAYLIST_CLEARAUDIO 40
#DEFINE_CONSTANT REQUESTID_PLAYLIST_CLEARVIDEO 41
#DEFINE_CONSTANT REQUESTID_PLAYLIST_ADD 42
#DEFINE_CONSTANT REQUESTID_PLAYER_OPEN 43
#DEFINE_CONSTANT REQUESTID_SKIPNEXT 50
#DEFINE_CONSTANT REQUESTID_SKIPPREV 51
#DEFINE_CONSTANT REQUESTID_SMALLSKIPFORWARD 52
#DEFINE_CONSTANT REQUESTID_SMALLSKIPBACKWARD 53
#DEFINE_CONSTANT REQUESTID_LARGESKIPFORWARD 54
#DEFINE_CONSTANT REQUESTID_LARGESKIPBACKWARD 55
#DEFINE_CONSTANT REQUESTID_VIDEOLIBRARY_SCAN 56
#DEFINE_CONSTANT REQUESTID_AUDIOLIBRARY_SCAN 57
#DEFINE_CONSTANT REQUESTID_SEEKTIME 58
#DEFINE_CONSTANT REQUESTID_SEEKPERCENTAGE 59
#DEFINE_CONSTANT REQUESTID_INPUT_CONTEXTMENU 60
#DEFINE_CONSTANT REQUESTID_GETADDONS 70
#DEFINE_CONSTANT REQUESTID_GETADDONDETAILS 71
#DEFINE_CONSTANT REQUESTID_VERSION 99
#DEFINE_CONSTANT REQUESTID_PING 100
/* Types of playing media, output via Currently_Playing_Type*/
#DEFINE_CONSTANT TYPE_NONE 0
#DEFINE_CONSTANT TYPE_MOVIE 1
#DEFINE_CONSTANT TYPE_AUDIO 2
#DEFINE_CONSTANT TYPE_SERIES 3
#DEFINE_CONSTANT TYPE_PICTURES 4
#DEFINE_CONSTANT TYPE_OTHERVIDEO 5
/* Types of List */
#DEFINE_CONSTANT MOVIE_TITLE_LIST 1
#DEFINE_CONSTANT TV_SHOW_LIST 2
#DEFINE_CONSTANT TV_SEASON_LIST 3
#DEFINE_CONSTANT TV_EPISODE_LIST 4
#DEFINE_CONSTANT MUSIC_ARTIST_LIST 5
#DEFINE_CONSTANT MUSIC_ALBUM_LIST 6
#DEFINE_CONSTANT MUSIC_SONG_LIST 7
#DEFINE_CONSTANT MUSIC_GENRE_LIST 8
#DEFINE_CONSTANT MUSIC_ARTIST_ALBUM_LIST 9 // AllSongs & Albums
#DEFINE_CONSTANT MUSIC_GENRE_ARTIST_LIST 10 // AllArtists & Artists
#DEFINE_CONSTANT HOME_LIST 20
#DEFINE_CONSTANT MUSIC_LIST 21
#DEFINE_CONSTANT PICTURE_LIST 22
#DEFINE_CONSTANT ADDON_LIST 23
#DEFINE_CONSTANT SPECIAL_SEASON 65535
/* Types of XBMC Playlist/Player type */
#DEFINE_CONSTANT XBMC_ACTIVEPLAYER_NONE 255
#DEFINE_CONSTANT XBMC_ACTIVEPLAYER_AUDIO 0
#DEFINE_CONSTANT XBMC_ACTIVEPLAYER_VIDEO 1
#DEFINE_CONSTANT XBMC_ACTIVEPLAYER_SLIDESHOW 2
/*******************************************************************************************
DIGITAL, ANALOG and SERIAL INPUTS and OUTPUTS
(Uncomment and declare inputs and outputs as needed)
*******************************************************************************************/
DIGITAL_OUTPUT IsConnected,
Loading, // HIGH when a JSON reply is being received;
_SKIP_, MovieDetails, // HIGH when on Movie details popup
TvShowDetails, // HIGH when on Episode details popup
MusicDetails, // HIGH when on Album details popup
_SKIP_,PlayFb, // HIGH when something is playing
StopFb, // HIGH when playback is stopped
PauseFb, // HIGH when playback is paused
RewindFB, // HIGH when we are rewinding. (Note this is not the same as seeking)
FastForwardFB, // HIGH when we are fastforwarding. (Note this is not the same as seeking)
_SKIP_,ScreensaverActive, // HIGH when screensaver is active
ShuffleStatus, // HIGH when playlist is being shuffled
Watched[10]; // HIGH when item has already been watched, i.e. when Playcount>0
ANALOG_OUTPUT _SKIP_,VersionID#, // The version id of the JSON api. 4 = Eden, 6 = Frodo
CurrentlyPlayingType, // 1 = movie, 2 = audio, 3 = tv, 4= picture, 5 = other video
CurrentList, // The ID of the current list
Position_Seconds, // Position in track in seconds
Duration_Seconds, // Total length of track in seconds
ScrollBarPercentage#,// Percentage (0-99) user has moved through the media list (feedback for scroll bar)
NumberAudioStreams, // Number of audio streams in movie/episode
NumberSubtitleStreams, // Number of subtitle streams in movie/episode
RepeatStatus; // 0 = 'off', 1 = 'all', 2 = 'one'
STRING_OUTPUT _SKIP_,
PlotSelected$, // The plot of the Selected movie or TV showList_Summary$
List_Summary$,_SKIP_, // e.g. "7 to 12 of 15"
CurrentFilename$, // The file name of the currently playing track
CurrentTitle$,_SKIP_, // The name of the current track
CurrentCoverArt$, // The uri of the coverart for the current track
CurrentGenre$, // Music/Movie genre
CurrentStudio$, // Movie studio
CurrentDirector$, // The movie director's name.
CurrentWriter$, // Movie writer
CurrentTagLine$, // Movie tag line
CurrentRating$, // imdb rating
CurrentMPAA$, // MPAA rating
CurrentYear$, // The year the song/movie was released
CurrentShowTitle$, // TV Show title
CurrentSeason$, // TV Show season
CurrentEpisode$, // TV Show episode
CurrentFirstAired$,_SKIP_, // TV Show first aired date
CurrentTrackNumber$, // The track number
CurrentArtist$, // The artist of the current track
CurrentAlbum$, // The album of the current track
CurrentAudioBitRate$, // audio bitrate
CurrentAudioCodec$, // audio codec
CurrentAudioChannels$, // Number of Channels
CurrentAudioLanguage$, // Current Language
CurrentVideoCodec$, // video codec
CurrentVideoAspect$, // video aspect ratio
CurrentVideoHeight$, // video picture height
CurrentVideoWidth$,_SKIP_, // video picture width
NextTitle$, // Metadata about next item on playlist
NextArtist$, // Metadata about next item on playlist
NextGenre$, // Metadata about next item on playlist
NextAlbum$, // Metadata about next item on playlist
NextTrackNumber$, // Metadata about next item on playlist
PlayingSpeed$, // Speed of current audio/video playback (1x, 2x, 4x etc.)
_SKIP_;
ANALOG_OUTPUT Runtime[10]; // Number of seconds for each track/movie
STRING_OUTPUT Title$[10],
Year$[10],
Genre$[10],
Rating$[10],
Director$[10],
Tagline$[10],
Thumb$[10],
Writer$[10],
EpisodeOrTrackNum$[10],
SeasonOrAlbumName$[10],
Studio$[10],
MPAA$[10],
SeriesOrArtistName$[10],
Fanart$[10],
Filename$[10],
Banner$[10],
PlotDescription$[10];
DIGITAL_INPUT _SKIP_,_SKIP_,_SKIP_,_SKIP_,_SKIP_,_SKIP_,_SKIP_;
DIGITAL_INPUT Connect; // When HIGH connect to the XBMC tcp socket.
/* Browse functionality */
DIGITAL_INPUT _SKIP_,_SKIP_,
Poll, // Poll Xbmc for metadata about currently playing track
_SKIP_,_SKIP_,
List_RecentItems, // When HIGH only show recently added Movies/Albums
List_UnWatchedOnly, // When HIGH only show unwatched Movies/TvShows
List_TopPage, // Go to 1st page
List_BottomPage, // Go to last page
List_PageMinus, // Go back one page
List_PagePlus, // Go forward one page
List_Back, // Return to previous list
List_Home, // Go to the Home list
List_Movies, // Show movies list
List_Albums, // Show music albums list
List_TVShows, // Show TV shows list
List_Artists, // Show music artists list
List_Pictures, // Show Pictures list
List_Addons, // Show Addons list
List_Exit_Details_Page,
_SKIP_,
PlayNext,
PlayPrev,
JumpFwd_Sm,
JumpBack_Sm,
JumpFwd_Lg,
JumpBack_Lg,
_SKIP_,UpdateMovies,
UpdateMusic,
ContextMenu;
DIGITAL_INPUT _SKIP_,RunAllTests; // Run all unit tests. Only works in DEBUG
STRING_INPUT _SKIP_,SearchCriteria$[100]; // Filter String
ANALOG_INPUT _SKIP_,PlayItem, // Begin playing this listitem
SelectedItem, // We have selected this listitem
Seek_Percentage, Seek_Time, // Seek to this %age, time.
_SKIP_,UnitTestNumber#; // Run the specified unit test. DEBUG only.
///////////////////////////// Parameters
STRING_PARAMETER XBMC_IPAddr$[16]; //the ip of the XBMC server.
STRING_PARAMETER XBMC_HttpPort$[5]; //the port that the XBMC server lives on
INTEGER_PARAMETER StepAmount; // Only return this many results from database at a time
STRING_PARAMETER XBMC_TcpPort$[5]; //the port that the XBMC server lives on
/*******************************************************************************************
Parameter Properties
(Uncomment and declare parameter properties as needed)
*******************************************************************************************/
#BEGIN_PARAMETER_PROPERTIES XBMC_IPAddr$
propDefaultValue = "";
propShortDescription = "The IP Address of the XBMC HTTP server.";
#END_PARAMETER_PROPERTIES
#BEGIN_PARAMETER_PROPERTIES XBMC_HttpPort$
propDefaultValue = "";
propShortDescription = "The port that the XBMC HTTP server is listening on. (NOT the tcp server)";
#END_PARAMETER_PROPERTIES
#BEGIN_PARAMETER_PROPERTIES StepAmount
propValidUnits = unitDecimal;
propDefaultUnit = unitDecimal;
propDefaultValue = 10d;
propShortDescription = "Only return this many results from database at a time.";
#END_PARAMETER_PROPERTIES
#BEGIN_PARAMETER_PROPERTIES XBMC_TcpPort$
propDefaultValue = "";
propShortDescription = "The port that the XBMC JSON TCP server is listening on. (NOT the httpp server) (usu 9090)";
#END_PARAMETER_PROPERTIES
/*******************************************************************************************
SOCKETS
*******************************************************************************************/
TCP_CLIENT XBMC[BUFFER_SIZE]; // Socket for connecting to XBMC on TCP port 9090
/*******************************************************************************************
GLOBAL VARIABLES
*******************************************************************************************/
SIGNED_INTEGER ConnectionStatus; // Status of XBMC socket, used to determine if
// the Connect event needs to reconnect or do nothing.
INTEGER SocketLock; // Locking flag that is set before any socket activity are submitted
INTEGER ReceiveLock; // Locking flag that is set when processing data from Xbmc
STRING Remainder$[4000]; // Store unprocessed bytes from 1st pass of ProcessResponse()
INTEGER VersionID; // The JSON-RPC protocol version. 4 for Eden, 6 for Frodo
INTEGER ActivePlayerID; // The ID of the current active player. Zero for none.
SIGNED_INTEGER PlaySpeed; // Speed of current audio/video playback (1x, 2x, 4x etc.) Negative for rewind.
INTEGER IsPlaying; // 1 = Something is playing, 0 = nothing is playing
STRING PlayingItemType$[10]; // e.g. 'song', 'movie' etc.
INTEGER PlayingItemId; // id of current item
INTEGER NextItemId; // id of next item
INTEGER PlaylistPosition; // position in active playlist
DYNAMIC INTEGER Playlist[25]; // An array of the item IDs in the active playlist
INTEGER ListIDs[10]; // A store of the IDs of objects in current list
INTEGER ListIndex; // The index of the current object within the list
INTEGER ListTotal; // Total number of items in list (limits.total)
STRING AddonIDs[10][40]; // A store of AddonIDs
STRING HomeListItems$[4][8]; // Labels for the Home List
STRING MusicListItems$[3][7]; // Labels for the Music List
/*******************************************************************************************
"StoredStrings"
A temporary storage of json strings received from Xbmc. These stored strings,
together with the array of tokens are then used to decode the JSON into useful data.
The strings are stored in a 2D array to get around the string size limit of 65535 characters
*******************************************************************************************/
STRUCTURE StoredStringPosition
{
// These are both zero-based even though strings are 1-based
INTEGER listIndex; //The number of the current array
INTEGER arrayPosition; //The position we have got to in the current array
};
DYNAMIC STRING StoredStrings[1][STORED_STRING_SIZE];
StoredStringPosition Store;
// Update the StoredStringPosition structure after a string has
// been added to the StoredStrings array
FUNCTION Store_RecalculatePosition(INTEGER value)
{
Store.arrayPosition = Store.arrayPosition + value;
if (Store.arrayPosition = STORED_STRING_SIZE)
{
Store.listIndex = Store.listIndex+1;
Store.arrayPosition = 0;
IF (Store.listIndex > GetNumArrayRows(StoredStrings))
ResizeArray(StoredStrings,Store.listIndex+1,STORED_STRING_SIZE);
}
}
FUNCTION Store_Store(STRING stringToAdd$, INTEGER numberOfBytes)
{
INTEGER length;
INTEGER spareBytesInCurrentArray;
INTEGER lengthToCopy;
length = numberOfBytes;
spareBytesInCurrentArray = STORED_STRING_SIZE - Store.arrayPosition;
lengthToCopy = MIN(length, spareBytesInCurrentArray);
SETSTRING(LEFT(stringToAdd$,lengthToCopy)
,Store.arrayPosition+1
,StoredStrings[Store.listIndex]);
length = length - lengthToCopy;
Store_RecalculatePosition(lengthToCopy);
WHILE (length)
{
lengthToCopy = MIN(length, STORED_STRING_SIZE);
SETSTRING(MID(stringToAdd$,numberOfBytes-length+1,lengthToCopy)
,1
,StoredStrings[Store.listIndex]);
length = length - lengthToCopy;
Store_RecalculatePosition(lengthToCopy);
}
}
// start cannot be less than 1
STRING_FUNCTION Store_RetrieveByLength(LONG_INTEGER start, INTEGER length)
{
INTEGER numberBytes;
STRING s$[STORED_STRING_RET_SIZE];
StoredStringPosition pStart;
LONG_INTEGER remainder;
INTEGER lengthToCopy;
if (start = 0)
{
GenerateUserError("In Store_Retrieve: start cannot be zero");
RETURN ("");
}
start = start-1;
numberBytes = length;
if (start < STORED_STRING_SIZE)
{
pStart.listIndex = 0;
pStart.arrayPosition = LowWord(start);
}
else
{
remainder = start MOD STORED_STRING_SIZE;
pStart.listIndex = (start - remainder) / STORED_STRING_SIZE;
pStart.arrayPosition = LowWord(remainder);
}
lengthToCopy = MIN(
LEN(StoredStrings[pStart.listIndex])-pStart.arrayPosition
,length);
SETSTRING(MID(StoredStrings[pStart.listIndex], pStart.arrayPosition+1, lengthToCopy)
, 1, s$);
length = length - lengthToCopy;
while (length)
{
pStart.listIndex = pStart.listIndex+1;
lengthToCopy = MIN(length, STORED_STRING_SIZE);
SETSTRING(MID(StoredStrings[pStart.listIndex], 1, lengthToCopy)
, numberBytes-length+1, s$);
length = length - lengthToCopy;
}
return (s$);
}
// start cannot be less than 1
STRING_FUNCTION Store_Retrieve(LONG_INTEGER start, LONG_INTEGER end)
{
RETURN (Store_RetrieveByLength(start,LowWord(end-start)));
}
/*******************************************************************************************
"Jsmn" (http://zserge.com/jsmn.html)
jsmn (pronounced like 'jasmine') is a minimalistic JSON parser in C.
It splits JSON string into tokens. Let's consider a JSON string:
"{ "name" : "Jack", "age" : 27 }"
jsmn will split it into the following tokens:
Object: { "name" : "Jack", "age" : 27} (the whole object)
Strings: "name", "Jack", "age" (keys and some values)
Number: 27
The key idea is that jsmn tokens do not hold any data, but just point
to the token boundaries in JSON string instead.
*******************************************************************************************/
#DEFINE_CONSTANT JSMN_ERROR_NOMEM -1 //Not enough tokens were provided
#DEFINE_CONSTANT JSMN_ERROR_INVAL -2 //Invalid character inside JSON string. Fatal.
#DEFINE_CONSTANT JSMN_ERROR_PART -3 //The string is not a full JSON packet, more bytes expected
#DEFINE_CONSTANT JSMN_SUCCESS 0 //Everything was fine
#DEFINE_CONSTANT JSMN_PRIMITIVE 0 //Number, Null or True/False
#DEFINE_CONSTANT JSMN_OBJECT 1 //An object {...}
#DEFINE_CONSTANT JSMN_ARRAY 2 //An Array [...]
#DEFINE_CONSTANT JSMN_STRING 3 //A string "..."
INTEGER tokenCount; // Number of filled tokens
/*
* JSON parser. Contains an array of token blocks available. Also stores
* the string being parsed now and current position in that string
*/
STRUCTURE JsmnParser
{
LONG_INTEGER pos; // offset in the JSON string.
INTEGER toknext; //next token to allocate
SIGNED_INTEGER toksuper; //superior token node, e.g parent object or array
LONG_INTEGER currpos; //Starting position of smaller string in larger string
};
/*
* Jsmn token. Does not hold any data, but just points
* to the token boundaries in JSON string instead.
*/
STRUCTURE JsmnToken
{
INTEGER type; // One of JSMN_PRIMITIVE, JSMN_OBJECT, JSMN_ARRAY, JSMN_STRING
LONG_INTEGER start; //start position in JSON data string. 1-based
LONG_INTEGER end; //end position in JSON data string
INTEGER size; //Number of characters in token
SIGNED_INTEGER parent; //Token number of parent
};
DYNAMIC JsmnToken Tokens[10]; // Array of tokens, initially 10-long
JsmnParser parser;
/**
* Fills token type and boundaries.
*/
FUNCTION Jsmn_Fill_Token(JsmnToken token, INTEGER type,
LONG_INTEGER start, LONG_INTEGER end)
{
token.type = type;
token.start = start;
token.end = end;
token.size = 0;}
/**
* Resets the module-level parser to an i nitialized state.
*/
FUNCTION Jsmn_Init()
{
parser.pos = 1;
parser.toknext = 0;
parser.toksuper = -1;
parser.currpos = 0;
tokenCount = 0;
}
/**
* Allocates a fresh unused token from the token pool.
*/
SIGNED_INTEGER_FUNCTION Jsmn_Alloc_Token(INTEGER num_tokens)
{
if (parser.toknext >= num_tokens)
{
return (JSMN_ERROR_NOMEM);
}
tokens[parser.toknext].start = 0;
tokens[parser.toknext].end = 0;
tokens[parser.toknext].size = 0;
tokens[parser.toknext].parent = -1;
tokenCount = parser.toknext;
parser.toknext = parser.toknext + 1;
return (parser.toknext-1);
}
/*
* Return an Error, recording current state.
*/
INTEGER_FUNCTION Jsmn_Error(SIGNED_INTEGER r)
{
if (r != JSMN_ERROR_NOMEM)
parser.currpos = parser.pos;
return (r);
}
/**
* Fills next available token with JSON primitive.
*/
SIGNED_INTEGER_FUNCTION Jsmn_Parse_Primitive(STRING js, INTEGER num_bytes, INTEGER num_tokens)
{
JsmnToken token;
LONG_INTEGER start;
INTEGER i;
INTEGER c;
SIGNED_INTEGER token_num;
INTEGER found;
found =0;
start = parser.pos - parser.currpos;
for (i = start to num_bytes)
{
c = byte(js, LowWord(parser.pos - parser.currpos)); //extract a char
//PRINT("PP char: %c, parser.pos %ld, num_bytes %d, parser.currpos %ld",c, parser.pos, num_bytes, parser.currpos);
switch (c)
{
// Unlike in a CSWITCH, BREAK in a SWITCH exits both the SWITCH and the FOR loop
case (TAB): {found = 1; break;}
case (CR): {found = 1; break;}
case (LF): {found = 1; break;}
case (SPACE): {found = 1; break;}
case (','): {found = 1; break;}
case (']'): {found = 1; break;}
case ('}'): {found = 1; break;}
case ('['):
return (JSMN_ERROR_INVAL);
case ('{'):
return (JSMN_ERROR_INVAL);
case (DBLQUOTE):
return (JSMN_ERROR_INVAL);
case (c < 32 || c >= 127):
return (JSMN_ERROR_INVAL);
}
parser.pos = parser.pos +1;
}
IF (found=0)
{
/* In strict mode primitive must be followed by a comma/object/array */
parser.pos = start;
return (JSMN_ERROR_PART);
}
token_num = Jsmn_Alloc_Token(num_tokens);
if (token_num < 0)
{
parser.pos = start;
return (JSMN_ERROR_NOMEM);
}
Jsmn_Fill_Token(Tokens[token_num], JSMN_PRIMITIVE, start + parser.currpos, parser.pos);
Tokens[token_num].parent = parser.toksuper;
parser.pos = parser.pos - 1;
return (JSMN_SUCCESS);
}
/**
* Fills next token with JSON string.
*/
SIGNED_INTEGER_FUNCTION Jsmn_Parse_String(STRING js, INTEGER num_bytes, INTEGER num_tokens)
{
INTEGER i;
LONG_INTEGER start;
INTEGER c;
SIGNED_INTEGER token_num;
// Return immediately if there are no characters left in the string
IF (parser.pos-parser.currpos = num_bytes)
{
parser.pos = parser.pos;
return (JSMN_ERROR_PART);
}
ELSE
{
// Skip starting quote
parser.pos = parser.pos + 1;
start = parser.pos - parser.currpos;
}
// Loop through each byte in the string
FOR (i = start TO num_bytes)
{
c = byte(js, LowWord(parser.pos - parser.currpos)); //extract a char
//PRINT("PS char: %c, parser.pos %ld, start %ld, parser.currpos %ld",c, parser.pos, start, parser.currpos);
/* Quote: end of string */
IF (c = DBLQUOTE)
{
token_num = jsmn_alloc_token(num_tokens);
if (token_num < 0)
{
parser.pos = start-1;
return (JSMN_ERROR_NOMEM);
}
Jsmn_Fill_Token(Tokens[token_num], JSMN_STRING, start + parser.currpos, parser.pos);
Tokens[token_num].parent = parser.toksuper;
return (JSMN_SUCCESS);
}
/* Backslash: Quoted symbol expected */
ELSE if (c = BACKSLASH)
{
/* Must check that this is still within the bounds of the string */
parser.pos = parser.pos+1;
IF(LowWord(parser.pos - parser.currpos)>num_bytes)
{
parser.pos = start + parser.currpos;
return (JSMN_ERROR_PART);
}
// Switch on the next byte
c = byte(js, LowWord(parser.pos - parser.currpos));
cswitch (c)
{
/* Allowed escaped symbols */
case (DBLQUOTE): { break; }
case ('/'): { break; }
case (BACKSLASH): { break; }
case ('b'): { break; }
case ('f'): { break; }
case ('r'): { break; }
case ('n'): { break; }
case ('t'): { break; }
/* Allows escaped symbol \uXXXX */
case ('u'):
/* TODO */
{ break; }
/* Unexpected symbol */
default:
{
parser.pos = start + parser.currpos;
return (JSMN_ERROR_INVAL);
}
}
// Increment counter to skip next character
i = i + 1;
}
parser.pos = parser.pos + 1;
}
parser.pos = start-1;
return (JSMN_ERROR_PART);
}
/**
* Parse JSON string and fill tokens.
*/
SIGNED_INTEGER_FUNCTION Jsmn_Parse(STRING js, INTEGER num_bytes,
INTEGER num_tokens)
{
SIGNED_INTEGER r; // response
INTEGER i; //loop var
INTEGER c; // char
INTEGER type; // One of JSMN_PRIMITIVE, JSMN_OBJECT, JSMN_ARRAY, JSMN_STRING
SIGNED_INTEGER token_num;
FOR (i = 1 to num_bytes)
{
c = byte(js, LowWord(parser.pos - parser.currpos)); //extract a char
//PRINT("char: %c (%d), parser.pos %ld, num_bytes %d, parser.currpos %ld",c,c, parser.pos, num_bytes, parser.currpos);
IF (c = '{' || c = '[')
{
token_num = jsmn_alloc_token(num_tokens);
if (token_num < 0)
return (JSMN_ERROR_NOMEM);
if (parser.toksuper != -1)
{
tokens[parser.toksuper].size = tokens[parser.toksuper].size + 1;
tokens[token_num].parent = parser.toksuper;
}
IF (c = '{')
tokens[token_num].type = JSMN_OBJECT;
ELSE
tokens[token_num].type = JSMN_ARRAY;
tokens[token_num].start = parser.pos;
parser.toksuper = parser.toknext - 1;
}
ELSE IF (c = '}' || c = ']')
{
IF (c = '}')
type = JSMN_OBJECT;
ELSE
type = JSMN_ARRAY;
IF (parser.toknext < 1)
return (Jsmn_Error(JSMN_ERROR_INVAL));
token_num = parser.toknext - 1;
while (1)
{
if (tokens[token_num].start != 0 && tokens[token_num].end = 0)
{
if (tokens[token_num].type != type)
return (Jsmn_Error(JSMN_ERROR_INVAL));
tokens[token_num].end = parser.pos+1;
parser.toksuper = tokens[token_num].parent;
if (tokens[token_num].parent = -1)
return (JSMN_SUCCESS);
break;
}
if (tokens[token_num].parent = -1)
{
break;
}
token_num = tokens[token_num].parent;
}
}
ELSE IF (c = DBLQUOTE)
{
r = Jsmn_Parse_String(js, num_bytes, num_tokens);
i = LowWord(parser.pos - parser.currpos);
if (r < 0)
return (Jsmn_Error(r));
if (parser.toksuper != -1)
tokens[parser.toksuper].size = tokens[parser.toksuper].size + 1;
}
ELSE IF (c = TAB || c = CR || c = LF || c = ':' || C = ',' || C = SPACE)
{
//Do Nothing.
}
ELSE IF (c = '-' || (c >= 46 && c <= 57) || c = 't' || c = 'f' || c = 'n')
{
/* In strict mode primitives can only be numbers, booleans or null */
r = jsmn_parse_primitive(js, num_bytes, num_tokens);
i = LowWord(parser.pos - parser.currpos);
if (r < 0)
{
return (Jsmn_Error(r));
}
if (parser.toksuper != -1)
tokens[parser.toksuper].size = tokens[parser.toksuper].size+1;
}
ELSE
{
/* Unexpected char in strict mode */
return (Jsmn_Error(JSMN_ERROR_INVAL));
}
//PRINT("i: %d, parser.pos %ld, num_bytes: %d", i, parser.pos, num_bytes);
parser.pos = parser.pos + 1;
}
for (i = parser.toknext - 1 TO 0 STEP -1)
{
/* Unmatched opened object or array */
if (tokens[i].start != 0 && tokens[i].end = 0)
return (Jsmn_Error(JSMN_ERROR_PART));
}
return (JSMN_SUCCESS);
}
/**
* Parse JSON string and fill tokens by repeatedly calling Jsmn_Parse.
* Supply new tokens if receive NoMem error
* Return the error/success code if not a NoMem error
*/
SIGNED_INTEGER_FUNCTION Jsmn_Tokenize(STRING js, INTEGER num_bytes)
{
SIGNED_INTEGER r;
INTEGER num_tokens;
num_tokens = GetNumStructureArrayCols(Tokens);
r = Jsmn_Parse(js, num_bytes, num_tokens);
while (r = JSMN_ERROR_NOMEM)
{
num_tokens = GetNumStructureArrayCols(Tokens);
ResizeStructureArray(Tokens, num_tokens*2+1);
r = Jsmn_Parse(js, num_bytes, num_tokens);
}
return (r);
}
/*******************************************************************************************
"JsonReader"
This section of the document combines the string information in 'StoredStrings' with
the JSON structure information in the tokens to actually generate meaningful data.
*******************************************************************************************/
INTEGER tokenIndex; // index (number) of current token
INTEGER_FUNCTION Read()
{
if (tokenIndex >= tokenCount)
RETURN (0);
ELSE
{
tokenIndex = tokenIndex + 1;
RETURN (1);
}
}
STRING_FUNCTION GetString()
{
RETURN (Store_Retrieve(tokens[tokenIndex].start, tokens[tokenIndex].end));
}
INTEGER_FUNCTION GetInteger()
{
RETURN (AtoI(GetString()));
}
LONG_INTEGER_FUNCTION GetLong()
{
RETURN (AtoL(GetString()));
}
INTEGER_FUNCTION GetBool()
{
STRING value$[5];
value$ = LOWER(GetString());
IF (value$ = "true")
RETURN (ON);
ELSE
RETURN (OFF);
}
SIGNED_INTEGER_FUNCTION GetSignedInteger()
{
STRING number$[20];
number$ = GetString();
IF (LEFT(number$,1) = "-")
RETURN (-AtoI(number$));
ELSE
RETURN (AtoI(number$));
}
/*
* Return the contents of a string array as a single string
*/
STRING_FUNCTION GetStringArray()
{
STRING value$[500];
INTEGER i;
INTEGER numberArrayItems;
numberArrayItems = tokens[tokenIndex].size;
IF (tokens[tokenIndex].type = JSMN_ARRAY && numberArrayItems)
{
Read();
value$ = GetString();
FOR (i = 2 TO numberArrayItems)
{
Read();
MAKESTRING(value$,"%s, %s", value$, GetString());
}
RETURN (value$);
}
ELSE
RETURN ("[]");
}
/*
* Reset all internal variables connected with JSON parsing to a clean state
*/
FUNCTION Init()
{
INTEGER i;
// Reset StoredStrings
FOR (i = 0 TO GetNumArrayRows(StoredStrings))
{
StoredStrings[i] = "";
}
Store.listIndex = 0;
Store.arrayPosition = 0;
// Reset Jsmn Parser
Jsmn_Init();