gpsfake.py.in 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. #!@PYSHEBANG@
  2. # @GENERATED@
  3. """gpsfake -- test harness for gpsd.
  4. Simulates one or more GPSes, playing back logfiles.
  5. Most of the logic for this now lives in gps.fake,
  6. factored out so we can write other test programs with it.
  7. """
  8. #
  9. #
  10. # This file is Copyright 2010 by the GPSD project
  11. # SPDX-License-Identifier: BSD-2-clause
  12. # This code runs compatibly under Python 2 and 3.x for x >= 2.
  13. # Preserve this property!
  14. # Codacy D203 and D211 conflict, I choose D203
  15. # Codacy D212 and D213 conflict, I choose D212
  16. from __future__ import absolute_import, print_function, division
  17. from distutils import spawn
  18. import argparse
  19. import os
  20. import platform
  21. import pty
  22. import socket
  23. import sys
  24. import time
  25. # pylint wants local modules last
  26. try:
  27. import gps
  28. import gps.fake as gpsfake # The "as" pacifies pychecker
  29. import gps.misc # for polybyte() polystr()
  30. except ImportError as e:
  31. sys.stderr.write(
  32. "gpsfake: can't load Python gps libraries -- check PYTHONPATH.\n")
  33. sys.stderr.write("%s\n" % e)
  34. sys.exit(1)
  35. gps_version = '@VERSION@'
  36. if gps.__version__ != gps_version:
  37. sys.stderr.write("gpsfake: ERROR: need gps module version %s, got %s\n" %
  38. (gps_version, gps.__version__))
  39. sys.exit(1)
  40. try:
  41. my_input = raw_input
  42. except NameError:
  43. my_input = input
  44. # Get version of stdout for bytes data (NOP in Python 2)
  45. bytesout = gps.get_bytes_stream(sys.stdout)
  46. class Baton(object):
  47. """Ship progress indications to stderr."""
  48. # By setting this > 1 we reduce the frequency of the twirl
  49. # and speed up test runs. Should be relatively prime to the
  50. # number of baton states, otherwise it will cause beat artifacts
  51. # in the twirling.
  52. SPINNER_INTERVAL = 11
  53. def __init__(self, prompt, endmsg=None):
  54. """Init class Baton."""
  55. self.stream = sys.stderr
  56. self.stream.write(prompt + "...")
  57. if os.isatty(self.stream.fileno()):
  58. self.stream.write(" \b")
  59. self.stream.flush()
  60. self.count = 0
  61. self.endmsg = endmsg
  62. self.time = time.time()
  63. def twirl(self, ch=None):
  64. """Twirl the baton."""
  65. if self.stream is None:
  66. return
  67. if os.isatty(self.stream.fileno()):
  68. if ch:
  69. self.stream.write(ch)
  70. self.stream.flush()
  71. elif self.count % Baton.SPINNER_INTERVAL == 0:
  72. self.stream.write("-/|\\"[self.count % 4])
  73. self.stream.write("\b")
  74. self.stream.flush()
  75. self.count = self.count + 1
  76. def end(self, mesg=None):
  77. """Write end message."""
  78. if mesg is None:
  79. mesg = self.endmsg
  80. if self.stream:
  81. self.stream.write("...(%2.2f sec) %s.\n"
  82. % (time.time() - self.time, mesg))
  83. def hexdump(s):
  84. """Convert string to hex"""
  85. rep = ""
  86. for c in s:
  87. rep += "%02x" % ord(c)
  88. return rep
  89. def check_xterm():
  90. """Check whether xterm and DISPLAY are available."""
  91. xterm = spawn.find_executable('xterm')
  92. return xterm and os.access(xterm, os.X_OK) and os.environ.get('DISPLAY')
  93. def fakehook(linenumber, fakegps):
  94. """Do the real work."""
  95. if not fakegps.testload.sentences:
  96. sys.stderr.write("fakegps: no sentences in test load.\n")
  97. raise SystemExit(1)
  98. if linenumber % len(fakegps.testload.sentences) == 0:
  99. if options.singleshot and linenumber > 0:
  100. return False
  101. if options.progress:
  102. baton.twirl('*\b')
  103. elif not options.singleshot:
  104. if not options.quiet:
  105. sys.stderr.write("gpsfake: log cycle of %s begins.\n"
  106. % fakegps.testload.name)
  107. time.sleep(options.cycle)
  108. if options.linedump and fakegps.testload.legend:
  109. ml = fakegps.testload.sentences[
  110. linenumber % len(fakegps.testload.sentences)].strip()
  111. if not fakegps.testload.textual:
  112. ml = hexdump(ml)
  113. announce = ((fakegps.testload.legend %
  114. (linenumber % len(fakegps.testload.sentences) + 1)) +
  115. gps.polystr(ml))
  116. if options.promptme:
  117. my_input(announce + "? ")
  118. else:
  119. print(announce)
  120. if options.progress:
  121. baton.twirl()
  122. return True
  123. if __name__ == '__main__':
  124. description = 'Fake gpsd from a log file.'
  125. usage = '%(prog)s [OPTIONS] logfile...'
  126. epilog = ('BSD terms apply: see the file COPYING in the distribution root'
  127. ' for details.')
  128. parser = argparse.ArgumentParser(
  129. description=description,
  130. epilog=epilog,
  131. formatter_class=argparse.RawDescriptionHelpFormatter,
  132. usage=usage)
  133. parser.add_argument(
  134. '-?',
  135. action="help",
  136. help='show this help message and exit'
  137. )
  138. parser.add_argument(
  139. '-1',
  140. '--singleshot',
  141. dest='singleshot',
  142. default=False,
  143. action="store_true",
  144. help=('Logfile is interpreted once only rather than repeatedly. '
  145. '[Default %(default)s]')
  146. )
  147. parser.add_argument(
  148. '-b',
  149. '--baton',
  150. dest='progress',
  151. default=False,
  152. action="store_true",
  153. help=('Enable a twirling-baton progress indicator. '
  154. '[Default %(default)s]')
  155. )
  156. parser.add_argument(
  157. '-c',
  158. '--cycle',
  159. default=0.0,
  160. dest='cycle',
  161. metavar='CYCLE',
  162. type=float,
  163. help=('Sets the delay between sentences in seconds. '
  164. '[Default %(default)s]'),
  165. )
  166. parser.add_argument(
  167. '-D',
  168. '--debug',
  169. action='append',
  170. dest='debug',
  171. metavar='OPT',
  172. help='Pass a -D option OPT to the daemon.',
  173. )
  174. parser.add_argument(
  175. '-g',
  176. '--gdb',
  177. dest='gdb',
  178. default=False,
  179. action="store_true",
  180. help='Run the gpsd instance within gpsfake under control of gdb.',
  181. )
  182. parser.add_argument(
  183. '-G',
  184. '--lldb',
  185. dest='lldb',
  186. default=False,
  187. action="store_true",
  188. help='Run the gpsd instance within gpsfake under control of lldb.',
  189. )
  190. parser.add_argument(
  191. '-i',
  192. '--promptme',
  193. dest='promptme',
  194. default=False,
  195. action="store_true",
  196. help=('Single-stepping through logfile. [Default %(default)s]'),
  197. )
  198. parser.add_argument(
  199. '-l',
  200. '--linedump',
  201. dest='linedump',
  202. default=False,
  203. action="store_true",
  204. help=('Dump a line or packet number just before each sentence. '
  205. '[Default %(default)s]'),
  206. )
  207. parser.add_argument(
  208. '-m',
  209. '--monitor',
  210. default=None,
  211. dest='mon',
  212. metavar='PROG',
  213. help='Specifies a monitor program under which the daemon is run.',
  214. )
  215. parser.add_argument(
  216. '-n',
  217. '--nowait',
  218. dest='nowait',
  219. default=False,
  220. action="store_true",
  221. help=('Start the daemon reading from gpsfake without '
  222. 'waiting for a client.'),
  223. )
  224. parser.add_argument(
  225. '-o',
  226. '--options',
  227. dest='options',
  228. metavar='="OPT"',
  229. help=('Pass options ="OPT" to the daemon.\n'
  230. 'The equal sign and Quotes required.'),
  231. )
  232. parser.add_argument(
  233. '-p',
  234. '--pipe',
  235. dest='pipe',
  236. default=False,
  237. action="store_true",
  238. help='Sets watcher mode and dump to stdout. [Default %(default)s]',
  239. )
  240. parser.add_argument(
  241. '-P',
  242. '--port',
  243. default=None,
  244. dest='port',
  245. metavar='PORT',
  246. type=int,
  247. help="Sets the daemon's listening port to PORT [Default %(default)s]",
  248. )
  249. parser.add_argument(
  250. '-q',
  251. '--quiet',
  252. dest='quiet',
  253. default=False,
  254. action="store_true",
  255. help='Act in a quiet manner. [Default %(default)s]',
  256. )
  257. parser.add_argument(
  258. '-r',
  259. '--clientinit',
  260. default='?WATCH={"json":true,"nmea":true}',
  261. dest='client_init',
  262. metavar='STR',
  263. help=('Specifies an initialization command to use in pipe mode. '
  264. '[Default %(default)s]'),
  265. )
  266. parser.add_argument(
  267. '-s',
  268. '--speed',
  269. default=4800,
  270. dest='speed',
  271. metavar='SPEED',
  272. type=int,
  273. help='Sets the baud rate for the slave tty. [Default %(default)s]',
  274. )
  275. parser.add_argument(
  276. '-S',
  277. '--slow',
  278. dest='slow',
  279. default=False,
  280. action="store_true",
  281. help=('Insert realistic delays in the test input. '
  282. '[Default %(default)s]'),
  283. )
  284. parser.add_argument(
  285. '-t',
  286. '--tcp',
  287. dest='tcp',
  288. default=False,
  289. action="store_true",
  290. help='Force TCP. [Default %(default)s]',
  291. )
  292. parser.add_argument(
  293. '-T',
  294. '--sysinfo',
  295. dest='sysinfo',
  296. default=False,
  297. action="store_true",
  298. help='Print some system information and exit.',
  299. )
  300. parser.add_argument(
  301. '-u',
  302. '--udp',
  303. dest='udp',
  304. default=False,
  305. action="store_true",
  306. help='Force UDP. [Default %(default)s]',
  307. )
  308. parser.add_argument(
  309. '-v',
  310. '--verbose',
  311. dest='verbose',
  312. default=0,
  313. action='count',
  314. help='Verbose. Repeat for more verbosity. [Default %(default)s]',
  315. )
  316. parser.add_argument(
  317. '-W',
  318. '--timeout',
  319. default=60,
  320. dest='timeout',
  321. metavar='SEC',
  322. type=int,
  323. help='Specify timeout. [Default %(default)s]',
  324. )
  325. parser.add_argument(
  326. '-V', '--version',
  327. action='version',
  328. version="%(prog)s: Version " + gps_version + "\n",
  329. help='Output version to stderr, then exit'
  330. )
  331. parser.add_argument(
  332. '-x',
  333. '--predump',
  334. dest='predump',
  335. default=False,
  336. action="store_true",
  337. help='Dump packets as gpsfake gathers them. [Default %(default)s]',
  338. )
  339. parser.add_argument(
  340. 'arguments',
  341. metavar='logfile',
  342. nargs='*',
  343. help='Logfile(s) to read and feed to gpsd. At least one required.'
  344. )
  345. options = parser.parse_args()
  346. if options.sysinfo:
  347. sys.stdout.write("sys %s platform %s\nWRITE_PAD = %.5f\n"
  348. % (sys.platform, platform.platform(),
  349. gpsfake.GetDelay(options.slow)))
  350. raise SystemExit(0)
  351. if not options.arguments:
  352. sys.stderr.write("gpsfake: requires at least one logfile argument.\n")
  353. raise SystemExit(0)
  354. if options.promptme:
  355. options.linedump = True
  356. # debug options to pass to gpsd
  357. doptions = ''
  358. if options.debug:
  359. doptions += "-D " + options.debug[0] + " "
  360. if options.nowait:
  361. doptions += "-n "
  362. if options.options:
  363. doptions += options.options
  364. monitor = ()
  365. timeout = 0
  366. if options.gdb:
  367. if check_xterm():
  368. monitor = "xterm -e gdb -tui --args "
  369. else:
  370. monitor = "gdb --args "
  371. timeout = 0
  372. elif options.lldb:
  373. if check_xterm():
  374. monitor = "xterm -e lldb -- "
  375. else:
  376. monitor = "lldb -- "
  377. timeout = 0
  378. elif options.mon:
  379. monitor = options.mon + " "
  380. if options.timeout:
  381. timeout = options.timeout
  382. if not options.tcp and not options.udp:
  383. try:
  384. pty.openpty()
  385. except (AttributeError, OSError):
  386. sys.stderr.write('gpsfake: ptys not available, falling back'
  387. ' to UDP.\n')
  388. options.udp = True
  389. if options.progress:
  390. baton = Baton("Processing %s" % ",".join(options.arguments), "done")
  391. elif not options.quiet:
  392. sys.stderr.write("Processing %s\n" % ",".join(options.arguments))
  393. # Don't allocate a private port when cycling logs for client testing.
  394. if options.port is None and not options.pipe:
  395. options.port = int(gps.GPSD_PORT)
  396. test = gpsfake.TestSession(options=doptions,
  397. prefix=monitor,
  398. predump=options.predump,
  399. port=options.port,
  400. slow=options.slow,
  401. tcp=options.tcp,
  402. timeout=timeout,
  403. udp=options.udp,
  404. verbose=options.verbose)
  405. if options.pipe:
  406. test.reporter = bytesout.write
  407. if options.verbose:
  408. options.progress = False
  409. test.progress = sys.stderr.write
  410. test.spawn()
  411. try:
  412. for logfile in options.arguments:
  413. try:
  414. test.gps_add(logfile, speed=options.speed, pred=fakehook,
  415. oneshot=options.singleshot)
  416. except gpsfake.TestLoadError as e:
  417. sys.stderr.write("gpsfake: " + e.msg + "\n")
  418. raise SystemExit(1)
  419. except gpsfake.PacketError as e:
  420. sys.stderr.write("gpsfake: " + e.msg + "\n")
  421. raise SystemExit(1)
  422. except gpsfake.DaemonError as e:
  423. sys.stderr.write("gpsfake: " + e.msg + "\n")
  424. raise SystemExit(1)
  425. except IOError as e:
  426. if e.filename is None:
  427. sys.stderr.write("gpsfake: unknown internal I/O error %s\n"
  428. % e)
  429. else:
  430. sys.stderr.write("gpsfake: no such file as %s or "
  431. "file unreadable\n" % e.filename)
  432. raise SystemExit(1)
  433. except OSError:
  434. sys.stderr.write("gpsfake: can't open pty.\n")
  435. raise SystemExit(1)
  436. try:
  437. if options.pipe:
  438. test.client_add(options.client_init + "\n")
  439. # Give daemon time to get ready for the feeds.
  440. # Without a delay here there's a window for test
  441. # sentences to arrive before the watch takes effect.
  442. # This needs to increase if leading sentences in
  443. # test loads aren't being processed.
  444. # Until the ISYNC driver was introduced, 1 sec was
  445. # sufficient here. The extra 0.4s allows for the
  446. # additional two 200ms delays introduced by the
  447. # calls to gpsd_set_speed() in isync_detect()
  448. time.sleep(1.4)
  449. test.run()
  450. except socket.error as msg:
  451. sys.stderr.write("gpsfake: socket error %s.\n" % msg)
  452. raise SystemExit(1)
  453. except gps.client.json_error as e:
  454. sys.stderr.write("gpsfake: JSON error on line %s is %s.\n"
  455. % (repr(e.data), e.explanation))
  456. raise SystemExit(1)
  457. except KeyboardInterrupt:
  458. sys.stderr.write("gpsfake: aborted\n")
  459. raise SystemExit(1)
  460. finally:
  461. test.cleanup()
  462. if options.progress:
  463. baton.end()
  464. # The following sets edit modes for GNU EMACS
  465. # Local Variables:
  466. # mode:python
  467. # End:
  468. # vim: set expandtab shiftwidth=4