#!/usr/bin/python
# Code to control the wind direction sensor. Write observations to disk
# and to web in intervals determined by input.txt
# Computes a 1 minute geometric average
# 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 RPi.GPIO as GPIO, time, datetime, sys, helper_functions # pylint: disable=import-error
from helper_functions import root

# Get script arguments
arguments = helper_functions.getArguments()
interval = arguments[0]
chords_toggle = arguments[1]
chords_id = arguments[2]

# Rainfall Accumulation in mm per bucket tip (TB3 Specs)
CALIBRATION = 0.2

# Identify the GPIO pin for the rain gauge
PIN = 23

GPIO.setmode(GPIO.BCM)  
GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Variable to keep track of how much rain
rain = 0
rain_accumulation = 0.0

# Call back function for each bucket tip
def tipped(channel):
	global rain
	rain = rain + CALIBRATION
				
# Register the call back for pin interrupts
GPIO.add_event_detect(PIN, GPIO.FALLING, callback=tipped, bouncetime=300)

print "Rain (tipping bucket) Sensor"

# Display, write to file, and send to CHORDS
while True:
	then = float(time.time())
	try:
		# Get current date/time for logging and filename
		now = datetime.datetime.now()

		# Accumulate rain for larger intervals
		rain_accumulation = rain_accumulation + rain

		# Handle script output
		line = "%02d %02d %4d %02d %02d %6.2f" % (now.month, now.day, now.year, now.hour, now.minute, rain)
		filename = root + 'data/rain/rain_%4d%02d%02d.dat' % (now.year, now.month, now.day)
		helper_functions.output(True, line, filename)

		# Function to send data to CHORDS (if applicable)
		url = "http://3d.chordsrt.com/measurements/url_create?instrument_id=%d&rain=%04.2f&key=21DE6A8A" % (chords_id, rain_accumulation)
		helper_functions.reportCHORDS(chords_toggle, now.minute, interval, url)

		# Reset rain_accumination if it's time to record it
		if now.minute % interval == 0: 
			rain_accumulation = 0.0
					
		rain = 0		

		# Wait until a minute has passed since current run began, and run again
		now = float(time.time())
		diff = now-then
		time.sleep(60-diff)

	except Exception, e:
		helper_functions.handleError(e)
		
GPIO.cleanup()

