from machine import Pin,I2C,SoftI2C
from time import sleep
from i2c_lcd import I2cLcd
import utime , time
from servo import Servo
import network
from umqtt.simple import MQTTClient
import ujson
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER    = "broker.mqttdashboard.com"
MQTT_USER      = "toan"
MQTT_PASSWORD  = "0811"
MQTT_TOPIC     = "status door lock"
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
  print(".", end="")
  time.sleep(0.1)
print(" Connected!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
#set servo and led 
servo=Servo(pin=26)
led_G = Pin(12,Pin.OUT)
led_R = Pin(14,Pin.OUT)
led_Y = Pin(27,Pin.OUT)
push_button = Pin(2, Pin.IN)  # 23 number pin is input
#set lcd
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 4, 20)
# CONSTANTS
KEY_UP   = const(0)
KEY_DOWN = const(1)
#set Keypad names
keys = [['1', '2', '3', 'A'], 
        ['4', '5', '6', 'B'], 
        ['7', '8', '9', 'C'], 
        ['*', '0', '#', 'D']]
# Pin names for Pico
cols = [5,18,19,23]
rows = [15,4,16,17]
# set pins for rows as outputs
row_pins = [Pin(pin_name, mode=Pin.OUT) for pin_name in rows]
# set pins for cols as inputs
col_pins = [Pin(pin_name, mode=Pin.IN, pull=Pin.PULL_DOWN) for pin_name in cols]
#set init Keypad
def init():
    for row in range(0,4):
        for col in range(0,4):
            row_pins[row].value(0)
#set scan row,col keypad 
def scan(row, col):
    """ scan the keypad """
    # set the current column to high
    row_pins[row].value(1)
    key = None
    # check for keypressed events
    if col_pins[col].value() == KEY_DOWN:
        key = KEY_DOWN
    if col_pins[col].value() == KEY_UP:
        key = KEY_UP
    row_pins[row].value(0)
    # return the key state
    return key
#quet phim
def scankeys():  
    key_press = ''
    for row in range(4):
        for col in range(4):
            key = scan(row, col)
            if key == KEY_DOWN : 
                key_press = keys[row][col]      
    return key_press
#Đúng mật khẩu : 
def True_Pass() :
    global message 
    led_G.value(1)
    servo.move(180) 
    lcd.move_to(4,3),lcd.putstr('Welcome QT7 !')
    message = ujson.dumps({
        "Cửa đang mở"
    })
    print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
    client.publish(MQTT_TOPIC, message)
    sleep(5)
    Default_Screen()
    message = ujson.dumps({
        "Cửa đã đóng"
    })
#Sai mật khẩu :
def Wrong_Pass() :
    global message 
    led_R.value(1)
    lcd.move_to(2,3),lcd.putstr('Wrong password !')
    message = ujson.dumps({
        "Nhập sai mật khẩu"
    })
    sleep(2)
#Nhập mật khẩu :
def Enter_Pass () : 
    global i
    i = i+1
    if(i == 1) :
        enter_pass.append(key)
        lcd.move_to(6,2),lcd.putstr(key)
        sleep(0.3)
        lcd.move_to(6,2),lcd.putstr('*')
    elif(i == 2) :
        enter_pass.append(key)
        lcd.move_to(8,2),lcd.putstr(key)
        sleep(0.3)
        lcd.move_to(8,2),lcd.putstr('*')
    elif(i == 3) :
        enter_pass.append(key)
        lcd.move_to(10,2),lcd.putstr(key)
        sleep(0.3)
        lcd.move_to(10,2),lcd.putstr('*')
    elif(i == 4) : 
        enter_pass.append(key)
        lcd.move_to(12,2),lcd.putstr(key)
        sleep(0.3)
        lcd.move_to(12,2),lcd.putstr('*')
    last_key_press = key
    sleep(0.1)
#Thay đổi mật khẩu :
def Change_Pass () : 
    global correct_pass , enter_pass , message
    correct_pass = enter_pass
    enter_pass = []
    led_Y.value(1)
    lcd.clear(),lcd.putstr('Change Successful !')
    message = ujson.dumps({
        "Đổi mật khẩu thành công"
    })
    sleep(0.1)
#Màn hình mặc định :
def Default_Screen () : 
    servo.move(0)
    led_Y.value(0) , led_R.value(0) , led_G.value(0)
    lcd.clear(), lcd.move_to(0,0), lcd.putstr("Nguyen Quoc Toan")
    lcd.move_to(0,1), lcd.putstr("191413456")
    #Nguyen Quoc Toan - DTCN2 - K60
Default_Screen()
init()
enter_pass = []
correct_pass = ['0','8','1','1']
i = 0
wrong = 0
mode = ''
while True: 
    key = scankeys()
    if key == 'A':
        lcd.clear(), lcd.move_to(0,0)
        lcd.putstr('Enter The Password :')
        mode = 'A'
        enter_pass = [] 
        i = 0
    elif key == 'B':
        lcd.clear(), lcd.move_to(0,0)
        lcd.putstr('Current Password :')
        mode = 'B'
        enter_pass = [] 
        i = 0
    elif key == 'D':
        Default_Screen()
    
    if mode == 'A':
        if key != 'A' and key!= 'B' and key != 'C' and key !='D' and key !='':
            Enter_Pass()
            if key == "#" :
                if enter_pass == correct_pass:
                    True_Pass()
                    wrong = 0
                    mode = ''
                else:
                    wrong = wrong + 1
                    Wrong_Pass()
                    if(wrong >=2) : 
                        lcd.clear()
                        sleep(10)
                        wrong = 0
                    mode= ''
                    Default_Screen()
    elif mode == 'B':
        if key != 'A' and key!= 'B' and key != 'C' and key !='D' and key !='':
            Enter_Pass()
            if key == "#" :
                if enter_pass == correct_pass:
                    lcd.clear(), lcd.move_to(0,0)
                    lcd.putstr('New Password :')
                    mode = 'changepass'
                    enter_pass = []
                    i = 0
                else:
                    Wrong_Pass()
                    mode= ''
                    Default_Screen()
    elif mode == 'changepass':
        if key != 'A' and key!= 'B' and key != 'C' and key !='D' and key !='':
            Enter_Pass()
            if key == "#" :
                Change_Pass()
                sleep(1)
                mode= ''
                Default_Screen()