# This file is Copyright (c) 2010 by the GPSD project
# BSD terms apply: see the file COPYING in the distribution root for details.
"""
gpsdfake - a fake gpsd server that spews specified data at gpsd clients.
"""

import sys, SocketServer

class FakeHandler(SocketServer.BaseRequestHandler):
    "Instantiated once per connection to the server."
    def handle(self):
        global lines
        # self.request is the TCP socket connected to the client
        # Read the client's ?WATCH request.
        self.data = self.request.recv(1024).strip()
        # We'd like to send a fake banner to the client on startup,
        # but there's no (documented) method for that.  We settle
        # for shipping on first request.
        self.request.send('{"class":"VERSION",'
                          '"version":"gpsdfake","rev":"gpsdfake",'
                          '"proto_major":3,"proto_minor":1}\r\n')
        # Perpetually resend the data we have specified 
	while True:
	    for line in lines:
		self.request.send(line)

if __name__ == "__main__":
    (HOST, PORT) = "localhost", 2947

    try:
        if len(sys.argv) <= 1:
            sys.stderr.write("gpsdfake: requires a file argument.\n")
            sys.exit(1)

        lines = open(sys.argv[1]).readlines()

        # Create the server, binding to localhost on port 2947
        server = SocketServer.TCPServer((HOST, PORT), FakeHandler)

        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    sys.exit(0)

# The following sets edit modes for GNU EMACS
# Local Variables:
# mode:python
# End:
