Car PC Hacks

Hack 67. Use GPS on Your Car PC

With GPS, your car PC can always know where on Earth it is, and with wireless Internet, it can also tell the world.

The Global Positioning System (GPS) provides fairly accurate (to within a few meters) location coordinates for anyone who has a GPS receiver. GPS receivers come in a variety of shapes and sizes, from standalone units with LCD screens showing your location in latitude and longitude, to units with a little map and an "X" marking where you are. The GPS hardware and antenna can be made smaller than a matchbox, and you can purchase tiny CompactFlash-sized GPS receivers for PDAs, or small USB dongle receivers for PCs (see Figure 6-10).

Figure 6-10. A USB GPS receiver

Knowing exactly where you are can be useful for many different applications, and recording everywhere you've been can be even more useful. Maybe you run a business with a fleet of automobiles, and you want to be able to store your routes on a daily basis and improve efficiency by examining exactly where you went. Or maybe you're going on a cross-country trip and you want to keep a journal of your travels. Why not include the coordinates of the path you take?

Even better, you can upload your coordinates to a web page as you travel, so others can keep track of your vehicle in real time. This feature can be used for people to monitor your progress while you're making a trip, so you can keep track of someone who borrows your car, to monitor the positions of company vehicles in real time, or even for stolen vehicle recovery (assuming your car PC always runs when the car is driven).

GPS is standard, well documented, and easy to program for, and while you can simply purchase navigation software [Hack #71], none of the navigation programs on the market are designed with all the features I've mentioned. In this hack, I'll briefly explain how to understand the language GPS units speak and then provide several example programs (available for download at http://www.oreilly.com/catalog/carpchks) that illustrate the features I've mentioned.

The term telemetry describes the action of remotely communicating with a device for measurement, be it a Mars rover or a gas meter. Telematics, however, is a term that has recently come into use to describe all the technologies (and businesses) involving GPS, wireless data, and vehicles.

6.7.1. How GPS Works

The basic way that GPS works is that satellites in known locations in space transmit radio signals with embedded timestamps to Earth. Your GPS receiver measures the time that it takes for four or more of these different satellite signals to reach your location, and compares that information to the current time. If you've ever heard of "triangulating your position," it's like that, but with GPS you're "quadrangling" or "sextangling" your positionthe more GPS satellites your receiver can get a signal from, the more points of reference it has to calculate a more accurate position.

When you first power up a GPS receiver, it has to spend a while getting a "lock" on the satellites, and it has to find at least four signals that it can use to calculate a position. If your GPS receiver has been powered on recently (a "warm start"), it will remember at least which hemisphere it is in, and perhaps the general latitude and longitude, and so will be able to get its bearings in a matter of seconds. However, when you turn on a GPS receiver for the first time (or when you turn it on after its batteries have been removed and it has "forgotten" everything), it has to literally figure out where on Earth it is, which can take a few minutes.

The GPS represents coordinates in the same way that the Greeks originally used coordinates. The sky is divided into 12 regions, which are further split into 30 one-degree segments (12 * 30 = 360). Locations in GPS are represented using the standard trigonometric system of Degrees, Minutes, and Seconds, such as:

47 Degrees 38 Minutes 12.372 Seconds North Latitude 122 Degrees 7 Minutes 58.8 Seconds West Longitude

On a computer, Minutes and Seconds are often mathematically combined to one decimal fraction. For example:

47.63677 Latitude -122.13300 Longitude

North is positive latitude, and east is positive longitude; south is negative latitude, and west is negative longitude.

Most GPS receivers communicate their current location coordinates to the computer using the NMEA 0183 protocol. (Make sure the GPS receiver you purchase conforms to this format.)You can find out more information about this standard from the National Marine Electronics Association (NMEA) web site, at http://www.nmea.org/pub/0183.

Most GPS devices for the computer run at a nice, mellow speed of 4,800 baud (for comparison, modems run at 56,000 baud) and speak in ASCII characters over a serial port or USB port. If you plug a GPS unit into your serial port, run a terminal program (e.g., Hyperterminal on Windows), and set the baud rate correctly, you'll see what the GPS device is saying.

The NMEA protocol is fairly simple. Once connected, the GPS device will output a string every second or so containing its latitudinal and longitudinal data. While the GPS unit is still figuring out where it is, it will not output location coordinates, but it may report which satellites it sees and what it is currently doing.

Writing a program to process GPS information is as straightforward as reading data sent to the serial port and processing some text. This is easily done in any programming or scripting language.

6.7.2. Reading and Understanding GPS Sentences

Assuming that you have your GPS device attached and configured (though usually not much configuration is necessary, other than making sure that the port and speed settings are correct), reading information from it is very easy, since it talks in ASCII and provides data that is close to what is necessary for this hack. The device outputs comma-delimited sentences. The beginning of each sentence is a code that explains what is in the rest of the sentence. The sentences that tell you your current coordinates start with $GPGGA. These will probably be the only sentences that you are interested in, but you can check the NMEA 0183 standard if you want to know more. The most interesting parts of the sentence are listed in Table 6-2.

Table 6-2. Some useful NMEA codes

Field number

Description

Example

1

Time that the position was calculated. (hhmmss.ss)

180432.00

2

Latitude (ddmm.mmmmmm)

4738.2062

3

Direction of latitude (N=north, S=south)

N

4

Longitude (dddmm.mmmmmm)

12207.98

5

Direction of longitude (W=west, E=east)

W

6

GPS quality (0=invalid, 1=GPS fix, 2=DGPS fix)

1

7

Number of satellites used for calculation

07

9

Altitude above mean sea level

212.15

10

Units for altitude (M=meters)

M

For information on the other fields, check the NMEA 0183 reference.

6.7.3. Creating a Record of Your Travels

I've written a handful of Perl scripts to illustrate how easy it is to work with GPS information. You can download the source code for each of these examples at http://www.carpchacks.com/gps/. The programs were developed on a Windows XP machine running Perl. You can get Perl for Windows from ActiveState (http://activestate.com/Products/ActivePerl/). The second two code examples require an additional script to be running on an Internet-based web server running Perl. These scripts require IIS or Apache, Perl, and write access to a file so they can store GPS locations.

Each of the Perl scripts running on the car PC will be storing locations to a file. Like any log file, this can get very large over time. Whatever method you use to get the data off your car PC, you should have some mechanism for moving and storing it all.

These scripts are examples, so if you want a more secure solution that isn't viewable by the whole world, you may want to password-protect the script on your web server. Making a robust, secure version of a GPS tracking web service is left as an exercise to the reader.

Example #1: Record Your Travels to a File

My first code example runs on the car PC. It reads the GPS sentences from the GPS receiver, decodes them, and writes a simple travel log of latitude, longitude, and timestamp to disk. The text file generated by this script can be manually parsed later on your desktop PC and displayed on a map (see the next section in this hack, "Displaying GPS Data on a Map").

When you get home and your car PC can connect to your home network [Hack #64], you can transfer this file off of the car PC and start over again with a fresh file.

Example #2: Upload Your Current Position to a Web Page in Real Time

My second code example is a pair of client/server Perl scripts. The client script is almost the same as the first code example, except I've added a few lines that post the GPS data to the web server script at an interval (I have mine set to every four minutes). It depends on you having always-on Internet access in your car, but the bandwidth requirements are so low that any persistent wireless connection will do. (T-Mobile offers a $20/month GPRS plan, as of this writingsee "Get Online in Your Car" [Hack #62].)

The server-side script collects the location data (latitude, longitude, and timestamp) from the car PC and stores it to a file. The same script that receives data from the car PC also returns an HTML page linking to a map of the current location (see Figure 6-11). There are two versions of the server-side script. One of them only keeps track of the current location, so viewing it from a web page will simply show the last uploaded location of the vehicle. The other version of the script keeps a path for the last 24 hours (this is user-configurable, depending on how much history you want to keep). This allows viewers to observe the migratory patterns of your car PC for as far back as you'd care to store it.

Example #3: Use MapPoint to Generate Maps on the Car PC

This third code example can deal with intermittent Internet connectivity (for instance, relying on WiFi hotspots [Hack #68]). It also adds code to produce a map that's visible in the car, if MapPoint 2004 is installed on the car PC. The site I used to learn how to control MapPoint with my Perl scripts is http://www.mp2kmag.com/a100--perl.automate.Win32-OLE.mappoint.html.

This code uses MapPoint's ability to generate a graphic file with the GPS map coordinates drawn on it. It then uploads that image and the HTML code displaying that image to the web server (see Figure 6-12). Using MapPoint on the client machine simply moves the map-generation code from a web service to the client and allows for local viewing of the generated map file.

6.7.4. Displaying GPS Data on a Map

All of this tracking information is great, but without pretty graphical maps at the end, there's little payoff for all the hard work. Unfortunately, high-quality, high-resolution mapping software costs money, and the terms of service of most online mapping sites do not necessarily permit you to generate free, real-time illustrations of your car PC's travels (i.e., they'll want you to pay for that functionality). A great site that does allow this (and which I've included in my sample code) is Acme Labs (http://mapper.acme.com). Another useful site with few restrictions on its use is http://terraserver.microsoft.com.

Figure 6-11. A real-time position map using http://mapper.acme.com

MSN Maps, Yahoo! Maps, MapQuest, and Google Maps can all display graphical maps of your location information if you learn how to generate the right URLs, and depending on the license agreements of these sites, you may be able to link to them with your location (but always check the site's acceptable use policy before doing so).

Google Maps (http://maps.google.com; see Figure 6-13) is growing in popularity for projects like this, and they tend to be more flexible than their competitors when it comes to terms of service.

Figure 6-12. A map generated with MapPoint 2004

As mentioned in the description of Example #3, you can also run MapPoint (or a similar mapping product with an API) to generate the maps on your car PC and then simply upload them. This uses more bandwidth, but yields potentially better-looking results than a free online mapping service can provide.

Each of the major search engines is in the process of adding a local search capability, and this is causing them to revamp, enhance, and solidify their online mapping technologies. At the same time, improved mobile Internet connectivity is becoming available. It's a great time to be tinkering in this area, as the raw materials for some really innovative telematics hacks are now readily available.

Collecting GPS Location Data

The script that runs on your car PC to collect GPS coordinates can fill an entire hard drive in time if the information is not managed intelligently. The script will generate data once a second, as long as the GPS device has a fix on your location. If you are just blindly storing data to the disk and you wind up sitting at a red light or stuck in traffic for a few minutes, that can add up to a lot of unnecessarily recorded data points. By keeping track of the distance traveled between data points, you can determine whether a new data point is different enough (i.e., whether the car has moved) and thus whether it should be saved to disk.

To determine the distance between two GPS points in decimal form, you can use the Great Circle Distance Formula:

r * arccos[sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon2 - lon1)]

However, that's rather complex and really only pertains to measuring long distances on the curved surface of the Earth. For my own approximations (since in each case the distances traveled will probably be only a few meters), I have used the following equation:

Sqrt([4774.81 * (lat2 - lat1)2] + [2809 * (lon2 - lon1)2]) = distance in miles

In my program, I use this equation to determine how far I have moved from the last recorded data point.

Another thing that I have found about GPS is that while it's fairly accurate, it does have a tendency to jitterthat is, if I'm sitting still, it will show me moving around slightly. Since I don't want all those random changes to be saved in my log files, I decided to specify a certain minimum distance that must be traveled before a new point is recorded. I chose 45 feet, or about 0.00852272727 miles, as my minimum distance to travel. I can now calculate the minimum required difference in GPS coordinates:

Difference in GPS = Sqrt((0.00852272727)2 / 7583.81)

The result of this calculation is around .0000978, which I then further rounded to 0.0001. (See why 45 feet is not so random?) You can use these calculations to easily come up with your own threshold, in the manner that I just described.

Just to make my data even tidier, whenever I read a data point that is within the threshold that I defined, instead of throwing it away, I simply average it with the previous value that I was comparing to. This helps focus in on my location when my car is sitting still for a while in traffic.

Figure 6-13. A car PC location using Google Maps

6.7.5. See Also

  • "Choose Your in-Car Navigation Software" [Hack #71]

J.P. Stewart

    Категории