import serial
import struct

# 定义电池状态常量
BATSTATE_CHARGE_COMPLETE = 0x01
BATSTATE_CHARGE_NOW = 0x02
BATSTATE_CHARGE_LEARN = 0x10
BATSTATE_DISCHAR_NOW = 0x04

# 定义TagResult结构体对应的Python类
class TagResult:
    def __init__(self, data):
        fmt = '<hhiHHBB4x'  # 小端序（little-endian），对应INT16、INT16、INT16、UINT16、UINT16、UINT8、UINT8和4个字节的预留空间
        temp, current, volt, remaintime, capacity, cappercent, state, *_ = struct.unpack(fmt, data)
        
        self.temp = temp / 10 if temp > -3276.8 else float('nan')  # 假设温度值需要除以10得到实际℃数
        self.current = current  # mA
        self.volt = volt  # mV
        self.remaintime = remaintime  # 分钟
        self.capacity = capacity  # mAH
        self.cappercent = cappercent  # 百分比%
        self.state = state  # 充放电状态

    @property
    def chargingStatus(self):
        statusString = ""
        if self.state & BATSTATE_DISCHAR_NOW:
            statusString = f"剩余使用时间约:{self.remaintime}分钟"
            if self.state & BATSTATE_CHARGE_LEARN:
                statusString += "，现在插入充电器可执行充电校准"

        elif (self.state & BATSTATE_CHARGE_NOW) or (self.state & BATSTATE_CHARGE_COMPLETE):
            if self.state & BATSTATE_CHARGE_NOW:
                statusString = "充电中"
            else:
                statusString = "充电完成"
            if self.state & BATSTATE_CHARGE_LEARN:
                statusString += "，正在执行充电校准"

        return statusString

class BatteryManange():

    def __init__(self):
        self.port = 'COM2'  # 替换为实际的串口号
        self.baudRate = 9600
        try:
            self.ser = serial.Serial(self.port, self.baudRate)
        except:
            pass

    def readBatteryInfo(self):
        command = b'\xAA\xFF\x55\xFF\x01\x80\xAA\xEE\x55\xEE'
        self.ser.write(command)
        response = self.ser.read(26)
        
        # 检查包头和包尾是否正确
        if not (response.startswith(b'\xAA\xFF\x55\xFF') and response.endswith(b'\xAA\xEE\x55\xEE')):
            raise ValueError("无效的包头或包尾")

        contentData = response[4:22]
        # 创建TagResult对象并解析电池信息
        result = TagResult(contentData)
        # print(result.chargingStatus)
        return result

    def close(self):
        pass
        # self.ser.close()

