-
Notifications
You must be signed in to change notification settings - Fork 12
/
IridiumSBD.cpp
1655 lines (1443 loc) · 48.5 KB
/
IridiumSBD.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
/*
IridiumSBD - An Arduino library for Iridium SBD ("Short Burst Data") Communications
Suggested and generously supported by Rock Seven Location Technology
(http://rock7mobile.com), makers of the brilliant RockBLOCK satellite modem.
Copyright (C) 2013-2017 Mikal Hart
All rights reserved.
Updated by Paul Clark to provide I2C support for the Qwiic Iridium 9603N
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <time.h>
#include "IridiumSBD.h"
bool ISBDCallback() __attribute__((weak));
void ISBDConsoleCallback(IridiumSBD *device, char c) __attribute__((weak));
void ISBDDiagsCallback(IridiumSBD *device, char c) __attribute__((weak));
bool ISBDCallback() { return true; }
void ISBDConsoleCallback(IridiumSBD *device, char c) { }
void ISBDDiagsCallback(IridiumSBD *device, char c) { }
// Power on the RockBLOCK or return from sleep
int IridiumSBD::begin()
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalBegin();
this->reentrant = false;
// Absent a successful startup, keep the device turned off
if (ret != ISBD_SUCCESS)
power(false);
return ret;
}
// Transmit a binary message
int IridiumSBD::sendSBDBinary(const uint8_t *txData, size_t txDataSize)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalSendReceiveSBD(NULL, txData, txDataSize, NULL, NULL);
this->reentrant = false;
return ret;
}
// Transmit and receive a binary message
int IridiumSBD::sendReceiveSBDBinary(const uint8_t *txData, size_t txDataSize, uint8_t *rxBuffer, size_t &rxBufferSize)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalSendReceiveSBD(NULL, txData, txDataSize, rxBuffer, &rxBufferSize);
this->reentrant = false;
return ret;
}
// Transmit a text message
int IridiumSBD::sendSBDText(const char *message)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalSendReceiveSBD(message, NULL, 0, NULL, NULL);
this->reentrant = false;
return ret;
}
// Transmit a text message and receive reply
int IridiumSBD::sendReceiveSBDText(const char *message, uint8_t *rxBuffer, size_t &rxBufferSize)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalSendReceiveSBD(message, NULL, 0, rxBuffer, &rxBufferSize);
this->reentrant = false;
return ret;
}
// High-level wrapper for AT+CSQ
int IridiumSBD::getSignalQuality(int &quality)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalGetSignalQuality(quality);
this->reentrant = false;
return ret;
}
// Gracefully put device to lower power mode (if sleep pin provided)
int IridiumSBD::sleep()
{
if (this->reentrant)
return ISBD_REENTRANT;
if (this->useSerial && (this->sleepPin == -1))
return ISBD_NO_SLEEP_PIN;
this->reentrant = true;
int ret = internalSleep();
this->reentrant = false;
if (ret == ISBD_SUCCESS)
power(false); // power off
return ret;
}
// Return sleep state
bool IridiumSBD::isAsleep()
{
return this->asleep;
}
// Return number of pending messages
int IridiumSBD::getWaitingMessageCount()
{
return this->remainingMessages;
}
// Define capacitor recharge times
void IridiumSBD::setPowerProfile(POWERPROFILE profile) // 0 = direct connect (default), 1 = USB
{
switch(profile)
{
case DEFAULT_POWER_PROFILE:
this->sbdixInterval = ISBD_DEFAULT_SBDIX_INTERVAL;
break;
case USB_POWER_PROFILE:
this->sbdixInterval = ISBD_USB_SBDIX_INTERVAL;
break;
}
}
// Tweak AT timeout
void IridiumSBD::adjustATTimeout(int seconds)
{
this->atTimeout = seconds;
}
// Tweak Send/Receive SBDIX process timeout
void IridiumSBD::adjustSendReceiveTimeout(int seconds)
{
this->sendReceiveTimeout = seconds;
}
// Tweak ISBD startup timeout
void IridiumSBD::adjustStartupTimeout(int seconds)
{
this->startupTimeout = seconds;
}
void IridiumSBD::useMSSTMWorkaround(bool useWorkAround) // true to use workaround from Iridium Alert 5/7
{
this->msstmWorkaroundRequested = useWorkAround;
}
void IridiumSBD::enableRingAlerts(bool enable) // true to enable SBDRING alerts and RING signal pin
{
this->ringAlertsEnabled = enable;
if (enable)
{
this->ringAsserted = false;
if (!this->useSerial) // If we are using I2C, clear the ring indicator flag
{
clearRingIndicator();
}
}
}
bool IridiumSBD::hasRingAsserted()
// This should only be called occasionally as it will force an I2C transaction each time if we are using I2C
{
if (!ringAlertsEnabled)
return false;
if (!reentrant)
{
// It's possible that the SBDRING message comes while we're not doing anything
filterSBDRING();
}
bool ret = ringAsserted;
this->ringAsserted = false;
if (!this->useSerial) // If we are using I2C, check the RI flag now
{
if (checkRingIndicator()) // If the RI flag is set
{
ret = true; // Return true
diagprint(F("RI flag seen!\r\n"));
clearRingIndicator(); // Clear the flag
}
}
else // If we are using serial then let's check the ringPin manually instead of assuming cancelled() will be able to do it
{
if ((ringPin != -1) && digitalRead(ringPin) == LOW)
{
ret = true; // Return true
//diagprint(F("ringPin seen!\r\n"));
}
}
return ret;
}
int IridiumSBD::getSystemTime(struct tm &tm)
{
char msstmResponseBuf[24];
send(F("AT-MSSTM\r"));
if (!waitForATResponse(msstmResponseBuf, sizeof(msstmResponseBuf), "-MSSTM: "))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
if (!isxdigit(msstmResponseBuf[0]))
return ISBD_NO_NETWORK;
// Latest epoch began at May 11, 2014, at 14:23:55 UTC.
struct tm epoch_start;
epoch_start.tm_year = 2014 - 1900;
epoch_start.tm_mon = 5 - 1;
epoch_start.tm_mday = 11;
epoch_start.tm_hour = 14;
epoch_start.tm_min = 23;
epoch_start.tm_sec = 55;
unsigned long ticks_since_epoch = strtoul(msstmResponseBuf, NULL, 16);
/* Strategy: we'll convert to seconds by finding the largest number of integral
seconds less than the equivalent ticks_since_epoch. Subtract that away and
we'll be left with a small number that won't overflow when we scale by 90/1000.
Many thanks to Scott Weldon for this suggestion.
*/
unsigned long secs_since_epoch = (ticks_since_epoch / 1000) * 90;
unsigned long small_ticks = ticks_since_epoch - (secs_since_epoch / 90) * 1000;
secs_since_epoch += small_ticks * 90 / 1000;
time_t epoch_time = mktime(&epoch_start);
time_t now = epoch_time + secs_since_epoch;
memcpy(&tm, localtime(&now), sizeof tm);
return ISBD_SUCCESS;
}
int IridiumSBD::getFirmwareVersion(char *version, size_t bufferSize)
{
if (bufferSize < 8)
return ISBD_RX_OVERFLOW;
send(F("AT+CGMR\r"));
if (!waitForATResponse(version, bufferSize, "Call Processor Version: "))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
return ISBD_SUCCESS;
}
void IridiumSBD::enableSuperCapCharger(bool enable)
{
if (useSerial) // Do nothing if we are using serial (the user will have to enable the charger manually)
{
diagprint(F("enableSuperCapCharger is only valid when using I2C on the Qwiic Iridium\r\n"));
return;
}
// Enable/disable the supercapacitor charger by pulling its SHDN pin high/low
check9603pins(); // Update IO_REGISTER
if (enable)
{
IO_REGISTER |= IO_SHDN; // Set the SHDN bit
}
else
{
IO_REGISTER &= ~IO_SHDN; // Clear the SHDN bit
}
set9603pins(IO_REGISTER); // Update the pins
}
bool IridiumSBD::checkSuperCapCharger()
{
if (useSerial) // Do nothing if we are using serial (the user will have to check PGOOD manually)
{
diagprint(F("checkSuperCapCharger is only valid when using I2C on the Qwiic Iridium\r\n"));
return(false);
}
// Check the status of the supercapacitor charger PGOOD pin
check9603pins(); // Update IO_REGISTER
if (IO_REGISTER &= IO_PGOOD) // If the PGOOD bit is set, return true
{
return(true);
}
else
{
return(false);
}
}
void IridiumSBD::enable9603Npower(bool enable)
{
if (useSerial) // Do nothing if we are using serial (the user will have to enable the 9603N power manually)
{
diagprint(F("enable9603Npower is only valid when using I2C on the Qwiic Iridium\r\n"));
return;
}
// Enable/disable power to the 9603N by pulling PWR_EN high/low
check9603pins(); // Update IO_REGISTER
if (enable)
{
IO_REGISTER |= IO_PWR_EN; // Set the PWR_EN bit
}
else
{
IO_REGISTER &= ~IO_PWR_EN; // Clear the PWR_EN bit
}
set9603pins(IO_REGISTER); // Update the pins
}
void IridiumSBD::enable9603(bool enable)
{
if (useSerial) // Do nothing if we are using serial (the user will have to enable the 9603N manually)
{
diagprint(F("enable9603 is only valid when using I2C on the Qwiic Iridium\r\n"));
return;
}
// Enable/disable the 9603 by pulling ON_OFF high/low
check9603pins(); // Update IO_REGISTER
if (enable)
{
IO_REGISTER |= IO_ON_OFF; // Set the ON_OFF bit
}
else
{
IO_REGISTER &= ~IO_ON_OFF; // Clear the ON_OFF bit
}
set9603pins(IO_REGISTER); // Update the pins
}
void IridiumSBD::enable841lowPower(bool enable)
{
if (useSerial) // Do nothing if we are using serial
{
diagprint(F("enable841lowPower is only valid when using I2C on the Qwiic Iridium\r\n"));
return;
}
// Enable/disable the Qwiic Iridium ATtiny841's low power mode
check9603pins(); // Update IO_REGISTER
if (enable)
{
IO_REGISTER |= IO_LOW_PWR; // Set the LOW_PWR bit
}
else
{
IO_REGISTER &= ~IO_LOW_PWR; // Clear the LOW_PWR bit
}
set9603pins(IO_REGISTER); // Update the pins
}
bool IridiumSBD::checkRingIndicator()
{
if (useSerial) // Do nothing if we are using serial (the user will have to use hasRingAsserted instead)
{
diagprint(F("checkRingIndicator is only valid when using I2C on the Qwiic Iridium\r\n"));
return(false);
}
// Check the status of the 9603 Ring Indicator flag
check9603pins(); // Update IO_REGISTER
if (IO_REGISTER &= IO_RI) // If the RI bit is set, return true
{
return(true);
}
else
{
return(false);
}
}
void IridiumSBD::clearRingIndicator()
{
if (useSerial) // Do nothing if we are using serial
{
diagprint(F("clearRingIndicator is only valid when using I2C on the Qwiic Iridium\r\n"));
return;
}
// Clear the 9603 RI flag
check9603pins(); // Update IO_REGISTER
IO_REGISTER &= ~IO_RI; // Clear the RI bit
set9603pins(IO_REGISTER); // Update the pins
this->ringAsserted = false; // Also clear the ringAsserted flag
}
bool IridiumSBD::checkNetworkAvailable()
{
if (useSerial) // Do nothing if we are using serial
{
diagprint(F("checkNetworkAvailable is only valid when using I2C on the Qwiic Iridium\r\n"));
return(false);
}
// Check the status of the 9603 Network Available pin
check9603pins(); // Update IO_REGISTER
if (IO_REGISTER &= IO_NA) // If the NA bit is set, return true
{
return(true);
}
else
{
return(false);
}
}
// High-level wrapper for AT+SBDD
int IridiumSBD::clearBuffers(int buffers)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalClearBuffers(buffers);
this->reentrant = false;
return ret;
}
// High-level wrapper for AT+CGSN
int IridiumSBD::getIMEI(char *IMEI, size_t bufferSize)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalGetIMEI(IMEI, bufferSize);
this->reentrant = false;
return ret;
}
//Returns true if the I2C device is connected
//Always returns true for serial
boolean IridiumSBD::isConnected()
{
if (this->useSerial) // If we are using Serial
{
return true;
}
else
{
wireport->beginTransmission((uint8_t)deviceaddress);
return (wireport->endTransmission() == 0); // Check that the device ack's
}
}
// High-level wrapper for passThruI2Cread
int IridiumSBD::passThruI2Cread(uint8_t *rxBuffer, size_t &rxBufferSize, size_t &numBytes)
// rxBuffer is a pointer to the receive buffer which will store the read serial data
// rxBufferSize is the size of the receive buffer (so we don't overflow it)
// On return, numBytes contains the number of bytes written into the rxBuffer (<= rxBufferSize)
// If there was too much data for the rxBuffer, the function will return an ISBD_RX_OVERFLOW error
{
if (useSerial) // Do nothing if we are using serial
{
diagprint(F("passThruI2Cread is only valid when using I2C on the Qwiic Iridium\r\n"));
return(0);
}
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalPassThruI2Cread(rxBuffer, rxBufferSize, numBytes);
this->reentrant = false;
return ret;
}
// High-level wrapper for passThruI2Cwrite
int IridiumSBD::passThruI2Cwrite(uint8_t *txBuffer, size_t &txBufferSize)
// txBuffer is a pointer to the transmit buffer which contains the serial data to be written
// txBufferSize is the number of bytes to be written
{
if (useSerial) // Do nothing if we are using serial
{
diagprint(F("passThruI2Cwrite is only valid when using I2C on the Qwiic Iridium\r\n"));
return(0);
}
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalPassThruI2Cwrite(txBuffer, txBufferSize);
this->reentrant = false;
return ret;
}
/*
Private interface
*/
int IridiumSBD::internalBegin()
{
diagprint(F("Calling internalBegin\r\n"));
if (!this->asleep)
return ISBD_ALREADY_AWAKE;
if (!this->useSerial) // If we are using I2C
{
check9603pins(); // Update IO_REGISTER with the status of the 9603 pins
check9603data(); // Get any waiting 9603 serial data
}
power(true); // power on
bool modemAlive = false;
unsigned long startupTime = 500; //ms
for (unsigned long start = millis(); millis() - start < startupTime;)
if (cancelled())
return ISBD_CANCELLED;
// Turn on modem and wait for a response from "AT" command to begin
for (unsigned long start = millis(); !modemAlive && millis() - start < 1000UL * this->startupTimeout;)
{
send(F("AT\r"));
modemAlive = waitForATResponse();
if (cancelled())
return ISBD_CANCELLED;
}
if (!modemAlive)
{
diagprint(F("No modem detected.\r\n"));
return ISBD_NO_MODEM_DETECTED;
}
// The usual initialization sequence
const char *strings[3] = { "ATE1\r", "AT&D0\r", "AT&K0\r" };
for (int i=0; i<3; ++i)
{
send(strings[i]);
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
}
// Enable or disable RING alerts as requested by user
// By default they are on if a RING pin was supplied on constructor
diagprint(F("Ring alerts are")); diagprint(ringAlertsEnabled ? F("") : F(" NOT")); diagprint(F(" enabled.\r\n"));
if (ringAlertsEnabled) enableRingAlerts(true); // This will clear ringAsserted and the Ring Indicator flag
else {
if (!this->useSerial) clearRingIndicator(); // If ring alerts are not enabled and using I2C, make sure the Ring Indicator flag is clear
}
send(ringAlertsEnabled ? F("AT+SBDMTA=1\r") : F("AT+SBDMTA=0\r"));
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
// Decide whether the internal MSSTM workaround should be enforced on TX/RX
// By default it is unless the firmware rev is >= TA13001
char version[8];
int ret = getFirmwareVersion(version, sizeof(version));
if (ret != ISBD_SUCCESS)
{
diagprint(F("Unknown FW version\r\n"));
msstmWorkaroundRequested = true;
}
else
{
diagprint(F("Firmware version is ")); diagprint(version); diagprint(F("\r\n"));
if (version[0] == 'T' && version[1] == 'A')
{
unsigned long ver = strtoul(version + 2, NULL, 10);
msstmWorkaroundRequested = ver < ISBD_MSSTM_WORKAROUND_FW_VER;
}
}
diagprint(F("MSSTM workaround is")); diagprint(msstmWorkaroundRequested ? F("") : F(" NOT")); diagprint(F(" enforced.\r\n"));
// Done!
diagprint(F("InternalBegin: success!\r\n"));
return ISBD_SUCCESS;
}
int IridiumSBD::internalSendReceiveSBD(const char *txTxtMessage, const uint8_t *txData, size_t txDataSize, uint8_t *rxBuffer, size_t *prxBufferSize)
{
diagprint(F("internalSendReceive\r\n"));
if (this->asleep)
return ISBD_IS_ASLEEP;
// Binary transmission?
if (txData && txDataSize)
{
if (txDataSize > ISBD_MAX_MESSAGE_LENGTH)
return ISBD_MSG_TOO_LONG;
// send will use serial or wire as appropriate
send(F("AT+SBDWB="), true, false);
send(txDataSize);
send(F("\r"), false);
if (!waitForATResponse(NULL, 0, NULL, "READY\r\n"))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
uint16_t checksum = 0;
if (this->useSerial)
{
for (size_t i=0; i<txDataSize; ++i)
{
stream->write(txData[i]);
checksum += (uint16_t)txData[i];
}
stream->write((uint8_t)(checksum >> 8));
stream->write((uint8_t)(checksum & 0xFF));
}
else
{
//lastCheck = millis(); // Update lastCheck so we enforce a full I2C_POLLING_WAIT
// We need to make sure we don't send too much I2C data in one go (otherwise we will overflow the ATtiny841's I2C buffer)
size_t bytes_to_send = txDataSize; // Send this many bytes in total
size_t i=0;
size_t nexti;
while (bytes_to_send > (TINY_I2C_BUFFER_LENGTH - 3)) // If there are too many bytes to send all in one go
{
nexti = i + (TINY_I2C_BUFFER_LENGTH - 3);
wireport->beginTransmission((uint8_t)deviceaddress);
wireport->write(DATA_REG); // Point to the serial data 'register'
for (; i<nexti; ++i)
{
wireport->write(txData[i]); // Write each byte
checksum += (uint16_t)txData[i];
}
bytes_to_send = bytes_to_send - (TINY_I2C_BUFFER_LENGTH - 3); // Decrease the number of bytes still to send
wireport->endTransmission(); // Send data and release the bus (the 841 (WireS) doesn't like it if the Master holds the bus!)
}
// There are now <= (TINY_I2C_BUFFER_LENGTH - 3) bytes left to send, so send them and then release the bus
wireport->beginTransmission((uint8_t)deviceaddress);
wireport->write(DATA_REG); // Point to the 'serial register'
for (; i<txDataSize; ++i)
{
wireport->write(txData[i]);
checksum += (uint16_t)txData[i];
}
wireport->write((uint8_t)(checksum >> 8));
wireport->write((uint8_t)(checksum & 0xFF));
if (wireport->endTransmission() != 0) //Send data and release bus
diagprint(F("I2C write was not successful!\r\n"));
}
consoleprint(F("["));
consoleprint((uint16_t)txDataSize);
consoleprint(F(" bytes]"));
diagprint(F("Checksum:"));
diagprint(checksum);
diagprint(F("\r\n"));
if (!waitForATResponse(NULL, 0, NULL, "0\r\n\r\nOK\r\n"))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
}
else // Text transmission
{
#if true // use long string implementation
if (txTxtMessage == NULL) // It's ok to have a NULL txtTxtMessage if the transaction is RX only
{
send(F("AT+SBDWT=\r"));
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
}
else
{
// remove any embedded \r
char *p = strchr(txTxtMessage, '\r');
if (p) *p = 0;
if (strlen(txTxtMessage) > ISBD_MAX_MESSAGE_LENGTH)
return ISBD_MSG_TOO_LONG;
send(F("AT+SBDWT\r"));
if (!waitForATResponse(NULL, 0, NULL, "READY\r\n"))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
sendlong(txTxtMessage);
send("\r");
if (!waitForATResponse(NULL, 0, NULL, "0\r\n\r\nOK\r\n"))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
}
#else
send(F("AT+SBDWT="), true, false);
if (txTxtMessage != NULL) // It's ok to have a NULL txtTxtMessage if the transaction is RX only
sendlong(txTxtMessage);
send(F("\r"), false);
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
#endif
}
// Long SBDIX loop begins here
for (unsigned long start = millis(); millis() - start < 1000UL * this->sendReceiveTimeout;)
{
bool okToProceed = true;
if (this->msstmWorkaroundRequested)
{
okToProceed = false;
int ret = internalMSSTMWorkaround(okToProceed);
if (ret != ISBD_SUCCESS)
return ret;
}
if (okToProceed)
{
uint16_t moCode = 0, moMSN = 0, mtCode = 0, mtMSN = 0, mtLen = 0, mtRemaining = 0;
int ret = doSBDIX(moCode, moMSN, mtCode, mtMSN, mtLen, mtRemaining);
if (ret != ISBD_SUCCESS)
return ret;
diagprint(F("SBDIX MO code: "));
diagprint(moCode);
diagprint(F("\r\n"));
if (moCode >= 0 && moCode <= 4) // this range indicates successful return!
{
diagprint(F("SBDIX success!\r\n"));
this->remainingMessages = mtRemaining;
if (mtCode == 1 && rxBuffer) // retrieved 1 message
{
diagprint(F("Incoming message!\r\n"));
return doSBDRB(rxBuffer, prxBufferSize);
}
else
{
// No data returned
if (prxBufferSize)
*prxBufferSize = 0;
}
return ISBD_SUCCESS;
}
else if (moCode == 12 || moCode == 14 || moCode == 16) // fatal failure: no retry
{
diagprint(F("SBDIX fatal!\r\n"));
return ISBD_SBDIX_FATAL_ERROR;
}
else // retry
{
diagprint(F("Waiting for SBDIX retry...\r\n"));
if (!noBlockWait(sbdixInterval))
return ISBD_CANCELLED;
}
}
else // MSSTM check fail
{
diagprint(F("Waiting for MSSTM retry...\r\n"));
if (!noBlockWait(ISBD_MSSTM_RETRY_INTERVAL))
return ISBD_CANCELLED;
}
} // big wait loop
diagprint(F("SBDIX timeout!\r\n"));
return ISBD_SENDRECEIVE_TIMEOUT;
}
int IridiumSBD::internalGetSignalQuality(int &quality)
{
if (this->asleep)
return ISBD_IS_ASLEEP;
char csqResponseBuf[2];
send(F("AT+CSQ\r"));
if (!waitForATResponse(csqResponseBuf, sizeof(csqResponseBuf), "+CSQ:"))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
if (isdigit(csqResponseBuf[0]))
{
quality = atoi(csqResponseBuf);
return ISBD_SUCCESS;
}
return ISBD_PROTOCOL_ERROR;
}
int IridiumSBD::internalMSSTMWorkaround(bool &okToProceed)
{
/*
According to Iridium 9602 Product Bulletin of 7 May 2013, to overcome a system erratum:
"Before attempting any of the following commands: +SBDDET, +SBDREG, +SBDI, +SBDIX, +SBDIXA the field application
should issue the AT command AT-MSSTM to the transceiver and evaluate the response to determine if it is valid or not:
Valid Response: "-MSSTM: XXXXXXXX" where XXXXXXXX is an eight-digit hexadecimal number.
Invalid Response: "-MSSTM: no network service"
If the response is invalid, the field application should wait and recheck system time until a valid response is
obtained before proceeding.
This will ensure that the Iridium SBD transceiver has received a valid system time before attempting SBD communication.
The Iridium SBD transceiver will receive the valid system time from the Iridium network when it has a good link to the
satellite. Ensuring that the received signal strength reported in response to AT command +CSQ and +CIER is above 2-3 bars
before attempting SBD communication will protect against lockout.
*/
char msstmResponseBuf[24];
send(F("AT-MSSTM\r"));
if (!waitForATResponse(msstmResponseBuf, sizeof(msstmResponseBuf), "-MSSTM: "))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
// Response buf now contains either an 8-digit number or the string "no network service"
okToProceed = isxdigit(msstmResponseBuf[0]);
return ISBD_SUCCESS;
}
int IridiumSBD::internalSleep()
{
if (this->asleep)
return ISBD_IS_ASLEEP;
#if false // recent research suggest this is not what you should do when just sleeping
// Best Practices Guide suggests this before shutdown
send(F("AT*F\r"));
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
#endif
return ISBD_SUCCESS;
}
bool IridiumSBD::noBlockWait(int seconds)
{
for (unsigned long start=millis(); millis() - start < 1000UL * seconds;)
if (cancelled())
return false;
return true;
}
// Wait for response from previous AT command. This process terminates when "terminator" string is seen or upon timeout.
// If "prompt" string is provided (example "+CSQ:"), then all characters following prompt up to the next CRLF are
// stored in response buffer for later parsing by caller.
bool IridiumSBD::waitForATResponse(char *response, int responseSize, const char *prompt, const char *terminator)
{
diagprint(F("Waiting for response "));
diagprint(terminator);
diagprint(F("\r\n"));
if (response)
memset(response, 0, responseSize);
int matchPromptPos = 0; // Matches chars in prompt
int matchTerminatorPos = 0; // Matches chars in terminator
enum {LOOKING_FOR_PROMPT, GATHERING_RESPONSE, LOOKING_FOR_TERMINATOR};
int promptState = prompt ? LOOKING_FOR_PROMPT : LOOKING_FOR_TERMINATOR;
consoleprint(F("<< "));
for (unsigned long start=millis(); millis() - start < 1000UL * atTimeout;)
{
if (cancelled())
return false;
while (filteredavailable() > 0)
{
char c = filteredread();
if (prompt)
{
switch (promptState)
{
case LOOKING_FOR_PROMPT:
if (c == prompt[matchPromptPos])
{
++matchPromptPos;
if (prompt[matchPromptPos] == '\0')
promptState = GATHERING_RESPONSE;
}
else
{
matchPromptPos = c == prompt[0] ? 1 : 0;
}
break;
case GATHERING_RESPONSE: // gathering response from end of prompt to first \r
if (response)
{
if (c == '\r' || responseSize < 2)
{
promptState = LOOKING_FOR_TERMINATOR;
}
else
{
*response++ = c;
responseSize--;
}
}
break;
}
}
if (c == terminator[matchTerminatorPos])
{
++matchTerminatorPos;
if (terminator[matchTerminatorPos] == '\0')
return true;
}
else
{
matchTerminatorPos = c == terminator[0] ? 1 : 0;
}
} // while (filteredavailable() > 0)
} // timer loop
return false;
}
bool IridiumSBD::cancelled()
{
if (this->useSerial)
{
if ((ringPin != -1) && digitalRead(ringPin) == LOW)
{
ringAsserted = true;
//diagprint(F("ringPin seen!\r\n"));
}
}
return !ISBDCallback();
}
int IridiumSBD::doSBDIX(uint16_t &moCode, uint16_t &moMSN, uint16_t &mtCode, uint16_t &mtMSN, uint16_t &mtLen, uint16_t &mtRemaining)
{
// Returns xx,xxxxx,xx,xxxxx,xx,xxx
char sbdixResponseBuf[32];
send(F("AT+SBDIX\r"));
if (!waitForATResponse(sbdixResponseBuf, sizeof(sbdixResponseBuf), "+SBDIX: "))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
uint16_t *values[6] = { &moCode, &moMSN, &mtCode, &mtMSN, &mtLen, &mtRemaining };
for (int i=0; i<6; ++i)
{
char *p = strtok(i == 0 ? sbdixResponseBuf : NULL, ", ");
if (p == NULL)
return ISBD_PROTOCOL_ERROR;
*values[i] = atol(p);
}
return ISBD_SUCCESS;
}
int IridiumSBD::doSBDRB(uint8_t *rxBuffer, size_t *prxBufferSize)
{
bool rxOverflow = false;
send(F("AT+SBDRB\r"));
if (!waitForATResponse(NULL, 0, NULL, "AT+SBDRB\r")) // waits for its own echo
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
if(!this->useSerial) check9603data(); // Check for any 9603 serial data
// Time to read the binary data: size[2], body[size], checksum[2]
unsigned long start = millis();
while (millis() - start < 1000UL * atTimeout)
{
if(!this->useSerial) check9603data(); // Keep checking for new 9603 serial data
if (cancelled())
return ISBD_CANCELLED;
if (this->useSerial && (stream->available() >= 2))
break;
if ((!this->useSerial) && (i2cSerAvailable() >= 2))
break;
}
if (this->useSerial && (stream->available() < 2))
return ISBD_SENDRECEIVE_TIMEOUT;
if ((!this->useSerial) && (i2cSerAvailable() < 2))
return ISBD_SENDRECEIVE_TIMEOUT;