def read_temp(scale="F"):
  """ read_temp parses raw temperature data output
  
  :param: temperature scale type "F" or "C"
  :type: string

  :returns: temperature data in fahrenheit or celsius
  :rtype: float
  """
  lines = read_temp_raw()
  count = 0
  max_loops = 10
  while (lines[0].strip()[-3:] != 'YES'):
    time.sleep(0.2)
    lines = read_temp_raw()
    count = count + 1
    if (count == max_loops):
      error = "The 'read_temp' function made " + str(max_loops) + " attempts to read output and failed: " + lines
      log.error(error)
      if alert_now(alert_file):
        send_mail(script_name, script_name + " running on '" + local_host + "' could not read temperature data output", error)
      sys.exit(3)
  equals_pos = lines[1].find('t=')
  if equals_pos != -1:
    temp_string = lines[1][equals_pos+2:]
    temp_c = float(temp_string) / 1000.0
    if (scale == "C"):
      return round_up_two(temp_c)
    else:
      temp_f = temp_c * 9.0 / 5.0 + 32.0
      return round_up_two(temp_f)
def read_temp_raw():
  """read_temp_raw retrieves temperature data from DS18B20 sensor

  :returns: raw temperature data
  :rtype: list
  """
  try:
    device_folder = glob.glob(base_dir + '28*')[0]
    device_file = device_folder + '/w1_slave'
    f = open(device_file, 'r')
    try:
      lines = f.readlines()
      return lines
    finally:
      f.close()
  except (IndexError, IOError), e:
    error = "read_temp_raw encountered an error: %s %s" % (e.__class__, e)
    log.error(error)
    if alert_now(alert_file):
      send_mail(script_name, script_name + " running on '" + local_host + "' could not read raw temperature data", error)
    sys.exit(2)
    return True
  else:
    return False

log.info("BEGIN LOGGING")

current_temp = None
try:
  current_temp = get_current_temp()
  log.info("Current temp returned: " + str(current_temp))
  spreadsheet_data = [datetime.datetime.now().isoformat(), current_temp]
  log.info("Spreadsheet input generated: " + str(spreadsheet_data))
except Exception, e:
  error = "Error getting current temperature %s %s" % (e.__class__, e)
  log.error(error)
  if alert_now(alert_file):
    send_mail(script_name, script_name + " running on '" + local_host + "' could not retrieve data properly from thermostat(" + config.thermostat_address + ")", error)
  sys.exit(1)

if (current_temp <= minimum_temperature):
  error = "The current temperature is " + str(current_temp) + " degrees.  The alert threshold is " + str(minimum_temperature) + " degrees."
  log.error(error)
  if alert_now(alert_file):
    send_mail(script_name, "CRITICAL ALERT from " + script_name + ": Temperature reading passed alert threshold", error)

try:
  log.info("Attempting to login to Google.")
  gc = get_gspread_client_login()
except Exception, e:
  error = "Google login error: %s %s" % (e.__class__, e)
  log.error(error)