from machine import Pin,ADC,PWM
import machine
from time import sleep
from ultrasound import HCSR04
import mqtt as mq
import potentiometer as pt 

count_times = 20
interruptCounter = 0


buzzer = PWM(Pin(12,Pin.IN))
buzzer.init(freq=2,duty=0)
Button=Pin(13,Pin.IN)                   #set button pin 
LEDR=Pin(23,Pin.OUT)                    #set red pin 
#LEDW=Pin(22,Pin.OUT)                    #set white pin 
ult = HCSR04(trigPin = 21,echoPin = 19) #set ultrasoun pin 
#pt.pt_print()


def callback(pin):
  global interruptCounter
  interruptCounter = interruptCounter+1
  print("pin change",pin)
  LEDR.value(0)
  buzzer.duty(0)
p2 = Pin(13, Pin.IN, Pin.PULL_UP)
# use its pull up resistor, which will guarantee that it will be in a known state (VCC) when no electrical signal is applied.
p2.irq(trigger= Pin.IRQ_RISING , handler=callback)

def red_light_twink(blinktime,sleeptime):
  for i in range(blinktime):
    LEDR.value(1)
    ledstate = LEDR.value()
    mq.sub(component = "red_led")
    mq.pub(component='red_led',statement=ledstate)
    sleep(sleeptime)
    LEDR.value(0)
    sleep(sleeptime)
    ledstate = LEDR.value()
    mq.sub(component = "red_led")
    mq.pub(component='red_led',statement=ledstate)


t = 1 

while 1:
  mq.client.connect()
  for i in range(count_times):
    mq.client.connect()
    mq.client.check_msg()
    state = machine.disable_irq()
    #time.sleep(0.25)
    machine.enable_irq(state)
    #totalInterruptsCounter = totalInterruptsCounter+1
    print("interruptCounter has occurred:" + str(mq.interruptCounter))
    ledstate = LEDR.value()
    mq.sub(component = "red_led")
    potentiometer_value = pt.potentiometer.read() #reading analog pin
    pt.detect()
    
    print("  red led = ",ledstate)
    mq.pub(component='red_led',statement=ledstate)
    
    print("ultrasound = ",ult.distance())
    mq.pub(component='ultrasound',statement=ult.distance())

    print("potentiometer = ",potentiometer_value) #printing the ADC value
    mq.pub(component='potentiometer',statement=potentiometer_value)
    

    if (250 > ult.distance() and ult.distance() > 100):
      red_light_twink(3,0.16)
      p2.irq(trigger= Pin.IRQ_RISING , handler=callback)
      print("100 ~ 250 red led on")
    elif(99 > ult.distance() and ult.distance() > 50):
      red_light_twink(10,0.05)
      p2.irq(trigger= Pin.IRQ_RISING , handler=callback)
      print("50 ~ 99 red led on")
    elif(50 > ult.distance() and ult.distance() > 2):
      print("2 ~ 50 red led on")
      LEDR.value(1)
      buzzer.freq(1000)
      buzzer.duty(1000)
      mq.sub(component="red_led")
      mq.pub(component='red_led',statement=ledstate)
      
      mq.line()
      p2.irq(trigger= Pin.IRQ_RISING , handler=callback)

      
    print(t,"time")  
    t+=1
    sleep(3)