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
|
# This file is Copyright 2010 by the GPSD project
# SPDX-License-Identifier: BSD-2-clause
"""
gpsdfake - a fake gpsd server that spews specified data at gpsd clients.
"""
from __future__ import print_function
import socket
try:
import socketserver
except:
import SocketServer as socketserver # until the true death of Python 2
import sys
import time
class FakeHandler(socketserver.BaseRequestHandler):
"Instantiated once per connection to the server."
def handle(self):
try:
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(b'{"class":"VERSION",'
b'"version":"gpsdfake-3","rev":"3",'
b'"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)
time.sleep(0.5)
except Exception:
pass
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], 'rb').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:
print()
except socket.error as e:
print(e.args[1])
sys.exit(0)
# The following sets edit modes for GNU EMACS
# Local Variables:
# mode:python
# End:
# vim: set expandtab shiftwidth=4
|