#!/usr/bin/python # Hotplug script for gpsd by Eric S. Raymond, March 2005 # This script is part of the gpsd distribution: see http://gpsd.berlios.de import os, syslog, glob, socket def gpsd_connect(): "Acquire a connection to the GPSD port." msg = "getaddrinfo returns an empty list" sock = None sockfile = None for res in socket.getaddrinfo("localhost", 2947, 0, socket.SOCK_STREAM): (af, socktype, proto, canonname, sa) = res try: sock = socket.socket(af, socktype, proto) sock.connect(sa) sockfile = sock.makefile() except socket.error, msg: if sock: sock.close() sock = None sockfile = None continue break if not sock: syslog.syslog("gpsd is not running or is unreachable") return None else: return sockfile def wake_up_gpsd(devpath): subnodes = glob.glob("/sys" + devpath + "/*") subnodes = map(os.path.basename, subnodes) subnodes = filter(lambda s: s.startswith("ttyUSB"), subnodes) if len(subnodes) == 0: syslog.syslog("no ttyUSB device under " + devpath) return elif len(subnodes) > 1: syslog.syslog("too many ttyUSB devices under " + devpath) return else: tty = "/dev/" + subnodes[0] syslog.syslog(tty + " has gone active") # Next get a connection to gpsd; start one if not already running connect = gpsd_connect() if connect: syslog.syslog("reached a running gpsd") else: syslog.syslog("attempting to launch gpsd") os.system("gpsd") connect = gpsd_connect() if not connect: return # We've got a live connection to gpsd. Ship it the right F command. # No need to look at the response; gpsd will lock on to the device # if it's really a GPS and ignore it if it's not. connect.write("F=%s\r\n" % tty) connect.close() return syslog.openlog('gpsdplug', 0, syslog.LOG_DAEMON) syslog.syslog("gpsdplug begins with action: %s" % os.getenv("ACTION")) devpath = os.getenv("DEVPATH") if not devpath: syslog.syslog("No DEVPATH") else: # First, discover the device #syslog.syslog("DEVPATH = %s" % devpath) wake_up_gpsd(devpath) syslog.syslog("gpsdplug ends") syslog.closelog()