#!/usr/bin/python

import RPi.GPIO as GPIO
import time
import os

GPIO.setmode(GPIO.BCM)

TRIG = 14
ECHO = 4

# Evergreen 1500 Gallon Pump Tank Model 1500P
# 35 Gallons per inch of tank depth
# (According to installer Mark Babbitt,
#  needs verification)
GAL_PER_INCH = 35
# Sensor height above bottom of tank
SENSOR_HEIGHT = 60

# Home Assistant MQTT Info
MQTT_HOST = "10.0.1.19"
MQTT_PORT = "1883"
MQTT_USER = "septic"
MQTT_PASS = ""
MQTT_TOPIC = "septic/level"

GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

GPIO.output(TRIG, False)
print "Waiting for sensor to settle"
time.sleep(2)

try:
    while True:
        GPIO.output(TRIG, True)
        time.sleep(0.00001)
        GPIO.output(TRIG, False)
        while GPIO.input(ECHO)==0:
            pulse_start = time.time()
        while GPIO.input(ECHO)==1:
            pulse_end = time.time()
        pulse_duration = pulse_end - pulse_start
        distance = pulse_duration * 17150 / 2.54
        print "Distance: ", distance, "inch"
        # compute height of water from bottom of tank
        water_height = SENSOR_HEIGHT - distance
        gallons = water_height * GAL_PER_INCH
	gallons = round(gallons, 2)
        print "Tank Level: ", gallons, " gallons"
        os.system("/usr/bin/mosquitto_pub " +
                        " -h " + MQTT_HOST +
                        " -p " + MQTT_PORT +
                        " -u " + MQTT_USER +
                        " -P " + MQTT_PASS +
                        " -t " + MQTT_TOPIC +
                        " -m " + str(gallons));
        time.sleep(10)

except KeyboardInterrupt:
    GPIO.cleanup()


