RMaixtr преди 1 година
ревизия
c6f93b8cf1
променени са 56 файла, в които са добавени 5064 реда и са изтрити 0 реда
  1. 998 0
      backup/CocoPi.py
  2. 0 0
      backup/CocoPi_intro_manual.html
  3. 0 0
      backup/CocoPi_intro_manual.pdf
  4. 531 0
      backup/main.py
  5. 60 0
      backup/preset/app/01_camera.py
  6. 93 0
      backup/preset/app/02_photoViewer.py
  7. 35 0
      backup/preset/app/03_colorDetection.py
  8. 123 0
      backup/preset/app/04_recorder.py
  9. 162 0
      backup/preset/app/05_audioPlayer.py
  10. 28 0
      backup/preset/app/06_musicPlayer.py
  11. 37 0
      backup/preset/app/07_videoPlayer.py
  12. 71 0
      backup/preset/app/08_timeCounter.py
  13. 35 0
      backup/preset/app/09_localTimeClock.py
  14. 57 0
      backup/preset/app/10_servoControl.py
  15. 87 0
      backup/preset/app/11_motorControl.py
  16. 32 0
      backup/preset/app/12_pictureLoopPlay.py
  17. 41 0
      backup/preset/app/13_qrCodeScanner.py
  18. 67 0
      backup/preset/app/14_humanDetection.py
  19. 68 0
      backup/preset/app/15_faceDetection.py
  20. 170 0
      backup/preset/app/16_faceComparison.py
  21. 76 0
      backup/preset/app/17_objectRecognition.py
  22. 76 0
      backup/preset/app/18_edgeDetection.py
  23. 72 0
      backup/preset/app/19_handWrittenDigiRecognition.py
  24. 105 0
      backup/preset/app/20_carLicensePlateRecognition.py
  25. 66 0
      backup/preset/app/21_maskDetection.py
  26. 76 0
      backup/preset/app/22_gestureRecognition.py
  27. 71 0
      backup/preset/app/23_fingerGuessing.py
  28. 189 0
      backup/preset/app/24_connectWiFi.py
  29. 220 0
      backup/preset/app/25_aboutCocoPi.py
  30. 101 0
      backup/preset/app/26_internetCamera.py
  31. 70 0
      backup/preset/app/27_internetWeatherPrediction.py
  32. 142 0
      backup/preset/app/28_internetTimeClock.py
  33. 53 0
      backup/preset/app/29_environmentDetection.py
  34. 295 0
      backup/preset/app/30_train_data_collect.py
  35. 269 0
      backup/preset/app/31_train_deploy_model.py
  36. 0 0
      backup/preset/configInfo.json
  37. 26 0
      backup/preset/server/ccrb.crt
  38. 27 0
      backup/preset/server/ccrb.key
  39. 88 0
      backup/preset/server/wirelessServer.py
  40. 8 0
      backup/readme.txt
  41. 0 0
      backup/user/app/.nomedia
  42. 0 0
      backup/user/audio/.nomedia
  43. 0 0
      backup/user/font/.nomedia
  44. 0 0
      backup/user/img/.nomedia
  45. 0 0
      backup/user/text/.nomedia
  46. 1 0
      backup/user/text/owner.txt
  47. 0 0
      backup/user/userInfo.json
  48. 0 0
      backup/user/video/.nomedia
  49. 0 0
      backup/user_latest_code.png
  50. 118 0
      backup/user_latest_code.py
  51. 0 0
      backup/user_latest_code.xml
  52. BIN
      cclb_launch
  53. 2 0
      reload_usb.py
  54. 160 0
      retinaface.py
  55. 12 0
      startup.py
  56. 46 0
      yolo2_20class_awnn.py

+ 998 - 0
backup/CocoPi.py

@@ -0,0 +1,998 @@
+'''
+=========================================================
+    ______                         ______
+   /\  _  \                       /\  _  \  __
+   \ \ \/\_\    ____    ____   ___\ \ \_\ \/\_\
+    \ \ \/_/_  / __ \  / __ \ / __'\ \  __/\/_/_
+     \ \ \_\ \/\ \_\ \/\ \__//\ \_\ \ \ \/   /\ \
+      \ \____/\ \____/\ \____\ \____/\ \_\   \ \_\
+       \/___/  \/___/  \/____/\/___/  \/_/    \/_/
+  __
+ /\ \       __                           ----------------
+ \ \ \     /\_\    ____  __  __  __  _    pi.cocorobo.hk
+  \ \ \    \/_/_ /  _  \/\ \/\ \/\ \/ \  ----------------
+   \ \ \____ /\ \/\ \/\ \ \ \_\ \/>  </   SYSTEM VERSION
+    \ \_____\\ \_\ \_\ \_\ \____//\_/\_\  -- 23.06.01 ---
+     \/_____/ \/_/\/_/\/_/\/___/ \//\/_/ ----------------
+
+=========================================================
+'''
+#########################################################
+# ------------------------------------------------------
+#|          封装包内容:         |        类名称:      |
+#|-------------------------------|----------------------|
+#|  2023.02.16:                  |                      |
+#|  【添加】                     |                      |
+#|  1、AHT20温湿度传感器         |    AHT20             |
+#|  2、MPU6050陀螺仪六轴传感器   |    MPU6050           |  
+#|  3、板载4颗按钮A、B、C、D     |    BUTTON            |
+#|  4、光线强度传感器            |    LIGHTINTENSITY    |
+#|  5、板载LED灯!                |    LED               |
+#|  6、直流电机                  |    DCMOTOR           |
+#|  7、模拟舵机                  |    SERVO             |
+#|------------------------------------------------------|
+#|  2023.02.27:                  |                      |
+#|  【修复完善】                 |    BUTTON、LED       |
+#|  【添加】                     |    WIFI              |
+#|------------------------------------------------------|
+#|  2023.03.09:                 |                      |
+#|  【修复完善】                 |    LED               |
+#|------------------------------------------------------|
+#|  2023.03.14:                  |                      |
+#|  【修复完善】                 |    SERVO             |
+#|-------------------------------------------------------
+#|  2023.06.01:                  |                      |
+#|  【替换】                     |    BUTTON            |
+#|  【替换】                     |    LED               |
+#|  【替换】                     |    DCMOTOR           |
+#|  【替换】                     |    SERVO             |
+#|  【添加】                     |    RGB               |
+#|  【添加】                     |    ADC               |
+#|  【添加】                     |    DAC               |
+#|  【添加】                     |    INPUT             |
+#|  【添加】                     |    OUT               |
+#|  【添加】                     |    UvcVideo          |
+#|-------------------------------------------------------
+#|  2023.06.15:                  |                      |
+#|  【更改】                     |    STM8S             |
+#|-------------------------------------------------------
+#########################################################
+
+from smbus2 import SMBus
+import time
+import math
+from maix import gpio
+import os
+import SUNXI_GPIO
+from maix import camera
+import time
+import sys
+sys.path.append('/root/preset/server')
+
+##################################
+#     1、AHT20温湿度传感器       #
+##################################
+
+AHT20_I2CADDR = 0x38
+AHT20_CMD_SOFTRESET = [0xBA]
+AHT20_CMD_INITIALIZE = [0xBE, 0x08, 0x00]
+AHT20_CMD_MEASURE = [0xAC, 0x33, 0x00]
+AHT20_STATUSBIT_BUSY = 7                    # The 7th bit is the Busy indication bit. 1 = Busy, 0 = not.
+AHT20_STATUSBIT_CALIBRATED = 3              # The 3rd bit is the CAL (calibration) Enable bit. 1 = Calibrated, 0 = not
+
+class AHT20:
+    # Usage: AHT20 crc8 checker. 
+    # A total of 6 * 8 bits data need to check. G(x) = x8 + x5 + x4 + 1 -> 0x131(0x31), Initial value = 0xFF. No XOROUT. 
+    N_DATA = 6
+    # 1 * 8 bits CRC
+    N_CRC = 1
+    # Initial value. Equal to bit negation the first data (status of AHT20)
+    INIT = 0xFF
+    # Useful value to help calculate
+    LAST_8_bit = 0xFF
+    # Devide number retrieve from CRC-8 MAXIM G(x) = x8 + x5 + x4 + 1
+    CRC_DEVIDE_NUMBER = 0x131
+    
+    # I2C communication driver for AHT20, using only smbus2
+    def __init__(self, BusNum=2):
+        # Initialize AHT20
+        self.BusNum = BusNum
+        self.cmd_soft_reset()
+
+        # Check for calibration, if not done then do and wait 10 ms
+        if not self.get_status_calibrated == 1:
+            self.cmd_initialize()
+            while not self.get_status_calibrated() == 1:
+                time.sleep(0.01)
+                
+    def get_normalized_bit(self,value, bit_index):
+        # Return only one bit from value indicated in bit_index
+        return (value >> bit_index) & 1
+        
+    def cmd_soft_reset(self):
+        # Send the command to soft reset
+        with SMBus(self.BusNum) as i2c_bus:
+            i2c_bus.write_i2c_block_data(AHT20_I2CADDR, 0x0, AHT20_CMD_SOFTRESET)
+        time.sleep(0.04)    # Wait 40 ms after poweron
+        return True
+
+    def cmd_initialize(self):
+        # Send the command to initialize (calibrate)
+        with SMBus(self.BusNum) as i2c_bus:
+            i2c_bus.write_i2c_block_data(AHT20_I2CADDR, 0x0 , AHT20_CMD_INITIALIZE)
+        return True
+
+    def cmd_measure(self):
+        # Send the command to measure
+        with SMBus(self.BusNum) as i2c_bus:
+            i2c_bus.write_i2c_block_data(AHT20_I2CADDR, 0, AHT20_CMD_MEASURE)
+        time.sleep(0.08)    # Wait 80 ms after measure
+        return True
+
+    def get_status(self):
+        # Get the full status byte
+        with SMBus(self.BusNum) as i2c_bus:
+            return i2c_bus.read_i2c_block_data(AHT20_I2CADDR, 0x0, 1)[0]
+        return True
+
+    def get_status_calibrated(self):
+        # Get the calibrated bit
+        return self.get_normalized_bit(self.get_status(), AHT20_STATUSBIT_CALIBRATED)
+
+    def get_status_busy(self):
+        # Get the busy bit
+        return self.get_normalized_bit(self.get_status(), AHT20_STATUSBIT_BUSY)
+            
+    def get_measure(self):
+        # Get the full measure
+
+        # Command a measure
+        self.cmd_measure()
+
+        # Check if busy bit = 0, otherwise wait 80 ms and retry
+        while self.get_status_busy() == 1:
+            time.sleep(0.08) # Wait 80 ns
+        
+        # TODO: do CRC check
+
+        # Read data and return it
+        with SMBus(self.BusNum) as i2c_bus:
+            return i2c_bus.read_i2c_block_data(AHT20_I2CADDR, 0x0, 7)
+
+    def mod2_division_8bits(self,a, b, number_of_bytes, init_value):
+        "calculate mod2 division in 8 bits. a mod b. init_value is for crc8 init value."
+        head_of_a = 0x80
+        # Processiong a
+        a = a << 8
+        # Preprocessing head_of_a
+        for i in range(0, number_of_bytes):
+            head_of_a = head_of_a << 8
+            b = b << 8
+            init_value = init_value << 8
+        a = a ^ init_value
+        while (head_of_a > 0x80):
+            # Find a 1
+            if (head_of_a & a):
+                head_of_a = head_of_a >> 1
+                b = b >> 1
+                a = a ^ b
+            else:
+                head_of_a = head_of_a >> 1
+                b = b >> 1
+            # This will show calculate the remainder
+            # print("a:{0}\thead of a:{1}\tb:{2}".format(
+            #     bin(a), bin(head_of_a), bin(b)))
+        return a
+
+    def AHT20_crc8_calculate(self,all_data_int):
+        init_value = INIT
+        # Preprocess all the data and CRCCode from AHT20
+        data_from_AHT20 = 0x00
+        # Preprocessing the first data (status)
+        # print(bin(data_from_AHT20))
+        for i_data in range(0, len(all_data_int)):
+            data_from_AHT20 = (data_from_AHT20 << 8) | all_data_int[i_data]
+        # print(bin(data_from_AHT20))
+        mod_value = self.mod2_division_8bits(
+            data_from_AHT20, CRC_DEVIDE_NUMBER, len(all_data_int), init_value)
+        # print(mod_value)
+        return mod_value
+
+
+    def AHT20_crc8_check(self,all_data_int):
+        """
+        The input data shoule be:
+        Status Humidity0 Humidity1 Humidity2|Temperature0 Temperature1 Temperature2 CRCCode.
+        In python's int64.
+        """
+        mod_value = self.AHT20_crc8_calculate(all_data_int[:-1])
+        if (mod_value == all_data_int[-1]):
+            return True
+        else:
+            return False
+
+    def get_measure_CRC8(self):
+        """
+        This function will calculate crc8 code with G(x) = x8 + x5 + x4 + 1 -> 0x131(0x31), Initial value = 0xFF. No XOROUT.
+        return: all_data (1 bytes status + 2.5 byes humidity + 2.5 bytes temperature + 1 bytes crc8 code), isCRC8_pass
+        """
+        all_data = self.get_measure()
+        isCRC8_pass = self.AHT20_crc8_check(all_data)
+
+        return all_data, isCRC8_pass
+
+    def get_temperature(self):
+        # Get a measure, select proper bytes, return converted data
+        measure = self.get_measure()
+        measure = ((measure[3] & 0xF) << 16) | (measure[4] << 8) | measure[5]
+        measure = measure / (pow(2,20))*200-50
+        return measure
+        
+    def get_temperature_crc8(self):
+        isCRC8Pass = False
+        while (not isCRC8Pass): 
+            measure, isCRC8Pass = self.get_measure_CRC8()
+            time.sleep(80 * 10**-3)
+        measure = ((measure[3] & 0xF) << 16) | (measure[4] << 8) | measure[5]
+        measure = measure / (pow(2,20))*200-50
+        return measure
+
+    def get_humidity(self):
+        # Get a measure, select proper bytes, return converted data
+        measure = self.get_measure()
+        measure = (measure[1] << 12) | (measure[2] << 4) | (measure[3] >> 4)
+        measure = measure * 100 / pow(2,20)
+        return measure
+
+    def get_humidity_crc8(self):
+        isCRC8Pass = False
+        while (not isCRC8Pass): 
+            measure, isCRC8Pass = self.get_measure_CRC8()
+            time.sleep(80 * 10**-3)
+        measure = (measure[1] << 12) | (measure[2] << 4) | (measure[3] >> 4)
+        measure = measure * 100 / pow(2,20)
+        return measure
+
+##################################
+#   2、MPU6050陀螺仪六轴传感器   #
+##################################
+
+SLAVE_ADDR = 0x68
+
+PWR_MGMT_1 = 0x6B
+PWR_MGMT_2 = 0x6C
+WHO_AM_I = 0x75
+
+GYRO_X = 0x43
+GYRO_Y = 0x45
+GYRO_Z = 0x47
+
+ACCL_X = 0x3B
+ACCL_Y = 0x3D
+ACCL_Z = 0x3F
+
+class MPU6050:
+    def __init__(self, BusNum=2):
+        # Initialize mpu6050
+        self.BusNum = BusNum
+        self.cmd_soft_reset()
+        
+    def cmd_soft_reset(self):
+        # Send the command to soft reset
+        with SMBus(self.BusNum) as bus:
+            bus.write_byte_data(SLAVE_ADDR, PWR_MGMT_1, 0)
+        time.sleep(0.04)    # Wait 40 ms after poweron
+
+    def read_byte(self,addr):
+        with SMBus(self.BusNum) as bus:
+            return bus.read_byte_data(SLAVE_ADDR,addr)
+
+    def read_word(self,addr):
+        with SMBus(self.BusNum) as bus:
+            h = bus.read_byte_data(SLAVE_ADDR, addr)
+            l = bus.read_byte_data(SLAVE_ADDR, addr+1)
+        val = (h << 8) + l
+        return val
+
+    def read_word_i2c(self,addr):
+        val = self.read_word(addr)
+        if (val >= 0x8000):
+            return -((65535 - val) + 1)
+        else:
+            return val
+
+    def dist(self,x, y):
+        return math.sqrt((x*x) + (y*y))
+
+    def get_x_rotat(self,x,y, z):
+        rad = math.atan2(y,self.dist(x, z))
+        return math.degrees(rad)
+
+    def get_y_rotat(self,x, y, z):
+        rad = math.atan2(x,self.dist(y, z))
+        return -math.degrees(rad)
+
+    def read_gyro(self):
+        GYR_X = self.read_word_i2c(GYRO_X)
+        GYR_Y = self.read_word_i2c(GYRO_Y)
+        GYR_Z = self.read_word_i2c(GYRO_Z)
+
+        #print ("GYRO -> X:{:04.2f} Y:{:04.2f} Z:{:04.2f}".format((GYR_X/131), (GYR_Y/131), (GYR_Z/131)))
+        return (GYR_X/131), (GYR_Y/131), (GYR_Z/131)
+
+    def read_acc(self):
+        ACC_X = self.read_word_i2c(ACCL_X)
+        ACC_Y = self.read_word_i2c(ACCL_Y)
+        ACC_Z = self.read_word_i2c(ACCL_Z)
+
+        CALC_ACC_X = ACC_X/16384.0
+        CALC_ACC_Y = ACC_Y/16384.0
+        CALC_ACC_Z = ACC_Z/16384.0
+
+        #print ("ACCL -> X:{:04.2f} Y:{:04.2f} Z:{:04.2f}".format(CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z))
+        #print("ROTATE -> X:{:04.2f} Y:{:04.2f}\n".format(get_x_rotat(CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z), get_y_rotat(CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z)))
+        return CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z,self.get_x_rotat(CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z),self.get_y_rotat(CALC_ACC_X, CALC_ACC_Y, CALC_ACC_Z)
+    
+    def get_gyro_x(self):
+        return self.read_gyro()[0]
+    
+    def get_gyro_y(self):
+        return self.read_gyro()[1]
+    
+    def get_gyro_z(self):
+        return self.read_gyro()[2]
+    
+    def get_acc_x(self):
+        return self.read_acc()[0]
+    
+    def get_acc_y(self):
+        return self.read_acc()[1]
+    
+    def get_acc_z(self):
+        return self.read_acc()[2]
+    
+    def get_angle_x(self):
+        return self.read_acc()[3]
+    
+    def get_angle_y(self):
+        return self.read_acc()[4]
+
+'''
+##################################
+#    3、板载4颗按钮A、B、C、D    #
+##################################
+class BUTTON:
+    import os
+    def __init__(self, gpioId):
+        sendMsg_1='echo '
+        sendMsg_2=' > /sys/class/gpio/export'
+        sendMsg_3=' > /sys/class/gpio/unexport'
+        sendMsg_4='echo "in" > /sys/class/gpio/gpio'
+        sendMsg_5='/direction'
+        sendMsg_6='/sys/class/gpio/gpio'
+        sendMsg_7='/value'
+        self.gpio=str(224+gpioId)
+        self.msgStart=sendMsg_1+self.gpio+sendMsg_2
+        self.msgMode=sendMsg_4+self.gpio+sendMsg_5
+        self.msgDel=sendMsg_1+self.gpio+sendMsg_3
+        self.msgGet=sendMsg_6+self.gpio+sendMsg_7
+
+    def is_pressed(self):
+        import os
+        if(os.access(self.msgGet, os.F_OK) is False):
+            os.system(self.msgStart)
+        os.system(self.msgMode)
+        with open(self.msgGet, "rb") as self.file:
+            self.getValue=int(self.file.read())
+        if self.getValue != 1:
+            return True
+        else:
+            return False
+        
+    def __del__(self):
+        os.system(self.msgDel)
+'''
+
+##################################
+#    3、板载4颗按钮A、B、C、D    #
+##################################
+class BUTTON:
+    def __init__(self, gpioId):
+        self.gpio=224+gpioId
+        SUNXI_GPIO.setcfg(self.gpio, SUNXI_GPIO.IN)
+
+    def is_pressed(self):
+        self.getValue=SUNXI_GPIO.input(self.gpio)
+        if self.getValue != 1:
+            return True
+        else:
+            return False
+
+##################################
+#       4、光线强度传感器        #
+##################################
+class LIGHTINTENSITY:
+    def __init__(self, addr=b"0x05070080") -> None:
+        self.addr = addr
+        self.path = "/sys/class/sunxi_dump/dump"
+        self.file = open(self.path, "wb+")
+        self.last = self.value()
+    def value(self):
+        self.file.write(b"0x05070080")
+        self.file.seek(0)
+        return int(self.file.read()[:-1], 16)
+    def __del__(self):
+        try:
+            if self.file:
+                self.file.close()
+                del self.file
+        except Exception as e:
+            pass
+'''
+##################################
+#         5、板载LED灯           #
+##################################
+class LED:
+    import os
+    def __init__(self, gpioId=14):
+        sendMsg_1='echo '
+        sendMsg_2=' > /sys/class/gpio/export'
+        sendMsg_3=' > /sys/class/gpio/unexport'
+        sendMsg_4='echo "out" > /sys/class/gpio/gpio'
+        sendMsg_5='/direction'
+        self.sendMsg_6=' > /sys/class/gpio/gpio'
+        self.sendMsg_7='/value'
+        self.sendMsg_8='echo '
+        self.gpio=str(224+gpioId)
+        self.msgStart=sendMsg_1+self.gpio+sendMsg_2
+        self.msgMode=sendMsg_4+self.gpio+sendMsg_5
+        self.msgDel=sendMsg_1+self.gpio+sendMsg_3
+        self.msgGet=self.sendMsg_6+self.gpio+self.sendMsg_7
+
+    def out(self,value):
+        import os
+        os.system(self.msgStart)
+        os.system(self.msgMode)
+        if value==0 or value==1:
+            self.value=value
+        else:
+            self.value=0
+        self.msgSet=self.sendMsg_8+str(self.value)+self.sendMsg_6+self.gpio+self.sendMsg_7
+        os.system(self.msgSet)
+
+    def __del__(self):
+        os.system(self.msgDel)
+'''
+##################################
+#         5、板载LED灯           #
+##################################
+class LED:
+    def __init__(self, gpioId=69):
+        self.gpioId=gpioId
+        SUNXI_GPIO.setcfg(self.gpioId, SUNXI_GPIO.OUT)
+    def out(self,value):
+        if value==0 or value==1:
+            self.value=1-value
+        else:
+            self.value=0
+        SUNXI_GPIO.output(self.gpioId,self.value)
+        
+'''
+##################################
+#          6、直流电机           #
+##################################
+class DCMOTOR:
+    def __init__(self,dcMotorID="M1"):
+        self.motorId=dcMotorID
+        os.system('i2cset -y 2 0x40 0x00 0x00')         #初始化
+        #设定频率freq=50,预分频prescale=int(25000000.0 / 4096.0 / freq + 0.5)
+        os.system('i2cset -y 2 0x40 0x00 0x10')         #设定pca9685为睡眠模式
+        os.system('i2cset -y 2 0x40 0xfe 0x7a')         #设定预分频
+        os.system('i2cset -y 2 0x40 0x00 0x00')         #重新初始化
+        time.sleep(0.01)
+        os.system('i2cset -y 2 0x40 0x00 0xa1')         #设定pca9685为活跃模式
+        
+    def numberMap(self,value, leftMin, leftMax, rightMin, rightMax):
+        leftSpan = leftMax - leftMin
+        rightSpan = rightMax - rightMin
+        valueScaled = float(value - leftMin) / float(leftSpan)
+        return rightMin + (valueScaled * rightSpan)
+
+    def dcMotorOffRegisterValue(self,dcMotorSetSpeed):
+        dcMotorOffRegister = int(self.numberMap(dcMotorSetSpeed,0,255,0,4095))
+        dcMotorOffRegister_L = hex(dcMotorOffRegister & 0xff)
+        dcMotorOffRegister_H = hex((dcMotorOffRegister >> 8) & 0xff)
+        return dcMotorOffRegister_L, dcMotorOffRegister_H
+    
+    def dcMotorControl(self,dcMotorSetSpeed=0,dcMotorSetRotationDirection=True):
+        if self.motorId=="M1":
+            if dcMotorSetRotationDirection == True:
+                dcMotorOffRegisterValue6_L ='i2cset -y 2 0x40 0x20 '+str(self.dcMotorOffRegisterValue(dcMotorSetSpeed)[0])
+                dcMotorOffRegisterValue6_H ='i2cset -y 2 0x40 0x21 '+str(self.dcMotorOffRegisterValue(dcMotorSetSpeed)[1])
+                os.system('i2cset -y 2 0x40 0x1e 0x00') #设定6通道ON_L为0
+                os.system('i2cset -y 2 0x40 0x1f 0x00') #设定6通道ON_H为0
+                os.system(dcMotorOffRegisterValue6_L)   #设定6通道OFF_L为速度寄存器值低位
+                os.system(dcMotorOffRegisterValue6_H)   #设定6通道OFF_H为速度寄存器值高位
+                os.system('i2cset -y 2 0x40 0x22 0x00') #设定7通道ON_L为0
+                os.system('i2cset -y 2 0x40 0x23 0x00') #设定7通道ON_H为0
+                os.system('i2cset -y 2 0x40 0x24 0x00') #设定7通道OFF_L为0
+                os.system('i2cset -y 2 0x40 0x25 0x00') #设定7通道OFF_H为0
+            elif dcMotorSetRotationDirection == False:
+                dcMotorOffRegisterValue7_L ='i2cset -y 2 0x40 0x24 '+str(self.dcMotorOffRegisterValue(dcMotorSetSpeed)[0])
+                dcMotorOffRegisterValue7_H ='i2cset -y 2 0x40 0x25 '+str(self.dcMotorOffRegisterValue(dcMotorSetSpeed)[1])
+                os.system('i2cset -y 2 0x40 0x1e 0x00') #设定6通道ON_L为0
+                os.system('i2cset -y 2 0x40 0x1f 0x00') #设定6通道ON_H为0
+                os.system('i2cset -y 2 0x40 0x20 0x00') #设定6通道OFF_L为0
+                os.system('i2cset -y 2 0x40 0x21 0x00') #设定6通道OFF_H为0
+                os.system('i2cset -y 2 0x40 0x22 0x00') #设定7通道ON_L为0
+                os.system('i2cset -y 2 0x40 0x23 0x00') #设定7通道ON_H为0
+                os.system(dcMotorOffRegisterValue7_L)   #设定7通道OFF_L为速度寄存器值低位
+                os.system(dcMotorOffRegisterValue7_H)   #设定7通道OFF_H为速度寄存器值高位
+            else:
+                pass
+        elif self.motorId=="M2":
+            if dcMotorSetRotationDirection == True:
+                dcMotorOffRegisterValue9_L ='i2cset -y 2 0x40 0x2c '+str(self.dcMotorOffRegisterValue(dcMotorSetSpeed)[0])
+                dcMotorOffRegisterValue9_H ='i2cset -y 2 0x40 0x2d '+str(self.dcMotorOffRegisterValue(dcMotorSetSpeed)[1])
+                os.system('i2cset -y 2 0x40 0x2a 0x00') #设定9通道ON_L为0
+                os.system('i2cset -y 2 0x40 0x2b 0x00') #设定9通道ON_H为0
+                os.system(dcMotorOffRegisterValue9_L)   #设定9通道OFF_L为速度寄存器值低位
+                os.system(dcMotorOffRegisterValue9_H)   #设定9通道OFF_H为速度寄存器值高位
+                os.system('i2cset -y 2 0x40 0x2e 0x00') #设定10通道ON_L为0
+                os.system('i2cset -y 2 0x40 0x2f 0x00') #设定10通道ON_H为0
+                os.system('i2cset -y 2 0x40 0x30 0x00') #设定10通道OFF_L为0
+                os.system('i2cset -y 2 0x40 0x31 0x00') #设定10通道OFF_H为0
+            elif dcMotorSetRotationDirection == False:
+                dcMotorOffRegisterValue10_L ='i2cset -y 2 0x40 0x30 '+str(self.dcMotorOffRegisterValue(dcMotorSetSpeed)[0])
+                dcMotorOffRegisterValue10_H ='i2cset -y 2 0x40 0x31 '+str(self.dcMotorOffRegisterValue(dcMotorSetSpeed)[1])
+                os.system('i2cset -y 2 0x40 0x2a 0x00') #设定9通道ON_L为0
+                os.system('i2cset -y 2 0x40 0x2b 0x00') #设定9通道ON_H为0
+                os.system('i2cset -y 2 0x40 0x2c 0x00') #设定9通道OFF_L为0
+                os.system('i2cset -y 2 0x40 0x2d 0x00') #设定9通道OFF_H为0
+                os.system('i2cset -y 2 0x40 0x2e 0x00') #设定10通道ON_L为0
+                os.system('i2cset -y 2 0x40 0x2f 0x00') #设定10通道ON_H为0
+                os.system(dcMotorOffRegisterValue10_L)  #设定10通道OFF_L为速度寄存器值低位
+                os.system(dcMotorOffRegisterValue10_H)  #设定10通道OFF_H为速度寄存器值高位
+            else:
+                pass
+        else:
+            pass
+
+    def __del__(self):
+        if self.motorId=="M1":
+            os.system('i2cset -y 2 0x40 0x1e 0x00') #设定6通道ON_L为0
+            os.system('i2cset -y 2 0x40 0x1f 0x00') #设定6通道ON_H为0
+            os.system('i2cset -y 2 0x40 0x20 0x00') #设定6通道OFF_L为0
+            os.system('i2cset -y 2 0x40 0x21 0x00') #设定6通道OFF_H为0
+            os.system('i2cset -y 2 0x40 0x22 0x00') #设定7通道ON_L为0
+            os.system('i2cset -y 2 0x40 0x23 0x00') #设定7通道ON_H为0
+            os.system('i2cset -y 2 0x40 0x24 0x00') #设定7通道OFF_L为0
+            os.system('i2cset -y 2 0x40 0x25 0x00') #设定7通道OFF_H为0
+        elif self.motorId=="M2":
+            os.system('i2cset -y 2 0x40 0x2a 0x00') #设定9通道ON_L为0
+            os.system('i2cset -y 2 0x40 0x2b 0x00') #设定9通道ON_H为0
+            os.system('i2cset -y 2 0x40 0x2c 0x00') #设定9通道OFF_L为0
+            os.system('i2cset -y 2 0x40 0x2d 0x00') #设定9通道OFF_H为0
+            os.system('i2cset -y 2 0x40 0x2e 0x00') #设定10通道ON_L为0
+            os.system('i2cset -y 2 0x40 0x2f 0x00') #设定10通道ON_H为0
+            os.system('i2cset -y 2 0x40 0x30 0x00') #设定10通道OFF_H为0
+            os.system('i2cset -y 2 0x40 0x31 0x00') #设定10通道OFF_L为0
+        else:
+            pass
+'''
+
+'''
+##################################
+#          7、模拟舵机           #
+##################################
+class SERVO:
+    def __init__(self,servoID="S1"):
+        self.servoId=servoID
+        os.system('i2cset -y 2 0x40 0x00 0x00')     #初始化
+        #设定频率freq=50,预分频prescale=int(25000000.0 / 4096.0 / freq + 0.5)
+        os.system('i2cset -y 2 0x40 0x00 0x10')     #设定pca9685为睡眠模式
+        os.system('i2cset -y 2 0x40 0xfe 0x7a')     #设定预分频
+        os.system('i2cset -y 2 0x40 0x00 0x00')     #重新初始化
+        time.sleep(0.01)
+        os.system('i2cset -y 2 0x40 0x00 0xa1')     #设定pca9685为活跃模式
+
+    def servoOffRegisterValue(self,servoSetDegree):
+        servoPwmus = (servoSetDegree * 2000 / 180 + 500)    # 0.6 ~ 2.4——【2023.03.14更改:0.5~2.5】
+        servoOffRegister = int(servoPwmus * 4096 / 20000)
+        servoOffRegister_L = hex(servoOffRegister & 0xff)
+        servoOffRegister_H = hex((servoOffRegister >> 8) & 0xff)
+        return servoOffRegister_L, servoOffRegister_H
+
+    def servoControl(self,servoSetDegree=0):
+        if self.servoId=="S1":
+            servoOffRegisterCmd5_L ="i2cset -y 2 0x40 0x1c "+str(self.servoOffRegisterValue(servoSetDegree)[0])
+            servoOffRegisterCmd5_H ="i2cset -y 2 0x40 0x1d "+str(self.servoOffRegisterValue(servoSetDegree)[1])
+            os.system('i2cset -y 2 0x40 0x1a 0x00') #设定5通道ON_L为0
+            os.system('i2cset -y 2 0x40 0x1b 0x00') #设定5通道ON_H为0
+            os.system(servoOffRegisterCmd5_L)       #设定5通道OFF_L为
+            os.system(servoOffRegisterCmd5_H)       #设定5通道OFF_H为
+        elif self.servoId=="S2":
+            servoOffRegisterCmd11_L ="i2cset -y 2 0x40 0x34 "+str(self.servoOffRegisterValue(servoSetDegree)[0])
+            servoOffRegisterCmd11_H ="i2cset -y 2 0x40 0x35 "+str(self.servoOffRegisterValue(servoSetDegree)[1])
+            os.system('i2cset -y 2 0x40 0x32 0x00') #设定11通道ON_L为0
+            os.system('i2cset -y 2 0x40 0x33 0x00') #设定11通道ON_H为0
+            os.system(servoOffRegisterCmd11_L)      #设定11通道OFF_L为
+            os.system(servoOffRegisterCmd11_H)      #设定11通道OFF_H为
+        else:
+            pass
+
+    def __del__(self):
+        time.sleep(0.01)
+'''        
+
+##################################
+#          7、QMI8658            #
+##################################
+class QMI8658(object):
+    def __init__(self, smbus=2, address=0X6B):
+        self._address = address
+        import smbus2
+        self._bus = smbus2.SMBus(smbus)
+        bRet = self.WhoAmI()
+        if bRet:
+            self.Read_Revision()
+        else:
+            return None
+        self.Config_apply()
+
+    def _read_byte(self, cmd):
+        rec = self._bus.read_i2c_block_data(int(self._address), int(cmd), 1)
+        return rec[0]
+
+    def _read_block(self, reg, length=1):
+        rec = self._bus.read_i2c_block_data(int(self._address), int(reg), length)
+        return rec
+
+    def _read_u16(self, cmd):
+        LSB = self._bus.read_i2c_block_data(int(self._address), int(cmd), 1)
+        MSB = self._bus.read_i2c_block_data(int(self._address), int(cmd)+1, 1)
+        return (MSB[0] << 8) + LSB[0]
+
+    def _write_byte(self, cmd, val):
+        self._bus.write_i2c_block_data(int(self._address), int(cmd), bytes([int(val)]))
+
+    def WhoAmI(self):
+        bRet = False
+        if (0x05) == self._read_byte(0x00):
+            bRet = True
+        return bRet
+
+    def Read_Revision(self):
+        return self._read_byte(0x01)
+
+    def Config_apply(self):
+        # REG CTRL1
+        self._write_byte(0x02, 0x60)
+        # REG CTRL2 : QMI8658AccRange_8g  and QMI8658AccOdr_1000Hz
+        self._write_byte(0x03, 0x23)
+        # REG CTRL3 : QMI8658GyrRange_512dps and QMI8658GyrOdr_1000Hz
+        self._write_byte(0x04, 0x53)
+        # REG CTRL4 : No
+        self._write_byte(0x05, 0x00)
+        # REG CTRL5 : Enable Gyroscope And Accelerometer Low-Pass Filter
+        self._write_byte(0x06, 0x11)
+        # REG CTRL6 : Disables Motion on Demand.
+        self._write_byte(0x07, 0x00)
+        # REG CTRL7 : Enable Gyroscope And Accelerometer
+        self._write_byte(0x08, 0x03)
+
+    def Read_Raw_XYZ(self):
+        xyz = [0, 0, 0, 0, 0, 0]
+        raw_timestamp = self._read_block(0x30, 3)
+        raw_acc_xyz = self._read_block(0x35, 6)
+        raw_gyro_xyz = self._read_block(0x3b, 6)
+        raw_xyz = self._read_block(0x35, 12)
+        timestamp = (raw_timestamp[2] << 16) | (
+            raw_timestamp[1] << 8) | (raw_timestamp[0])
+        for i in range(6):
+            # xyz[i]=(raw_acc_xyz[(i*2)+1]<<8)|(raw_acc_xyz[i*2])
+            # xyz[i+3]=(raw_gyro_xyz[((i+3)*2)+1]<<8)|(raw_gyro_xyz[(i+3)*2])
+            xyz[i] = (raw_xyz[(i*2)+1] << 8) | (raw_xyz[i*2])
+            if xyz[i] >= 32767:
+                xyz[i] = xyz[i]-65535
+        return xyz
+
+    def Read_XYZ(self):
+        xyz = [0, 0, 0, 0, 0, 0]
+        raw_xyz = self.Read_Raw_XYZ()
+        #QMI8658AccRange_8g
+        acc_lsb_div = (1 << 12)
+        #QMI8658GyrRange_512dps
+        gyro_lsb_div = 64
+        for i in range(3):
+            xyz[i] = raw_xyz[i]/acc_lsb_div  # (acc_lsb_div/1000.0)
+            xyz[i+3] = raw_xyz[i+3]*1.0/gyro_lsb_div
+        return xyz
+        
+import smbus2
+import time
+
+class stm8s(object):
+
+    bus = smbus2.SMBus(2) # 2 indicates /dev/i2c-2
+    address = 0x50
+
+    # 0x00 # 触发配置
+    # 0x01 # 重置配置
+    # 0x02 # pwm0 历史配置
+    # 0x03 # pwm1 历史配置
+
+    # 引脚配置模式有 1. pwm 2. gpio ouput gpio input 3. adc 4.ws2812_singe 5 ws2812_multi
+    def __init__(self):
+        self.reset()
+        time.sleep(0.05)
+        pass
+    
+    def clear(self):
+        self.write(1, 1)
+        self.reset()
+        time.sleep(0.05)
+    
+    def write(self, addr, val):
+        for i in range(0, 3):
+            try:
+                self.bus.write_byte_data(self.address, addr, val)
+                time.sleep(0.001) # 1ms
+                # print(addr, val) # debug
+                return True
+            except Exception:
+                time.sleep(0.01)
+                continue
+        return False
+
+    def read(self, addr):
+        for i in range(0, 3):
+            try:
+                tmp = self.bus.read_byte_data(self.address, addr)
+                time.sleep(0.001) # 1ms
+                # print(addr, tmp) # debug
+                return tmp
+            except Exception:
+                time.sleep(0.01)
+                continue
+        return None
+
+    def reset(self):
+        self.write(0, 1)
+        time.sleep(0.05) # 重启并配置需要时间
+
+    def dump(self):
+        for i in range(0, 32):
+            print(i, self.read(i))
+
+class singleRgb(stm8s):
+    def __init__(self):
+        self.valR=0
+        self.valG=0
+        self.valB=0
+        self.brightness=255
+        self.show()
+    
+    def setColor(self,r,g,b):
+        if(r>=0 and r<=255):
+            self.valR=int(r*self.brightness/255)
+        else:
+            self.valR=0
+        if(g>=0 and g<=255):
+            self.valG=int(g*self.brightness/255)
+        else:
+            self.valG=0
+        if(b>=0 and b<=255):
+            self.valB=int(b*self.brightness/255)
+        else:
+            self.valB=0
+            
+    def setBrightness(self,brightness):
+        if(brightness>=0 and brightness<=255):
+            self.brightness=brightness
+        else:
+            self.brightness=0
+    
+    def show(self):
+        self.write(31, self.valB)
+        self.write(30, self.valG)
+        self.write(29, self.valR)
+        self.write(28, 6)
+
+class dcMotor(stm8s):
+    def __init__(self,id):
+        self.id=id
+
+    def m1a(self,val=0):
+        self.write(4,5)    #M1A
+        self.write(5,0)
+        self.write(6,0)
+        self.write(7,val)
+        
+    def m1b(self,val=0):
+        self.write(8,5)    #M1B
+        self.write(9,0)
+        self.write(10,0)
+        self.write(11,val)
+        
+    def m2a(self,val=0):
+        self.write(12,5)    #M2A
+        self.write(13,0)
+        self.write(14,0)
+        self.write(15,val)
+        
+    def m2b(self,val=0):
+        self.write(16,5)    #M2B
+        self.write(17,0)
+        self.write(18,0)
+        self.write(19,val)
+        
+    def dcMotorCtrl(self,dir,speed):
+        if(0<=speed and speed<=255):
+            if(self.id ==1):                #Motor1
+                if(dir==0):
+                    self.m1a(speed)
+                    self.m1b(0)
+                else:
+                    self.m1a(255-speed)
+                    self.m1b(1)
+            elif(self.id ==2):
+                if(dir==0):
+                    self.m2a(speed)
+                    self.m2b(0)
+                else:
+                    self.m2a(255-speed)
+                    self.m2b(1)
+        else:
+            pass
+            
+class multiFuncGpio(stm8s):
+    def __init__(self,id=0,mode=0):
+        self.id=id
+        self.rgbId=0
+        self.brightness=255
+        self.mode=mode
+        self.write(20+self.id*4,self.mode)
+        self.reset()
+        time.sleep(0.05)
+    ##################################################
+    # mode |  0  |  1  |  2  |  3  |  4  |  5  |  6  |      
+    #-------------------------------------------------
+    # Func |free |servo|INPUT| OUT | ADC | PWM | BEEP|
+    ##################################################
+    # mode=0,为空闲状态,引脚不执行任何功能
+    # mode=1,为控制舵机模式,值控制范围为0°~180°
+    # mode=2,为数字输入模式,返回值0或1
+    # mode=3,为数字输出模式,输出值为0或1
+    # mode=4,为ADC采样模式,返回值为0~1023
+    # mode=5,为PWM输出模式,输出值范围为0~255
+    # mode=6,为控制蜂鸣器模式,控制范围为20hz~12000hz
+    # mode=7,为控制灯带模式,暂未实现
+    # id=0,控制多功能引脚1,向20号寄存器写入模式数据
+    # id=1,控制多功能引脚2,向24号寄存器写入模式数据
+    
+    def servoCtrl(self,angle):
+        if ((angle>=0) and (angle<=180)):
+            self.write(23+self.id*4,angle)
+        else:
+            pass
+            
+    def digitalRead(self):
+        try:
+            self.gpioVal= self.read(23+ self.id*4)
+            if(self.gpioVal != None):
+                return 1-self.gpioVal
+        except:
+            print("ERROR 233")
+    
+    def digitalWrite(self,val):
+        if ((val>=0) and (val<=1)):
+            self.write(23+self.id*4,val)
+        else:
+            pass
+            
+    def analogRead(self):
+        try:
+            self.adcValH= self.read(22+ self.id*4)
+            self.adcValL= self.read(23+ self.id*4)
+            if (self.adcValH != None and self.adcValL != None):
+            # adcValH adcValL 大小端合并 16bit
+                self.adcVal = self.adcValL + (self.adcValH << 8)
+                return self.adcVal
+        except:
+            print("ERROR 2333")
+        
+    def analogWrite(self,val):
+        if ((val>=0) and (val<=255)):
+            self.write(23+self.id*4,val)
+        else:
+            pass
+            
+    
+    def beep(self,frequency):
+        if ((val>=20) and (val<=12000)):
+            self.write(22+self.id*4,val>>8)
+            self.write(23+self.id*4,val&0b11111111)
+        else:
+            pass
+        
+    def pixelInit_(self):
+        for i in range(16):
+            self.setPixelColor(i,0,0,0)
+            self.pixelShow()
+    
+    def setBrightness(self,brightness):
+        if(brightness>=0 and brightness<=255):
+            self.brightness=brightness
+        else:
+            self.brightness=0
+    
+    def setPixelColor(self,rgbId,r,g,b):
+        if(rgbId >=0 and rgbId <=15):
+            self.rgbId=rgbId    #rgbId范围:0~15
+        else:
+            self.rgbId=0
+        if(r>=0 and r<=255):
+            self.valR=int(r*self.brightness/255)
+        else:
+            self.valR=0
+        if(g>=0 and g<=255):
+            self.valG=int(g*self.brightness/255)
+        else:
+            self.valG=0
+        if(b>=0 and b<=255):
+            self.valB=int(b*self.brightness/255)
+        else:
+            self.valB=0
+    
+    #self.id的值为0或1,用于控制灯带缓冲区(S1或者S2引脚)
+    def pixelShow(self):
+        self.write(32+ self.id*48+self.rgbId*3, self.valR)    
+        self.write(33+ self.id*48+self.rgbId*3, self.valG)
+        self.write(34+ self.id*48+self.rgbId*3, self.valB)
+        
+
+class UvcVideo(camera.MaixVideo):
+
+    def __init__(self, source="/dev/videoX"):
+        self.source = source
+        super(UvcVideo, self).__init__()
+        import os, time
+        usb_path = '/sys/devices/platform/soc/usbc0/otg_role'
+        # 确认 usb_path 内容为 usb_host 如果不是,自动设置为 usb_host
+        if os.popen('cat %s' % usb_path).read().strip() != 'usb_host':
+            os.system('echo "usb_host" > %s' % usb_path)
+            time.sleep(2) # 要设置 2s 左右才能初始化工作,否则会报 VIDIOC_S_FMT 失败。
+
+    def config(self, size=None, video=2, horizontal=0, vertical=0):
+        if size == None:
+            size = (320, 240)
+        super(UvcVideo, self).config(size)
+        print('[camera] config input size(%d, %d, %d)' %
+            (self.width(), self.height(), video))
+        if self.cam:
+            self.cam = None
+        try:
+            import _coco_camera
+            self.cam = _coco_camera.Camera(self.width(), self.height(), video, horizontal, vertical)
+        except Exception as e:
+            print(e)
+            self.cam = None
+
+    def read(self):
+        if self.cam == None:
+            self.config()
+        if self.cam:
+            ret, frame = self.cam.read()
+            if ret:
+                return frame  # bytes
+            else:
+                try:
+                    self.config()
+                except Exception as e:
+                    print(e)
+        return None
+
+    def __del__(self):
+        if self.cam:
+            self.cam = None

+ 0 - 0
backup/CocoPi_intro_manual.html


+ 0 - 0
backup/CocoPi_intro_manual.pdf


+ 531 - 0
backup/main.py

@@ -0,0 +1,531 @@
+#!/usr/bin/env python
+#version    :       2023.06.15
+#language   :       ch
+#hardware   :       pi
+
+import time
+from maix import *
+import gc
+import os,sys
+import sys
+sys.path.append('/root/')
+from CocoPi import BUTTON
+from CocoPi import stm8s
+from CocoPi import multiFuncGpio
+
+gc.enable()
+gc.collect()
+iic_slaver=stm8s()
+iic_slaver.clear()
+PIXEL_LED1= multiFuncGpio(0,7)
+PIXEL_LED2= multiFuncGpio(1,7)
+PIXEL_LED1.pixelInit_()
+PIXEL_LED2.pixelInit_()
+time.sleep(0.01)
+del iic_slaver
+del PIXEL_LED1
+del PIXEL_LED2
+
+count = 0
+
+def gc_log():
+    global count
+    gc.collect()
+    count = count + 1
+
+splash_theme_color = (15,21,46)
+btn_selected = (255,255,255)
+btn_unselected = (76,86,127)
+txt_selected = (255,255,255)
+txt_unselected = (76,86,127)
+color_splash_theme = (15,21,46)
+color_blue = (31,61,185)
+color_blue_lighter = (60,131,211)
+color_white = (255,255,255)
+color_gray = (60,73,126)
+color_orange = (255,165,0)
+color_red = (255,0,0)
+
+
+btn_width = 134
+btn_height = 52
+btn_y_base = 5
+btn_col = (btn_y_base, btn_y_base+btn_width, btn_y_base+152)
+btn_row = 180
+
+main_title = (
+        "运行",
+        "上次程序",
+        "打开",
+        "样例菜单",
+        "B",
+        "A"
+    )
+splash_text = (
+        "系统版本: 2023-06-15 ",
+        "System version: N/A",
+        "2. 加载程序后,按下A键两秒退出程序界面.",
+        "    ",
+        "    ",
+        "启动上次程序中...",
+        "错误: 未找到程序...",
+        "错误: 语法有误",
+        "正在打开样例菜单...",
+        "未找到样例菜单.",
+        "运行",
+        "加载...",
+        "返回",
+        "按下C键返回主界面",
+        "按下D键重启",
+        "按下B键关机",
+        "1. 按下A键七秒来关闭或者重启CocoPi系统.",
+        "    ",
+        "    ",
+        "CocoPi V6",
+        "/ Linux / AIot /Python /",
+        "/Graphical programming /",
+        "------------- 基础 --------------",
+        "----------- 人工智能 ----------",
+        "------------ 物联网 ------------",
+    )
+
+title_logo_text = image.open("/root/preset/img/cocorobo_text.jpg")
+iconUpNp = image.open("/root/preset/img/arrow_up_filled.jpg")
+iconUpP = image.open("/root/preset/img/arrow_up_pressed.jpg")
+iconDownNp = image.open("/root/preset/img/arrow_down_filled.jpg")
+iconDownP = image.open("/root/preset/img/arrow_down_pressed.jpg")
+frostedGlass = image.open("/root/preset/img/frostedglass_.jpg")
+#backUp = image.open("/root/preset/img/backup_48x48.png")
+#powerOff = image.open("/root/preset/img/poweroff_48x48.png")
+#reBoot = image.open("/root/preset/img/reboot_48x48.png")
+
+run_user_code_path='/root/user_latest_code.py'
+run_try_demo_path='/root/play_music.py'
+
+
+key_A = BUTTON(14)
+key_B = BUTTON(8)
+key_C = BUTTON(13)
+key_D = BUTTON(7)
+
+splash = image.new(size=(320, 240),mode = "RGB")
+img_drop=image.new(size=(320,240),mode="RGB")
+
+demo_i=0
+demo_j=0
+demo_m=0
+demo_n=0
+pressTime=0
+systemRunNum=0
+
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+def screenFirstPage():
+    from maix import display,image,camera
+    global splash,title_logo_text,btn_col,btn_row,splash_text,txt_unselected,txt_selected,btn_selected,btn_unselected,\
+splash_theme_color,btn_height,btn_width,main_title,menuSelect,gc_log,demo_i,demo_j,demo_m,demo_n,screenShow,img_drop,\
+frostedGlass
+    gc_log()
+    image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+    splash.clear()
+    splash.draw_rectangle(0,0,320,320,color=splash_theme_color,thickness=-1)
+    splash.draw_image(title_logo_text, btn_col[0]+16, 10)
+    x, y = image.get_string_size(splash_text[0], 1)
+
+    splash.draw_string(btn_col[0]+16, 40, splash_text[19]+"  "+splash_text[0], color=(0,255,255), thickness = 1)
+#    splash.draw_string(btn_col[0], 60, splash_text[20], color=(0,255,255), thickness = 1)
+#    splash.draw_string(btn_col[0], 80, splash_text[21], color=(0,255,255), thickness = 1)
+#    splash.draw_string(btn_col[0], 60, splash_text[0], color=(0,255,255), thickness = 1)
+    splash.draw_string(btn_col[0]+16, btn_row-105, splash_text[16], color=txt_unselected, thickness = 1)
+    splash.draw_string(btn_col[0]+16, btn_row-85, splash_text[17], color=txt_unselected, thickness = 1)
+    #splash.draw_string(btn_col[0], btn_row-105, splash_text[18], color=txt_unselected, thickness = 1)
+    splash.draw_string(btn_col[0]+16, btn_row-65, splash_text[2], color=txt_unselected, thickness = 1)
+    splash.draw_string(btn_col[0]+16, btn_row-45, splash_text[3], color=txt_unselected, thickness = 1)
+    splash.draw_string(btn_col[0]+16, btn_row-25, splash_text[4], color=txt_unselected, thickness = 1)
+
+    if menuSelect==0:
+        splash.draw_rectangle(btn_col[1]+40, btn_row, btn_col[1]+btn_width+42, btn_row+btn_height, color=btn_selected, thickness=1)
+        splash.draw_string(btn_col[1]+52, btn_row+7, main_title[2], color=txt_selected, thickness = 1)
+        splash.draw_string(btn_col[1]+52, btn_row+27, main_title[3], color=txt_selected, thickness = 1)
+        splash.draw_string(btn_col[1]+157, btn_row+27, main_title[5], color=txt_unselected, thickness = 1)
+
+        splash.draw_rectangle(btn_col[0], btn_row, btn_col[0]+btn_width, btn_row+btn_height, color=btn_selected, thickness=1)
+        splash.draw_string(btn_col[0]+96, btn_row+7, main_title[0], color=txt_selected, thickness = 1)
+        splash.draw_string(btn_col[0]+68, btn_row+27, main_title[1], color=txt_selected, thickness = 1)
+        splash.draw_string(btn_col[0]+7, btn_row+27, main_title[4], color=txt_unselected, thickness = 1)
+
+    if menuSelect==1:
+        splash.draw_rectangle(btn_col[0], btn_row, btn_col[0]+btn_width, btn_row+btn_height, color=btn_unselected, thickness=1)
+        splash.draw_string(btn_col[0]+7, btn_row+7, main_title[0], color=txt_unselected, thickness = 1)
+        splash.draw_string(btn_col[0]+7, btn_row+27, main_title[1], color=txt_unselected, thickness = 1)
+
+        splash.draw_rectangle(btn_col[1], btn_row, btn_col[1]+btn_width, btn_row+btn_height, color=btn_selected, thickness=1)
+        splash.draw_string(btn_col[1]+7, btn_row+7, main_title[2], color=txt_selected, thickness = 1)
+        splash.draw_string(btn_col[1]+7, btn_row+27, main_title[3], color=txt_selected, thickness = 1)
+
+    splash.draw_image(frostedGlass, 0, 0,alpha=0.2)
+    #screenShow()
+    display.show(splash)
+
+def screenSecondPage():
+    from maix import display, image,camera
+    global splash,title_logo_text,btn_col,btn_row,splash_text,txt_unselected,txt_selected,btn_selected,btn_unselected,\
+splash_theme_color,btn_height,btn_width,main_title,demoSelect,gc_log,color_splash_theme,color_blue,color_blue_lighter,\
+color_white,color_gray,color_orange,color_red,iconUpNp,iconUpP,iconDownNp,iconDownP,demoListText,screenShow,img_drop,\
+frostedGlass
+    gc_log()
+    image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+    splash.clear()
+    splash.draw_rectangle(0,0,320,240,color=splash_theme_color,thickness=-1)
+    splash.draw_rectangle(0,0,320,32,color=color_blue,thickness=-1)
+    splash.draw_image(iconUpNp, 3, 3)
+    splash.draw_image(iconDownNp, 287, 3)
+
+    splash.draw_rectangle(0,214,50,240,color=color_blue,thickness=-1)
+    splash.draw_rectangle(270,214,320,240,color=color_blue,thickness=-1)
+    splash.draw_string(12, 218, splash_text[10], color=(255,255,255), thickness = 1)
+    splash.draw_string(282, 218, splash_text[12], color=(255,255,255), thickness = 1)
+
+    demo_i=int(demoSelect/6)
+    demo_j=demoSelect%6
+    demo_m=int(demoNum/6)
+    demo_n=demoNum%6
+    for j in range(6):
+        if demo_i==demo_m:
+            if j>=demo_n:
+                pass
+            else:
+                if j==demo_j:
+                    pass
+                else:
+                    splash.draw_rectangle(0,33+30*j,319,33+30*(j+1),color=color_gray,thickness=1)
+                    splash.draw_string(8, 39+30*j,demoListText[j+demo_i*6] , color=color_gray, thickness = 1)
+        else:
+            if j==demo_j:
+                pass
+            else:
+                splash.draw_rectangle(0,33+30*j,319,33+30*(j+1),color=color_gray,thickness=1)
+                splash.draw_string(8, 39+30*j,demoListText[j+demo_i*6] , color=color_gray, thickness = 1)
+    if demoSelect<13:
+        splash.draw_string(72, 10, splash_text[22], color=(255,255,255), thickness = 1)
+    elif demoSelect<23:
+        splash.draw_string(72, 10, splash_text[23], color=(255,255,255), thickness = 1)
+    else:
+        splash.draw_string(72, 10, splash_text[24], color=(255,255,255), thickness = 1)
+    splash.draw_rectangle(0,33+30*demo_j,319,33+30*(demo_j+1),color=color_white,thickness=1)
+    splash.draw_string(8, 39+30*demo_j,demoListText[demoSelect] , color=color_white, thickness = 1)
+    splash.draw_string(146, 218, str(demoSelect+1), color=(255,255,255), thickness = 1)
+    splash.draw_string(160, 218, "/"+str(demoNum), color=(255,255,255), thickness = 1)
+    splash.draw_image(frostedGlass, 0, 0,alpha=0.2)
+    #screenShow()
+    display.show(splash)
+
+def systemPage():
+    from maix import display, image,camera
+    import time
+    global splash,title_logo_text,btn_col,btn_row,splash_text,txt_unselected,txt_selected,btn_selected,btn_unselected,\
+splash_theme_color,btn_height,btn_width,main_title,demoSelect,gc_log,color_splash_theme,color_blue,color_blue_lighter,\
+color_white,color_gray,color_orange,color_red,iconUpNp,iconUpP,iconDownNp,iconDownP,demoListText,screenShow,img_drop,\
+frostedGlass
+    image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+    for i in range(10):
+        splash.draw_image(frostedGlass, 0, 0,alpha=0.2)
+        #screenShow()
+        display.show(splash)
+    splash.draw_string(80, 68, splash_text[13], 1,color=(0,255,0), thickness = 1)
+    splash.draw_string(80, 118, splash_text[14], 1,color=(255,255,0), thickness = 1)
+    splash.draw_string(80, 168, splash_text[15], 1,color=(255,0,0), thickness = 1)
+    #splash.draw_image(backUp, 20, 140)
+    #screenShow()
+    splash.draw_image((image.open("/root/preset/img/backup_00ff00_32x32.png")).rotate(0, adjust=0),40,60,alpha=1)
+    splash.draw_image((image.open("/root/preset/img/reboot_ffff00_32x32.png")).rotate(0, adjust=0),40,110,alpha=1)
+    splash.draw_image((image.open("/root/preset/img/poweroff_ff0000_32x32.png")).rotate(0, adjust=0),40,160,alpha=1)
+
+    display.show(splash)
+
+pageVal=0
+menuSelect=0
+demoSelect=0
+execVal=0
+demoListText=(
+    "相机",
+    "相册",
+    "颜色分析",
+    "录音机",
+    "音频播放器",
+    "播放演示音乐",
+    "播放演示视频",
+    "秒表计时器",
+    "系统时钟显示",
+    "舵机操控",
+    "电机操控",
+    "图片轮播",
+    "二维码扫描",
+    "人形识别",
+    "人脸检测",
+    "人脸比对",
+    "物体识别",
+    "边缘检测",
+    "手写数字识别",
+    "车牌识别",
+    "口罩识别",
+    "手势识别",
+    "猜拳识别",
+    "扫码连接WIFI",
+    "关于CocoPi",
+    "无线相机",
+    "网络天气",
+    "网络时钟",
+    "环境监测",
+    "模型训练:数据集采集",
+    "模型训练:模型部署",
+
+)
+demoNameList=(
+    "01_camera",
+    "02_photoViewer",
+    "03_colorDetection",
+    "04_recorder",
+    "05_audioPlayer",
+    "06_musicPlayer",
+    "07_videoPlayer",
+    "08_timeCounter",
+    "09_localTimeClock",
+    "10_servoControl",
+    "11_motorControl",
+    "12_pictureLoopPlay",
+    "13_qrCodeScanner",
+    "14_humanDetection",
+    "15_faceDetection",
+    "16_faceComparison",
+    "17_objectRecognition",
+    "18_edgeDetection",
+    "19_handWrittenDigiRecognition",
+    "20_carLicensePlateRecognition",
+    "21_maskDetection",
+    "22_gestureRecognition",
+    "23_fingerGuessing",
+    "24_connectWifi",
+    "25_aboutCocoPi",
+    "26_internetCamera",
+    "27_internetWeatherPrediction",
+    "28_internetTimeClock",
+    "29_environmentDetection",
+    "30_train_data_collect",
+    "31_train_deploy_model",
+)
+demoNum=len(demoListText)
+pageSig=1
+selectSig=1
+def buttonDectect():
+    from maix import display, image,camera
+    import time
+    import os
+    global key_A,key_B,key_C,key_D,pageVal,menuSelect,execVal,demoNum,demoSelect,splash,iconUpP,iconDownP,screenShow,img_drop,systemRunNum,pageSig,selectSig
+
+    if(pageVal==0):
+        if(key_A.is_pressed()):
+            pressTime=time.perf_counter()
+            while key_A.is_pressed()==1:
+                if(time.perf_counter()-pressTime)<5:
+                    time.sleep(0.001)
+                    pageVal=1
+                else:
+                    pageVal=2
+                    break
+            execVal=0
+        elif(key_B.is_pressed()):
+            while key_B.is_pressed()==1:
+                time.sleep(0.001)
+            execVal=1
+#         elif (key_B.is_pressed()):
+#             while key_B.is_pressed()==1:
+#                 time.sleep(0.001)
+#             pageVal=1
+        else:
+            pass
+    elif(pageVal==1):
+        if execVal==0:
+            if(key_D.is_pressed()):
+                splash.draw_image(iconUpP, 3, 3)
+                #screenShow()
+                display.show(splash)
+                while key_D.is_pressed()==1:
+                    time.sleep(0.001)
+                demoSelect=demoSelect-1
+                if(demoSelect==-1):
+                    demoSelect=demoNum-1
+            elif (key_C.is_pressed()):
+                splash.draw_image(iconDownP, 287, 3)
+                #screenShow()
+                display.show(splash)
+                while key_C.is_pressed()==1:
+                    time.sleep(0.001)
+                demoSelect=demoSelect+1
+                if(demoSelect==demoNum):
+                    demoSelect=0
+            elif (key_B.is_pressed()):
+                while key_B.is_pressed()==1:
+                    time.sleep(0.001)
+                execVal=2+demoSelect
+            elif (key_A.is_pressed()):
+                while key_A.is_pressed()==1:
+                    time.sleep(0.001)
+                menuSelect=0
+                pageVal=0
+                demoSelect=0
+                execVal=0
+                try:
+                    with open( '/tmp/page.txt', 'w' ) as f:
+                        f.write(str(pageVal))
+                except:
+                    pass
+                try:
+                    with open( '/tmp/menu.txt', 'w' ) as f:
+                        f.write(str(demoSelect))
+                except:
+                    pass
+                pageSig=1
+                selectSig=1
+            else:
+                pass
+        else:
+            if (key_A.is_pressed()):
+                while key_A.is_pressed()==1:
+                    time.sleep(0.001)
+                menuSelect=0
+                pageVal=0
+                demoSelect=0
+                execVal=0
+                systemRunNum=0
+    elif pageVal==2:
+        if(key_C.is_pressed()):
+            pageVal=0
+            menuSelect=0
+            pageVal=0
+            demoSelect=0
+            execVal=0
+            systemRunNum=0
+        elif key_B.is_pressed():
+            os.system("poweroff")
+        elif key_D.is_pressed():
+            os.system("reboot")
+    else:
+        pass
+
+def running():
+    from maix import display, image,camera
+    global splash,title_logo_text,btn_col,btn_row,splash_text,txt_unselected,txt_selected,btn_selected,btn_unselected,\
+splash_theme_color,btn_height,btn_width,main_title,menuSelect,pageVal,execVal,screenFirstPage,screenSecondPage,\
+color_splash_theme,color_blue,color_blue_lighter,color_white,color_gray,color_orange,color_red,demo_i,demo_j,\
+demo_m,demo_n,screenShow,img_drop,systemRunNum,systemPage,demoNameList,pageSig,selectSig,demoSelect
+    if pageSig==1:
+        try:
+            with open( '/tmp/page.txt', 'r' ) as f:
+                pageVal=int(f.read())
+                print(pageVal)
+            pageSig=0
+        except:
+            pass
+    if selectSig==1:
+        try:
+            with open( '/tmp/menu.txt', 'r' ) as f:
+                demoSelect=int(f.read())
+                print(demoSelect)
+            selectSig=0
+        except:
+            pass
+
+    if(pageVal==0):
+        screenFirstPage()
+        if(execVal==0):
+            pass
+            #splash.draw_rectangle(btn_col[0], btn_row-26,btn_col[0]+220,26, color=splash_theme_color, thickness=1)
+            #screenShow()
+            #display.show(splash)
+        else:
+            try:
+                splash.draw_string(btn_col[0], btn_row-25, splash_text[5], color=(0,255,255),thickness = 1)
+                #screenShow()
+                display.show(splash)
+                time.sleep(0.5)
+                os.system("ln -sf %s /tmp/event && touch /tmp/start" % "/root/user_latest_code.py")
+
+            except BaseException as e:
+                execVal=0
+                print(str(e))
+                splash.draw_rectangle(btn_col[0], btn_row-26,btn_col[0]+220,26, color=splash_theme_color, thickness=1)
+                splash.draw_string(btn_col[0], btn_row-85, splash_text[9], color=(255,0,0), thickness = 1)
+                #screenShow()
+                display.show(splash)
+    elif(pageVal==1):
+        if(execVal==0):
+            screenSecondPage()
+            #print("show(demoSelect)")
+        else:
+            demo_i=int(demoSelect/6)
+            demo_j=demoSelect%6
+            demo_m=int(demoNum/6)
+            demo_n=demoNum%6
+            splash.draw_rectangle(0,33+30*demo_j,319,33+30*(demo_j+1),color=color_orange,thickness=-1)
+            splash.draw_rectangle(0,33+30*demo_j,319,33+30*(demo_j+1),color=color_white,thickness=1)
+            splash.draw_string(8, 39+30*demo_j,splash_text[11] , color=color_white, thickness = 1)
+            #screenShow()
+            display.show(splash)
+            time.sleep(0.5)
+            app_path_1='ln -sf /root/preset/app/'
+            app_path_2='.py /tmp/event && touch /tmp/start'
+            app_path=app_path_1+demoNameList[execVal-2]+app_path_2
+            #print(app_path)
+            try:
+                with open( '/tmp/page.txt', 'w' ) as f:
+                    f.write(str(pageVal))
+            except:
+                pass
+            try:
+                with open( '/tmp/menu.txt', 'w' ) as f:
+                    f.write(str(demoSelect))
+            except:
+                pass
+            pageSig=1
+            selectSig=1
+            os.system(app_path)
+    else:
+        if systemRunNum==0:
+            systemPage()
+            systemRunNum=systemRunNum+1
+        else:
+            pass
+
+def screenShow():
+    from maix import image,display,camera
+    global img_drop
+    screenCapture=splash.crop(0,0,240,320)
+    img_drop.draw_image((screenCapture.rotate(0,adjust=1)),0,0)
+    #img_drop.draw_image((screenCapture.rotate(-90,adjust=1)),0,0)
+    display.show(img_drop)
+try:
+    with open( '/tmp/filesyStem.txt', 'w' ) as f:
+        f.write("a")
+    #os.system("rm /etc/wifi/wpa_supplicant.conf && touch /etc/wifi/wpa_supplicant.conf && sync && fsck.ext4 -p /dev/root && mount -o remount -o rw /dev/root && rm /etc/wifi/wpa_supplicant.conf && touch /etc/wifi/wpa_supplicant.conf && sync &")
+    os.system("sync && rm /tmp/filesyStem.txt && sync")
+    #os.system("fsck.ext4 -p /dev/root && mount -o remount -o rw /dev/root")
+    #os.system("rm /etc/wifi/wpa_supplicant.conf && touch /etc/wifi/wpa_supplicant.conf && sync")
+    
+except:
+    os.system("fsck.ext4 -p /dev/root && mount -o remount -o rw /dev/root")
+
+try:
+    os.popen("cd /root/preset/server/ && python wirelessServer.py &")
+except:
+    pass
+while True:
+    buttonDectect()
+    running()
+
+del key_A
+del key_B
+del key_C
+del key_D
+
+
+

+ 60 - 0
backup/preset/app/01_camera.py

@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#version:2023.04.06
+#显示摄像头图像
+from maix import camera
+from maix import display
+from maix import image     #引入python模块包
+import time
+import sys
+sys.path.append('/root/')
+from CocoPi import BUTTON
+
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+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
+    
+def timeStampConvert():
+    timeListOutput=""
+    timeListOutput = str(time.localtime().tm_year) + \
+        str(time.localtime().tm_mon)+str(time.localtime().tm_mday) + \
+        str(time.localtime().tm_hour)+str(time.localtime().tm_min) + \
+        str(time.localtime().tm_sec)
+    return timeListOutput
+
+key_C = BUTTON(13)
+camera.camera.config(size=(240, 320))
+while True:
+    buttonDetect()
+    savePathHead="/root/user/img/photo_"
+    savePathTail=".png"
+    if buttonState!=2:
+        img_backdrop = image.new(size=(320,240),color=(0, 0, 0))    #创建背景画布
+        camera_img = camera.capture()    #从摄像头中获取一张图像
+        camera_img_capture = camera_img.crop(0, 0, 240, 320)        #截取图像
+        img_backdrop.draw_image(camera_img_capture.rotate(90,adjust=1))
+        img_backdrop.draw_image((image.open("/root/preset/img/camera_bfbfbf_24x24.png")).rotate(0, adjust=0),292,2,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)         #将图像显示出来
+    else:
+        img_backdrop = image.new(size=(320,240),color=(0, 0, 0))    #创建背景画布
+        camera_img = camera.capture()    #从摄像头中获取一张图像
+        camera_img_capture = camera_img.crop(0, 0, 240, 320)        #截取图像
+        camera_img_rotate=camera_img_capture.rotate(90,adjust=1)
+        camera_img_rotate.save(savePathHead+timeStampConvert()+savePathTail)
+        img_backdrop.draw_image(camera_img_rotate.resize(280, 210),20,15)
+        img_backdrop.draw_image((image.open("/root/preset/img/camera_bfbfbf_24x24.png")).rotate(0, adjust=0),292,2,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)         #将图像显示出来
+        time.sleep(0.5)
+        

+ 93 - 0
backup/preset/app/02_photoViewer.py

@@ -0,0 +1,93 @@
+#!/usr/bin/env python
+#version    :       2023.04.04
+#language   :       ch
+import os
+from maix import display
+from maix import image
+from maix import camera
+import time
+import os
+import sys
+sys.path.append('/root/')
+from CocoPi import BUTTON
+
+key_A = BUTTON(14)
+key_B = BUTTON(8)
+key_C = BUTTON(13)
+key_D = BUTTON(7)
+camera.camera.config(size=(240,320))
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+
+###需要查询的文件夹目录及文件格式后缀###
+def getImgFileList(filePath="/root/user/img/",selectFile=".png"):
+    import os
+    FileList=[]
+    aimFilePath=filePath
+    aimFile=selectFile
+    aimFileLenth=len(selectFile)*(-1)
+    for root,dirs,files in os.walk(aimFilePath):
+        for name in files:
+            if str(name)[aimFileLenth:]==aimFile:
+                FileList.append(name)
+    return FileList
+pngImgShow=getImgFileList()
+picNum=len(pngImgShow)
+picSelect=0
+deleteSig=False
+
+canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+blackBlock=image.new(size=(320, 24), mode="RGB", color=(0, 0, 0))
+
+while True:
+    if picNum==0:
+        canvas.clear()
+        canvas.draw_string(104, 100, "未找到PNG格式图片!", 1, color=(255, 0, 0))
+    else:
+        if key_B.is_pressed():
+            while key_B.is_pressed():
+                time.sleep(0.001)
+            deleteSig=True
+            os.system("rm /root/user/img/"+pngImgShow[picSelect])
+            pngImgShow=getImgFileList()
+            picNum=len(pngImgShow)
+        else:
+            if key_D.is_pressed():
+                while key_D.is_pressed():
+                    time.sleep(0.001)
+                picSelect=picSelect-1
+            elif key_C.is_pressed():
+                while key_C.is_pressed():
+                    time.sleep(0.001)
+                picSelect=picSelect+1
+            else:
+                picSelect=picSelect
+                
+            if picSelect>picNum-1:
+                picSelect=0
+            elif picSelect<0:
+                picSelect=picNum-1
+            else:
+                pass
+            canvas.clear()
+            try:
+                canvas.draw_image((image.open("/root/user/img/"+pngImgShow[picSelect])),0,0)
+            except:
+                canvas.draw_string(104, 100, "无法打开这张图片!", 1, color=(255,0, 0))
+                
+            canvas.draw_string(60, 218, pngImgShow[picSelect], color=(255,255,255), thickness = 1)
+    
+    canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 0,alpha=0.8)
+    canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 216,alpha=0.8)
+    canvas.draw_image((image.open("/root/preset/img/trashBox_ff0000_24x24.png")).rotate(0, adjust=0),8,216,alpha=1)
+    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/left_ffffff_16x16.png")).rotate(0, adjust=0),6,4,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/left_ffffff_16x16.png")).rotate(180, adjust=0),296,4,alpha=1)
+    #canvas.draw_image((image.open("/root/preset/img/blackBlock_000000_320x33.png")).rotate(0, adjust=0),0,0,alpha=0.3)
+    #canvas.draw_string(8, 39+30*demo_j,demoListText[demoSelect] , color=color_white, thickness = 1)
+    if picNum==0:
+        canvas.draw_string(116, 3, str(picSelect), color=(255,255,255), thickness = 1)
+    else:
+        canvas.draw_string(116, 3, str(picSelect+1), color=(255,255,255), thickness = 1)
+    canvas.draw_string(160, 3, "/   "+str(picNum), color=(255,255,255), thickness = 1)
+    
+    display.show(canvas)

+ 35 - 0
backup/preset/app/03_colorDetection.py

@@ -0,0 +1,35 @@
+#!/usr/bin/env python
+#version    :       2023.04.06
+#language   :       ch
+from maix import display
+from maix import image
+from maix import camera
+camera.camera.config(size=(240,320))
+ScreenOrientation = False
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+
+while True:
+    canvas = lcdRotation(camera.capture(),CAMERAROTATE)
+    RGB = canvas.get_blob_color((154, 114, 10, 10), 0, 0)
+    canvas.draw_rectangle(154,114, 164,124, color=(255,0,0), thickness=1)
+    canvas.draw_rectangle(0,0, 319,20, color=((int(RGB[0])),(int(RGB[1])),(int(RGB[2]))), thickness=-1)
+    canvas.draw_string(120,0, (''.join([str(x) for x in ["(", int(RGB[0]), ",", int(RGB[1]), ",", int(RGB[2]), ")"]])), scale = 1, color = ((255 - int(RGB[0])),(255 - int(RGB[1])),(255 - int(RGB[2]))), thickness = 1)
+    if ScreenOrientation:
+        canvasVER = canvas.crop(0,0,240,320)
+        canvasVER = canvasVER.rotate(-90, adjust=1)
+        display.show(canvasVER)
+    else:
+        display.show(canvas)

+ 123 - 0
backup/preset/app/04_recorder.py

@@ -0,0 +1,123 @@
+#!/usr/bin/env python
+#version    :       2023.04.06
+#language   :       ch
+from maix import display
+from maix import image
+from maix import camera
+import pyaudio
+import wave
+import time
+import sys
+sys.path.append('/root/')
+#按键初始化
+from CocoPi import BUTTON
+key_C = BUTTON(13)
+
+buttonState=0
+newState=0
+oldState=0
+def buttonDetect():
+    global buttonState,newState,oldState,key_C
+    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
+    
+def timeStampConvert():
+    timeListOutput=""
+    timeListOutput = str(time.localtime().tm_year) + \
+        str(time.localtime().tm_mon)+str(time.localtime().tm_mday) + \
+        str(time.localtime().tm_hour)+str(time.localtime().tm_min) + \
+        str(time.localtime().tm_sec)
+    return timeListOutput
+
+#音频初始化
+CHUNK = 1024
+FORMAT = pyaudio.paInt16
+CHANNELS = 2
+RATE = 44100
+
+#屏幕初始化
+canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+startPointer=0
+startTime=0
+global deltaTime
+deltaTime=0
+# 初始化
+startTime = time.time()
+oldState=0
+newState=0
+savePathHead="/root/user/audio/"
+savePathTail=".wav"
+recordState=0
+canvas.draw_string(12, 18, "提示:按下C键来开始/停止录音!", 1, color=(0, 255, 0))
+canvas.draw_string(58, 48, "   ", 1, color=(0, 255, 0))
+canvas.draw_image(image.open("/root/preset/img/recording.png"),288 , 8,alpha=1)
+canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+display.show(canvas)
+while True:
+    
+    buttonDetect()
+    if buttonState==2:
+        recordState=1-recordState
+        print("recordState",recordState)
+    if recordState==1:
+        if startPointer==0:
+            canvas.clear()
+            canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+            canvas.draw_string(12, 18, "提示:按下C键来开始/停止录音!", 1, color=(0, 255, 0))
+            canvas.draw_string(58, 48, "   ", 1, color=(0, 255, 0))
+            canvas.draw_image(image.open("/root/preset/img/recording.png"),288 , 8,alpha=1)
+            canvas.draw_string(24, 108, "开始录音!", 1, color=(0, 255, 0))
+            canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+            display.show(canvas)
+            print("Recording start!")
+            startTime = round(time.time(), 2)
+            startPointer=1
+            p = pyaudio.PyAudio()
+            stream = p.open(format=FORMAT,
+                            channels=CHANNELS,
+                            rate=RATE,
+                            input=True,
+                            frames_per_buffer=CHUNK)
+            frames = []
+        else:
+            data = stream.read(CHUNK,exception_on_overflow = False)
+            frames.append(data)  
+    elif recordState==0:
+        if startPointer==1:
+            stream.stop_stream()
+            stream.close()
+            p.terminate()
+            WAVE_OUTPUT_FILENAME=savePathHead+timeStampConvert()+savePathTail
+            wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
+            wf.setnchannels(CHANNELS)
+            wf.setsampwidth(p.get_sample_size(FORMAT))
+            wf.setframerate(RATE)
+            wf.writeframes(b''.join(frames))
+            wf.close()
+            deltaTime = round(time.time() - startTime, 2)
+            canvas.clear()
+            canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+            canvas.draw_string(12, 18, "提示:按下C键来开始/停止录音!", 1, color=(0, 255, 0))
+            canvas.draw_string(58, 48, "   ", 1, color=(0, 255, 0))
+            canvas.draw_image(image.open("/root/preset/img/recording.png"),288 , 8,alpha=1)
+            canvas.draw_string(24, 108, "录制完成!", 1, color=(0, 255, 0))
+            canvas.draw_string(24, 128, "持续时间(秒):"+str(deltaTime), 1, color=(0, 255, 0))
+            canvas.draw_string(24, 148, "文件保存路径:", 1, color=(0, 255, 0))
+            canvas.draw_string(24, 168, WAVE_OUTPUT_FILENAME, 1, color=(0, 255, 0))
+            canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+            
+            display.show(canvas)
+            print(deltaTime)
+            startPointer=0
+        else:
+            startPointer=0
+    else:
+        pass

+ 162 - 0
backup/preset/app/05_audioPlayer.py

@@ -0,0 +1,162 @@
+#!/usr/bin/python
+#version    :       2023.04.06
+#language   :       ch
+import os
+from maix import display
+from maix import image
+from maix import camera
+import time
+import pyaudio
+import wave
+import sys
+sys.path.append('/root/')
+from CocoPi import BUTTON
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+key_A = BUTTON(14)
+key_B = BUTTON(8)
+key_C = BUTTON(13)
+key_D = BUTTON(7)
+camera.camera.config(size=(240,320))
+
+buttonState=0
+newState=0
+oldState=0
+def buttonDetect():
+    global buttonState,newState,oldState,key_C
+    newState=key_B.is_pressed()
+    if newState == True and oldState == False:
+        buttonState=1
+    elif newState == False and oldState == True:
+        buttonState=2
+    else:
+        buttonState=0
+    oldState=newState
+
+
+###需要查询的文件夹目录及文件格式后缀###
+def getWavFileList(filePath="/root/user/audio/",selectFile=".wav"):
+    import os
+    FileList=[]
+    aimFilePath=filePath
+    aimFile=selectFile
+    aimFileLenth=len(selectFile)*(-1)
+    for root,dirs,files in os.walk(aimFilePath):
+        for name in files:
+            if str(name)[aimFileLenth:]==aimFile:
+                FileList.append(name)
+    return FileList
+
+wavShow=getWavFileList()
+print(wavShow)
+audioNum=len(wavShow)
+audioSelect=0
+playState=0
+playRunState=0
+
+canvas = image.new(size = (320, 240))
+
+while True:
+    if audioNum==0:
+        canvas.clear()
+        canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 0,alpha=0.8)
+        canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 216,alpha=0.8)
+        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/left_ffffff_16x16.png")).rotate(0, adjust=0),6,4,alpha=1)
+        canvas.draw_image((image.open("/root/preset/img/left_ffffff_16x16.png")).rotate(180, adjust=0),296,4,alpha=1)
+        canvas.draw_string(4, 140, "未找到WAV格式音频文件!", 1, color=(0, 255, 0))
+        display.show(canvas)
+    else:
+        if key_C.is_pressed():
+            while key_C.is_pressed():
+                time.sleep(0.001)
+            audioSelect=audioSelect-1
+        elif key_D.is_pressed():
+            while key_D.is_pressed():
+                time.sleep(0.001)
+            audioSelect=audioSelect+1
+        else:
+            buttonDetect()
+            if buttonState==2:
+                playState=1-playState
+                print("playState",playState)
+        if audioSelect>audioNum-1:
+            audioSelect=0
+        elif audioSelect<0:
+            audioSelect=audioNum-1
+        else:
+            pass
+        if playState==1:
+            if playRunState==0:
+                canvas.clear()
+                canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 0,alpha=0.8)
+                canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 216,alpha=0.8)
+                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/left_ffffff_16x16.png")).rotate(0, adjust=0),6,4,alpha=1)
+                canvas.draw_image((image.open("/root/preset/img/left_ffffff_16x16.png")).rotate(180, adjust=0),296,4,alpha=1)
+                canvas.draw_string(4, 80, "音频状态:正在播放!", 1, color=(0, 255, 0))
+                canvas.draw_image((image.open("/root/preset/img/stop24.png")).rotate(0, adjust=0),4,216,alpha=1)
+                canvas.draw_string(104, 218, wavShow[audioSelect], 1, color=(0, 255, 0))
+                display.show(canvas)
+                CHUNK = 1024
+                wf = wave.open(r"/root/user/audio/"+wavShow[audioSelect], 'rb')
+                p = pyaudio.PyAudio()
+                stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),output=True)
+                data = wf.readframes(CHUNK)
+                playRunState=1
+            elif playRunState==1:
+                if len(data) > 0:
+                    stream.write(data)
+                    data = wf.readframes(CHUNK)
+                else:
+                    stream.stop_stream()
+                    stream.close()
+                    p.terminate()
+                    canvas.clear()
+                    canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 0,alpha=0.8)
+                    canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 216,alpha=0.8)
+                    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/left_ffffff_16x16.png")).rotate(0, adjust=0),6,4,alpha=1)
+                    canvas.draw_image((image.open("/root/preset/img/left_ffffff_16x16.png")).rotate(180, adjust=0),296,4,alpha=1)
+                    canvas.draw_string(4, 80, "音频状态:播放完成!", 1, color=(0, 255, 0))
+                    canvas.draw_image((image.open("/root/preset/img/play24.png")).rotate(0, adjust=0),4,216,alpha=1)
+                    canvas.draw_string(104, 218, wavShow[audioSelect], 1, color=(0, 255, 0))
+                    display.show(canvas)
+                    playRunState=0
+                    playState=0
+                    time.sleep(0.5)
+            else:
+                pass
+        elif playState==0:
+            if playRunState==0:
+                canvas.clear()
+                canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 0,alpha=0.8)
+                canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 216,alpha=0.8)
+                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/left_ffffff_16x16.png")).rotate(0, adjust=0),6,4,alpha=1)
+                canvas.draw_image((image.open("/root/preset/img/left_ffffff_16x16.png")).rotate(180, adjust=0),296,4,alpha=1)
+                canvas.draw_string(4, 80, "音频状态:等待播放!", 1, color=(0, 255, 0))
+                canvas.draw_image((image.open("/root/preset/img/play24.png")).rotate(0, adjust=0),4,216,alpha=1)
+                canvas.draw_string(104, 218, wavShow[audioSelect], 1, color=(0, 255, 0))
+                display.show(canvas)
+                playRunState=0
+            elif playRunState==1:
+                stream.stop_stream()
+                stream.close()
+                p.terminate()
+                canvas.clear()
+                canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 0,alpha=0.8)
+                canvas.draw_image(image.open("/root/preset/img/blackBlock_7f7f7f_320x24.jpg"), 0, 216,alpha=0.8)
+                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/left_ffffff_16x16.png")).rotate(0, adjust=0),6,4,alpha=1)
+                canvas.draw_image((image.open("/root/preset/img/left_ffffff_16x16.png")).rotate(180, adjust=0),296,4,alpha=1)
+                canvas.draw_string(4, 80, "音频状态:播放结束!", 1, color=(0, 255, 0))
+                canvas.draw_image((image.open("/root/preset/img/play24.png")).rotate(0, adjust=0),4,216,alpha=1)
+                canvas.draw_string(4, 100, "音频路径:"+wavShow[audioSelect], 1, color=(0, 255, 0))
+                display.show(canvas)
+                playRunState=0
+            else:
+                pass
+        else:
+            pass
+        #canvas.clear()
+        #canvas.draw_image((image.open("/root/user/audio/"+wavShowShow[audioSelect])),0,0)

+ 28 - 0
backup/preset/app/06_musicPlayer.py

@@ -0,0 +1,28 @@
+import os
+import pyaudio
+import wave
+import sys
+
+def voice_numberMap(value):
+    valueScaled = float(value - 0) / float(100)
+    return valueScaled * 31
+
+
+
+while True:
+    os.system("amixer cset numid=8,iface=MIXER,name='LINEOUT volume'voice_numberMap(25)")
+    CHUNK = 1024
+    wf = wave.open(r"/root/preset/audio/funky_stars_quazar.wav", 'rb')#(sys.argv[1], 'rb'
+    p = pyaudio.PyAudio()
+
+    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),output=True)
+
+    data = wf.readframes(CHUNK)
+    while len(data) > 0:
+        stream.write(data)
+        data = wf.readframes(CHUNK)
+
+    stream.stop_stream()
+    stream.close()
+
+    p.terminate()

+ 37 - 0
backup/preset/app/07_videoPlayer.py

@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+#version    :       2023.04.04
+#language   :       ch
+import pyaudio, av, os,_thread
+from maix import display, camera, image
+# ffmpeg -r 30 -i badapple_240_60fps.mp4 -vf scale=240:240,setdar=1:1 output.mp4
+# adb push ./output.mp4 /root/
+path_to_video = '/root/preset/video/output_240_240.mp4'
+try:
+    container = av.open(path_to_video)
+    ai_stream = container.streams.audio[0]
+    vi_stream = container.streams.video[0]
+    fifo = av.AudioFifo()
+    p = pyaudio.PyAudio()
+    ao = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=True)
+    audio = [p, ao, fifo]
+    def play_audio(audio):
+        try:
+            while len(audio):
+                for frame in audio[2].read_many(4096):
+                    audio[1].write(frame.planes[0].to_bytes())
+        except Exception as e:
+            print(e)
+    _thread.start_new_thread(play_audio, (audio, ) )
+    for frame in container.decode(video=0, audio=0):
+        if 'Audio' in repr(frame):
+            frame.pts = None
+            frame.time_base = None
+            fifo.write(frame)
+        if 'Video' in repr(frame):
+            img = image.load(bytes(frame.to_rgb().planes[0]), (vi_stream.width, vi_stream.height))
+            display.show(img)
+finally:
+    ao.stop_stream()
+    ao.close()
+    p.terminate()
+    audio = []

+ 71 - 0
backup/preset/app/08_timeCounter.py

@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#version    :       2023.04.06
+#language   :       ch
+from maix import display
+from maix import image
+from maix import camera
+import time
+import sys
+sys.path.append('/root/')
+from CocoPi import BUTTON
+# 秒表小程序
+key_C = BUTTON(13)
+key_B = BUTTON(8)
+camera.camera.config(size=(240,320))
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+signal=0
+startPointer=0
+startTime=0
+global deltaTime
+deltaTime=0
+# 初始化
+startTime = time.time()
+oldState=0
+newState=0
+canvas = image.new(color=(0,0,0),size = (320, 240))
+while True:
+    canvas.clear()
+    if key_B.is_pressed():
+        time.sleep(0.02)
+        deltaTime = 0
+        startTime = round(time.time(), 3)
+    else:
+        pass
+    newState=key_C.is_pressed()
+    if (newState==0 and oldState==1):
+        time.sleep(0.02)
+        signal=1-signal
+        if deltaTime == 0:
+            startTime = round(time.time(), 3)
+        else:
+            startTime =  round(time.time(), 3) - deltaTime
+    else:
+        pass
+    if signal==1:
+        if startPointer==0:
+            startPointer=1
+            #print("startPoniter",startPoniter)
+        else:
+            #pass
+            deltaTime = round(time.time() - startTime, 3)
+            #deltaTime = time.time()-startTime
+            #deltaTime = round(time.time()-startTime, 5)
+            #canvas.draw_string(80, 128, "持续时间:"+str(deltaTime), 1, color=(0, 255, 0))
+        
+    elif signal==0:
+        startPointer=0
+    else:
+        pass
+    if signal==1:
+        canvas.draw_string(80, 108, "正在计时中...", 1, color=(0, 255, 0))
+        canvas.draw_image((image.open("/root/preset/img/stop24.png")).rotate(0, adjust=0),288,2,alpha=1)
+    else:
+        canvas.draw_string(80, 108, "等待计时...", 1, color=(0, 255, 0))
+        canvas.draw_image((image.open("/root/preset/img/play24.png")).rotate(0, adjust=0),288,2,alpha=1)
+    canvas.draw_string(80, 128, "计时持续时间(秒):"+str(deltaTime), 1, color=(0, 255, 0))
+    canvas.draw_string(16, 8, "按下C键来开始/停止计时!", 1, color=(0, 255, 0))
+    
+    canvas.draw_image((image.open("/root/preset/img/restart_ff0000_24x24.png")).rotate(0, adjust=0),2,216,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+    display.show(canvas)
+    oldState=newState

+ 35 - 0
backup/preset/app/09_localTimeClock.py

@@ -0,0 +1,35 @@
+#!/usr/bin/env python
+#version    :       2023.04.07
+#language   :       ch
+import time
+from maix import camera, display, image
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+month={
+    "Jan":"1月",
+    "Feb": "2月",
+    "Mar": "3月",
+    "Apr": "4月",
+    "May": "5月",
+    "Jun": "6月",
+    "Jul": "7月",
+    "Aug": "8月",
+    "Sep": "9月",
+    "Oct": "10月",
+    "Nov": "11月",
+    "Dec": "12月",
+}
+week={
+    "Mon": "星期一",
+    "Tue": "星期二",
+    "Wed": "星期三",
+    "Thu": "星期四",
+    "Fri": "星期五",
+    "Sat": "星期六",
+    "Sun": "星期日",
+}
+while True:
+    hello_img = image.new(size = (240, 240), color = (0, 0, 0), mode = "RGB")
+    date = time.asctime().split(" ")
+    hello_img.draw_string(20, 108, date[5]+"年"+month[date[1]]+date[3]+"日 "+date[4]+" "+week[date[0]], scale = 1.0, color = (255, 255, 255), thickness = 1)
+    display.show(hello_img)
+    time.sleep(1)

+ 57 - 0
backup/preset/app/10_servoControl.py

@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#version    :       2023.06.01
+#language   :       ch
+#hardware   :       pi
+from maix import display
+from maix import image
+from maix import camera
+import time
+import sys
+sys.path.append('/root/')
+from CocoPi import BUTTON
+from CocoPi import multiFuncGpio
+S1=multiFuncGpio(0,1)
+S2=multiFuncGpio(1,1)
+
+key_D = BUTTON(7)
+key_C = BUTTON(13)
+
+camera.camera.config(size=(240,320))
+ScreenOrientation = False
+angle=0
+addValue=0
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+
+canvas = image.new(size = (320, 240))
+while True:
+    if(key_C.is_pressed()):
+        if angle<180:
+            addValue=1
+        else:
+            addValue=0
+    elif key_D.is_pressed():
+        if angle>0:
+            addValue=-1
+        else:
+            addValue=0
+    else:
+        addValue=0
+    canvas = image.new(color=(0,0,0),size = (320, 240))
+    
+    angle=angle+addValue
+    #canvas.draw_string(4, 180, "C:increase servo's angle", 1, color=(0, 255, 0))
+    #canvas.draw_string(4, 200, "D:decrease servo's angle", 1, color=(0, 255, 0))
+    canvas.draw_string(108, 10, "舵机角度值:"+str(angle), 1, color=(0, 0, 255))
+    canvas.draw_image((image.open("/root/preset/img/sg90.png")).rotate(0, adjust=1),132,70,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/sg90_double_arm.png")).rotate(angle, adjust=0),103,89,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/increase_bfbfbf_24x24.png")).rotate(0, adjust=0),288,8,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/decrease_bfbfbf_24x24.png")).rotate(0, adjust=0),8,8,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+    S1.servoCtrl(angle)
+    S2.servoCtrl(angle)
+    if ScreenOrientation:
+        canvasVER = canvas.crop(0,0,240,320)
+        canvasVER = canvasVER.rotate(-90, adjust=1)
+        display.show(canvasVER)
+    else:
+        display.show(canvas)

+ 87 - 0
backup/preset/app/11_motorControl.py

@@ -0,0 +1,87 @@
+#!/usr/bin/env python
+#version    :       2023.06.01
+#language   :       ch
+#hardware   :       pi
+
+from maix import display
+from maix import image
+from maix import camera
+import time
+import sys
+sys.path.append('/root/')
+from CocoPi import BUTTON
+from CocoPi import dcMotor
+D1=dcMotor(1)
+D2=dcMotor(2)
+
+key_D = BUTTON(7)
+key_B = BUTTON(8)
+key_C = BUTTON(13)
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+camera.camera.config(size=(240,320))
+ScreenOrientation = False
+speed=0
+rotation=1
+addValue=1
+angle=0
+
+canvas = image.new(size = (320, 240))
+while True:
+    if (key_B.is_pressed()):
+        while key_B.is_pressed():
+            time.sleep(0.001)
+        rotation=(-1)*rotation
+    if(key_C.is_pressed()):
+        if speed<255:
+            addValue=1
+        else:
+            addValue=0
+    elif key_D.is_pressed():
+        if speed>0:
+            addValue=-1
+        else:
+            addValue=0
+    else:
+        addValue=0
+    canvas = image.new(color=(0,0,0),size = (320, 240))
+    
+    speed=speed+addValue
+    canvas.draw_string(80, 8, "转速:"+str(speed), 1, color=(0, 255, 0))
+    if rotation==1:
+        canvas.draw_image((image.open("/root/preset/img/clockwise_bfbfbf_24x24.png")).rotate(0, adjust=0),8,216,alpha=1)
+        #canvas.draw_string(40, 24, "rotation:clockwise", 1, color=(0, 255, 0))
+    else:
+        canvas.draw_image((image.open("/root/preset/img/anticlockwise_bfbfbf_24x24.png")).rotate(0, adjust=0),8,216,alpha=1)
+        #canvas.draw_string(40, 24, "rotation:anticlockwise", 1, color=(0, 255, 0))
+    angle=angle-int(rotation*speed/3)
+    if angle>3600:
+        angle=angle-3600
+    elif angle<-3600:
+        angle=angle+3600
+    else:
+        angle=angle
+    #canvas.draw_string(4, 180, "C:change fan's direction of rotation", 1, color=(0, 255, 0))
+    #canvas.draw_string(4, 200, "D:increase fan's speed of rotation", 1, color=(0, 255, 0))
+    #canvas.draw_string(4, 220, "B:decrease fan's speed of rotation", 1, color=(0, 255, 0))
+    canvas.draw_image((image.open("/root/preset/img/ttMotor_200_64.png")).rotate(0, adjust=1),80,90,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/fan_140_140.png")).rotate(angle, adjust=0),60,52,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/increase_bfbfbf_24x24.png")).rotate(0, adjust=0),288,8,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/decrease_bfbfbf_24x24.png")).rotate(0, adjust=0),8,8,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+    if(speed<80):
+        D1.dcMotorCtrl(0,1)
+        D2.dcMotorCtrl(0,1)
+    else:
+        if rotation==1:
+            D1.dcMotorCtrl(1,speed)
+            D2.dcMotorCtrl(1,speed)
+        else:
+            D1.dcMotorCtrl(0,speed)
+            D2.dcMotorCtrl(0,speed)
+    if ScreenOrientation:
+        canvasVER = canvas.crop(0,0,240,320)
+        canvasVER = canvasVER.rotate(-90, adjust=1)
+        display.show(canvasVER)
+    else:
+        display.show(canvas)
+

+ 32 - 0
backup/preset/app/12_pictureLoopPlay.py

@@ -0,0 +1,32 @@
+#!/usr/bin/env python
+#version    :       2023.04.04
+#language   :       ch
+from maix import display
+
+from maix import image
+
+from maix import camera
+import time
+
+camera.camera.config(size=(240,320))
+
+ScreenOrientation = False
+
+
+
+canvas = image.new(size = (320, 240))
+img_num = 0
+while True:
+    img_num = img_num + 1
+    canvas.draw_image((image.open((str("/root/preset/img/dog/dog") + str(str(img_num) + str(".jpg"))))),0,0)
+
+    time.sleep(1)
+    if img_num == 30:
+        img_num = 1
+    if ScreenOrientation:
+        canvasVER = canvas.crop(0,0,240,320)
+        canvasVER = canvasVER.rotate(-90, adjust=1)
+        display.show(canvasVER)
+    else:
+        canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+        display.show(canvas)

+ 41 - 0
backup/preset/app/13_qrCodeScanner.py

@@ -0,0 +1,41 @@
+#!/usr/bin/env python
+#version    :       2023.04.04
+#language   :       ch
+from maix import camera, display, zbar, image
+import sys
+sys.path.append('/root/CocoPi.py')
+ScreenOrientation = False
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+camera.camera.config(size=(240,320))
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+while True:
+    canvas = lcdRotation(camera.capture(),CAMERAROTATE)
+    mks = canvas.find_qrcodes()
+    for mk in mks:
+        #外框数据
+        X = mk['x']
+        Y = mk['y']
+        W = mk['w']
+        H = mk['h']            
+        #二维码信息
+        string = mk['payload']
+        #画外框
+        canvas.draw_rectangle(X, Y, X + W, Y + H, color=(0, 0, 255), thickness = 2) 
+        #打印信息
+        canvas.draw_string(int(X) , int(Y - 35) , str(string), 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)
+    display.show(canvas)
+    

+ 67 - 0
backup/preset/app/14_humanDetection.py

@@ -0,0 +1,67 @@
+from time import time
+from maix import image
+ScreenOrientation = False
+class Person:
+    mud_path = "/root/preset/model/person_int8.mud"
+    labels = ["person"]
+    anchors = [4.72, 6.26, 1.39, 3.53, 0.78, 1.9, 0.35, 0.95, 2.49, 4.87]
+
+    def __init__(self) -> None:
+        from maix import nn
+        self.model = nn.load(self.mud_path)
+        from maix.nn import decoder
+        self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
+
+    def __del__(self):
+        del self.model
+        del self.decoder
+
+    def cal_fps(self ,start , end):
+        one_second = 1
+        one_flash = end - start
+        fps = one_second / one_flash
+        return  fps
+
+    def draw_rectangle_with_title(self ,img, box, disp_str , fps ):
+        img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
+        img.draw_string(box[0], box[1]+ box[3] ,disp_str, scale=1,color=(0, 0, 255), thickness=2)
+        #img.draw_string(0, 0 ,'FPS :'+str(fps), scale=2 ,color=(0, 0, 255), thickness=2)
+
+    def process(self,input):
+        t =  time()
+        out = self.model.forward(input, quantize=1, layout = "hwc")
+        boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.6, img_size=(224,224))
+        for i, box in enumerate(boxes):
+            class_id = probs[i][0]
+            prob = probs[i][1][class_id]
+            disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100)
+            fps = self.cal_fps(t, time())
+            self.draw_rectangle_with_title(input, box, disp_str, fps)
+
+
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+canvasImg = image.new(size = (320, 240))
+def main():
+    from maix import display, camera
+    app = Person()
+    #camera.config((224,224))
+    while True:
+        img = lcdRotation(camera.capture(),CAMERAROTATE).crop(0, 0,224, 224)
+        app.process(img)
+        canvasImg.draw_image(img,48,8)
+        canvasImg.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+        display.show(canvasImg)
+
+main()

+ 68 - 0
backup/preset/app/15_faceDetection.py

@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#version    :       2023.04.04
+#language   :       ch
+from maix import camera
+from maix import display
+
+from maix import image
+
+from maix import nn
+from maix.nn import decoder
+
+camera.camera.config(size=(240,320))
+
+ScreenOrientation = False
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+
+model = {
+    "param": "/root/preset/model/yolo2_face_awnn.param",
+    "bin": "/root/preset/model/yolo2_face_awnn.bin"
+}
+labels = ["person"]
+options = {
+    "model_type":  "awnn",
+    "inputs": {
+        "input0": (224, 224, 3)
+    },
+    "outputs": {
+        "output0": (7, 7, (1+4+len(labels))*5)
+    },
+    "mean": [127.5, 127.5, 127.5],
+    "norm": [0.0078125, 0.0078125, 0.0078125],
+}
+anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
+m = nn.load(model, opt=options)
+yolo2_decoder = decoder.Yolo2(len(labels), anchors, net_in_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]), net_out_size=(7, 7))
+
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+
+canvasImg = image.new(size = (240, 320))
+while True:
+    img_facedetection = lcdRotation(camera.capture(),CAMERAROTATE)
+    img_facedetection = img_facedetection.crop(0, 0,224, 224)
+    out = m.forward(img_facedetection.tobytes(), quantize=True, layout="hwc")
+    boxes, probs = yolo2_decoder.run(out, nms=0.3, threshold=0.3, img_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]))
+    if len(boxes):
+        for i in (boxes):
+            img_facedetection.draw_rectangle(i[0],i[1], int(i[0]+i[2]),int(i[1]+i[3]), color=(255,0,0), thickness=1)
+    if ScreenOrientation:
+        img_facedetectionVER = img_facedetection.crop(0,0,240,320)
+        img_facedetectionVER = img_facedetectionVER.rotate(-90, adjust=1)
+        display.show(img_facedetectionVER)
+    else:
+        canvasImg.draw_image(img_facedetection,48,8)
+        canvasImg.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+        display.show(canvasImg)

+ 170 - 0
backup/preset/app/16_faceComparison.py

@@ -0,0 +1,170 @@
+'''
+    Face recognize demo, download modle from maixhub first:
+            https://maixhub.com/
+'''
+
+from maix import nn, display, camera, image
+from maix.nn.app import face
+from maix.nn.app.face import FaceRecognize
+import time
+import sys
+sys.path.append('/root/')
+from CocoPi import BUTTON
+
+key_A = BUTTON(14)
+key_B = BUTTON(8)
+key_C = BUTTON(13)
+key_D = BUTTON(7)
+ScreenOrientation = False
+class Face_Recognizer:
+    def __init__(self, threshold = 0.5, nms = 0.3, max_face_num = 1):
+        model = "/root/preset/model/retinaface.mud"
+        model_fe = "/root/preset/model/fe_resnet.mud"
+        self.input_size = (224, 224, 3)
+        input_size_fe = (128, 128, 3)
+        self.feature_len = 256
+        self.features = []
+        print("-- load model:", model)
+        m = nn.load(model)
+        print("-- load ok")
+        print("-- load model:", model_fe)
+        m_fe = nn.load(model_fe)
+        print("-- load ok")
+
+        self.recognizer = FaceRecognize(m, m_fe, self.feature_len, self.input_size, threshold, nms, max_face_num)
+        print("-- init end")
+
+    def get_faces(self, img, std_img = False):
+        faces = self.recognizer.get_faces(img, std_img)
+        return faces
+
+    def __len__(self):
+        return len(self.features)
+
+    def add_user(self, name, feature):
+        self.features.append([name, feature])
+        return True
+
+    def remove_user(self, name_del):
+        rm = None
+        for name, feature in self.features:
+            if name_del == name:
+                rm = [name, feature]
+        if rm:
+            self.features.remove(rm)
+            return True
+        return False
+
+    def recognize(self, feature):
+        max_score = 0
+        uid = -1
+        for i, user in enumerate(self.features):
+            score = self.recognizer.compare(user[1], feature)
+            if score > max_score:
+                max_score = score
+                uid = i
+        if uid >= 0:
+            return self.features[uid][0], max_score
+        return None, 0
+
+
+    def get_input_size(self):
+        '''
+            @return input_size (w, h, c)
+        '''
+        return self.input_size
+
+    def get_feature_len(self):
+        return self.feature_len
+
+    def darw_info(self, img, box, points, disp_str, bg_color=(255, 0, 0, 255), font_color=(255, 255, 255, 255), font_size=32):
+        font_wh = image.get_string_size(disp_str)
+        for p in points:
+            img.draw_rectangle(p[0] - 1, p[1] -1, p[0] + 1, p[1] + 1, color=bg_color)
+        img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3], color=bg_color, thickness=2)
+        if disp_str:
+            img.draw_rectangle(box[0], box[1] - font_wh[1], box[0] + font_wh[0], box[1], color=bg_color, thickness = -1)
+            img.draw_string(box[0], box[1] - font_wh[1], disp_str, color=font_color)
+
+
+    def darw_title(self, img, dis_size ,key_l = None, key_r =None):
+        if key_C:
+            key_l = "| "+ key_l
+            img.draw_string( 1, 2 ,key_l , scale = 1, color = (255, 255, 255), thickness = 2)
+        if key_D:
+            key_r = key_r+" |"
+            w = int(dis_size[0] - 4 - image.get_string_size(key_r)[0] * 1)
+            img.draw_string( w, 2 ,key_r , scale = 1, color = (255, 255, 255), thickness = 2)
+
+
+
+max_face_num = 4
+detect_threshold = 0.5
+detect_nms = 0.3
+score_threshold = 70
+names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
+
+face_recognizer = Face_Recognizer(detect_threshold, detect_nms, max_face_num = max_face_num)
+camera.config(size=face_recognizer.get_input_size()[:2])
+
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+
+
+canvasImg = image.new(size = (240, 320))
+while 1:
+    img = lcdRotation(camera.capture(),CAMERAROTATE).crop(0, 0,224, 224)
+    if not img:
+        time.sleep(0.02)
+        continue
+    faces = face_recognizer.get_faces(img)
+    face_recognizer.darw_title(img , face_recognizer.get_input_size()[:2] , "rm" ,"add")
+
+    if faces:
+        # for prob, box, landmarks, feature, std_img in faces:
+        for prob, box, landmarks, feature in faces:
+            # [ prob, [x,y,w,h], [[x,y], [x,y], [x,y], [x,y], [x,y]], feature ]
+            if key_C.is_pressed():
+                if len(face_recognizer) < len(names):
+                    while not (key_C.is_pressed() == False):
+                        time.sleep(0.1)
+                    idx = len(face_recognizer)
+                    print("add user: {}, {}".format(idx, names[idx]))
+                    face_recognizer.add_user(names[idx], feature)
+                else:
+                    print("user full")
+            name, score = face_recognizer.recognize(feature)
+            if name:
+                if score > score_threshold:
+                    face_recognizer.darw_info(img, box, landmarks, "{}:{:.2f}".format(name, score), font_color=(0, 0, 255, 255), bg_color=(0, 255, 0, 255))
+                    print("user: {}, score: {:.2f}".format(name, score))
+                else:
+                    face_recognizer.darw_info(img, box, landmarks, "{}:{:.2f}".format(name, score), font_color=(255, 255, 255, 255), bg_color=(255, 0, 0, 255))
+                    print("maybe user: {}, score: {:.2f}".format(name, score))
+            else:
+                face_recognizer.darw_info(img, box, landmarks, "", font_color=(255, 255, 255, 255), bg_color=(255, 255, 255, 255))
+
+    if key_D.is_pressed():
+        if len(face_recognizer) > 0:
+            while not (key_D.is_pressed() == False):
+                time.sleep(0.1)
+            idx = len(face_recognizer) - 1
+            print("remove user:", names[idx])
+            face_recognizer.remove_user(names[idx])
+        else:
+            print("user empty")
+    canvasImg.draw_image(img,48,8)
+    canvasImg.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+    display.show(canvasImg)

+ 76 - 0
backup/preset/app/17_objectRecognition.py

@@ -0,0 +1,76 @@
+#!/usr/bin/env python
+#version    :       2023.04.07
+#language   :       ch
+from maix import camera
+from maix import display
+
+from maix import image
+
+from maix import nn
+from maix.nn import decoder
+
+camera.camera.config(size=(240,320))
+
+ScreenOrientation = False
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+
+model = {
+    "param": "/root/preset/model/yolo2_20class_awnn.param",
+    "bin": "/root/preset/model/yolo2_20class_awnn.bin"
+}
+options = {
+    "model_type":  "awnn",
+    "inputs": {
+        "input0": (224, 224, 3)
+    },
+    "outputs": {
+        "output0": (7, 7, (1+4+20)*5)
+    },
+    "mean": [127.5, 127.5, 127.5],
+    "norm": [0.0078125, 0.0078125, 0.0078125],
+}
+labels = ['飞机', '自行车', '鸟', '船', '瓶子', '公共汽车', '汽车', '猫', '椅子', '牛', '餐桌', '狗', '马', '摩托车', '人', '盆栽', '羊', '沙发', '火车', '电视监视器']
+#labels = ['plane', 'bicycle', 'bird', 'ship', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'table', 'dog', 'horse', 'motobike', 'human', 'Pot plant', 'sheep', 'sofa', 'train', 'tv']
+anchors = [5.4, 5.38, 1.65, 2.09, 0.8, 1.83, 2.45, 4.14, 0.46, 0.8]
+m = nn.load(model, opt=options)
+yolo2_decoder = decoder.Yolo2(len(labels), anchors, net_in_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]), net_out_size=(7, 7))
+
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+
+
+canvasImg = image.new(size = (240, 320))
+while True:
+    img_objectrecognition = lcdRotation(camera.capture(),CAMERAROTATE)
+    img_objectrecognition = img_objectrecognition.crop(0, 0,224, 224)
+    out = m.forward(img_objectrecognition.tobytes(), quantize=True, layout="hwc")
+    boxes, probs = yolo2_decoder.run(out, nms=0.3, threshold=0.3, img_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]))
+    if len(boxes):
+        for boxesi, box in enumerate(boxes):
+            boxes[boxesi].append(probs[boxesi])
+    if len(boxes):
+        for i in (boxes):
+            img_objectrecognition.draw_string(10,0, (str(str(labels[i[4][0]])) + str(round(i[4][1][i[4][0]]*100, 2))), scale = 1, color = (255,0,0) , thickness = 1)
+            img_objectrecognition.draw_rectangle(i[0],i[1], int(i[0]+i[2]),int(i[1]+i[3]), color=(255,0,0), thickness=1)
+    else:
+        img_objectrecognition.draw_string(10,0, "Not recognize any object", scale = 1, color = (255,0,0) , thickness = 1)
+    if ScreenOrientation:
+        img_objectrecognitionVER = img_objectrecognition.crop(0,0,240,320)
+        img_objectrecognitionVER = img_objectrecognitionVER.rotate(-90, adjust=1)
+        display.show(img_objectrecognitionVER)
+    else:
+        canvasImg.draw_image(img_objectrecognition,48,8)
+        canvasImg.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+        display.show(canvasImg)

+ 76 - 0
backup/preset/app/18_edgeDetection.py

@@ -0,0 +1,76 @@
+#!/usr/bin/env python
+#version    :       2023.04.07
+#language   :       ch
+from maix import camera
+from maix import display
+
+from maix import image
+
+import numpy as np
+
+camera.camera.config(size=(240,320))
+
+ScreenOrientation = False
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+
+class Edge:
+    model = {
+        "param": "/root/preset/model/sobel_int8.param",
+        "bin": "/root/preset/model/sobel_int8.bin"
+    }
+    input_size = (224, 224, 3)
+    output_size = (222, 222, 3)
+    options = {
+        "model_type":  "awnn",
+        "inputs": {
+            "input0": input_size
+        },
+        "outputs": {
+            "output0": output_size
+        },
+        "mean": [127.5, 127.5, 127.5],
+        "norm": [0.0078125, 0.0078125, 0.0078125],
+    }
+    def __init__(self):
+        from maix import nn
+        print("-- load model:", self.model)
+        self.model = nn.load(self.model, opt=self.options)
+        print("-- load ok")
+    def __del__(self):
+        del self.model
+
+m = Edge()
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+
+
+canvas = image.new(size = (320, 240))
+while True:
+    img_edgedetection = lcdRotation(camera.capture(),CAMERAROTATE)
+    img_edgedetection = img_edgedetection.resize(224, 224, padding = 0)
+    out = m.model.forward(img_edgedetection, quantize=True, layout="hwc")
+    out = out.astype(np.float32).reshape(m.output_size)
+    out = (np.ndarray.__abs__(out) * 255 / out.max()).astype(np.uint8)
+    data = out.tobytes()
+    edgeModel = img_edgedetection.load(data,(222, 222), mode="RGB")
+    # canvas = edgeModel
+    if ScreenOrientation:
+        canvasVER = canvas.crop(0,0,240,320)
+        canvasVER = canvasVER.rotate(-90, adjust=1)
+        display.show(canvasVER)
+    else:
+        canvas.draw_image(edgeModel,48,8)
+        canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+        display.show(canvas)

+ 72 - 0
backup/preset/app/19_handWrittenDigiRecognition.py

@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#version    :       2023.04.07
+#language   :       ch
+from maix import camera
+from maix import display
+
+from maix import image
+
+from maix import nn
+from maix.nn import decoder
+
+camera.camera.config(size=(240,320))
+
+ScreenOrientation = False
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+
+
+
+class Number_recognition:
+    mdsc_path = "/root/preset/model/Number.mud"
+    labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
+    anchors = [1.0, 5.0, 1.35, 5.42, 0.49, 2.55, 0.86, 3.75, 0.65, 4.38]
+
+    def __init__(self):
+        self.model = nn.load(self.mdsc_path)
+        self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
+    def __del__(self):
+        del self.model
+        del self.decoder
+    def cal_fps(self ,start , end):
+        one_second = 1
+        one_flash = end - start
+        fps = one_second / one_flash
+        return  fps
+
+number_recognition = Number_recognition()
+canvasImg = image.new(size = (240, 320))
+while True:
+    img_mnist = lcdRotation(camera.capture(),CAMERAROTATE)
+    img_mnist = img_mnist.resize(224, 224, padding = 0)
+    out = number_recognition.model.forward(img_mnist, quantize=1, layout = "hwc")
+    boxes, probs = number_recognition.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
+    if len(boxes):
+        for boxesi, box in enumerate(boxes):
+            boxes[boxesi].append(probs[boxesi])
+    if len(boxes):
+        for i in (boxes):
+            img_mnist.draw_string(i[0],i[1], (str(number_recognition.labels[i[4][0]]) + str(str(":") + str(round(i[4][1][i[4][0]]*100, 2)))), scale = 1, color = (255,0,0) , thickness = 1)
+            img_mnist.draw_rectangle(i[0],i[1], int(i[0] + i[2]),int(i[1] + i[3]), color=(255,0,0), thickness=1)
+    if ScreenOrientation:
+        img_mnistVER = img_mnist.crop(0,0,240,320)
+        img_mnistVER = img_mnistVER.rotate(-90, adjust=1)
+        display.show(img_mnistVER)
+    else:
+        canvasImg.draw_image(img_mnist,48,8)
+        canvasImg.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+        display.show(canvasImg)

+ 105 - 0
backup/preset/app/20_carLicensePlateRecognition.py

@@ -0,0 +1,105 @@
+#!/usr/bin/env python
+#version    :       2023.04.07
+#language   :       ch
+from time import time
+
+ScreenOrientation = False
+
+class LPR:
+    loc_model_path = '/root/preset/model/loc.mud'
+    reg_model_path = '/root/preset/model/reg.mud'
+    chars =[ "皖", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑",
+                    "苏", "浙", "京", "闽", "赣", "鲁", "豫", "鄂", "湘" , "粤",
+                    "桂", "琼", "川", "贵", "云", "藏", "陕", "甘", "青" , "宁",
+                    "新", "警", "学", "A"  , "B" ,  "C" ,  "D" ,  "E" ,  "F"  ,  "G",
+                    "H" ,   "J" ,  "K" ,  "L" , "M" , "N" ,  "P" ,  "Q" ,  "R" , "S",
+                    "T" ,  "U" ,  "V" , "W", "X"  , "Y" , "Z" , "0" , "1", "2", "3",
+                    "4", "5", "6", "7", "8", "9", "-"]
+
+    variances = [0.1, 0.2]
+    steps = [8, 16, 32]
+    min_sizes = [12, 24, 48, 96, 192, 320]
+
+    def __init__(self) -> None:
+        from maix import nn
+        self.loc_model = nn.load(self.loc_model_path , opt = None)
+        self.reg_model = nn.load(self.reg_model_path , opt = None)
+
+        from maix.nn import decoder
+        self.loc_decoder = decoder.license_plate_location([224,224] , self.steps , self.min_sizes, self.variances)
+        self.reg_decoder  = decoder.CTC((1,68,18))
+
+    def __del__(self):
+        del self.loc_model
+        del self.loc_decoder
+
+    def cal_fps(self ,start , end):
+        one_second = 1
+        one_flash = end - start
+        fps = one_second / one_flash
+        return  fps
+
+    def  draw_fps(self,img , fps):
+        img.draw_string(0, 0 ,'FPS :'+str(fps), scale=1,color=(255, 0, 255), thickness=1)
+
+    def draw_string(self , img , x , y , string , color):
+        img.draw_string( x , y , string ,color = color)
+
+    def draw_paste(self , src ,dst):
+        src.paste(dst , 0 , 0)
+
+    def draw_rectangle(self,img, box):
+        img.draw_rectangle(box[0], box[1], box[2], box[3],color=(230 ,230, 250), thickness=2)
+
+    def draw_point(self,img,landmark):
+        for i in range(4):
+            x = landmark[2 * i ]
+            y = landmark[2 * i + 1]
+            img.draw_rectangle(x-2,y-2, x+2,y+2,color= (193 ,255 ,193), thickness =-1)
+
+    def process(self,input):
+        loc_out = self.loc_model.forward(input, quantize=1, layout = "chw") # retinaface decoder only support chw layout
+        boxes , landmarks = self.loc_decoder.run(loc_out, nms = 0.2 ,score_thresh = 0.7 , outputs_shape =[[1,4,2058],[1,2,2058],[1,8,2058]])
+
+        for i,box in enumerate(boxes):
+
+            landmark = landmarks[i][:6]
+            reg_in  = input.crop_affine(landmark , 94 , 24)
+            reg_out = self.reg_model.forward(reg_in ,  quantize=1, layout = "chw")
+
+            LP_number = self.reg_decoder.run(reg_out)
+            string_LP = ''
+            for id in LP_number:
+                string_LP += self.chars[id]
+
+            self.draw_string(input , box[0], box[1] , string_LP  ,color=(225,0,0))
+            self.draw_paste(input , reg_in)
+            self.draw_rectangle(input,box)
+            self.draw_point(input , landmarks[i])
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+def main():
+    from maix import display, camera , image
+    image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+    app  = LPR()
+    
+    canvasImg = image.new(size = (240, 320))
+    while True:
+        img = lcdRotation(camera.capture(),CAMERAROTATE).crop(0, 0,224, 224)
+        app.process(img)
+        canvasImg.draw_image(img,48,8)
+        canvasImg.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+        display.show(canvasImg)
+        # break
+main()

+ 66 - 0
backup/preset/app/21_maskDetection.py

@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#version    :       2023.04.07
+#language   :       ch
+from time import time
+from maix import display, camera,image
+
+ScreenOrientation = False
+class Mask:
+    mud_path = "/root/preset/model/mask_int8.mud"
+    labels = ["no wear","wear"]
+    anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
+
+    def __init__(self) -> None:
+        from maix import nn
+        self.model = nn.load(self.mud_path)
+        from maix.nn import decoder
+        self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
+
+    def __del__(self):
+        del self.model
+        del self.decoder
+
+    def cal_fps(self ,start , end):
+        one_second = 1
+        one_flash = end - start
+        fps = one_second / one_flash
+        return  fps
+
+    def draw_rectangle_with_title(self ,img, box, disp_str , fps ):
+        img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
+        img.draw_string(box[0], box[1]+ box[3] ,disp_str, scale=1,color=(0, 0, 255), thickness=1)
+        img.draw_string(0, 0 ,'FPS :'+str(fps), scale=2 ,color=(0, 0, 255), thickness=1)
+
+    def process(self,input):
+        t =  time()
+        out = self.model.forward(input, quantize=1, layout = "hwc")
+        boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.6, img_size=(224,224))
+        for i, box in enumerate(boxes):
+            class_id = probs[i][0]
+            prob = probs[i][1][class_id]
+            disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100)
+            fps = self.cal_fps(t, time())
+            self.draw_rectangle_with_title(input, box, disp_str, fps)
+
+app = Mask()
+
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+canvasImg = image.new(size = (320, 240))
+while True:
+    img = lcdRotation(camera.capture(),CAMERAROTATE).crop(0, 0,224, 224)
+    app.process(img)
+    canvasImg.draw_image(img,48,8)
+    canvasImg.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+    display.show(canvasImg)

+ 76 - 0
backup/preset/app/22_gestureRecognition.py

@@ -0,0 +1,76 @@
+#!/usr/bin/env python
+#version    :       2023.04.07
+#language   :       ch
+from time import time
+from maix import image
+
+ScreenOrientation = False
+
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+class Hand:
+    mud_path = "/root/preset/model/hand_int8.mud"
+    labels = ["0","1","2","3","4","5"]
+    anchors = [3.78, 5.81, 3.97, 3.98, 4.05, 4.98, 4.81, 5.41, 2.91, 4.53]
+
+    def __init__(self) -> None:
+        from maix import nn
+        self.model = nn.load(self.mud_path)
+        from maix.nn import decoder
+        self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
+
+    def __del__(self):
+        del self.model
+        del self.decoder
+
+    def cal_fps(self ,start , end):
+        one_second = 1
+        one_flash = end - start
+        fps = one_second / one_flash
+        return  fps
+
+    def draw_rectangle_with_title(self ,img, box, disp_str , fps ):
+        img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
+        img.draw_string(box[0], box[1]+ box[3] ,disp_str, scale=1,color=(0, 0, 255), thickness=2)
+        img.draw_string(0, 0 ,'FPS :'+str(fps), scale=2 ,color=(0, 0, 255), thickness=2)
+
+    def process(self,input):
+        t =  time()
+        out = self.model.forward(input, quantize=1, layout = "hwc")
+        boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.6, img_size=(224,224))
+        for i, box in enumerate(boxes):
+            class_id = probs[i][0]
+            prob = probs[i][1][class_id]
+            disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100)
+            fps = self.cal_fps(t, time())
+            self.draw_rectangle_with_title(input, box, disp_str, fps)
+
+
+
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+
+def main():
+    from maix import display, camera,image
+    global Hand
+    app =  Hand()
+    canvasImg = image.new(size = (320, 240))
+    while True:
+        img = lcdRotation(camera.capture(),CAMERAROTATE).crop(0, 0,224, 224)
+        app.process(img)
+        canvasImg.draw_image(img,48,8)
+        canvasImg.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+        display.show(canvasImg)
+
+main()

+ 71 - 0
backup/preset/app/23_fingerGuessing.py

@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#version    :       2023.04.04
+#language   :       en
+from time import time
+from maix import image
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+ScreenOrientation = False
+class Mora:
+    mud_path = "/root/preset/model/mora_int8.mud"
+    labels = ["Scissors", "Stone" ,"Paper"]
+    anchors = [3.23, 3.25, 1.47, 1.55, 5.09, 5.33, 4.03, 4.28, 2.12, 2.56]
+
+    def __init__(self) -> None:
+        from maix import nn
+        self.model = nn.load(self.mud_path)
+        from maix.nn import decoder
+        self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
+
+    def __del__(self):
+        del self.model
+        del self.decoder
+
+    def cal_fps(self ,start , end):
+        one_second = 1
+        one_flash = end - start
+        fps = one_second / one_flash
+        return  fps
+
+    def draw_rectangle_with_title(self ,img, box, disp_str , fps ):
+        img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
+        img.draw_string(box[0], box[1] ,disp_str, scale=1,color=(222, 0, 3), thickness=2)
+        #img.draw_string(0, 0 ,'FPS :'+str(fps), scale=2 ,color=(0, 0, 255), thickness=2)
+
+    def process(self,input):
+        t =  time()
+        out = self.model.forward(input, quantize=1, layout = "hwc")
+        boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.5, img_size=(224,224))
+        for i, box in enumerate(boxes):
+            class_id = probs[i][0]
+            prob = probs[i][1][class_id]
+            disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100)
+            fps = self.cal_fps(t, time())
+            self.draw_rectangle_with_title(input, box, disp_str, fps)
+
+
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+def main():
+    from maix import display, camera,image
+    app = Mora()
+    canvasImg = image.new(size = (320, 240))
+    while True:
+        img = lcdRotation(camera.capture(),CAMERAROTATE).crop(0, 0,224, 224)
+        app.process(img)
+        canvasImg.draw_image(img,48,8)
+        canvasImg.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+        display.show(canvasImg)
+
+main()

+ 189 - 0
backup/preset/app/24_connectWiFi.py

@@ -0,0 +1,189 @@
+#!/usr/bin/env python
+#version    :       2023.05.05
+#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
+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)
+ScreenOrientation = False
+image.load_freetype("/root/preset/fonts/simhei.ttf")
+camera.camera.config(size=(240,320))
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+def getPublicIp():
+    import requests
+    url = 'https://myip.ipip.net'
+    res = requests.get(url,verify=False).text.split(" ")
+    return res[1][3:]
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+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 = lcdRotation(camera.capture(),CAMERAROTATE)
+    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, "正在连接WIFI,请等待...", 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连接成功!"
+                # canvas.draw_string(10,80, "路由器公网IP:" + PublicIp, scale = 1.5, color = (0,0,0), thickness = 1)
+                canvas.draw_string(10,110, "局域网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 = "正在连接WIFI,请等待..."
+                        runConnectSig= False
+                    else:
+                        passwordInfo = ""
+                        ssidInfo = ""
+                        connectText = "WIFI连接失败!"
+                        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名:"+ssidInfo, scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
+            canvas.draw_string(int(X) , int(Y - 25) , "密码:"+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)
+    

+ 220 - 0
backup/preset/app/25_aboutCocoPi.py

@@ -0,0 +1,220 @@
+#!/usr/bin/env python
+#version    :       2023.04.07
+#language   :       ch
+from maix import *
+import socket
+import os
+import sys
+sys.path.append('/root/')
+import http.client
+from CocoPi import BUTTON
+import time
+
+key_A = BUTTON(14)
+key_B = BUTTON(8)
+key_C = BUTTON(13)
+key_D = BUTTON(7)
+#image.load_freetype("/root/preset/fonts/JetBrainsMono-Bold-7.ttf")
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+
+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
+
+def getPublicIp():
+    import requests
+    url = 'https://myip.ipip.net'
+    res = requests.get(url).text.split(" ")
+    return res[1][3:]
+
+PublicIp=""
+PrivateIP=""
+
+baseInfo=[
+        "--------------------------------------",
+        "     --- 设计 --- 创造 --- 分享 ---",
+        "--------------------------------------",
+        "                       系统信息         ",
+        "***************************",
+        "系统名称:          CocoPi Linux",
+        "系统版本:              2023.06.15",
+        "--------------------------------------",
+        "  用户名:                ",
+        "--------------------------------------",
+        "          网络信息         ",
+        "***************************",
+        " ",
+        " ",
+        " ",
+        " ",
+        "--------------------------------------",
+        "Python 版本                        3.8.5",
+        "***************************",
+        "Python 包信息                 版本号",
+        "***************************",
+        "av                                                9.2.0",
+        "beautifulsoup4                4.11.1",
+        "certifi                              2020.6.20",
+        "cffi                                            1.14.3",
+        "chardet                                    3.0.4",
+        "click                                           7.1.2",
+        "defusedxml                           0.6.0",
+        "et-xmlfile                                1.0.1",
+        "evdev                                        1.4.0",
+        "Flask                                         1.1.2",
+        "Flask-Login                           0.5.0",
+        "gpiod                                        1.4.0",
+        "html5lib                                      1.1",
+        "idna                                            2.10",
+        "itsdangerous                        1.1.0",
+        "jdcal                                          1.4.1",
+        "jieba                                       0.42.1",
+        "Jinja2                                    2.11.2",
+        "lxml                                           4.5.2",
+        "maixpy3                                  0.5.4",
+        "MarkupSafe                           1.1.1",
+        "numpy                                   1.19.2",
+        "openpyxl                                 3.0.5",
+        "Pillow                                        7.2.0",
+        "pip                                           20.1.1",
+        "plumbum                               1.6.9",
+        "ply                                                3.11",
+        "pyasn1                                     0.4.8",
+        "PyAudio                                0.2.11",
+        "pycparser                                 2.20",
+        "pylibmodbus                        0.5.0",
+        "pyserial                                        3.4",
+        "qrcode                                          6.1",
+        "requests                               2.24.0",
+        "rpyc                                            5.0.1",
+        "rsa                                                  4.6",
+        "schedule                                0.6.0",
+        "setuptools                           47.1.0",
+        "six                                            1.15.0",
+        "smbus2                                   0.4.2",
+        "soupsieve                               2.3.1",
+        "spidev                                           3.5",
+        "SQLAlchemy                       1.3.18",
+        "urllib3                                  1.25.10",
+        "websocket-client                1.5.1",
+        "Werkzeug                                1.0.1",
+        "zbarlight                                      3.0",
+        "--------------------------------------",
+    ]
+
+ownerName=""
+try:
+    with open( '/root/user/text/owner.txt', 'r' ) as f:
+        ownerName=f.read()
+except:
+    ownerName="N/A"
+baseInfo[8]="{: <28}".format("用户名:     "+ownerName)
+canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+canvas.draw_string(12 , 100 , "检查WIFI连接状态...", scale = 1, color = (255,255,255), thickness = 2)
+display.show(canvas)
+checkInternet=False
+try:
+    if getWifiConnectState()["state"]==True:
+        PublicIp=getPublicIp()
+        PrivateIP=getPrivateIp()
+        baseInfo[12]="{: <28}".format("路由器公网IP:"+PublicIp)
+        baseInfo[13]="{: <28}".format("局域网IP:"+PrivateIP)
+        baseInfo[14]="{: <28}".format("WIFI热点名:"+getWifiConnectState()["AP"])
+        baseInfo[15]="{: <28}".format("WIFI信号强度:"+getWifiConnectState()["RSSI"])
+    else:
+        PublicIp="N/A"
+        PrivateIP="N/A"
+        baseInfo[12]="{: <28}".format("路由器公网IP:    N/A")
+        baseInfo[13]="{: <28}".format("局域网IP:   N/A")
+        baseInfo[14]="{: <28}".format("WIFI热点名:    N/A")
+        baseInfo[15]="{: <28}".format("WIFI RSSI:   N/A")
+except:
+    PublicIp="N/A"
+    PrivateIP="N/A"
+    baseInfo[12]="{: <28}".format("路由器公网IP:    N/A")
+    baseInfo[13]="{: <28}".format("局域网IP:   N/A")
+    baseInfo[14]="{: <28}".format("WIFI热点名:    N/A")
+    baseInfo[15]="{: <28}".format("WIFI信号强度:   N/A")
+    pass
+
+xPosition=48
+yPosition=160
+ySpeedMax=12
+yDirection=0
+yRealSpeed=0
+totalNum=0
+while True:
+    canvas.clear()
+    canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+    if key_D.is_pressed():
+        yDirection=-1
+    elif key_B.is_pressed():
+        yDirection=1
+    else:
+        yDirection=0
+    if yDirection==1:
+        if yRealSpeed<(ySpeedMax*yDirection):
+            yRealSpeed=yRealSpeed+1
+        else:
+            yRealSpeed=yRealSpeed
+    elif yDirection==-1:
+        if yRealSpeed>(ySpeedMax*yDirection):
+            yRealSpeed=yRealSpeed-1
+        else:
+            yRealSpeed=yRealSpeed
+    else:
+        if yRealSpeed>0:
+            yRealSpeed=yRealSpeed-1
+        elif yRealSpeed<0:
+            yRealSpeed=yRealSpeed+1
+        else:
+            yRealSpeed=0
+    yPosition=yPosition+yRealSpeed
+    if yPosition>160:
+        yPosition=160
+    elif yPosition<-900:
+        yPosition=-900
+    else:
+        yPosition=yPosition
+    #canvas.draw_string(60 , 8 , "yPosition:"+str(yPosition)+"yRealSpeed:"+str(yRealSpeed), scale = 1, color = (255,255,255), thickness = 1)
+    canvas.draw_image(image.open("/root/preset/img/cocorobo_152146.png"),xPosition+40 , yPosition-144,alpha=1)
+    canvas.draw_image(image.open("/root/preset/img/cocorobo_text.jpg"),xPosition+32 , yPosition-20,alpha=1)
+
+    for i in range(len(baseInfo)):
+        if  (yPosition+(i)*16)<260 and (yPosition+(i)*16)>-20:
+            canvas.draw_string(xPosition , yPosition+i*16 , baseInfo[i], scale = 1, color = (255,255,255), thickness = 1)
+        else:
+            pass
+    canvas.draw_image((image.open("/root/preset/img/left_ffffff_16x16.png")).rotate(90, adjust=0),6,6,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/left_ffffff_16x16.png")).rotate(270, adjust=0),6,216,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+    display.show(canvas)

+ 101 - 0
backup/preset/app/26_internetCamera.py

@@ -0,0 +1,101 @@
+#!/usr/bin/env python
+#version    :       2023.04.04
+#language   :       ch
+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
+
+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()
+
+
+
+camera.camera.config(size=(240, 320))
+qrShowState=0
+while True:
+    buttonDetect()
+    
+    img_backdrop = image.new(size=(320,240),color=(0, 0, 0))    #创建背景画布
+    camera_img = camera.capture()    #从摄像头中获取一张图像
+    camera_img_capture = camera_img.crop(0, 0, 240, 320).rotate(90,adjust=1)        #截取图像
+    jpg = utils.rgb2jpg(camera_img_capture.convert("RGB").tobytes(), 320, 240)
+    queue.put(mjpg.BytesImage(jpg))
+    img_backdrop.draw_image(camera_img_capture)
+    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)         #将图像显示出来

+ 70 - 0
backup/preset/app/27_internetWeatherPrediction.py

@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#version    :       2023.04.03
+#language   :       en
+from maix import display
+from maix import image
+from maix import camera
+import bs4
+import ssl
+import json
+ssl._create_default_https_context = ssl._create_unverified_context
+import http.client
+camera.camera.config(size=(240,320))
+
+ScreenOrientation = False
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+
+def get_content(city):
+    weather_list = []
+    try:        
+        conn = http.client.HTTPSConnection("weather.visualcrossing.com")
+        conn.request("GET", "/VisualCrossingWebServices/rest/services/timeline/"+city+"?unitGroup=us&include=days&key=XGMGVZSNH3RFJWNQYL4Z5THYS&contentType=json")
+        res = conn.getresponse()
+        data = res.read().decode("utf-8")
+        # print(json.loads(data)["days"],'1111111111111111111')
+        for i in json.loads(data)["days"]:
+            # print(i)
+            weather_list.extend([{"D":i["datetime"],"W":i["conditions"],
+            "T":str(round((i["tempmax"]-32)/1.8))+"/"+str(round((i["tempmin"]-32)/1.8))+"℃"}])
+    # weather_list = data.decode("utf-8")["days"]
+    except:
+        print('no result')
+    # with open("/root/wResult.txt","w") as f:
+    #     f.write(data.decode("utf-8"))
+    # print(weather_list)
+    return weather_list
+
+# https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/forecast?locations=Herndon,VA,20170&aggregateHours=24&unitGroup=us&shortColumnNames=false&contentType=csv&key=YOURAPIKEY
+
+canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+canvas.draw_string(4 , 100 , "正在检查网络连接状态...", scale = 1, color = (255,255,255), thickness = 2)
+display.show(canvas)
+weather_all1 = get_content('shenzhen')
+weather_all2 = get_content('HongKong')
+weather_all3 = get_content('Macau')
+weather_all4 = get_content('Guangzhou')
+while True:
+    canvas.clear()
+    try:
+        canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+        #canvas.draw_string(2,20, ("Day:"+str(weather_all1[0]["D"])), scale = 1, color = (255,255,255) , thickness = 1)
+        canvas.draw_string(2,20, ("气象变化:"+str(weather_all1[0]["W"])+"  ,温度:"+str(weather_all1[0]["T"]))[:-1]+"℃", scale = 1, color = (255,255,255) , thickness = 1)
+        canvas.draw_string(0,0, "深圳", scale = 1, color = (255,255,255) , thickness = 1)
+        canvas.draw_string(0,60, "香港", scale = 1, color = (255,255,255) , thickness = 1)
+        #canvas.draw_string(2,80, ("Day:"+str(weather_all2[0]["D"])), scale = 1, color = (255,255,255) , thickness = 1)
+        canvas.draw_string(2,80, ("气象变化:"+str(weather_all2[0]["W"])+"  ,温度:"+str(weather_all2[0]["T"]))[:-1]+"℃", scale = 1, color = (255,255,255) , thickness = 1)
+        canvas.draw_string(0,120, "澳门", scale = 1, color = (255,255,255) , thickness = 1)
+        #canvas.draw_string(2,140, ("Day:"+str(weather_all3[0]["D"])), scale = 1, color = (255,255,255) , thickness = 1)
+        canvas.draw_string(2,140, ("气象变化:"+str(weather_all3[0]["W"])+"  ,温度:"+str(weather_all3[0]["T"]))[:-1]+"℃", scale = 1, color = (255,255,255) , thickness = 1)
+        canvas.draw_string(0,180, "广州", scale = 1, color = (255,255,255) , thickness = 1)
+        #canvas.draw_string(2,200, ("Day:"+str(weather_all4[0]["D"])), scale = 1, color = (255,255,255) , thickness = 1)
+        canvas.draw_string(2,200, ("气象变化:"+str(weather_all4[0]["W"])+"  ,温度:"+str(weather_all4[0]["T"]))[:-1]+"℃",scale = 1, color = (255,255,255) , thickness = 1)
+    except:
+        canvas.draw_string(20,80, "获取天气信息失败!", scale = 1, color = (255,255,255) , thickness = 1)
+    if ScreenOrientation:
+        canvasVER = canvas.crop(0,0,240,320)
+        canvasVER = canvasVER.rotate(-90, adjust=1)
+        display.show(canvasVER)
+    else:
+        canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),288,216,alpha=1)
+        display.show(canvas)

+ 142 - 0
backup/preset/app/28_internetTimeClock.py

@@ -0,0 +1,142 @@
+#!/usr/bin/env python
+#version    :       2023.04.04
+#language   :       en
+
+import os
+from maix import display
+
+from maix import image
+
+from maix import camera
+import sys
+sys.path.append('/root/')
+import time
+import http.client
+import json
+import requests
+import bs4
+from datetime import datetime
+from CocoPi import AHT20
+
+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
+
+camera.camera.config(size=(240,320))
+
+ScreenOrientation = False
+
+
+def getNetworkDate():
+    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)
+        sys.exit()
+    except:
+        pass
+
+def get_html(url):
+    '''
+    封装请求
+    '''
+    headers = {
+        'User-Agent':
+        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
+        'ContentType':
+        'text/html; charset=utf-8',
+        'Accept-Encoding':
+        'gzip, deflate, sdch',
+        'Accept-Language':
+        'zh-CN,zh;q=0.8',
+        'Connection':
+        'keep-alive',
+    }
+    try:
+        htmlcontet = requests.get(url, headers=headers, timeout=30)
+        htmlcontet.raise_for_status()
+        htmlcontet.encoding = 'utf-8'
+        return htmlcontet.text
+    except:
+        return " 请求失败 "
+
+def get_content(url):
+    '''
+    抓取页面天气数据
+    '''
+    weather_list = []
+    html = get_html(url)
+    soup = bs4.BeautifulSoup(html, 'lxml')
+    content_ul = soup.find('div', class_='t').find('ul', class_='clearfix').find_all('li')
+
+    for content in content_ul:
+        try:
+            weather = {}
+            weather['day'] = content.find('h1').text
+            weather['temperature'] = content.find(
+                'p', class_='tem').span.text + content.find(
+                    'p', class_='tem').em.text
+            weather_list.append(weather)
+        except:
+            print('查询不到')
+    print(weather_list)
+    return weather_list
+
+def getCurrent_data(type):
+    now = datetime.now()
+    return now.strftime("%"+type+"")
+
+aht20 = AHT20(2)
+
+def screenShow(inputImg,rotationAngle):
+    #global img_drop
+
+    if rotationAngle==90 or rotationAngle == 270:
+        screenCapture=inputImg.crop(0,0,240,320)
+    else:
+        screenCapture=inputImg.crop(0,0,320,240)
+    canvas_screenShow = screenCapture.rotate(-rotationAngle,adjust=1)
+    display.show(canvas_screenShow)
+
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+canvas.draw_string(48 , 100 , "正在检查网络连接状态...", scale = 1, color = (209,72,54), thickness = 1)
+display.show(canvas)
+
+#os.system("wifi_disconnect_ap_test")
+#os.system('wifi_connect_chinese_ap_test "CocoRobo_SZ" "cocorobo2019"')
+#CLIENT = ntplib.NTPClient()
+#RESPONSE = CLIENT.request('127.0.0.1')
+getNetworkDate_noexit()
+canvas = image.new(size = (320, 240))
+getNetworkDate()
+weather = get_content('http://www.weather.com.cn/weather1d/101280601.shtml')
+image.load_freetype("/root/preset/fonts/DigitalNumbers-Regular.ttf")
+while True:
+    time.sleep(1)
+    canvas.clear()
+    canvas.draw_string(10,10, (''.join([str(x) for x in [getCurrent_data("Y"), "-", getCurrent_data("m"), "-", getCurrent_data("d"), " "]])), scale = 2, color = (111,195,223) , thickness = 1)
+    canvas.draw_string(25,85, (''.join([str(x) for x in [getCurrent_data("H"), "-", getCurrent_data("M"), "-", getCurrent_data("S")]])), scale = 3, color = (111,195,223) , thickness = 1)
+    canvas.draw_string(190,190, str((str(int((aht20.get_humidity()))))) + str("%RH"), scale = 2, color = (111,195,223) , thickness = 1)
+    canvas.draw_string(30,190, (str(weather[1].get("temperature"))), scale = 2, color = (111,195,223) , thickness = 1)
+    screenShow(canvas,0)
+

+ 53 - 0
backup/preset/app/29_environmentDetection.py

@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+#version    :       2023.04.04
+#language   :       ch
+import sys
+import time
+from maix import display,image,camera
+sys.path.append('/root/')
+from CocoPi import AHT20
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+
+class v83x_ADC():
+    def __init__(self, addr=b"0x05070080") -> None:
+        self.addr = addr
+        self.path = "/sys/class/sunxi_dump/dump"
+        self.file = open(self.path, "wb+")
+        self.last = self.value()
+    def __del__(self):
+        try:
+            if self.file:
+                self.file.close()
+                del self.file
+        except Exception as e:
+            pass
+    def value(self):
+        self.file.write(b"0x05070080")
+        self.file.seek(0)
+        return int(self.file.read()[:-1], 16)
+
+v831_adc0 = v83x_ADC()
+
+aht20 = AHT20(2)    #创建温湿度传感器对象
+def aht20Test():
+    global aht20,img_backdrop
+    from maix import display
+    h=round(aht20.get_humidity()+10,2)
+    t=round(aht20.get_temperature()-15,2)
+    img_backdrop.draw_string(16, 108, "原始湿度值:"+str(h)+"RH%", scale = 1.0,color = (0, 255, 0), thickness = 1)
+    img_backdrop.draw_string(16, 132, "原始温度值:"+str(t)+"℃", scale = 1.0,color = (0, 255, 0), thickness = 1)
+    
+
+
+camera.camera.config(size=(240, 320))
+img_backdrop = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+
+while True:
+    img_backdrop.clear()
+    img_backdrop = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
+    aht20Test()
+    v=v831_adc0.value()
+    img_backdrop.draw_string(16, 84, "原始光照强度值:"+str(v), scale = 1.0,color = (0, 255, 0), thickness = 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)
+    time.sleep(0.5)

+ 295 - 0
backup/preset/app/30_train_data_collect.py

@@ -0,0 +1,295 @@
+#!/usr/bin/env python
+#version    :       2023.06.01
+#language   :       ch
+#haraware   :       pi
+
+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 json
+import requests
+
+key_A = BUTTON(14)
+key_B = BUTTON(8)
+key_C = BUTTON(13)
+key_D = BUTTON(7)
+ScreenOrientation = False
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+camera.camera.config(size=(240,320))
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+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
+
+name = ''
+host = ''
+isCollect = False
+image_num = 0
+save_path = ""
+startConnect=False
+
+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 = ""
+startConnectWifi=False
+wifiConnectState = False
+# PublicIp=""
+PrivateIP=""
+runConnectSig=True
+connectSuccessSig=False
+while True:
+    canvas = lcdRotation(camera.capture(),CAMERAROTATE)
+    IP = getPrivateIp()
+    if ssidInfo!="" and passwordInfo!="":
+        startConnectWifi=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, "正在连接WIFI,请等待...", scale = 1.5, color = (0,0,0), thickness = 1)
+        display.show(canvas)
+    if startConnectWifi==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)
+                startConnectWifi= 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连接成功!"
+                canvas.draw_string(10,50, "WiFi连接成功!", 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=""
+                display.show(canvas)
+                time.sleep(3)
+                canvas.clear()
+                
+                break
+            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)
+                    startConnectWifi= False
+                    connectText = ""
+                    checkConnectState = False
+                    connectSuccessSig = False
+                    wifiConnectState = False
+                    runConnectSig== True
+                    passwordInfo = ""
+                    ssidInfo = ""
+                else:
+                    if runConnectSig== True:
+                        connectText = "正在连接WIFI,请等待..."
+                        runConnectSig= False
+                    else:
+                        passwordInfo = ""
+                        ssidInfo = ""
+                        connectText = "WIFI连接失败!"
+                        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名:"+ssidInfo, scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
+            canvas.draw_string(int(X) , int(Y - 25) , "密码:"+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)
+  
+while True:
+    canvas.clear()
+    canvas = lcdRotation(camera.capture(),CAMERAROTATE)
+    # IP = extract_ip()
+    if str(name) != '' and str(host) != '':
+        startConnect=True
+    if startConnect==True:
+        _COCOCLOUD_SEND_ENDPOINT = "https://" + host.split("//")[1] + "v831_update_code_connect_device"
+        _COCOCLOUD_SEND_DATA = {"DatasetName":"" + str(name) + ""}
+        try:
+            _COCOCLOUD_SEND_REQUEST = requests.post(_COCOCLOUD_SEND_ENDPOINT, json = _COCOCLOUD_SEND_DATA , headers = { "Content-type": "application/json" }, timeout = 60)
+            print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content))
+        except BaseException as e:
+            print(e)
+        pass
+        isCollect = True
+        break
+    else:
+        mks = canvas.find_qrcodes()
+        for mk in mks:
+            #外框数据
+            X = mk['x']
+            Y = mk['y']
+            W = mk['w']
+            H = mk['h']            
+            #二维码信息
+            string = mk['payload']
+            
+            try:
+                codeData = string.split(";")
+                name = codeData[0].split("=")[1]
+                host = codeData[1].split("=")[1]
+            except:
+                pass
+            #画外框
+            canvas.draw_rectangle(X, Y, X + W, Y + H, color=(0, 0, 255), thickness = 2) 
+            #打印信息
+            canvas.draw_string(int(X) , int(Y - 35) , str(string), scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
+
+    canvas.draw_string(0, 0 , "扫描二维码来访问图片标注服务器", scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
+    canvas.draw_string(0, 20 , " ", scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
+    # canvas.draw_image((image.open("/root/preset/img/camera_ff0000_24x24.png")).rotate(0, adjust=0),290,2,alpha=1)
+    canvas.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),290,208,alpha=1)
+        
+    display.show(canvas)
+
+isAlTake = False
+while True:
+    canvas1 = lcdRotation(camera.capture(),CAMERAROTATE)
+    if isCollect:
+        if not isAlTake:
+            if key_C.is_pressed() :
+                while not (key_C.is_pressed() == False):
+                    time.sleep(0.01)
+                image_num = image_num + 1
+                save_path = ''.join([str(x) for x in ["/root/user/img/image", str(image_num), ".jpg"]])
+                canvas1.save(save_path)
+                isAlTake = True
+            canvas1.draw_string(0, 0 , "请拍照来采集图片数据", scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
+            canvas1.draw_image((image.open("/root/preset/img/camera_ff0000_24x24.png")).rotate(0, adjust=0),290,2,alpha=1)
+            canvas1.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),290,208,alpha=1)
+            display.show(canvas1)
+
+        if isAlTake:
+            canvas1.draw_image((image.open(save_path)),0,0)
+            # if key_D.is_pressed() :
+            #     while not (key_D.is_pressed() == False):
+            #         time.sleep(0.01)
+            #     img = open(save_path,'rb')
+            #     data = {"file": img}
+            #     param = {"name": str(name)}
+            #     res = requests.post("https://" + host.split("//")[1] + "v831_upload_image", files=data, data=param)
+            #     print(res.status_code)
+            #     if str(res.status_code) == "200":
+            #         isAlTake = False
+            # if key_C.is_pressed() :
+            #     while not (key_C.is_pressed() == False):
+            #         time.sleep(0.01)
+            #     isAlTake = False
+            img = open(save_path,'rb')
+            data = {"file": img}
+            param = {"name": str(name)}
+            res = requests.post("https://" + host.split("//")[1] + "v831_upload_image", files=data, data=param)
+            print(res.status_code)
+            if str(res.status_code) == "200":
+                isAlTake = False
+            # canvas1.draw_image((image.open("/root/preset/img/upload_ff0000_24x24.png")).rotate(0, adjust=0),5,2,alpha=1)
+            # canvas1.draw_image((image.open("/root/preset/img/cancel_ff0000_24x24.png")).rotate(0, adjust=0),280,2,alpha=1)
+            canvas1.draw_image((image.open("/root/preset/img/exit_ff0000_24x24.png")).rotate(0, adjust=0),290,208,alpha=1)
+            display.show(canvas1)
+
+    display.show(canvas1)

+ 269 - 0
backup/preset/app/31_train_deploy_model.py

@@ -0,0 +1,269 @@
+#!/usr/bin/env python
+#version    :       2023.06.01
+#language   :       ch
+#hardware   :       pi
+
+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 json
+import requests
+
+key_A = BUTTON(14)
+key_B = BUTTON(8)
+key_C = BUTTON(13)
+key_D = BUTTON(7)
+ScreenOrientation = False
+image.load_freetype("/root/preset/fonts/SourceHanSansCN-Regular.otf")
+camera.camera.config(size=(240,320))
+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
+
+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)
+    
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+
+def urldownload(url,filepath=None,filename=None,canvas1=image.new(size = (320, 40))):
+    """
+    下载文件到指定目录
+    :param url: 文件下载的url
+    :param filename: 要存放的目录及文件名,例如:./test.xls
+    :return:
+    """
+    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
+    down_res = requests.get(url,headers=headers,stream=True)
+    chunk_size = 1024 * 1024  # 单次请求最大值
+    content_size = int(down_res.headers['content-length'])  # 内容体总大小
+    data_count = 0
+    with open(filepath,'wb') as file:
+        for data in down_res.iter_content(chunk_size=chunk_size):
+            file.write(data)
+            data_count = data_count + len(data)
+            now_jd = (data_count / content_size) * 100
+            # print("\r 文件下载进度:%d%%(%d/%d) - %s" % (now_jd, data_count, content_size, filename), end=" ")
+            canvas1.clear()
+            canvas1.draw_string(0,0,str("下载中: ") + filename, scale = 1, color = (255, 0, 0), thickness = 2)
+            canvas1.draw_string(0,20 , str("进度: %d%%(%d/%d)" % (now_jd, data_count, content_size)), scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
+            display.show(canvas1)
+            # time.sleep(1)
+
+    # return down_res.code
+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
+
+
+canvas1 = image.new(size = (320, 40))
+ssidInfo = ""
+passwordInfo = ""
+checkConnectState = False
+connectText = ""
+startConnect=False
+param = ''
+bin = ''
+py = ''
+startConnectWifi=False
+wifiConnectState = False
+# PublicIp=""
+PrivateIP=""
+runConnectSig=True
+connectSuccessSig=False
+while True:
+    canvas = lcdRotation(camera.capture(),CAMERAROTATE)
+    IP = getPrivateIp()
+    if ssidInfo!="" and passwordInfo!="":
+        startConnectWifi=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, "正在连接WIFI,请等待...", scale = 1.5, color = (0,0,0), thickness = 1)
+        display.show(canvas)
+    if startConnectWifi==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)
+                startConnectWifi= False
+                connectText = ""
+                checkConnectState = False
+                connectSuccessSig = False
+                wifiConnectState = False
+                runConnectSig== True
+                ssidInfo=""
+                passwordInfo=""
+            if checkConnectState == True:
+                if connectSuccessSig == False:
+                    # PublicIp=getPublicIp()
+                    PrivateIP=getPrivateIp()
+                    connectSuccessSig = True
+                canvas.draw_string(10,50, "WiFi连接成功!", scale = 1.5, color = (0,0,0) , thickness = 1)
+                canvas.draw_string(10,110, "局域网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)
+                display.show(canvas)
+                ssidInfo=""
+                passwordInfo=""
+                time.sleep(3)
+                canvas.clear()
+                break
+            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)
+                    startConnectWifi= False
+                    connectText = ""
+                    checkConnectState = False
+                    connectSuccessSig = False
+                    wifiConnectState = False
+                    runConnectSig== True
+                    passwordInfo = ""
+                    ssidInfo = ""
+                else:
+                    if runConnectSig== True:
+                        connectText = "正在连接WIFI,请等待..."
+                        runConnectSig= False
+                    else:
+                        passwordInfo = ""
+                        ssidInfo = ""
+                        connectText = "WIFI连接失败!"
+                        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名:"+ssidInfo, scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
+            canvas.draw_string(int(X) , int(Y - 25) , "密码:"+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)
+    
+while True:
+    canvas = lcdRotation(camera.capture(),CAMERAROTATE)
+    # IP = extract_ip()
+    if(str(param) != '' and str(bin) != '' and str(py) != ''):
+        startConnect=True
+    if startConnect==True:
+        canvas.clear()
+        time.sleep(5)
+        urldownload("https://" + bin.split("//")[1],"/root/user/model/" + (str(bin).split("newModels/")[1].split("/")[0]) + ".bin",(str(bin).split("newModels/")[1].split("/")[0]) + ".bin",canvas1)
+        urldownload("https://" + param.split("//")[1],"/root/user/model/" + (str(param).split("newModels/")[1].split("/")[0]) + ".param", (str(param).split("newModels/")[1].split("/")[0]) + ".param",canvas1)
+        urldownload("https://" + py.split("//")[1],"/root/" + (str(py).split("newModels/")[1].split("/")[1]),"user_latest_code.py",canvas1)
+        break
+    else:
+        mks = canvas.find_qrcodes()
+        for mk in mks:
+            #外框数据
+            X = mk['x']
+            Y = mk['y']
+            W = mk['w']
+            H = mk['h']            
+            #二维码信息
+            try:
+                string = mk['payload']
+                codeData = json.loads(string)
+                param = codeData['param']
+                bin = codeData['bin']
+                py = codeData['py']
+            except:
+                pass
+            #画外框
+            canvas.draw_rectangle(X, Y, X + W, Y + H, color=(0, 0, 255), thickness = 2) 
+            #打印信息
+            canvas.draw_string(int(X) , int(Y - 35) , str(string), scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
+                
+    canvas.draw_string(0, 0 , "扫描二维码来下载模型", 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),290,208,alpha=1)
+    display.show(canvas)
+
+os.system("ln -sf %s /tmp/event && touch /tmp/start" % "/root/user_latest_code.py")

+ 0 - 0
backup/preset/configInfo.json


+ 26 - 0
backup/preset/server/ccrb.crt

@@ -0,0 +1,26 @@
+-----BEGIN CERTIFICATE-----
+MIIEYjCCA0qgAwIBAgIJAOS8Bh4qCqhBMA0GCSqGSIb3DQEBCwUAMIGGMQswCQYD
+VQQGEwJDTjESMBAGA1UECAwJR3Vhbmdkb25nMREwDwYDVQQHDAhTaGVuemhlbjEV
+MBMGA1UECgwMQ29jb1JvYm8gTFREMRowGAYDVQQDDBFDb2NvUm9ibyBUcnVzdCBD
+QTEdMBsGCSqGSIb3DQEJARYOaXRAY29jb3JvYm8uY2MwHhcNMTgxMjI0MDg1ODIz
+WhcNMjExMDEzMDg1ODIzWjB+MQswCQYDVQQGEwJDTjESMBAGA1UECAwJR3Vhbmdk
+b25nMREwDwYDVQQHDAhTaGVuemhlbjEVMBMGA1UECgwMQ29jb1JvYm8gTFREMRIw
+EAYDVQQDDAlsb2NhbGhvc3QxHTAbBgkqhkiG9w0BCQEWDml0QGNvY29yb2JvLmNj
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvk3cAwel+eWyJXAl9RB9
+rhxQHc4vDr/VshOy157/+jj6rUyDqRpdWh66DBmn429ReXzRsxhu5dhWUfWzztjW
+1pJ1159mC9TTGWWRqCKuVDNXtXq7QYD6apODjpk7U/lpKed4Gf6DWMtGk4BSAJ8g
+Y3k/R/bE6iCQHJLE/yVnWw/tw5P8lKRajUi36JzOKQ6l0cJqa1vFXjs9S64xzhlp
+HfKLPLzwEjIYVVJTShBQSVuNz9WcetQkID8FUm4uJg1XkFBJXY6pxXgTeeHpPEO2
+HgOIXaJi2clIshjgMGHkseP62coS8LyoDZ7uLJf8JhR8Rdb+Qn+n/54RbFWDGyUs
+mwIDAQABo4HZMIHWMIGlBgNVHSMEgZ0wgZqhgYykgYkwgYYxCzAJBgNVBAYTAkNO
+MRIwEAYDVQQIDAlHdWFuZ2RvbmcxETAPBgNVBAcMCFNoZW56aGVuMRUwEwYDVQQK
+DAxDb2NvUm9ibyBMVEQxGjAYBgNVBAMMEUNvY29Sb2JvIFRydXN0IENBMR0wGwYJ
+KoZIhvcNAQkBFg5pdEBjb2Nvcm9iby5jY4IJANpFK/+zAjUeMAkGA1UdEwQCMAAw
+CwYDVR0PBAQDAgTwMBQGA1UdEQQNMAuCCWxvY2FsaG9zdDANBgkqhkiG9w0BAQsF
+AAOCAQEAq7LoQ+AMK9SEw+HSPivOt8zE356FGvGxaXImwHA87vPPGozIN6nLYSey
+qtR0kxpRYU0Ki2zijqN4BZNZD7p6gRzbOA8pnO41tBUUmXIsgoYSKykuPVO8NkiA
+bdFo8m5TBOrkIJXf6rrfXOaFQbZ5n75H9N8UrdXKQz9sp13vfZYmltRt1+ya+0Xw
+h1mrnDMBZqFkttkKDu+nFoJTJcBZ0xUEh5u0gdFNZQDdQeZO+SYKtUIhdhVN+3HM
+JnQXM3eeTl/EzS8PvntQa0BV3M4jHO7W+7piOBD5exNmIFkHqd0f6h4MQ2b+rLsE
+MQFHzwA1WZLZKzUUlQe763uXn2KG5w==
+-----END CERTIFICATE-----

+ 27 - 0
backup/preset/server/ccrb.key

@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEpQIBAAKCAQEAvk3cAwel+eWyJXAl9RB9rhxQHc4vDr/VshOy157/+jj6rUyD
+qRpdWh66DBmn429ReXzRsxhu5dhWUfWzztjW1pJ1159mC9TTGWWRqCKuVDNXtXq7
+QYD6apODjpk7U/lpKed4Gf6DWMtGk4BSAJ8gY3k/R/bE6iCQHJLE/yVnWw/tw5P8
+lKRajUi36JzOKQ6l0cJqa1vFXjs9S64xzhlpHfKLPLzwEjIYVVJTShBQSVuNz9Wc
+etQkID8FUm4uJg1XkFBJXY6pxXgTeeHpPEO2HgOIXaJi2clIshjgMGHkseP62coS
+8LyoDZ7uLJf8JhR8Rdb+Qn+n/54RbFWDGyUsmwIDAQABAoIBAE3OcZS/jMnWcvbB
+mpNO0cPdCZiWE0FZh5qOWUG1XX1FzKAMN4xtHhvZkkGeP7lKaypbsTUjWTwaLnjG
+F2UL3RLPwOSO5F8T/ddVYq82tsXwU/z8GBGZFUl71H76AXq875VVcRJXsAYe3lUy
+UtS0Or7Q9OGMcEg1VhaIn4ieF1rwPE6QvsWiXzDcqvA9GFqLfVHE4i88CwkeBKdB
+S52HkXruVExekwITJxo6pcj61BRD8xLypFyy923+ONPSjACtetbukA9QFOsOvFSQ
+kymCaR65in5smkMrFeiTa6srDtIvUxFMdhnOmPbsmWsrR2k98ZMi+85k1OOG8vXO
+JeIAxSECgYEA7b6tTyql2RCiPoS2HiCJVsjcpwz/Pv0BduR6zNNn59HzVO3hZ+td
+Y3mAtU2ix7WK5A+9ezw4ge40TrolHxYgpUBkCrATVBxOKKChvNhRQ/Tc/26ewDrl
+1U0l0B/qi30+INwbC6gXSV2vvL5rRcCjBfTVOJ2xAxLtfcCVkMVyufECgYEAzOql
+aSC5FoSSaaL1FHMRlQjbe8UG2fdlMNAuSzkqVa2QfQefvTpFk3RD4hJR38HHenph
+m1xdlqoGSp1pjcGFCj5UfSSee01kIFa3CZ9eGqxb8JXnJex7oGC+F8mzwjYqYetr
+wTi46PeX+w+Gnq2e1gI8/QjNlL8F6KCqhRoo40sCgYEAvq/iaA4H6dt6lnRxciac
+oXwH5wD4tTfO9eJ6UFD8FScDacpGschJJmEtB75WYqJM3XF2hCKgHC7Hy6Fn5tAj
+rQfBdgUV66+sTM/SChriy4PZwhKiyAI1l+kB/DWtNOZmb4q7MpVG4DSBoPyGI/NH
+jp56aqeoc5O54tQV4oFL7LECgYEAibUel/l/qNxKsGbsoGN761XaeeC8a/pPrHAa
+zD6MbquHMB7RgI8Kdr9pZyG8l8xXy702nvuBgWCdfcMvTi5Aw9ODX94eCurFYN4l
+f3fz+6Tc3F9AyUGVCwA4fy/zd46DCO72qRD/YsARCI00gKpY1aUHa1xhG5cL13sx
+XOVpmOUCgYEA2mh8UCY5ANQ3McXBx346+RxKLZnDkntyS6A9JbZSWgp2ca8TfpXS
+XQgdmDkz6VNO3I6tasqRqZVcTFpVSRpkmyCob7cu7XpZ5hUZjK4a+5xUR+KBZ1LI
+OAFAJ9JjDwcTEujArla4aUAntxvKBWGv2LHKVluy5aOGGfKTzUDWbro=
+-----END RSA PRIVATE KEY-----

+ 88 - 0
backup/preset/server/wirelessServer.py

@@ -0,0 +1,88 @@
+import asyncio
+import websockets
+import ssl
+import os
+import signal
+import linecache
+
+
+ssl._create_default_https_context = ssl._create_unverified_context
+ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+ssl_context.load_cert_chain("/root/preset/server/ccrb.crt", "/root/preset/server/ccrb.key")
+p1 = None
+p2 = None
+p3 = None
+countn = 0
+
+async def send(websocket):
+    global p2
+    global p1
+    global countn
+    await asyncio.create_subprocess_shell("echo > /root/event.log &")
+    #open("/root/event.log", 'w').close()
+    while True:
+        await asyncio.sleep(0.03)
+        if True:
+            try:
+                proxy_recv_msg = ""
+                linecache.clearcache()
+                logarr = linecache.getlines("/root/event.log")[-20:]
+                open("/root/event.log", 'w').close()
+                #os.remove(r'/root/event.log')
+                #await asyncio.create_subprocess_shell("echo '' > /root/event.log")
+                #print(linecache.getlines("/root/event.log")[-10:])
+                proxy_recv_msg = "".join(logarr).rstrip('\x00')
+                #print(len(logarr))
+                if proxy_recv_msg != "" and proxy_recv_msg != "\n":                                                                         
+                    try:                                                                                         
+                        await websocket.send(proxy_recv_msg)
+                    except websockets.ConnectionClosed:
+                        try:
+                            if p1.returncode == None:                                                                                                                                                
+                                os.killpg(p1.pid, signal.SIGUSR1)
+                            #open("/root/event.log", 'w').close()
+                            #await asyncio.create_subprocess_shell("echo "" > /root/event.log")                                                                                                                
+                        finally:                                                                                                                                             
+                            pass                                                           
+                        pass 
+            finally:                                                                                         
+                pass
+
+async def receive(websocket):
+    global p2
+    global p3
+    global p1    
+#    if p2 == None and p3 == None:
+#        p2 = await asyncio.create_subprocess_shell("echo '' > /tmp/event.log && tail -f /tmp/event.log", stdout=asyncio.subprocess.PIPE, preexec_fn = os.setsid)
+#        p3 = p2
+#    else:
+#        p2 = p3
+
+    while True:
+        await asyncio.sleep(0.5)
+        recv_text = await websocket.recv()
+        if p1 != None:
+            try:
+                if p1.returncode == None:
+                    p1.kill()
+                    os.killpg(p1.pid, signal.SIGUSR1)
+            finally:
+                pass
+        p1 = await asyncio.create_subprocess_shell(recv_text, stdout=None, preexec_fn = os.setsid)
+        print(p1.pid)
+
+async def main_logic(websocket, path):
+        await runstart(websocket, path)
+        asyncio.run(runstart(websocket, path))
+
+async def runstart(websocket, path):
+        a = asyncio.create_task(send(websocket))
+        b = asyncio.create_task(receive(websocket))
+        await a
+        await b
+
+
+start_server = websockets.serve(main_logic, '0.0.0.0', 5678, ssl=ssl_context)
+
+asyncio.get_event_loop().run_until_complete(start_server)        
+asyncio.get_event_loop().run_forever()

+ 8 - 0
backup/readme.txt

@@ -0,0 +1,8 @@
+手动升级资源包方法:
+1、替换/root/main.py
+2、删除原本的/root/preset/app 目录全部文件并替换
+3、删除原本的/root/preset/fonts 目录全部文件并替换
+4、合并/root/preset/img 目录文件
+5、移除/home/cclb_launch 文件,将新的cclb_launch复制到/root/ 目录下,用 cp /root/cclb_launch /home/cclb_launch 将文件进行拷贝,切换到
+/home/ 目录,用 chmod 777 * 命令给权限
+6、 reboot 重启

+ 0 - 0
backup/user/app/.nomedia


+ 0 - 0
backup/user/audio/.nomedia


+ 0 - 0
backup/user/font/.nomedia


+ 0 - 0
backup/user/img/.nomedia


+ 0 - 0
backup/user/text/.nomedia


+ 1 - 0
backup/user/text/owner.txt

@@ -0,0 +1 @@
+CocoPi

+ 0 - 0
backup/user/userInfo.json


+ 0 - 0
backup/user/video/.nomedia


+ 0 - 0
backup/user_latest_code.png


+ 118 - 0
backup/user_latest_code.py

@@ -0,0 +1,118 @@
+from maix import camera, display, zbar, image
+import socket
+import os
+import sys
+sys.path.append('/root/CocoPi.py')
+import http.client
+from CocoPi import BUTTON
+import time
+
+key_A = BUTTON(14)
+key_B = BUTTON(8)
+key_C = BUTTON(13)
+key_D = BUTTON(7)
+ScreenOrientation = False
+image.load_freetype("/root/preset/fonts/yahei-ttf.ttf")
+camera.camera.config(size=(240,320))
+def lcdRotation(inputImg,rotationAngle):
+    from maix import image
+    imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
+    if ScreenOrientation:
+        imgRotationAim = image.new(size = (240, 320))
+    else:
+        imgRotationAim = image.new(size = (320, 240))
+    return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
+
+if ScreenOrientation:
+    CAMERAROTATE = +180
+else:
+    CAMERAROTATE = +90
+
+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 wifi_is_content():
+    global getDateNum
+    cmd = "wifi_get_connection_info_test 1"
+
+    res = os.popen(cmd).read()
+    data = False
+    print(res)
+    if res.find('get connection infomation successfully!') != -1:
+        data = True
+
+    return data
+def extract_ip():
+    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
+
+SSID = ""
+PASS = ""
+isContent = True
+contentText = ""
+
+canvas1 = image.new(size = (320, 240))
+while True:
+    canvas = lcdRotation(camera.capture(),CAMERAROTATE)
+    IP = extract_ip()
+    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(";")
+        SSID = codeData[0].split(":")[1]
+        PASS = 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 - 35) , str(string), scale = 1, color = (255, 0, 0), thickness = 2)  #内框ID
+    if key_C.is_pressed():
+        while not (key_C.is_pressed() == False):
+            time.sleep(0.01)
+        os.system("wifi_disconnect_ap_test")
+        os.system('wifi_connect_chinese_ap_test '+SSID+' '+PASS+'')
+        isContent = False
+        contentText == ""
+    elif(contentText == "" and isContent == False):
+
+        if wifi_is_content():
+            contentText = "Wi-Fi success"
+            canvas1 = image.new(size = (320, 320), color = (255,255,255), mode = "RGB")
+        else:
+            contentText = "Wi-Fi failure"
+        isContent = True
+    # canvas1.draw_rectangle(0,0, 320,20, color=(255,255,255), thickness=-1)
+    canvas.draw_image(canvas1,0,0, alpha=0.6)
+    canvas.draw_string(10,50, contentText, scale = 1.5, color = (0,0,0) , thickness = 1)
+    canvas.draw_string(10,0, "Press C to take pictures for networking", scale = 1, color = (0,0,0) , thickness = 1)
+    canvas.draw_string(10,20, "Hold D to build and exit", scale = 1, color =(0,0,0) , thickness = 1)
+    if IP != "127.0.0.1" and contentText != "":
+        canvas.draw_string(10,80, "IP:" + extract_ip(), scale = 1.5, color = (0,0,0), thickness = 1)
+    display.show(canvas)
+    

+ 0 - 0
backup/user_latest_code.xml


BIN
cclb_launch


+ 2 - 0
reload_usb.py

@@ -0,0 +1,2 @@
+import os
+os.system("/etc/init.d/S12usb restart")

+ 160 - 0
retinaface.py

@@ -0,0 +1,160 @@
+from maix import nn, camera, image, display
+from maix.nn.app.face import FaceRecognize
+import time
+from evdev import InputDevice
+from select import select
+
+
+score_threshold = 70                            #识别分数阈值
+input_size = (224, 224, 3)                      #输入图片尺寸
+input_size_fe = (128, 128, 3)                   #输入人脸数据
+feature_len = 256                               #人脸数据宽度
+steps = [8, 16, 32]                             #
+channel_num = 0                                 #通道数量
+users = []                                      #初始化用户列表
+names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]  #人脸标签定义
+model = {
+    "param": "/home/model/face_recognize/model_int8.param",
+    "bin": "/home/model/face_recognize/model_int8.bin"
+}
+model_fe = {
+    "param": "/home/model/face_recognize/fe_res18_117.param",
+    "bin": "/home/model/face_recognize/fe_res18_117.bin"
+}
+
+
+for i in range(len(steps)):
+    channel_num += input_size[1] / steps[i] * (input_size[0] / steps[i]) * 2
+channel_num = int(channel_num)     #统计通道数量
+options = {                             #准备人脸输出参数
+    "model_type":  "awnn",
+    "inputs": {
+        "input0": input_size
+    },
+    "outputs": {
+        "output0": (1, 4, channel_num) ,
+        "431": (1, 2, channel_num) ,
+        "output2": (1, 10, channel_num)
+    },
+    "mean": [127.5, 127.5, 127.5],
+    "norm": [0.0078125, 0.0078125, 0.0078125],
+}
+options_fe = {                             #准备特征提取参数
+    "model_type":  "awnn",
+    "inputs": {
+        "inputs_blob": input_size_fe
+    },
+    "outputs": {
+        "FC_blob": (1, 1, feature_len)
+    },
+    "mean": [127.5, 127.5, 127.5],
+    "norm": [0.0078125, 0.0078125, 0.0078125],
+}
+keys = InputDevice('/dev/input/event0')
+
+threshold = 0.5                                         #人脸阈值
+nms = 0.3
+max_face_num = 1                                        #输出的画面中的人脸的最大个数
+print("-- load model:", model)
+m = nn.load(model, opt=options)
+print("-- load ok")
+print("-- load model:", model_fe)
+m_fe = nn.load(model_fe, opt=options_fe)
+print("-- load ok")
+face_recognizer = FaceRecognize(m, m_fe, feature_len, input_size, threshold, nms, max_face_num)
+
+def get_key():                                      #按键检测函数
+    r,w,x = select([keys], [], [],0)
+    if r:
+        for event in keys.read():
+            if event.value == 1 and event.code == 0x02:     # 右键
+                return 1
+            elif event.value == 1 and event.code == 0x03:   # 左键
+                return 2
+            elif event.value == 2 and event.code == 0x03:   # 左键连按
+                return 3
+    return 0
+
+def map_face(box,points):                           #将224*224空间的位置转换到240*240或320*240空间内
+    # print(box,points)
+    if display.width() == display.height():
+        def tran(x):
+            return int(x/224*display.width())
+        box = list(map(tran, box))
+        def tran_p(p):
+            return list(map(tran, p))
+        points = list(map(tran_p, points))
+    else:
+        # 168x224(320x240) > 224x224(240x240) > 320x240
+        s = (224*display.height()/display.width()) # 168x224
+        w, h, c = display.width()/224, display.height()/224, 224/s
+        t, d = c*h, (224 - s) // 2 # d = 224 - s // 2 == 28
+        box[0], box[1], box[2], box[3] = int(box[0]*w), int((box[1]-28)*t), int(box[2]*w), int((box[3])*t)
+        def tran_p(p):
+            return [int(p[0]*w), int((p[1]-d)*t)] # 224 - 168 / 2 = 28 so 168 / (old_h - 28) = 240 / new_h
+        points = list(map(tran_p, points))
+    # print(box,points)
+    return box,points
+
+def darw_info(draw, box, points, disp_str, bg_color=(255, 0, 0), font_color=(255, 255, 255)):    #画框函数
+    box,points = map_face(box,points)
+    font_wh = image.get_string_size(disp_str)
+    for p in points:
+        draw.draw_rectangle(p[0] - 1, p[1] -1, p[0] + 1, p[1] + 1, color=bg_color)
+    draw.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3], color=bg_color, thickness=2)
+    draw.draw_rectangle(box[0], box[1] - font_wh[1], box[0] + font_wh[0], box[1], color=bg_color, thickness = -1)
+    draw.draw_string(box[0], box[1] - font_wh[1], disp_str, color=font_color)
+def recognize(feature):                                                                   #进行人脸匹配
+    def _compare(user):                                                         #定义映射函数
+        return face_recognizer.compare(user, feature)                      #推测匹配分数 score相关分数
+    face_score_l = list(map(_compare,users))                               #映射特征数据在记录中的比对分数
+    return max(enumerate(face_score_l), key=lambda x: x[-1])                #提取出人脸分数最大值和最大值所在的位置
+
+def run():
+    img = camera.capture()                       #获取224*224*3的图像数据
+    AI_img = img.copy().resize(224, 224)
+    if not img:
+        time.sleep(0.02)
+        return
+    faces = face_recognizer.get_faces(AI_img.tobytes(),False)           #提取人脸特征信息
+    if faces:
+        for prob, box, landmarks, feature in faces:
+            key_val = get_key()
+            if key_val == 1:                                # 右键添加人脸记录
+                if len(users) < len(names):
+                    print("add user:", len(users))
+                    users.append(feature)
+                else:
+                    print("user full")
+            elif key_val == 2:                              # 左键删除人脸记录
+                if len(users) > 0:
+                    print("remove user:", names[len(users) - 1])
+                    users.pop()
+                else:
+                    print("user empty")
+
+            if len(users):                             #判断是否记录人脸
+                maxIndex = recognize(feature)
+
+                if maxIndex[1] > score_threshold:                                      #判断人脸识别阈值,当分数大于阈值时认为是同一张脸,当分数小于阈值时认为是相似脸
+                    darw_info(img, box, landmarks, "{}:{:.2f}".format(names[maxIndex[0]], maxIndex[1]), font_color=(0, 0, 255, 255), bg_color=(0, 255, 0, 255))
+                    print("user: {}, score: {:.2f}".format(names[maxIndex[0]], maxIndex[1]))
+                else:
+                    darw_info(img, box, landmarks, "{}:{:.2f}".format(names[maxIndex[0]], maxIndex[1]), font_color=(255, 255, 255, 255), bg_color=(255, 0, 0, 255))
+                    print("maybe user: {}, score: {:.2f}".format(names[maxIndex[0]], maxIndex[1]))
+            else:                                           #没有记录脸
+                darw_info(img, box, landmarks, "error face", font_color=(255, 255, 255, 255), bg_color=(255, 0, 0, 255))
+
+
+    display.show(img)
+
+
+
+if __name__ == "__main__":
+    import signal
+    def handle_signal_z(signum,frame):
+        print("APP OVER")
+        exit(0)
+    signal.signal(signal.SIGINT,handle_signal_z)
+    while True:
+        run()

+ 12 - 0
startup.py

@@ -0,0 +1,12 @@
+#!/usr/bin/env python
+from maix import camera, display, image, nn
+image.load_freetype("/home/res/sans.ttf")
+qrcode = image.open('/home/res/qrcode.png')
+canvas = image.new((display.width(), display.height()), (0xFF, 0xFF, 0xFF), "RGB")
+canvas.draw_image(qrcode, (canvas.width - qrcode.width) // 2, (canvas.height - qrcode.height) // 2)
+info = "wiki.sipeed.com/maixpy3"
+w, h = image.get_string_size(info, 1.2)
+canvas.draw_string((canvas.width - w) // 2 + 5, canvas.height - h - 5, info, 1.2, color=(0x00, 0x00, 0x00))
+for i in range(120):
+    img = camera.capture().draw_image(canvas, alpha=0.7)
+    display.show(img)

+ 46 - 0
yolo2_20class_awnn.py

@@ -0,0 +1,46 @@
+from maix import nn, camera, image, display
+from maix.nn import decoder
+import time
+
+model = {
+    "param": "/home/model/yolo2_20class_awnn.param",
+    "bin": "/home/model/yolo2_20class_awnn.bin"
+}
+options = {
+    "model_type":  "awnn",
+    "inputs": {
+        "input0": (224, 224, 3)
+    },
+    "outputs": {
+        "output0": (7, 7, (1+4+20)*5)
+    },
+    "mean": [127.5, 127.5, 127.5],
+    "norm": [0.0078125, 0.0078125, 0.0078125],
+}
+
+labels = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
+anchors = [5.4, 5.38, 1.65, 2.09, 0.8, 1.83, 2.45, 4.14, 0.46, 0.8]
+
+m = nn.load(model, opt=options)
+yolo2_decoder = decoder.Yolo2(len(labels), anchors, net_in_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]), net_out_size=(7, 7))
+
+while True:
+    img = camera.capture()
+    AI_img = img.copy().resize(224, 224)
+    out = m.forward(AI_img.tobytes(), quantize=True, layout="hwc")
+    boxes, probs = yolo2_decoder.run(out, nms=0.3, threshold=0.3, img_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]))
+
+    if len(boxes):
+        for i, box in enumerate(boxes):
+            class_id = probs[i][0]
+            prob = probs[i][1][class_id]
+            disp_str = "{}:{:.2f}%".format(labels[class_id], prob*100)
+            img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3], color = (0, 255, 0), thickness=2)
+            x = box[0]
+            y = box[1] - 20
+            if y < 0:
+                y = 0
+            img.draw_string(x, y, disp_str, 1.5, color = (255, 0, 0), thickness=2)
+
+    display.show(img)
+