nmeatknzr.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * =====================================================================================
  3. *
  4. * Filename: nmeatknzr.c
  5. *
  6. * Description: nmea tokenizer source file
  7. *
  8. * Version: 1.0
  9. * Created: 2018/8/15 17:14:56
  10. * Revision: none
  11. * Compiler: gcc
  12. *
  13. * Author: YOUR NAME (),
  14. * Organization:
  15. *
  16. * =====================================================================================
  17. */
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include "nmeatknzr.h"
  21. /*
  22. * Get token from nmea_tokenizer
  23. * @t: the nmea_tokenizer
  24. * @index: index of token
  25. * @return: the token at @index. If @index outof range, return a dummy one.
  26. */
  27. struct token nmea_tokenizer_get(struct nmea_tokenizer *t, int index)
  28. {
  29. static char dummy[] = "";
  30. struct token tok;
  31. if (index < 0 || index >= t->count) {
  32. tok.p = tok.end = dummy;
  33. }
  34. else {
  35. tok = t->tokens[index];
  36. }
  37. return tok;
  38. }
  39. /*
  40. * Init nmea_tokenizer from ptr of NMEA sentence
  41. * @r: the nmea_tokenizer
  42. * @p: ptr to the nmea sentence start
  43. * @end: ptr to the nmea sentence end
  44. * @return: the token's count
  45. */
  46. int nmea_tokenizer_init(struct nmea_tokenizer *t, char *p, char *end)
  47. {
  48. int count = 0;
  49. char *q;
  50. if (p < end && p[0] == '$') { // skip leading '$'
  51. p += 1;
  52. }
  53. if (end > p && end[-1] == '\n') { // skip tailing '\n'
  54. end -= 1;
  55. }
  56. if (end > p && end[-1] == '\r') { // skip tailing '\r'
  57. end -= 1;
  58. }
  59. if (end >= p + 3 && end[-3] == '*') { // skip to '*'
  60. end -= 3;
  61. }
  62. while (p < end) { // split buffer by ','
  63. q = (char *)memchr(p, ',', end - p);
  64. if (q == NULL) {
  65. q = end;
  66. }
  67. if (q >= p) {
  68. if (count < MAX_NMEA_TOKENS) {
  69. t->tokens[count].p = p;
  70. t->tokens[count].end = q;
  71. count += 1;
  72. }
  73. }
  74. if (q < end) {
  75. q += 1;
  76. }
  77. p = q;
  78. }
  79. t->count = count;
  80. return count;
  81. }