Listing 1: Code required to initialize the port


// Set the baud rate to 4800 which works for most devices
BasicPortSettings portSettings = new BasicPortSettings();
portSettings.BaudRate = BaudRates.CBR_4800;

// Create a new serial port
serialPort = new Port(serialPortName, portSettings);

serialPort.RThreshold = 1;	// get an event for every 1 byte received
serialPort.InputLen = 1;	// calling Input will read 1 byte
serialPort.SThreshold = 1;

// Open the port
serialPort.Open();
if(!serialPort.IsOpen)
{
	throw new ArgumentException(String.Format("{0} is unavailable",
	 serialPortName), "serialPortName");
}
// Set it up so that every time a new character is received we get an event
serialPort.DataReceived+=new
 OpenNETCF.IO.Serial.Port.CommEvent(serialPort_DataReceived);

Listing 2: Incoming Data


// Get the data
byte[] data = serialPort.Input;
if(!bIgnoreStartup)
{
	if(data[0] == 13)
	{
		// Convert the bytes received to a string
		System.Diagnostics.Debug.WriteLine(serialData.ToString());
		// Hand them off to the sentence parser
		DoGpsEvent(serialData.ToString());
		serialData.Length = 0;
	}
	else if(data[0] != 10)
	{
		// Grab the serial data
serialData.Append(System.Text.UTF8Encoding.UTF8.GetString(data,0,1));
		System.Diagnostics.Debug.WriteLine(serialData.ToString());
	}
}
else if(data[0] == 36)
{
	// Grab the serial data
	serialData.Append(System.Text.UTF8Encoding.UTF8.GetString(data,0,1));
	System.Diagnostics.Debug.WriteLine(serialData.ToString());
	bIgnoreStartup = false;
}

Listing 3: Break Up the Initial Sentence


// Trim off any leading or trailing space
gpsSentence = gpsSentence.Trim();

// the only sentences we recognize start with a $ and contain a , in them
if(gpsSentence.StartsWith("$") && gpsSentence.IndexOf(",") > 1)
{
	// Strip out the sentence identifier
	string sentenceId = gpsSentence.Substring(3, 3);

	switch(sentenceId)
	{
		case "GLL":
			DoLatLongFix(new LatLongFixEventArgs(gpsSentence));
			break;

		case "GGA":
			DoPositionFix(new PositionFixEventArgs(gpsSentence));
			break;
		// TODO: GSA, GSV, RMC
		default:
			// This is a sentence type we don't know
	DoUnknownSentence(new UnknownSentenceEventArgs(gpsSentence));
			break;
	}
}
else
{
	// Fire off an unknown sentence with
	DoUnknownSentence(new UnknownSentenceEventArgs(gpsSentence));
}

Listing 4: Sentence parsing for the GLL fix type


internal LatLongFixEventArgs(string s) : base(s)
{
    string[] words = s.Split(',');
    System.Diagnostics.Debug.Assert(words[0] == "$GPGLL");
    latitude = new Latitude(words[1], words[2]);
    longitude = new Longitude(words[3], words[4]);
	// Do we have fix data?
	if(words.Length>5)
	{
		// Try to parse the UTC date but don't throw if we can't
		try
		{
	timeStamp = DateTime.ParseExact(words[5], "HHMMss", new
			 System.Globalization.CultureInfo("en-US", false));
		}
		catch{}
	}
}