#!/usr/bin/env python3
# We want to automatically shut down when the battery voltage is lower than a certain specified value, is it possible?
# Please run the 'python3 /home/pi/x728/x728v2-asd.py &' to get this function

import struct
import smbus
import sys
import time
import RPi.GPIO as GPIO

GPIO_PORT=26
I2C_ADDR=0x36
BUZZER_PIN = 20
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_PORT, GPIO.OUT)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
GPIO.setwarnings(False)

def readVoltage(bus):

     address = I2C_ADDR
     read = bus.read_word_data(address, 2)
     swapped = struct.unpack("<H", struct.pack(">H", read))[0]
     voltage = swapped * 1.25 /1000/16
     return voltage


def readCapacity(bus):

     address = I2C_ADDR
     read = bus.read_word_data(address, 4)
     swapped = struct.unpack("<H", struct.pack(">H", read))[0]
     capacity = swapped/256
     return capacity


bus = smbus.SMBus(1)

try:
  while True:

   print ("******************")
   print(("Voltage:%5.2fV" % readVoltage(bus)))
   print(("Battery:%5i%%" % readCapacity(bus)))

   if readCapacity(bus) == 100:
           print ("Battery FULL")

   if readCapacity(bus) < 20:
           print ("Battery Low")
           GPIO.output(BUZZER_PIN, 1)
           time.sleep(0.3)
           GPIO.output(BUZZER_PIN, 0)
           time.sleep(0.2)
           GPIO.output(BUZZER_PIN, 1)
           time.sleep(0.1)
           GPIO.output(BUZZER_PIN, 0)
           time.sleep(0.2)
           GPIO.output(BUZZER_PIN, 1)
           time.sleep(0.1)
           GPIO.output(BUZZER_PIN, 0)
           time.sleep(0.2)
           GPIO.output(BUZZER_PIN, 1)
           time.sleep(0.3)
           GPIO.output(BUZZER_PIN, 0)
           time.sleep(0.1)

   #Set battery low voltage to shut down
   if readVoltage(bus) < 3.00:
           print ("Battery LOW!!!")
           print ("Shutdown in 10 seconds")
           time.sleep(10)
           GPIO.output(GPIO_PORT, GPIO.HIGH)
           time.sleep(3)
           GPIO.output(GPIO_PORT, GPIO.LOW)

   time.sleep(2)


except KeyboardInterrupt:
    # here you put any code you want to run before the program
    # exits when you press CTRL+C
    print("Exiting") # print value of counter

#except:
#    # this catches ALL other exceptions including errors.
#    # You won't get any error messages for debugging
#    # so only use it once your code is working
#    print("Exiting") # print value of counter

finally:
    GPIO.cleanup() # this ensures a clean exit
    print("Other error or exception occurred!")
