#!/usr/bin/env python
#version    :       2023.12.31
#language   :       pi
from maix import image     #引入python模块包
from maix import camera, mjpg, utils, display
import time
import qrcode
import sys
import os
import socket
sys.path.append('/root/')
from CocoPi import BUTTON

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
   
def getWifiConnectState():
    wifiConnectState=False
    cmd = "wifi_get_connection_info_test 1"
    res = os.popen(cmd).read()
    if res.find('get connection infomation successfully!') != -1:
        wifiConnectState = True
    else:
        wifiConnectState = False
    return wifiConnectState

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

image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
PrivateIP=""
canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
canvas.draw_string(8 , 100 , "检查网络连接状态...", scale = 1, color = (255,255,255), thickness = 1)
display.show(canvas)
wirelessTransmitPath=" "

try:
    if getWifiConnectState()==True:
        PrivateIP=getPrivateIp()
        pathHead="http://"
        pathTail=":18811"
        wirelessTransmitPath=pathHead+PrivateIP+pathTail
    else:
        PrivateIP="N/A"
        wirelessTransmitPath="请先连接网络"
except:
    wirelessTransmitPath="请先连接网络"
    pass

os.system("rm /root/user/img/wirelessPictureTransmit.jpg")
qrcode.make(wirelessTransmitPath).save("/root/user/img/wirelessPictureTransmit.jpg")


key_A = BUTTON(14)
key_B = BUTTON(8)
key_C = BUTTON(13)
key_D = BUTTON(7)

buttonState=0
newState=0
oldState=0
def buttonDetect():
    global buttonState,newState,oldState
    newState=key_C.is_pressed()
    if newState == True and oldState == False:
        buttonState=1
    elif newState == False and oldState == True:
        buttonState=2
    else:
        buttonState=0
    oldState=newState

queue = mjpg.Queue(maxsize=8)
mjpg.MjpgServerThread(
    "0.0.0.0", 18811, mjpg.BytesImageHandlerFactory(q=queue)).start()


if cameraSize==True:
    camera.camera.config(size=(320,240))
else:
    camera.camera.config(size=(240,320))
qrShowState=0
while True:
    buttonDetect()
    
    img_backdrop = image.new(size=(320,240),color=(0, 0, 0))    #创建背景画布
    camera_img = getLcdRotation(camera.capture())    #从摄像头中获取一张图像
    camera_img_capture = camera_img.crop(0, 0, 320, 240)        #截取图像
    jpg = utils.rgb2jpg(camera_img.convert("RGB").tobytes(), 320, 240)
    queue.put(mjpg.BytesImage(jpg))
    img_backdrop.draw_image(camera_img)
    if buttonState==2:
        qrShowState=1-qrShowState
    if qrShowState==1:
        img_backdrop.draw_image(image.open("/root/user/img/wirelessPictureTransmit.jpg").resize(260,260), 30, -10,alpha=0.8)
    img_backdrop.draw_image((image.open("/root/preset/img/qrcode_3c83f0_24x24.png")).rotate(0, adjust=0),288,6,alpha=1)
    img_backdrop.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
    display.show(img_backdrop)         #将图像显示出来
