/
particle_core.cpp
3970 lines (3355 loc) · 106 KB
/
particle_core.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
#include "particle_core.h"
//#include <Arduino.h>
#include "../ESP8266WiFi/src/ESP8266WiFi.h"
#include "handshake.h"
#include "messages.h"
#include "coap.h"
#include "aes.h"
#include "rsa.h"
#include "dsakeygen.h"
#include "append_list.h"
#include "appender.h"
#include "file_transfer.h"
#include "crc32.h"
#ifdef __cplusplus
extern "C" {
#endif
#include <c_types.h>
#include <user_interface.h>
#include <mem.h>
#include <osapi.h>
#include "espmissingincludes.h"
#include "oakboot.h"
#ifdef __cplusplus
}
#endif
namespace particle_core {
#define PROTOCOL_BUFFER_SIZE 800
#define QUEUE_SIZE 800
uint8_t spark_failed_connects = 0;
bool spark_ok_to_connect = false;
//this has to be aligned
uint8_t chunk_buffer[512];
WiFiClient pClient;
static System_Mode_TypeDef system_mode = DEFAULT_MODE;
typedef unsigned short uint16_t;
typedef uint16_t chunk_index_t;
unsigned char queue[PROTOCOL_BUFFER_SIZE];
typedef struct {
//can cut off here if needed
char device_id[25]; //device id in hex
char claim_code[65]; // server public key
uint8 claimed; // server public key
uint8 device_private_key[1216]; // device private key
uint8 device_public_key[384]; // device public key
uint8 server_public_key[768]; //also contains the server address at offset 384
uint8 server_address_type; //domain or ip of cloud server
uint8 server_address_length; //domain or ip of cloud server
char server_address_domain[254]; //domain or ip of cloud server
uint8 ota_success;
uint32 server_address_ip; //[4]//domain or ip of cloud server
unsigned short firmware_version;
unsigned short system_version; //
char version_string[33]; //
uint8 reserved_flags[32]; //
uint8 reserved1[32];
uint8 product_store[24];
char ssid[33]; //ssid and terminator
char passcode[65]; //passcode and terminator
uint8 channel; //channel number
int32 third_party_id; //
char third_party_data[256]; //
char first_update_domain[65];
char first_update_url[65];
char first_update_fingerprint[60];
uint8 current_rom_scheme[1];
uint8 system_update_pending;
uint8 magic;
uint8 chksum;
//uint8 reserved2[698];
} oak_config;
struct msg {
uint8_t token;
size_t len;
uint8_t* response;
size_t response_len;
};
#define SPARK_SERVER_PORT 5683
#define USER_VAR_MAX_COUNT 10
#define USER_VAR_KEY_LENGTH 12
#define USER_FUNC_MAX_COUNT 4
#define USER_FUNC_KEY_LENGTH 12
#define USER_FUNC_ARG_LENGTH 64
#define USER_EVENT_NAME_LENGTH 64
#define USER_EVENT_DATA_LENGTH 64
#define SECTOR_SIZE 0x1000
#define DEVICE_CONFIG_SECTOR 256
#define DEVICE_BACKUP_CONFIG_SECTOR 512
#define DEVICE_CHKSUM_INIT 0xee
#define DEVICE_MAGIC 0xf0
#define DEVICE_CONFIG_SIZE 3398
#define PRIVATE_KEY_LENGTH (612)
#define PUBLIC_KEY_LENGTH (162)
/* Length in bytes of DER-encoded 2048-bit RSA public key */
#define SERVER_PUBLIC_KEY_LENGTH (294)
#define SERVER_DOMAIN_LENGTH (253)
const CloudVariableTypeBool BOOLEAN;
const CloudVariableTypeInt INT;
const CloudVariableTypeString STRING;
const CloudVariableTypeDouble DOUBLE;
uint8 config_buffer[DEVICE_CONFIG_SIZE];
oak_config *deviceConfig = (oak_config*)config_buffer;
uint8 boot_buffer[BOOT_CONFIG_SIZE];
oakboot_config *bootConfig = (oakboot_config*)boot_buffer;
volatile bool spark_connect_pending = false;
byte device_id[12];
bool spark_initialized = false;
#ifdef DEBUG_SETUP
void ERROR(String out){
Serial.println(out);
}
#endif
#ifdef DEBUG_SETUP
void INFO(String out){
Serial.println(out);
}
#endif
aes_context aes;
unsigned char key[16];
unsigned char iv_send[16];
unsigned char iv_receive[16];
unsigned char salt[8];
unsigned short _message_id;
unsigned char _token;
uint32_t last_message_millis;
uint32_t last_chunk_millis; // NB: also used to synchronize time
unsigned short chunk_index;
unsigned short chunk_size;
bool expecting_ping_ack;
bool initialized;
uint8_t updating;
struct User_Var_Lookup_Table_t
{
const void *userVar;
Spark_Data_TypeDef userVarType;
char userVarKey[USER_VAR_KEY_LENGTH+1];
const void* (*update)(const char* name, Spark_Data_TypeDef varType, const void* var, void* reserved);
};
struct User_Func_Lookup_Table_t
{
void* pUserFuncData;
cloud_function_t pUserFunc;
char userFuncKey[USER_FUNC_KEY_LENGTH];
};
User_Var_Lookup_Table_t* find_var_by_key_or_add(const char* varKey);
User_Func_Lookup_Table_t* find_func_by_key_or_add(const char* funcKey);
static append_list<User_Var_Lookup_Table_t> vars(5);
static append_list<User_Func_Lookup_Table_t> funcs(5);
FilteringEventHandler event_handlers[5];
User_Var_Lookup_Table_t* find_var_by_key(const char* varKey)
{
for (int i = vars.size(); i-->0; )
{
if (0 == strncmp(vars[i].userVarKey, varKey, USER_VAR_KEY_LENGTH))
{
return &vars[i];
}
}
return NULL;
}
User_Var_Lookup_Table_t* find_var_by_key_or_add(const char* varKey)
{
User_Var_Lookup_Table_t* result = find_var_by_key(varKey);
return result ? result : vars.add();
}
User_Func_Lookup_Table_t* find_func_by_key(const char* funcKey)
{
for (int i = funcs.size(); i-->0; )
{
if (0 == strncmp(funcs[i].userFuncKey, funcKey, USER_FUNC_KEY_LENGTH))
{
return &funcs[i];
}
}
return NULL;
}
User_Func_Lookup_Table_t* find_func_by_key_or_add(const char* funcKey)
{
User_Func_Lookup_Table_t* result = find_func_by_key(funcKey);
return result ? result : funcs.add();
}
int call_raw_user_function(void* data, const char* param, void* reserved)
{
user_function_int_str_t* fn = (user_function_int_str_t*)(data);
String p(param);
return (*fn)(p);
}
int call_std_user_function(void* data, const char* param, void* reserved)
{
user_std_function_int_str_t* fn = (user_std_function_int_str_t*)(data);
return (*fn)(String(param));
}
void call_wiring_event_handler(const void* handler_data, const char *event_name, const char *data)
{
wiring_event_handler_t* fn = (wiring_event_handler_t*)(handler_data);
(*fn)(event_name, data);
}
bool spark_connected()
{
return pClient.connected();
}
unsigned short next_message_id()
{
return ++_message_id;
}
static uint8 calc_device_chksum(uint8 *start, uint8 *end) {
uint8 chksum = DEVICE_CHKSUM_INIT;
while(start < end) {
chksum ^= *start;
start++;
}
return chksum;
}
void writeDeviceConfig(){
deviceConfig->chksum = calc_device_chksum((uint8*)deviceConfig,(uint8*)&deviceConfig->chksum);
noInterrupts();
spi_flash_erase_sector(DEVICE_CONFIG_SECTOR);
spi_flash_write(DEVICE_CONFIG_SECTOR * SECTOR_SIZE, reinterpret_cast<uint32_t*>(config_buffer), DEVICE_CONFIG_SIZE);
spi_flash_erase_sector(DEVICE_BACKUP_CONFIG_SECTOR);
spi_flash_write(DEVICE_BACKUP_CONFIG_SECTOR * SECTOR_SIZE, reinterpret_cast<uint32_t*>(config_buffer), DEVICE_CONFIG_SIZE);
interrupts();
}
uint8_t hex_nibble(unsigned char c) {
if (c<'0')
return 0;
if (c<='9')
return c-'0';
if (c<='Z')
return c-'A'+10;
if (c<='z')
return c-'a'+10;
return 0;
}
size_t hex_decode(uint8_t* buf, size_t len, const char* hex) {
unsigned char c = '0'; // any non-null character
size_t i;
for (i=0; i<len && c; i++) {
uint8_t b;
if (!(c = *hex++))
break;
b = hex_nibble(c)<<4;
if (c) {
c = *hex++;
b |= hex_nibble(c);
}
*buf++ = b;
}
return i;
}
// Returns bytes received or -1 on error
int blocking_send(const unsigned char *buf, int length)
{
if(!spark_connected())
return -1;
#ifdef DEBUG_SETUP
Serial.println("BLSEND");
#endif
pClient.setTimeout(100);
#ifdef DEBUG_SETUP
uint32_t start = millis();
#endif
int byte_count = pClient.write(buf, length);
yield();
#ifdef DEBUG_SETUP
Serial.println(byte_count);
Serial.println((millis()-start)/1000);
#endif
//Maybe this should have been if(byte_count ==0 && length > 0)
//Removing seemed to not have ill effect
// if(byte_count==0)
// byte_count = -1;
return byte_count;
}
// Returns bytes received or -1 on error
int receive(unsigned char *buf, int length)
{
pClient.setTimeout(2000);
int available = pClient.available();
if(available >= length){
return pClient.readBytes(buf, length);
}
else if(available > 0){
return pClient.readBytes(buf, available);
}
else{
if(!spark_connected())
return -1;
else
return 0;
}
}
// Returns bytes received or -1 on error
int blocking_receive(unsigned char *buf, int length)
{
if(!spark_connected())
return -1;
yield();
#ifdef DEBUG_SETUP
Serial.println("BLRECV");
#endif
pClient.setTimeout(2000);
int byte_count = pClient.readBytes(buf, length);
if(byte_count==0)
byte_count = -1;
return byte_count;
}
int set_key(const unsigned char *signed_encrypted_credentials)
{
unsigned char credentials[40];
unsigned char hmac[20];
if (0 != decipher_aes_credentials(deviceConfig->device_private_key,
signed_encrypted_credentials,
credentials))
return 1;//decrypt error
calculate_ciphertext_hmac(signed_encrypted_credentials, credentials, hmac);
if (0 == verify_signature(signed_encrypted_credentials + 128,
deviceConfig->server_public_key,
hmac))
{
memcpy(key, credentials, 16);
memcpy(iv_send, credentials + 16, 16);
memcpy(iv_receive, credentials + 16, 16);
memcpy(salt, credentials + 32, 8);
_message_id = *(credentials + 32) << 8 | *(credentials + 33);
_token = *(credentials + 34);
unsigned int seed;
memcpy(&seed, credentials + 35, 4);
randomSeed(seed);
return 0;
}
else return 1;//auth error
}
void encrypt(unsigned char *buf, int length)
{
aes_setkey_enc(&aes, key, 128);
aes_crypt_cbc(&aes, AES_ENCRYPT, length, iv_send, buf, buf);
memcpy(iv_send, buf, 16);
}
void ping(unsigned char *buf)
{
unsigned short message_id = next_message_id();
buf[0] = 0x40; // Confirmable, no token
buf[1] = 0x00; // code signifying empty message
buf[2] = message_id >> 8;
buf[3] = message_id & 0xff;
memset(buf + 4, 12, 12); // PKCS #7 padding
encrypt(buf, 16);
}
size_t wrap(unsigned char *buf, size_t msglen)
{
size_t buflen = (msglen & ~15) + 16;
char pad = buflen - msglen;
memset(buf + 2 + msglen, pad, pad); // PKCS #7 padding
encrypt(buf + 2, buflen);
buf[0] = (buflen >> 8) & 0xff;
buf[1] = buflen & 0xff;
return buflen + 2;
}
void hello(unsigned char *buf, bool newly_upgraded)
{
unsigned short message_id = next_message_id();
size_t len = Messages::hello(buf+2, message_id, newly_upgraded, PLATFORM_ID, PRODUCT_ID, deviceConfig->firmware_version, false, nullptr, 0);
wrap(buf, len);
}
inline void coded_ack(unsigned char *buf,
unsigned char code,
unsigned char message_id_msb,
unsigned char message_id_lsb
)
{
buf[0] = 0x60; // acknowledgment, no token
buf[1] = code;
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
memset(buf + 4, 12, 12); // PKCS #7 padding
encrypt(buf, 16);
}
inline void coded_ack(unsigned char *buf,
unsigned char token,
unsigned char code,
unsigned char message_id_msb,
unsigned char message_id_lsb)
{
buf[0] = 0x61; // acknowledgment, one-byte token
buf[1] = code;
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
buf[4] = token;
memset(buf + 5, 11, 11); // PKCS #7 padding
encrypt(buf, 16);
}
void variable_value(unsigned char *buf,
unsigned char token,
unsigned char message_id_msb,
unsigned char message_id_lsb,
bool return_value)
{
buf[0] = 0x61; // acknowledgment, one-byte token
buf[1] = 0x45; // response code 2.05 CONTENT
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
buf[4] = token;
buf[5] = 0xff; // payload marker
buf[6] = return_value ? 1 : 0;
memset(buf + 7, 9, 9); // PKCS #7 padding
encrypt(buf, 16);
}
void variable_value(unsigned char *buf,
unsigned char token,
unsigned char message_id_msb,
unsigned char message_id_lsb,
int return_value)
{
buf[0] = 0x61; // acknowledgment, one-byte token
buf[1] = 0x45; // response code 2.05 CONTENT
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
buf[4] = token;
buf[5] = 0xff; // payload marker
buf[6] = return_value >> 24;
buf[7] = return_value >> 16 & 0xff;
buf[8] = return_value >> 8 & 0xff;
buf[9] = return_value & 0xff;
memset(buf + 10, 6, 6); // PKCS #7 padding
encrypt(buf, 16);
}
void variable_value(unsigned char *buf,
unsigned char token,
unsigned char message_id_msb,
unsigned char message_id_lsb,
double return_value)
{
buf[0] = 0x61; // acknowledgment, one-byte token
buf[1] = 0x45; // response code 2.05 CONTENT
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
buf[4] = token;
buf[5] = 0xff; // payload marker
memcpy(buf + 6, &return_value, 8);
memset(buf + 14, 2, 2); // PKCS #7 padding
encrypt(buf, 16);
}
// Returns the length of the buffer to send
int variable_value(unsigned char *buf,
unsigned char token,
unsigned char message_id_msb,
unsigned char message_id_lsb,
const void *return_value,
int length)
{
buf[0] = 0x61; // acknowledgment, one-byte token
buf[1] = 0x45; // response code 2.05 CONTENT
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
buf[4] = token;
buf[5] = 0xff; // payload marker
memcpy(buf + 6, return_value, length);
int msglen = 6 + length;
int buflen = (msglen & ~15) + 16;
char pad = buflen - msglen;
memset(buf + msglen, pad, pad); // PKCS #7 padding
encrypt(buf, buflen);
return buflen;
}
uint32_t timestamp_offset;
uint32_t last_time_offset;
void set_time(uint32_t time){
timestamp_offset = time - (millis()/1000);
last_time_offset = millis()/1000;
}
uint32_t get_time(){
//as long as we get time once every 98 days this should be OK
if(millis()/1000<last_time_offset){
timestamp_offset += 4294968;
}
last_time_offset = millis()/1000;
return timestamp_offset+last_time_offset;
}
void handle_time_response(uint32_t time)
{
// deduct latency
uint32_t latency = last_chunk_millis ? (millis()-last_chunk_millis)/2000 : 0;
last_chunk_millis = 0;
set_time(time-latency);
}
int numUserFunctions(void)
{
return funcs.size();
}
const char* getUserFunctionKey(int function_index)
{
return funcs[function_index].userFuncKey;
}
int numUserVariables(void)
{
return vars.size();
}
const char* getUserVariableKey(int variable_index)
{
return vars[variable_index].userVarKey;
}
int userVarType(const char *varKey)
{
User_Var_Lookup_Table_t* item = find_var_by_key(varKey);
return item ? item->userVarType : -1;
}
SparkReturnType::Enum wrapVarTypeInEnum(const char *varKey)
{
switch (userVarType(varKey))
{
case 1:
return SparkReturnType::BOOLEAN;
case 4:
return SparkReturnType::STRING;
case 9:
return SparkReturnType::DOUBLE;
case 2:
default:
return SparkReturnType::INT;
}
}
bool send_subscription(const char *event_name, const char *device_id)
{
uint16_t msg_id = next_message_id();
size_t msglen = subscription(queue + 2, msg_id, event_name, device_id);
size_t buflen = (msglen & ~15) + 16;
char pad = buflen - msglen;
memset(queue + 2 + msglen, pad, pad); // PKCS #7 padding
encrypt(queue + 2, buflen);
queue[0] = (buflen >> 8) & 0xff;
queue[1] = buflen & 0xff;
return (0 <= blocking_send(queue, buflen + 2));
}
bool send_subscription(const char *event_name,
SubscriptionScope::Enum scope)
{
uint16_t msg_id = next_message_id();
size_t msglen = subscription(queue + 2, msg_id, event_name, scope);
size_t buflen = (msglen & ~15) + 16;
char pad = buflen - msglen;
memset(queue + 2 + msglen, pad, pad); // PKCS #7 padding
encrypt(queue + 2, buflen);
queue[0] = (buflen >> 8) & 0xff;
queue[1] = buflen & 0xff;
return (0 <= blocking_send(queue, buflen + 2));
}
void send_subscriptions()
{
const int NUM_HANDLERS = sizeof(event_handlers) / sizeof(FilteringEventHandler);
for (int i = 0; i < NUM_HANDLERS; i++)
{
if (NULL != event_handlers[i].handler)
{
if (event_handlers[i].device_id[0])
{
send_subscription(event_handlers[i].filter, event_handlers[i].device_id);
}
else
{
send_subscription(event_handlers[i].filter, event_handlers[i].scope);
}
}
}
}
bool event_handler_exists(const char *event_name, EventHandler handler,
void *handler_data, SubscriptionScope::Enum scope, const char* id)
{
const int NUM_HANDLERS = sizeof(event_handlers) / sizeof(FilteringEventHandler);
for (int i = 0; i < NUM_HANDLERS; i++)
{
if (event_handlers[i].handler==handler &&
event_handlers[i].handler_data==handler_data &&
event_handlers[i].scope==scope) {
const size_t MAX_FILTER_LEN = sizeof(event_handlers[i].filter);
const size_t FILTER_LEN = strnlen(event_name, MAX_FILTER_LEN);
if (!strncmp(event_handlers[i].filter, event_name, FILTER_LEN)) {
const size_t MAX_ID_LEN = sizeof(event_handlers[i].device_id)-1;
const size_t id_len = id ? strnlen(id, MAX_ID_LEN) : 0;
if (id_len)
return !strncmp(event_handlers[i].device_id, id, id_len);
else
return !event_handlers[i].device_id[0];
}
}
}
return false;
}
bool add_event_handler(const char *event_name, EventHandler handler,
void *handler_data, SubscriptionScope::Enum scope, const char* id)
{
if (event_handler_exists(event_name, handler, handler_data, scope, id))
return true;
const int NUM_HANDLERS = sizeof(event_handlers) / sizeof(FilteringEventHandler);
for (int i = 0; i < NUM_HANDLERS; i++)
{
if (NULL == event_handlers[i].handler)
{
const size_t MAX_FILTER_LEN = sizeof(event_handlers[i].filter);
const size_t FILTER_LEN = strnlen(event_name, MAX_FILTER_LEN);
memcpy(event_handlers[i].filter, event_name, FILTER_LEN);
memset(event_handlers[i].filter + FILTER_LEN, 0, MAX_FILTER_LEN - FILTER_LEN);
event_handlers[i].handler = handler;
event_handlers[i].handler_data = handler_data;
event_handlers[i].device_id[0] = 0;
const size_t MAX_ID_LEN = sizeof(event_handlers[i].device_id)-1;
const size_t id_len = id ? strnlen(id, MAX_ID_LEN) : 0;
memcpy(event_handlers[i].device_id, id, id_len);
event_handlers[i].device_id[id_len] = 0;
event_handlers[i].scope = scope;
return true;
}
}
return false;
}
const void *getUserVar(const char *varKey)
{
User_Var_Lookup_Table_t* item = find_var_by_key(varKey);
const void* result = nullptr;
if (item) {
if (item->update)
result = item->update(item->userVarKey, item->userVarType, item->userVar, nullptr);
else
result = item->userVar;
}
return result;
}
void userFuncScheduleImpl(User_Func_Lookup_Table_t* item, const char* paramString, bool freeParamString, FunctionResultCallback callback)
{
int result = item->pUserFunc(item->pUserFuncData, paramString, NULL);
if (freeParamString)
delete paramString;
callback((const void*)long(result), SparkReturnType::INT);
}
int userFuncSchedule(const char *funcKey, const char *paramString, FunctionResultCallback callback, void* reserved)
{
// for now, we invoke the function directly and return the result via the callback
User_Func_Lookup_Table_t* item = find_func_by_key(funcKey);
if (!item)
return -1;
userFuncScheduleImpl(item, paramString, false, callback);
return 0;
}
SubscriptionScope::Enum convert(Spark_Subscription_Scope_TypeDef subscription_type)
{
return(subscription_type==MY_DEVICES) ? SubscriptionScope::MY_DEVICES : SubscriptionScope::FIREHOSE;
}
bool register_event(const char* eventName, SubscriptionScope::Enum event_scope, const char* deviceID)
{
bool success;
if (deviceID)
success = send_subscription(eventName, deviceID);
else
success = send_subscription(eventName, event_scope);
return success;
}
bool spark_subscribe(const char *eventName, EventHandler handler, void* handler_data,
Spark_Subscription_Scope_TypeDef scope, const char* deviceID, void* reserved)
{
//SYSTEM_THREAD_CONTEXT_SYNC(spark_subscribe(eventName, handler, handler_data, scope, deviceID, reserved));
auto event_scope = convert(scope);
bool success = add_event_handler(eventName, handler, handler_data, event_scope, deviceID);
if (success && spark_connected())
{
register_event(eventName, event_scope, deviceID);
}
return success;
}
inline EventType::Enum convert(Spark_Event_TypeDef eventType) {
return eventType==PUBLIC ? EventType::PUBLIC : EventType::PRIVATE;
}
inline bool is_system(const char* event_name) {
// if there were a strncmpi this would be easier!
char prefix[6];
if (!*event_name || strlen(event_name)<5)
return false;
memcpy(prefix, event_name, 5);
prefix[5] = '\0';
return !strcasecmp(prefix, "spark");
}
// Returns true on success, false on sending timeout or rate-limiting failure
bool send_event(const char *event_name, const char *data,
int ttl, EventType::Enum event_type)
{
if (updating)
{
return false;
}
bool is_system_event = is_system(event_name);
if (is_system_event) {
static uint16_t lastMinute = 0;
static uint8_t eventsThisMinute = 0;
uint16_t currentMinute = uint16_t(millis()>>16);
if (currentMinute==lastMinute) { // == handles millis() overflow
if (eventsThisMinute==255)
return false;
}
else {
lastMinute = currentMinute;
eventsThisMinute = 0;
}
eventsThisMinute++;
}
else {
static uint32_t recent_event_ticks[5] = {
(uint32_t) -1000, (uint32_t) -1000,
(uint32_t) -1000, (uint32_t) -1000,
(uint32_t) -1000 };
static int evt_tick_idx = 0;
uint32_t now = recent_event_ticks[evt_tick_idx] = millis();
evt_tick_idx++;
evt_tick_idx %= 5;
if (now - recent_event_ticks[evt_tick_idx] < 1000)
{
// exceeded allowable burst of 4 events per second
return false;
}
}
uint16_t msg_id = next_message_id();
size_t msglen = Messages::event(queue + 2, msg_id, event_name, data, ttl, event_type, false);
size_t wrapped_len = wrap(queue, msglen);
return (0 <= blocking_send(queue, wrapped_len));
}
bool spark_send_event(const char* name, const char* data, int ttl, Spark_Event_TypeDef eventType, void* reserved)
{
//SYSTEM_THREAD_CONTEXT_SYNC(spark_send_event(name, data, ttl, eventType, reserved));
//return spark_protocol_send_event(sp, name, data, ttl, convert(eventType), NULL);
return send_event(name, data, ttl, convert(eventType));
}
bool spark_variable(const char *varKey, const void *userVar, Spark_Data_TypeDef userVarType, spark_variable_t* extra)
{
//SYSTEM_THREAD_CONTEXT_SYNC(spark_variable(varKey, userVar, userVarType, extra));
User_Var_Lookup_Table_t* item = NULL;
if (NULL != userVar && NULL != varKey && strlen(varKey)<=USER_VAR_KEY_LENGTH)
{
if ((item=find_var_by_key_or_add(varKey))!=NULL)
{
item->userVar = userVar;
item->userVarType = userVarType;
if (extra) {
item->update = extra->update;
}
memset(item->userVarKey, 0, USER_VAR_KEY_LENGTH);
memcpy(item->userVarKey, varKey, USER_VAR_KEY_LENGTH);
}
}
return item!=NULL;
}
void function_return(unsigned char *buf,
unsigned char token,
int return_value)
{
unsigned short message_id = next_message_id();
buf[0] = 0x51; // non-confirmable, one-byte token
buf[1] = 0x44; // response code 2.04 CHANGED
buf[2] = message_id >> 8;
buf[3] = message_id & 0xff;
buf[4] = token;
buf[5] = 0xff; // payload marker
buf[6] = return_value >> 24;
buf[7] = return_value >> 16 & 0xff;
buf[8] = return_value >> 8 & 0xff;
buf[9] = return_value & 0xff;
memset(buf + 10, 6, 6); // PKCS #7 padding
encrypt(buf, 16);
}
bool spark_function_internal(const cloud_function_descriptor* desc, void* reserved)
{
User_Func_Lookup_Table_t* item = NULL;
if (NULL != desc->fn && NULL != desc->funcKey && strlen(desc->funcKey)<=USER_FUNC_KEY_LENGTH)
{
if ((item=find_func_by_key(desc->funcKey)) || (item = funcs.add()))
{
item->pUserFunc = desc->fn;
item->pUserFuncData = desc->data;
memset(item->userFuncKey, 0, USER_FUNC_KEY_LENGTH);
memcpy(item->userFuncKey, desc->funcKey, USER_FUNC_KEY_LENGTH);
}
}
return item!=NULL;
}
/**
* This is the original released signature for firmware version 0 and needs to remain like this.
* (The original returned void - we can safely change to bool.)
*/
bool spark_function(const char *funcKey, p_user_function_int_str_t pFunc, void* reserved)
{
//SYSTEM_THREAD_CONTEXT_SYNC(spark_function(funcKey, pFunc, reserved));
bool result;
if (funcKey) { // old call, with funcKey != NULL
cloud_function_descriptor desc;
desc.funcKey = funcKey;
desc.fn = call_raw_user_function;
desc.data = (void*)pFunc;
result = spark_function_internal(&desc, NULL);
}
else { // new call - pFunc is actually a pointer to a descriptor
result = spark_function_internal((cloud_function_descriptor*)pFunc, reserved);
}
return result;
}
bool register_function(cloud_function_t fn, void* data, const char* funcKey)
{
cloud_function_descriptor desc;
memset(&desc, 0, sizeof(desc));
desc.size = sizeof(desc);
desc.fn = fn;
desc.data = (void*)data;
desc.funcKey = funcKey;
return spark_function(NULL, (user_function_int_str_t*)&desc, NULL);
}
String buffer_to_string(const uint8_t *buf,size_t length){
String result = "";
for(uint8_t i = 0; i<length; i++){
result += buf[i];
}
return result;
}
bool spark_describe_called = false;
int description(unsigned char *buf, unsigned char token,
unsigned char message_id_msb, unsigned char message_id_lsb, int desc_flags)
{