import subprocess
import math
import picamera
import os
import RPi.GPIO as GPIO
import time
import datetime
import smbus
import io
import fcntl
import glob

SG=1
temp=str(0)
dpm=str(0)
SAL=str(0)

file_read = io.open("/dev/i2c-1", "rb", buffering=0)
file_write = io.open("/dev/i2c-1", "wb", buffering=0)

I2C_SLAVE = 0x703
fcntl.ioctl(file_read, I2C_SLAVE, 100)  #atlas scientific conductivity prob address 100
fcntl.ioctl(file_write, I2C_SLAVE, 100)

lad=raw_input('lat degrees ')
lam=raw_input('lat min ')
las=raw_input('lat sec ')
lac=raw_input('N or S ')
lod=raw_input('long degrees ')
lom=raw_input('long min ')
los=raw_input('long sec ')
loc=raw_input('W or E ')
loca=lad+' '+lam+"' "+las+'" '+lac+' '+lod+' '+lom+"' "+los+'" '+loc
locad=str(float(lad) +round(((float(lam)+(float(las)/60))/60),6))+lac+str(float(lod)+round(((float(lom)+(float(los)/60))/60),6))+loc
lo=locad.replace('.','-')

TXT = str(datetime.datetime.now())
TXT=TXT[2:16]
TXT=TXT.replace('-','')
TXT=TXT.replace(' ','')
TXT=TXT.replace(':','')
TXT=TXT+'-'+lo
PF='./UW'+TXT
os.mkdir(PF)
FN=TXT
TXT=PF+"/CTD"+TXT+".csv"

fo=open(TXT,'a')
fo.write('date    time,pressure,depth M,Depth F,temp C,Temp F,Con,Salinity,SG,'+loca+','+locad+'\n')
fo.close()

bus = smbus.SMBus(1)
bus.write_byte(0x40,0xFE)
time.sleep(1)
bus.write_byte(0x76, 0x1E)
time.sleep(0.5)
data = bus.read_i2c_block_data(0x76, 0xA2, 2)
C1 = data[0] * 256 + data[1]
data = bus.read_i2c_block_data(0x76, 0xA4, 2)
C2 = data[0] * 256 + data[1]
data = bus.read_i2c_block_data(0x76, 0xA6, 2)
C3 = data[0] * 256 + data[1]
data = bus.read_i2c_block_data(0x76, 0xA8, 2)
C4 = data[0] * 256 + data[1]
data = bus.read_i2c_block_data(0x76, 0xAA, 2)
C5 = data[0] * 256 + data[1]
data = bus.read_i2c_block_data(0x76, 0xAC, 2)
C6 = data[0] * 256 + data[1]

def read_con():
        # reads a specified number of bytes from I2C, then parses and displays the result
        try:
		Ts="T,"+str(temp)+"\00"
        	file_write.write(Ts)
        	time.sleep(0.3)
        	file_write.write("R\00")
        	time.sleep(0.65)
        	res = file_read.read(31)         # read from the board
        	res=res.replace('\x00','')
        	res=res[1:]
		#return res
	except IOError:
		res=str(con)
		print "error ",tpt," con ",res
	else:
	        return res
def pres(): #30Bar
	bus.write_byte(0x76, 0x40)
	time.sleep(0.018)
	value = bus.read_i2c_block_data(0x76, 0x00, 3)
	D1 = value[0] * 65536 + value[1] * 256 + value[2]
	bus.write_byte(0x76, 0x50)
	time.sleep(0.018)
	value = bus.read_i2c_block_data(0x76, 0x00, 3)
	D2 = value[0] * 65536 + value[1] * 256 + value[2]
	dT = D2 - C5 * 256
	TEMP = 2000 + dT * C6 / 8388608
	OFF = C2 * 65536 + (C4 * dT) / 128
	SENS = C1 * 32768 + (C3 * dT ) / 256
	T2 = 0
	OFF2 = 0
	SENS2 = 0
	if TEMP > 2000 :
		T2 = 7 * (dT * dT)/ 137438953472
		OFF2 = ((TEMP - 2000) * (TEMP - 2000)) / 16
		SENS2= 0
	elif TEMP < 2000 :
		T2 = 3 * (dT * dT) / 8589934592
		OFF2 = 3 * ((TEMP - 2000) * (TEMP - 2000)) / 2 #changed from 8 to 2
		SENS2 = 5 * ((TEMP - 2000) * (TEMP - 2000)) / 8
		if TEMP < -1500:
			OFF2 = OFF2 + 7 * ((TEMP + 1500) * (TEMP + 1500))
			SENS2 = SENS2 + 4 * ((TEMP + 1500) * (TEMP + 1500))
	TEMP = TEMP - T2
	OFF = OFF - OFF2
	SENS = SENS - SENS2
	pressure = ((((D1 * SENS) / 2097152) - OFF) / 8192) / 10.0 #8192 for 30Bar sensors change to 32768 for 14Bar
	pressure=pressure+39 #correction
        return pressure

def si7051():
	bus.write_byte(0x40,0xF3)
	time.sleep(.011)
	data= bus.read_i2c_block_data(0x40,0xE0,2)
	rt= data[0] * 256 + data[1]
	temp=((175.72 * rt)/65536)-46.85
	return temp

SL=pres()
SL=(pres()+pres()+pres())/3
print 'OK ',SL
tpt=str(datetime.datetime.now())
fo=open(TXT,'a')
fo.write(tpt[0:19])
fo.write(',%.2f\n' %SL)
fo.close()

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(20,GPIO.OUT)
GPIO.output(20,1)  #****************LIGHTS ON***************************

camera = picamera.PiCamera(sensor_mode=5,framerate=30)
camera.resolution=(1640,922)
camera.rotation=180
camera.meter_mode='matrix'
camera.iso=800
camera.annotate_text_size=20
try:
    
    for filename in camera.record_sequence([PF+'/UW'+FN+'-%d.h264' % i for i in range(1,49)],quality=24):
        starttime=datetime.datetime.now()
        camera.annotate_text = loca+'   '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'   '+temp+'C   '+dpm+'M   '+SAL+'g/kg   '
        while (datetime.datetime.now()-starttime).seconds <900: #900 = 15min
            temp=si7051()
            tempf=1.8 * temp + 32
            p=pres()
            con=read_con()
            sgp=con.rfind('.')
            sgp=sgp-1
            SG=con[sgp: ]
            SGS=SG
            SG=float(SG)
            slp=con.find(',')
            slp=slp+1
            sgp=sgp-1
            SAL=con[slp:sgp]
            dpm=(SL-p)/(98.1*SG)
            dpFT=3.28084*dpm
            tpt=str(datetime.datetime.now())
            fo=open(TXT,'a')
            fo.write(tpt[0:19])
            fo.write(',%.2f' %p)
            fo.write(',%.3f' %dpm)
            fo.write(',%.3f' %dpFT)
            fo.write(',%.2f' %temp)
            fo.write(',%.2f,' %tempf)
            fo.write(con)
            fo.write('\n')
            fo.close()
            temp=str('%.2f'% round(temp,2))
            dpm=str('%.2f'% round(dpm,2))
            camera.annotate_text = loca+'   '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'   '+temp+'C   '+dpm+'M   '+SAL+'g/kg   '#+SGS+'g/cm3'
        camera.wait_recording()
    GPIO.output(20,0)
    nfd=len(glob.glob(PF+'/*'))
    for i in range(1,nfd):
        f=str(i)
        mp4com= 'MP4Box -fps 30 -add '+PF+'/UW'+FN+'-'+f+'.h264 '+PF+'/UW'+FN+'-'+f+'.mp4'
        subprocess.call(mp4com,shell=True)
        dh264='rm '+PF+'/UW'+FN+'-'+f+'.h264'
        subprocess.call(dh264,shell=True)

except KeyboardInterrupt:
    pass
    GPIO.cleanup()
    nfd=len(glob.glob(PF+'/*'))
    for i in range(1,nfd):
        f=str(i)
        mp4com= 'MP4Box -fps 30 -add '+PF+'/UW'+FN+'-'+f+'.h264 '+PF+'/UW'+FN+'-'+f+'.mp4'
        subprocess.call(mp4com,shell=True)
        dh264='rm '+PF+'/UW'+FN+'-'+f+'.h264'
        subprocess.call(dh264,shell=True)
