# GhostSensor Env by Forrest
# Some code from Adafruit's tutorials at:
### https://learn.adafruit.com/adafruit-bme680-humidity-temperature-barometic-pressure-voc-gas
### https://learn.adafruit.com/adafruit-pioled-128x32-mini-oled-for-raspberry-pi
import csv
import time
import subprocess
import board
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306
import adafruit_bme680
time.sleep(1)



try:
    i2c = board.I2C()
    time.sleep(1)
    disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)
    bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False)
    bme680.sea_level_pressure = 1013.25
except:
    time.sleep(2)
    try:
        i2c = board.I2C()
        disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)
        bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False)
        bme680.sea_level_pressure = 1013.25
    except:
        i2c = board.I2C()
        disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)
        bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False)
        bme680.sea_level_pressure = 1013.25

disp.fill(0)
disp.show()
width = disp.width
height = disp.height
image = Image.new("1", (width, height))
draw = ImageDraw.Draw(image)
draw.rectangle((0, 0, width, height), outline=0, fill=0)
padding = -2
top = padding
bottom = height - padding
x = 0
font = ImageFont.load_default()
temperature_offset = -5
time.sleep(1)
start_r = time.time()
while True:
    draw.rectangle((0, 0, width, height), outline=0, fill=0)
    draw.text((x, top + 0), "Temp: {:.2f} F".format(((bme680.temperature + temperature_offset)*9/5)+32), font=font, fill=255)
    draw.text((x, top + 8), "VOC Gas: {:.0f} ohm".format(bme680.gas), font=font, fill=255)
    draw.text((x, top + 16), "Humidity: {:.2f}%".format(bme680.relative_humidity), font=font, fill=255)
    draw.text((x, top + 25), "Pressure: {:.3f} hPa".format(bme680.pressure), font=font, fill=255)
    disp.image(image)
    disp.show()
    time.sleep(0.5)
    if time.time() - start_r > 30:
        start_r = time.time()
        fields=[start_r,((bme680.temperature + temperature_offset)*9/5)+32,bme680.gas,bme680.relative_humidity,bme680.pressure,bme680.altitude]
        with open(r'ghostSensorData.csv', 'a+') as f:
            writer = csv.writer(f)
            writer.writerow(fields)
