
import os
import time
import MySQLdb
import datetime
import sys
import RPi.GPIO as GPIO
import spidev
import Adafruit_DHT
from Adafruit_Python_BMP.Adafruit_BMP import BMP085

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 250000
sensor = BMP085.BMP085()

def poll_sensor(channel):
    if channel:
        cbyte = 0b11000000
    else:
        cbyte = 0b10000000
    
    r = spi.xfer2([1, cbyte, 0])
    return ((r[1] & 31)<<6)+(r[2]>>2)

while True:
        db = MySQLdb.connect("mysql57.websupport.sk","rpidb","pGCAxgclJ6","rpidb",3311)
        cursor = db.cursor()
        date = datetime.datetime.now()        
        hum, temp = Adafruit_DHT.read_retry(11, 4)
        press = sensor.read_pressure()
        channel = 0
        UV = poll_sensor(channel) / 25
        channel = 1
        water = poll_sensor(channel)        
        print ('OK')
        sql = """INSERT INTO weather (TEPLOTA, VLHKOST,TLAK, VODA, UV, DATE)
		 VALUES(%s, %s, %s, %s, %s, %s)"""
        try:
            cursor.execute(sql, (str(temp), str(hum), str(press), str(water), str(UV), str(date)))
            db.commit()
        except:
            print ("Error: Will rollback")
            db.rollback()
        time.sleep(600)

cursor.close()
db.close()
