Keeping USB Drive from Sleeping Mapnik Package for Ubuntu
Sep 20

As part of one of my current projects, maptop, I needed a simple module to detect whether or not a GPS receiver is connected to the computer, and if so, which port is it connected to.

For the task, I used PySerial, along with some of their example code, to test if each serial port can be opened, and if so, if there are NMEA GPS sentences coming in on it.  It uses a fixed baud rate of 4800, which is what my receiver is using and is also specified here.  The timeout of 2 seconds seems to work (at least with my device).  Both the baud rate and the timeout can be changed by modifying the BAUD_RATE and TIMEOUT “constants” at the top of the script.

I’m not sure if this works on Windows or not, I haven’t tested it yet, but it *should work*.

Below is the code for the module:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env python
# 
# Copyright 2009 Matthew Brush < mbrush AT leftclick DOT ca >
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
 
__version__ = "0.1"
__all__ = [ 'get_gps_port', 'test_port' ]
 
import serial
import glob
import re
import platform
 
BAUD_RATE = 4800    # the standard nmea baud rate
TIMEOUT = 2         # time to wait for nmea sentences
 
class NoGpsReceiverError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
 
def scan():
    """ Scan for available ports. return a list of device names. """
    if platform.system == 'Windows':
        import scanwin32
        ports = []
        for order, port, desc, hwid in sorted(scanwin32.comports()):
            ports.append(port)
        return ports
    else:
        import scanlinux
        return scanlinux.scan()
 
 
def test_port(port):
    """ Detects whether NMEA GPS sentences can be read from the port. """
    nmea_gps_pattern = '^\$GP[A-Z]{3},'
    gps_detected = False
    try:
        s = serial.Serial(port, BAUD_RATE, timeout=TIMEOUT)
        for i in range(1,10):   # try 10 lines in a row
            line = s.readline().strip()
            m = re.match(nmea_gps_pattern, line)
            if m:
                gps_detected = True
                break
        s.close()
        return gps_detected
    except serial.SerialException:
        return False
 
def get_gps_port():
    """ Looks for GPS data coming in on any serial port and returns the port name. """
    for port in scan():
        if test_port(port):
            return port
    raise NoGpsReceiverError('Unable to locate a suitable GPS receiver.')
 
def main():
    print "Testing ports to find GPS receiver..."
    try:
        if platform.system == 'Windows':
            print "  Warning: gpsdetect not tested in Windows yet."
        for port in scan():
            if test_port(port):
                print "Detected GPS receiver on '" + port + "'."
                found_gps = True
                break
    except NoGpsReceiverError:
        print "No GPS receivers were detected on the system."
 
 
if __name__ == '__main__': main()

The complete source can be downloaded here.

  • Share/Bookmark

2 Responses to “GPS Device Detection in Python”

  1. Samuel Chell Says:

    I love my new Garmin Nuvi 780 … it is very easy to use … I just took it on a trip to Dallas with my family and we all loved how we could just go anywhere on the spur of the moment .. checked movie times .. checked restaurants. it was great.

    I use it with Bluetooth connection to my cell phone … it is great because it auto connects each time I get in my car … It was easy to get the sound to come from my radio by simply dialing the right FM channel. But, I need to get an external microphone .. everyone tells me they think I am in a tunnel, and cannot hear me unless I move the NUVI near to my face (this is not reasonable), so I plan to get a microphone so I can answer the phone and place the external mic on my visor.

  2. Administrator Says:

    That looks like a very nice device, much better than the Garmin Street Pilot c530 I use in my car.

Leave a Reply

1,134 spam comments
blocked by
Akismet