1.背景概述
Linux下基于gpsd+chrony授时,在有些情况下会存在收敛慢或者参考时间选择错误问题,因此需要授时监测脚本进行监测,便于在异常时候发现并处理。
2. gpsd+chrony授时配置方法
2.1 安装chrony
sudo apt-get install chrony
service chrony restart
修改chrony配置文件:/etc/chrony/chrony.conf
keyfile /etc/chrony/chrony.keys
driftfile /var/lib/chrony/chrony.drift
refclock PPS /dev/pps0 lock NMEA refid PPS
refclock SHM 0 offset 0.5 delay 0.2 refid NMEA noselect
logdir /var/log/chrony
maxupdateskew 1.0
leapsectz right/UTC
rtcsync
makestep 1.0 -1
2.2 安装gpsd
sudo apt-get install gpsd
修改GPSD配置文件:/etc/default/gpsd,其中/dev/ttyTHS1为gps数据输出串口(波特率自动识别)
START_DAEMON="true"
USBAUTO="true"
DEVICES="/dev/ttyTHS1"
GPSD_OPTIONS="-n -G"
开机自动启配置:
sudo systemctl enable gpsd
2.3 查看gpsd是否接收到gps数据
安装完成后执行 cgps –s查看是否有GPS数据安装完成后执行 cgps –s查看是否有GPS数据
验证授时是否成功
在终端执行watch chronyc sources –v会出现如下图所示结果:
红色框内的GPSD前有 * 标志表示接收到GPS信号
3. 监测脚本
功能说明:
- 授时时间差大于1ms,将认为授时异常
- 参考时间小于2023,将认为授时异常
- 授时源不是PPS时,将认为授时异常
- 授时异常时,将重启授时服务(gpsd+chrony)
import os
import sys
import time
import socket
import subprocess
def printt(string):
print('{} {}'.format(time.ctime(), string))
sys.stdout.flush()
def get_hostname():
return socket.gethostname()
def get_chrony_sync_server():
try:
source = ''
reftime = 2020
r = os.popen('chronyc tracking').readlines()
print('{}'.format(r))
if len(r) == 13:
source = r[0].split('(')[-1][:-2]
if len(r[2].split(' ')) == 10 :
reftime = int(r[2].split(' ')[9][:-1])
offset = float(r[3].split()[3])*1e6
if 'slow' in r[3]:
offset = -offset
printt('{} {:.3f}us'.format(source, offset))
else:
printt('cmd exe failed!')
except Exception as e:
printt(e)
return source, offset, reftime
def restart_gpsd():
subprocess.Popen(['sudo', 'service', 'gpsd', 'restart'])
printt('restart gpsd!')
time.sleep(5)
def restart_chrony():
subprocess.Popen(['sudo', 'service', 'chrony', 'restart'])
printt('restart chrony!')
time.sleep(60)
if __name__ == '__main__':
hostname = get_hostname()
printt('I am {}'.format(hostname))
source, offset, reftime = get_chrony_sync_server()
printt('{} {:.3f}us reftime:{}'.format(source, offset, reftime))
if offset > 1000 or offset < -1000 or source != 'PPS' or reftime < 2023:
restart_gpsd()
restart_chrony()
print('restart gpsd and chrony')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)