Browse Source

add minmea_checksum

Kosma Moczek 11 năm trước cách đây
mục cha
commit
ae62148805
3 tập tin đã thay đổi với 39 bổ sung0 xóa
  1. 15 0
      minmea.c
  2. 5 0
      minmea.h
  3. 19 0
      tests.c

+ 15 - 0
minmea.c

@@ -26,6 +26,21 @@ static int hex2int(char c)
     return -1;
 }
 
+uint8_t minmea_checksum(const char *sentence)
+{
+    // Support senteces with or without the starting dollar sign.
+    if (*sentence == '$')
+        sentence++;
+
+    uint8_t checksum = 0x00;
+
+    // The optional checksum is an XOR of all bytes between "$" and "*".
+    while (*sentence && *sentence != '*')
+        checksum ^= *sentence++;
+
+    return checksum;
+}
+
 bool minmea_check(const char *sentence, bool strict)
 {
     uint8_t checksum = 0x00;

+ 5 - 0
minmea.h

@@ -138,6 +138,11 @@ struct minmea_sentence_gsv {
     struct minmea_sat_info sats[4];
 };
 
+/**
+ * Calculate raw sentence checksum. Does not check sentence integrity.
+ */
+uint8_t minmea_checksum(const char *sentence);
+
 /**
  * Check sentence validity and checksum. Returns true for valid sentences.
  */

+ 19 - 0
tests.c

@@ -56,6 +56,21 @@ static const char *invalid_sentences[] = {
     NULL,
 };
 
+START_TEST(test_minmea_checksum)
+{
+    ck_assert_int_eq(minmea_checksum(""), 0x00);
+    ck_assert_int_eq(minmea_checksum("$"), 0x00);
+    ck_assert_int_eq(minmea_checksum("*"), 0x00);
+    ck_assert_int_eq(minmea_checksum("$*"), 0x00);
+    ck_assert_int_eq(minmea_checksum("$GPTXT,01,01,02,ANTSTATUS=INIT*25"), 0x25);
+    ck_assert_int_eq(minmea_checksum("$GPTXT,01,01,02,ANTSTATUS=INIT"), 0x25);
+    ck_assert_int_eq(minmea_checksum("GPTXT,01,01,02,ANTSTATUS=INIT*25"), 0x25);
+    ck_assert_int_eq(minmea_checksum("GPTXT,01,01,02,ANTSTATUS=INIT"), 0x25);
+    ck_assert_int_eq(minmea_checksum("$GPXTE,A,A,0.67,L,N*6F"), 0x6f);
+    ck_assert_int_eq(minmea_checksum("GPXTE,A,A,0.67,L,N*6f"), 0x6f);
+}
+END_TEST
+
 START_TEST(test_minmea_check)
 {
     for (const char **sentence=valid_sentences_nochecksum; *sentence; sentence++) {
@@ -913,6 +928,10 @@ static Suite *minmea_suite(void)
 {
     Suite *s = suite_create ("minmea");
 
+    TCase *tc_checksum = tcase_create("minmea_checksum");
+    tcase_add_test(tc_checksum, test_minmea_checksum);
+    suite_add_tcase(s, tc_checksum);
+
     TCase *tc_check = tcase_create("minmea_check");
     tcase_add_test(tc_check, test_minmea_check);
     suite_add_tcase(s, tc_check);