-
Notifications
You must be signed in to change notification settings - Fork 11
/
n_helpers.c
2575 lines (2307 loc) · 87.4 KB
/
n_helpers.c
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
/*!
* @file n_helpers.c
*
* Written by Ray Ozzie and Blues Inc. team.
*
* Copyright (c) 2019 Blues Inc. MIT License. Use of this source code is
* governed by licenses granted by the copyright holder including that found in
* the
* <a href="https://github.com/blues/note-c/blob/master/LICENSE">LICENSE</a>
* file.
*
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "n_lib.h"
#ifdef NOTE_C_TEST
#include "test_static.h"
#else
#define NOTE_C_STATIC static
#endif
// When interfacing with the Notecard, it is generally encouraged that the JSON
// object manipulation and calls to the note-arduino library are done directly
// at point of need. However, there are cases in which it's convenient to have a
// wrapper. The most common reason is when it's best to have a suppression timer
// on the actual call to the Notecard so as not to assault the I2C bus or UART
// on a continuing basis - the most common examples of this being "card.time"
// and any other Notecard state that needs to be polled for an app, such as the
// device location, its voltage level, and so on. This file contains this kind
// of wrapper, just implemented here as a convenience to all developers.
// Time-related suppression timer and cache
static uint32_t timeBaseSetAtMs = 0;
static JTIME timeBaseSec = 0;
static bool timeBaseSetManually = false;
static uint32_t suppressionTimerSecs = 10;
static uint32_t refreshTimerSecs = 86400;
static uint32_t timeTimer = 0;
static uint32_t timeRefreshTimer = 0;
static bool zoneStillUnavailable = true;
static bool zoneForceRefresh = false;
static char curZone[10] = {0};
static char curArea[64] = {0};
static char curCountry[8] = "";
static int curZoneOffsetMins = 0;
// Location-related suppression timer and cache
static uint32_t locationTimer = 0;
static char locationLastErr[64] = {0};
static bool locationValid = false;
// Connection-related suppression timer and cache
static uint32_t connectivityTimer = 0;
static bool cardConnected = false;
// Status suppression timer
static uint32_t statusTimer = 0;
// DEPRECATED. Turbo communications mode, for special use cases and well-tested
// hardware.
bool cardTurboIO = false;
// Service config-related suppression timer and cache
static uint32_t serviceConfigTimer = 0;
static char scDevice[128] = {0};
static char scSN[128] = {0};
static char scProduct[128] = {0};
static char scService[128] = {0};
// For date conversions
#define daysByMonth(y) ((y)&03||(y)==0?normalYearDaysByMonth:leapYearDaysByMonth)
static short leapYearDaysByMonth[] = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335};
static short normalYearDaysByMonth[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
static const char *daynames[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
// Forwards
NOTE_C_STATIC void setTime(JTIME seconds);
NOTE_C_STATIC bool timerExpiredSecs(uint32_t *timer, uint32_t periodSecs);
NOTE_C_STATIC int yToDays(int year);
static const char NOTE_C_BINARY_EOP = '\n';
//**************************************************************************/
/*!
@brief Decode binary data received from the Notecard.
@param encData The encoded binary data to decode.
@param encDataLen The length of the encoded binary data.
@param decBuf The target buffer for the decoded data. For in-place decoding,
`decBuf` can use the same address as `encData` (see note).
@param decBufSize The size of `decBuf`.
@returns The length of the decoded data, or zero on error.
@note Use `NoteBinaryCodecMaxDecodedLength()` to calculate the required
size for the buffer pointed to by the `decBuf` parameter, which MUST
accommodate both the encoded data and newline terminator.
@note This API supports in-place decoding. If you wish to utilize in-place
decoding, then set `decBuf` to `encData` and `decBufSize` to `encLen`.
*/
/**************************************************************************/
uint32_t NoteBinaryCodecDecode(const uint8_t *encData, uint32_t encDataLen,
uint8_t *decBuf, uint32_t decBufSize)
{
uint32_t result;
// Validate parameter(s)
if (encData == NULL || decBuf == NULL) {
NOTE_C_LOG_ERROR(ERRSTR("NULL parameter", c_err));
result = 0;
} else if (decBufSize < cobsGuaranteedFit(encDataLen)) {
NOTE_C_LOG_ERROR(ERRSTR("output buffer too small", c_err));
result = 0;
} else {
result = cobsDecode((uint8_t *)encData, encDataLen, NOTE_C_BINARY_EOP, decBuf);
}
return result;
}
//**************************************************************************/
/*!
@brief Encode binary data to transmit to the Notecard.
@param decData The decoded binary data to encode.
@param decDataLen The length of the decoded binary data.
@param encBuf The target buffer for the encoded data. For in-place encoding,
`encBuf` can use the same buffer as `decData`, but cannot
share the same address (see note).
@param encBufSize The size of `encBuf`.
@returns The length of the encoded data, or zero on error.
@note Use `NoteBinaryCodecMaxEncodedLength()` to calculate the required
size for the buffer pointed to by the `encBuf` parameter, which MUST
accommodate both the encoded data and newline terminator.
@note This API supports in-place encoding. If you wish to utilize in-place
encoding, shift the decoded data to the end of the buffer, update
`decBuf` accordingly, and set the value of `encBuf` to the beginning
of the buffer.
*/
/**************************************************************************/
uint32_t NoteBinaryCodecEncode(const uint8_t *decData, uint32_t decDataLen,
uint8_t *encBuf, uint32_t encBufSize)
{
uint32_t result;
// Validate parameter(s)
if (decData == NULL || encBuf == NULL) {
NOTE_C_LOG_ERROR(ERRSTR("NULL parameter", c_err));
result = 0;
} else if ((encBufSize < cobsEncodedMaxLength(decDataLen))
&& (encBufSize < cobsEncodedLength(decData, decDataLen))) {
// NOTE: `cobsEncodedMaxLength()` provides a constant time [O(1)] means
// of checking the buffer size. Only when it fails will the linear
// time [O(n)] check, `cobsEncodedLength()`, be invoked.
NOTE_C_LOG_ERROR(ERRSTR("output buffer too small", c_err));
result = 0;
} else {
result = cobsEncode((uint8_t *)decData, decDataLen, NOTE_C_BINARY_EOP, encBuf);
}
return result;
}
//**************************************************************************/
/*!
@brief Compute the maximum decoded data length guaranteed
to fit into a fixed-size buffer, after being encoded.
This API is designed for a space constrained environment, where a
working buffer has been allocated to facilitate binary transactions.
There are two primary use cases:
1. When data is retrieved from the Notecard, it must be requested in
terms of the unencoded offset and length. However, the data is
encoded prior to transmission, and, as a result, the buffer must be
capable of receiving the encoded (larger) data. This API returns a
length that is safe to request from the Notecard, because the
resulting encoded data is guaranteed to fit in the provided buffer.
2. When data is transmitted to the Notecard, this API can be used to
verify whether or not unencoded data of a given length will fit in
the provided buffer after encoding.
@param bufferSize The size of the fixed-size buffer.
@returns The max length of unencoded data certain to fit in the fixed-size
buffer, after being encoded.
*/
/**************************************************************************/
uint32_t NoteBinaryCodecMaxDecodedLength(uint32_t bufferSize)
{
return cobsGuaranteedFit(bufferSize);
}
//**************************************************************************/
/*!
@brief Compute the maximum buffer size needed to encode
any unencoded buffer of the given length.
@param unencodedLength The length of an unencoded buffer.
@returns The max required buffer size to hold the encoded data.
*/
/**************************************************************************/
uint32_t NoteBinaryCodecMaxEncodedLength(uint32_t unencodedLength)
{
return cobsEncodedMaxLength(unencodedLength);
}
//**************************************************************************/
/*!
@brief Get the length of the data in the Notecard's binary store. If there's
no data on the Notecard, then `*len` will return 0.
@param len [out] The length of the decoded contents of the Notecard's binary
store.
@returns An error string on error and NULL on success.
*/
/**************************************************************************/
const char * NoteBinaryStoreDecodedLength(uint32_t *len)
{
// Validate parameter(s)
if (!len) {
const char *err = ERRSTR("len cannot be NULL", c_bad);
NOTE_C_LOG_ERROR(err);
return err;
}
// Issue a "card.binary" request.
J *rsp = NoteRequestResponse(NoteNewRequest("card.binary"));
if (!rsp) {
const char *err = ERRSTR("unable to issue binary request", c_err);
NOTE_C_LOG_ERROR(err);
return err;
}
// Ensure the transaction doesn't return an error
// and confirm the binary feature is available
if (NoteResponseError(rsp)) {
const char *jErr = JGetString(rsp, "err");
// Swallow `{bad-bin}` errors, because we intend to overwrite the data.
if (!NoteErrorContains(jErr, c_badbinerr)) {
NOTE_C_LOG_ERROR(jErr);
JDelete(rsp);
const char *err = ERRSTR("unexpected error received during handshake", c_bad);
NOTE_C_LOG_ERROR(err);
return err;
}
}
// Examine "length" from the response to evaluate the length of the decoded
// data residing on the Notecard.
*len = JGetInt(rsp, "length");
JDelete(rsp);
return NULL;
}
//**************************************************************************/
/*!
@brief Get the required buffer length to receive the entire binary object
stored in the Notecard's binary store.
@param len [out] The length required to hold the entire contents of the
Notecard's binary store. If there's no data on the Notecard, then
`len` will return 0.
@returns An error string on error and NULL on success.
*/
/**************************************************************************/
const char * NoteBinaryStoreEncodedLength(uint32_t *len)
{
// Validate parameter(s)
if (!len) {
const char *err = ERRSTR("size cannot be NULL", c_err);
NOTE_C_LOG_ERROR(err);
return err;
}
// Issue a "card.binary" request.
J *rsp = NoteRequestResponse(NoteNewRequest("card.binary"));
if (!rsp) {
const char *err = ERRSTR("unable to issue binary request", c_err);
NOTE_C_LOG_ERROR(err);
return err;
}
// Ensure the transaction doesn't return an error
// and confirm the binary feature is available
if (NoteResponseError(rsp)) {
const char *jErr = JGetString(rsp, "err");
// Swallow `{bad-bin}` errors, because we intend to overwrite the data.
if (!NoteErrorContains(jErr, c_badbinerr)) {
NOTE_C_LOG_ERROR(jErr);
JDelete(rsp);
const char *err = ERRSTR("unexpected error received during handshake", c_bad);
NOTE_C_LOG_ERROR(err);
return err;
}
}
// Examine "cobs" from the response to evaluate the space required to hold
// the encoded data to be received from the Notecard.
long int cobs = JGetInt(rsp, "cobs");
JDelete(rsp);
*len = cobs;
return NULL;
}
//**************************************************************************/
/*!
@brief Receive a large binary object from the Notecard's binary store.
@param buffer A buffer to hold the binary range.
@param bufLen The total length of the provided buffer.
@param decodedOffset The offset to the decoded binary data residing
in the Notecard's binary store.
@param decodedLen The length of the decoded data to fetch from the Notecard.
@returns NULL on success, else an error string pointer.
@note The buffer must be large enough to hold the encoded value of the
data store contents from the requested offset for the specified length.
To determine the necessary buffer size for a given data length, use
`NoteBinaryCodecMaxEncodedLength()`, or if you wish to consume the
entire buffer use `(NoteBinaryStoreEncodedLength() + 1)` instead.
*/
/**************************************************************************/
const char * NoteBinaryStoreReceive(uint8_t *buffer, uint32_t bufLen,
uint32_t decodedOffset, uint32_t decodedLen)
{
// Validate parameter(s)
if (!buffer) {
const char *err = ERRSTR("NULL buffer", c_bad);
NOTE_C_LOG_ERROR(err);
return err;
}
if (bufLen < cobsEncodedMaxLength(decodedLen)) {
const char *err = ERRSTR("insufficient buffer size", c_bad);
NOTE_C_LOG_ERROR(err);
return err;
}
if (decodedLen == 0) {
const char *err = ERRSTR("decodedLen cannot be zero (0)", c_bad);
NOTE_C_LOG_ERROR(err);
return err;
}
// Claim Notecard Mutex
_LockNote();
// Issue `card.binary.get` and capture `"status"` from response
char status[NOTE_MD5_HASH_STRING_SIZE] = {0};
J *req = NoteNewRequest("card.binary.get");
if (req) {
JAddIntToObject(req, "offset", decodedOffset);
JAddIntToObject(req, "length", decodedLen);
// We already have the Notecard lock, so call
// noteTransactionShouldLock with `lockNotecard` set to false so we
// don't try to lock again.
J *rsp = noteTransactionShouldLock(req, false);
JDelete(req);
// Ensure the transaction doesn't return an error.
if (!rsp || NoteResponseError(rsp)) {
if (rsp) {
NOTE_C_LOG_ERROR(JGetString(rsp,"err"));
JDelete(rsp);
}
const char *err = ERRSTR("failed to initialize binary transaction", c_err);
NOTE_C_LOG_ERROR(err);
_UnlockNote();
return err;
}
// Examine "status" from the response to evaluate the MD5 checksum.
strlcpy(status, JGetString(rsp,"status"), NOTE_MD5_HASH_STRING_SIZE);
JDelete(rsp);
} else {
const char *err = ERRSTR("unable to allocate request", c_mem);
NOTE_C_LOG_ERROR(err);
_UnlockNote();
return err;
}
// Read raw bytes from the active interface into a predefined buffer
uint32_t available = 0;
NOTE_C_LOG_DEBUG("receiving binary data...");
const char *err = _ChunkedReceive(buffer, &bufLen, false, (CARD_INTRA_TRANSACTION_TIMEOUT_SEC * 1000), &available);
NOTE_C_LOG_DEBUG("binary receive complete.");
// Release Notecard Mutex
_UnlockNote();
// Ensure transaction was successful
if (err) {
// Queue a reset when a problem is detected, otherwise `note-c` will
// attempt to allocate memory to receive the response.
NoteResetRequired();
return ERRSTR(err, c_err);
}
// Check buffer overflow condition
if (available) {
const char *err = ERRSTR("unexpected data available", c_err);
NOTE_C_LOG_ERROR(err);
// Queue a reset when a problem is detected, otherwise `note-c` will
// attempt to allocate memory to receive the response.
NoteResetRequired();
return err;
}
// _ChunkedReceive returns the raw bytes that came off the wire, which
// includes a terminating newline that ends the packet. This newline isn't
// part of the binary payload, so we decrement the length by 1 to remove it.
--bufLen;
// Decode it in place, which is safe because decoding shrinks
const uint32_t decLen = NoteBinaryCodecDecode(buffer, bufLen, buffer, bufLen);
// Ensure the decoded length matches the caller's expectations.
if (decodedLen != decLen) {
const char *err = ERRSTR("length mismatch after decoding", c_err);
NOTE_C_LOG_ERROR(err);
// Queue a reset when a problem is detected, otherwise `note-c` will
// attempt to allocate memory to receive the response.
NoteResetRequired();
return err;
}
// Put a hard marker at the end of the decoded portion of the buffer. This
// enables easier human reasoning when interrogating the buffer, if the
// buffer holds a string.
buffer[decLen] = '\0';
// Verify MD5
char hashString[NOTE_MD5_HASH_STRING_SIZE] = {0};
NoteMD5HashString(buffer, decLen, hashString, NOTE_MD5_HASH_STRING_SIZE);
if (strncmp(hashString, status, NOTE_MD5_HASH_STRING_SIZE)) {
const char *err = ERRSTR("computed MD5 does not match received MD5", c_err);
NOTE_C_LOG_ERROR(err);
return err;
}
// Return `NULL` if success, else error string pointer
return NULL;
}
//**************************************************************************/
/*!
@brief Reset the Notecard's binary store.
@returns NULL on success, else an error string pointer.
@note This operation is necessary to clear the Notecard's binary buffer after
a binary object is received from the Notecard, or if the Notecard's
binary store has been left in an unknown state due to an error arising
from a binary transfer to the Notecard.
*/
/**************************************************************************/
const char * NoteBinaryStoreReset(void)
{
J *req = NoteNewRequest("card.binary");
if (req) {
JAddBoolToObject(req, "delete", true);
// Ensure the transaction doesn't return an error.
J *rsp = NoteRequestResponse(req);
if (NoteResponseError(rsp)) {
NOTE_C_LOG_ERROR(JGetString(rsp,"err"));
JDelete(rsp);
const char *err = ERRSTR("failed to reset binary buffer", c_err);
NOTE_C_LOG_ERROR(err);
return err;
}
JDelete(rsp);
} else {
const char *err = ERRSTR("unable to allocate request", c_mem);
NOTE_C_LOG_ERROR(err);
return err;
}
return NULL;
}
//**************************************************************************/
/*!
@brief Transmit a large binary object to the Notecard's binary store.
@param unencodedData A buffer with data to encode in place.
@param unencodedLen The length of the data in the buffer.
@param bufLen The total length of the buffer (see notes).
@param notecardOffset The offset where the data buffer should be appended
to the decoded binary data residing in the Notecard's
binary store. This does not provide random access, but
rather ensures alignment across sequential writes.
@returns NULL on success, else an error string pointer.
@note Buffers are encoded in place, the buffer _MUST_ be larger than the data
to be encoded. The original contents of the buffer will be modified.
Use `NoteBinaryCodecMaxEncodedLength()` to calculate the required size
for the buffer pointed to by the `unencodedData` parameter, which MUST
accommodate both the encoded data and newline terminator.
*/
/**************************************************************************/
const char * NoteBinaryStoreTransmit(uint8_t *unencodedData, uint32_t unencodedLen,
uint32_t bufLen, uint32_t notecardOffset)
{
// Validate parameter(s)
if (!unencodedData) {
const char *err = ERRSTR("unencodedData cannot be NULL", c_err);
NOTE_C_LOG_ERROR(err);
return err;
} else if ((bufLen < cobsEncodedMaxLength(unencodedLen))
&& (bufLen < (cobsEncodedLength(unencodedData, unencodedLen) + 1))) {
// NOTE: `cobsEncodedMaxLength()` provides a constant time [O(1)] means
// of checking the buffer size. Only when it fails will the linear
// time [O(n)] check, `cobsEncodedLength()`, be invoked.
const char *err = ERRSTR("insufficient buffer size", c_bad);
NOTE_C_LOG_ERROR(err);
return err;
}
// Issue a "card.binary" request.
J *rsp = NoteRequestResponse(NoteNewRequest("card.binary"));
if (!rsp) {
const char *err = ERRSTR("unable to issue binary request", c_err);
NOTE_C_LOG_ERROR(err);
return err;
}
// Ensure the transaction doesn't return an error
// and confirm the binary feature is available
if (NoteResponseError(rsp)) {
const char *jErr = JGetString(rsp, "err");
// Swallow `{bad-bin}` errors, because we intend to overwrite the data.
if (!NoteErrorContains(jErr, c_badbinerr)) {
NOTE_C_LOG_ERROR(jErr);
JDelete(rsp);
const char *err = ERRSTR("unexpected error received during handshake", c_bad);
NOTE_C_LOG_ERROR(err);
return err;
}
}
// Examine "length" and "max" from the response to evaluate the unencoded
// space available to "card.binary.put" on the Notecard.
const long len = JGetInt(rsp,"length");
const long max = JGetInt(rsp,"max");
JDelete(rsp);
if (!max) {
const char *err = ERRSTR("unexpected response: max is zero or not present", c_err);
NOTE_C_LOG_ERROR(err);
return err;
}
// Validate the index provided by the caller, against the `length` value
// returned from the Notecard to ensure the caller and Notecard agree on
// how much data is residing on the Notecard.
if ((long)notecardOffset != len) {
const char *err = ERRSTR("notecard data length is misaligned with offset", c_mem);
NOTE_C_LOG_ERROR(err);
return err;
}
// When offset is zero, the Notecard's entire binary buffer is available
const uint32_t remaining = (notecardOffset ? (max - len) : max);
if (unencodedLen > remaining) {
const char *err = ERRSTR("buffer size exceeds available memory", c_mem);
NOTE_C_LOG_ERROR(err);
return err;
}
// Calculate MD5
char hashString[NOTE_MD5_HASH_STRING_SIZE] = {0};
NoteMD5HashString(unencodedData, unencodedLen, hashString, NOTE_MD5_HASH_STRING_SIZE);
// Shift the data to the end of the buffer. Next, we'll encode the data,
// outputting the encoded data to the front of the buffer.
const uint32_t dataShift = (bufLen - unencodedLen);
memmove(unencodedData + dataShift, unencodedData, unencodedLen);
// Create an alias to help reason about the buffer after in-place encoding.
uint8_t * const encodedData = unencodedData;
// Update unencoded data pointer
unencodedData += dataShift;
// Capture encoded length
// NOTE: `(bufLen - 1)` accounts for one byte of space we need to save for a
// newline to mark the end of the packet.
const uint32_t encLen = NoteBinaryCodecEncode(unencodedData, unencodedLen, encodedData, (bufLen - 1));
// Append the \n, which marks the end of a packet.
encodedData[encLen] = '\n';
const size_t NOTE_C_BINARY_RETRIES = 3;
for (size_t i = 0 ; i < NOTE_C_BINARY_RETRIES ; ++i) {
// Claim Notecard Mutex
_LockNote();
// Issue a "card.binary.put"
J *req = NoteNewRequest("card.binary.put");
if (req) {
JAddIntToObject(req, "cobs", encLen);
if (notecardOffset) {
JAddIntToObject(req, "offset", notecardOffset);
}
JAddStringToObject(req, "status", hashString);
// We already have the Notecard lock, so call
// noteTransactionShouldLock with `lockNotecard` set to false so we
// don't try to lock again.
rsp = noteTransactionShouldLock(req, false);
JDelete(req);
// Ensure the transaction doesn't return an error.
if (!rsp || NoteResponseError(rsp)) {
if (rsp) {
NOTE_C_LOG_ERROR(JGetString(rsp,"err"));
JDelete(rsp);
}
const char *err = ERRSTR("failed to initialize binary transaction", c_err);
NOTE_C_LOG_ERROR(err);
_UnlockNote();
// On errors, we restore the caller's input buffer by decoding
// it. The caller is then able to retry transmission with their
// original pointer to this buffer.
NoteBinaryCodecDecode(encodedData, encLen, encodedData, bufLen);
return err;
}
JDelete(rsp);
} else {
const char *err = ERRSTR("unable to allocate request", c_mem);
NOTE_C_LOG_ERROR(err);
_UnlockNote();
NoteBinaryCodecDecode(encodedData, encLen, encodedData, bufLen);
return err;
}
// Immediately send the encoded binary.
NOTE_C_LOG_DEBUG("transmitting binary data...");
const char *err = _ChunkedTransmit(encodedData, (encLen + 1), false);
NOTE_C_LOG_DEBUG("binary transmission complete.");
// Release Notecard Mutex
_UnlockNote();
// Ensure transaction was successful
if (err) {
NoteBinaryCodecDecode(encodedData, encLen, encodedData, bufLen);
return ERRSTR(err, c_err);
}
// Issue a `"card.binary"` request.
rsp = NoteRequestResponse(NoteNewRequest("card.binary"));
if (!rsp) {
const char *err = ERRSTR("unable to validate request", c_err);
NOTE_C_LOG_ERROR(err);
NoteBinaryCodecDecode(encodedData, encLen, encodedData, bufLen);
return err;
}
// Ensure the transaction doesn't return an error
// to confirm the binary was received
if (NoteResponseError(rsp)) {
const char *jErr = JGetString(rsp, "err");
if (NoteErrorContains(jErr, c_badbinerr)) {
NOTE_C_LOG_WARN(jErr);
JDelete(rsp);
if ( i < (NOTE_C_BINARY_RETRIES - 1) ) {
NOTE_C_LOG_WARN("retrying binary transmission...");
continue;
}
const char *err = ERRSTR("binary data invalid", c_bad);
NOTE_C_LOG_ERROR(err);
NoteBinaryCodecDecode(encodedData, encLen, encodedData, bufLen);
return err;
} else {
NOTE_C_LOG_ERROR(jErr);
JDelete(rsp);
const char *err = ERRSTR("unexpected error received during confirmation", c_bad);
NOTE_C_LOG_ERROR(err);
NoteBinaryCodecDecode(encodedData, encLen, encodedData, bufLen);
return err;
}
}
JDelete(rsp);
break;
}
// Return `NULL` on success
return NULL;
}
//**************************************************************************/
/*!
@brief Determine if the card time is "real" calendar/clock time, or if
it is simply the millisecond clock since boot.
@returns A boolean indicating whether the current time is valid.
*/
/**************************************************************************/
bool NoteTimeValid(void)
{
timeTimer = 0;
return NoteTimeValidST();
}
//**************************************************************************/
/*!
@brief Determine if if the suppression-timer card time is valid.
@returns A boolean indicating whether the current time is valid.
*/
/**************************************************************************/
bool NoteTimeValidST(void)
{
NoteTimeST();
return (timeBaseSec != 0);
}
//**************************************************************************/
/*!
@brief Get the current epoch time, unsuppressed.
@returns The current time.
*/
/**************************************************************************/
JTIME NoteTime(void)
{
timeTimer = 0;
return NoteTimeST();
}
/*!
@brief Set the number of minutes between refreshes of the time from the
Notecard, to help minimize clock drift on this host. Set this to 0 for
no auto-refresh; it defaults to daily.
@param mins Minutes between time refreshes.
*/
void NoteTimeRefreshMins(uint32_t mins)
{
refreshTimerSecs = mins * 60;
}
//**************************************************************************/
/*!
@brief Set the time.
@param seconds The UNIX Epoch time.
*/
/**************************************************************************/
NOTE_C_STATIC void setTime(JTIME seconds)
{
timeBaseSec = seconds;
timeBaseSetAtMs = _GetMs();
}
/*!
@brief Set the time from a source that is NOT the Notecard
@param secondsUTC The UNIX Epoch time, or 0 for automatic Notecard time
@param offset The local time zone offset, in minutes, to adjust UTC
@param zone The optional local time zone name (3 character c-string). Note
that this isn't used in any time calculations. To compute
accurate local time, only the offset is used. See
https://www.iana.org/time-zones for a time zone database.
@param country The optional country
@param area The optional region
*/
void NoteTimeSet(JTIME secondsUTC, int offset, char *zone, char *country, char *area)
{
if (secondsUTC == 0) {
timeBaseSec = 0;
timeBaseSetAtMs = 0;
timeBaseSetManually = false;
zoneStillUnavailable = true;
zoneForceRefresh = false;
} else {
timeBaseSec = secondsUTC;
timeBaseSetAtMs = _GetMs();
timeBaseSetManually = true;
zoneStillUnavailable = false;
curZoneOffsetMins = offset;
strlcpy(curZone, zone == NULL ? "UTC" : zone, sizeof(curZone));
strlcpy(curArea, area == NULL ? "" : area, sizeof(curArea));
strlcpy(curCountry, country == NULL ? "" : country, sizeof(curCountry));
}
}
//**************************************************************************/
/*!
@brief Print a full, newline-terminated line.
@param line The c-string line to print.
*/
/**************************************************************************/
void NotePrintln(const char *line)
{
NotePrint(line);
NotePrint(c_newline);
}
//**************************************************************************/
/*!
@brief Log text "raw" to either the active debug console or to the
Notecard's USB console.
@param text A debug string for output.
*/
/**************************************************************************/
bool NotePrint(const char *text)
{
bool success = false;
if (noteIsDebugOutputActive()) {
NoteDebug(text);
return true;
}
J *req = NoteNewRequest("card.log");
JAddStringToObject(req, "text", text);
success = NoteRequest(req);
return success;
}
//**************************************************************************/
/*!
@brief Get the current epoch time as known by the module. If it isn't known
by the module, just return the time since boot as indicated by the
millisecond clock.
@returns The current time, or the time since boot.
*/
/**************************************************************************/
JTIME NoteTimeST(void)
{
// Handle timer tick wrap by resetting the base
uint32_t nowMs = _GetMs();
if (timeBaseSec != 0 && nowMs < timeBaseSetAtMs) {
int64_t actualTimeMs = 0x100000000LL + (int64_t) nowMs;
int64_t elapsedTimeMs = actualTimeMs - (int64_t) timeBaseSetAtMs;
uint32_t elapsedTimeSecs = (uint32_t) (elapsedTimeMs / 1000);
timeBaseSec += elapsedTimeSecs;
timeBaseSetAtMs = nowMs;
}
// If it's time to refresh the time, do so
if (refreshTimerSecs != 0 && timerExpiredSecs(&timeRefreshTimer, refreshTimerSecs)) {
timeTimer = 0;
}
// If we haven't yet fetched the time, or if we still need the timezone, do
// so with a suppression timer so that we don't hammer the module before
// it's had a chance to connect to the network to fetch time.
if (!timeBaseSetManually && (timeTimer == 0 || timeBaseSec == 0 || zoneStillUnavailable || zoneForceRefresh)) {
if (timerExpiredSecs(&timeTimer, suppressionTimerSecs)) {
// Request time and zone info from the card
J *rsp = NoteRequestResponse(NoteNewRequest("card.time"));
if (rsp != NULL) {
if (!NoteResponseError(rsp)) {
JTIME seconds = JGetInt(rsp, "time");
if (seconds != 0) {
// Set the time
setTime(seconds);
// Get the zone
char *z = JGetString(rsp, "zone");
if (z[0] != '\0') {
char zone[64];
strlcpy(zone, z, sizeof(zone));
// Only use the 3-letter abbrev
char *sep = strchr(zone, ',');
if (sep == NULL) {
zone[0] = '\0';
} else {
*sep = '\0';
}
zoneStillUnavailable = (memcmp(zone, "UTC", 3) == 0);
zoneForceRefresh = false;
strlcpy(curZone, zone, sizeof(curZone));
curZoneOffsetMins = JGetInt(rsp, "minutes");
strlcpy(curCountry, JGetString(rsp, "country"), sizeof(curCountry));
strlcpy(curArea, JGetString(rsp, "area"), sizeof(curArea));
}
}
}
NoteDeleteResponse(rsp);
}
}
}
// Adjust the base time by the number of seconds that have elapsed since
// the base.
JTIME adjustedTime = timeBaseSec + (int32_t) (((int64_t) nowMs - (int64_t) timeBaseSetAtMs) / 1000);
// Done
return adjustedTime;
}
/*!
@brief Set suppression timer secs, returning the previous value.
@param secs New suppression timer seconds.
@returns Previous suppression timer seconds
*/
uint32_t NoteSetSTSecs(uint32_t secs)
{
uint32_t prev = suppressionTimerSecs;
suppressionTimerSecs = secs;
return prev;
}
//**************************************************************************/
/*!
@brief Return local region info, if known. Returns true if valid.
@param retCountry (out) The country.
@param retArea (out) The area value.
@param retZone (out) The timezone value.
@param retZoneOffset (out) The timezone offset.
@returns boolean indicating if the region information is valid.
*/
/**************************************************************************/
bool NoteRegion(char **retCountry, char **retArea, char **retZone, int *retZoneOffset)
{
NoteTimeST();
if (zoneStillUnavailable) {
if (retCountry != NULL) {
*retCountry = (char *) "";
}
if (retArea != NULL) {
*retArea = (char *) "";
}
if (retZone != NULL) {
*retZone = (char *) "UTC";
}
if (retZoneOffset != NULL) {
*retZoneOffset = 0;
}
return false;
}
if (retCountry != NULL) {
*retCountry = curCountry;
}
if (retArea != NULL) {
*retArea = curArea;
}
if (retZone != NULL) {
*retZone = curZone;
}
if (retZoneOffset != NULL) {
*retZoneOffset = curZoneOffsetMins;
}
return true;
}
/*!
@brief Return local time info, if known. Returns true if valid.
@param retYear [out] Pointer to return year value.
@param retMonth [out] Pointer to return month value.
@param retDay [out] Pointer to return day value.
@param retHour [out] Pointer to return hour value.
@param retMinute [out] Pointer to return minute value.
@param retSecond [out] Pointer to return seconds value.
@param retWeekday [out] Pointer to return weekday string.
@param retZone [in,out] If NULL, local time will be returned in UTC, else
returns pointer to zone string
@returns True if either the zone or DST have changed since last call, false
otherwise.
@note Only call this if time is valid.
*/
bool NoteLocalTimeST(uint16_t *retYear, uint8_t *retMonth, uint8_t *retDay,
uint8_t *retHour, uint8_t *retMinute, uint8_t *retSecond, char **retWeekday,
char **retZone)
{
// Preset
if (retYear != NULL) {
*retYear = 0;
}
if (retMonth != NULL) {