def __init__(self): """ Creates the logfile, and writes the header row """ self.logfile_name = 'logs/%s-%s.slp.csv' % (get_date_string(), get_time_string()) log.info("Logging to %s" % self.logfile_name) try: self.logfile = open(self.logfile_name, 'a') self.logwriter = csv.writer(self.logfile) except Exception as e: log.error("Unable to open logfile: %s" % e) sys.exit(1) # Write CSV header information self.logwriter.writerow(SleepEntry.header_names())
def __init__(self, filename, **kwargs): """Opens the specified file, and reads the header line""" super(SleepFile, self).__init__(**kwargs) self.last_sleep_entry = None """Used mostly for debugging malformed csv files. Constantly updated with the last SleepEntry that was successfully read in.""" try: self._file = open(filename, 'r') self.total_size = os.path.getsize(filename) header = self._file.readline().strip() self.total_read = len(header) log.info("CSV Headers: %s" % header) except Exception as e: log.error("Couldn't open input file: %s" % e) sys.exit(1)
def _get_teensy_usb(self): """Searches, opens, and returns a serial port object connected to the Teensy. :raises EnvironmentError: On unsupported or unknown platforms :returns: An initialized serial object (hopefully) connected to the Teensy """ if sys.platform.startswith('win'): log.debug("Using windows system.") ports = ['COM' + str(i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this is to exclude your current terminal "/dev/tty" log.debug("Using linux system") ports = glob.glob('/dev/tty[A-Za-z]*') elif sys.platform.startswith('darwin'): log.debug("Using darwin (Apple) system") ports = glob.glob('/dev/tty.*') else: log.error("Unsupported / uncrecognized platform") raise EnvironmentError('Unsupported platform') for port in ports: log.debug("Found available port: %s" % port) # Method 1: Match via ready-to-read serial ports for port in ports: log.debug("Checking: %s" % port) try: teensy = serial.Serial(port=port, timeout=1) if teensy.read(4) != '': log.info("Using %s" % port) return teensy except (OSError, serial.SerialException): pass
def sleep_entries(self): """Probably one of the most complicated functions in this whole program. This function yields a new SleepEntry every time it is iterated over. WHAT? Yeah, that's what it does. It basically makes it so that you can use this function as a foreach to read the data, and it will stop returning SleepEntrys when there are none left in the file, without having to worry about counters and such.. Example: sleep_file = InFile('sample_file.log') for sleep_entry in sleep_file.sleep_entries: print sleep_entry """ for line in self._file: self.total_read += len(line) if line == '': # End of file reached self._file.close() raise StopIteration else: values = line.strip().split(",") assert len(values) == len(SleepEntry.header_names()), \ "Malformed sleepfile: %s Last correct line: %s" % (values, self.last_sleep_entry) try: # Convert numbers to integers, and dates/timeis date = values[1] time = values[2] index = int(values[0]) movement_value = int(values[3]) self.last_sleep_entry = SleepEntry(index, movement_value, date, time) # Yield the results. Why yield? Well, yielding means that the next time this funciton is called, # it will continue where it left off, here at the yield statement. yield self.last_sleep_entry except ValueError: log.error("Malformed sleepfile: %s Last correct line: %s" % (values, self.last_sleep_entry))
def check_correct_run_dir(): if os.getcwd()[-20:] != '/live-sleep-analyzer': log.error("Please cd into the project directory before running any scripts!") sys.exit(1)