import os
import time

# from lief import Object
import asyncio
from collections import OrderedDict


class DebugUart():

    def __init__(self, mcu):
        # super().__init__()
        self.mcu = mcu
        # 0x01 0x42 0x6C 0x6b

    async def set(self, text):
        await asyncio.sleep(0.1)
        #  1 0x42 0x6C 0x6b
        # text = self.ui.textEdit.toPlainText()
        # self.ui.textEdit_2.clear()
        if not text:
            return
        text = text.replace("，", ",")
        text = text.replace(" ", ",")
        text = text.replace("\n", ",")
        data = text.split(",")
        try:
            buf = [
                self.mcu.command["signal_forwarding"],
                0x01,
                0x01,
                0x00,
                0x00,
            ]
            data = [int(x, 16) for x in data if x]
            buf.extend(data)
            text = " ".join([f"0x{x:02X}" for x in data])
            self.mcu.msg_type = "send_command"
            self.mcu.sendSocketMessage(
                code=0,
                msg="命令发送完成",
                device_status=2,
                data={"command": text, "type": "input"},
            )
            self.mcu.msg_type = "mcu"
            # self.ui.textEdit.setText(text)
            # # 刷新界面命令
            # QApplication.processEvents()
            self.mcu.add_send_data_queue(buf)
            loop = asyncio.get_event_loop()
            loop.create_task(self.get(), name="sendCommand3")
        except BaseException as e:
            print("解析错误", e)
            pass

    async def get(self, *args):
        await asyncio.sleep(0.1)
        self.mcu.last_from_mcu_move_respond_data = None
        _s = time.time()
        print("_s", _s)
        while 1:
            await asyncio.sleep(0.1)
            if time.time() - _s > 3:
                return False
            # print("last_from_mcu_move_respond_data 1", time.time() - _s)
            # print(
            #     "last_from_mcu_move_respond_data 2",
            #     self.mcu.last_from_mcu_move_respond_data,
            # )
            if self.mcu.last_from_mcu_move_respond_data is not None:
                break
        receive_data = self.mcu.last_from_mcu_move_respond_data
        receive_data = receive_data[2:]
        print("<------------------get_from_mcu_move_respond_data")
        # self.ui.textEdit_2.setText(" ".join([hex(x) for x in receive_data]))
        text = " ".join([hex(x) for x in receive_data])
        self.mcu.msg_type = "send_command"
        self.mcu.sendSocketMessage(
            code=0,
            msg="命令发送完成",
            device_status=2,
            data={"command": text, "type": "output"},
        )
        self.mcu.msg_type = "mcu"
        if len(receive_data) >= 37:
            # 锁定按键菜单 Lock 为 Disable（0x01 为 Enable）；
            data = OrderedDict()
            # 锁定按键菜单 Lock 为 Disable（0x01 为 Enable）；
            data["锁定按键菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=4, len_data=1
            )
            # 控制模式菜单 Ctrl_Mode 为 CR_VFOC，即 FOC 矢量闭环控制模式；
            data["控制模式菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=5, len_data=1
            )
            # 脉冲端口复用功能菜单 P_PUL 为 PUL_ENA，即使能脉冲输入控制
            data["脉冲端口复用功能菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=6, len_data=1
            )
            # 通讯端口复用功能菜单 P_Serial 为 UART_FUN，即使能串口通讯；
            data["通讯端口复用功能菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=7, len_data=1
            )
            # En 引脚的有效电平菜单 En 为 Hold，即一直有效
            data["En引脚的有效电平菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=8, len_data=1
            )
            # 电机旋转正方向菜单 Dir 为 CW，即顺时针方向
            data["电机旋转正方向菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=9, len_data=1
            )
            # 细分菜单 MStep 为 16 细分;（注：256 细分用 00 表示）
            data["细分菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=10, len_data=1
            )
            # 细分插补功能菜单 MPlyer 为 Enable，即使能细分插补；
            data["细分插补功能菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=11, len_data=1
            )
            # 自动熄屏功能菜单 AutoSDD 为 Disable，即关闭自动熄屏功能
            data["自动熄屏功能菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=12, len_data=1
            )
            # 采样电流低通滤波器强度菜单 LPFilter 为 Def
            data["采样电流低通滤波器强度菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=13, len_data=1
            )
            # 开环模式工作电流菜单 Ma 为 120 0Ma
            data["开环模式工作电流菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=14, len_data=2
            )
            # 闭环模式最大电流菜单 Ma_Limit 为 2200Ma；
            data["闭环模式最大电流菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=16, len_data=2
            )
            # 闭环模式最大转速菜单 Vm_Limit 为 3000RPM（转/每分钟）；
            data["闭环模式最大转速菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=18, len_data=2
            )
            # 电流环带宽菜单 CurBW_Hz 为 1000rad/s；
            data["电流环带宽菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=20, len_data=2
            )
            # 串口波特率菜单 UartBaud 为 115200;（对应小屏幕选项顺序）
            data["串口波特率菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=22, len_data=1
            )
            # CAN 通讯速率菜单 CAN_Baud 为 500000;（对应小屏幕选项顺序）
            data["CAN通讯速率菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=23, len_data=1
            )
            # 通讯校验方式菜单 Checksum 为 0x6B;
            data["通讯校验方式菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=24, len_data=1
            )
            # 控制命令应答菜单 Response 为 Receive，即只返回确认收到命令;
            data["控制命令应答菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=25, len_data=1
            )
            # 通讯控制输入角度精确度选项菜单 S_PosTDP 为 Disable;
            data["通讯控制输入角度精确度选项菜单"] = (
                self.mcu.get_data_from_receive_data(
                    receive_data=receive_data, start=26, len_data=1
                )
            )
            # 堵转保护功能菜单 Clog_Pro 为 Enable，即使能堵转保护;
            data["堵转保护功能菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=27, len_data=1
            )
            # 堵转保护转速阈值菜单 Clog_Rpm 为 8RPM（转/每分钟）;
            data["堵转保护转速阈值菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=28, len_data=2
            )
            # 堵转保护电流阈值菜单 Clog_Ma 为 2000Ma;
            data["堵转保护电流阈值菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=30, len_data=2
            )
            # 堵转保护检测时间阈值菜单 Clog_Ms 为 2000ms;
            data["堵转保护检测时间阈值菜单"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=32, len_data=2
            )
            # 位置到达窗口为 0.3
            data["位置到达窗口"] = self.mcu.get_data_from_receive_data(
                receive_data=receive_data, start=34, len_data=2
            )

            for k, v in data.items():
                print("{}:{}".format(k, v))
            return data
