#!/usr/bin/python
# Code to control the windspeed sensor. 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 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]

# Sensor counter variable
COUNT = 1

# Number of sensors in anemometer
SENSOR_NUM = 2

# Sample time in seconds
SAMPLE = 58.5

# Wind speed calibration factor
CAL_Factor = 2.64 # (3.14/1.19)

# Offset factor for different plastic material (PLA)
OFFSET = 0.0

SCALE = CAL_Factor*(2*3.14156*0.079)/(SENSOR_NUM*SAMPLE) # wind speed in m/s

# Identify the GPIO pin for the wind sensor
PIN = 22
##PIN = 15

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

# Variable to keep track of how much rotations
wind = 0

# Call back function for each wind sensor reading
def cb(channel):
	global wind
	wind = wind + COUNT
					
# Register the call back for pin interrupts
GPIO.add_event_detect(PIN, GPIO.FALLING, callback=cb, bouncetime=1)

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

print "Wind Speed Sensor"

# Display and write data to file and send to CHORDS
while True:
	then = float(time.time())
	try:
		if wind > 0:
			wind_spd = wind*SCALE+OFFSET
		else:
			wind_spd = 0.0

		# Get current time for each record and filename
		now = datetime.datetime.now()

		# Handle script output
		line = "%02d %02d %4d %02d %02d %6.2f" % (now.month, now.day, now.year, now.hour, now.minute, wind_spd)		
		filename = root + 'data/wind_speed/wind_speed_%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&ws=%04.2f&key=21DE6A8A" % (chords_id, wind_spd)
		helper_functions.reportCHORDS(chords_toggle, now.minute, interval, url)

		wind = 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)
		##time.sleep(3-diff)

	except Exception, e:
		helper_functions.handleError(e)

GPIO.cleanup()
