#!/usr/bin/env python
#version    :       2023.12.31
#language   :       ch
from maix import camera, display, zbar, image
import socket
import os
import sys
sys.path.append('/root/')
import http.client
from CocoPi import BUTTON
import time
import ssl
import os
ScreenOrientation = False
try:
    if os.path.exists("/etc/cameraSize.cfg"):
        cameraSize = True
    else:
        cameraSize = False
except:
    cameraSize = False
def getLcdRotation(cameraCapture):
    global cameraSize
    if cameraSize:
        return lcdRotationNew(cameraCapture)
    else:
        return lcdRotation(cameraCapture)

def lcdRotationNew(inputImg):
    global cameraSize,ScreenOrientation
    imageRotationBuffer = inputImg.crop(0, 0, 320, 240)
    if ScreenOrientation:
        imgRotationAim = image.new(size = (240, 320))
        rotationAngle = 90
        GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
    else:
        imgRotationAim = image.new(size = (320, 240))
        GETROTATION = imageRotationBuffer

    GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
    return GETROTATION

def lcdRotation(inputImg):
    global cameraSize,ScreenOrientation
    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
    if ScreenOrientation:
        imgRotationAim = image.new(size = (240, 320))
        rotationAngle = 180
    else:
        imgRotationAim = image.new(size = (320, 240))
        rotationAngle = 90
    GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
    GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
    return GETROTATION
   
ssl._create_default_https_context = ssl._create_unverified_context

key_A = BUTTON(14)
key_B = BUTTON(8)
key_C = BUTTON(13)
key_D = BUTTON(7)
image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
if cameraSize==True:
    camera.camera.config(size=(320,240))
else:
    camera.camera.config(size=(240,320))

def getPublicIp():
    import requests
    url = 'https://myip.ipip.net'
    res = requests.get(url,verify=False).text.split(" ")
    return res[1][3:]

    

def getNetworkDate_noexit():
    global getDateNum
    try:
        coon = http.client.HTTPConnection('www.baidu.com')
        coon.request("GET","/")
        r = coon.getresponse()
        ts = r.getheader('date')
        GMT_time = time.strptime(ts[5:25],"%d %b %Y %H:%M:%S")
        BeiJing_time = time.localtime(time.mktime(GMT_time) + 8*60*60)
        format_time = time.strftime("%Y-%m-%d %H:%M:%S",BeiJing_time)
        command = "date -s "+"\"{}\"".format(format_time)
        os.system(command)
        getDateNum = 1
        # sys.exit()
    except:
        pass

def getWifiConnectState():
    cmd = "wifi_get_connection_info_test 1"
    res = os.popen(cmd).read()
    wifiInfo = {}
    if res.find('get connection infomation successfully!') != -1:
        wifiInfo["state"]=True
        wifiInfo["AP"] = res[res.find("Connected AP: ")+13:res.find("IP address: ")-1]
        wifiInfo["IP"] = res[res.find("IP address: ")+12:res.find("frequency")-1]
        wifiInfo["frequency"] = res[res.find("frequency: ")+10:res.find("RSSI")-1]
        wifiInfo["RSSI"] = res[res.find("RSSI: ")+6:res.find("link_speed")-1]
        wifiInfo["link_speed"] = res[res.find("link_speed: ")+10:res.find("IP address: ")-1]
        wifiInfo["noise"] = res[res.find("noise: ")+6:res.find("noise: ")+11]
    else:
        wifiInfo["state"]=False
        wifiInfo["AP"] = "N/A"
        wifiInfo["IP"] = "N/A"
        wifiInfo["frequency"] = "N/A"
        wifiInfo["RSSI"] = "N/A"
        wifiInfo["link_speed"] = "N/A"
        wifiInfo["noise"] = "N/A"
    return wifiInfo

def getPrivateIp():
    st = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    try:
        st.connect(("10.255.255.255",1))
        IP = st.getsockname()[0]
    except Exception:
        IP = "127.0.0.1"
    finally:
        st.close()
    return IP

ssidInfo = ""
passwordInfo = ""
checkConnectState = False
connectText = ""
startConnect=False
wifiConnectState = False
# PublicIp=""
PrivateIP=""
runConnectSig=True
connectSuccessSig=False
while True:
    canvas = getLcdRotation(camera.capture())
    IP = getPrivateIp()
    if ssidInfo!="" and passwordInfo!="":
        startConnect=True
        #connectText = "Waitting for Connection..."
        #canvas.draw_string(10,40, ssidInfo+" "+str(len(ssidInfo))+" "+str(type(ssidInfo)), scale = 1.5, color = (0,0,0), thickness = 1)
        canvas.draw_string(10,50, "Connect ...", scale = 1.5, color = (0,0,0), thickness = 1)
        display.show(canvas)
    if startConnect==True:
        canvas_1 = image.new(size = (320, 320), color = (255,255,255), mode = "RGB")
        canvas.draw_image(canvas_1,0,0, alpha=0.4)
        if wifiConnectState == True:
            if key_B.is_pressed():
                while (key_B.is_pressed() == True):
                    time.sleep(0.001)
                startConnect= False
                connectText = ""
                checkConnectState = False
                connectSuccessSig = False
                wifiConnectState = False
                runConnectSig== True
                ssidInfo=""
                passwordInfo=""
            if checkConnectState == True:
                if connectSuccessSig == False:
                    # PublicIp=getPublicIp()
                    PrivateIP=getPrivateIp()
                    connectSuccessSig = True
                connectText = "WiFi Connect Success！"
                # canvas.draw_string(10,80, "路由器公网IP:" + PublicIp, scale = 1.5, color = (0,0,0), thickness = 1)
                canvas.draw_string(10,80, "IP:" + PrivateIP, scale = 1.5, color = (0,0,0), thickness = 1)
                canvas.draw_image((image.open("/root/preset/img/restart_ff0000_24x24.png")).rotate(0, adjust=0),8,216,alpha=1)
                ssidInfo=""
                passwordInfo=""
            else:
                pass
        else:
            if checkConnectState == False:
                os.system("wifi_disconnect_ap_test")
                os.system('wifi_connect_chinese_ap_test '+ssidInfo+' '+passwordInfo+'')
                wifiConnectState=getWifiConnectState()["state"]
                checkConnectState = True
            if checkConnectState == True:
                if key_B.is_pressed():
                    while (key_B.is_pressed() == True):
                        time.sleep(0.001)
                    startConnect= False
                    connectText = ""
                    checkConnectState = False
                    connectSuccessSig = False
                    wifiConnectState = False
                    runConnectSig== True
                    passwordInfo = ""
                    ssidInfo = ""
                else:
                    if runConnectSig== True:
                        connectText = "Connecting..."
                        runConnectSig= False
                    else:
                        passwordInfo = ""
                        ssidInfo = ""
                        connectText = "WIFI Connect Failed!"
                        canvas.draw_image((image.open("/root/preset/img/restart_ff0000_24x24.png")).rotate(0, adjust=0),8,216,alpha=1)
                
        
        canvas.draw_string(10,50, connectText, scale = 1.5, color = (0,0,0) , thickness = 1)
    else:
        mks = canvas.find_qrcodes()
        for mk in mks:
            #外框数据
            X = mk['x']
            Y = mk['y']
            W = mk['w']
            H = mk['h']            
            #二维码信息
            string = mk['payload']
            codeData = string.split(";")
            ssidInfo = codeData[0].split(":")[1]
            passwordInfo = codeData[1].split(":")[1]
            #画外框
            canvas.draw_rectangle(X, Y, X + W, Y + H, color=(0, 0, 255), thickness = 2) 
            #打印信息
            canvas.draw_string(int(X) , int(Y - 45) , "WIFI Name:"+ssidInfo, scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
            canvas.draw_string(int(X) , int(Y - 25) , "PSD:"+passwordInfo, scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
    canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
    #canvas.draw_image((image.open("/root/preset/img/camera_bfbfbf_24x24.png")).rotate(0, adjust=0),292,2,alpha=1)
    display.show(canvas)
    
