gpsfake.in 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. #!@PYSHEBANG@
  2. # @GENERATED@
  3. #
  4. '''
  5. gpsfake -- test harness for gpsd
  6. Simulates one or more GPSes, playing back logfiles.
  7. Most of the logic for this now lives in gps.fake,
  8. factored out so we can write other test programs with it.
  9. '''
  10. #
  11. # This file is Copyright 2010 by the GPSD project
  12. # SPDX-License-Identifier: BSD-2-clause
  13. # This code runs compatibly under Python 2 and 3.x for x >= 2.
  14. # Preserve this property!
  15. from __future__ import absolute_import, print_function, division
  16. from distutils import spawn
  17. import getopt
  18. import os
  19. import platform
  20. import pty
  21. import socket
  22. import sys
  23. import time
  24. # pylint wants local modules last
  25. try:
  26. import gps
  27. import gps.fake as gpsfake # The "as" pacifies pychecker
  28. except ImportError as e:
  29. sys.stderr.write(
  30. "gpsfake: can't load Python gps libraries -- check PYTHONPATH.\n")
  31. sys.stderr.write("%s\n" % e)
  32. sys.exit(1)
  33. gps_version = '@VERSION@'
  34. if gps.__version__ != gps_version:
  35. sys.stderr.write("gpsfake: ERROR: need gps module version %s, got %s\n" %
  36. (gps_version, gps.__version__))
  37. sys.exit(1)
  38. try:
  39. my_input = raw_input
  40. except NameError:
  41. my_input = input
  42. # Get version of stdout for bytes data (NOP in Python 2)
  43. bytesout = gps.get_bytes_stream(sys.stdout)
  44. class Baton(object):
  45. "Ship progress indications to stderr."
  46. # By setting this > 1 we reduce the frequency of the twirl
  47. # and speed up test runs. Should be relatively prime to the
  48. # number of baton states, otherwise it will cause beat artifacts
  49. # in the twirling.
  50. SPINNER_INTERVAL = 11
  51. def __init__(self, prompt, endmsg=None):
  52. self.stream = sys.stderr
  53. self.stream.write(prompt + "...")
  54. if os.isatty(self.stream.fileno()):
  55. self.stream.write(" \b")
  56. self.stream.flush()
  57. self.count = 0
  58. self.endmsg = endmsg
  59. self.time = time.time()
  60. def twirl(self, ch=None):
  61. "Twirl the baton"
  62. if self.stream is None:
  63. return
  64. if os.isatty(self.stream.fileno()):
  65. if ch:
  66. self.stream.write(ch)
  67. self.stream.flush()
  68. elif self.count % Baton.SPINNER_INTERVAL == 0:
  69. self.stream.write("-/|\\"[self.count % 4])
  70. self.stream.write("\b")
  71. self.stream.flush()
  72. self.count = self.count + 1
  73. def end(self, mesg=None):
  74. "Write end message"
  75. if mesg is None:
  76. mesg = self.endmsg
  77. if self.stream:
  78. self.stream.write("...(%2.2f sec) %s.\n"
  79. % (time.time() - self.time, mesg))
  80. def hexdump(s):
  81. "Convert string to hex"
  82. rep = ""
  83. for c in s:
  84. rep += "%02x" % ord(c)
  85. return rep
  86. def check_xterm():
  87. "Check whether xterm and DISPLAY are available."
  88. xterm = spawn.find_executable('xterm')
  89. return xterm and os.access(xterm, os.X_OK) and os.environ.get('DISPLAY')
  90. def fakehook(linenumber, fakegps):
  91. "Do the real work"
  92. if not fakegps.testload.sentences:
  93. sys.stderr.write("fakegps: no sentences in test load.\n")
  94. raise SystemExit(1)
  95. if linenumber % len(fakegps.testload.sentences) == 0:
  96. if singleshot and linenumber > 0:
  97. return False
  98. if progress:
  99. baton.twirl('*\b')
  100. elif not singleshot:
  101. if not quiet:
  102. sys.stderr.write("gpsfake: log cycle of %s begins.\n"
  103. % fakegps.testload.name)
  104. time.sleep(cycle)
  105. if linedump and fakegps.testload.legend:
  106. ml = fakegps.testload.sentences[
  107. linenumber % len(fakegps.testload.sentences)].strip()
  108. if not fakegps.testload.textual:
  109. ml = hexdump(ml)
  110. announce = fakegps.testload.legend \
  111. % (linenumber % len(fakegps.testload.sentences) + 1) + ml
  112. if promptme:
  113. my_input(announce + "? ")
  114. else:
  115. print(announce)
  116. if progress:
  117. baton.twirl()
  118. return True
  119. if __name__ == '__main__':
  120. def usage():
  121. "Print usage and exit"
  122. sys.stderr.write("""usage: gpsfake [OPTIONS] logfile...
  123. [-1] logfile is interpreted once only rather than repeatedly
  124. [-b] enable a twirling-baton progress indicator
  125. [-c cycle] sets the delay between sentences in seconds
  126. [-D debug] passes a -D option to the daemon
  127. [-g] run the gpsd instance within gpsfake under control of gdb
  128. [-G] run the gpsd instance within gpsfake under control of lldb
  129. [-h] print a usage message and exit
  130. [-i] single-stepping through logfile
  131. [-l] dump a line or packet number just before each sentence
  132. [-m monitor] specifies a monitor program under which the daemon is run
  133. [-n] start the daemon reading the GPS without waiting for a client
  134. [-o options] specifies options to pass to the daemon
  135. [-p] sets watcher mode and dump to stdout
  136. [-P port] sets the daemon's listening port
  137. [-q] act in a quiet manner
  138. [-r initcmd] specifies an initialization command to use in pipe mode
  139. [-S] insert realistic delays in the test input
  140. [-s speed] sets the baud rate for the slave tty
  141. [-t] force TCP
  142. [-T] print some system information and exit
  143. [-v] verbose
  144. [-V] Version
  145. [-W] specify timeout (default 60s), 0 means none
  146. [-x] dump packets as gpsfake gathers them
  147. """)
  148. raise SystemExit(0)
  149. try:
  150. (options, arguments) = getopt.getopt(
  151. sys.argv[1:],
  152. "1bc:D:gGhilm:no:pP:qr:s:StTuvxVW:"
  153. )
  154. except getopt.GetoptError as msg:
  155. print("gpsfake: " + str(msg))
  156. raise SystemExit(1)
  157. port = None
  158. progress = False
  159. cycle = 0.0
  160. monitor = ""
  161. speed = 4800
  162. linedump = False
  163. predump = False
  164. pipe = False
  165. singleshot = False
  166. promptme = False
  167. client_init = '?WATCH={"json":true,"nmea":true}'
  168. doptions = ""
  169. tcp = False
  170. udp = False
  171. verbose = 0
  172. slow = False
  173. quiet = False
  174. timeout = None # Really means default
  175. for (switch, val) in options:
  176. if switch == '-1':
  177. singleshot = True
  178. elif switch == '-b':
  179. progress = True
  180. elif switch == '-c':
  181. cycle = float(val)
  182. elif switch == '-D':
  183. doptions += " -D " + val
  184. elif switch == '-g':
  185. if check_xterm():
  186. monitor = "xterm -e gdb -tui --args "
  187. else:
  188. monitor = "gdb --args "
  189. timeout = 0
  190. elif switch == '-G':
  191. if check_xterm():
  192. monitor = "xterm -e lldb -- "
  193. else:
  194. monitor = "lldb -- "
  195. timeout = 0
  196. elif switch == '-h':
  197. usage()
  198. elif switch == '-i':
  199. linedump = promptme = True
  200. elif switch == '-l':
  201. linedump = True
  202. elif switch == '-m':
  203. monitor = val + " "
  204. elif switch == '-n':
  205. doptions += " -n"
  206. elif switch == '-o':
  207. doptions = val
  208. elif switch == '-p':
  209. pipe = True
  210. elif switch == '-P':
  211. port = int(val)
  212. elif switch == '-q':
  213. quiet = True
  214. elif switch == '-r':
  215. client_init = val
  216. elif switch == '-s':
  217. speed = int(val)
  218. elif switch == '-S':
  219. slow = True
  220. elif switch == '-t':
  221. tcp = True
  222. elif switch == '-T':
  223. sys.stdout.write("sys %s platform %s: WRITE_PAD = %.5f\n"
  224. % (sys.platform, platform.platform(),
  225. gpsfake.GetDelay(slow)))
  226. raise SystemExit(0)
  227. elif switch == '-u':
  228. udp = True
  229. elif switch == '-v':
  230. verbose += 1
  231. elif switch == '-V':
  232. sys.stderr.write("gpsfake: Version %s\n" % gps_version)
  233. sys.exit(0)
  234. elif switch == '-W':
  235. try:
  236. timeout = int(val)
  237. except ValueError:
  238. sys.stderr.write("gpsfake: bad timeout value (%s). "
  239. "Expected a number.\n" % val)
  240. raise SystemExit(1)
  241. elif switch == '-x':
  242. predump = True
  243. try:
  244. pty.openpty()
  245. except (AttributeError, OSError):
  246. sys.stderr.write("gpsfake: ptys not available, falling back to UDP.\n")
  247. udp = True
  248. if not arguments:
  249. sys.stderr.write("gpsfake: requires at least one logfile argument.\n")
  250. raise SystemExit(1)
  251. if progress:
  252. baton = Baton("Processing %s" % ",".join(arguments), "done")
  253. elif not quiet:
  254. sys.stderr.write("Processing %s\n" % ",".join(arguments))
  255. # Don't allocate a private port when cycling logs for client testing.
  256. if port is None and not pipe:
  257. port = int(gps.GPSD_PORT)
  258. test = gpsfake.TestSession(prefix=monitor, port=port, options=doptions,
  259. tcp=tcp, udp=udp, verbose=verbose,
  260. predump=predump, slow=slow, timeout=timeout)
  261. if pipe:
  262. test.reporter = bytesout.write
  263. if verbose:
  264. progress = False
  265. test.progress = sys.stderr.write
  266. test.spawn()
  267. try:
  268. for logfile in arguments:
  269. try:
  270. test.gps_add(logfile, speed=speed, pred=fakehook,
  271. oneshot=singleshot)
  272. except gpsfake.TestLoadError as e:
  273. sys.stderr.write("gpsfake: " + e.msg + "\n")
  274. raise SystemExit(1)
  275. except gpsfake.PacketError as e:
  276. sys.stderr.write("gpsfake: " + e.msg + "\n")
  277. raise SystemExit(1)
  278. except gpsfake.DaemonError as e:
  279. sys.stderr.write("gpsfake: " + e.msg + "\n")
  280. raise SystemExit(1)
  281. except IOError as e:
  282. if e.filename is None:
  283. sys.stderr.write("gpsfake: unknown internal I/O error %s\n"
  284. % e)
  285. else:
  286. sys.stderr.write("gpsfake: no such file as %s or "
  287. "file unreadable\n" % e.filename)
  288. raise SystemExit(1)
  289. except OSError:
  290. sys.stderr.write("gpsfake: can't open pty.\n")
  291. raise SystemExit(1)
  292. try:
  293. if pipe:
  294. test.client_add(client_init + "\n")
  295. # Give daemon time to get ready for the feeds.
  296. # Without a delay here there's a window for test
  297. # sentences to arrive before the watch takes effect.
  298. # This needs to increase if leading sentences in
  299. # test loads aren't being processed.
  300. # Until the ISYNC driver was introduced, 1 sec was
  301. # sufficient here. The extra 0.4s allows for the
  302. # additional two 200ms delays introduced by the
  303. # calls to gpsd_set_speed() in isync_detect()
  304. time.sleep(1.4)
  305. test.run()
  306. except socket.error as msg:
  307. sys.stderr.write("gpsfake: socket error %s.\n" % msg)
  308. raise SystemExit(1)
  309. except gps.client.json_error as e:
  310. sys.stderr.write("gpsfake: JSON error on line %s is %s.\n"
  311. % (repr(e.data), e.explanation))
  312. raise SystemExit(1)
  313. except KeyboardInterrupt:
  314. sys.stderr.write("gpsfake: aborted\n")
  315. raise SystemExit(1)
  316. finally:
  317. test.cleanup()
  318. if progress:
  319. baton.end()
  320. # The following sets edit modes for GNU EMACS
  321. # Local Variables:
  322. # mode:python
  323. # End:
  324. # vim: set expandtab shiftwidth=4