#!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""
Created on Sep 17, 2020

@author: stkim
"""
from printThread_info import printThread_info
import os
import threading
import zipfile
from configparser import ConfigParser
from xmlrpc import client
from time import sleep
import sys
import datetime
import cv2
import logging.handlers
from logging.handlers import TimedRotatingFileHandler
import time
from PIL import Image
from multiprocessing import Process
import RPi.GPIO as GPIO

logger = logging.getLogger('dp110server')


class mainprintThread(threading.Thread):

    def setPrint(self, parent, printer, rpcprinter, totalLayer, baseNumber, thickness, ZeroPoint):
        self.parent = parent
        self.printer = printer
        self.rpcprinter = rpcprinter
        self.baseNumber = baseNumber
        self.totalLayer = totalLayer
        self.nowLayer = 1
        self.totalHeight = float(totalLayer * thickness)
        self.thickness = thickness
        self.ZeroPoint = ZeroPoint

        self.beginningTime = float(self.printer.LightTime_Beginning)
        self.basicTime = float(self.printer.LightTime_Basic)
        self.LightStep_Beginning = float(self.printer.LightStep_Beginning)
        self.BasicwaitTime = float(self.printer.basicWaitTime)
        self.beginningWaitTime = float(self.printer.beginWaitTime)

        self.motorSpeed = float(self.printer.ZMotorSpeed * 2)   # basic motor speed
        self.InitialMotorSpeed = float(self.printer.InitialMotorSpeed * 2) # initial motor speed

        self.motorDistance = float(self.printer.LowSpeedAmount)  # basic motor distance
        self.InitialMotorDistance = float(self.printer.InitialMotorDistance) # initial motor distance

        self.pause = False
        self.interimPause = False
        self.interimResume = False
        self.interimcheck = False
        self.printHight = 0
        self.stop = False
        self.startPoint = False
        self.proxy = client.ServerProxy('http://127.0.0.1:8181')
        # self.proxy = xmlrpclib.ServerProxy('http://192.168.0.80:8282')
        self.MoveMount = 0
        self.fastZeroMove = self.ZeroPoint - 10
        self.zeroMoveTime = self.fastZeroMove / 0.00015625
        self.ZeroPointMP = self.ZeroPoint / 0.00015625
        self.DivfastZeroMove = self.fastZeroMove / 10
        self.sumfastZeroMove = 0
        self.endFlagSumfastZeroMove = self.printer.ZeroPoint - 40
        self.divMotorTime = int((self.DivfastZeroMove / 4) - 0.13)
        self.tempCurrent = 0
        self.display_opencv = 0

    def run(self):
        if self.display_opencv:
            #  openCV declare start
            print('thread run start')
            self.img = cv2.imread(os.environ.get('HOME', '/home/pi') + '/carima/dp110server/images/black.png',
                                  cv2.IMREAD_GRAYSCALE)
            self.mask_image = cv2.imread(os.environ.get('HOME', '/home/pi') + '/carima/basic/mask.png',
                                         cv2.IMREAD_GRAYSCALE)
            cv2.namedWindow("main", cv2.WINDOW_NORMAL)
            cv2.setWindowProperty("main", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
            cv2.moveWindow("main", 800, 0)
            cv2.imshow("main", self.img)
            cv2.waitKey(50)
            #  openCV declare end
        else:
            self.printer.printConnect1()
            cv2.waitKey(1)
            cv2.waitKey(1)

        self.proxy.ui_lamp(False)
        sleep(0.2)
        self.printer.boardGo(0, 1)
        while self.sumfastZeroMove < self.fastZeroMove:
            self.sumfastZeroMove += self.DivfastZeroMove
            self.endFlagSumfastZeroMove += self.DivfastZeroMove
            if self.parent.printendPositionFlag == 0:
                if self.sumfastZeroMove >= self.fastZeroMove:
                    test1 = self.printer.boardGo(self.fastZeroMove, 0)
                    print(test1)
                else:
                    test2 = self.printer.boardGo(self.sumfastZeroMove, 0)
                    print(test2)
            else:
                if self.endFlagSumfastZeroMove >= self.fastZeroMove:
                    self.printer.boardGo(self.fastZeroMove, 0)
                    # 분할된 영점 값이 출력물 높이에 따른 출력 완료 후 높이가 달라짐에 따른 오차로 인해 발생되는 영점값에 대한 처리
                else:
                    self.printer.boardGo(self.endFlagSumfastZeroMove, 0)
            if self.stop:
                self.run_stop()
                return 1
            if self.endFlagSumfastZeroMove >= self.fastZeroMove and self.parent.printendPositionFlag == 1:
                # cv2.waitKey(100)
                sleep(0.1)
            elif self.sumfastZeroMove >= self.fastZeroMove and self.parent.printendPositionFlag == 0:
                # cv2.waitKey(100)
                sleep(0.1)
            elif self.endFlagSumfastZeroMove < self.fastZeroMove or self.sumfastZeroMove < self.fastZeroMove:
                sleep(self.divMotorTime)

        sleep(0.1)
        test3 = self.printer.changeTimer(self.motorSpeed)
        print(test3)
        sleep(0.1)
        test4 = self.printer.boardGo(self.ZeroPoint, 1)
        print(test4)
        sleep(0.1)

        if self.stop:
            self.run_stop()
            return 1

        if (self.beginningTime > self.basicTime) and (self.LightStep_Beginning != 0):
            Minus_beginningTime = int((self.beginningTime - self.basicTime) / self.LightStep_Beginning)
        else:
            Minus_beginningTime = 0
        self.printer.printConnect1()

        while self.nowLayer <= self.totalLayer:  # 조형 반복 시퀀스
            if self.nowLayer <= self.LightStep_Beginning:
                self.motorSpeed = self.InitialMotorSpeed
                self.motorDistance = self.InitialMotorDistance
            elif self.nowLayer > self.LightStep_Beginning:
                self.motorSpeed = float(self.printer.ZMotorSpeed * 2)
                self.motorDistance = float(self.printer.LowSpeedAmount)

            test5 = self.printer.changeTimer(self.motorSpeed)
            print(test5)

            # pause and resume
            if self.pause:
                if self.stop:
                    self.run_stop()
                    return 1
                if self.interimPause:
                    self.printer.changeTimer(16)
                    sleep(0.2)
                    if self.printHight <= 30:
                        self.printer.boardGo(30, 1)
                    elif 30 < self.printHight <= 60:
                        self.printer.boardGo(15, 1)
                    elif 60 < self.printHight:
                        self.printer.boardGo(1, 1)
                    self.interimPause = False
                    self.interimcheck = True
                    sleep(0.5)
                    continue
                else:
                    if self.stop:
                        self.run_stop()
                        return 1
                    sleep(0.5)
                    continue
            elif self.interimResume & self.interimcheck:  # 일시정지 해제
                self.printer.boardGo(self.ZeroPoint - self.MoveMount - self.motorDistance, 1)
                self.interimResume = False
                self.interimcheck = False
                sleep(0.1)
                self.printer.changeTimer(self.motorSpeed)

            if self.startPoint:
                if self.nowLayer <= self.totalLayer:
                    self.MoveMount += self.thickness
                    # 1) motor down
                    # self.parent.Insertlog('==> 1. motor down')
                    test6 = self.printer.boardGo(self.ZeroPoint - self.MoveMount, 1)
                    print(test6)
                    self.printHight = self.thickness * self.nowLayer
                    # self.tempCurrent = self.printer.checkTmpSensor()

            if self.stop:
                self.run_stop()
                return 1

            if self.nowLayer <= self.totalLayer:
                # 2) notice to qt
                # self.parent.Insertlog('==> 2. proxy info Layer : ' + str(self.nowLayer))
                self.proxy.ui_layer(self.nowLayer)

            # 3) WaitTime on by resin cfg
            # self.parent.Insertlog('==> 3. WaitTime : ' + str(self.BasicwaitTime))
            if self.nowLayer <= self.printer.LightStep_Beginning:
                if self.beginningWaitTime != 0:
                    # cv2.waitKey(self.beginningWaitTime)
                    sleep(self.beginningWaitTime)
            else:
                if self.BasicwaitTime != 0:
                    # cv2.waitKey(self.BasicwaitTime)
                    sleep(self.BasicwaitTime)

            if self.stop:
                self.run_stop()
                return 1

            # 4) image on
            # self.parent.Insertlog('==> 4. image on')
            if self.display_opencv:
                imagefile = os.environ.get('HOME', '/home/pi') + '/carima/buffer/image/SEC_0001.png'
                if os.path.isfile(imagefile):
                    ori_image = cv2.imread(os.environ.get('HOME', '/home/pi') + '/carima/buffer/image/SEC_%04d.png' %
                                           self.nowLayer, cv2.IMREAD_GRAYSCALE)
                else:
                    ori_image = cv2.imread(os.environ.get('HOME', '/home/pi') + '/carima/buffer/image/SEC_%06d.png' %
                                           self.nowLayer, cv2.IMREAD_GRAYSCALE)

                if 0:   # ccat use below but other no use, work at qt
                    flip_ori_image = cv2.flip(ori_image, 1)
                    mixed_image = cv2.bitwise_and(flip_ori_image, self.mask_image)
                    cv2.imshow("main", mixed_image)
                else:
                    cv2.imshow("main", ori_image)

                # cv2.waitKey(50)
                cv2.waitKey(1)
            else:
                self.printer.image_display(self.nowLayer)

            # 5) engine on
            # self.parent.Insertlog('==> 5. engine on')
            self.proxy.ui_lamp(True)

            # 6) display continue time
            # self.parent.Insertlog('==> 6. display continue time')
            if self.nowLayer <= self.printer.LightStep_Beginning:
                sleep(self.beginningTime)
            else:
                sleep(self.basicTime)

            # self.printer.lightOn1(self.nowLayer, self.basicTime, self.beginningTime)
            if self.stop:
                self.run_stop()
                return 1

            # 7) image off
            # self.parent.Insertlog('==> 7. image off')
            if self.display_opencv:
                self.img = cv2.imread(os.environ.get('HOME', '/home/pi') + '/carima/dp110server/images/black.png',
                                      cv2.IMREAD_GRAYSCALE)
                cv2.imshow("main", self.img)
                # cv2.waitKey(50)
                cv2.waitKey(1)
            else:
                self.printer.display.showSliceOffImage()

            # add layer
            self.nowLayer += 1

            if self.stop:
                self.run_stop()
                return 1

            # 8) Lamp off
            # self.parent.Insertlog('==> 8. engine off')
            self.proxy.ui_lamp(False)

            # 9) sleep between engine off and motor up
            # self.parent.Insertlog('==> 9. sleep 0.1')
            sleep(0.1)  # wait between light off and motor up
            if self.nowLayer <= self.LightStep_Beginning:
                self.beginningTime = self.beginningTime - Minus_beginningTime

            # 10) motor up
            # self.parent.Insertlog('==> 10. motor up')
            test7 = self.printer.boardGo(self.ZeroPoint - self.motorDistance - self.MoveMount, 1)
            print(test7)
            if self.stop:
                self.run_stop()
                return 1

            # TODO:check sequence
            self.startPoint = True
            # 11) loop or end
            if self.nowLayer > self.totalLayer:
                if self.display_opencv:
                    cv2.destroyAllWindows()
                else:
                    self.printer.display.showSliceOffImage()

                self.printer.InsideLED_fanOFF()
                self.printer.removeImageFile()
                self.printer.MaxSpeed()
                # self.printer.boardGo(1, 1)
                self.parent.boardHome_inPrinting()
                self.proxy.ui_isPrinting()
                self.proxy.ui_isPrinting()
                self.parent.Insertlog('printing complete')
                self.parent.is_printing = 3
                return 1

    def run_stop(self):
        self.printer.InsideLED_fanOFF()
        print("run_stop start")
        if self.display_opencv:
            cv2.destroyAllWindows()
        else:
            self.printer.display.showSliceOffImage()

        self.printer.MaxSpeed()
        sleep(0.2)
        # self.printer.boardGo(1, 0)
        self.parent.boardHome_inPrinting()
        sleep(0.2)
        self.proxy.ui_isPrinting()
        sleep(0.2)
        self.proxy.ui_isPrinting()
        self.parent.is_printing = 3

class AduThread(threading.Thread):

    def AdusetPrint(self, printer, parent):
        self.printer = printer
        self.parent = parent
        self.RFIDstop = False

    def run(self):
        self.proxy = client.ServerProxy("http://127.0.0.1:8181")
        while 1:
            if self.printer.ActiveRFID() != -1:
                self.printer.enterPasswd()
                RfidValue = self.printer.readDatablock2()
                if RfidValue == -1:
                    continue
                Tagvalue = RfidValue.count('3D')
                if Tagvalue >= 1:
                    self.parent.Insertlog(RfidValue)
                    self.proxy.ui_getRFID(RfidValue)
                    self.AduThread = 0
                    return 1
            else:
                sleep(0.1)
            if self.RFIDstop:
                return 1


class printThread(object):
    """
    classdocs
    """

    def __init__(self, params):
        """
        Constructor
        """
        self.printer = printThread_info()
        self.rpcprinter = printThread
        self.is_open = -1
        self.is_printing = 3
        self.new_img = 0
        self.homebutton = 0
        self.openPort = 0
        self.is_light_on = False
        self.Initlog()
        self.Insertlog('system on')
        self.proxy = client.ServerProxy("http://127.0.0.1:8181")
        self.printer.display.xmlrpcclient()
        self.trySerial = 0
        self.firstboot = 0
        self.upSignal = 0
        self.downSignal = 0
        self.printendPositionFlag = 0
        print(params)
        self.engineUSEStartTime = 0
        self.printThread_opencv_test = 0
        self.maskImagePath = os.environ.get('HOME', '/home/dp110') + '/carima/basic/mask.png'
        # self.focusImagePath = os.environ.get('HOME', '/home/dp110') + '/carima/basic/focus.png'

        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(38, GPIO.OUT)
        GPIO.setup(37, GPIO.OUT)
        GPIO.setup(40, GPIO.OUT)
        GPIO.output(38, 0)  # PCB
        GPIO.output(37, 0)  # PCB
        GPIO.output(40, 0)  # PCB

        if os.name == 'posix':
            self.configPath = os.environ.get('HOME', '/home/pi') + '/carima/system.cfg'
            self.resinconfigPath = os.environ.get('HOME', '/home/pi') + '/carima/resin.cfg'
        else:
            self.configPath = 'System.cfg'

    def testsleepTime(self):
        testdata = float(4.5)
        while 1:
            self.Insertlog('timeCheck')
            sleep(testdata)

    def lamponoffTest(self):
        while 1:
            self.proxy.ui_lamp(True)
            self.proxy.ui_lamp(False)
        return 1

    def testXML(self, T):
        return self.proxy.T(T)

    def py_isOpenPorts(self):
        return self.is_open

    def lampTest(self, on):
        if on == 1:
            self.proxy.ui_lamp(True)
            return 1
        else:
            self.proxy.ui_lamp(False)
            return 2

    def py_reOpenPorts(self):
        GPIO.output(38, 1)
        sleep(3.5)
        GPIO.output(38, 0)
        sleep(3.5)
        self.Insertlog('reopen port')
        self.printer.rePrintConnet(0)
        if self.printer.printConnect() is False:
            self.Insertlog('Motor Serial Connect Failed')
            return self.proxy.ui_openPorts(False)
        else:
            sleep(0.5)
            if self.homebutton != 1:
                self.openPort = 1
                self.proxy.ui_openPorts(True)

        self.printer.InsideLED_fanOFF()
        self.Insertlog('Motor Serial Connect success')
        return 1

    def py_printPause(self, pauseinterim):
        if pauseinterim:
            self.pthread.pause = True
            self.pthread.interimPause = True
            self.Insertlog('printing interimpause')
        else:
            self.pthread.pause = True
            self.Insertlog('printing pause')
        return 1

    def py_printResume(self, pauseinterim):
        if pauseinterim:
            self.pthread.pause = False
            self.pthread.interimResume = True
        else:
            self.pthread.pause = False
        self.Insertlog('printing resume')
        return 1

    def py_openPorts(self):
        self.printer.readConfig(self.configPath)
        self.Insertlog('open port')
        self.printer.openPorts(0)
        if self.printer.printConnect() is False:
            self.py_reOpenPorts()
            return self.proxy.ui_openPorts(True)
        else:
            self.printer.printConnect1()
            data1 = self.printer.boardHome()
            self.Insertlog(data1)
            self.Insertlog('First Home')
            sleep(0.1)
            self.printer.printConnect2()
            sleep(2)
            self.proxy.ui_initZeroPoint(False)
            self.Insertlog('Motor Serial Connect success')
            return 1

    def py_isPrinting(self):
        return self.is_printing

    def py_printStart(self, reginame, totalLayer, thickness):
        self.printer.readConfig(self.configPath)
        self.printer.resinConfig(self.resinconfigPath, reginame)
        # ifolder = os.environ.get('HOME','/home/dp110') + '/carima/build-3DPrinter-Desktop-Release/buffer/image'
        ifolder = os.environ.get('HOME', '/home/dp110') + '/carima/buffer/image'
        if not os.path.exists(ifolder):
            self.logger.error('path not exists: %s' % ifolder)
            return False
        base_index = 1

        self.printer.display.imageRoot = ifolder
        self.printer.display.fileType = 'png'

        self.pthread = mainprintThread()
        self.pthread.setPrint(self, self.printer, self.rpcprinter, totalLayer, base_index,
                              thickness, self.printer.ZeroPoint)

        self.printer.InsideLED_fanON()
        self.printer.set_first_motor_speed()     # originalTimer()
        self.py_engineLightOn()
        self.pthread.start()
        self.Insertlog('printing start - %d' % totalLayer)
        self.is_printing = 1
        return 1

    # TODO: receive file data and unzip file
    def py_uploadFile(self, fileName, fileData):
        if os.path.isdir(os.environ.get('HOME', '/home/pi') + '/carima/buffer/image'):
            self.printer.removeImageFile()
        fileNames = os.environ.get('HOME', '/home/dp110') + '/carima/buffer/' + fileName
        with open(fileNames, "wb") as handle:
            handle.write(fileData.data)

        fzip = zipfile.ZipFile(fileNames)
        fzip.extractall(os.environ.get('HOME', '/home/pi') + '/carima/buffer/image')

        fzip.close()
        return 1

    def py_sliceUpload(self, fileName, fileData):
        fileNames = os.environ.get('HOME', '/home/dp110') + '/carima/data/' + fileName
        with open(fileNames, "wb") as handle:
            handle.write(fileData.data)
        return 1

    def py_sliceDownload(self):
        with open("/home/dp110/carima/system.cfg", "rb") as handle:
            return client.Binary(handle.read())
        handle.close()

    def py_getCurrentLayer(self):
        sleep(0.3)
        return self.pthread.nowLayer

    def py_printStop(self):
        self.is_printing = 3
        self.pthread.stop = True
        self.Insertlog('printing stop')
        try:
            self.printer.removeImageFile()
        except:
            return 1
        return 1

    def py_isPause(self):
        return self.pthread.pause

    def py_isEngineOn(self):
        return 1

    def py_enginePower(self, isOn):
        return 1

    def py_isLightOn(self):
        return 1

    def py_engineLightOn(self):
        self.Insertlog('engine_on')
        self.engineUSEStartTime = datetime.datetime.now().replace(microsecond=0)
        return 1

    def py_engineLightOff(self):
        self.Insertlog('engine_off')
        Config = ConfigParser()
        Config.optionxform = str
        # 엔진이 켜졌던 시간부터 꺼진 시간을 계산
        engine_EndTime = datetime.datetime.now().replace(microsecond=0)
        engine_CurUseTime = engine_EndTime - self.engineUSEStartTime
        # 이전 엔진 총 사용 시간을 로드함
        # Config.read('/home/dp110/carima/system.cfg')
        Config.read('/home/pi/carima/system.cfg')
        pre_Engine_USETime = Config.get('SYSTEM', 'Engine_TotalTime')
        dtime = datetime.datetime.strptime(pre_Engine_USETime, '%H:%M:%S')
        # 24시간이 넘어가면 계산되지 못함
        TotalTime = dtime + engine_CurUseTime
        convert = TotalTime.strftime('%H:%M:%S')
        # filepath = '/home/dp110/carima/system.cfg'
        filepath = '/home/pi/carima/system.cfg'
        # 이번 엔진 총 사용 시간을 write 함
        # Config.set('SYSTEM', 'Engine_TotalTime', convert)
        Config.set('SYSTEM', 'EngineUsage', convert)
        with open(filepath, 'wb') as configfile:
            Config.write(configfile)
        return 1

    def py_boardHome(self):
        self.homebutton = 1
        self.printendPositionFlag = 0
        self.printer.printConnect1()
        sleep(0.5)
        self.printer.boardHome()
        sleep(0.5)
        self.printer.printConnect2()
        sleep(2)
        self.proxy.ui_initZeroPoint(True)
        return 1

    def boardHome_inPrinting(self):
        self.homebutton = 1
        self.printendPositionFlag = 0
        self.printer.printConnect1()
        sleep(0.5)
        self.printer.boardHome()
        sleep(0.5)
        self.printer.EndPrintBuzzer()
        self.printer.printConnect2()
        sleep(2)
        self.proxy.ui_initZeroPoint(False)
        return 1

    def py_led_fanOn(self):
        return self.printer.led_fanOn()

    def py_ledOn_fanOff(self):
        return self.printer.ledOn_fanOff()

    def py_ledblink_fanOn(self):
        return self.printer.ledblink_fanOn()

    # def py_temperature(self):
    #     if self.is_printing == 1:
    #         return self.pthread.tempCurrent
    #     elif self.is_printing == 3:
    #         return self.printer.checkTmpSensor()
    #     else:
    #         return -100

    def py_goRFID(self):
        if self.firstboot == 0:
            self.printer.rePrintConnet(0)
            sleep(0.5)
            self.firstboot = 1
        self.printer.printConnect2()
        self.AThread = AduThread()
        self.AThread.AdusetPrint(self.printer, self)
        self.AThread.start()
        return 1

    def py_stopRFID(self):
        try:
            self.AThread.RFIDstop = True
            return 1
        except:
            return 1

    # TODO: stuff
    def py_shutdown(self):
        self.printer.ShutdownBuzzer()
        self.Insertlog('system off')
        os.system("sudo shutdown -h 0")
        return 1

    def py_boardGo(self, A):
        self.printer.boardGo(A, 0)
        return 1

    def py_boardDown(self, ZMotorAmount):
        self.Insertlog("start")
        self.printer.boardDown(ZMotorAmount, 0)
        self.Insertlog("stop")
        self.downSignal = 1
        return 1

    def py_boardUp(self, ZMotorAmount):
        self.Insertlog("start")
        self.printer.boardUp(ZMotorAmount, 0)
        self.Insertlog("stop")
        self.upSignal = 1
        return 1

    def py_boardStop(self):
        if self.upSignal == 1:
            self.printer.upboardStop()
            self.upSignal = 0
        elif self.downSignal == 1:
            self.printer.downboardStop()
            self.downSignal = 0
        return 1

    def py_zeroPointUp(self, ZMotorAmount):
        self.Insertlog('start %d' % ZMotorAmount)
        self.printer.printConnect1()
        self.printer.zeroboardUp(ZMotorAmount, 1)
        self.Insertlog('finish')
        return self.printer.printConnect2()

    def py_zeroPointDown(self, ZMotorAmount, value):
        self.Insertlog('start %d' % ZMotorAmount)
        self.printer.printConnect1()
        self.printer.zeroboardDown(ZMotorAmount, 0, 1)
        self.Insertlog('finish')
        return self.printer.printConnect2()

    def py_motorUpDir(self):
        self.printer.motorUpDir()
        return 1

    def py_motorPosition(self):
        return self.printer.motorPositions()

    def py_basicImage(self, status):
        if status == 1:
            self.printer.BasicImageOn()
            self.Insertlog('basicimage_on')
            return 1
        else:
            self.printer.BasicImageOff()
            self.Insertlog('basicimage_off')
            return 1

    def py_basicEditImage(self, status):
        if status == 1:
            self.printer.BasicEditImageOn()
            self.Insertlog('basicEditimage_on')
            return 1
        else:
            self.printer.BasicImageOff()
            self.Insertlog('basicimage_off')
            return 1

    def py_basicImage1280(self, status):
        if status == 1:
            self.printer.BasicImageOn1280()
            self.Insertlog('basicimage_on')
            return 1
        else:
            self.printer.BasicImageOff()
            self.Insertlog('basicimage_off')
            return 1

    def py_focusImage(self, status):
        if status == 1:
            self.printer.display.focusImageOn()
            self.Insertlog('FocusImgOn')
            return 1
        else:
            self.printer.display.clear()
            self.Insertlog('FocusImgOff')
            return 1

    def BasicImageOncont(self):
        self.printer.display.whiteclearcont()
        return 1

    def py_setupGrid(self, xres, yres, xgrid, ygrid, line):
        return self.printer.display.setupGrids(xres, yres, xgrid, ygrid, line)

    def py_showGrid(self, x, y, val):
        self.printer.display.makeGrids((5 - x), y, val)
        # blackImg = Image.open(os.environ.get('HOME','/home/pi') + '/carima/dp110server/images/black.png')
        # gridImg = Image.open(os.environ.get('HOME','/home/pi') + '/carima/grid.png')
        # xpos = (5-x) * 320
        # ypos = y * 270
        # blackImg.paste(gridImg, (xpos,ypos))
        # blackImg.save(os.environ.get('HOME','/home/pi') + '/carima/Grid.png')
        self.printer.display.gridImageOn()
        return 1

    # def py_showGrid1280(self, x, y, val):
    #     self.printer.display.makeGrids1280(0, 0, val)
    #     blackImg = Image.open(os.environ.get('HOME', '/home/pi') + '/carima/dp110server/images/black1280.png')
    #     gridImg = Image.open(os.environ.get('HOME', '/home/pi') + '/carima/grid.png')
    #     xpos = x * 213
    #     ypos = (3 - y) * 200
    #     blackImg.paste(gridImg, (xpos, ypos))
    #     blackImg.save(os.environ.get('HOME', '/home/pi') + '/carima/Grid.png')
    #     self.printer.display.gridImageOn()
    #     return 1

    def py_clearGrid(self):
        self.printer.display.clear()
        return 1

    def cv_show_img(self, imgPath):
        cv2.namedWindow("main", cv2.WINDOW_NORMAL)
        cv2.setWindowProperty("main", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
        cv2.moveWindow("main", 800, 0)
        # cv2.startWindowThread()
        # cv2.waitKey(50)
        img = cv2.imread(imgPath, cv2.IMREAD_COLOR)
        cv2.imshow("main", img)
        cv2.waitKey(50)
        # while 1:
        #     print("showimg")
        #     sleep(0.1)

    def py_maskImage(self, turn):
        # Exposure Light for Cleaning
        print('py_maskImage turn is %d' % turn)
        if self.printThread_opencv_test:
            if turn == 1:
                self.cv_show_img(self.maskImagePath)
            else:
                cv2.destroyAllWindows()
            return 1
        else:
            if turn == 1:
                self.printer.display.maskImageOn()
            else:
                self.printer.display.clear()
            return 1

    def py_buildImage(self, turn):
        if turn == 1:
            self.printer.display.buildImageOn()
        else:
            self.printer.display.clear()
        return 1

    # def py_fixBuildImage(self, turn):
    #     if turn == 1:
    #         self.printer.display.fixBuildImageOn()
    #     else:
    #         self.printer.display.clear()
    #     return 1

    def py_whiteImage(self, turn):
        if turn == 1:
            self.printer.display.whiteImageOn()
        else:
            self.printer.display.clear()
        return 1

    def py_whiteImage1280(self, turn):
        if turn == 1:
            self.printer.display.whiteImageOn1280()
        else:
            self.printer.display.clear()
        return 1

    def py_whiteImageOff(self):
        self.printer.display.whiteImageOff()
        return 1

    def py_adminSet(self):
        self.Insertlog('admin set')
        return 1

    def Insertlog(self, logmsg):
        now = datetime.datetime.now()
        if self.logtime != now.strftime('%d-%H'):
            self.logbytime.removeHandler(self.logbytime.handlers[0])
            self.Initlog()
        self.logbytime.info(logmsg)
        return 1

    def Initlog(self):
        # 년월에 해당하는 폴더가 생성되어 있는지 먼저 파악 -> 매번 해당 루틴을 수행하는 은 좋지 않다. 처음 프린터가 실행되었을 때만 확인
        now = datetime.datetime.now()
        nowDateYM = now.strftime(os.environ.get('HOME', '/home/pi') + '/SystemLog/%Y-%m')
        if not os.path.exists(nowDateYM):
            os.makedirs(nowDateYM)
        self.logtime = now.strftime('%d-%H')
        nowDateMDH = now.strftime(os.environ.get('HOME', '/home/pi') + '/SystemLog/%Y-%m/%m-%d-%H')
        self.logbytime = logging.getLogger('imjlog')
        hdlr = logging.handlers.TimedRotatingFileHandler(nowDateMDH)
        formatter = logging.Formatter('[%(asctime)s] %(message)s')
        hdlr.setFormatter(formatter)
        self.logbytime.addHandler(hdlr)
        self.logbytime.setLevel(logging.INFO)
        return 1

    def py_checkxmlrpcclient(self):
        return self.printer.display.xmlrpcclient()

    def py_bufferTest(self):
        self.printer.display.bufferImgTest()
        return 1

    def Ainitmotor(self):
        self.printer.initMotorpostion()
        return 1

    def ActiveRFID(self):
        return self.printer.ActiveRFID()

    def enterPasswd(self):
        return self.printer.enterPasswd()

    def readDatablock1(self):
        self.RFIDdata = self.printer.readDatablock1()
        return self.RFIDdata

    def readDatablock2(self):
        return self.printer.readDatablock2()

    def readRFIDSection(self):
        return self.printer.readRFIDSection()

    def printEndBuzzer(self):
        return self.printer.EndPrintBuzzer()

    def SystemEndBuzzer(self):
        return self.printer.ShutdownBuzzer()

    def checkTempSensor(self):
        return self.printer.checkTmpSensor()

    def readPidTemp(self):
        return self.printer.Aboard.readPidTemp()

    def setPidTemp(self):
        return self.printer.Aboard.setPidTemp()

    def checkSenSorPin(self):
        return self.printer.Aboard.checkSensor(1000)

    def CheckSignal_pin4(self):
        return self.printer.Aboard.CheckSignal_pin4(1000)

    def CheckSignal_pin2(self):
        return self.printer.Aboard.CheckSignal_pin3(1000)

    def leftmove2(self):
        self.printer.printConnect1()
        return self.printer.Aboard.leftmove2(1000)

    def leftmove2_1(self):
        return self.printer.Aboard.leftmove2_1(1000)

    def rightmove3(self):
        self.printer.printConnect1()
        return self.printer.Aboard.rightmove3(1000)

    def rightmove3_1(self):
        return self.printer.Aboard.rightmove3_1(1000)

    def moveStop(self):
        return self.printer.Aboard.StopMove(1000)

    def TestMotorSpeed(self, motor_time):
        self.Insertlog('1')
        self.printer.New_changeTimer(motor_time)
        self.Insertlog('2')
        return 1

    def TestSensor(self):
        return self.printer.Aboard.test1111(1000)

    def TestPosition(self):
        return self.printer.Aboard.test2222(1000)

    def T(self):
        self.Insertlog('test_complete')
        return 1

    def changeMotorSpeed(self, value):
        self.printer.New_changeTimer(value)
        return 1

    def testMotorTime(self, speed, thickness):
        self.printer.printConnect1()
        self.printer.New_changeTimer(speed)
        count = 1
        retry = 0
        moveMount = 0
        while count < 11:
            retry = 0
            self.printer.boardGo(0, 1)
            while retry < 4:
                self.Insertlog('start motor %d' % count)
                startTime = time.time()
                self.printer.boardGo(count, 1)
                endTime = time.time()
                runningTime = endTime - startTime
                self.Insertlog(runningTime)

                startTime = time.time()
                self.printer.boardGo(thickness, 1)
                endTime = time.time()
                runningTime = endTime - startTime
                self.Insertlog(runningTime)

                retry += 1
            count += 1
        return 1


