/** Flush/empty the position average list @param positionAverageList The position average list */ void flushPositionAverageList(PositionAverageList * positionAverageList) { assert (positionAverageList != NULL); positionAverageList->entriesCount = 0; memset(&positionAverageList->counters, 0, sizeof(positionAverageList->counters)); nmea_zero_INFO(&positionAverageList->positionAverageCumulative.nmeaInfo); memset(&positionAverageList->positionAverageCumulative.track, 0, sizeof(positionAverageList->positionAverageCumulative.track)); memset(&positionAverageList->positionAverageCumulative.mtrack, 0, sizeof(positionAverageList->positionAverageCumulative.mtrack)); memset(&positionAverageList->positionAverageCumulative.magvar, 0, sizeof(positionAverageList->positionAverageCumulative.magvar)); nmea_zero_INFO(&positionAverageList->positionAverage.nmeaInfo); }
int main() { const char *buff[] = { "$GPRMC,173843,A,3349.896,N,11808.521,W,000.0,360.0,230108,013.4,E*69\r\n", "$GPGGA,111609.14,5001.27,N,3613.06,E,3,08,0.0,10.2,M,0.0,M,0.0,0000*70\r\n", "$GPGSV,2,1,08,01,05,005,80,02,05,050,80,03,05,095,80,04,05,140,80*7f\r\n", "$GPGSV,2,2,08,05,05,185,80,06,05,230,80,07,05,275,80,08,05,320,80*71\r\n", "$GPGSA,A,3,01,02,03,04,05,06,07,08,00,00,00,00,0.0,0.0,0.0*3a\r\n", "$GPRMC,111609.14,A,5001.27,N,3613.06,E,11.2,0.0,261206,0.0,E*50\r\n", "$GPVTG,217.5,T,208.8,M,000.00,N,000.01,K*4C\r\n" }; int it; nmeaINFO info; nmeaPARSER parser; nmea_zero_INFO(&info); nmea_parser_init(&parser); for(it = 0; it < 6; ++it) nmea_parse(&parser, buff[it], (int)strlen(buff[it]), &info); nmea_parser_destroy(&parser); return 0; }
int main() { const char *buff = "$GPGGA,073044.000,2235.8106,N,11359.9026,E,1,8,1.01,143.7,M,-2.4,M,,*41\r\n\ $GPRMC,070344.000,A,2235.8106,N,11359.9026,E,0.17,220.01,200916,,,A*6A\r\n"; int it; nmeaINFO info; nmeaPARSER parser; nmea_zero_INFO(&info); nmea_parser_init(&parser); // for(it = 0; it < 1; ++it) nmea_parse(&parser, buff, (int)strlen(buff), &info); printf("gps time:\t%04d-%02d-%02d %02d:%02d:%02d\n", info.utc.year + 1900, info.utc.mon + 1, info.utc.day, info.utc.hour + 8, info.utc.min, info.utc.sec); printf("gps latitude:\t%f\n", info.lat); printf("gps longitude:\t%f\n", info.lon); printf("gps altitude:\t%f\n", info.elv); nmea_parser_destroy(&parser); return 0; }
/////////////////////////////////////////////////////////////////////////////////////////////////// ///NMEAParser_init /////////////////////////////////////////////////////////////////////////////////////////////////// void NMEAParser_init ( void ) { nmeaINFO info; nmeaPARSER parser; nmea_zero_INFO ( &info ); nmea_parser_init ( &parser ); }
// [ref] ${NMEALIB_HOME)/samples/generator/main.c. void use_generator() { nmeaINFO info; nmea_zero_INFO(&info); nmeaGENERATOR *gen = nmea_create_generator(NMEA_GEN_ROTATE, &info); if (0 == gen) { std::cerr << "generator not created" << std::endl; return; } char buff[2048]; for (int i = 0; i < 10000; ++i) { const int gen_sz = nmea_generate_from(buff, 2048, &info, gen, GPGGA | GPGSA | GPGSV | GPRMC | GPVTG); // for display. buff[gen_sz] = '\0'; std::cout << buff << std::endl; #ifdef NMEA_WIN Sleep(500); #else usleep(500000); #endif } nmea_gen_destroy(gen); }
void awal_gps() { nmea_zero_INFO(&infoGPS); nmea_parser_init(&parserGPS); printf(" Monita : GPS init !!\r\n"); //strcpy(pesanGPS, "$GPRMC,084702.000,A,0612.6782,S,10654.3289,E,0.00,278.92,030511,,,A*72\r\n"); }
/** * static int Gps_set(void * _self, va_list *app) - Perform a new gps acquisition. * \param *_self - pointer to the device * \param *app - none * \return: <LI><Breturn = 0:</B>when the GPS device is connected on a Grove nest DIG port, with or without a valid connection </LI> <LI><Breturn = -1:</B>when the GPS device is not connected on a Grove nest DIG port. </LI> </UL> */ static int Gps_set(void *_self,va_list *app) { struct Gps *self = _self; char gps_sentences[70]; unsigned int timer = 65000; flag = 1; nmea_zero_INFO(&self->info); nmea_parser_init(&self->parser); UARTOn(self->uart_module); UARTFlush(self->uart_module); vTaskDelay(50); while((UARTBufferSize(self->uart_module)<3) && timer) timer--; if(!timer) return -1; timer = 500; while((gps_sentences[0] != '$') && timer) { timer--; while(UARTBufferSize(self->uart_module)<1); UARTRead(self->uart_module,gps_sentences,1); if(gps_sentences[0] == '$') { while(UARTBufferSize(self->uart_module) < 5); UARTRead(self->uart_module,(gps_sentences+1),5); //Reads all the chars in the if((gps_sentences[4] == 'M')) { while(UARTBufferSize(self->uart_module) < 65); UARTRead(self->uart_module,(gps_sentences+6),64); //Reads all the chars in the gps_sentences[70] = '\0'; int i = 0; i = nmea_parse(&self->parser, gps_sentences, (int)strlen(gps_sentences), &self->info); if(i) { flag = 0; self->lat = nmea_ndeg2degree (self->info.lat); self->lon = -nmea_ndeg2degree (self->info.lon); self->year = self->info.utc.year+1900; self->mon = self->info.utc.mon; self->day = self->info.utc.day; self->hour = self->info.utc.hour; self->min = self->info.utc.min; self->sec = self->info.utc.sec; self->speed = self->info.speed; break; } } } gps_sentences[0]= 0; } nmea_parser_destroy(&self->parser); UARTOff(self->uart_module); return 0; }
int main() { static const char * filename = "../../samples/parse_file/gpslog.txt"; nmeaINFO info; nmeaPARSER parser; FILE *file; char buff[2048]; int size, it = 0; nmeaPOS dpos; file = fopen(filename, "rb"); if(!file) { printf("Could not open file %s\n", filename); return -1; } nmea_property()->trace_func = &trace; nmea_property()->error_func = &error; nmea_zero_INFO(&info); nmea_parser_init(&parser); /* while(1) { */ while(!feof(file)) { size = (int)fread(&buff[0], 1, 100, file); nmea_parse(&parser, &buff[0], size, &info); nmea_info2pos(&info, &dpos); printf( "%03d, Lat: %f, Lon: %f, Sig: %d, Fix: %d\n", it++, dpos.lat, dpos.lon, info.sig, info.fix ); } fseek(file, 0, SEEK_SET); /* } */ nmea_parser_destroy(&parser); fclose(file); return 0; }
boatReal::boatReal(QString pseudo, bool activated, Projection * proj,MainWindow * main, myCentralWidget * parent): boat(pseudo,activated,proj,main,parent) { qWarning()<<"creating boat real"; setData(0,BOATREAL_WTYPE); isMoving=false; set_boatType(BOAT_REAL); setFont(QApplication::font()); /* init thread */ gpsReader = NULL; nmea_zero_INFO(&info); this->lat=0; this->lon=0; this->vacLen=300; trace=new vlmLine(proj,parent->getScene(),Z_VALUE_ESTIME); previousLon=lon; previousLat=lat; QPen penTrace; penTrace.setColor(Qt::red); penTrace.setBrush(Qt::red); penTrace.setWidthF(0.5); trace->setNbVacPerHour(3600/this->getVacLen()); trace->setLinePen(penTrace); trace->slot_showMe(); gotPosition=false; WP=QPointF(0,0); this->speed=0; this->heading=0; this->windSpeed=-1; this->setStatus(true); this->playerName=pseudo; this->fix=1; this->sig=0; this->eta=-1; changeLocked=false; forceEstime=false; this->declinaison=Settings::getSetting("declinaison",0).toDouble(); this->minSpeedForEngine=Settings::getSetting("minSpeedForEngine",0).toDouble(); this->speedWithEngine=Settings::getSetting("speedWithEngine",4).toDouble(); myCreatePopUpMenu(); connect(this->popup,SIGNAL(aboutToShow()),parent,SLOT(slot_resetGestures())); connect(this->popup,SIGNAL(aboutToHide()),parent,SLOT(slot_resetGestures())); this->lastUpdateTime=QDateTime().currentDateTimeUtc().toTime_t(); this->displayNMEA=false; this->pause=true; }
ReceiverThread::ReceiverThread(boatReal * parent) { qRegisterMetaType<nmeaINFO>("nmeaINFO"); connect(this,SIGNAL(updateBoat(nmeaINFO)),parent,SLOT(updateBoat(nmeaINFO))); connect(this,SIGNAL(finished()),parent,SLOT(slot_threadStartedOrFinished())); connect(this,SIGNAL(started()),parent,SLOT(slot_threadStartedOrFinished())); port=NULL; //initPort(); this->parent=parent; nmea_zero_INFO(&info); nmea_parser_init(&parser); if(parser.buff_size==0) qWarning()<<"no parser!!!"; this->listNMEA=NULL; }
int main() { const char *buff[] = { "$GPGGA,000000,2508.644,N,12145.244,E,8,00,99.9,00000,M,00000,M,,*4A\r\n\r\n", "$SDDBT,0008.2,f,0002.5,M,0001.4,F*3E\r\n\r\n" }; const char *buff2[] = { "$GPDTM,W84,,0.0000,N,0.0000,E,0.0000,W84*5F\r\n", "$GPAPB,V,V,-0.00,L,N,V,V,090.2,T,0009,090.2,T,090.2,T,N*6F\r\n", "$GPBOD,090.2,T,090.2,M,0009,0000*4E\r\n", "$GPBWC,000000,2508.956,N,12146.687,E,090.2,T,090.2,M,000.27,N,N*74\r\n", "$GPGGA,000000,2508.957,N,12146.385,E,0,00,99.9,00000,M,00000,M,,*40\r\n", "$GPGBS,,,,,,,,*41\r\n", "$GPRMC,000000,V,2508.957,N,12146.385,E,00.0,000.0,010105,,,N*57\r\n", "$GPVTG,000.0,T,,,00.0,N,00.0,K,N*4F\r\n", "$GPRMC,000000,V,2515.791,N,12145.337,E,00.0,251.7,010105,,,S*49\r\n" }; int it; for(it = 0; it < 2; ++it) { nmeaINFO info; nmeaPARSER parser; nmea_zero_INFO(&info); nmea_parser_init(&parser); nmea_parse(&parser, buff[it], (int)strlen(buff[it]), &info); printf("parse: %s\n", buff[it]); printf("declination: %f\n", info.declination); printf("utc.min: %f\n", info.utc.min); printf("HDOP: %f\n", info.HDOP); printf("VDOP: %f\n", info.VDOP); printf("lat: %f\n", info.lat); printf("lon: %f\n", info.lon); printf("elv: %f\n", info.elv); printf("depth: %f\n", info.depthinfo.depth_M); nmea_parser_destroy(&parser); } return 0; }
int main() { nmeaINFO info; char buff[2048]; int gen_sz; int it; nmea_zero_INFO(&info); info.sig = 3; info.fix = 3; info.lat = 5000.0; info.lon = 3600.0; info.speed = 2.14 * NMEA_TUS_MS; info.elv = 10.86; info.satinfo.inuse = 1; info.satinfo.inview = 1; /* info.satinfo.sat[0].id = 1; info.satinfo.sat[0].in_use = 1; info.satinfo.sat[0].elv = 50; info.satinfo.sat[0].azimuth = 0; info.satinfo.sat[0].sig = 99; */ for(it = 0; it < 10; ++it) { gen_sz = nmea_generate( &buff[0], 2048, &info, GPGGA | GPGSA | GPGSV | GPRMC | GPVTG ); buff[gen_sz] = 0; printf("%s\n", &buff[0]); usleep(500000); info.speed += .1; } return 0; }
int nmea_gen_init(nmeaGENERATOR *gen, nmeaINFO *info) { int RetVal = 1; int smask = info->smask; nmeaGENERATOR *igen = gen; nmea_zero_INFO(info); info->smask = smask; info->lat = NMEA_DEF_LAT; info->lon = NMEA_DEF_LON; while(RetVal && igen) { if(igen->init_call) RetVal = (*igen->init_call)(igen, info); igen = igen->next; } return RetVal; }
int main() { nmeaGENERATOR *gen; nmeaINFO info; char buff[2048]; int gen_sz; int it; FILE* file; nmea_zero_INFO(&info); if(0 == (gen = nmea_create_generator(NMEA_GEN_ROTATE, &info))) return -1; file = fopen("go.txt", "w"); for(it = 0; it < 100; ++it) { memset(buff, 0, 2048); gen_sz = nmea_generate_from( &buff[0], 2048, &info, gen, GPGGA | SDDBT // | GPGSA | GPGSV | GPRMC | GPVTG ); buff[gen_sz] = 0; //printf("%s\n", &buff[0]); fprintf(file, "%s", buff); #ifdef NMEA_WIN //Sleep(500); #else usleep(500000); #endif } fclose(file); nmea_gen_destroy(gen); return 0; }
void RealtimeRunningData::produceData() { running_data_t data; nmeaINFO info; if (m_gps) info = m_gps->getInfo(); else nmea_zero_INFO(&info); data.datatime = QDateTime::currentDateTime(); data.latitude = info.lat; data.longtitude = info.lon; data.velocity = info.speed; data.oriention = info.direction; //data.distant =; if (m_flowmeter) { data.flowrate = m_flowmeter->flowrate(); data.totalflow = m_flowmeter->totalflow(); } else { data.flowrate = 0.0; data.totalflow = 0.0; } m_data = data; saveData(m_data); emit dataProduced(m_data); //std::cerr << "realtime produced." << QTime::currentTime().toString().toStdString() << std::endl; m_timer.start(1000 * (g_settings.RunningDataInterval().toInt() - QTime::currentTime().second() % g_settings.RunningDataInterval().toInt())); }
// [ref] ${NMEALIB_HOME)/samples/generate/main.c. void generate() { nmeaINFO info; nmea_zero_INFO(&info); info.sig = 3; info.fix = 3; info.lat = 5000.0; info.lon = 3600.0; info.speed = 2.14 * NMEA_TUS_MS; info.elv = 10.86; info.satinfo.inuse = 1; info.satinfo.inview = 1; /* info.satinfo.sat[0].id = 1; info.satinfo.sat[0].in_use = 1; info.satinfo.sat[0].elv = 50; info.satinfo.sat[0].azimuth = 0; info.satinfo.sat[0].sig = 99; */ char buff[2048]; for (int i = 0; i < 10; ++i) { const int gen_sz = nmea_generate(buff, 2048, &info, GPGGA | GPGSA | GPGSV | GPRMC | GPVTG); // for display. buff[gen_sz] = '\0'; std::cout << buff << std::endl; #ifdef NMEA_WIN Sleep(500); #else usleep(500000); #endif info.speed += .1; } }
int parse_gps(char * database, int tripid) { int retval; // Open database connection retval = sqlite3_open(database, &handle); if (retval) { printf("GPS Parsing: Database connection failed: %d\n", retval); return -1; } sqlite3_exec(handle, "PRAGMA synchronous = NORMAL", 0, 0, 0); sqlite3_exec(handle, "PRAGMA journal_mode = MEMORY", 0, 0, 0); // Select data from database char selectquery[100]; sprintf(selectquery, "SELECT Gps_ID, RawData FROM GpsData WHERE Trip_ID = %d", tripid); sqlite3_stmt *stmt; retval = sqlite3_prepare_v2(handle, selectquery, -1, &stmt, 0); if (retval) { printf("GPS Parsing: Selecting data from DB Failed: %d\n", retval); printf("Query: %s\n", selectquery); return -1; } // Initialize NMEA parser nmeaINFO info; nmeaPARSER parser; nmea_zero_INFO(&info); nmea_parser_init(&parser); // Begin SQL transaction sqlite3_exec(handle, "BEGIN TRANSACTION", 0, 0, 0); // Step through SELECT query while (1) { retval = sqlite3_step(stmt); if (retval == SQLITE_ROW) { // Gather row from database int gpsid = (int) sqlite3_column_int(stmt, 0); char *rawdata = (char*) sqlite3_column_text(stmt, 1); int len = (int) strlen(rawdata); // Parse NMEA data nmea_parse(&parser, rawdata, len, &info); // Convert time format to C_time struct tm converttime; converttime.tm_year = info.utc.year; converttime.tm_mon = info.utc.mon; converttime.tm_mday = info.utc.day; converttime.tm_hour = info.utc.hour; converttime.tm_min = info.utc.min; converttime.tm_sec = info.utc.sec; // Update row with NMEA data char query[200]; sprintf( query, "UPDATE GpsData SET UTC = %f, Fix = %d, Latitude = %f, Longitude = %f, Speed = %f, Direction = %f, Declination = %f WHERE Gps_ID = %d", (float) mktime(&converttime), info.fix, nmea_ndeg2degree(info.lat), nmea_ndeg2degree(info.lon), info.speed, info.direction, info.declination, gpsid); retval = sqlite3_exec(handle, query, 0, 0, 0); if (retval) { printf("GPS Parsing: Updating data in DB Failed: %d\n", retval); return -1; } } else if (retval == SQLITE_DONE) { break; } else { printf("GPS Parsing: SQL error whilst reading rows: %d\n", retval); return -1; } } // End SQL transaction sqlite3_exec(handle, "END TRANSACTION", 0, 0, 0); // Remove unnecesary data char removequery[100]; sprintf(removequery, "DELETE FROM GpsData WHERE RawData NOT LIKE '$GPRMC%%'"); retval = sqlite3_exec(handle, removequery, 0, 0, 0); if (retval) { printf("GPS Parsing: Removing data from DB Failed: %d\n", retval); printf("Query: %s\n", removequery); return -1; } // Destroy the evidence! nmea_parser_destroy(&parser); sqlite3_close(handle); return 0; }
void GpsInfo::reset() { // Reset the GPS info nmea_zero_INFO(&_info); }
int main() { const char *buff[] = { "$GPRMC,213916.199,A,4221.0377,N,07102.9778,W,0.00,,010207,,,A*6A\r\n", "$GPRMC,213917.199,A,4221.0510,N,07102.9549,W,0.23,175.43,010207,,,A*77\r\n", "$GPRMC,213925.000,A,4221.1129,N,07102.9146,W,0.00,,010207,,,A*68\r\n", "$GPRMC,111609.14,A,5001.27,N,3613.06,E,11.2,0.0,261206,0.0,E*50\r\n" }; nmeaPOS pos[NUM_POINTS], pos_moved[NUM_POINTS][2]; double dist[NUM_POINTS][2]; double azimuth[NUM_POINTS][2], azimuth_moved[NUM_POINTS]; int result[2]; int it = 0; nmeaPARSER parser; nmea_parser_init(&parser); for(it = 0; it < NUM_POINTS; ++it) { nmeaINFO info; nmea_zero_INFO(&info); (void)nmea_parse(&parser, buff[it], (int)strlen(buff[it]), &info); nmea_info2pos(&info, &pos[it]); } nmea_parser_destroy(&parser); for(it = 0; it < NUM_POINTS; ++it) { dist[it][0] = nmea_distance(&pos[0], &pos[it]); dist[it][1] = nmea_distance_ellipsoid( &pos[0], &pos[it], &azimuth[it][0], &azimuth[it][1] ); } for(it = 0; it < NUM_POINTS; ++it) { result[0] = nmea_move_horz(&pos[0], &pos_moved[it][0], azimuth[it][0], dist[it][0]); result[1] = nmea_move_horz_ellipsoid( &pos[0], &pos_moved[it][1], azimuth[it][0], dist[it][0], &azimuth_moved[it] ); } /* Output of results */ printf("Coordinate points:\n"); for(it = 0; it < NUM_POINTS; ++it) { printf( "P%d in radians: lat:%9.6lf lon:%9.6lf \tin degree: lat:%+010.6lf° lon:%+011.6lf°\n", it, pos[it].lat, pos[it].lon, nmea_radian2degree(pos[it].lat), nmea_radian2degree(pos[it].lon) ); } printf("\nCalculation results:\n"); for(it = 0; it < NUM_POINTS; ++it) { printf("\n"); printf("Distance P0 to P%d\ton spheroid: %14.3lf m\n", it, dist[it][0]); printf("Distance P0 to P%d\ton ellipsoid: %14.3lf m\n", it, dist[it][1]); printf("Azimuth P0 to P%d\tat start: %8.3lf°\tat end: %8.3lf°\n", it, nmea_radian2degree(azimuth[it][0]), nmea_radian2degree(azimuth[it][1])); printf("Move P0 to P%d\t \tAzimuth at end: %8.3lf°\n", it, nmea_radian2degree(azimuth_moved[it])); printf("Move P0 to P%d\ton spheroid: %3s lat:%+010.6lf° lon:%+011.6lf°\n", it, result[0] == 1 ? "OK" : "nOK", nmea_radian2degree(pos_moved[it][0].lat), nmea_radian2degree(pos_moved[it][0].lon)); printf("Move P0 to P%d\ton ellipsoid: %3s lat:%+010.6lf° lon:%+011.6lf°\n", it, result[0] == 1 ? "OK" : "nOK", nmea_radian2degree(pos_moved[it][1].lat), nmea_radian2degree(pos_moved[it][1].lon)); printf("Move P0 to P%d\toriginal: lat:%+010.6lf° lon:%+011.6lf°\n", it, nmea_radian2degree(pos[it].lat), nmea_radian2degree(pos[it].lon)); } return 0; }
int nmea_decode_test(void){ int tempOut=0; s16 AccelGyro[7]={0}; s16 TempBuffer[7]={0}; nmeaINFO info; //GPS parsed info nmeaPARSER parser; //struct used for decoding uint8_t new_parse=0; //new or not, have history? nmeaTIME beiJingTime; nmea_property()->trace_func = &trace; nmea_property()->error_func = &error; //GPS initialization nmea_zero_INFO(&info); nmea_parser_init(&parser); while(1) { if(GPS_HalfTransferEnd) /* received half the buffer size*/ { /* parse using nmea format */ nmea_parse(&parser, (const char*)&gps_rbuff[0], HALF_GPS_RBUFF_SIZE, &info); GPS_HalfTransferEnd = 0; //Clear flag new_parse = 1; //new info } else if(GPS_TransferEnd) /* receiving the other half */ { nmea_parse(&parser, (const char*)&gps_rbuff[HALF_GPS_RBUFF_SIZE], HALF_GPS_RBUFF_SIZE, &info); GPS_TransferEnd = 0; new_parse =1; } if(new_parse ) //if have new info { //Converts time to GMT GMTconvert(&info.utc,&beiJingTime,8,1); /* Output data*/ printf("\r\n Time:%d,%d,%d,%d,%d,%d\r\n", beiJingTime.year+1900, beiJingTime.mon+1,beiJingTime.day,beiJingTime.hour,beiJingTime.min,beiJingTime.sec); printf("\r\n Latitude:%f,Longtitude:%f\r\n",info.lat,info.lon); printf("\r\n Numbers of Sat in use:%d, Numbers of Sat in view:%d",info.satinfo.inuse,info.satinfo.inview); printf("\r\n Numbers of meters above horizon: %f", info.elv); printf("\r\n Speed: %f km/h ", info.speed); printf("\r\n Direction: %f degree", info.direction); new_parse = 0; } //--------------------------actual loop------------------------ //------------------------this is imu------------------------ printf("\r\nMPU Readings:"); MPU6050_GetRawAccelGyro(AccelGyro); printf("\r\nIMU[0]: %10d",AccelGyro[0]); printf("\t IMU[1]: %10d",AccelGyro[1]); printf("\t IMU[2]: %10d",AccelGyro[2]); printf("\t IMU[3]: %10d",AccelGyro[3]); printf("\t IMU[4]: %10d",AccelGyro[4]); printf("\t IMU[5]: %10d",AccelGyro[5]); //--------------------------temp loop-------------------------- //tempOut=USART3_getTemp(); //printf("\r\n temp is: %d\n",tempOut); //------------------------------------------------------------- delay_ms(1000); } }
void *nmea_loop(void *args) { /* Set thread name */ prctl(PR_SET_NAME, "gps nmea read", getpid()); /* Retrieve file descriptor and thread flag */ struct arg_struct *arguments = (struct arg_struct *)args; int *fd = arguments->fd_ptr; bool *thread_should_exit = arguments->thread_should_exit_ptr; /* Initialize gps stuff */ nmeaINFO info_d; nmeaINFO *info = &info_d; char gps_rx_buffer[NMEA_BUFFER_SIZE]; /* gps parser (nmea) */ nmeaPARSER parser; nmea_parser_init(&parser); nmea_zero_INFO(info); /* advertise GPS topic */ struct vehicle_gps_position_s nmea_gps_d = {.counter=0}; nmea_gps = &nmea_gps_d; orb_advert_t gps_handle = orb_advertise(ORB_ID(vehicle_gps_position), nmea_gps); while (!(*thread_should_exit)) { /* Parse a message from the gps receiver */ uint8_t read_res = read_gps_nmea(fd, gps_rx_buffer, NMEA_BUFFER_SIZE, info, &parser); if (0 == read_res) { /* convert data, ready it for publishing */ /* convert nmea utc time to usec */ struct tm timeinfo; timeinfo.tm_year = info->utc.year; timeinfo.tm_mon = info->utc.mon; timeinfo.tm_mday = info->utc.day; timeinfo.tm_hour = info->utc.hour; timeinfo.tm_min = info->utc.min; timeinfo.tm_sec = info->utc.sec; time_t epoch = mktime(&timeinfo); // printf("%d.%d.%d %d:%d:%d:%d\n", timeinfo.tm_year, timeinfo.tm_mon, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, info->utc.hsec); nmea_gps->timestamp = hrt_absolute_time(); nmea_gps->time_gps_usec = (uint64_t)((epoch)*1000000 + (info->utc.hsec)*10000); nmea_gps->fix_type = (uint8_t)info->fix; nmea_gps->lat = (int32_t)(ndeg2degree(info->lat) * 1e7f); nmea_gps->lon = (int32_t)(ndeg2degree(info->lon) * 1e7f); nmea_gps->alt = (int32_t)(info->elv * 1000.0f); nmea_gps->eph = (uint16_t)(info->HDOP * 100); //TODO:test scaling nmea_gps->epv = (uint16_t)(info->VDOP * 100); //TODO:test scaling nmea_gps->vel = (uint16_t)(info->speed * 1000 / 36); //*1000/3600*100 nmea_gps->cog = (uint16_t)info->direction*100; //nmea: degrees float, ubx/mavlink: degrees*1e2 nmea_gps->satellites_visible = (uint8_t)info->satinfo.inview; int i = 0; /* Write info about individual satellites */ for (i = 0; i < 12; i++) { nmea_gps->satellite_prn[i] = (uint8_t)info->satinfo.sat[i].id; nmea_gps->satellite_used[i] = (uint8_t)info->satinfo.sat[i].in_use; nmea_gps->satellite_elevation[i] = (uint8_t)info->satinfo.sat[i].elv; nmea_gps->satellite_azimuth[i] = (uint8_t)info->satinfo.sat[i].azimuth; nmea_gps->satellite_snr[i] = (uint8_t)info->satinfo.sat[i].sig; } if (nmea_gps->satellites_visible > 0) { nmea_gps->satellite_info_available = 1; } else { nmea_gps->satellite_info_available = 0; } nmea_gps->counter_pos_valid++; nmea_gps->timestamp = hrt_absolute_time(); nmea_gps->counter++; pthread_mutex_lock(nmea_mutex); nmea_state->last_message_timestamp = hrt_absolute_time(); pthread_mutex_unlock(nmea_mutex); /* publish new GPS position */ orb_publish(ORB_ID(vehicle_gps_position), gps_handle, nmea_gps); } else if (read_res == 2) { //termination /* de-advertise */ close(gps_handle); break; } } //destroy gps parser nmea_parser_destroy(&parser); if(gps_verbose) printf("[gps] nmea loop is going to terminate\n"); return NULL; } void *nmea_watchdog_loop(void *args) { /* Set thread name */ prctl(PR_SET_NAME, "gps nmea watchdog", getpid()); bool nmea_healthy = false; uint8_t nmea_fail_count = 0; uint8_t nmea_success_count = 0; bool once_ok = false; /* Retrieve file descriptor and thread flag */ struct arg_struct *arguments = (struct arg_struct *)args; //int *fd = arguments->fd_ptr; bool *thread_should_exit = arguments->thread_should_exit_ptr; int mavlink_fd = open(MAVLINK_LOG_DEVICE, 0); while (!(*thread_should_exit)) { // printf("nmea_watchdog_loop : while "); /* if we have no update for a long time print warning (in nmea mode there is no reconfigure) */ pthread_mutex_lock(nmea_mutex); uint64_t timestamp_now = hrt_absolute_time(); bool all_okay = true; if (timestamp_now - nmea_state->last_message_timestamp > NMEA_WATCHDOG_CRITICAL_TIME_MICROSECONDS) { all_okay = false; } pthread_mutex_unlock(nmea_mutex); if (!all_okay) { /* gps error */ nmea_fail_count++; // printf("nmea error, nmea_fail_count=%u\n", nmea_fail_count); // fflush(stdout); /* If we have too many failures and another mode or baud should be tried, exit... */ if ((gps_mode_try_all == true || gps_baud_try_all == true) && (nmea_fail_count >= NMEA_HEALTH_FAIL_COUNTER_LIMIT) && (nmea_healthy == false) && once_ok == false) { if (gps_verbose) printf("\t[gps] no NMEA module found\n"); gps_mode_success = false; break; } if (nmea_healthy && nmea_fail_count >= NMEA_HEALTH_FAIL_COUNTER_LIMIT) { printf("\t[gps] ERROR: NMEA GPS module stopped responding\n"); // global_data_send_subsystem_info(&nmea_present_enabled); mavlink_log_critical(mavlink_fd, "[gps] NMEA module stopped responding\n"); nmea_healthy = false; nmea_success_count = 0; } fflush(stdout); sleep(1); } else { /* gps healthy */ // printf("\t[gps] nmea success\n"); nmea_success_count++; if (!nmea_healthy && nmea_success_count >= NMEA_HEALTH_SUCCESS_COUNTER_LIMIT) { printf("[gps] NMEA module found, status ok (baud=%d)\r\n", current_gps_speed); // global_data_send_subsystem_info(&nmea_present_enabled_healthy); mavlink_log_info(mavlink_fd, "[gps] NMEA module found, status ok\n"); nmea_healthy = true; nmea_fail_count = 0; once_ok = true; } } usleep(NMEA_WATCHDOG_WAIT_TIME_MICROSECONDS); } if(gps_verbose) printf("[gps] nmea watchdog loop is going to terminate\n"); close(mavlink_fd); return NULL; }
/** * Read the position file * @param fileName the filename * @param nmeaInfo the NMEA data */ bool readPositionFile(char * fileName, nmeaINFO * nmeaInfo) { bool retval = false; struct stat statBuf; nmeaINFO result; FILE * fd = NULL; unsigned int lineNumber = 0; char * name = NULL; char * value = NULL; if (stat(fileName, &statBuf)) { /* could not access the file */ goto out; } if (!memcmp(&cachedStat.timeStamp, &statBuf.st_mtime, sizeof(cachedStat.timeStamp))) { /* file did not change since last read */ goto out; } fd = fopen(fileName, "r"); if (!fd) { goto out; } nmea_zero_INFO(&result); result.sig = POSFILE_DEFAULT_SIG; result.fix = POSFILE_DEFAULT_FIX; result.HDOP = POSFILE_DEFAULT_HDOP; result.VDOP = POSFILE_CALCULATED_VDOP(result.HDOP); result.PDOP = POSFILE_CALCULATED_PDOP(result.HDOP); result.lat = POSFILE_DEFAULT_LAT; result.lon = POSFILE_DEFAULT_LON; result.elv = POSFILE_DEFAULT_ELV; result.speed = POSFILE_DEFAULT_SPEED; result.track = POSFILE_DEFAULT_TRACK; result.mtrack = POSFILE_DEFAULT_MTRACK; result.magvar = POSFILE_DEFAULT_MAGVAR; memcpy(&cachedStat.timeStamp, &statBuf.st_mtime, sizeof(cachedStat.timeStamp)); while (fgets(line, LINE_LENGTH, fd)) { regmatch_t pmatch[regexNameValuematchCount]; lineNumber++; if (regexMatch(®exComment, line, 0, NULL)) { continue; } if (!regexMatch(®exNameValue, line, regexNameValuematchCount, pmatch)) { pudError(false, "Position file \"%s\", line %d uses invalid syntax: %s", fileName, lineNumber, line); goto out; } /* determine name/value */ name = &line[pmatch[1].rm_so]; line[pmatch[1].rm_eo] = '\0'; value = &line[pmatch[2].rm_so]; line[pmatch[2].rm_eo] = '\0'; if (!strncasecmp(POSFILE_NAME_SIG, name, sizeof(line))) { if (!strncasecmp(POSFILE_VALUE_SIG_BAD, value, sizeof(line))) { result.sig = NMEA_SIG_BAD; } else if (!strncasecmp(POSFILE_VALUE_SIG_LOW, value, sizeof(line))) { result.sig = NMEA_SIG_LOW; } else if (!strncasecmp(POSFILE_VALUE_SIG_MID, value, sizeof(line))) { result.sig = NMEA_SIG_MID; } else if (!strncasecmp(POSFILE_VALUE_SIG_HIGH, value, sizeof(line))) { result.sig = NMEA_SIG_HIGH; } else { pudError(false, "Position file \"%s\", line %d uses an invalid value for \"%s\"," " valid values are [%s|%s\%s|%s]", fileName, lineNumber, POSFILE_NAME_SIG, POSFILE_VALUE_SIG_BAD, POSFILE_VALUE_SIG_LOW, POSFILE_VALUE_SIG_MID, POSFILE_VALUE_SIG_HIGH); goto out; } nmea_INFO_set_present(&result.present, SIG); } else if (!strncasecmp(POSFILE_NAME_FIX, name, sizeof(line))) { if (!strncasecmp(POSFILE_VALUE_FIX_BAD, value, sizeof(line))) { result.fix = NMEA_FIX_BAD; } else if (!strncasecmp(POSFILE_VALUE_FIX_2D, value, sizeof(line))) { result.fix = NMEA_FIX_2D; } else if (!strncasecmp(POSFILE_VALUE_FIX_3D, value, sizeof(line))) { result.fix = NMEA_FIX_3D; } else { pudError(false, "Position file \"%s\", line %d uses an invalid value for \"%s\"," " valid values are [%s\%s|%s]", fileName, lineNumber, POSFILE_NAME_FIX, POSFILE_VALUE_FIX_BAD, POSFILE_VALUE_FIX_2D, POSFILE_VALUE_FIX_3D); goto out; } nmea_INFO_set_present(&result.present, FIX); } else if (!strncasecmp(POSFILE_NAME_HDOP, name, sizeof(line))) {
int main(int argc, char *argv[]) { int it = 0; int done = 0; nmeaINFO info; nmeaPARSER parser; int select_result = -1; // value returned frome select() struct timeval select_timeout; int nfds = 0; fd_set rset; char rs232_device; int bytes_read; char rs232_buffer[1024]; char *token; char nmea_message[256]; if(argc < 2) { printf("Usage: %s <file to parse>\n", argv[0]); return -1; } rs232_device = open(argv[1], O_RDWR | O_NOCTTY); if(rs232_device < 0) perror("com_open"); // Select UART2_TX and set it as output printf("Setting tx. . .\n"); sprintf(rs232_buffer, "echo 11 > /sys/kernel/debug/omap_mux/spi0_d0"); if(system(rs232_buffer) < 0) perror("setting tx"); // Select UART1_RX and set it as input pulled up printf("Setting rx. . .\n"); sprintf(rs232_buffer, "echo 39 > /sys/kernel/debug/omap_mux/spi0_sclk"); if(system(rs232_buffer) < 0) perror("setting rx"); const char *buff[] = { "$GPRMC,173843,A,3349.896,N,11808.521,W,000.0,360.0,230108,013.4,E*69\r\n", "$GPGGA,111609.14,5001.27,N,3613.06,E,3,08,0.0,10.2,M,0.0,M,0.0,0000*70\r\n", "$GPGSV,2,1,08,01,05,005,80,02,05,050,80,03,05,095,80,04,05,140,80*7f\r\n", "$GPGSV,2,2,08,05,05,185,80,06,05,230,80,07,05,275,80,08,05,320,80*71\r\n", "$GPGSA,A,3,01,02,03,04,05,06,07,08,00,00,00,00,0.0,0.0,0.0*3a\r\n", "$GPRMC,111609.14,A,5001.27,N,3613.06,E,11.2,0.0,261206,0.0,E*50\r\n", "$GPVTG,217.5,T,208.8,M,000.00,N,000.01,K*4C\r\n" }; select_timeout.tv_sec = 1; select_timeout.tv_usec = 0; nmea_zero_INFO(&info); nmea_parser_init(&parser); while(!done) { fflush(stdout); FD_ZERO(&rset); if(rs232_device > 0) { FD_SET(rs232_device, &rset); nfds = max(nfds, rs232_device); } select_result = select(nfds + 1, &rset, NULL, NULL, NULL); if(select_result == -1 && errno == EAGAIN) { perror("select"); continue; } if(select_result == -1) { perror("main:"); return 1; } if(rs232_device > 0) { if(FD_ISSET(rs232_device, &rset)) { //bytes_read = read(rs232_device, rs232_buffer, sizeof(rs232_buffer)); bytes_read = rs232_read(rs232_device); if(bytes_read > 0) { if(rs232_check_last_char('\n')) { bytes_read = rs232_unload_rx(rs232_buffer); if(bytes_read > 0) { rs232_buffer[bytes_read] = 0; token = strtok(rs232_buffer, "\n"); while(token != NULL) { sprintf(nmea_message, "%s\n", token); nmea_parse(&parser, nmea_message, (int)strlen(nmea_message), &info); if(it > 0) { printf("\033[15A"); } else it++; printf("Time: %i/%i/%i %i:%i:%i.%i\n", info.utc.day, info.utc.mon + 1, info.utc.year + 1900, info.utc.hour, info.utc.min, info.utc.sec, info.utc.hsec); printf("Signal: %i\n", info.sig); printf("Operating Mode: %i\n", info.fix); printf("Position Diluition of Precision: %f\n", info.PDOP); printf("Horizontal Diluition of Precision: %f\n", info.HDOP); printf("Vertical Diluition of Precisione: %f\n", info.VDOP); printf("Latitude: %f\n", info.lat); printf("Longitude: %f\n", info.lon); printf("Elevation: %f m\n", info.elv); printf("Speed: %f km/h\n", info.speed); printf("Direction: %f degrees\n", info.direction); printf("Magnetic variation degrees: %f\n", info.declination); printf("\nSatellite: \tin view: %i\n\t\tin use: %i\n", info.satinfo.inview, info.satinfo.inuse); token = strtok(NULL, "\n"); } } } } } } //int smask; /**< Mask specifying types of packages from which data have been obtained */ //nmeaTIME utc; /**< UTC of position */ //int sig; /**< GPS quality indicator (0 = Invalid; 1 = Fix; 2 = Differential, 3 = Sensitive) */ //int fix; /**< Operating mode, used for navigation (1 = Fix not available; 2 = 2D; 3 = 3D) */ //double PDOP; /**< Position Dilution Of Precision */ //double HDOP; /**< Horizontal Dilution Of Precision */ //double VDOP; /**< Vertical Dilution Of Precision */ //double lat; /**< Latitude in NDEG - +/-[degree][min].[sec/60] */ //double lon; /**< Longitude in NDEG - +/-[degree][min].[sec/60] */ //double elv; /**< Antenna altitude above/below mean sea level (geoid) in meters */ //double speed; /**< Speed over the ground in kilometers/hour */ //double direction; /**< Track angle in degrees True */ //double declination; /**< Magnetic variation degrees (Easterly var. subtracts from true course) */ //nmeaSATINFO satinfo; /**< Satellites information */ /*it++; if(it > 6) done = 1; select_timeout.tv_sec = 1; select_timeout.tv_usec = 0;*/ } nmea_parser_destroy(&parser); return 0; }
void processNMEA() { argsCarrier *Args = malloc(sizeof(argsCarrier)); nmeaArgs *nArgs = malloc(sizeof(nmeaArgs)); nmeaINFO *info = malloc(sizeof(nmeaINFO)); nmeaPARSER parser; nmea_zero_INFO(info); nmea_parser_init(&parser); char *NMEA2; nmeaINFO info2; // Fix up the end so the NMEA parser accepts it int count = (int)strlen(NMEA); NMEA[count-1] = '\r'; NMEA[count] = '\n'; NMEA[count+1] = '\0'; // Parse the data nmea_parse(&parser, NMEA, (int)strlen(NMEA), info); if (info->smask == 0) { //Bad data free(nArgs); free(info); free(Args); return; } // NOTE: Make copy of NMEA and Data for these threads - Don't want them to be overwritten by other threads // Have the individual case function take care of freeing them Args->NMEA = (char *)malloc((strlen(&NMEA[0])+1)*sizeof(char)); nArgs->NMEA = (char *)malloc((strlen(&NMEA[0])+1)*sizeof(char)); strcpy(Args->NMEA, NMEA); strcpy(nArgs->NMEA, NMEA); Args->info = info; nArgs->time = getUTCTime(&(info->utc)); adamGpsCallbacks->create_thread_cb("adamgps-nmea", updateNMEA, nArgs); switch (info->smask) { case 1: //< GGA - Essential fix data which provide 3D location and accuracy data. adamGpsCallbacks->create_thread_cb("adamgps-gga", updateGGA, Args); break; case 2: //< GSA - GPS receiver operating mode, SVs used for navigation, and DOP values. adamGpsCallbacks->create_thread_cb("adamgps-gsa", updateGSA, Args); break; case 4: //< GSV - Number of SVs in view, PRN numbers, elevation, azimuth & SNR values. adamGpsCallbacks->create_thread_cb("adamgps-gsv", updateGSV, Args); break; case 8: //< RMC - Recommended Minimum Specific GPS/TRANSIT Data. //adamGpsCallbacks->create_thread_cb("adamgps-loc", updateRMC, Args); free(Args->info); free(Args->NMEA); free(Args); break; case 16: //< VTG - Actual track made good and speed over ground. free(Args->info); free(Args->NMEA); free(Args); break; default: free(Args->info); free(Args->NMEA); free(Args); break; } //LOGV("Successful read: %i", info->smask); }
void _main(int argc, char *argv[]) { (void)argc; (void)argv; if (scl_init("gpsp") != 0) { syslog(LOG_CRIT, "could not init scl module"); exit(EXIT_FAILURE); } gps_socket = scl_get_socket("data"); if (gps_socket == NULL) { syslog(LOG_CRIT, "could not get scl gate"); exit(EXIT_FAILURE); } int64_t hwm = 1; zmq_setsockopt(gps_socket, ZMQ_SNDHWM, &hwm, sizeof(hwm)); opcd_param_t params[] = { {"serial_path", &serial_path}, {"serial_speed", &serial_speed}, OPCD_PARAMS_END }; opcd_params_init("sensors.gps.", 0); opcd_params_apply("", params); int status = serial_open(&port, serial_path, tsint_get(&serial_speed), 0, 0, 0); if (status < 0) { syslog(LOG_CRIT, "could not open serial port: %s", serial_path); exit(EXIT_FAILURE); } nmeaPARSER parser; nmea_parser_init(&parser); nmeaINFO info; nmea_zero_INFO(&info); int time_set = 0; int smask = 0; /* global smask collects all sentences and is never reset, in contrast to info.smask */ while (running) { int c = serial_read_char(&port); if (c < 0) continue; char b = c; /* parse NMEA frame: */ if (nmea_parse(&parser, &b, 1, &info) == 1) { smask |= info.smask; if ( (info.smask & GPGGA) /* check for new position update */ && (smask & (GPGSA | GPRMC))) /* go sure that we collect all sentences for first output*/ { GpsData gps_data = GPS_DATA__INIT; /* set general data: */ char time_str[TIME_STR_LEN]; generate_time_str(time_str, &info.utc); gps_data.fix = 0; gps_data.time = time_str; /* set system time to gps time once: */ if (!time_set && info.fix >= 2) { char shell_date_cmd[TIME_STR_LEN + 8]; linux_sys_set_timezone(convert(info.lat), convert(info.lon)); sprintf(shell_date_cmd, "date -s \"%s\"", time_str); time_set = system(shell_date_cmd) == 0; } /* set position data if a minimum of satellites is seen: */ if (info.fix >= 2) { gps_data.fix = 2; PB_SET(gps_data, hdop, info.HDOP); PB_SET(gps_data, lat, convert(info.lat)); PB_SET(gps_data, lon, convert(info.lon)); PB_SET(gps_data, sats, info.satinfo.inuse); PB_SET(gps_data, course, info.track); PB_SET(gps_data, speed, info.speed); } /* set data for 3d fix: */ if (info.fix == 3) { gps_data.fix = 3; PB_SET(gps_data, vdop, info.VDOP); PB_SET(gps_data, alt, info.elv); } /* add satellit info: */ unsigned int i; gps_data.n_satinfo = info.satinfo.inview; SatInfo **satinfo = malloc(gps_data.n_satinfo * sizeof(SatInfo *)); for (i = 0; i < gps_data.n_satinfo; i++) { /* fill SatInfo structure: */ nmeaSATELLITE *nmea_satinfo = &info.satinfo.sat[i]; satinfo[i] = malloc(gps_data.n_satinfo * sizeof(SatInfo)); sat_info__init(satinfo[i]); satinfo[i]->id = nmea_satinfo->id; satinfo[i]->in_use = info.satinfo.in_use[i] ? 1 : 0; satinfo[i]->elv = nmea_satinfo->elv; satinfo[i]->azimuth = nmea_satinfo->azimuth; satinfo[i]->sig = nmea_satinfo->sig; } gps_data.satinfo = satinfo; /* send the data: */ SCL_PACK_AND_SEND_DYNAMIC(gps_socket, gps_data, gps_data); /* free allocated memory: */ for (i = 0; i < gps_data.n_satinfo; i++) { free(satinfo[i]); } free(satinfo); } nmea_zero_INFO(&info); } } }
UartNMEAGPS::UartNMEAGPS() { m_healthy = false; nmea_zero_INFO(&info); nmea_parser_init(&parser); }