summaryrefslogtreecommitdiff
path: root/recipes-navigation/gpsd/gpsd/gpsd_settime.sh
blob: 7078de968fd06275978f1694f1a0036df5e4d7d5 (plain)
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
#!/bin/bash
# Get the time from gpspipe, and if present, set the time.
# DEBUG=1 to set debug
NAME=gpsd_ubx_settime
shopt -s expand_aliases
alias LG="logger -t $NAME"
function kill_it
{
    cmd=$1
    pid=$2
    sig=$3
    ((DEBUG)) && LG -p user.info "terminating $cmd(${pid}) with SIG${sig}"
    kill -SIG${sig} ${pid}
    result=$?
    ((DEBUG)) && LG -p user.info "kill -SIG${sig} ${pid} result is $result"
}        

trap "stty echo icanon" exit

OIFS=$IFS
IFS=$'\n'
if ! /usr/sbin/gpsd_fixed </dev/null ; then
   LG -s -p user.warn "GPS does not have a fix yet.  Try again later."
   exit 1
fi


# Terminate gpspipe after 10 seconds if it is our child
# gpspipe has issues with terminals and stalling on terminal
# read of the console.
(
  sleep 10
  ppid=$BASHPID
  pgid=$(ps --no-heading -o pgid -p $ppid)
  
  if ((${#pgid} == 0)) ; then
    LG -p user.err "Could not find a pgid for $ppid"
    ps -fjp $ppid | LG -p user.error
  fi

  # pgrep does not work during boot.
  pgrpmemb=$(ps --no-heading -o pgid,pid,comm -e | grep '^ *'"${pgid}"' *' | sed -r 's/^ *[0-9]+ *//')
  gpspipepid=$(echo "${pgrpmemb}" | egrep '[[:space:]]gpspipe$' | sed 's/[[:space:]].*//')

  ((DEBUG)) && LG -p user.info "$pgid is pgid $gpspipepid is gpspipepid"
  # Find the gpspipepid that is our grandchild
  ((didkill=0))
  
  # for loop is in case gpspipepid has children.
  for p in ${gpspipepid} ; do
    if ((${#p})) ; then
        kill_it gpspipe $p TERM
        ((didkill=p))
        break
    fi
  done
  if ((didkill == 0)) ; then
    exit 0
  fi
  # Do a sigkill to be sure.
  sleep 2
  kill_it gpspipe $didkill KILL
) &
        
# Get the ISO8601 time from GPSD
ISO8601=$(gpspipe -w | egrep -m1 '\{"class":"TPV","device":"/dev/gps0"(,"status":[0-9])*,"mode":3,"time":"' | sed -e 's/.*,"time":"//' -e 's/Z",.*//')

if (( ${#ISO8601} > 18 )) ; then
  LG -p user.warn "Updating time to time, ${ISO8601}."
  [[ $ISO8601 =~ ([^-]*)-([^-]*)-([^T]*)T([^:]*):([^:]*):([^\.]*)\. ]]
  Y=${BASH_REMATCH[1]}
  M=${BASH_REMATCH[2]}
  D=${BASH_REMATCH[3]}
  h=${BASH_REMATCH[4]}
  m=${BASH_REMATCH[5]}
  s=${BASH_REMATCH[6]}
fi
if ((${#Y} == 4 )) && ((${#M} > 0)) && ((${#D} > 0)) && ((${#h} > 0)) && ((${#m} > 0)) && ((${#s} > 0)) ; then
  if [[ $(readlink -f /bin/date) =~ busybox ]] ; then
      date -u "${Y}.${M}.${D}-${h}:${m}:${s}" >/dev/null
  else 
      date -u "${M}${D}${h}${m}${Y}.${s}" >/dev/null
  fi
else
  LG -p user.err "gpspipe output is bad or missing"
  exit 1
fi
exit 0