#!/usr/bin/env/python3.2

import time 
import os 
import re 
import datetime 
import sqlite3
import sys

def get1WireTemp(path):
	try:
		f = os.popen(path)
		text = f.readlines()
		f.close()
		no = text[0].find('NO')
		while text[0].find('NO') != -1:
			f = os.popen(path)
			text = f.readlines()
			f.close()
			#print('w %r' % text[0])
		index = text[1].find('t')
		indexStart = index + 2
		indexEnd = index + 7
		strTemperature = text[1][indexStart:indexEnd]
		fTemperature1 = float(int(strTemperature) / 1000)
		return(fTemperature1) 

	except (KeyboardInterrupt, SystemExit):
		raise # this exception is raised to be caught by the outer try block

# Log temperature to the database
def logToDatabase(temperature):
	try:
		try:
			xAxis = 0.0
			yAxis = 0.0
			zAxis = 0.0
			fTemperature = float(temperature)
			con = sqlite3.connect('/mnt/networkShare/database/ADXL345.db')
			cur = con.cursor()
			cur.execute("INSERT INTO Environment (Temperature, xAxis, yAxis, zAxis) VALUEs(?, ?, ?, ?)", (fTemperature, xAxis, yAxis, zAxis))
			con.commit()
		
		except (KeyboardInterrupt, SystemExit):
			raise

	except sqlite3.Error as e:
		if con:
			con.rollback()

		print('Error %s' % e.args[0])
		sys.exit(1)

	finally:
		if con:
			con.close()


while(1):
	try:
		currentTemperature1 = get1WireTemp('cat /sys/bus/w1/devices/w1_bus_master1/28-0000049bc2c6/w1_slave') 
		logToDatabase(currentTemperature1)
		time.sleep(0.01)
	except (KeyboardInterrupt, SystemExit):
		sys.exit(1)
