#!/usr/bin/python
# Code to control the tipping bucket rain gauge. 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

# Adpated from Joe Gutting Adafruit SI1145 library for Arduino, Adafruit_GPIO.I2C & BMP Library by Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

import SI1145.SI1145 as SI1145, sys, struct, array, time, io, os, fcntl, datetime, 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]
	
# Assign variable to sensor name
sensor = SI1145.SI1145()

try:
	# Run the code
	vis = sensor.readVisible()
	IR = sensor.readIR()
	UV = sensor.readUV()
	uvIndex = UV / 100.0

	# Print to screen
	print "SI1145 Sensor"
	print "Vis:       %s" % vis
	print "IR:        %s" % IR
	print "UV Index:  %s" % uvIndex

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

	# Handle script output
	line = "%02d %02d %4d %02d %02d %10.3f %10.3f %10.3f %10.3f" % (now.month, now.day, now.year, now.hour, now.minute, vis, IR, UV, uvIndex)
	filename = root + 'data/si1145/si1145_%4d%02d%02d.dat' % (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&vis1=%010.1f&ir1=%010.1f&uv1=%010.1f&key=21DE6A8A" % (chords_id, vis, IR, UV)
	helper_functions.reportCHORDS(chords_toggle, now.minute, interval, url)

except Exception, e:
	helper_functions.handleError(e)
