import pir2Data
import pir2A
import time, datetime
import smbus
global g_RPiGPIO

g_RPiGPIO="RPi7GPIO"   #change this for gpiozero

if g_RPiGPIO=="RPi.GPIO":  #do NOT change this
    import     RPi.GPIO as GPIO
else:
    import     RPi7GPIO as GPIO
#if end
    
#pir2A.select_RPiGPIO(RPiGPIO)

progName="PiR2_CheckUp_C.py v72"
print("progName:"+progName)
print("by D@CC")
print("on 2024AJan22")
print("used before starting up pir2main.py v70 with Device :60")
print(" on a new micro SD card and/or new electronics.")
print(" uses pir2A.py and ",g_RPiGPIO)
print(" tested ok using,",g_RPiGPIO," on 2024AJan25")
print("Issue 01: RPiGPIO not yet in global")
print("Issue 02: Should time out waiting for Return")
print("Issue 03: Should play a valid TYPING sound")
print("Issue 04: Should WARNING if pushbutton not tested")
print("Issue 05: Should default to using gpiozero (for RPi 5B")
print("Issue 06: Should test to see if special PiR2A pin is grounded, if NOT, offer to Stop")
print("Issue 07: Should test for white LED")
print("Issue 08: Check if Wifi is available.0")
print("Issue 09: Display Pi SN")
print("Issue 10: Identify pin usages")
def unity(func):
    #by D@CC on 2024AJan18
    #Purpose: return "constants" such as GPIO.BCM, GPIO.HIGH etc
    #strReturn=func()
    try:
        strReturn=func()
    except:
        strReturn=True
    finally:
        pass
    #try end
    if strReturn=="GPIO.PUD_UP":
        return strReturn
    #if end
    if strReturn=="GPIO.HIGH": strReturn=func(parm=True)
    if strReturn=="GPIO.LOW" : strReturn=func(parm=False)
    return strReturn
#/unity.py
global g_do0_pin
g_do0_pin=17

global g_ledR_pin
g_ledR_pin=27

global g_diC_pin
g_diC_pin=18

global g_btn_pin
g_btn_pin=22           # GPIO22

print("g_do0_pin",g_do0_pin)
#print("g_di0_pin",g_di0_pin)
print("g_btn_pin",g_btn_pin)
print("g_diC_pin",g_diC_pin)
print("g_ledR_pin",g_ledR_pin)

print("Within 10 seconds, the MehInCharge Clock image ")
print("will be displayed for 3 seconds,")
print("with the PiR2 audio welcome message.")

#Note: the fbi module must be installed for the image to be displayed
pir2A.control_imageTV("PiR2_Clock.jpg", "", 3)   #display for 3 seconds

#based on:
#pir2A.testGPIO(27)

def findNth(targetStr,inStr,n) :
#searches for TargetStr in inStr
#   beginning at position beginN
# finds the nth occurrence
#returns -1 if not found
#
#  WARNING only works for target Strings of length 1
#
    beginN=0
    countDown=n
    posN=beginN      #start searching at column beginN
    while countDown>0:
        countDown=countDown-1

        if posN==-1 :
            return -1
        else:
            #print("countDown",countDown,"colN:",posN)
            posN=inStr.find(targetStr,posN)+1
            #print("  found it in colN:",posN)
        #end if
    #end while
    return posN
#end def

if False :
    testStr="abc,def,ghi,klm"
    posN=findNth(",",testStr,2)
    print("posN:",posN)
    quit()
#end if

pir2A.control_audioTV("PiR2_Welcome.wav")

####################### display Log file ##################

logFileName=pir2A.g_fileArray[1]
print("logFileName:"+logFileName)
#print timeNow
timeNow=time.time()
#print(type(timeNow))

print("Unix timeNow:",timeNow)
ydt=                              \
datetime.datetime.fromtimestamp(  \
    int(timeNow)             \
    ).strftime('%Y-%m-%d %H:%M:%S')
print("Date Now:"+ydt)
#print("opening log file")

logF=open(logFileName,"r")
cntRec=0
maxDisplay=10
tab1="   "
print("first", maxDisplay,"log records are:")

while cntRec <= (maxDisplay-1) :
    cntRec=cntRec+1
    recStr=logF.readline()
    #print("recStr:"+recStr+":")
    if cntRec==1 :
        #print("recStr:"+recStr+":")       
        time0  =findNth(",",recStr,3)
        timeEnd=findNth(",",recStr,4)-1
        #print("FromTo:",time0,timeEnd)
        timeNowStr=recStr[time0:timeEnd]
        #print("timeNowStr:"+timeNowStr+":")
        #timeNow=float(timeNowStr)
        #timeNow=3.4
        #print(type(timeNow))
        #timeNow=recStr[time0,timeEnd]
        #print("time from Log:",timeNowStr)
        ydt=                              \
        datetime.datetime.fromtimestamp(  \
            int(float(timeNowStr))             \
            ).strftime('%Y-%m-%d %H:%M:%S')
        print("logDate:"+ydt)
    #end if


    print(tab1+str(cntRec)+" logRec:",recStr,end='')
#end while

logF.close()

################# end of log print 10 records ########################


############### sortable Date/Time #####################

print()

timeNow=str(time.time())
dateTime=pir2A.sortableDateTime(timeNow)
print("dateTime:"+dateTime)

#################### acquire piIP ############################   
    
pi_IP = pir2A.acquire_piIP()
print("pi_IP:",pi_IP)

#################### blink the redLED ############################


######################## rpiInfo #################################
rpiInfo="not yet in RPi5GPIO"
#rpiInfo=GPIO.RPI_INFO
print("rpiInfo:",rpiInfo)

ledR_pin=27

#a=input("input a before 2nd time")
#print("@182,2nd time")
#pir2A.testGPIO(27)
#print("@184,after 2nd time")

print("reading g_diC_pin (code not tested)")

GPIO.setmode(GPIO.BCM)          #First time
GPIO.setup(g_diC_pin,GPIO.IN)
isDown=GPIO.input(g_diC_pin)
print("g_diC_pin:",isDown)
#GPIO.cleanup()

print("will blink redLED twice")                       #72
# set up HIGH & LOW for this RPi?GPIO
if g_RPiGPIO=="RPi.GPIO":
    HIGH=GPIO.HIGH
    LOW=GPIO.LOW
    print("@199, using GPIO.HIGH for:",g_RPiGPIO)
else:
    HIGH=unity(GPIO.HIGH)
    LOW=unity(GPIO.LOW)
    print("@203, using unit(GPIO.HIGH) for:",g_RPiGPIO)
#if end
if True :
    GPIO.setup(g_ledR_pin,GPIO.OUT)
    testHIGH=unity(GPIO.HIGH)           #72 testHIGH is True for RPi.GPIO
    #                                   #72 testHIGH is ???? for RPi7GPIO
    #print("@209,testHIGH:",testHIGH)

    GPIO.output(g_ledR_pin,HIGH)
    time.sleep(1)
    GPIO.output(g_ledR_pin,LOW)
    time.sleep(1)
    GPIO.output(g_ledR_pin,HIGH)
    time.sleep(1)
    GPIO.output(g_ledR_pin,LOW)
    time.sleep(1)
    #GPIO.cleanup()
#end if
    
if False :
    pir2A.control_redLED(g_ledR_pin,"1")
    time.sleep(1)
    pir2A.control_redLED(g_ledR_pin,"0")
    time.sleep(1)
    pir2A.control_redLED(g_ledR_pin,"1")
    time.sleep(1)
    pir2A.control_redLED(g_ledR_pin,"0")
    time.sleep(1)
#end if
    
print("will blink yelLED twice")                        #72


#GPIO.setmode(GPIO.BCM)   #needed after GPIO.cleanup()  #72
#print("@237, g_do0_pin",g_do0_pin)                            #72
#GPIO.cleanup()
GPIO.setup(g_do0_pin,GPIO.OUT) # removed from next func #72
#print("@240, g_RPiGPIO:",g_RPiGPIO)
#print("@241, g_do0_pin,GPIO.OUT:",g_do0_pin,GPIO.OUT)
#print("@242, after GPIO.setup(g_do0_pin,GPIO.OUT)")
#print("@243, call pir2A.control_digOut0(g_do0_pin,HIGH,HIGH,LOW,g_RPiGPIO)")          #72
pir2A.control_digOut0(g_do0_pin,HIGH,HIGH,LOW,g_RPiGPIO)          #72
time.sleep(1)
#print("@246 call pir2A.control_digOut0(...)")          #72
pir2A.control_digOut0(g_do0_pin,LOW,HIGH,LOW,g_RPiGPIO)           #72
time.sleep(1)
pir2A.control_digOut0(g_do0_pin,HIGH,HIGH,LOW,g_RPiGPIO)          #72
time.sleep(1)
pir2A.control_digOut0(g_do0_pin,LOW,HIGH,LOW,g_RPiGPIO)           #72
time.sleep(1)
#GPIO.cleanup()
print("after blinking yelLED twice")

isDown= 0

#print("testing pushButton on:",g_btn_pin)

if False :
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(g_btn_pin,GPIO.IN)
    isDown=GPIO.input(g_btn_pin)
    print("isDown:",isDown)   #this works on 2021GJul06 for GPIO22
else:
    print("g_btn_pin",g_btn_pin)
    GPIO.setup(g_btn_pin,GPIO.IN)     #72 was in next function
    isDown = pir2A.acquire_pushButton(g_btn_pin)
    print("pushButton:",isDown)
    
    print("Notice that the mp3 will start playing in the background,")
    print("while the prompt message displays (and waits for input).")
    
    pir2A.control_audioTV("typing_3.mp3")  #keyboard sounds to encourage a response.
    
    a=input("while pressing the pushButton, Hit Return (within 10 secs)")
    #time.sleep(1)
    #isDown = 1
    #GPIO.setup(btn_pin,unity(GPIO.IN))     #72 was in next function
    isDown = pir2A.acquire_pushButton(g_btn_pin)
    #GPIO.cleanup()            # allow next routine to define & use GPIO
    print("pushButton is:",isDown)

#end if
################# reading the extTemp00 using I2C ########################

#tempExt=3.14159
#print("                    ambient tempExt:",tempExt)
#pir2A.acquire_tempId00(busA,DEVICE_ADDRESS,unitsStr)
global g_tempId00bus
g_tempId00bus=1
global g_tempId00addr
g_tempId00addr=0x0048
#g_tempId00addr
#print("@292,g_tempId00bus:",hex(g_tempId00bus))
busA=pir2A.init_I2C_Bus(g_tempId00bus)
#print("@294,busA:",busA)
time0=time.time()
dT=int(time.time()-time0)
#print("@297,g_tempId00addr:",hex(g_tempId00addr))
temp=pir2A.acquire_tempId00(busA,g_tempId00addr," C")
print("                    ambient temp:",temp)
print("at ",dT,"temp:",temp)
time.sleep(5)

dT=int(time.time()-time0)
temp=pir2A.acquire_tempId00(busA,g_tempId00addr," C")
print("at ",dT,"temp:",temp)
time.sleep(5)
print()
print("                    turning heat on")
#GPIO.setmode(GPIO.BCM)         # necessary after GPIO.cleanup()
pir2A.control_digOut0(g_do0_pin,HIGH,HIGH,LOW,g_RPiGPIO)

for n in range(3):
    dT=int(time.time()-time0)
    temp=pir2A.acquire_tempId00(busA,g_tempId00addr," C")
    print("at ",dT,"temp:",temp)
    time.sleep(5)
#end for
print("temp should have risen by around .5 degrees")

print("                    turning heat off")
pir2A.control_digOut0(g_do0_pin,LOW,HIGH,LOW,g_RPiGPIO)
for n in range(18):
    dT=int(time.time()-time0)
    temp=pir2A.acquire_tempId00(busA,g_tempId00addr," C")
    print("at ",dT,"temp:",temp)
    time.sleep(5)
#end for
print("                     final temp:,",temp)
print("temp should have returned to normal")

################# sending audio alarm ########################
    
print("end of testing, sound the audio alarm.")
pir2A.control_audioTV("alarm.wav")            # sound the alarm 1st
pir2A.control_audioTV("alarm.wav")            # sound the alarm 2nd time

print("the alarm was sounded!")

print("end of "+progName)

