c++gpsnmea

How to sychronize the output of NMEA gps sentences


I have two functions :

string get_GPGGA() {
// read_gga_sentence extract only gga
return gps.read_gga_sentence();
}

string get_GPGSA() {
// read_gsa_sentence extract only gsa
return gps.read_gsa_sentence();
}

int main() {
    while(true) {
    cout << get_GPGGA();
    cout << get_GPGSA();
    }
}

The problem is, the gps module transmit 4 sentences in one second. So the first time I call read_gga_sentence(), I have discarded all the other sentences and kept gga. and the same with read_gsa_sentence. But I found out that this creates a delay in my program, because once I call the first get_GPGGA(), it waits 1 second, and then I can call get_GPGSA(). However, I want to be able to print them all in the same 1 second

Do I need multithreading here?


Solution

  • You don't need multithreading, just buffering and a gps.Read() function. Which library do you use ?

    GPS messages are text/line based:

    $GPGGA,092750.000,5321.6802,N,00630.3372,W,1,8,1.03,61.7,M,55.2,M,,*76
    $GPGSA,A,3,10,07,05,02,29,04,08,13,,,,,1.72,1.03,1.38*0A
    $GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70
    $GPGSV,3,2,11,02,39,223,19,13,28,070,17,26,23,252,,04,14,186,14*79
    $GPGSV,3,3,11,29,09,301,24,16,09,020,,36,,,*76
    $GPRMC,092750.000,A,5321.6802,N,00630.3372,W,0.02,31.66,280511,,,A*43
    $GPGGA,092751.000,5321.6802,N,00630.3371,W,1,8,1.03,61.7,M,55.3,M,,*75
    $GPGSA,A,3,10,07,05,02,29,04,08,13,,,,,1.72,1.03,1.38*0A
    $GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70
    $GPGSV,3,2,11,02,39,223,16,13,28,070,17,26,23,252,,04,14,186,15*77
    $GPGSV,3,3,11,29,09,301,24,16,09,020,,36,,,*76
    $GPRMC,092751.000,A,5321.6802,N,00630.3371,W,0.06,31.66,280511,,,A*45
    

    Read them and store each line in a buffer. Then read your buffer starting from the end and find the last GGA message.

    You code could be something like

    // wait 1 GPS message
    string get_GPGGA() {
    buffer.add(gps.Read()); 
    // read_gga_sentence extract only gga
    return buffer.read_last_gga_sentence();
    }
    
    string get_GPGSA() {
    // Wait 1 GPS message
    buffer.add(gps.Read()); 
    // read_gsa_sentence extract last gsa
    return buffer.read_gsa_sentence();
    }
    
    int main() {
        while(true) {
        cout << get_GPGGA();
        cout << get_GPGSA();
        }
    }
    

    Create a GPSBuffer class

    class GPSBuffer {
       void add(string msg);
       string read_last_gga_sentence();
       string read_last_gga_sentence();
    } buffer;