#!/usr/bin/env python
#-*- coding: utf-8 -*-
#----------------------------------------------------------------------
# bibliothèques "système"
#----------------------------------------------------------------------
import time
import sys
import smbus2

#----------------------------------------------------------------------
# bibliothèques "locales"
#----------------------------------------------------------------------
import globals
import CRC8

#----------------------------------------------------------------------
# variables et constantes
#----------------------------------------------------------------------
I2C_SHT85 = 0x44

#--------------------------------------------------------------------------------------------------
def SHT85_open() :

	global SHT85_open_flag

	try :
		SHT85_open_flag = False

		if globals.DEBUG_SHT85 :
			print("SHT85_open -> starting...")

		if ( globals.BUS_1_OK_flag ) :
			if SHT85_heater_off() :
				SHT85_open_flag = True
			else :
				if globals.DEBUG_SHT85 :
					print("SHT85_open -> SHT85_heater_off -> erreur !!!")

		else :
			if globals.DEBUG_SHT85:
				print("SHT85_open -> le bus i2c-1 n'est pas OK !!!")

	except :
		if globals.DEBUG_SHT85 :
			print("SHT85_open -> exception !!!")
		
	finally :
		return SHT85_open_flag

#-----------------------------------------------------------------------------
def SHT85_init():
	
	try:
	
		SHT85_init_STATUS = False
		
		if SHT85_open_flag :

			if globals.DEBUG_SHT85:
				print("SHT85_init -> starting...")

			if SHT85_reset():
			
				serial_number = SHT85_serial_number()
				
				if serial_number[0] :
					if globals.DEBUG_SHT85 :
						print('SHT85_init -> serial number = '  + serial_number[1] )

				else :
					if globals.DEBUG_SHT85 :
						print('SHT85_init -> serial number -> erreur !!! ' )

				SHT85_init_STATUS = True
			
			else :
				if globals.DEBUG_SHT85 :
					print('SHT85_init -> reset -> erreur !!! ' )
			
		else :
			if globals.DEBUG_SHT85 :
				print("SHT85_init -> SHT85_open_flag = False !!!")
		
	except :
	
		SHT85_init_STATUS = False
		if globals.DEBUG_SHT85 :
			print("SHT85_init -> exception !!!")

	finally :
		return SHT85_init_STATUS
		
#----------------------------------------------------------------------
# reset : [0x30, 0xA2]
#----------------------------------------------------------------------
def SHT85_reset():
	try:
		SHT85_reset_STATUS = False
		
		globals.bus_1.write_i2c_block_data(I2C_SHT85, 0x30, [0xA2])

		time.sleep(0.002)

		if globals.DEBUG_SHT85:
			if globals.DEBUG_SHT85 :
				print("  SHT85_reset -> OK")
		
		SHT85_reset_STATUS = True
		
	except:
		SHT85_reset_STATUS = False
		if globals.DEBUG_SHT85 :
			print("  SHT85_reset -> exception !")

	finally :
		return SHT85_reset_STATUS
		
#----------------------------------------------------------------------
# heater off : [0x30, 0x66]
#----------------------------------------------------------------------
def SHT85_heater_off():

	SHT85_heater_off_STATUS = False

	try:
		
		globals.bus_1.write_i2c_block_data(I2C_SHT85, 0x30, [0x66])

		time.sleep(0.002)

		if globals.DEBUG_SHT85:
			print("  SHT85_heater_off -> OK")
		
		SHT85_heater_off_STATUS = True
		
	except:
	
		SHT85_heater_off_STATUS = False
		if globals.DEBUG_SHT85 :
			print("  SHT85_heater_off -> exception !")

	finally :
	
		return SHT85_heater_off_STATUS

#----------------------------------------------------------------------
# serial_number : [0x36 0x82]
#----------------------------------------------------------------------
def SHT85_serial_number():

	SHT85_SN_STATUS 		= False
	serial_number_string 	= "0x00000000"

	try :
	
		globals.bus_1.write_i2c_block_data(I2C_SHT85, 0x36, [0x82])
		time.sleep(0.001)
		data = globals.bus_1.read_i2c_block_data(I2C_SHT85, 0x00, 6)
		
		if ( len(data) == 6 ):
		
			data_crc8 = [0,0]
			Flag_crc8 = True
			
			for i in range(2):
				data_crc8[i] = CRC8.crc8_scd30(data[3*i],data[3*i+1])
				
				Flag_crc8 = Flag_crc8 and ( data[3*i+2] == data_crc8[i] )
				
			if Flag_crc8:
				sn = data[0] << 24 | data[1] << 16 | data[3] << 8 | data[4]
				serial_number_string = "0x%08x" % sn
				SHT85_SN_STATUS = True
				 
			else:
				if globals.DEBUG_SHT85:
					print("SHT85_serial_number -> erreur CRC !")
		else:
			if globals.DEBUG_SHT85:
				print("SHT85_serial_number -> erreur nb bytes !")
		
	except :
		SHT85_SN_STATUS = False
		if globals.DEBUG_SHT85 :
			print("  SHT85_serial_number -> exception !")
	
	finally :
		return [SHT85_SN_STATUS, serial_number_string]

#----------------------------------------------------------------------
# stop : [0x30 0x93]
#----------------------------------------------------------------------
def SHT85_stop():

	SHT85_STOP_STATUS = False

	try :
		globals.bus_1.write_i2c_block_data(SHT85_ADDR, 0x30, [0x93])
		time.sleep(0.001)
		SHT85_STOP_STATUS = True
	
	except :
		SHT85_STOP_STATUS = False
		if globals.DEBUG_SHT85 :
			print("  SHT85_stop -> exception !")
	
	finally :
		return SHT85_STOP_STATUS

#----------------------------------------------------------------------
# start one shot : [0x24 0x00] (high repeatability)
#----------------------------------------------------------------------
def SHT85_read():

	chaine_SHT85 = [False, "0.00", "0.00"]
	
	try:

		if True :

			globals.bus_1.write_i2c_block_data(I2C_SHT85, 0x24, [0x00])
			time.sleep(0.020)
			data   = globals.bus_1.read_i2c_block_data(I2C_SHT85, 0x00, 6)

			if ( len(data) == 6 ):
			
				data_crc8 = [0,0]
				Flag_crc8 = True
				
				for i in range(2):
					data_crc8[i] = CRC8.crc8_scd30(data[3*i],data[3*i+1])
					
					Flag_crc8 = Flag_crc8 and ( data[3*i+2] == data_crc8[i] )
					
				if Flag_crc8:
					SHT85_T    = ( -45.0 ) + ( 175.0 / 65535.0 ) * ( float(256*data[0] + data[1]) )
					SHT85_HR   = ( 100.0 / 65535.0) * ( float(256*data[3] + data[4]) )
					
					chaine_SHT85 = [ True ,	"{0:.2f}".format( SHT85_T ), "{0:.2f}".format( SHT85_HR ) ]
					 
				else:
					globals.Flag_mesures_OK = ( globals.Flag_mesures_OK & 0x0FFFFFFFFFFF ) | 0x100000000000
					if globals.DEBUG_SHT85:
						print("SHT85_read -> erreur CRC !")
			else:
				globals.Flag_mesures_OK = ( globals.Flag_mesures_OK & 0x0FFFFFFFFFFF ) | 0x200000000000
				if globals.DEBUG_SHT85:
					print("SHT85_read -> erreur nb bytes !")
		else:
			globals.Flag_mesures_OK = ( globals.Flag_mesures_OK & 0x0FFFFFFFFFFF ) | 0x300000000000
			if globals.DEBUG_SHT85:
				print("SHT85_read -> data not ready !")
			
	except Exception as e:

		globals.Flag_mesures_OK = ( globals.Flag_mesures_OK & 0x0FFFFFFFFFFF ) | 0x400000000000

		exception_type, exception_object, exception_traceback = sys.exc_info()
		line_number = exception_traceback.tb_lineno
		exception_string = "SHT85_read -> exception -> type : " + str(exception_type) + " ; ligne = " + str(line_number)

		if globals.DEBUG_SHT85 :
			print(exception_string)

	finally:
			
		return chaine_SHT85
		
#-----------------------------------------------------------------------------
