# Esp32 - PIR alarm excercise
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-09-04  initial release

import	time
from	machine	import Pin
from	drivers	import	Pir, Leds64

# ======================== Btn =========================

class Btn:
    
    def __init__(self, pin_nr=33):
        self.btn = Pin(pin_nr, Pin.IN, Pin.PULL_UP)
        
        
    # return True if button pressed
    def isPressed(self):
        return not self.btn()
    
# ====================== test ==========================

# test used peripherals i.e. Pir, Btn and Leds64
def test():
    pir = Pir()
    btn = Btn()
    leds64 = Leds64(); leds64.on()
    while True:
        print(int(pir.get()), end=' ')
        leds64.write(b'\xFF'*8) if btn.isPressed() else leds64.write(b'\x00'*8)
        time.sleep_ms(200)

# ======================= main =======================

# Alarm  detection. On PIR movement detection set leds64 on, reset by button press
class Main:
    
    def __init__(self):
        self.pir = Pir()
        self.btn = Btn()
        self.leds64 = Leds64(); self.leds64.on()
        self.alarm = False
        print('Alarm activated ...')
        while True:
            self.taskDetect()
            self.taskShowAlarm()
            time.sleep_ms(200)
        
        
    # task handling movement alarms. Call continuously 
    def taskDetect(self):
        if self.btn.isPressed():
            self.alarm = False
            print('\nAlarm reset')
        elif self.pir.get() and not self.alarm:		# display off while button pressed
            self.alarm = True
            print('alarm set', end=' ')


    # lit 64 leds panel when alarm is active. call contnuously
    def taskShowAlarm(self):
        if self.alarm:
            self.leds64.write(b'\xFF'*8)
            print('*', end='')
        else:
            self.leds64.write(b'\x00'*8)


#test()
Main()

# ========================= end =================================
