'''
Weather station:
        One script to rule them all...
HMH - 18/07/2018
'''

import sys,time,os
import Adafruit_DHT, Adafruit_MCP3008
import Adafruit_GPIO.SPI as SPI
import RPi.GPIO as GPIO
import spidev
import numpy as np
from gpiozero import DigitalInputDevice
from time import sleep
#import math
#import subprocess
import datetime,requests,json
import smtplib
from email.mime.text import MIMEText
import simple_read_windspeed as srw
#import analog_read as ar
try:
    import aqi
except:
    print 'USB not connected'
    
import platform, string

def sendemail(from_addr, to_addr_list,
              subject, message,
              login, password,
              smtpserver='smtp.gmail.com:587'):
    header = 'From: %s\n' % from_addr
    header += 'To: %s\n' % ','.join(to_addr_list)
    header += 'Subject: %s\n\n' % subject
    message = header + message

    server = smtplib.SMTP(smtpserver)
    server.starttls()
    server.login(login,password)
    problems = server.sendmail(from_addr, to_addr_list, message)
    server.quit()
    return problems

def get_temp_hum(sensor,pin):
    t_array = np.zeros(10)
    h_array = np.zeros(10)
    for i in range(0,len(t_array)):
        h_array[i], t_array[i] = Adafruit_DHT.read_retry(sensor, pin)
    humidity = np.median(h_array)
    temperature = np.median(t_array)
    return humidity, temperature


def windspeed_helper():
    count = 0
    wind_speed_sensor = srw.DigitalInputDevice(5)
    wind_speed_sensor.when_activated = srw.spin
    time_interval = 0.5*60 # seconds
    time_later = time.time()
    timestamp = time.time()
    wind_array = []
    while time_later < timestamp + time_interval:
        srw.count = 0
        srw.sleep(5)
        instantaneous_windspeed = srw.get_windspeed()
        if count == 1:
            instantaneous_windspeed = 0.0
        wind_array.append(instantaneous_windspeed)
        time_later = time.time()
    #windspeed = srw.calculate_speed(5)
    #wind_array = simple_read_windspeed.wind_val
    #windspeed = np.mean(wind_array)
    #print "value from anemometer: ",wind_array
    return wind_array

def dust_helper():
    pm25 = []
    pm10 = []
    aqi.cmd_set_sleep(0)
    aqi.cmd_set_mode(1);
    for t in range(15):
        values = aqi.cmd_query_data();
        if values is not None:
            pm25.append(values[0])
            pm10.append(values[1])
            time.sleep(2)
    #print pm10
    #print pm25
    #print("Going to sleep for 5min...")
    aqi.cmd_set_mode(0);
    aqi.cmd_set_sleep()
    #time.sleep(300)
    return pm10,pm25


def read_analog(numSamples,pinVal):
    #Hardware SPI configuration:
    SPI_PORT = 0
    SPI_DEVICE = 0
    mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

    # Choose GPIO pin - not actually sure if we need this, but leaving it in for meow
    ledPin = 18

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(ledPin,GPIO.OUT)

    samplingTime = 280.0
    deltaTime = 40.0
    sleepTime = 9680.0
    
    return_array = []
    try: 
        for i in range(0,numSamples):
            GPIO.output(ledPin,0)
            time.sleep(samplingTime*10.0**-6)
            # The read_adc function will get the value of the specified channel
            voMeasured = mcp.read_adc(pinVal)
            time.sleep(samplingTime*10.0**-6)
            GPIO.output(ledPin,1)
            time.sleep(samplingTime*10.0**-6)
            calcVoltage = voMeasured*(5.0/1024)
            return_array.append(calcVoltage)
            time.sleep(1)

    except KeyboardInterrupt:
        GPIO.cleanup()
    return return_array


if __name__=="__main__":

    error_log_name = 'error_log.txt'
    erf = open(error_log_name,'a')
    myname = os.uname()[1]
    try:
        # Send email to let human know I'm alive
        sendemail(from_addr = 'oddweatherstation@gmail.com',
                  to_addr_list = ['heiko@opendata.durban'],
                  subject = 'System has restarted',