#!/usr/bin/python
# Code to control the MCP9808 temperature 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 Adafruit_MCP9808.MCP9808 as MCP9808, 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]

# Define the sensor variable
sensor = MCP9808.MCP9808()

# Initialize communication with the sensor.
sensor.begin()

try:
	# Get observation
	tempC = sensor.readTempC()
	tempF = tempC*1.8+32

	# Print to screen
	print "MCP9808 Sensor"
	print "Temperature:  %.2f degC" % tempC
	print "Temperature:  %.2f degF" % tempF

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

	# Handle script output
	line = "%02d %02d %4d %02d %02d %6.1f %5.1f" % (now.month, now.day, now.year, now.hour, now.minute, tempC, tempF)
	filename = root + 'data/mcp9808/mcp9808_%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&t3=%05.1f&key=21DE6A8A" % (chords_id, tempC)
	helper_functions.reportCHORDS(chords_toggle, now.minute, interval, url)

except Exception, e:
	helper_functions.handleError(e)
