import Adafruit_BMP.BMP085 as BMP085
import smbus
import os
import sys
import getopt
import sqlite3
import math
import pigpio
import time


def read_temperature():
	handle = pi.i2c_open(1, 0x40) # open i2c bus
	pi.i2c_write_byte(handle, 0xF3) # send read temp command
	time.sleep(0.055) # readings take up to 50ms, lets give it some time
	(count, byteArray) = pi.i2c_read_device(handle, 3) # vacuum up those bytes
	pi.i2c_close(handle) # close the i2c bus
	t1 = byteArray[0] # most significant byte msb
	t2 = byteArray[1] # least significant byte lsb
	temp_reading = (t1 * 256) + t2 # combine both bytes into one big integer
	temp_reading = math.fabs(temp_reading) # I'm an idiot and can't figure out any other way to make it a float 
	temperature = ((temp_reading / 65536) * 175.72 ) - 46.85 # formula from datasheet
	return temperature

def read_humidity():
	handle = pi.i2c_open(1, 0x40) # open i2c bus
	pi.i2c_write_byte(handle, 0xF5) # send read humi command
	time.sleep(0.055) # readings take up to 50ms, lets give it some time
	(count, byteArray) = pi.i2c_read_device(handle, 3) # vacuum up those bytes
	pi.i2c_close(handle) # close the i2c bus
	h1 = byteArray[0] # most significant byte msb
	h2 = byteArray[1] # least significant byte lsb
	humi_reading = (h1 * 256) + h2 # combine both bytes into one big integer
	humi_reading = math.fabs(humi_reading) # I'm an idiot and can't figure out any other way to make it a float
	uncomp_humidity = ((humi_reading / 65536) * 125 ) - 6 # formula from datasheet
	# to get the compensated humidity we need to read the temperature
	temperature = read_temperature()
	humidity = ((25 - temperature) * -0.15) + uncomp_humidity
	return humidity





var = 1
sensor = BMP085.BMP085()
pi = pigpio.pi()

while var == 1:
	temp = sensor.read_temperature()
	pressure = sensor.read_pressure()
	humidity = read_humidity()
	cmd = "curl "+"'http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID=<YOURID>&PASSWORD=<yourpass>&dateutc=now&tempf="+str((temp*1.8)+32)+"&humidity="+str(round(humidity,2))+"&baromin="+str((pressure/100)*0.0295299)+"&action=updateraw"+"'"
	print(cmd)
	os.system(cmd)
	time.sleep(120)
