#!/usr/bin/python
# Code to control the wind direction sensor. Write observations to disk
# Used for Demos
# 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 spidev, time, os, glob, csv, datetime, sys, RPi.GPIO as GPIO, helper_functions # pylint: disable=import-error
from helper_functions import root

# Code for MCP3002
# Channel 0 is for wind direction
def analog_read(channel, spi):
	if ((channel > 1) or (channel < 0)):
		return -1
	r = spi.xfer2([1, (2 + channel) << 6, 0])
	adc_out = ((r[1]&31) << 6) + (r[2]>>2)
	return adc_out

# Setup sensors
spi = spidev.SpiDev()
spi.open(0,0)

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.OUT)

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

print "Wind Direction Demo"

while True:
	try:
		# Wind sensor is on channel 0
		ch = 0
		reading = analog_read(ch, spi)

		# Input of min/max from ADC taken from Calibration
		ADC_min = 103 
		ADC_max = 920
		ADC_range = ADC_max - ADC_min

		# Convert to deg from north
		if (reading < ADC_min):
			wnddir = 0
		elif (reading > ADC_max):
			wnddir = 360
		else:
			# Get ADC to relative zero
			ADC_rel = reading - ADC_min
			wnddir = ADC_rel*360.0/ADC_range

		# Get current time for writing to file
		now = datetime.datetime.now()

		# Handle script output
		line = "%02d %02d %4d %02d %02d %02d %5d %5.1f deg" % (now.month, now.day, now.year, now.hour, now.minute, now.second, reading, wnddir)			
		filename = root + 'data/wind_instant/wind_instant_%4d%02d%02d.dat' % (now_file.year, now_file.month, now_file.day)
		helper_functions.output(True, line, filename)

		time.sleep(1)
	
	except Exception, e:
		helper_functions.handleError(e)