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)
    return(temp)

def temp():
    round(sense.get_temperature()*1.8+32)
def humidity():
    round(sense.get_humidity())
def pressure():
    round(sense.get_pressure())

    
while True :
    currenttime = datetime.now().day, datetime.now().hour, datetime.now().minute
    currenttimeb = time.strftime("%D:%H:%M")
    temper = round(sense.get_temperature()*1.8+32)
    humidityer = round(sense.get_humidity())
    pressureer = round(sense.get_pressure())
    message = 'Temp is %d F. Humidity is %d percent. Pressure is %d mbars.' %(temper,humidityer,pressureer) 
    tempA = GetTemperature()
    tempA = str(tempA)
    temp = str(temper)
    titletime = datetime.now().year, datetime.now().month, datetime.now().day
    titletime = str(titletime)
    print(temper)
    print(currenttime)
    print(humidityer)
    currenttime = str(currenttime)
    humidity = str(humidityer)
    sleep(60)
    temp2 = round(sense.get_temperature()*1.8+32)
    temp2 = str(temp2)
    tempA = GetTemperature()
    tempA = str(tempA)
    currenttime2 = datetime.now().hour, datetime.now().minute
    currenttime2 = str(currenttime2)
    humidity2 = round(sense.get_humidity())
    humidity2 = str(humidity2)
    print (temp2)
    print (currenttime2)
    print(humidity2)
    sleep(60)
    temp3 = round(sense.get_temperature()*1.8+32)
    temp3 = str(temp3)
    tempA = GetTemperature()
    tempA = str(tempA)
    currenttime3 = datetime.now().hour, datetime.now().minute
    currenttime3 = str(currenttime3)
    humidity3 = round(sense.get_humidity())
    humidity3 = str(humidity3)
    print (temp3)
    print (currenttime3)
    print (humidity3)
    sleep(60)
    temp4 = round(sense.get_temperature()*1.8+32)
    temp4 = str(temp4)
    tempA = GetTemperature()
    tempA = str(tempA)
    currenttime4 = datetime.now().hour, datetime.now().minute
    currenttime4 = str(currenttime4)
    humidity4 = round(sense.get_humidity())
    humidity4 = str(humidity4)
    print (temp4)
    print (currenttime4)
    print (humidity4)
    sleep(60)
    temp5 = round(sense.get_temperature()*1.8+32)
    temp5 = str(temp5)
    tempA = GetTemperature()
    tempA = str(tempA)
    currenttime5 = datetime.now().hour, datetime.now().minute
    currenttime5 = str(currenttime5)
    humidity5 = round(sense.get_humidity())
    humidity5 = str(humidity5)
    print (temp5)
    print (currenttime5)
    print (humidity5)
    sleep(60)
    temp6 = round(sense.get_temperature()*1.8+32)
    temp6 = str(temp4)
    tempA = GetTemperature()
    tempA = str(tempA)
    currenttime6 = datetime.now().hour, datetime.now().minute
    currenttime6 = str(currenttime6)
    humidity6 = round(sense.get_humidity())
    humidity6 = str(humidity6)
    print (temp6)
    print (currenttime6)
    print (humidity6)
    #date = time.strftime("%D:%H:%M")
    #date = str(date+".htm")
    #print(date)
    camera.rotation = 180
    camera.start_preview()
    sleep(5)
    camera.capture('/home/pi/image4.jpg')
    camera.stop_preview()
    
    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('<meta charset="UTF-8">\n')
        f.write('<title>Created By Bryn/Python</title>\n')
        f.write('<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', 'Temp', 'Temp 2', 'Humidity'],\n")
        f.write("['")
        f.write(currenttime)
        f.write("',")
        f.write(temp)
        f.write(", ")
        f.write(tempA)
        f.write(", ")
        f.write(humidity)
        f.write("],\n")
        f.write("['")
        f.write(currenttime)
        f.write("', ")
        f.write(temp)
        f.write(", ")
        f.write(tempA)
        f.write(", ")
        f.write(humidity)
        f.write("],\n")
        f.write(" ['")
        f.write(currenttime)
        f.write("', ")
        f.write(temp)
        f.write(", ")
        f.write(tempA)
        f.write(", ")
        f.write(humidity)
        f.write("],\n")
        f.write("['")
        f.write(currenttime)
        f.write("', ")
        f.write(temp)
        f.write(", ")
        f.write(tempA)
        f.write(", ")
        f.write(humidity)
        f.write("],\n")
        f.write("['")
        f.write(currenttime)
        f.write("', ")
        f.write(temp)
        f.write(", ")
        f.write(tempA)
        f.write(", ")
        f.write(humidity)
        f.write("],\n")
        f.write("['")
        f.write(currenttime)
        f.write("', ")
        f.write(temp)
        f.write(", ")
        f.write(tempA)
        f.write(", ")
        f.write(humidity)
        f.write("]\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("</head>\n")
        f.write("<body>\n")
        f.write('<div id="curve_chart" style="width: 900px; height: 500px"></div>\n')
        f.write('<p>\n')
        f.write(message )
        f.write('</p>\n')
        f.write('<img src = "image4.jpg" width = "500" height = "500">')
        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'
    ftppath = 'Bryn'
    filename = "PythonWeather"+currenttime+".htm"
    s.cwd(ftppath)
    f = open(file, 'rb')
    s.storlines('STOR ' + filename, f)
    s.sendcmd('chmod 0664 PythonWeather.htm')

