#!/usr/bin/python
# Code to control the BMP180 and BMP280 I2C sensors. Write observations to disk
# and to web in intervals determined by input.txt
# Paul A. Kucera, Ph.D. and Joseph E. Rener
# UCAR
# Boulder, CO USA
# Email: pkucera@ucar.edu and jrener@ucar.edu
# Copyright (c) 2018 UCAR
# Developed at COMET at University Corporation for Atmospheric Research and the Research Applications Laboratory at the National Center for Atmospheric Research (NCAR)
# Updated: 28 September 2018

import sys, struct, array, time, io, os, fcntl, datetime, helper_functions # pylint: disable=import-error
from helper_functions import root

sensor_found = True

try: # Import the  BMP280 Library: 4/06/2017
	import Adafruit_BMP.BMP280 as BMP280 # pylint: disable=import-error
	bmp = BMP280.BMP280()
	version = "280"
except Exception, e: # Otherwise, import the BMP085 Library
	try:
		import Adafruit_BMP.BMP085 as BMP085 # pylint: disable=import-error
		bmp = BMP085.BMP085(2)
		version = "180"
	except Exception, e: 
		now = datetime.datetime.now()
		print "%02d %02d %4d %02d %02d - Error: could not find the bmp180 or 280 sensors." % (now.month, now.day, now.year, now.hour, now.minute)
		sensor_found = False

if sensor_found:
	try:
		# Get script arguments
		arguments = helper_functions.getArguments()
		interval = arguments[0]
		chords_toggle = arguments[1]
		chords_id = arguments[2]
		pressure_level = arguments[3]*100 # Multiplied by 100 since, for whatever reason, that's how the math wants it.

		# Measured Variables
		altitude = bmp.read_altitude(pressure_level)
		tempC = bmp.read_temperature()
		pressure = bmp.read_pressure()

		# Derived Variables
		tempF = tempC*1.8+32
		slp = (pressure/100.0)*pow(1-(0.0065*altitude)/(tempC+0.0065*altitude+273.15),-5.257)
		station_pres = pressure/100.0
		slp_hg = slp/33.86389

		# Print to screen
		print "BMP" + version + " Sensor"
		print "Temperature:         %.2f degC" % tempC
		print "Temperature:         %.2f degF" % tempF
		print "Station Pressure:   ", station_pres, "mb"
		print "Sea Level Pressure:  %.2f mb" % slp
		print "Sea Level Pressure:  %.2f inHg" % slp_hg
		print "Altitude:            %.2f m" % altitude

		# Get current time
		now = datetime.datetime.now()

		# Handle script output
		line = "%02d %02d %4d %02d %02d %7.2f %6.2f %7.2f %8.2f %6.2f %8.2f" % (now.month, now.day, now.year, now.hour, now.minute, tempC, tempF, station_pres, slp, slp_hg, altitude)
		filename = root + 'data/bmp/bmp%s_%4d%02d%02d.dat' % (version, now.year, now.month, now.day)
		helper_functions.output(False, line, filename)

		# Function to send data to CHORDS (if applicable)
		url = "http://3d.chordsrt.com/measurements/url_create?instrument_id=%d&t2=%05.1f&msl1=%07.2f&sp1=%07.2f&key=21DE6A8A" % (chords_id, tempC, slp, station_pres)
		helper_functions.reportCHORDS(chords_toggle, now.minute, interval, url)	
		
	except Exception, e:
		helper_functions.handleError(e)