#!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""
Created on Jun 07, 2021

@author: dkyoo
"""
import serial
# import logging
import binascii
from time import sleep
# from xmlrpc import client


class serial_Blade():
    """    derived board control class
    """
    def __init__(self, port):
        # self.logger = logging.getLogger('dp110server')
        # self.proxy = client.ServerProxy("http://127.0.0.1:8080")
        try:
            self.ser = serial.Serial('/dev/ttyUSB0', baudrate=9600)
            # sleep(2)
            # self.ser = serial.Serial('/dev/ttyUSB1', baudrate=9600)
            print("serial_Blade Serial success")
        except:
            print("serial_Blade Serial fail")
            return -1

    def openSerialPort(self):
        try:
            if not self.ser.isOpen():
                self.ser.open()
            return self.ser.isOpen()
        except:
            return -1

    def closeSerialPort(self):
        try:
            if self.ser.isOpen():
                self.ser.close()
            return True
        except serial.SerialException as e:
            self.logger.error("Could not open serial port %s: %s\n" % (self.ser.portstr, e))
            return False

    def HexStrToByteArray(self, data, size=6):
        bstr = bytearray.fromhex(data)
        # if len(bstr) != size:
        #     return False
        return bstr

    def ByteArrayToHexStr(self, byte):
        return binascii.hexlify(byte)

    def readData(self, msecs=30000):
        self.ser.flush()
        sleep(0.2)
        ret = self.ser.readline()
        self.ser.flushOutput()
        return ret

    def writeData(self, data, msecs):
        self.ser.write(data)

    def readSignal(self, shex, msecs):
        try:
            self.writeData(shex.encode(), msecs)
            s = self.readData(msecs)
            return s
        except:
            self.ser.flushOutput()
            # self.proxy.ui_errorPython(True)
            self.logger.error("sendSignal exception:%d" % self.s)
            return None

    def sendCommand(self, shex, msecs):
        ret = self.readSignal(shex, msecs)
        if ret != None:
            return ret
        else:
            ret = self.readSignal(shex, msecs)
            return ret

    def convertMoveValue(self, value):  # 0.0003125
        lvalue = value / 0.00015625
        lvalues = round(lvalue, 1)
        llvalues = int(lvalues)
        hexdata = '{:06X}'.format(llvalues)
        return hexdata

    def convertValue(self, value):
        llvalues = int(value)
        hexdata = '{:05X}'.format(llvalues)
        return hexdata

    def z_AbsoluteMove(self, value, msecs, check):
        if check == 0:
            sdata = "7E01%s0" % self.convertMoveValue(value)
        elif check == 1:
            sdata = "7E01%s1" % self.convertMoveValue(value)
        elif check == 2:
            sdata = "7E01%s2" % self.convertMoveValue(value)
        return self.sendCommand(sdata, msecs)

    def z_AbsoluteMove1(self, value, msecs, check):
        if check == 1:
            sdata = "7E10%s1" % self.convertMoveValue(value)
        else:
            sdata = "7E10%s0" % self.convertMoveValue(value)
        return self.sendCommand(sdata, msecs)

    def z_home(self, msecs=50000):
        return self.sendCommand("7E03", msecs)

    def z_home_blade(self, msecs=50000):
        return self.sendCommand("7E03", msecs)

    def motorPositions(self, msecs):
        postionValue = int(self.sendCommand("7E02", msecs))
        realValue = postionValue * 0.00015625
        return realValue

    def downBoardStop(self, msecs):
        return self.sendCommand("7E04", msecs)

    def upBoardStop(self, msecs):
        return self.sendCommand("7E05", msecs)

    def lowCurrent(self, msecs):
        return self.sendCommand("7E210000000B", msecs)

    def HighCurrent(self, msecs):
        return self.sendCommand("7E220000000B", msecs)

    def changeSpeedValue(self, value, msecs):
        sdata = "7E08%s" % self.convertValue(value)
        return self.sendCommand(sdata, msecs)

    def sendCommands(self, shex, msecs):
        try:
            self.writeData(shex, msecs)
            s = self.readData(msecs)
            checkSerial = s.count('s')
            if checkSerial >= 1:
                return 1
            else:
                return -1
        except:
            # self.proxy.ui_errorPython(True)
            # self.logger.error("sendSignal exception:%d" % self.s)
            print("sendCommands error : ", s)
            return None

    def blade_motor_home(self):
        shex = "7E03"
        self.ser.write(shex.encode())
        self.ser.flush()
        sleep(0.2)
        ret = self.ser.readline()
        print("==> serial_Blade, blade Home : ", ret)
        self.ser.flushOutput()
        return ret

    def blade_motor_move(self, value, check):
        if check == 0:
            sdata = "7E01%s0" % self.convertMoveValue(value)
        elif check == 1:
            sdata = "7E01%s1" % self.convertMoveValue(value)
        elif check == 2:
            sdata = "7E01%s2" % self.convertMoveValue(value)

        # self.sendCommand(sdata, msecs)
        self.ser.write(sdata.encode())
        self.ser.flush()
        sleep(0.2)
        ret = self.ser.readline()
        # print("==> serial_Blade, blade move : ", ret)
        self.ser.flushOutput()
        return ret
