1#!/usr/bin/env python
2"""
3==============================================================================
4
5  This file is part of GPSTk, the GPS Toolkit.
6
7  The GPSTk is free software; you can redistribute it and/or modify
8  it under the terms of the GNU Lesser General Public License as published
9  by the Free Software Foundation; either version 3.0 of the License, or
10  any later version.
11
12  The GPSTk is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  GNU Lesser General Public License for more details.
16
17  You should have received a copy of the GNU Lesser General Public
18  License along with GPSTk; if not, write to the Free Software Foundation,
19  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
20
21  This software was developed by Applied Research Laboratories at the
22  University of Texas at Austin.
23  Copyright 2004-2020, The Board of Regents of The University of Texas System
24
25==============================================================================
26
27==============================================================================
28
29  This software was developed by Applied Research Laboratories at the
30  University of Texas at Austin, under contract to an agency or agencies
31  within the U.S. Department of Defense. The U.S. Government retains all
32  rights to use, duplicate, distribute, disclose, or release this software.
33
34  Pursuant to DoD Directive 523024
35
36  DISTRIBUTION STATEMENT A: This software has been approved for public
37                            release, distribution is unlimited.
38
39==============================================================================
40"""
41
42import argparse
43import gpstk
44import sys
45
46# default args to argv are left in so the script can be run without starting
47# a new python process. This is very useful for testing!
48def main(args=sys.argv[1:]):
49    program_description = ('Converts from a given input time specification to '
50                           'other time formats. Include the quotation marks. '
51                           'All year values are four digit years. '
52                           'Example: $ python gpstk_timeconvert.py -f "158 200" ')
53    parser = argparse.ArgumentParser(description=program_description)
54
55    group = parser.add_mutually_exclusive_group()
56    group.add_argument('-A', '--ansi', help='\"ANSI-Second\"')
57    group.add_argument('-c', '--civil',
58                       help='\"Month(numeric) DayOfMonth Year Hour:Minute:Second\"')
59    group.add_argument('-R', '--rinex',
60                       help='\"Year(2-digit) Month(numeric) DayOfMonth Hour Minute Second\"')
61    group.add_argument('-o', '--ews', help='\"GPSEpoch 10bitGPSweek SecondOfWeek\"')
62    group.add_argument('-f', '--ws', help='\"FullGPSWeek SecondOfWeek\"')
63    group.add_argument('-w', '--wz', help='\"FullGPSWeek Zcount\"')
64    group.add_argument(      '--z29', help='\"29bitZcount\"')
65    group.add_argument('-Z', '--z32', help='\"32bitZcount\"')
66    group.add_argument('-j', '--julian', help='\"JulianDate\"')
67    group.add_argument('-m', '--mjd', help='\"ModifiedJulianDate\"')
68    group.add_argument('-u', '--unixtime', help='\"UnixSeconds UnixMicroseconds\"')
69    group.add_argument('-y', '--doy', help='\"Year DayOfYear SecondsOfDay\"')
70
71    parser.add_argument('-F', '--output_format', help='Time format to use on output')
72
73    parser.add_argument('-a', '--add_offset', type=int, nargs='+',
74                        help='add NUM seconds to specified time')
75    parser.add_argument('-s', '--sub_offset', type=int, nargs='+',
76                        help='subtract NUM seconds to specified time')
77    args = parser.parse_args(args)
78
79    # these format keys must match the long arg names
80    formats = {
81        'ansi'     : '%K',
82        'civil'    : '%m %d %Y %H:%M:%f',
83        'rinex'    : '%y %m %d %H %M %S',
84        'ews'      : '%E %G %g',
85        'ws'       : '%F %g',
86        'wz'       : '%F %Z',
87        'z29'      : '%E %c',
88        'z32'      : '%C',
89        'julian'   : '%J',
90        'mjd'      : '%Q',
91        'unixtime' : '%U',
92        'doy'      : '%Y %j %s'
93    }
94
95    time_found = False
96    for key in formats:
97        input_time = getattr(args, key)  # args.ansi, args.civil, etc.
98        if input_time is not None:
99            try:
100                ct = gpstk.scanTime(input_time, formats[key])
101                time_found = True
102            except gpstk.InvalidRequest:
103                raise gpstk.InvalidRequest('Input could not be parsed.'
104                     '\nCheck the formatting and ensure that the input is both valid and in quotes.'
105                     '\nAlso check if the time is too early/late for these formats.')
106
107
108    if not time_found:
109        ct = gpstk.SystemTime().toCommonTime()
110
111    ct.setTimeSystem(gpstk.TimeSystem('GPS'))
112
113    if args.add_offset is not None:
114        for t in args.add_offset:
115            ct.addSeconds(float(t))
116    if args.sub_offset is not None:
117        for t in args.sub_offset:
118            ct.addSeconds(-float(t))
119
120    if args.output_format is not None:
121        print gpstk.printTime(ct, args.output_format)
122    else:
123        def left_align(str):
124            spacing = ' ' * 8
125            return spacing + str.ljust(31)
126
127        print ''  # newline
128
129        print left_align('Month/Day/Year H:M:S'),
130        print gpstk.CivilTime(ct)
131
132        print left_align('Modified Julian Date'),
133        print gpstk.MJD(ct)
134
135        print left_align('GPSweek DayOfWeek SecOfWeek'),
136        print gpstk.GPSWeekSecond(ct).printf('%G %w % 13.6g')
137
138        print left_align('FullGPSweek Zcount'),
139        print gpstk.GPSWeekZcount(ct).printf('%F % 6z')
140
141        print left_align('Year DayOfYear SecondOfDay'),
142        print gpstk.YDSTime(ct).printf('%Y %03j % 12.6s')
143
144        print left_align('Unix: Second Microsecond'),
145        print gpstk.UnixTime(ct).printf('%U % 6u')
146
147        print left_align('Zcount: 29-bit (32-bit)'),
148        print gpstk.GPSWeekZcount(ct).printf('%c (%C)')
149
150        print ''  # newline
151
152
153if __name__ == '__main__':
154    main()
155