#! /usr/bin/env python3
#-*- coding: utf-8 -*-
#----------------------------------------------------------------------
# clear && python3 /home/scripts_python/powerdown_soft_shutdown.py
# /home/scripts_shell/powerdown_soft_shutdown.sh
#----------------------------------------------------------------------
#sudo systemctl start   powerdown_soft_shutdown.service
#sudo systemctl stop    powerdown_soft_shutdown.service
#sudo systemctl restart powerdown_soft_shutdown.service
#sudo systemctl status  powerdown_soft_shutdown.service
#----------------------------------------------------------------------

#----------------------------------------------------------------------
# bibliothèques "système"
#----------------------------------------------------------------------
import os
import glob
from   subprocess import *
import time
import serial

import RPi.GPIO as GPIO

#----------------------------------------------------------------------
# constantes & variables
#----------------------------------------------------------------------
BIPS_ON = False
BIPS_ON = True

POWER_DOWN    = 26
BUZZER        = 5
TFT_BACKLIGHT = 18

BIP_ON            = 0.025
BIP_OFF           = 0.045
BIP_ON_POWEROFF   = 0.200
BIP_OFF_POWEROFF  = 0.100

serial_interface = "/dev/ttyAMA0"

#----------------------------------------------------------------------
DEBUG = True
DEBUG = False

#----------------------------------------------------------------------
# 
#----------------------------------------------------------------------
def run_cmd(cmd):
	try :
		p = Popen(cmd, shell = True, stdout = PIPE, stderr = PIPE)
		
		cmd_retour    = p.communicate()[0]
		chaine_retour = cmd_retour.decode()
		
		p.wait()
		
		run_cmd_return_code = p.returncode
		if ( run_cmd_return_code != 0 ) :
			chaine_retour = "NOK!!!"
			
	except :
		chaine_retour = "NOK!!!"
	
	finally :	
		return chaine_retour
						
#----------------------------------------------------------------------
def AQCM_shutdown():
	try:
		
		cmd1 = "sudo poweroff"

		if ( run_cmd(cmd1) != "NOK!!!" ) :
			time.sleep(0.5)
			return True
		else :
			return False

	except:
		return False
		
#----------------------------------------------------------------------
def get_only_IP_MAC():
	try:
		cmd1 = "ip addr show wlan0 | grep inet       | awk '{print $2}'"
		ip_str_0 = run_cmd(cmd1)
		if ( ip_str_0 != "NOK!!!" ) :
			ip_str = ip_str_0[0:ip_str_0.index('/')]
			ip_str = ip_str.strip()
			ip_str = ip_str.replace(" ", "")
		else :
			ip_str = "001.002.003.004"
			
	except:
		ip_str = "004.003.002.001"

	try:
		cmd2 = "ip addr show wlan0 | grep link/ether | awk '{print $2}'"
		cmd2 = "cat /sys/class/net/wlan0/address"
		mac_str_0 = run_cmd(cmd2)
		if ( mac_str_0 != "NOK!!!" ) :
			mac_str = mac_str_0.strip()
			mac_str = mac_str.replace(" ", "")
		else :
			mac_str = "01:02:03:04:05:06"
			
	except:
		mac_str = "06:05:04:03:02:01"

	return [ip_str, mac_str]
	
#----------------------------------------------------------------------
def UART_init() :
	global UART_open_flag
	global UART

	try:
		#---------------------------------------------------------------------
		UART_open_flag = False
		#---------------------------------------------------------------------
		print("  UART_init...")
			
		#---------------------------------------------------------------------
		UART = serial.Serial(
				serial_interface,
				9600,
				bytesize = serial.EIGHTBITS,
				parity = serial.PARITY_NONE,
				stopbits = serial.STOPBITS_ONE,
				timeout = 5.0
			)

		if (UART.isOpen() == True):
			UART.write("\r\n\r\nAQCM05\r\n".encode() )
			#UART.write(b"\xff\x01\x86\x00\x00\x00\x00\x00\x79")
			time.sleep(0.500)
			UART.flushInput()

			time.sleep(1.000)
			
			print("  UART_init : OK !!!")
			UART_open_flag = True

		else :
			print("  UART_init : NOK !!!")

	except:
		print("  UART_init : exception !")
		
	finally :
		print(" ")
		return UART_open_flag

#----------------------------------------------------------------------
def UART_close():
	try:
		if (UART.isOpen() == True):
			UART.close()
		return True
		
	except:
		print("UART_close : exception !")
		return False
		
#----------------------------------------------------------------------



#----------------------------------------------------------------------
# début du code exécutable
#----------------------------------------------------------------------
try:
	print( "powerdown_soft_shutdown : démarrage..." )
	
	GPIO.setmode(GPIO.BCM)
	GPIO.setwarnings(False)
	GPIO.setup(POWER_DOWN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
	GPIO.setup(BUZZER, GPIO.OUT, initial=GPIO.LOW)
	
	compteur_powerdown = 0
	VECTEUR_BP_PBC     = [1,1,1,1,1,1,1,1]	

	while True :
	
		for i in range (0,7):
			VECTEUR_BP_PBC[i] = VECTEUR_BP_PBC[i+1]
		VECTEUR_BP_PBC[7] = GPIO.input(POWER_DOWN)
		
		#print( VECTEUR_BP_PBC )
		#print( compteur_powerdown )
		time.sleep(0.250)

		if ( VECTEUR_BP_PBC == [1,1,1,1,1,1,1,1] ) :

			#----------------------------------------------------------------------

			if ( compteur_powerdown > 0 ) :

				print( "  powerdown_soft_shutdown : avertissement : power is UP !!!" )
				print( " " )

				if BIPS_ON :
					for j in range (0,2):
						GPIO.output(BUZZER, GPIO.HIGH)
						time.sleep(BIP_ON)
						GPIO.output(BUZZER, GPIO.LOW)
						time.sleep(BIP_OFF)

			compteur_powerdown = 0
	
		if ( VECTEUR_BP_PBC == [0,0,0,0,0,0,0,0] ) :
		
			print( "  powerdown_soft_shutdown : avertissement : power is DOWN !!!" )
			print( " " )

			if ( compteur_powerdown == 0 ) :
				if BIPS_ON :
					for j in range (0,3):
						GPIO.output(BUZZER, GPIO.HIGH)
						time.sleep(BIP_ON)
						GPIO.output(BUZZER, GPIO.LOW)
						time.sleep(BIP_OFF)

			VECTEUR_BP_PBC  = [1,1,1,1,1,1,1,0]
			VECTEUR_BP_PBC  = [1,1,1,1,0,0,0,0]
			compteur_powerdown += 1
			
			#----------------------------------------------------------------------
			if ( compteur_powerdown == 1 ) :

				#------------------------------------------------------------------
				print( "  start_beep : identification réseau..." )
				
				try :
					network_config = [ "008.007.006.005", "0C:0B:0A:09:08:07" ]
					network_config = get_only_IP_MAC()
					print( "  " + str(network_config) )

				except:
					print("  start_beep : network_config : exception !")
				
				print( " " )

				chaine_IP  = "IP  = " + network_config[0] + "\r\n"
				chaine_MAC = "MAC = " + network_config[1] + "\r\n"
				
				#------------------------------------------------------------------
				print( "  start_beep : envoi des infos réseau sur UART..." )
				
				try :
					UART_init()		
					print( "  " + chaine_IP )
					UART.write(chaine_IP.encode() )
					print( "  " + chaine_MAC )
					UART.write(chaine_MAC.encode() )
					UART.flushInput()
					print( " " )
					UART_close()
				
				except :
					print( "  UART : exception !!!" )

			#----------------------------------------------------------------------
			if ( compteur_powerdown > 1 ) :
		
				if AQCM_shutdown() :
					GPIO.setup(TFT_BACKLIGHT, GPIO.OUT, initial=GPIO.LOW)
					GPIO.output(TFT_BACKLIGHT, GPIO.LOW)
					print( "  powerdown_soft_shutdown : le raspberry pi s'arrête..." )

					if BIPS_ON :
						for j in range (0,3):
							GPIO.output(BUZZER, GPIO.HIGH)
							time.sleep(BIP_ON_POWEROFF)
							GPIO.output(BUZZER, GPIO.LOW)
							time.sleep(BIP_OFF_POWEROFF)
							
					time.sleep(5.000)

				else :
					print( "  powerdown_soft_shutdown : le raspberry pi ne veut pas s'arrêter !!!" )

					if BIPS_ON :
						for j in range (0,10):
							GPIO.output(BUZZER, GPIO.HIGH)
							time.sleep(BIP_ON)
							GPIO.output(BUZZER, GPIO.LOW)
							time.sleep(BIP_OFF)

		time.sleep(0.100)

except Exception as e0: 
	print("powerdown_soft_shutdown : exception -> " + str(e0) )
	print(" ")
		
finally:
	print("powerdown_soft_shutdown : sortie." )
	print(" ")

#----------------------------------------------------------------------
