import datetime
import os
import sys
import re

from astropy.io import ascii
import astropy.table as table

from panoptes.utils import logger

@logger.has_logger
class WeatherStation():
    """
    This object is used to determine the weather safe/unsafe condition.  It
    reads a simple text file written by the program for the particular type of
    weather station.
    """
    def __init__(self):
        ## Set up log file for weather telemetry
        self.telemetry_path = os.path.join('/', 'var', 'panoptes', 'logs', 'PanoptesWeather')
        if not os.path.exists(self.telemetry_path): os.mkdir(self.telemetry_path)
        self.update_logfiles()
        self.table_dtypes = {'Timestamp': 'S22',
                             'Safe': 'S6'}


    def update_logfiles(self):
        '''
        Check the UT date and re-define the filenames for the telemetry and
        conditions fies based on today's UT date.
        '''
        now = datetime.datetime.utcnow()
        self.condition_filename = 'condition_{}UT.txt'.format(now.strftime('%Y%m%d'))
        self.condition_file = os.path.join(self.telemetry_path, self.condition_filename)
        self.telemetry_filename = 'telemetry_{}UT.txt'.format(now.strftime('%Y%m%d'))
        self.telemetry_file = os.path.join(self.telemetry_path, self.telemetry_filename)


    def check_conditions(self, stale=180):
        '''
        Read the conditions file and populate the safe property with True or
        False based on the latest datum.
        '''
        self.logger.debug('Opening conditions file: {}'.format(self.condition_file))
        conditions = ascii.read(self.condition_file, guess=True,
                                     format='basic',
                                     converters={'Timestamp': [ascii.convert_numpy(self.table_dtypes['Timestamp'])],
                                                 'Safe': [ascii.convert_numpy(self.table_dtypes['Safe'])]}
                                    )
        last_entry = conditions[-1]
        time_string = last_entry['Timestamp'].decode("utf-8")
        safe_string = last_entry['Safe'].decode("utf-8")
        timestamp = datetime.datetime.strptime(time_string, '%Y/%m/%d %H:%M:%S UT')
        now = datetime.datetime.utcnow()
        dt = now - timestamp
        if dt.total_seconds() > stale:
            self.logger.warning('Weather data is stale by {:.1f} seconds'.format(dt.total_seconds()))
            self.safe = False
        else:
            if safe_string == 'SAFE':
                self.logger.info('Weather is SAFE (data is {:.1f} seconds old)'.format(dt.total_seconds()))
                self.safe = True
            elif safe_string == 'UNSAFE':
                self.logger.info('Weather is UNSAFE (data is {:.1f} seconds old)'.format(dt.total_seconds()))
                self.safe = False
            else:
                self.logger.warning('Weather telemetry not parsed')
                self.safe = None



if __name__ == '__main__':
    weather = WeatherStation()
    weather.check_conditions()


@@ -4,3044 +4,1074 @@
 ort 
-datetime%0Aimport os%0Aimport sys%0Aimport re%0A%0Afrom astropy.io import ascii%0Aimport astropy.table as table%0A%0Afrom panoptes.utils import logger%0A%0A@logger.has_logger%0Aclass WeatherStation():%0A    %22%22%22%0A    This object is used to determine the weather safe/unsafe condition.  It%0A    reads a simple text file written by the program for the particular type of%0A    weather station.%0A    %22%22%22%0A    def __init__(self):%0A        ## Set up log file for weather telemetry%0A        self.telemetry_path = os.path.join('/', 'var', 'panoptes', 'logs', 'PanoptesWeather')%0A        if not os.path.exists(self.telemetry_path): os.mkdir(self.telemetry_path)%0A        self.update_logfiles()%0A        self.table_dtypes = %7B'Timestamp': 'S22',%0A                             'Safe': 'S6'%7D%0A%0A%0A    def update_logfiles(self):%0A        '''%0A        Check the UT date and re-define the filenames for the telemetry and%0A        conditions fies based on today's UT date.%0A        '''%0A        now = datetime.datetime.utcnow()%0A        self.condition_filename = 'condition_%7B%7DUT.txt'.format(now.strftime('%25Y%25m%25d'))%0A        self.condition_file = os.path.join(self.telemetry_path, self.condition_filename)%0A        self.telemetry_filename = 'telemetry_%7B%7DUT.txt'.format(now.strftime('%25Y%25m%25d'))%0A        self.telemetry_file = os.path.join(self.telemetry_path, self.telemetry_filename)%0A%0A%0A    def check_conditions(self, stale=180):%0A        '''%0A        Read the conditions file and populate the safe property with True or%0A        False based on the latest datum.%0A        '''%0A        self.logger.debug('Opening conditions file: %7B%7D'.format(self.condition_file))%0A        conditions = ascii.read(self.condition_file, guess=True,%0A                                     format='basic',%0A                                     converters=%7B'Timestamp': %5Bascii.convert_numpy(self.table_dtypes%5B'Timestamp'%5D)%5D,%0A                                                 'Safe': %5Bascii.convert_numpy(self.table_dtypes%5B'Safe'%5D)%5D%7D%0A                                    )%0A        last_entry = conditions%5B-1%5D%0A        time_string = last_entry%5B'Timestamp'%5D.decode(%22utf-8%22)%0A        safe_string = last_entry%5B'Safe'%5D.decode(%22utf-8%22)%0A        timestamp = datetime.datetime.strptime(time_string, '%25Y/%25m/%25d %25H:%25M:%25S UT')%0A        now = datetime.datetime.utcnow()%0A        dt = now - timestamp%0A        if dt.total_seconds() %3E stale:%0A            self.logger.warning('Weather data is stale by %7B:.1f%7D seconds'.format(dt.total_seconds()))%0A            self.safe = False%0A        else:%0A            if safe_string == 'SAFE':%0A                self.logger.info('Weather is SAFE (data is %7B:.1f%7D seconds old)'.format(dt.total_seconds()))%0A                self.safe = True%0A            elif safe_string == 'UNSAFE':%0A                self.logger.info('Weather is UNSAFE (data is %7B:.1f%7D seconds old)'.format(dt.total_seconds()))%0A                self.safe = False%0A            else:%0A                self.logger.warning('Weather telemetry not parsed')%0A                self.safe = None%0A%0A%0A%0Aif __name__ == '__main__':%0A    weather = WeatherStation()%0A    weather.check_conditions(
+os%0Aimport sys%0A%0Afrom datetime import datetime as dt%0Afrom datetime import timedelta as tdelta%0A%0Afrom panoptes.utils import config, database%0A%0Aclass WeatherStation():%0A    %22%22%22%0A    This object is used to determine the weather safe/unsafe condition.  %0A    %22%22%22%0A    def __init__(self):%0A        ## Set up log file for weather telemetry%0A        pass%0A%0A%0A    def check_conditions(self, stale=180):%0A        '''%0A        '''%0A        now = dt.utcnow()%0A        try:%0A            sensors = database.PanMongo().sensors%0A            safe = sensors.find_one( %7B'type': 'weather', 'status': 'current'%7D )%5B'data'%5D%5B'Safe'%5D%0A            timestamp = sensors.find_one( %7B'type': 'weather', 'status': 'current'%7D )%5B'date'%5D%0A            age = (now - timestamp).total_seconds()%0A        except:%0A            safe = False%0A        else:%0A            if age %3E stale:%0A                safe = False%0A        return safe%0A%0Aif __name__ == '__main__':%0A    weather = WeatherStation()%0A    safe = weather.check_conditions()%0A    tranlator = %7BTrue: 'safe', False: 'unsafe'%7D%0A    print('Conditions are %7B%7D'.format(tranlator%5Bsafe%5D)
 )%0A%0A

Update to use mongo rather than text file