how to create api to receive raw nmea messages

106 Views Asked by At

I have a requirement to create an API to receive GPS data from an IOT device and insert that data into a SQL table. Below is the raw data format. I have tried to create an API controller, but that will work only if the data format is Json.

$GPGLL,4826.67566,N,12322.19605,W,022314.000,A,A*4A
$GPGSA,A,3,30,29,10,21,24,26,15,,,,,,2.9,1.9,2.2*3D
$GPGST,022314.000,8.8,13.0,6.1,65.6,7.1,11.1,14.0*63
$GPGSV,3,1,11,05,09,179,,02,10,072,25,30,28,194,38,29,77,118,42*72
$GPGSV,3,2,11,10,42,059,36,16,24,315,27,21,45,256,43,24,84,024,40*79*

Can anyone help to solve this?

I have tried to create an API controller but that will work only if the data format is Json.

public class GPSStatusController : ApiController
{
    public HttpResponseMessage Post([FromBody]GPSStatu Bts)
    {
        using (LocationEntities entities = new LocaionEntities())
        {
            var ins = new GPSStatu(); 
            ins.ID = Bts.EvID; 
            ins.GPSData = Bts.GPSData; 
            entities.BatteryStatus.Add(ins);
                   
            entities.SaveChanges();
        }
    }
}
1

There are 1 best solutions below

0
bgman On

If the raw data is just a csv string then you can do:

public async Task<IActionResult> Post()
{
    var list = new List<GPSStatu>()
    MemoryStream mem = new MemoryStream();

    await Request.Body.CopyToAsync(mem);
    // parse Memorystream
    var table = GenericCsvParse(mem,',',0,false,'"')
    foreach (DataRow row in table.Rows)
    {
        list.Add(new GPSStatu{ID = row[0].toString(),.....}
    }
}

public static DataTable GenericCsvParse(Stream fs, char delimiter, int skip, bool firstrowheader, char textqualifier)
{
    using (StreamReader sr = new StreamReader(fs))
    {
        using (GenericParserAdapter parser = new GenericParserAdapter(sr)
            {
                ColumnDelimiter = delimiter,
                SkipStartingDataRows = skip,
                FirstRowHasHeader = firstrowheader,
                TextQualifier = textqualifier
            })
        {
            return parser.GetDataTable();
        }
    }
}

Here I used https://www.nuget.org/packages/GenericParsing, but you can do it also with plain split string.