-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpsclock.py
191 lines (160 loc) · 6.08 KB
/
gpsclock.py
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ex:set noet:
# gpsclok: a tool to configure the gps recevier clock.
# written by:
# rasmus handberg [email protected]
# eric weiss [email protected]
# usage: see Help output
from __future__ import division, print_function, with_statement
import serial
import io
import logging
import argparse
try:
import configparser as ConfigParser
except:
import ConfigParser
from datetime import datetime
class GPSClock(object):
FAULTS = {
1: 'Drift Limit Fault',
2: 'Reference Fault',
4: 'GPS Communication Fault',
8: 'GPS Antenna Fault',
16: 'Oscillator Control Fault',
32: 'GPS Battery Fault'
}
def __init__(self, port):
# Start logger:
self.logger = logging.getLogger(__name__)
self.logger.debug('Setting up serial connection')
# Sete Config Parameter
# self.config=config
# Open serial connection to clock:
self.ser = serial.Serial(port=port, baudrate=9600, parity=serial.PARITY_NONE, timeout=1.0)
self.io = io.TextIOWrapper(io.BufferedRWPair(self.ser, self.ser, 1),
newline = '\n',
line_buffering = True)
# Make sure we are using the right settings:
self.SendAndRecieve('ECHO,0') # Turn echoing of commands off
self.SendAndRecieve('TMODE,0') # 0=UTC, 1=GPS, 2=LOCAL
self.SendAndRecieve('DSTSTATE,0') # Disable Daylight Savings Time
self.SendAndRecieve('PPMODE,0') # Disable Programmable Pulse
# Check for faults:
faults = self.faults
if faults is not None:
self.logger.error("Faults: %s", faults)
self.logger.debug("init done")
def close(self):
self.ser.close()
def __enter__(self, *args, **kwargs):
return self
def __exit__(self, *args, **kwargs):
self.close()
def SendAndRecieve(self, cmd):
self.logger.debug("Sending '%s'", cmd)
self.io.write(cmd + '\r\n')
self.ser.flush()
# Receive an answer:
res = self.io.readline()
res = res.strip()
if res == 'Syntax Error':
self.logger.error("Syntax Error: '%s'", cmd)
return None
self.logger.debug("Received '%s'" % res)
if res == '':
return None
elif cmd == '*': # Special case for "TIME"
return res[5:]
elif res.startswith(cmd + ','):
return res[len(cmd)+1:]
else:
return res
@property
def position(self):
"""Current position."""
return self.SendAndRecieve('POSITION')
@property
def time(self):
"""Current UTC time."""
ts = self.SendAndRecieve('*')
return datetime.strptime(ts[3:-2], '%Y,%j,%H,%M,%S.%f')
@property
def version(self):
"""Version of GPC Clock."""
return self.SendAndRecieve('VERSION')
@property
def faults(self):
"""List of current faults."""
flts = self.SendAndRecieve('FLTS')
flts = int(flts)
if flts == 0:
return None
# There was an error, figure out which ones:
faults = []
for bitval, description in self.FAULTS.items():
if flts & bitval > 0:
faults.append(description)
return faults
def setPulseTime(self, time=None, pps=True, autostart=True,conf=None):
# Set the time where pulse should be sent:
# TODO: This needs to be set
if time is not None:
self.SendAndRecieve('PPTIME,XXX:XX:XX:XX.0000000') # One pulse per second - on the second
elif conf is not None:
import datetime
dt=conf.get('settings','date')
tm=conf.get('settings','time')
(Year,Month,Day)=dt.split('/')
(Hour,Min,Sec)=tm.split(':')
a=datetime.datetime(int(Year), int(Month), int(Day), hour=int(Hour), minute=int(Min), second=int(Sec), microsecond=0, tzinfo=None)
sendStr="PPTIME,%03i:%02i:%02i:%02i.0000000" % (a.timetuple().tm_yday, a.timetuple().tm_hour,a.timetuple().tm_min,a.timetuple().tm_sec )
self.SendAndRecieve(sendStr) # One pulse per second - on the second
# If specified, also start the pulse:
elif pps:
self.SendAndRecieve('PPTIME,XXX:XX:XX:XX.0000000') # One pulse per second - on the second
if autostart:
self.startPulse()
def startPulse(self):
self.SendAndRecieve('PPMODE,1')
def stopPulse(self):
self.SendAndRecieve('PPMODE,0')
if __name__ == '__main__':
logging_level = logging.INFO
ConfigFile='config.ini'
# Command-line input:
parser = argparse.ArgumentParser(description='Configure GPS Clock for PICTURE.')
parser.add_argument('-p', '--port', type=str, help='COM port.', default='COM5')
parser.add_argument('-d', '--debug', help='Print debug messages.', action='store_true')
parser.add_argument('-q', '--quiet', help='Only report warnings and errors.', action='store_true')
parser.add_argument('-c', '--config',type=str , help='Use settings based of Config File.', default="config.ini")
args = parser.parse_args()
port = args.port
if args.quiet:
logging_level = logging.WARNING
elif args.debug:
logging_level = logging.DEBUG
if args.config:
config = ConfigParser.ConfigParser()
config.read_file(open(args.config))
else:
config=None
# Setup logging:
logger = logging.getLogger(__name__)
logger.setLevel(logging_level)
if not logger.hasHandlers():
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console = logging.StreamHandler()
console.setFormatter(formatter)
logger.addHandler(console)
# Do something simple:
# print("Starting...")
# print("COM Port: ", port)
with GPSClock(port) as c:
# print("Version: ", c.version)
# print("Time: ", c.time)
# print("Position: ", c.position)
# print("Faults: ", c.faults)
c.setPulseTime(conf=config)
# print("Done.")