#!/usr/bin/env python
# -*- encoding: utf-8 -*-


from utils.globalvar import SD
from widget.bms_balance import Win_Balance


class BmsBalanceControll:
    def __init__(self):
        self._view = Win_Balance()
        self.init()

    def init(self):
        self._view.balance_control_signal.connect(self._cell_balance_ctl)
        
    def _cell_balance_ctl(self, cmu_id, cell_id, state):
        print(cmu_id, cell_id, state)
        if (cell_id <= 40):
            try:
                data = []
                if len(data) < 8:
                    data += (8 - len(data)) * [0]
                data[0] = 0x02
                data[1] = 0xC0
                data[2] = cmu_id
                data[3] = ((1 if (state > 0) else 0) << (cell_id - 1)) & 0xFF
                data[4] = (((1 if (state > 0) else 0) << (cell_id - 1)) & 0xFF00) >> 8
                data[5] = (((1 if (state > 0) else 0) << (cell_id - 1)) & 0xFF0000) >> 16
                data[6] = (((1 if (state > 0) else 0) << (cell_id - 1)) & 0xFF000000) >> 24
                data[7] = (((1 if (state > 0) else 0) << (cell_id - 1)) & 0xFF00000000) >> 32
                msg = SD.CAN_CONTROL.send((0x18 << 24) | (SD.BCU_ID << 16) | 0x1804, data)
            except:
                self._view.can_connect_error()
        else:
            try:
                data = []
                if len(data) < 8:
                    data += (8 - len(data)) * [0]
                data[0] = 0x03
                data[1] = 0xC0
                data[2] = cmu_id
                data[3] = ((1 if (state > 0) else 0) << (cell_id - 41)) & 0xFF
                data[4] = (((1 if (state > 0) else 0) << (cell_id - 41)) & 0xFF00) >> 8
                data[5] = (((1 if (state > 0) else 0) << (cell_id - 41)) & 0xFF0000) >> 16
                data[6] = (((1 if (state > 0) else 0) << (cell_id - 41)) & 0xFF000000) >> 24
                data[7] = (((1 if (state > 0) else 0) << (cell_id - 41)) & 0xFF00000000) >> 32
                msg = SD.CAN_CONTROL.send((0x18 << 24) | (SD.BCU_ID << 16) | 0x1804, data)
            except:
                self._view.can_connect_error()