from sense_hat import SenseHat
from datetime import datetime
from time import sleep
import time
import RPi.GPIO as GPIO
import subprocess
from ftplib import FTP_TLS
from picamera import PiCamera

sense = SenseHat()
camera = PiCamera()

def GetTemperature():
#Routine to read the temperature
#Read the sensor 10 times checking the CRC until we have a good read 

    subprocess.call(['modprobe', 'w1-gpio'])
    subprocess.call(['modprobe', 'w1-therm'])

    # Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before.
    filename = "/sys/bus/w1/devices/28-00000a07c2ef/w1_slave"

    tfile = open(filename)
    # Read all of the text in the file.
    text = tfile.read()
    # Close the file now that the text has been read.
    tfile.close()
    # Split the text with new lines (\n) and select the second line.
    secondline = text.split("\n")[1]
    # Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
    temperaturedata = secondline.split(" ")[9]
    # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
    temperature = float(temperaturedata[2:])
    # Put the decimal point in the right place and display it.
    temperature = temperature / 1000
    temp = float(temperature)
    # Do the Farenheit conversion if required

    temp=temp*1.8+32
    temp = round(temp,2)
    temp = str(temp)
    return(temp)

while True :
    #variable for the time stamp.
    currenttime = datetime.now().day, datetime.now().hour, datetime.now().minute
    #Date and Time For Title.
    titletime = datetime.now().year, datetime.now().month, datetime.now().day
    titletime = str(titletime)
    #Gets the Time, Temp, Humidity and Pressure.
    currenttimeb = datetime.now().hour, datetime.now().minute
    temp = round(sense.get_temperature()*1.8+32)
    humidity = round(sense.get_humidity())
    pressure = round(sense.get_pressure())
    tempA = GetTemperature()
    message = 'Temp is %d F. Humidity is %d percent. Pressure is %d mbars.' %(temp,humidity,pressure) 

    #Converts the Time, Temp, and Humidity to a form the chart can print.
    tempA = str(tempA)
    temp = str(temp)
    currenttime = str(currenttime)
    currenttimeb = str(currenttimeb)
    humidity = str(humidity)
    #Prints Time, Temp, and Humidity while running.
    print(temp)
    print(currenttimeb)
    print(humidity)
    print(tempA)
    print('No Errors')
    sleep(120)
    #Gets the Second Round of readings.
    temp2 = round(sense.get_temperature()*1.8+32)
    tempB = GetTemperature()
    currenttime2 = datetime.now().hour, datetime.now().minute
    humidity2 = round(sense.get_humidity())
    #Converts the Time, Temp, and Humidity to a form the chart can print.
    temp2 = str(temp2)
    humidity2 = str(humidity2)
    currenttime2 = str(currenttime2)
    #Prints Time, Temp, and Humidity while running.
    print (temp2)
    print (currenttime2)
    print(humidity2)
    print(tempB)
    print('No Errors')
    sleep(120)
    #Gets the Second Round of readings.
    temp3 = round(sense.get_temperature()*1.8+32)
    tempC = GetTemperature()
    currenttime3 = datetime.now().hour, datetime.now().minute
    humidity3 = round(sense.get_humidity())
    #Converts the Time, Temp, and Humidity to a form the chart can print.
    temp3 = str(temp3)
    tempC = str(tempC)
    humidity3 = str(humidity3)
    currenttime3 = str(currenttime3)
    #Prints Time, Temp, and Humidity while running.
    print (temp3)
    print (currenttime3)
    print (humidity3)
    print(tempC)
    print('No Errors')
    sleep(120)
    #Gets the Fourth Round of readings.
    temp4 = round(sense.get_temperature()*1.8+32)
    tempD = GetTemperature()
    currenttime4 = datetime.now().hour, datetime.now().minute
    humidity4 = round(sense.get_humidity())
    #Converts the Time, Temp, and Humidity to a form the chart can print.
    temp4 = str(temp4)
    tempD = str(tempD)
    currenttime4 = str(currenttime4)
    humidity4 = str(humidity4)
    #Prints Time, Temp, and Humidity while running.
    print (temp4)
    print (currenttime4)
    print (humidity4)
    print(tempD)
    print('No Errors')
    sleep(120)
    #Gets the Fifth Round of readings.
    temp5 = round(sense.get_temperature()*1.8+32)
    tempE = GetTemperature()
    currenttime5 = datetime.now().hour, datetime.now().minute
    humidity5 = round(sense.get_humidity())
    #Converts the Time, Temp, and Humidity to a form the chart can print.
    temp5 = str(temp5)
    tempE = str(tempE)
    currenttime5 = str(currenttime5)
    humidity5 = str(humidity5)
    
    print (temp5)
    print (currenttime5)
    print (humidity5)
    print(tempE)
    print('No Error')
    sleep(120)
    #Gets the Fifth Round of readings.
    temp6 = round(sense.get_temperature()*1.8+32)
    tempF = GetTemperature()
    currenttime6 = datetime.now().hour, datetime.now().minute
    humidity6 = round(sense.get_humidity())
    #Converts the Time, Temp, and Humidity to a form the chart can print.
    temp6 = str(temp6)
    tempF = str(tempF)
    currenttime6 = str(currenttime6)
    humidity6 = str(humidity6)
    #Prints Time, Temp, and Humidity while running.
    print (temp6)
    print (currenttime6)
    print (humidity6)
    print(tempF)
    print('All Reading OK')
    #Takes a Picture.
    camera.rotation = 180
    camera.start_preview()
    sleep(5)
    camera.capture('/home/pi/'+currenttime+'.jpg')
    camera.stop_preview()
    #Writes the information to another file.
    filename = "PythonWeather"+currenttime+".htm"
    with open(filename, "w") as f:
        f.write('<doctype html>\n')
    with open(filename, "a") as f:
        f.write('<html>\n')
        f.write('<head>\n')
        f.write("</head>\n")
        f.write("<body>\n")
        f.write('<body bgcolor="#00cc00">')
        f.write('<h1><center>IOT Smart Home</center></h1>')
        f.write('<meta charset="UTF-8">\n')
        f.write('<title>Created By Bryn/Python</title>\n')
        f.write('<center><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>\n')
        f.write('<script type="text/javascript">\n')
        f.write("google.charts.load('current', {'packages':['corechart']});\n")
        f.write('google.charts.setOnLoadCallback(drawChart);\n')
        f.write('function drawChart() {\n')
        f.write('var data = google.visualization.arrayToDataTable([\n')
        f.write("['Time', 'Raspberry Pi Temp', 'Temp 2', 'Humidity'],\n")
        f.write("['"+currenttimeb+"',"+temp+", "+tempA+", "+humidity+"],\n")
        f.write("['"+currenttime2+"', "+temp2+", "+tempB+", "+humidity2+"],\n")
        f.write("['"+currenttime3+"', "+temp3+", "+tempC+", "+humidity3+"],\n")
        f.write("['"+currenttime4+"', "+temp4+", "+tempD+", "+humidity4+"],\n")
        f.write("['"+currenttime5+"', "+temp5+", "+tempE+", "+humidity5+"],\n")
        f.write("['"+currenttime6+"', "+temp6+", "+tempF+", "+humidity6+"],\n")
        f.write(']);\n')
        f.write('var options = {\n')
        f.write("title: 'Weather Graph")
        f.write(titletime)
        f.write("',\n curveType: 'function',\n legend: { position: 'bottom' }\n")
        f.write('};\n')
        f.write("var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));\n")
        f.write('chart.draw(data, options); \n}')
        f.write('</script>') 
        f.write('<div id="curve_chart" style="width: 900px; height: 500px"></div>\n')
        f.write('</center><center><p>\n')
        f.write(message )
        f.write('</p></center>\n')
        f.write('<h2><center> Room Picture </center> </h2>')
        f.write('<center><img src = "')
        f.write(currenttime)
        f.write('.jpg" width = "800" height = "500" border="5"></center>')
        f.write("</body>\n")
        f.write('</html>\n')
        f.write('<script type="text/javascript">(function (d, w)')
        f.write("{var x = d.getElementsByTagName('SCRIPT')[0];var f = function () {var s = d.createElement('SCRIPT');s.type = 'text/javascript';s.async =")
        f.write('true;s.src = "//np.lexity.com/embed/YW/017e8fb8f38b500ed7dda07e57117825?id=965bf228fcbf";x.parentNode.insertBefore(s, x);};w.attachEvent ? w.attachEvent')
        f.write("('onload',f) :w.addEventListener('load',f,false);}(document, window));</script><script type=")
        f.write('"text/javascript">(function (d, w) {var x = d.getElementsByTagName')
        f.write("('SCRIPT')[0];var f = function () {var s = d.createElement('SCRIPT');s.type = 'text/javascript';s.async = true;s.src = ")
        f.write('"//np.lexity.com/embed/YW/017e8fb8f38b500ed7dda07e57117825?id=965bf228fcbf";x.parentNode.insertBefore(s, x);};w.attachEvent ? w.attachEvent')
        f.write("('onload',f) :w.addEventListener('load',f,false);}(document, window));</script>")
    # Try to make it tell if a reading is unusual 
    print("Hi") 
    s = FTP_TLS('ftp.lafavre.us')
    s.login('gear@lafavre.us', 'Iotisnumber1!')
    file = '/home/pi/PythonWeather'+currenttime+'.htm'
    file2 = '/home/pi/'+currenttime+'.jpg'
    ftppath = '/Bryn'
    filename = "PythonWeather"+currenttime+".htm"
    filename2 = currenttime+".jpg"
    s.cwd(ftppath)
    f = open(file, 'rb')
    a = open(file2, 'rb')
    s.storbinary('STOR '+ filename2, a)
    s.storlines('STOR ' + filename, f)
    s.sendcmd('chmod 0664 PythonWeather.htm')
    print("Upload Complete")

