#!/usr/bin/env python
#
# python script to tail ascii files of $PASHR,ATT messages
# the script parses and displays info in a green gui if the data look good
# the script displays an error message in a red gui if the data look bad
# Teresa Chereskin, 28 March 2006 



#raw text string with the directory of the Ashtech files
ashdir = r'C:\ADCPDATA'

import sys, string, os, os.path, math
from Tkinter import *

#...........................................................
#...........................................................
#...........................................................
class fix:
  def __init__(self, afix=[]):
    if afix: self.update(afix)
  
  def update(self,afix):
    Day = { 0:'Sunday',1:'Monday',2:'Tuesday',3:'Wednesday',
    4:'Thursday',5:'Friday',6:'Saturday'}
    self.secsofWeek = afix[0]
    self.heading    = afix[1]
    self.reset      = afix[6]
    (f,i)           = math.modf(afix[0]/86400.0)
    self.DayofWeek  = Day[int(i)]
    (f,i)           = math.modf(f*24.0)
    self.hour       = int(i)
    (f,i)           = math.modf(f*60)
    self.min        = int(i)
    (f,i)           = math.modf(f*60)
    self.sec        = int(i)
    
  def copy(self, other):
    self.secsofWeek = other.secsofWeek
    self.heading = other.heading
    self.reset = other.reset
    
#...........................................................
#...........................................................
#...........................................................    
class ashtech:
  def __init__(self, next =[0,0,0,0,0,0,0], prev=[-1,0,0,0,0,0,0]):
    self.nextfix = fix(next)
    self.lastfix = fix(prev)

  def get_filelist(self,adir):
    n2rfiles  = []
    filenames = os.listdir(adir)  # list all files in CalCOFI directory
    [n2rfiles.append(file) for file in filenames if file[-4:] == '.N2R']
    n2rfiles.sort                 # in case DOS default order is not same as UNIX
#    return n2rfiles
    return n2rfiles[-1:]          # last file in list should be most recent,
                                  # based on directory sort

  def check_ash(self, afile, adir):                                
    file  = os.path.join(adir, afile[0])
    cmd      = 'tail -40 %s' % file
# n2rfiles.append(os.popen(cmd).readline()[:-1])
#    infile = open(file, 'r')
    boxcolor = 'red'
#     for nline in infile.readlines():
    for nline in os.popen(cmd).readlines():
      line = nline[:-1]
      try:
        if line[:11] ==  '$PASHR,ATT,':
          hold = map(float, line[11:-3].split(','))
          self.nextfix.update(hold)  
#          print 'last heading is ', self.nextfix.heading
          msg = ''
      except: 
          msg = ' Garbled text string.'
#      after parsing file, should have the last Ashtech heading  in file
#    print hold
    if self.nextfix.reset:
      msg = ' RESET ASHTECH NOW '
    elif self.nextfix.secsofWeek > self.lastfix.secsofWeek:
#       msg = ' last Ashtech heading value is %6.2f ' % self.nextfix.heading
      msg = ' Ashtech OK '
      boxcolor = 'green'
      self.lastfix.copy(self.nextfix)
    elif  self.lastfix.secsofWeek - self.nextfix.secsofWeek > 604500: # 604800 secs in GPS week, allow 5 min gap
#      msg = ' new week: last Ashtech heading value is %6.2f ' % self.nextfix.heading
      msg = ' new week: Ashtech OK '
      boxcolor = 'green'
      self.lastfix.copy(self.nextfix)
    else:
      msg = ' Ashtech not updating '  + msg
         
#     infile.close()
    return (msg, boxcolor)
#...........................................................
#...........................................................
#...........................................................    

class FormEditor:
    def __init__(self, name, sdir):
        self.sdir = sdir      # stash away some references
        self.row = 0
        self.current = None

        self.root = root = Tk()           # create window and size it
        root.minsize(500,300)

        root.rowconfigure(0, weight=1)    # define how columns and rows scale
        root.columnconfigure(0, weight=1) # when the window is resized
        root.columnconfigure(1, weight=2)
        root.after(1200, self.repeater)
        # create the title Label
        Label(root, text=name, font='bold').grid(columnspan=2)
        self.row = self.row + 1

        # create the main listbox and configure it
        self.listbox = Listbox(root, selectmode=SINGLE,bg = 'green')
        self.listbox.grid(columnspan=2,sticky=E+W+N+S)
        self.listbox.bind('<ButtonRelease-1>', self.select)
        self.row = self.row + 1

        # create a couple of buttons, with assigned commands

        self.add_button(self.root, self.row, 1, 'exit', sys.exit)
        self.load_data()


    def add_button(self, root, row, column, text, command):
        button = Button(root, text=text, command=command)
        button.grid(row=row, column=column, sticky=E+W, padx=5, pady=5)
    
    def repeater(self):
#        print "repeater"
        bgcolor = self.load_data()
        self.root.after(1500,self.repeater)
        if self.listbox.cget('bg') == 'green' and bgcolor == 'red':
          self.listbox.config(bg='red')
        elif self.listbox.cget('bg') == 'red' and bgcolor == 'green':
          self.listbox.config(bg='green')
#         else:
#           self.listbox.config(bg='green')
        
    def load_data(self):
        self.listbox.delete(0,END)
        boxcolor = 'red'
        self.items = []
        x = ashtech()
        lastfile = x.get_filelist(self.sdir)
#        print 'file is ', lastfile
        try:
          if lastfile[0]:
              (item, boxcolor) =  x.check_ash(lastfile, self.sdir)
              msgtime = ('Last fix time: %s, %02d:%02d:%02d GMT' 
              % (x.nextfix.DayofWeek, x.nextfix.hour, x.nextfix.min, x.nextfix.sec) )
              msghead = 'Ashtech heading:  %6.2f' % x.nextfix.heading
        except: 
          item =  'no N2R files found'
          msgtime = ''
          msghead = ''
        
        self.listbox.insert('end', `msgtime`)
        self.listbox.insert('end', `msghead`)
        self.listbox.insert('end', `item`)
        self.listbox.select_set(0)
        return boxcolor
        
    def select(self, event):
      pass

#...........................................................
#...........................................................
#...........................................................    
#...........................................................

if __name__ == '__main__':            

  mywin = FormEditor("Ashtech Checker", ashdir)
  mywin.root.mainloop()
 
