Example #1
0
class MainWindow(QMainWindow):
    errorSignal = pyqtSignal(str, str)
    hintSignal = pyqtSignal(str, str)
    updateProgressSignal = pyqtSignal(str, int, int, str)
    updateProgressPrintSignal = pyqtSignal(str)
    showSerialComboboxSignal = pyqtSignal()
    downloadResultSignal = pyqtSignal(bool, str)
    DataPath = "./"
    app = None
    firmware_start_bytes = [b'\x21\xa8', b'\xef\xbe', b'\xad\xde']

    def __init__(self, app):
        super().__init__()
        self.app = app
        self.programStartGetSavedParameters()
        self.initVar()
        self.initWindow()
        self.initEvent()
        self.updateFrameParams()

    def __del__(self):
        pass

    def initVar(self):
        self.burning = False
        self.isDetectSerialPort = False
        self.DataPath = parameters.dataPath
        self.kflash = KFlash(print_callback=self.kflash_py_printCallback)
        self.saveKfpkDir = ""
        self.packing = False
        self.zipTempFiles = []
        self.fileSelectWidgets = []

    def setWindowSize(self, w=520, h=550):
        self.resize(w, h)

    def setFileSelectItemLayout(self, item, isKfpkg):
        if isKfpkg:
            item[4].hide()
            item[2].setStretch(0, 1)
            item[2].setStretch(1, 12)
            item[2].setStretch(3, 4)
            item[2].setStretch(4, 1)
        else:
            item[4].show()
            item[2].setStretch(0, 1)
            item[2].setStretch(1, 8)
            item[2].setStretch(2, 4)
            item[2].setStretch(3, 4)
            item[2].setStretch(4, 1)

    def addFileSelectionItem(self):
        enableCheckbox = QCheckBox()
        filePathWidget = QLineEdit()
        fileBurnAddrWidget = QLineEdit("0x00000")
        openFileButton = QPushButton(tr("OpenFile"))
        removeButton = QPushButton()
        removeButton.setProperty("class", "remove_file_selection")
        oneFilePathWidget = QWidget()
        oneFilePathWidgetLayout = QHBoxLayout()
        oneFilePathWidget.setLayout(oneFilePathWidgetLayout)
        oneFilePathWidgetLayout.addWidget(enableCheckbox)
        oneFilePathWidgetLayout.addWidget(filePathWidget)
        oneFilePathWidgetLayout.addWidget(fileBurnAddrWidget)
        oneFilePathWidgetLayout.addWidget(openFileButton)
        oneFilePathWidgetLayout.addWidget(removeButton)

        filesItemLen = len(self.fileSelectWidgets)
        if filesItemLen != 0 and self.fileSelectWidgets[filesItemLen -
                                                        1][4].isHidden():
            fileBurnAddrWidget.hide()
        else:
            fileBurnAddrWidget.show()
        if filesItemLen == 0:
            removeButton.hide()
        elif filesItemLen == 1:
            self.fileSelectWidgets[0][7].show()
        #                0        1                   2                       3               4                   5               6           7             8
        item = [
            "kfpkg", oneFilePathWidget, oneFilePathWidgetLayout,
            filePathWidget, fileBurnAddrWidget, openFileButton, False,
            removeButton, enableCheckbox
        ]
        # for "bin":    ["bin", oneFilePathWidget,   oneFilePathWidgetLayout, filePathWidget, fileBurnAddrWidget, openFileButton, isFirmware, removeButton, enableCheckbox]
        self.fileSelectWidgets.append(item)

        self.setFileSelectItemLayout(item, True)

        openFileButton.clicked.connect(lambda: self.selectFile(item))
        removeButton.clicked.connect(
            lambda: self.removeFileSelectionItem(item))
        self.fileSelectLayout.addWidget(oneFilePathWidget)
        return item

    def removeFileSelectionItem(self, item):
        if self.packing:
            self.hintSignal.emit(tr("Busy"), tr("Please wait, packing ..."))
            return
        if len(self.fileSelectWidgets) <= 1:
            return
        item[5].clicked.disconnect()
        item[7].clicked.disconnect()
        item[1].setParent(None)
        self.fileSelectWidgets.remove(item)
        self.downloadWidget.resize(self.downloadWidget.width(), 58)
        self.setWindowSize(self.width())

    def initWindow(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        # main layout
        self.frameWidget = QWidget()
        mainWidget = QSplitter(Qt.Horizontal)
        self.frameLayout = QVBoxLayout()
        self.settingWidget = QWidget()
        settingLayout = QVBoxLayout()
        self.settingWidget.setProperty("class", "settingWidget")
        mainLayout = QVBoxLayout()
        self.settingWidget.setLayout(settingLayout)
        mainLayout.addWidget(self.settingWidget)
        mainLayout.setStretch(0, 2)
        menuLayout = QHBoxLayout()

        self.progressHint = QLabel()
        self.progressHint.hide()

        self.progressbarRootWidget = QWidget()
        progressbarLayout = QVBoxLayout()
        self.progressbarRootWidget.setProperty("class", "progressbarWidget")
        self.progressbarRootWidget.setLayout(progressbarLayout)

        self.downloadWidget = QWidget()
        downloadLayout = QVBoxLayout()
        self.downloadWidget.setProperty("class", "downloadWidget")
        self.downloadWidget.setLayout(downloadLayout)

        mainWidget.setLayout(mainLayout)
        # menu
        # -----
        # settings and others
        # -----
        # progress bar
        # -----
        # download button
        # -----
        # status bar
        self.frameLayout.addLayout(menuLayout)
        self.frameLayout.addWidget(mainWidget)
        self.frameLayout.addWidget(self.progressHint)
        self.frameLayout.addWidget(self.progressbarRootWidget)
        self.frameLayout.addWidget(self.downloadWidget)
        self.frameWidget.setLayout(self.frameLayout)
        self.setCentralWidget(self.frameWidget)
        self.setFrameStrentch(1)

        # option layout
        self.langButton = QPushButton()
        self.skinButton = QPushButton()
        self.aboutButton = QPushButton()
        self.langButton.setProperty("class", "menuItemLang")
        self.skinButton.setProperty("class", "menuItem2")
        self.aboutButton.setProperty("class", "menuItem3")
        self.langButton.setObjectName("menuItem")
        self.skinButton.setObjectName("menuItem")
        self.aboutButton.setObjectName("menuItem")
        menuLayout.addWidget(self.langButton)
        menuLayout.addWidget(self.skinButton)
        menuLayout.addWidget(self.aboutButton)
        menuLayout.addStretch(0)

        # widgets file select
        self.fileSelectGroupBox = QGroupBox(tr("SelectFile"))
        # container
        settingLayout.addWidget(self.fileSelectGroupBox)
        self.fileSelectContainerLayout = QVBoxLayout()
        self.fileSelectGroupBox.setLayout(self.fileSelectContainerLayout)
        # file selection
        self.fileSelecWidget = QWidget()
        self.fileSelectLayout = QVBoxLayout()
        self.fileSelecWidget.setLayout(self.fileSelectLayout)
        self.fileSelectContainerLayout.addWidget(self.fileSelecWidget)

        # add file selection item
        self.addFileSelectionItem()

        # add fileselection functions
        mergeBinWidget = QWidget()
        mergeBinWidgetLayout = QHBoxLayout()
        mergeBinWidget.setLayout(mergeBinWidgetLayout)
        self.addFileButton = QPushButton(tr("Add File"))
        self.packFilesButton = QPushButton(tr("Pack to kfpkg"))
        self.mergeBinButton = QPushButton(tr("Merge to .bin"))
        mergeBinWidgetLayout.addWidget(self.addFileButton)
        mergeBinWidgetLayout.addWidget(self.packFilesButton)
        mergeBinWidgetLayout.addWidget(self.mergeBinButton)
        self.fileSelectContainerLayout.addWidget(mergeBinWidget)

        # widgets board select
        boardSettingsGroupBox = QGroupBox(tr("BoardSettings"))
        settingLayout.addWidget(boardSettingsGroupBox)
        boardSettingsLayout = QGridLayout()
        boardSettingsGroupBox.setLayout(boardSettingsLayout)
        self.boardLabel = QLabel(tr("Board"))
        self.boardCombobox = ComboBox()
        self.boardCombobox.addItem(parameters.SipeedMaixDock)
        self.boardCombobox.addItem(parameters.SipeedMaixBit)
        self.boardCombobox.addItem(parameters.SipeedMaixBitMic)
        self.boardCombobox.addItem(parameters.SipeedMaixduino)
        self.boardCombobox.addItem(parameters.SipeedMaixGo)
        self.boardCombobox.addItem(parameters.SipeedMaixGoD)
        self.boardCombobox.addItem(parameters.M5StickV)
        self.boardCombobox.addItem(parameters.KendryteKd233)
        self.boardCombobox.addItem(parameters.kendryteTrainer)
        self.boardCombobox.addItem(parameters.Auto)
        self.burnPositionLabel = QLabel(tr("BurnTo"))
        self.burnPositionCombobox = ComboBox()
        self.burnPositionCombobox.addItem(tr("Flash"))
        self.burnPositionCombobox.addItem(tr("SRAM"))
        boardSettingsLayout.addWidget(self.boardLabel, 0, 0)
        boardSettingsLayout.addWidget(self.boardCombobox, 0, 1)
        boardSettingsLayout.addWidget(self.burnPositionLabel, 1, 0)
        boardSettingsLayout.addWidget(self.burnPositionCombobox, 1, 1)

        # widgets serial settings
        serialSettingsGroupBox = QGroupBox(tr("SerialSettings"))
        serialSettingsLayout = QGridLayout()
        serialPortLabek = QLabel(tr("SerialPort"))
        serailBaudrateLabel = QLabel(tr("SerialBaudrate"))
        slowModeLabel = QLabel(tr("Speed mode"))
        self.serialPortCombobox = ComboBox()
        self.serailBaudrateCombobox = ComboBox()
        self.serailBaudrateCombobox.addItem("115200")
        self.serailBaudrateCombobox.addItem("921600")
        self.serailBaudrateCombobox.addItem("1500000")
        self.serailBaudrateCombobox.addItem("2000000")
        self.serailBaudrateCombobox.addItem("3500000")
        self.serailBaudrateCombobox.addItem("4000000")
        self.serailBaudrateCombobox.addItem("4500000")
        self.serailBaudrateCombobox.setCurrentIndex(1)
        self.serailBaudrateCombobox.setEditable(True)
        self.slowModeCombobox = ComboBox()
        self.slowModeCombobox.addItem(tr("Slow mode"))
        self.slowModeCombobox.addItem(tr("Fast mode"))
        slowModeLabel.setToolTip(tr("slow mode tips"))
        self.slowModeCombobox.setToolTip(tr("slow mode tips"))

        serialSettingsLayout.addWidget(serialPortLabek, 0, 0)
        serialSettingsLayout.addWidget(serailBaudrateLabel, 1, 0)
        serialSettingsLayout.addWidget(slowModeLabel, 2, 0)
        serialSettingsLayout.addWidget(self.serialPortCombobox, 0, 1)
        serialSettingsLayout.addWidget(self.serailBaudrateCombobox, 1, 1)
        serialSettingsLayout.addWidget(self.slowModeCombobox, 2, 1)
        serialSettingsGroupBox.setLayout(serialSettingsLayout)
        settingLayout.addWidget(serialSettingsGroupBox)

        # set stretch
        settingLayout.setStretch(0, 1)
        settingLayout.setStretch(1, 1)
        settingLayout.setStretch(2, 2)

        # widgets progress bar

        self.progressbar = QProgressBar(self.progressbarRootWidget)
        self.progressbar.setValue(0)
        self.progressbarRootWidget.hide()

        # widgets download area
        self.downloadButton = QPushButton(tr("Download"))
        downloadLayout.addWidget(self.downloadButton)

        # main window
        self.statusBarStauts = QLabel()
        self.statusBarStauts.setMinimumWidth(80)
        self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                     ("#1aac2d", tr("DownloadHint")))
        self.statusBar().addWidget(self.statusBarStauts)

        self.setWindowSize()
        self.MoveToCenter()
        self.setWindowTitle(parameters.appName + " V" +
                            str(helpAbout.versionMajor) + "." +
                            str(helpAbout.versionMinor))
        icon = QIcon()
        print("icon path:" + self.DataPath + "/" + parameters.appIcon)
        icon.addPixmap(QPixmap(self.DataPath + "/" + parameters.appIcon),
                       QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        if sys.platform == "win32":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                parameters.appName)

        self.show()
        self.progressbar.setGeometry(10, 0,
                                     self.downloadWidget.width() - 25, 40)
        print("config file path:", parameters.configFilePath)

    def initEvent(self):
        self.serialPortCombobox.clicked.connect(self.portComboboxClicked)
        self.errorSignal.connect(self.errorHint)
        self.hintSignal.connect(self.hint)
        self.downloadResultSignal.connect(self.downloadResult)
        self.showSerialComboboxSignal.connect(self.showCombobox)
        self.updateProgressSignal.connect(self.updateProgress)
        self.updateProgressPrintSignal.connect(self.updateProgressPrint)
        self.langButton.clicked.connect(self.langChange)
        self.skinButton.clicked.connect(self.skinChange)
        self.aboutButton.clicked.connect(self.showAbout)
        self.downloadButton.clicked.connect(self.download)

        self.addFileButton.clicked.connect(
            lambda: self.fileSelectLayout.addWidget(self.addFileSelectionItem(
            )[1]))
        self.packFilesButton.clicked.connect(self.packFiles)
        self.mergeBinButton.clicked.connect(self.mergeBin)

        self.myObject = MyClass(self)
        slotLambda = lambda: self.indexChanged_lambda(self.myObject)
        self.serialPortCombobox.currentIndexChanged.connect(slotLambda)

    def setFrameStrentch(self, mode):
        if mode == 0:
            self.frameLayout.setStretch(0, 1)
            self.frameLayout.setStretch(1, 3)
            self.frameLayout.setStretch(2, 3)
            self.frameLayout.setStretch(3, 1)
            self.frameLayout.setStretch(4, 1)
            self.frameLayout.setStretch(5, 1)
        else:
            self.frameLayout.setStretch(0, 0)
            self.frameLayout.setStretch(1, 0)
            self.frameLayout.setStretch(2, 1)
            self.frameLayout.setStretch(3, 1)
            self.frameLayout.setStretch(4, 1)
            self.frameLayout.setStretch(5, 1)

    # @QtCore.pyqtSlot(str)
    def indexChanged_lambda(self, obj):
        mainObj = obj.arg
        self.serialPortCombobox.setToolTip(
            mainObj.serialPortCombobox.currentText())

    def portComboboxClicked(self):
        self.detectSerialPort()

    def MoveToCenter(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def highlightFirmwarePath(self, item, firmware):
        if firmware:
            item[3].setProperty("class", "qLineEditHighlight")
            item[4].setText("0x00000")
        else:
            item[3].setProperty("class", "qLineEditNormal")
        self.frameWidget.style().unpolish(item[3])
        self.frameWidget.style().polish(item[3])
        self.frameWidget.update()

    def fileSelectShow(self,
                       item,
                       name,
                       addr=None,
                       firmware=None,
                       enable=True,
                       loadFirst=False):
        isKfpkg = False
        if self.isKfpkg(name):
            isKfpkg = True
        if not item:  # add item from param
            if loadFirst:
                item = self.fileSelectWidgets[0]
            else:
                item = self.addFileSelectionItem()
            if isKfpkg:
                self.highlightFirmwarePath(item, False)
                self.setFileSelectItemLayout(item, True)
            else:
                item[4].setText("0x%06x" % (addr))
                self.setFileSelectItemLayout(item, False)
                if self.isFileFirmware(name):
                    self.highlightFirmwarePath(item, True)
                    item[6] = True
                else:
                    self.highlightFirmwarePath(item, False)
                    item[6] = False
            item[3].setText(name)
            item[8].setChecked(enable)
            return

        if isKfpkg:
            self.setFileSelectItemLayout(item, True)
            self.highlightFirmwarePath(item, False)
            # disable other items
            for i in self.fileSelectWidgets:
                i[8].setChecked(False)
            # only enable this kfpkg
            item[8].setChecked(True)
        else:
            self.setFileSelectItemLayout(item, False)
            if self.isFileFirmware(name):
                self.highlightFirmwarePath(item, True)
                item[4].setText("0x00000")
            else:
                self.highlightFirmwarePath(item, False)
            # disable kfpkg file
            for i in self.fileSelectWidgets:
                if self.isKfpkg(i[3].text()):
                    i[8].setChecked(False)
            # enable this bin file
            item[8].setChecked(True)
        item[3].setText(name)

    # return: ("bin", [(file path, burn addr, add prefix, enable),...])
    #      or ("kfpkg", file path)
    #      or (None, msg)
    def getBurnFilesInfo(self):
        files = []
        fileType = ""
        for item in self.fileSelectWidgets:
            path = item[3].text().strip()
            enable = item[8].isChecked()
            try:
                addr = int(item[4].text(), 16)
            except Exception:
                addr = 0
            if not enable:
                continue
            if path == "" or not os.path.exists(path):
                return (None, tr("Line {}: ").format(
                    self.fileSelectWidgets.index(item) + 1) +
                        tr("File path error") + ":" + path)
            if self.isKfpkg(path):
                if fileType == "bin":
                    return (
                        None,
                        tr("Can not select kfpkg and bin files at the time"))
                fileType = "kfpkg"
                if len(files) != 0:
                    return (None, tr("Only support one kfpkg file"))
                files = path
            else:
                if fileType == "kfpkg":
                    return (
                        None,
                        tr("Can not select kfpkg and bin files at the time"))
                fileType = "bin"
                files.append((path, addr, item[6], enable))
        return (fileType, files)

    class KFPKG():
        def __init__(self):
            self.fileInfo = {"version": "0.1.0", "files": []}
            self.filePath = {}
            self.burnAddr = []

        def addFile(self, addr, path, prefix=False):
            if not os.path.exists(path):
                raise ValueError(tr("FilePathError"))
            if addr in self.burnAddr:
                raise ValueError(
                    tr("Burn dddr duplicate") + ":0x%06x" % (addr))
            f = {}
            f_name = os.path.split(path)[1]
            f["address"] = addr
            f["bin"] = f_name
            f["sha256Prefix"] = prefix
            self.fileInfo["files"].append(f)
            self.filePath[f_name] = path
            self.burnAddr.append(addr)

        def listDumps(self):
            kfpkg_json = json.dumps(self.fileInfo, indent=4)
            return kfpkg_json

        def listDump(self, path):
            with open(path, "w") as f:
                f.write(json.dumps(self.fileInfo, indent=4))

        def listLoads(self, kfpkgJson):
            self.fileInfo = json.loads(kfpkgJson)

        def listLload(self, path):
            with open(path) as f:
                self.fileInfo = json.load(f)

        def save(self, path):
            listName = os.path.join(tempfile.gettempdir(),
                                    "kflash_gui_tmp_list.json")
            self.listDump(listName)
            try:
                with zipfile.ZipFile(path, "w") as zip:
                    for name, path in self.filePath.items():
                        zip.write(path,
                                  arcname=name,
                                  compress_type=zipfile.ZIP_DEFLATED)
                    zip.write(listName,
                              arcname="flash-list.json",
                              compress_type=zipfile.ZIP_DEFLATED)
                    zip.close()
            except Exception as e:
                os.remove(listName)
                raise e
            os.remove(listName)

    def checkFilesAddrValid(self, fileType, files):
        if fileType == "bin":
            files.sort(key=lambda file: file[1])
            startAddr = -1
            fileSize = 0
            fileShortLast = ""
            count = 0
            for file, addr, firmware, enable in files:
                if not enable:
                    continue
                fileShort = ".../" + "/".join(file.split("/")[-2:])
                if startAddr + fileSize > addr:
                    return (
                        False, tr("File address error") +
                        ": {} {} 0x{:X}, {} {} {} [0x{:X},0x{:X}]".format(
                            fileShort, tr("start from"), addr, tr("but file"),
                            fileShortLast, tr("address range is"), startAddr,
                            startAddr + fileSize))
                fileSize = os.path.getsize(file)
                startAddr = addr
                fileShortLast = fileShort
                count += 1
            if count == 0:
                return (False, tr("No file selected"))
        return (True, "")

    def packFiles(self):
        if self.packing:
            self.hintSignal.emit(tr("Busy"), tr("Please wait, packing ..."))
            return
        self.packing = True

        fileType, files = self.getBurnFilesInfo()
        if not fileType:
            self.errorSignal.emit(tr("Error"), files)
            self.packing = False
            return

        if fileType == "kfpkg":
            self.errorSignal.emit(tr("Error"), tr("Can not pack kfpkg"))
            self.packing = False
            return

        ok, msg = self.checkFilesAddrValid(fileType, files)
        if not ok:
            self.errorSignal.emit(tr("Error"), msg)
            self.packing = False
            return

        # select saving path
        if not os.path.exists(self.saveKfpkDir):
            self.saveKfpkDir = os.getcwd()
        fileName_choose, filetype = QFileDialog.getSaveFileName(
            self, tr("Save File"), self.saveKfpkDir, "k210 packages (*.kfpkg)")
        if fileName_choose == "":
            # self.errorSignal.emit(tr("Error"), tr("File path error"))
            self.packing = False
            return
        if not self.isKfpkg(fileName_choose):
            fileName_choose += ".kfpkg"
        self.saveKfpkDir = os.path.split(fileName_choose)[0]

        # pack and save
        t = threading.Thread(target=self.packFileProccess,
                             args=(
                                 files,
                                 fileName_choose,
                             ))
        t.setDaemon(True)
        t.start()

    def packFileProccess(self, files, fileSaveName):
        # generate flash-list.json
        kfpkg = self.KFPKG()
        try:
            for path, addr, prefix, enable in files:
                if enable:
                    kfpkg.addFile(addr, path, prefix)
        except Exception as e:
            self.errorSignal.emit(tr("Error"),
                                  tr("Pack kfpkg fail") + ":" + str(e))
            self.packing = False
            return

        # write kfpkg file
        try:
            kfpkg.save(fileSaveName)
        except Exception as e:
            self.errorSignal.emit(tr("Error"),
                                  tr("Pack kfpkg fail") + ":" + str(e))
            self.packing = False
            return
        self.hintSignal.emit(tr("Success"), tr("Save kfpkg success"))
        self.packing = False

    def getBurnFilesInfoFromKfpkg(self, kfpkg):
        tempDir = tempfile.gettempdir()
        listFileName = "flash-list.json"
        try:
            zip = zipfile.ZipFile(kfpkg, mode="r")
            zip.extract(listFileName, tempDir)
            with open(tempDir + "/" + listFileName) as f:
                info = json.load(f)
            filesInfo = {}
            for fileInfo in info["files"]:
                filesInfo[fileInfo["bin"]] = [
                    fileInfo["address"], fileInfo["sha256Prefix"]
                ]
            print(filesInfo, zip.namelist())
            binFiles = zip.namelist()
            binFiles.remove(listFileName)
            for file in binFiles:
                zip.extract(file, tempDir)
                self.zipTempFiles.append(
                    (tempDir + "/" + file, filesInfo[file][0],
                     filesInfo[file][1], True))
            zip.close()
        except Exception as e:
            return (None, str(e))
        return (self.zipTempFiles, "")

    def cleanKfpkgTempFiles(self):
        tempDir = tempfile.gettempdir()
        try:
            for file in self.zipTempFiles:
                os.remove(file[0])
        except Exception:
            pass
        self.zipTempFiles = []

    def mergeBin(self):
        if self.packing:
            self.hintSignal.emit(tr("Busy"), tr("Please wait, packing ..."))
            return
        self.packing = True
        fileType, files = self.getBurnFilesInfo()
        if not fileType:
            self.errorSignal.emit(tr("Error"), files)
            self.cleanKfpkgTempFiles()
            self.packing = False
            return
        if fileType == "kfpkg":
            files, msg = self.getBurnFilesInfoFromKfpkg(files)
            fileType = "bin"
            if not files:
                self.errorSignal.emit(tr("Error"), msg)
                self.cleanKfpkgTempFiles()
                self.packing = False
                return

        ok, msg = self.checkFilesAddrValid(fileType, files)
        if not ok:
            self.errorSignal.emit(tr("Error"), msg)
            self.packing = False
            self.cleanKfpkgTempFiles()
            return

        # select saving path
        if not os.path.exists(self.saveKfpkDir):
            self.saveKfpkDir = os.getcwd()
        fileName_choose, filetype = QFileDialog.getSaveFileName(
            self, tr("Save File"), self.saveKfpkDir, "Binary file (*.bin)")
        if fileName_choose == "":
            # self.errorSignal.emit(tr("Error"), tr("File path error"))
            self.packing = False
            self.cleanKfpkgTempFiles()
            return
        if not fileName_choose.endswith(".bin"):
            fileName_choose += ".bin"
        self.saveKfpkDir = os.path.split(fileName_choose)[0]

        # pack and save
        t = threading.Thread(target=self.mergeBinProccess,
                             args=(
                                 files,
                                 fileName_choose,
                             ))
        t.setDaemon(True)
        t.start()

    def mergeBinProccess(self, files, fileSaveName):
        self.updateProgressPrintSignal.emit(tr("Merging, please wait ..."))
        files.sort(key=lambda file: file[1])
        bin = b''
        aesFlag = b'\x00'
        startAddrLast = files[0][1]
        fileSizeLast = 0
        if files[0][2]:  # firmware
            name = files[0][0]
            size = os.path.getsize(name)
            f = open(name, "rb")
            firmware = f.read()
            f.close()

            bin += aesFlag  # add aes key flag
            bin += struct.pack('I', size)  # add firmware length
            bin += firmware  # add firmware content
            sha256Hash = hashlib.sha256(bin).digest()
            bin += sha256Hash  # add parity

            startAddrLast = 0
            fileSizeLast = len(bin)
            files.remove(files[0])

        for file, addr, firmware, enable in files:
            if not enable:
                continue
            fillLen = addr - (startAddrLast + fileSizeLast)
            if fillLen > 0:  # fill 0xFF
                fill = bytearray([0xFF for i in range(fillLen)])
                bin += fill
            with open(file, "rb") as f:  # add bin file content
                bin += f.read()
            startAddrLast = addr
            fileSizeLast = os.path.getsize(file)
        with open(fileSaveName, "wb") as f:
            f.write(bin)
        self.updateProgressPrintSignal.emit(tr("Save merged bin file success"))
        self.hintSignal.emit(tr("Success"), tr("Save merged bin file success"))
        self.packing = False
        self.cleanKfpkgTempFiles()

    def selectFile(self, item):
        if self.packing:
            self.hintSignal.emit(tr("Busy"), tr("Please wait, packing ..."))
            return
        index = self.fileSelectWidgets.index(item)
        oldPath = item[3].text()
        if oldPath == "" and index > 0:
            oldPath = self.fileSelectWidgets[index - 1][3].text()
        if oldPath == "":
            oldPath = os.getcwd()
        fileName_choose, filetype = QFileDialog.getOpenFileName(
            self, tr("SelectFile"), oldPath,
            "All Files (*);;bin Files (*.bin);;k210 packages (*.kfpkg);;kmodel (*.kmodel);;encrypted kmodle(*.smodel)"
        )  # 设置文件扩展名过滤,用双分号间隔

        if fileName_choose == "":
            return
        if not self.isFileValid(fileName_choose):
            self.errorSignal.emit(tr("Error"), tr("File path error"))
            return
        self.fileSelectShow(item, fileName_choose)

    def errorHint(self, title, str):
        QMessageBox.critical(self, title, str)

    def hint(self, title, str):
        QMessageBox.information(self, title, str)

    def findSerialPort(self):
        self.port_list = list(serial.tools.list_ports.comports())
        return self.port_list

    def portChanged(self):
        self.serialPortCombobox.setCurrentIndex(0)
        self.serialPortCombobox.setToolTip(str(self.portList[0]))

    def detectSerialPort(self):
        if not self.isDetectSerialPort:
            self.isDetectSerialPort = True
            t = threading.Thread(target=self.detectSerialPortProcess)
            t.setDaemon(True)
            t.start()

    def showCombobox(self):
        self.serialPortCombobox.showPopup()

    def isKfpkg(self, name):
        if name.endswith(".kfpkg"):
            return True
        return False

    def isFileFirmware(self, name):
        isFirmware = False
        if name.endswith(".bin"):
            f = open(name, "rb")
            start_bytes = f.read(6)
            f.close()
            for flags in self.firmware_start_bytes:
                if flags in start_bytes:
                    isFirmware = True
                    break
        return isFirmware

    def isFileValid(self, name):
        if not os.path.exists(name):
            return False
        return True

    def detectSerialPortProcess(self):
        while (1):
            portList = self.findSerialPort()
            if len(portList) > 0:
                currText = self.serialPortCombobox.currentText()
                self.serialPortCombobox.clear()
                for i in portList:
                    showStr = str(i[0]) + " (" + str(i[1]) + ")"
                    self.serialPortCombobox.addItem(showStr)
                index = self.serialPortCombobox.findText(currText)
                if index >= 0:
                    self.serialPortCombobox.setCurrentIndex(index)
                else:
                    self.serialPortCombobox.setCurrentIndex(0)
                break
            time.sleep(1)
        self.showSerialComboboxSignal.emit()
        self.isDetectSerialPort = False

    def programExitSaveParameters(self):
        paramObj = paremeters_save.ParametersToSave()
        paramObj.board = self.boardCombobox.currentText()
        paramObj.burnPosition = self.burnPositionCombobox.currentText()
        paramObj.baudRate = self.serailBaudrateCombobox.currentIndex()
        paramObj.skin = self.param.skin
        paramObj.language = translation.current_lang
        for item in self.fileSelectWidgets:
            path = item[3].text()
            try:
                addr = int(item[4].text(), 16)
            except Exception:
                addr = 0
            fileInfo = (path, addr, item[6], item[8].isChecked())
            paramObj.files.append(fileInfo)
        if self.slowModeCombobox.currentIndex() == 0:
            paramObj.slowMode = True
        else:
            paramObj.slowMode = False
        paramObj.save(parameters.configFilePath)

    def programStartGetSavedParameters(self):
        paramObj = paremeters_save.ParametersToSave()
        paramObj.load(parameters.configFilePath)
        translation.setLanguage(paramObj.language)
        self.param = paramObj

    def updateFrameParams(self):
        pathLen = len(self.param.files)
        if pathLen != 0:
            if len(self.param.files[0]
                   ) != 4:  # [ (path, addr, prefix, enable), ...]
                return
            count = 0
            for path, addr, firmware, enable in self.param.files:
                firmware = None if (not firmware) else True
                if count == 0:
                    self.fileSelectShow(None,
                                        path,
                                        addr,
                                        firmware,
                                        enable=enable,
                                        loadFirst=True)
                else:
                    self.fileSelectShow(None,
                                        path,
                                        addr,
                                        firmware,
                                        enable=enable,
                                        loadFirst=False)
                count += 1
        self.boardCombobox.setCurrentText(self.param.board)
        self.burnPositionCombobox.setCurrentText(self.param.burnPosition)
        self.serailBaudrateCombobox.setCurrentIndex(self.param.baudRate)
        if self.param.slowMode:
            self.slowModeCombobox.setCurrentIndex(0)
        else:
            self.slowModeCombobox.setCurrentIndex(1)

    def closeEvent(self, event):
        try:
            self.programExitSaveParameters()
        finally:
            event.accept()

    def langChange(self):
        if self.param.language == translation.language_en:
            translation.setLanguage(translation.language_zh)
            lang = tr("Chinese language")
        else:
            translation.setLanguage(translation.language_en)
            lang = tr("English language")

        self.hint(
            tr("Hint"),
            tr("Language Changed to ") + lang + "\n" +
            tr("Reboot to take effect"))
        self.frameWidget.style().unpolish(self.downloadButton)
        self.frameWidget.style().polish(self.downloadButton)
        self.frameWidget.update()

    def skinChange(self):
        if self.param.skin == 1:  # light
            file = open(self.DataPath + '/assets/qss/style-dark.qss', "r")
            self.param.skin = 2
        else:  # elif self.param.skin == 2: # dark
            file = open(self.DataPath + '/assets/qss/style.qss', "r")
            self.param.skin = 1
        self.app.setStyleSheet(file.read().replace("$DataPath", self.DataPath))
        file.close()

    def showAbout(self):
        QMessageBox.information(
            self, tr("About"),
            "<h1 style='color:#f75a5a';margin=10px;>" + parameters.appName +
            '</h1><br><b style="color:#08c7a1;margin = 5px;">V' +
            str(helpAbout.versionMajor) + "." + str(helpAbout.versionMinor) +
            "." + str(helpAbout.versionDev) + "</b><br><br>" + helpAbout.date +
            "<br><br>" + tr("help str") + "<br><br>" + helpAbout.strAbout())

    def autoUpdateDetect(self):
        auto = autoUpdate.AutoUpdate()
        if auto.detectNewVersion():
            self.hintSignal.emit(
                tr("Upgrade"),
                tr("Upgrade available, please download new release in release page"
                   ))
            auto.OpenBrowser()

    def openDevManagement(self):
        os.system('start devmgmt.msc')

    def updateProgress(self, fileTypeStr, current, total, speedStr):
        currBurnPos = self.burnPositionCombobox.currentText()
        if currBurnPos == tr("SRAM") or currBurnPos == tr_en("SRAM"):
            fileTypeStr = tr("ToSRAM")
        percent = current / float(total) * 100
        hint = "<font color=%s>%s %s:</font>   <font color=%s> %.2f%%</font>   <font color=%s> %s</font>" % (
            "#ff7575", tr("Downloading"), fileTypeStr, "#2985ff", percent,
            "#1aac2d", speedStr)
        self.progressHint.setText(hint)
        self.progressbar.setValue(percent)

    def updateProgressPrint(self, str):
        self.statusBarStauts.setText(str)

    def kflash_py_printCallback(self, *args, **kwargs):
        # end = kwargs.pop('end', "\n")
        msg = ""
        for i in args:
            msg += str(i)
        msg.replace("\n", " ")
        self.updateProgressPrintSignal.emit(msg)

    def progress(self, fileTypeStr, current, total, speedStr):
        self.updateProgressSignal.emit(fileTypeStr, current, total, speedStr)

    def download(self):
        if self.packing:
            self.hintSignal.emit(tr("Busy"), tr("Please wait, packing ..."))
            return
        if self.burning:
            self.terminateBurn()
            return
        fileType, filesInfo = self.getBurnFilesInfo()
        if not fileType or not filesInfo:
            self.errorSignal.emit(tr("Error"), tr("File path error"))
            return

        self.burning = True
        # if not self.checkFileName(filename):
        #     self.errorSignal.emit(tr("Error"), tr("FilePathError"))
        #     self.burning = False
        #     return
        color = False
        board = "dan"
        boardText = self.boardCombobox.currentText()
        if boardText == parameters.SipeedMaixGo:
            board = "goE"
        elif boardText == parameters.SipeedMaixGoD:
            board = "goD"
        elif boardText == parameters.SipeedMaixduino:
            board = "maixduino"
        elif boardText == parameters.SipeedMaixBit:
            board = "bit"
        elif boardText == parameters.SipeedMaixBitMic:
            board = "bit_mic"
        elif boardText == parameters.KendryteKd233:
            board = "kd233"
        elif boardText == parameters.kendryteTrainer:
            board = "trainer"
        elif boardText == parameters.M5StickV:
            board = "goE"
        elif boardText == parameters.Auto:
            board = None

        sram = False
        if self.burnPositionCombobox.currentText()==tr("SRAM") or \
            self.burnPositionCombobox.currentText()==tr_en("SRAM"):
            sram = True
        try:
            baud = int(self.serailBaudrateCombobox.currentText())
        except Exception:
            self.errorSignal.emit(tr("Error"), tr("BaudrateError"))
            self.burning = False
            return
        dev = ""
        try:
            dev = self.serialPortCombobox.currentText().split()[0]
        except Exception:
            pass
        if dev == "":
            self.errorSignal.emit(tr("Error"), tr("PleaseSelectSerialPort"))
            self.burning = False
            return
        slow = self.slowModeCombobox.currentIndex() == 0
        # hide setting widgets
        self.setFrameStrentch(1)
        self.settingWidget.hide()
        self.progressbar.setValue(0)
        self.progressbar.setGeometry(10, 0,
                                     self.downloadWidget.width() - 25, 40)
        self.progressbarRootWidget.show()
        self.progressHint.show()
        self.downloadButton.setText(tr("Cancel"))
        self.downloadButton.setProperty("class", "redbutton")
        self.downloadButton.style().unpolish(self.downloadButton)
        self.downloadButton.style().polish(self.downloadButton)
        self.downloadButton.update()
        self.statusBarStauts.setText("<font color=%s>%s ...</font>" %
                                     ("#1aac2d", tr("Downloading")))
        hint = "<font color=%s>%s</font>" % ("#ff0d0d", tr("DownloadStart"))
        self.progressHint.setText(hint)
        # download
        self.burnThread = threading.Thread(target=self.flashBurnProcess,
                                           args=(dev, baud, board, sram,
                                                 fileType, filesInfo,
                                                 self.progress, color, slow))
        self.burnThread.setDaemon(True)
        self.burnThread.start()

    def flashBurnProcess(self, dev, baud, board, sram, fileType, files,
                         callback, color, slow):
        success = True
        errMsg = ""
        tmpFile = ""

        if fileType == "kfpkg":
            if sram:
                errMsg = tr("only support bin file when Download to SRAM")
                success = False
            else:
                filename = files
        else:  #generate kfpkg
            if sram:
                filename = files[0][0]
            else:
                tmpFile = os.path.join(tempfile.gettempdir(),
                                       "kflash_gui_tmp.kfpkg")
                kfpkg = self.KFPKG()
                try:
                    for path, addr, prefix, enable in files:
                        if enable:
                            kfpkg.addFile(addr, path, prefix)
                    kfpkg.save(tmpFile)
                    filename = os.path.abspath(tmpFile)
                except Exception as e:
                    try:
                        os.remove(tmpFile)
                    except Exception:
                        print("can not delete temp file:", tmpFile)
                    errMsg = tr("Pack kfpkg fail") + ":" + str(e)
                    success = False
        if success:
            try:
                if board:
                    self.kflash.process(terminal=False,
                                        dev=dev,
                                        baudrate=baud,
                                        board=board,
                                        sram=sram,
                                        file=filename,
                                        callback=callback,
                                        noansi=not color,
                                        slow_mode=slow)
                else:
                    self.kflash.process(terminal=False,
                                        dev=dev,
                                        baudrate=baud,
                                        sram=sram,
                                        file=filename,
                                        callback=callback,
                                        noansi=not color,
                                        slow_mode=slow)
            except Exception as e:
                errMsg = tr2(str(e))
                if str(e) != "Burn SRAM OK":
                    success = False
        if tmpFile != "":
            try:
                os.remove(filename)
            except Exception:
                print("Can not delete tmp file:", filename)
        if success:
            self.downloadResultSignal.emit(True, errMsg)
        else:
            self.downloadResultSignal.emit(False, errMsg)
        self.burning = False

    def downloadResult(self, success, msg):
        if success:
            self.hintSignal.emit(tr("Success"), tr("DownloadSuccess"))
            self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                         ("#1aac2d", tr("DownloadSuccess")))
        else:
            if msg == tr("Cancel"):
                self.statusBarStauts.setText(
                    "<font color=%s>%s</font>" %
                    ("#ff1d1d", tr("DownloadCanceled")))
            else:
                msg = tr("ErrorSettingHint") + "\n\n" + msg
                self.errorSignal.emit(tr("Error"), msg)
                self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                             ("#ff1d1d", tr("DownloadFail")))
            self.progressHint.setText("")
        self.downloadButton.setText(tr("Download"))
        self.downloadButton.setProperty("class", "normalbutton")
        self.downloadButton.style().unpolish(self.downloadButton)
        self.downloadButton.style().polish(self.downloadButton)
        self.downloadButton.update()
        self.setFrameStrentch(0)
        self.progressbarRootWidget.hide()
        self.progressHint.hide()
        self.settingWidget.show()
        self.burning = False

    def terminateBurn(self):
        hint = "<font color=%s>%s</font>" % ("#ff0d0d",
                                             tr("DownloadCanceling"))
        self.progressHint.setText(hint)
        self.kflash.kill()
Example #2
0
class TCP_UDP(COMM):
    '''
        call sequence:
            onInit
            onWidget
            onUiInitDone
                isConnected
                send
            getConfig
    '''
    id = "tcp_udp"
    name = "TCP UDP"
    showSwitchSignal = pyqtSignal(ConnectionStatus)
    updateTargetSignal = pyqtSignal(str)
    updateClientsSignal = pyqtSignal(bool, tuple)

    def onInit(self, config):
        self.conn = None
        self.config = config
        default = {
            "protocol": "tcp",
            "mode": "client",
            "target": ["127.0.0.1:2345", ["127.0.0.1:2345"]],
            "port": 2345,
            "auto_reconnect": False,
            "auto_reconnect_interval": 1.0
        }
        for k in default:
            if not k in self.config:
                self.config[k] = default[k]
        self.widgetConfMap = {
            "protocol": None,
            "mode": None,
            "target": None,
            "port": None,
            "auto_reconnect": None,
            "auto_reconnect_interval": None
        }
        self.isOpened = False
        self.busy = False
        self.status = ConnectionStatus.CLOSED
        self.widget = None
        self.serverModeClientsConns = {
            # "127.0.0.1:76534": conn
        }
        self.serverModeSelectedClient = None  # None means all clients, or ip:port string

    def disconnect(self):
        if self.isConnected():
            self.openCloseSerial()

    def onDel(self):
        if self.isConnected():
            self.openCloseSerial()

    def __del__(self):
        try:
            self.status = ConnectionStatus.CLOSED
            if not self.conn is None:
                self.conn.close()
                self.conn = None
        except Exception:
            pass
        time.sleep(
            0.05
        )  # wait for child threads, not wait also ok, cause child threads are daemon

    def getConfig(self):
        '''
            get config, dict type
        '''
        return self.config

    def onUiInitDone(self):
        for key in self.config:
            self.setSerialConfig(key, self.widgetConfMap[key],
                                 self.config[key])

    def onWidget(self):
        serialSetting = QWidget()
        self.serialSettingsLayout = QGridLayout()
        protocolLabel = QLabel(_("Protocol"))
        self.modeLabel = QLabel(_("Mode"))
        self.targetLabel = QLabel(_("Target"))
        self.targetCombobox = ComboBox()
        self.targetCombobox.setEditable(True)
        self.portLabel = QLabel(_("Port"))
        self.portLabel.hide()
        self.porttEdit = QLineEdit()
        protocolWidget = QWidget()
        modeWidget = QWidget()
        layoutProtocol = QHBoxLayout()
        layoutMode = QHBoxLayout()
        protocolWidget.setLayout(layoutProtocol)
        modeWidget.setLayout(layoutMode)
        self.protoclTcpRadioBtn = QRadioButton("TCP")
        self.protoclUdpRadioBtn = QRadioButton("UDP")
        self.protoclTcpRadioBtn.setChecked(True)
        layoutProtocol.addWidget(self.protoclTcpRadioBtn)
        layoutProtocol.addWidget(self.protoclUdpRadioBtn)
        self.modeClientRadioBtn = QRadioButton("Client")
        self.modeServerRadioBtn = QRadioButton("Server")
        self.modeClientRadioBtn.setChecked(True)
        layoutMode.addWidget(self.modeClientRadioBtn)
        layoutMode.addWidget(self.modeServerRadioBtn)
        self.clientsCombobox = ComboBox()
        self.clientsCombobox.addItem("0 | " + _("All clients"))
        self.disconnetClientBtn = QPushButton(_("Disconnect"))
        self.autoReconnetLable = QLabel(_("Auto reconnect"))
        self.autoReconnect = QCheckBox()
        self.autoReconnectIntervalEdit = QLineEdit("1.0")
        self.serialOpenCloseButton = QPushButton(_("OPEN"))
        self.serialSettingsLayout.addWidget(protocolLabel, 0, 0)
        self.serialSettingsLayout.addWidget(protocolWidget, 0, 1, 1, 2)
        self.serialSettingsLayout.addWidget(self.modeLabel, 1, 0)
        self.serialSettingsLayout.addWidget(modeWidget, 1, 1, 1, 2)
        self.serialSettingsLayout.addWidget(self.targetLabel, 2, 0)
        self.serialSettingsLayout.addWidget(self.targetCombobox, 2, 1, 1, 2)
        self.serialSettingsLayout.addWidget(self.portLabel, 3, 0)
        self.serialSettingsLayout.addWidget(self.porttEdit, 3, 1, 1, 2)
        self.serialSettingsLayout.addWidget(self.clientsCombobox, 4, 0, 1, 2)
        self.serialSettingsLayout.addWidget(self.disconnetClientBtn, 4, 2, 1,
                                            1)
        self.serialSettingsLayout.addWidget(self.autoReconnetLable, 5, 0, 1, 1)
        self.serialSettingsLayout.addWidget(self.autoReconnect, 5, 1, 1, 1)
        self.serialSettingsLayout.addWidget(self.autoReconnectIntervalEdit, 5,
                                            2, 1, 1)
        self.serialSettingsLayout.addWidget(self.serialOpenCloseButton, 6, 0,
                                            1, 3)
        serialSetting.setLayout(self.serialSettingsLayout)
        self.widgetConfMap["protocol"] = self.protoclTcpRadioBtn
        self.widgetConfMap["mode"] = self.modeClientRadioBtn
        self.widgetConfMap["target"] = self.targetCombobox
        self.widgetConfMap["port"] = self.porttEdit
        self.widgetConfMap["auto_reconnect"] = self.autoReconnect
        self.widgetConfMap[
            "auto_reconnect_interval"] = self.autoReconnectIntervalEdit
        self.initEvet()
        self.widget = serialSetting
        return serialSetting

    def initEvet(self):
        self.serialOpenCloseButton.clicked.connect(self.openCloseSerial)
        self.porttEdit.textChanged.connect(self.onPortChanged)
        self.showSwitchSignal.connect(self.showSwitch)
        self.updateTargetSignal.connect(self.updateTarget)
        self.updateClientsSignal.connect(self.updateClients)
        self.protoclTcpRadioBtn.clicked.connect(
            lambda: self.changeProtocol("tcp"))
        self.protoclUdpRadioBtn.clicked.connect(
            lambda: self.changeProtocol("udp"))
        self.modeServerRadioBtn.clicked.connect(
            lambda: self.changeMode("server"))
        self.modeClientRadioBtn.clicked.connect(
            lambda: self.changeMode("client"))
        self.clientsCombobox.currentIndexChanged.connect(
            self.serverModeClientChanged)
        self.disconnetClientBtn.clicked.connect(
            self.serverModeDisconnectClient)
        self.autoReconnect.stateChanged.connect(
            lambda x: self.setVar("auto_reconnect", value=x))
        self.autoReconnectIntervalEdit.textChanged.connect(
            lambda: self.setVar("auto_reconnect_interval"))
        self.targetCombobox.currentTextChanged.connect(self.onTargetChanged)

    def changeProtocol(self, protocol, init=False):
        if init or protocol != self.config["protocol"]:
            if self.isConnected():
                self.openCloseSerial()
            if protocol == "tcp":
                self.modeClientRadioBtn.show()
                self.modeServerRadioBtn.show()
                self.modeLabel.show()
                self.changeMode(self.config["mode"], init=True)
            else:
                self.targetCombobox.show()
                self.targetLabel.show()
                self.porttEdit.show()
                self.portLabel.show()
                self.clientsCombobox.hide()
                self.disconnetClientBtn.hide()
                self.autoReconnect.hide()
                self.autoReconnectIntervalEdit.hide()
                self.autoReconnetLable.hide()
                self.modeClientRadioBtn.hide()
                self.modeServerRadioBtn.hide()
                self.modeLabel.hide()
                self.widget.adjustSize()
            self.config["protocol"] = protocol

    def changeMode(self, mode, init=False):
        if init or mode != self.config["mode"]:
            if self.isConnected():
                self.openCloseSerial()
            if mode == "server":
                self.targetCombobox.hide()
                self.targetLabel.hide()
                self.porttEdit.show()
                self.portLabel.show()
                self.clientsCombobox.show()
                self.disconnetClientBtn.show()
                self.autoReconnect.hide()
                self.autoReconnectIntervalEdit.hide()
                self.autoReconnetLable.hide()
            else:
                self.targetCombobox.show()
                self.targetLabel.show()
                self.porttEdit.hide()
                self.portLabel.hide()
                self.clientsCombobox.hide()
                self.disconnetClientBtn.hide()
                self.autoReconnect.show()
                self.autoReconnectIntervalEdit.show()
                self.autoReconnetLable.show()
            self.widget.adjustSize()
            self.config["mode"] = mode

    def onTargetChanged(self):
        text = self.targetCombobox.currentText()
        self.config["target"][0] = text

    def updateTarget(self, new):
        idx = self.targetCombobox.findText(new)
        if idx < 0:
            self.targetCombobox.addItem(new)
            self.config["target"][1].append(new)
        self.targetCombobox.setEditText(new)
        self.config["target"][0] = new

    def updateClients(self, add: bool, addr: tuple):
        host, port = addr
        if add:
            self.clientsCombobox.addItem(f'{host}:{port}')
        else:
            idx = self.clientsCombobox.findText(f'{host}:{port}')
            if idx > 0:
                self.clientsCombobox.removeItem(idx)
        self.clientsCombobox.setItemText(
            0, "{} | ".format(self.clientsCombobox.count() - 1) +
            _("All clients"))

    def serverModeClientChanged(self):
        if self.clientsCombobox.currentIndex() == 0:
            self.serverModeSelectedClient = None
        else:
            self.serverModeSelectedClient = self.clientsCombobox.currentText()

    def serverModeDisconnectClient(self):
        if not self.serverModeSelectedClient:
            for addr, conn in self.serverModeClientsConns.items():
                try:
                    conn.close()
                except Exception:
                    pass
        else:
            conn = self.serverModeClientsConns[self.serverModeSelectedClient]
            try:
                conn.close()
            except Exception:
                pass

    def onPortChanged(self):
        text = self.porttEdit.text()
        while 1:
            try:
                port = int(text)
                break
            except Exception:
                text = text[:-1]
        self.porttEdit.setText(text)

    def onSerialConfigChanged(self, conf_type, obj, value_type, caller=""):
        pass

    def setSerialConfig(self, conf_type, obj, value):
        if conf_type == "protocol":
            if value == "tcp":
                obj.setChecked(True)
            else:
                obj.setChecked(False)
        elif conf_type == "mode":
            if value == "client":
                obj.setChecked(True)
                self.changeMode("client", init=True)
            else:
                obj.setChecked(False)
                self.modeServerRadioBtn.setChecked(True)
                self.changeMode("server", init=True)
        elif conf_type == "target":
            for i, target in enumerate(self.config["target"][1]):
                self.targetCombobox.addItem(target)
            self.targetCombobox.setCurrentText(self.config["target"][0])
        elif conf_type == "port":
            obj.setText(str(value))
        elif conf_type == "auto_reconnect":
            obj.setChecked(value)
        elif conf_type == "auto_reconnect_interval":
            obj.setText("%.3f" % (value))

    def setVar(self, key, value=None):
        if key == "auto_reconnect":
            self.config[key] = value
        elif key == "auto_reconnect_interval":
            text = self.autoReconnectIntervalEdit.text()
            try:
                interval = float(text)
                self.config[key] = interval
            except Exception:
                text = "".join(re.findall('[\d\.]*', text))
                self.autoReconnectIntervalEdit.setText(text)

    def openCloseSerial(self):
        if self.busy:
            return
        self.busy = True
        if self.serialOpenCloseButton.text() == _("OPEN"):
            self.isOpened = False
        else:
            self.isOpened = True
        t = threading.Thread(target=self.openCloseSerialProcess)
        t.setDaemon(True)
        t.start()

    def openCloseSerialProcess(self):
        if self.isOpened:
            print("-- disconnect")
            try:
                # set status first to prevent auto reconnect
                self.status = ConnectionStatus.CLOSED
                if not self.conn is None:
                    time.sleep(0.1)  # wait receive thread exit
                    try:
                        self.conn.close()
                    except Exception:
                        pass
                    self.conn = None
                for k, conn in self.serverModeClientsConns.items():
                    try:
                        conn.close()
                    except Exception:
                        pass
            except Exception as e:
                print(e)
                pass
            self.onConnectionStatus.emit(self.status, "")
            self.showSwitchSignal.emit(self.status)
        else:
            try:
                if self.config["protocol"] == "tcp":
                    if self.config["mode"] == "client":
                        print("-- connect")
                        target = self.checkTarget(self.config["target"][0])
                        if not target:
                            raise Exception(
                                _("Target error") + ": " +
                                self.config["target"][0])
                        print("-- connect", target)
                        self.onConnectionStatus.emit(
                            ConnectionStatus.CONNECTING, "")
                        self.conn = socket.socket()
                        self.conn.connect(target)
                        self.status = ConnectionStatus.CONNECTED
                        print("-- connect success")
                        self.receiveProcess = threading.Thread(
                            target=self.receiveDataProcess, args=(self.conn, ))
                        self.receiveProcess.setDaemon(True)
                        self.receiveProcess.start()
                    else:
                        print("-- server mode, wait client connect")
                        self.conn = socket.socket()
                        self.conn.setsockopt(socket.SOL_SOCKET,
                                             socket.SO_REUSEADDR, 1)
                        self.conn.bind(("0.0.0.0", self.config["port"]))
                        self.conn.listen(100)
                        self.status = ConnectionStatus.CONNECTED
                        self.waitClentsProcess = threading.Thread(
                            target=self.waitClientsProcess)
                        self.waitClentsProcess.setDaemon(True)
                        self.waitClentsProcess.start()
                else:
                    print("-- UPD protocol")
                    self.conn = socket.socket(type=socket.SOCK_DGRAM)
                    self.conn.bind(("0.0.0.0", self.config["port"]))
                    self.status = ConnectionStatus.CONNECTED
                    self.receiveProcess = threading.Thread(
                        target=self.receiveDataProcess, args=(self.conn, ))
                    self.receiveProcess.setDaemon(True)
                    self.receiveProcess.start()
                self.onConnectionStatus.emit(self.status, "")
                self.showSwitchSignal.emit(self.status)
            except Exception as e:
                print("----", e)
                try:
                    self.conn.close()
                    self.conn = None
                except Exception:
                    pass
                msg = _("Connect Failed") + "\n" + str(e)
                self.hintSignal.emit("error", _("Error"), msg)
                self.status = ConnectionStatus.CLOSED
                self.onConnectionStatus.emit(self.status, msg)
                self.showSwitchSignal.emit(self.status)
        self.busy = False

    def checkTarget(self, target):
        if not target:
            return None
        host = target
        port = 80
        target = target.replace(":", ":")
        if target.endswith(":"):
            target = target[:-1]
        _host = re.match('http(.*)://(.*)', target)
        if _host:
            s, target = _host.groups()
            host = target
        _host = re.match('(.*):(\d*)', target)
        if _host:
            host, port = _host.groups()
            port = int(port)
        if host.endswith("/"):
            host = host[:-1]
        target = (host, port)
        target_str = f'{host}:{port}'
        self.updateTargetSignal.emit(target_str)
        return target

    # @pyqtSlot(ConnectionStatus)
    def showSwitch(self, status):
        if status == ConnectionStatus.CLOSED:
            self.serialOpenCloseButton.setText(_("OPEN"))
            self.serialOpenCloseButton.setProperty("class", "")
        elif status == ConnectionStatus.CONNECTED:
            self.serialOpenCloseButton.setText(_("CLOSE"))
            self.serialOpenCloseButton.setProperty("class", "")
        else:
            self.serialOpenCloseButton.setText(_("CLOSE"))
            self.serialOpenCloseButton.setProperty("class", "warning")
        self.updateStyle(self.serialOpenCloseButton)

    def updateStyle(self, widget):
        self.widget.style().unpolish(widget)
        self.widget.style().polish(widget)
        self.widget.update()

    def waitClientsProcess(self):
        while self.status != ConnectionStatus.CLOSED:
            print("-- wait for client connect")
            try:
                conn, addr = self.conn.accept()
            except Exception as e:
                if self.status != ConnectionStatus.CLOSED:
                    print("-- accept connection fail:", str(e))
                continue
            print("-- client connected, ip:", addr)
            addr_str = f'{addr[0]}:{addr[1]}'
            self.updateClientsSignal.emit(True, addr)
            self.onConnectionStatus.emit(
                ConnectionStatus.CONNECTED,
                _("Client connected:") + " " + addr_str)
            self.serverModeClientsConns[addr_str] = conn
            t = threading.Thread(target=self.receiveDataProcess,
                                 args=(conn, addr))
            t.setDaemon(True)
            t.start()
        print("-- wait connection thread exit")

    def receiveDataProcess(self, conn, remote_addr: tuple = None):
        waitingReconnect = False
        buffer = b''
        t = 0
        conn.settimeout(0.1)
        protocolIsTcp = self.config["protocol"] == "tcp"
        modeIsServer = self.config["mode"] == "server"
        remoteStr = ""
        if remote_addr:
            remoteStr = f'{remote_addr[0]}:{remote_addr[1]}'
        while self.status != ConnectionStatus.CLOSED:
            if waitingReconnect:
                try:
                    target = self.checkTarget(self.config["target"][0])
                    if not target:
                        raise Exception(
                            _("Target error") + ": " +
                            self.config["target"][0])
                    self.onConnectionStatus.emit(ConnectionStatus.CONNECTING,
                                                 "")
                    conn = socket.socket()
                    conn.connect(target)
                    conn.settimeout(0.1)
                    self.conn = conn
                    print("-- reconnect")
                    waitingReconnect = False
                    self.onConnectionStatus.emit(ConnectionStatus.CONNECTED,
                                                 _("Reconnected"))
                    self.showSwitchSignal.emit(ConnectionStatus.CONNECTED)
                    continue
                except Exception as e:
                    pass
                time.sleep(self.config["auto_reconnect_interval"])
                continue
            try:
                # length = max(1, self.conn.in_waiting)
                flush = True
                try:
                    if protocolIsTcp:
                        data = conn.recv(4096)
                        # ignore not selected target's msg
                        if modeIsServer and self.serverModeSelectedClient and (
                                remoteStr != self.serverModeSelectedClient):
                            data = None
                    else:
                        data, target = conn.recvfrom(4096)
                    if data == b'':  # closed by peer(peer send FIN, now we can close this connection)
                        if buffer:
                            self.onReceived(buffer)
                        raise Exception(_("Closed by peer"))
                except socket.timeout:
                    data = None
                if data:
                    if len(data) > 4096:
                        flush = False
                    t = time.time()
                    # if length == 1 and not buffer: # just start receive
                    #     buffer += data
                    #     continue
                    buffer += data
                if flush or (
                        buffer and
                    (time.time() - t > 0.001)):  # no new data in 0.1ms
                    try:
                        self.onReceived(buffer)
                    except Exception as e:
                        print("-- error in onReceived callback:", e)
                    buffer = b''
            except Exception as e:
                print("-- recv error:", e, type(e))
                if modeIsServer or not self.config["auto_reconnect"]:
                    over = False
                    if protocolIsTcp and modeIsServer:
                        self.onConnectionStatus.emit(
                            ConnectionStatus.CLOSED,
                            _("Connection") +
                            f' {remote_addr[0]}:{remote_addr[1]} ' +
                            _("closed!"))
                        over = True
                    else:
                        self.status = ConnectionStatus.CLOSED
                        self.onConnectionStatus.emit(
                            self.status,
                            _("Connection closed!") + " " + str(e))
                        self.showSwitchSignal.emit(self.status)
                    try:
                        conn.close()
                    except Exception:
                        pass
                    if over:
                        break
                elif (self.status != ConnectionStatus.CLOSED):
                    # close as fast as we can to release port
                    try:
                        conn.close()
                    except Exception:
                        pass
                    waitingReconnect = True
                    self.onConnectionStatus.emit(ConnectionStatus.LOSE,
                                                 _("Connection lose!"))
                    self.showSwitchSignal.emit(ConnectionStatus.LOSE)
                    time.sleep(self.config["auto_reconnect_interval"])
        # server mode remove client
        if self.config["mode"] == "server":
            remote_str = f'{remote_addr[0]}:{remote_addr[1]}'
            print(f"-- client {remote_str} disconnect")
            self.updateClientsSignal.emit(False, remote_addr)
            if remote_str == self.serverModeSelectedClient:
                self.serverModeSelectedClient = None
            self.serverModeClientsConns.pop(remote_str)
        print("-- receiveDataProcess exit")

    def send(self, data: bytes):
        if self.conn:
            if self.config["protocol"] == "tcp":
                if self.config["mode"] == "client":
                    self.conn.sendall(data)
                else:
                    if not self.serverModeSelectedClient:
                        for addr, conn in self.serverModeClientsConns.items():
                            conn.sendall(data)
                    else:
                        self.serverModeClientsConns[
                            self.serverModeSelectedClient].sendall(data)
            else:
                target = self.checkTarget(self.config["target"][0])
                if not target:
                    self.hintSignal.emit(
                        "error", _("Target error"),
                        _("Target error") + ": " + self.config["target"])
                self.conn.sendto(data, target)

    def isConnected(self):
        return self.status == ConnectionStatus.CONNECTED
Example #3
0
class MainWindow(QMainWindow):
    errorSignal = pyqtSignal(str, str)
    hintSignal = pyqtSignal(str, str)
    updateProgressSignal = pyqtSignal(str, int, int, str)
    updateProgressPrintSignal = pyqtSignal(str)
    showSerialComboboxSignal = pyqtSignal()
    downloadResultSignal = pyqtSignal(bool, str)
    DataPath = "./"
    app = None

    def __init__(self, app):
        super().__init__()
        self.app = app
        self.programStartGetSavedParameters()
        self.initVar()
        self.initWindow()
        self.updateFrameParams()
        self.initEvent()

    def __del__(self):
        pass

    def initVar(self):
        self.burning = False
        self.isDetectSerialPort = False
        self.DataPath = parameters.dataPath
        self.kflash = KFlash(print_callback=self.kflash_py_printCallback)

    def initWindow(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        # main layout
        self.frameWidget = QWidget()
        mainWidget = QSplitter(Qt.Horizontal)
        self.frameLayout = QVBoxLayout()
        self.settingWidget = QWidget()
        settingLayout = QVBoxLayout()
        self.settingWidget.setProperty("class", "settingWidget")
        mainLayout = QVBoxLayout()
        self.settingWidget.setLayout(settingLayout)
        mainLayout.addWidget(self.settingWidget)
        mainLayout.setStretch(0, 2)
        menuLayout = QHBoxLayout()

        self.progressHint = QLabel()
        self.progressHint.hide()

        self.progressbarRootWidget = QWidget()
        progressbarLayout = QVBoxLayout()
        self.progressbarRootWidget.setProperty("class", "progressbarWidget")
        self.progressbarRootWidget.setLayout(progressbarLayout)

        self.downloadWidget = QWidget()
        downloadLayout = QVBoxLayout()
        self.downloadWidget.setProperty("class", "downloadWidget")
        self.downloadWidget.setLayout(downloadLayout)

        mainWidget.setLayout(mainLayout)
        # menu
        # -----
        # settings and others
        # -----
        # progress bar
        # -----
        # download button
        # -----
        # status bar
        self.frameLayout.addLayout(menuLayout)
        self.frameLayout.addWidget(mainWidget)
        self.frameLayout.addWidget(self.progressHint)
        self.frameLayout.addWidget(self.progressbarRootWidget)
        self.frameLayout.addWidget(self.downloadWidget)
        self.frameWidget.setLayout(self.frameLayout)
        self.setCentralWidget(self.frameWidget)
        self.setFrameStrentch(0)

        # option layout
        self.langButton = QPushButton()
        self.skinButton = QPushButton()
        self.aboutButton = QPushButton()
        self.langButton.setProperty("class", "menuItemLang")
        self.skinButton.setProperty("class", "menuItem2")
        self.aboutButton.setProperty("class", "menuItem3")
        self.langButton.setObjectName("menuItem")
        self.skinButton.setObjectName("menuItem")
        self.aboutButton.setObjectName("menuItem")
        menuLayout.addWidget(self.langButton)
        menuLayout.addWidget(self.skinButton)
        menuLayout.addWidget(self.aboutButton)
        menuLayout.addStretch(0)

        # widgets file select
        fileSelectGroupBox = QGroupBox(tr("SelectFile"))
        settingLayout.addWidget(fileSelectGroupBox)
        fileSelectLayout = QHBoxLayout()
        fileSelectGroupBox.setLayout(fileSelectLayout)
        self.filePathWidget = QLineEdit()
        self.openFileButton = QPushButton(tr("OpenFile"))
        fileSelectLayout.addWidget(self.filePathWidget)
        fileSelectLayout.addWidget(self.openFileButton)

        # widgets board select
        boardSettingsGroupBox = QGroupBox(tr("BoardSettings"))
        settingLayout.addWidget(boardSettingsGroupBox)
        boardSettingsLayout = QGridLayout()
        boardSettingsGroupBox.setLayout(boardSettingsLayout)
        self.boardLabel = QLabel(tr("Board"))
        self.boardCombobox = ComboBox()
        self.boardCombobox.addItem(parameters.SipeedMaixDock)
        self.boardCombobox.addItem(parameters.SipeedMaixBit)
        self.boardCombobox.addItem(parameters.SipeedMaixBitMic)
        self.boardCombobox.addItem(parameters.SipeedMaixduino)
        self.boardCombobox.addItem(parameters.SipeedMaixGo)
        self.boardCombobox.addItem(parameters.SipeedMaixGoD)
        self.boardCombobox.addItem(parameters.KendryteKd233)
        self.boardCombobox.addItem(parameters.kendryteTrainer)
        self.boardCombobox.addItem(parameters.Auto)
        self.burnPositionLabel = QLabel(tr("BurnTo"))
        self.burnPositionCombobox = ComboBox()
        self.burnPositionCombobox.addItem(tr("Flash"))
        self.burnPositionCombobox.addItem(tr("SRAM"))
        boardSettingsLayout.addWidget(self.boardLabel, 0, 0)
        boardSettingsLayout.addWidget(self.boardCombobox, 0, 1)
        boardSettingsLayout.addWidget(self.burnPositionLabel, 1, 0)
        boardSettingsLayout.addWidget(self.burnPositionCombobox, 1, 1)

        # widgets serial settings
        serialSettingsGroupBox = QGroupBox(tr("SerialSettings"))
        serialSettingsLayout = QGridLayout()
        serialPortLabek = QLabel(tr("SerialPort"))
        serailBaudrateLabel = QLabel(tr("SerialBaudrate"))
        self.serialPortCombobox = ComboBox()
        self.serailBaudrateCombobox = ComboBox()
        self.serailBaudrateCombobox.addItem("115200")
        self.serailBaudrateCombobox.addItem("921600")
        self.serailBaudrateCombobox.addItem("1500000")
        self.serailBaudrateCombobox.addItem("2000000")
        self.serailBaudrateCombobox.addItem("3500000")
        self.serailBaudrateCombobox.addItem("4000000")
        self.serailBaudrateCombobox.addItem("4500000")
        self.serailBaudrateCombobox.setCurrentIndex(1)
        self.serailBaudrateCombobox.setEditable(True)

        serialSettingsLayout.addWidget(serialPortLabek, 0, 0)
        serialSettingsLayout.addWidget(serailBaudrateLabel, 1, 0)
        serialSettingsLayout.addWidget(self.serialPortCombobox, 0, 1)
        serialSettingsLayout.addWidget(self.serailBaudrateCombobox, 1, 1)
        serialSettingsGroupBox.setLayout(serialSettingsLayout)
        settingLayout.addWidget(serialSettingsGroupBox)

        # set stretch
        settingLayout.setStretch(0, 1)
        settingLayout.setStretch(1, 1)
        settingLayout.setStretch(2, 2)

        # widgets progress bar

        self.progressbar = QProgressBar(self.progressbarRootWidget)
        self.progressbar.setGeometry(10, 0, 400, 40)
        self.progressbar.setValue(0)
        self.progressbarRootWidget.hide()

        # widgets download area
        self.downloadButton = QPushButton(tr("Download"))
        downloadLayout.addWidget(self.downloadButton)

        # main window
        self.statusBarStauts = QLabel()
        self.statusBarStauts.setMinimumWidth(80)
        self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                     ("#1aac2d", tr("DownloadHint")))
        self.statusBar().addWidget(self.statusBarStauts)

        self.resize(400, 550)
        self.MoveToCenter()
        self.setWindowTitle(parameters.appName + " V" +
                            str(helpAbout.versionMajor) + "." +
                            str(helpAbout.versionMinor))
        icon = QIcon()
        print("icon path:" + self.DataPath + "/" + parameters.appIcon)
        icon.addPixmap(QPixmap(self.DataPath + "/" + parameters.appIcon),
                       QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        if sys.platform == "win32":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                parameters.appName)
        self.show()
        print("config file path:",
              os.getcwd() + "/" + parameters.configFilePath)

    def initEvent(self):
        self.serialPortCombobox.clicked.connect(self.portComboboxClicked)
        self.errorSignal.connect(self.errorHint)
        self.hintSignal.connect(self.hint)
        self.downloadResultSignal.connect(self.downloadResult)
        self.showSerialComboboxSignal.connect(self.showCombobox)
        self.updateProgressSignal.connect(self.updateProgress)
        self.updateProgressPrintSignal.connect(self.updateProgressPrint)
        self.langButton.clicked.connect(self.langChange)
        self.skinButton.clicked.connect(self.skinChange)
        self.aboutButton.clicked.connect(self.showAbout)
        self.openFileButton.clicked.connect(self.selectFile)
        self.downloadButton.clicked.connect(self.download)

        self.myObject = MyClass(self)
        slotLambda = lambda: self.indexChanged_lambda(self.myObject)
        self.serialPortCombobox.currentIndexChanged.connect(slotLambda)

    def setFrameStrentch(self, mode):
        if mode == 0:
            self.frameLayout.setStretch(0, 1)
            self.frameLayout.setStretch(1, 3)
            self.frameLayout.setStretch(2, 3)
            self.frameLayout.setStretch(3, 1)
            self.frameLayout.setStretch(4, 1)
            self.frameLayout.setStretch(5, 1)
        else:
            self.frameLayout.setStretch(0, 0)
            self.frameLayout.setStretch(1, 0)
            self.frameLayout.setStretch(2, 1)
            self.frameLayout.setStretch(3, 1)
            self.frameLayout.setStretch(4, 1)
            self.frameLayout.setStretch(5, 1)

    # @QtCore.pyqtSlot(str)
    def indexChanged_lambda(self, obj):
        mainObj = obj.arg
        self.serialPortCombobox.setToolTip(
            mainObj.serialPortCombobox.currentText())

    def portComboboxClicked(self):
        self.detectSerialPort()

    def MoveToCenter(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def selectFile(self):
        oldPath = self.filePathWidget.text()
        if oldPath == "":
            oldPath = os.getcwd()
        fileName_choose, filetype = QFileDialog.getOpenFileName(
            self, tr("SelectFile"), oldPath,
            "All Files (*);;bin Files (*.bin);;k210 packages (*.kfpkg)"
        )  # 设置文件扩展名过滤,用双分号间隔

        if fileName_choose == "":
            return
        if not self.checkFileName(fileName_choose):
            self.errorSignal.emit(tr("Error"), tr("FileTypeError"))
            return
        self.filePathWidget.setText(fileName_choose)

    def errorHint(self, title, str):
        QMessageBox.critical(self, title, str)

    def hint(self, title, str):
        QMessageBox.information(self, title, str)

    def findSerialPort(self):
        self.port_list = list(serial.tools.list_ports.comports())
        return self.port_list

    def portChanged(self):
        self.serialPortCombobox.setCurrentIndex(0)
        self.serialPortCombobox.setToolTip(str(self.portList[0]))

    def detectSerialPort(self):
        if not self.isDetectSerialPort:
            self.isDetectSerialPort = True
            t = threading.Thread(target=self.detectSerialPortProcess)
            t.setDaemon(True)
            t.start()

    def showCombobox(self):
        self.serialPortCombobox.showPopup()

    def checkFileName(self, name):
        if not name.endswith(".bin") and not name.endswith(".kfpkg"):
            return False
        if not os.path.exists(name):
            return False
        return True

    def detectSerialPortProcess(self):
        while (1):
            portList = self.findSerialPort()
            if len(portList) > 0:
                currText = self.serialPortCombobox.currentText()
                self.serialPortCombobox.clear()
                for i in portList:
                    showStr = str(i[0]) + " (" + str(i[1]) + ")"
                    self.serialPortCombobox.addItem(showStr)
                index = self.serialPortCombobox.findText(currText)
                if index >= 0:
                    self.serialPortCombobox.setCurrentIndex(index)
                else:
                    self.serialPortCombobox.setCurrentIndex(0)
                break
            time.sleep(1)
        self.showSerialComboboxSignal.emit()
        self.isDetectSerialPort = False

    def programExitSaveParameters(self):
        paramObj = paremeters_save.ParametersToSave()
        paramObj.filePath = self.filePathWidget.text()
        paramObj.board = self.boardCombobox.currentText()
        paramObj.burnPosition = self.burnPositionCombobox.currentText()
        paramObj.baudRate = self.serailBaudrateCombobox.currentIndex()
        paramObj.skin = self.param.skin
        paramObj.language = translation.current_lang
        f = open(parameters.configFilePath, "wb")
        f.truncate()
        pickle.dump(paramObj, f)
        f.close()

    def programStartGetSavedParameters(self):
        paramObj = paremeters_save.ParametersToSave()
        try:
            f = open(parameters.configFilePath, "rb")
            paramObj = pickle.load(f)
            f.close()
        except Exception as e:
            f = open(parameters.configFilePath, "wb")
            f.close()
        translation.setLanguage(paramObj.language)
        self.param = paramObj

    def updateFrameParams(self):
        self.filePathWidget.setText(self.param.filePath)
        self.boardCombobox.setCurrentText(self.param.board)
        self.burnPositionCombobox.setCurrentText(self.param.burnPosition)
        self.serailBaudrateCombobox.setCurrentIndex(self.param.baudRate)

    def closeEvent(self, event):
        self.programExitSaveParameters()

    def langChange(self):
        if self.param.language == translation.language_en:
            translation.setLanguage(translation.language_zh)
            lang = tr("Chinese language")
        else:
            translation.setLanguage(translation.language_en)
            lang = tr("English language")

        self.hint(
            tr("Hint"),
            tr("Language Changed to ") + lang + "\n" +
            tr("Reboot to take effect"))
        self.frameWidget.style().unpolish(self.downloadButton)
        self.frameWidget.style().polish(self.downloadButton)
        self.frameWidget.update()

    def skinChange(self):
        if self.param.skin == 1:  # light
            file = open(self.DataPath + '/assets/qss/style-dark.qss', "r")
            self.param.skin = 2
        else:  # elif self.param.skin == 2: # dark
            file = open(self.DataPath + '/assets/qss/style.qss', "r")
            self.param.skin = 1
        self.app.setStyleSheet(file.read().replace("$DataPath", self.DataPath))

    def showAbout(self):
        QMessageBox.information(
            self, tr("About"),
            "<h1 style='color:#f75a5a';margin=10px;>" + parameters.appName +
            '</h1><br><b style="color:#08c7a1;margin = 5px;">V' +
            str(helpAbout.versionMajor) + "." + str(helpAbout.versionMinor) +
            "." + str(helpAbout.versionDev) + "</b><br><br>" + helpAbout.date +
            "<br><br>" + helpAbout.strAbout())

    def autoUpdateDetect(self):
        auto = autoUpdate.AutoUpdate()
        if auto.detectNewVersion():
            auto.OpenBrowser()

    def openDevManagement(self):
        os.system('start devmgmt.msc')

    def updateProgress(self, fileTypeStr, current, total, speedStr):
        currBurnPos = self.burnPositionCombobox.currentText()
        if currBurnPos == tr("SRAM") or currBurnPos == tr_en("SRAM"):
            fileTypeStr = tr("ToSRAM")
        percent = current / float(total) * 100
        hint = "<font color=%s>%s %s:</font>   <font color=%s> %.2f%%</font>   <font color=%s> %s</font>" % (
            "#ff7575", tr("Downloading"), fileTypeStr, "#2985ff", percent,
            "#1aac2d", speedStr)
        self.progressHint.setText(hint)
        self.progressbar.setValue(percent)

    def updateProgressPrint(self, str):
        self.statusBarStauts.setText(str)

    def kflash_py_printCallback(self, *args, end="\n"):
        msg = ""
        for i in args:
            msg += str(i)
        msg.replace("\n", " ")
        self.updateProgressPrintSignal.emit(msg)

    def progress(self, fileTypeStr, current, total, speedStr):
        self.updateProgressSignal.emit(fileTypeStr, current, total, speedStr)

    def download(self):
        if self.burning:
            self.terminateBurn()
            return

        self.burning = True
        filename = self.filePathWidget.text()
        if not self.checkFileName(filename):
            self.errorSignal.emit(tr("Error"), tr("FilePathError"))
            self.burning = False
            return
        color = False
        board = "dan"
        boardText = self.boardCombobox.currentText()
        if boardText == parameters.SipeedMaixGo:
            board = "goE"
        elif boardText == parameters.SipeedMaixGoD:
            board = "goD"
        elif boardText == parameters.SipeedMaixduino:
            board = "maixduino"
        elif boardText == parameters.SipeedMaixBit:
            board = "bit"
        elif boardText == parameters.SipeedMaixBitMic:
            board = "bit_mic"
        elif boardText == parameters.KendryteKd233:
            board = "kd233"
        elif boardText == parameters.kendryteTrainer:
            board = "trainer"
        elif boardText == parameters.Auto:
            board = None

        sram = False
        if self.burnPositionCombobox.currentText()==tr("SRAM") or \
            self.burnPositionCombobox.currentText()==tr_en("SRAM"):
            sram = True
        try:
            baud = int(self.serailBaudrateCombobox.currentText())
        except Exception:
            self.errorSignal.emit(tr("Error"), tr("BaudrateError"))
            self.burning = False
            return
        dev = self.serialPortCombobox.currentText().split()[0]
        if dev == "":
            self.errorSignal.emit(tr("Error"), tr("PleaseSelectSerialPort"))
            self.burning = False
            return
        # hide setting widgets
        self.setFrameStrentch(1)
        self.settingWidget.hide()
        self.progressbar.setValue(0)
        self.progressbarRootWidget.show()
        self.progressHint.show()
        self.downloadButton.setText(tr("Cancel"))
        self.downloadButton.setProperty("class", "redbutton")
        self.downloadButton.style().unpolish(self.downloadButton)
        self.downloadButton.style().polish(self.downloadButton)
        self.downloadButton.update()
        self.statusBarStauts.setText("<font color=%s>%s ...</font>" %
                                     ("#1aac2d", tr("Downloading")))
        hint = "<font color=%s>%s</font>" % ("#ff0d0d", tr("DownloadStart"))
        self.progressHint.setText(hint)
        # download
        self.burnThread = threading.Thread(target=self.flashBurnProcess,
                                           args=(
                                               dev,
                                               baud,
                                               board,
                                               sram,
                                               filename,
                                               self.progress,
                                               color,
                                           ))
        self.burnThread.setDaemon(True)
        self.burnThread.start()

    def flashBurnProcess(self, dev, baud, board, sram, filename, callback,
                         color):
        success = True
        errMsg = ""
        try:
            if board:
                self.kflash.process(terminal=False,
                                    dev=dev,
                                    baudrate=baud,
                                    board=board,
                                    sram=sram,
                                    file=filename,
                                    callback=callback,
                                    noansi=not color)
            else:
                self.kflash.process(terminal=False,
                                    dev=dev,
                                    baudrate=baud,
                                    sram=sram,
                                    file=filename,
                                    callback=callback,
                                    noansi=not color)
        except Exception as e:
            errMsg = str(e)
            if str(e) != "Burn SRAM OK":
                success = False
        if success:
            self.downloadResultSignal.emit(True, errMsg)
        else:
            self.downloadResultSignal.emit(False, errMsg)

    def downloadResult(self, success, msg):
        if success:
            self.hintSignal.emit(tr("Success"), tr("DownloadSuccess"))
            self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                         ("#1aac2d", tr("DownloadSuccess")))
        else:
            if msg == "Cancel":
                self.statusBarStauts.setText(
                    "<font color=%s>%s</font>" %
                    ("#ff1d1d", tr("DownloadCanceled")))
            else:
                msg = tr("ErrorSettingHint") + "\n\n" + msg
                self.errorSignal.emit(tr("Error"), msg)
                self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                             ("#ff1d1d", tr("DownloadFail")))
            self.progressHint.setText("")
        self.downloadButton.setText(tr("Download"))
        self.downloadButton.setProperty("class", "normalbutton")
        self.downloadButton.style().unpolish(self.downloadButton)
        self.downloadButton.style().polish(self.downloadButton)
        self.downloadButton.update()
        self.setFrameStrentch(0)
        self.progressbarRootWidget.hide()
        self.progressHint.hide()
        self.settingWidget.show()
        self.burning = False

    def terminateBurn(self):
        hint = "<font color=%s>%s</font>" % ("#ff0d0d",
                                             tr("DownloadCanceling"))
        self.progressHint.setText(hint)
        self.kflash.kill()
Example #4
0
class MainWindow(QMainWindow):
    errorSignal = pyqtSignal(str, str)
    hintSignal = pyqtSignal(str, str)
    updateProgressSignal = pyqtSignal(str, int, int, str)
    updateProgressPrintSignal = pyqtSignal(str)
    showSerialComboboxSignal = pyqtSignal()
    downloadResultSignal = pyqtSignal(bool, str)
    DataPath = "./"
    app = None

    def __init__(self,app):
        super().__init__()
        self.app = app
        self.programStartGetSavedParameters()
        self.initVar()
        self.initWindow()
        self.initEvent()
        self.updateFrameParams()

    def __del__(self):
        pass

    def initVar(self):
        self.burning = False
        self.isDetectSerialPort = False
        self.DataPath = parameters.dataPath
        self.kflash = KFlash(print_callback=self.kflash_py_printCallback)
        self.saveKfpkDir = ""

    def setWindowSize(self, w=520, h=550):
        self.resize(w, h)

    def initWindow(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        # main layout
        self.frameWidget = QWidget()
        mainWidget = QSplitter(Qt.Horizontal)
        self.frameLayout = QVBoxLayout()
        self.settingWidget = QWidget()
        settingLayout = QVBoxLayout()
        self.settingWidget.setProperty("class","settingWidget")
        mainLayout = QVBoxLayout()
        self.settingWidget.setLayout(settingLayout)
        mainLayout.addWidget(self.settingWidget)
        mainLayout.setStretch(0,2)
        menuLayout = QHBoxLayout()
        
        self.progressHint = QLabel()
        self.progressHint.hide()

        self.progressbarRootWidget = QWidget()
        progressbarLayout = QVBoxLayout()
        self.progressbarRootWidget.setProperty("class","progressbarWidget")
        self.progressbarRootWidget.setLayout(progressbarLayout)
        
        self.downloadWidget = QWidget()
        downloadLayout = QVBoxLayout()
        self.downloadWidget.setProperty("class","downloadWidget")
        self.downloadWidget.setLayout(downloadLayout)

        mainWidget.setLayout(mainLayout)
        # menu
        # -----
        # settings and others
        # -----
        # progress bar
        # -----
        # download button
        # -----
        # status bar
        self.frameLayout.addLayout(menuLayout)
        self.frameLayout.addWidget(mainWidget)
        self.frameLayout.addWidget(self.progressHint)
        self.frameLayout.addWidget(self.progressbarRootWidget)
        self.frameLayout.addWidget(self.downloadWidget)
        self.frameWidget.setLayout(self.frameLayout)
        self.setCentralWidget(self.frameWidget)
        self.setFrameStrentch(1)

        # option layout
        self.langButton = QPushButton()
        self.skinButton = QPushButton()
        self.aboutButton = QPushButton()
        self.langButton.setProperty("class", "menuItemLang")
        self.skinButton.setProperty("class", "menuItem2")
        self.aboutButton.setProperty("class", "menuItem3")
        self.langButton.setObjectName("menuItem")
        self.skinButton.setObjectName("menuItem")
        self.aboutButton.setObjectName("menuItem")
        menuLayout.addWidget(self.langButton)
        menuLayout.addWidget(self.skinButton)
        menuLayout.addWidget(self.aboutButton)
        menuLayout.addStretch(0)
        
        # widgets file select
        self.fileSelectGroupBox = QGroupBox(tr("SelectFile"))
        settingLayout.addWidget(self.fileSelectGroupBox)
        self.fileSelectLayout = QVBoxLayout()
        self.fileSelectGroupBox.setLayout(self.fileSelectLayout)
        oneFilePathWidget = QWidget()
        oneFilePathWidgetLayout = QHBoxLayout()
        oneFilePathWidget.setLayout(oneFilePathWidgetLayout)
        filePathWidget = QLineEdit()
        openFileButton = QPushButton(tr("OpenFile"))
        oneFilePathWidgetLayout.addWidget(filePathWidget)
        oneFilePathWidgetLayout.addWidget(openFileButton)
        oneFilePathWidgetLayout.setStretch(0, 3)
        oneFilePathWidgetLayout.setStretch(1, 1)
        self.fileSelectLayout.addWidget(oneFilePathWidget)
        self.fileSelectWidgets = [["kfpkg", oneFilePathWidget, oneFilePathWidgetLayout, filePathWidget, None, openFileButton]]
                  # for "button": ["button", addoneWidget, addoneWidgetLayout, addFileButton, packFileButton]
                  # for "bin":    ["bin", oneFilePathWidget, oneFilePathWidgetLayout, filePathWidget, fileBurnAddrWidget, openFileButton, fileBurnEncCheckbox]
        # widgets board select
        boardSettingsGroupBox = QGroupBox(tr("BoardSettings"))
        settingLayout.addWidget(boardSettingsGroupBox)
        boardSettingsLayout = QGridLayout()
        boardSettingsGroupBox.setLayout(boardSettingsLayout)
        self.boardLabel = QLabel(tr("Board"))
        self.boardCombobox = ComboBox()
        self.boardCombobox.addItem(parameters.SipeedMaixDock)
        self.boardCombobox.addItem(parameters.SipeedMaixBit)
        self.boardCombobox.addItem(parameters.SipeedMaixBitMic)
        self.boardCombobox.addItem(parameters.SipeedMaixduino)
        self.boardCombobox.addItem(parameters.SipeedMaixGo)
        self.boardCombobox.addItem(parameters.SipeedMaixGoD)
        self.boardCombobox.addItem(parameters.KendryteKd233)
        self.boardCombobox.addItem(parameters.kendryteTrainer)
        self.boardCombobox.addItem(parameters.Auto)
        self.burnPositionLabel = QLabel(tr("BurnTo"))
        self.burnPositionCombobox = ComboBox()
        self.burnPositionCombobox.addItem(tr("Flash"))
        self.burnPositionCombobox.addItem(tr("SRAM"))
        boardSettingsLayout.addWidget(self.boardLabel, 0, 0)
        boardSettingsLayout.addWidget(self.boardCombobox, 0, 1)
        boardSettingsLayout.addWidget(self.burnPositionLabel, 1, 0)
        boardSettingsLayout.addWidget(self.burnPositionCombobox, 1, 1)

        # widgets serial settings
        serialSettingsGroupBox = QGroupBox(tr("SerialSettings"))
        serialSettingsLayout = QGridLayout()
        serialPortLabek = QLabel(tr("SerialPort"))
        serailBaudrateLabel = QLabel(tr("SerialBaudrate"))
        slowModeLabel = QLabel(tr("Speed mode"))
        self.serialPortCombobox = ComboBox()
        self.serailBaudrateCombobox = ComboBox()
        self.serailBaudrateCombobox.addItem("115200")
        self.serailBaudrateCombobox.addItem("921600")
        self.serailBaudrateCombobox.addItem("1500000")
        self.serailBaudrateCombobox.addItem("2000000")
        self.serailBaudrateCombobox.addItem("3500000")
        self.serailBaudrateCombobox.addItem("4000000")
        self.serailBaudrateCombobox.addItem("4500000")
        self.serailBaudrateCombobox.setCurrentIndex(1)
        self.serailBaudrateCombobox.setEditable(True)
        self.slowModeCombobox = ComboBox()
        self.slowModeCombobox.addItem(tr("Slow mode"))
        self.slowModeCombobox.addItem(tr("Fast mode"))
        
        serialSettingsLayout.addWidget(serialPortLabek,0,0)
        serialSettingsLayout.addWidget(serailBaudrateLabel, 1, 0)
        serialSettingsLayout.addWidget(slowModeLabel, 2, 0)
        serialSettingsLayout.addWidget(self.serialPortCombobox, 0, 1)
        serialSettingsLayout.addWidget(self.serailBaudrateCombobox, 1, 1)
        serialSettingsLayout.addWidget(self.slowModeCombobox, 2, 1)
        serialSettingsGroupBox.setLayout(serialSettingsLayout)
        settingLayout.addWidget(serialSettingsGroupBox)

        # set stretch
        settingLayout.setStretch(0,1)
        settingLayout.setStretch(1,1)
        settingLayout.setStretch(2,2)

        # widgets progress bar
        
        self.progressbar = QProgressBar(self.progressbarRootWidget)
        self.progressbar.setValue(0)
        self.progressbarRootWidget.hide()

        # widgets download area
        self.downloadButton = QPushButton(tr("Download"))
        downloadLayout.addWidget(self.downloadButton)

        # main window
        self.statusBarStauts = QLabel()
        self.statusBarStauts.setMinimumWidth(80)
        self.statusBarStauts.setText("<font color=%s>%s</font>" %("#1aac2d", tr("DownloadHint")))
        self.statusBar().addWidget(self.statusBarStauts)

        self.setWindowSize()
        self.MoveToCenter()
        self.setWindowTitle(parameters.appName+" V"+str(helpAbout.versionMajor)+"."+str(helpAbout.versionMinor))
        icon = QIcon()
        print("icon path:"+self.DataPath+"/"+parameters.appIcon)
        icon.addPixmap(QPixmap(self.DataPath+"/"+parameters.appIcon), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        if sys.platform == "win32":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(parameters.appName)
        
        self.show()
        self.progressbar.setGeometry(10, 0, self.downloadWidget.width()-25, 40)
        print("config file path:", parameters.configFilePath)

    def initEvent(self):
        self.serialPortCombobox.clicked.connect(self.portComboboxClicked)
        self.errorSignal.connect(self.errorHint)
        self.hintSignal.connect(self.hint)
        self.downloadResultSignal.connect(self.downloadResult)
        self.showSerialComboboxSignal.connect(self.showCombobox)
        self.updateProgressSignal.connect(self.updateProgress)
        self.updateProgressPrintSignal.connect(self.updateProgressPrint)
        self.langButton.clicked.connect(self.langChange)
        self.skinButton.clicked.connect(self.skinChange)
        self.aboutButton.clicked.connect(self.showAbout)
        self.downloadButton.clicked.connect(self.download)
        self.fileSelectWidget_Button(0).clicked.connect(lambda:self.selectFile(self.fileSelectWidget_Path(0)))

        self.myObject=MyClass(self)
        slotLambda = lambda: self.indexChanged_lambda(self.myObject)
        self.serialPortCombobox.currentIndexChanged.connect(slotLambda)

    def setFrameStrentch(self, mode):
        if mode == 0:
            self.frameLayout.setStretch(0,1)
            self.frameLayout.setStretch(1,3)
            self.frameLayout.setStretch(2,3)
            self.frameLayout.setStretch(3,1)
            self.frameLayout.setStretch(4,1)
            self.frameLayout.setStretch(5,1)
        else:
            self.frameLayout.setStretch(0,0)
            self.frameLayout.setStretch(1,0)
            self.frameLayout.setStretch(2,1)
            self.frameLayout.setStretch(3,1)
            self.frameLayout.setStretch(4,1)
            self.frameLayout.setStretch(5,1)
    
    def fileSelectWidget_Type(self, index):
        return self.fileSelectWidgets[index][0]

    def fileSelectWidget_Widget(self, index):
        return self.fileSelectWidgets[index][1]
    
    def fileSelectWidget_Layout(self, index):
        return self.fileSelectWidgets[index][2]

    def fileSelectWidget_Path(self, index):
        return self.fileSelectWidgets[index][3]

    def fileSelectWidget_Addr(self, index):
        return self.fileSelectWidgets[index][4]
    
    def fileSelectWidget_Button(self, index):
        return self.fileSelectWidgets[index][5]
    
    def fileSelectWidget_Prefix(self, index):
        return self.fileSelectWidgets[index][6]
    
    def fileSelectWidget_Close(self, index):
        return self.fileSelectWidgets[index][7]

    # @QtCore.pyqtSlot(str)
    def indexChanged_lambda(self, obj):
        mainObj = obj.arg
        self.serialPortCombobox.setToolTip(mainObj.serialPortCombobox.currentText())

    def portComboboxClicked(self):
        self.detectSerialPort()

    def MoveToCenter(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
    def removeFileSelection(self, button):
        index = -1
        for i in range(len(self.fileSelectWidgets)):
            if len(self.fileSelectWidgets[i]) >= 8:
                if self.fileSelectWidget_Close(i) == button:
                    index = i
        print(index)
        if index == -1:
            return
        if len(self.fileSelectWidgets) > 2:
            self.fileSelectWidget_Button(index).clicked.disconnect()
            self.fileSelectWidget_Close(index).clicked.disconnect()
            self.fileSelectWidget_Widget(index).setParent(None)
            self.fileSelectWidgets.remove(self.fileSelectWidgets[index])
        if len(self.fileSelectWidgets) == 2:
            self.fileSelectWidget_Close(0).clicked.disconnect()
            self.fileSelectWidget_Close(0).setParent(None)
            self.fileSelectWidgets[0].remove(self.fileSelectWidget_Close(0))
        self.downloadWidget.resize(self.downloadWidget.width(), 58)
        self.setWindowSize(self.width())

    def addAddFileWidget(self):
        if len(self.fileSelectWidgets) == 2:
            removeButton0 = QPushButton()
            removeButton0.setProperty("class", "remove_file_selection")
            self.fileSelectWidgets[0][2].addWidget(removeButton0)
            self.fileSelectWidgets[0].append(removeButton0)
            removeButton0.clicked.connect(lambda:self.removeFileSelection(removeButton0))
        oneFilePathWidget = QWidget()
        oneFilePathWidgetLayout = QHBoxLayout()
        oneFilePathWidget.setLayout(oneFilePathWidgetLayout)
        filePathWidget = QLineEdit()
        fileBurnAddrWidget = QLineEdit("0x00000")
        fileBurnEncCheckbox = QCheckBox(tr("Prefix"))
        openFileButton = QPushButton(tr("OpenFile"))
        removeButton = QPushButton()
        removeButton.setProperty("class", "remove_file_selection")
        oneFilePathWidgetLayout.addWidget(filePathWidget)
        oneFilePathWidgetLayout.addWidget(fileBurnAddrWidget)
        oneFilePathWidgetLayout.addWidget(fileBurnEncCheckbox)
        oneFilePathWidgetLayout.addWidget(openFileButton)
        oneFilePathWidgetLayout.addWidget(removeButton)
        oneFilePathWidgetLayout.setStretch(0, 4)
        oneFilePathWidgetLayout.setStretch(1, 2)
        oneFilePathWidgetLayout.setStretch(2, 1)
        oneFilePathWidgetLayout.setStretch(3, 2)
        # oneFilePathWidgetLayout.setStretch(4, 1)
        index = len(self.fileSelectWidgets)-1
        self.fileSelectWidgets.insert(index, ["bin", oneFilePathWidget, oneFilePathWidgetLayout, filePathWidget, fileBurnAddrWidget, openFileButton, fileBurnEncCheckbox, removeButton])
        self.fileSelectLayout.insertWidget(index, oneFilePathWidget)
        openFileButton.clicked.connect(lambda:self.selectFile(filePathWidget))
        removeButton.clicked.connect(lambda:self.removeFileSelection(removeButton))

    def fileSelectShowKfpkg(self, index, name):
        if index==0 and self.fileSelectWidget_Type(0) == "kfpkg": #only one kgpkg before
            self.fileSelectWidget_Path(index).setText(name)
        else:# have bin file before, remove all and add one for kfpkg
            for i in range(len(self.fileSelectWidgets)):
                if self.fileSelectWidget_Type(i)=="button":
                    self.fileSelectWidgets[i][3].clicked.disconnect()
                    self.fileSelectWidgets[i][4].clicked.disconnect()
                else:
                    self.fileSelectWidget_Button(i).clicked.disconnect()
                # self.fileSelectLayout.removeWidget(self.fileSelectWidget_Widget(i))
                self.fileSelectWidget_Widget(i).setParent(None)
            self.fileSelectWidgets.clear()
            oneFilePathWidget = QWidget()
            oneFilePathWidgetLayout = QHBoxLayout()
            oneFilePathWidget.setLayout(oneFilePathWidgetLayout)
            filePathWidget = QLineEdit()
            openFileButton = QPushButton(tr("OpenFile"))
            oneFilePathWidgetLayout.addWidget(filePathWidget)
            oneFilePathWidgetLayout.addWidget(openFileButton)
            oneFilePathWidgetLayout.setStretch(0, 3)
            oneFilePathWidgetLayout.setStretch(1, 1)
            self.fileSelectLayout.addWidget(oneFilePathWidget)
            self.fileSelectWidgets.append(["kfpkg", oneFilePathWidget, oneFilePathWidgetLayout, filePathWidget, None, openFileButton])
            openFileButton.clicked.connect(lambda:self.selectFile(filePathWidget))
            filePathWidget.setText(name)
            # TODO: resize window

    def fileSelectShowBin(self, index, name, addr=None, prefix=None, prefixAuto=False, closeButton=False ):
        if index==0 and self.fileSelectWidget_Type(0) == "kfpkg": #only one kgpkg before
            self.fileSelectWidget_Button(index).clicked.disconnect()
            # self.fileSelectLayout.removeWidget(self.fileSelectWidget_Widget(index))
            self.fileSelectWidget_Widget(index).setParent(None)
            self.fileSelectWidgets.clear()
            oneFilePathWidget = QWidget()
            oneFilePathWidgetLayout = QHBoxLayout()
            oneFilePathWidget.setLayout(oneFilePathWidgetLayout)
            filePathWidget = QLineEdit()
            fileBurnAddrWidget = QLineEdit("0x00000")
            fileBurnEncCheckbox = QCheckBox(tr("Prefix"))
            openFileButton = QPushButton(tr("OpenFile"))
            if closeButton:
                removeButton = QPushButton()
                removeButton.setProperty("class", "remove_file_selection")
            oneFilePathWidgetLayout.addWidget(filePathWidget)
            oneFilePathWidgetLayout.addWidget(fileBurnAddrWidget)
            oneFilePathWidgetLayout.addWidget(fileBurnEncCheckbox)
            oneFilePathWidgetLayout.addWidget(openFileButton)
            if closeButton:
                oneFilePathWidgetLayout.addWidget(removeButton)
            oneFilePathWidgetLayout.setStretch(0, 4)
            oneFilePathWidgetLayout.setStretch(1, 2)
            oneFilePathWidgetLayout.setStretch(2, 1)
            oneFilePathWidgetLayout.setStretch(3, 2)
            # oneFilePathWidgetLayout.setStretch(4, 1)
            self.fileSelectLayout.addWidget(oneFilePathWidget)
            openFileButton.clicked.connect(lambda:self.selectFile(filePathWidget))
            if closeButton:
                self.fileSelectWidgets.append(["bin", oneFilePathWidget, oneFilePathWidgetLayout, filePathWidget, fileBurnAddrWidget, openFileButton, fileBurnEncCheckbox, removeButton])
                removeButton.clicked.connect(lambda:self.removeFileSelection(removeButton))
                print(removeButton)
            else:
                self.fileSelectWidgets.append(["bin", oneFilePathWidget, oneFilePathWidgetLayout, filePathWidget, fileBurnAddrWidget, openFileButton, fileBurnEncCheckbox])
            # add ADD button
            addoneWidget = QWidget()
            addoneWidgetLayout = QHBoxLayout()
            addoneWidget.setLayout(addoneWidgetLayout)
            addFileButton = QPushButton(tr("Add File"))
            packFileButton = QPushButton(tr("Pack to kfpkg"))
            addoneWidgetLayout.addWidget(addFileButton)
            addoneWidgetLayout.addWidget(packFileButton)
            self.fileSelectLayout.addWidget(addoneWidget)
            self.fileSelectWidgets.append(["button", addoneWidget, addoneWidgetLayout, addFileButton, packFileButton])
            addFileButton.clicked.connect(self.addAddFileWidget)
            packFileButton.clicked.connect(self.packFile)

        self.fileSelectWidget_Path(index).setText(name)

        if prefixAuto:
            if name.endswith(".bin"):
                self.fileSelectWidget_Prefix(index).setChecked(True)
            else:
                self.fileSelectWidget_Prefix(index).setChecked(False)
        elif prefix:
            self.fileSelectWidget_Prefix(index).setChecked(True)
        if addr:
                self.fileSelectWidget_Addr(index).setText("0x%06x" %(addr))

    # return: ("kfpkg", [(file path, burn addr, add prefix),...])
    #      or ("bin", file path)
    #      or (None, None)
    def getBurnFilesInfo(self):
        files = []
        if self.fileSelectWidgets[0][0] == "kfpkg":
            path = self.fileSelectWidget_Path(0).text().strip()
            if path=="" or not os.path.exists(path):
                self.errorSignal.emit(tr("Error"), tr("Line {}: ").format(i+1)+tr("File path error")+":"+path)
                return (None, None)
            return ("kfpkg", path)
        for i in range(len(self.fileSelectWidgets)):
            if self.fileSelectWidgets[i][0] == "bin":
                path = self.fileSelectWidget_Path(i).text().strip()
                if path=="":
                    continue
                if not os.path.exists(path):
                    self.errorSignal.emit(tr("Error"), tr("Line {}: ").format(i+1)+tr("File path error")+":"+path)
                    return (None, None)
                try:
                    addr = int(self.fileSelectWidgets[i][4].text(), 16)
                except Exception:
                    self.errorSignal.emit(tr("Error"), tr("Line {}: ").format(i+1)+tr("Address error")+self.fileSelectWidgets[i][4].text())
                    return (None, None)
                files.append( (path, addr, self.fileSelectWidgets[i][6].isChecked()) )
        return ("bin", files)

    class KFPKG():
        def __init__(self):
            self.fileInfo = {"version": "0.1.0", "files": []}
            self.filePath = {}
            self.burnAddr = []
        
        def addFile(self, addr, path, prefix=False):
            if not os.path.exists(path):
                raise ValueError(tr("FilePathError"))
            if addr in self.burnAddr:
                raise ValueError(tr("Burn dddr duplicate")+":0x%06x" %(addr))
            f = {}
            f_name = os.path.split(path)[1]
            f["address"] = addr
            f["bin"] = f_name
            f["sha256Prefix"] = prefix
            self.fileInfo["files"].append(f)
            self.filePath[f_name] = path
            self.burnAddr.append(addr)

        def listDumps(self):
            kfpkg_json = json.dumps(self.fileInfo, indent=4)
            return kfpkg_json

        def listDump(self, path):
            with open(path, "w") as f:
                f.write(json.dumps(self.fileInfo, indent=4))

        def listLoads(self, kfpkgJson):
            self.fileInfo = json.loads(kfpkgJson)

        def listLload(self, path):
            with open(path) as f:
                self.fileInfo = json.load(f)

        def save(self, path):
            listName = os.path.join(tempfile.gettempdir(), "kflash_gui_tmp_list.json")
            self.listDump(listName)
            try:
                with zipfile.ZipFile(path, "w") as zip:
                    for name,path in self.filePath.items():
                        zip.write(path, arcname=name, compress_type=zipfile.ZIP_LZMA)
                    zip.write(listName, arcname="flash-list.json", compress_type=zipfile.ZIP_LZMA)
                    zip.close()
            except Exception as e:
                os.remove(listName)
                raise e
            os.remove(listName)

    def packFile(self):
        # generate flash-list.json
        fileType, files = self.getBurnFilesInfo()
        if not fileType or not files or fileType=="kfpkg":
            self.errorSignal.emit(tr("Error"), tr("File path error"))
            return
        kfpkg = self.KFPKG()
        try:
            for path, addr, prefix in files:
                kfpkg.addFile(addr, path, prefix)
        except Exception as e:
            self.errorSignal.emit(tr("Error"), tr("Pack kfpkg fail")+":"+str(e))
            return
        # select saving path
        if not os.path.exists(self.saveKfpkDir):
            self.saveKfpkDir = os.getcwd()
        fileName_choose, filetype = QFileDialog.getSaveFileName(self,  
                                    tr("Save File"),  
                                    self.saveKfpkDir,
                                    "k210 packages (*.kfpkg)")

        if fileName_choose == "":
            self.errorSignal.emit(tr("Error"), tr("File path error"))
            return
        if not fileName_choose.endswith(".kfpkg"):
            fileName_choose += ".kfpkg"
        self.saveKfpkDir = os.path.split(fileName_choose)[0]
        # print("save to ", fileName_choose)
        
        # write kfpkg file
        try:
            kfpkg.save(fileName_choose)
        except Exception as e:
            self.errorSignal.emit(tr("Error"), tr("Pack kfpkg fail")+":"+str(e))
            return
        self.hintSignal.emit(tr("Success"), tr("Save kfpkg success"))

    def selectFile(self, pathobj):
        index = -1
        for i in range(len(self.fileSelectWidgets)):
            if len(self.fileSelectWidgets[i]) >= 4:
                if pathobj == self.fileSelectWidget_Path(i):
                    index = i
        if index == -1:
            return
        tmp = index
        while tmp>=0:
            oldPath = self.fileSelectWidget_Path(tmp).text()
            if oldPath != "":
                break
            tmp -= 1
        if oldPath=="":
            oldPath = os.getcwd()
        fileName_choose, filetype = QFileDialog.getOpenFileName(self,  
                                    tr("SelectFile"),  
                                    oldPath,
                                    "All Files (*);;bin Files (*.bin);;k210 packages (*.kfpkg);;kmodel (*.kmodel);;encrypted kmodle(*.smodel)")   # 设置文件扩展名过滤,用双分号间隔

        if fileName_choose == "":
            return
        if not self.isFileValid(fileName_choose):
            self.errorSignal.emit(tr("Error"), tr("File path error"))
            return
        if self.isKfpkg(fileName_choose):
            self.fileSelectShowKfpkg(index, fileName_choose)
        else:
            self.fileSelectShowBin(index, fileName_choose, prefixAuto=True, closeButton=False)

    def errorHint(self, title, str):
        QMessageBox.critical(self, title, str)
    
    def hint(self, title, str):
        QMessageBox.information(self, title, str)

    def findSerialPort(self):
        self.port_list = list(serial.tools.list_ports.comports())
        return self.port_list

    def portChanged(self):
        self.serialPortCombobox.setCurrentIndex(0)
        self.serialPortCombobox.setToolTip(str(self.portList[0]))

    def detectSerialPort(self):
        if not self.isDetectSerialPort:
            self.isDetectSerialPort = True
            t = threading.Thread(target=self.detectSerialPortProcess)
            t.setDaemon(True)
            t.start()

    def showCombobox(self):
        self.serialPortCombobox.showPopup()

    def isKfpkg(self, name):
        if name.endswith(".kfpkg"):
            return True
        return False

    def isFileValid(self, name):
        if not os.path.exists(name):
            return False
        return True

    def detectSerialPortProcess(self):
        while(1):
            portList = self.findSerialPort()
            if len(portList)>0:
                currText = self.serialPortCombobox.currentText()
                self.serialPortCombobox.clear()
                for i in portList:
                    showStr = str(i[0])+" ("+str(i[1])+")"
                    self.serialPortCombobox.addItem(showStr)
                index = self.serialPortCombobox.findText(currText)
                if index>=0:
                    self.serialPortCombobox.setCurrentIndex(index)
                else:
                    self.serialPortCombobox.setCurrentIndex(0)
                break
            time.sleep(1)
        self.showSerialComboboxSignal.emit()
        self.isDetectSerialPort = False

    def programExitSaveParameters(self):
        paramObj = paremeters_save.ParametersToSave()
        paramObj.board    = self.boardCombobox.currentText()
        paramObj.burnPosition = self.burnPositionCombobox.currentText()
        paramObj.baudRate = self.serailBaudrateCombobox.currentIndex()
        paramObj.skin = self.param.skin
        paramObj.language = translation.current_lang
        path = self.fileSelectWidget_Path(0).text()
        if path.endswith(".kfpkg"):
            paramObj.files.append(path)
        else:
            for i in range(len(self.fileSelectWidgets)):
                try:
                    addr = int(self.fileSelectWidget_Addr(i).text(),16)
                except Exception:
                    continue
                paramObj.files.append( (self.fileSelectWidget_Path(i).text(), addr, self.fileSelectWidget_Prefix(i).isChecked()) )
        if self.slowModeCombobox.currentIndex()==0:
            paramObj.slowMode = True
        else:
            paramObj.slowMode = False
        paramObj.save(parameters.configFilePath)

    def programStartGetSavedParameters(self):
        paramObj = paremeters_save.ParametersToSave()
        paramObj.load(parameters.configFilePath)
        translation.setLanguage(paramObj.language)
        self.param = paramObj

    def updateFrameParams(self):
        pathLen = len(self.param.files)
        if pathLen == 1 and type(self.param.files[0])==str and self.param.files[0].endswith(".kfpkg"):
            self.fileSelectWidget_Path(0).setText(self.param.files[0])
        elif pathLen != 0:
            index = 0
            for path, addr, prefix  in self.param.files:
                prefix = None if (not prefix) else True
                if index!=0:
                    self.addAddFileWidget()
                if pathLen > 1 and index != 0:
                    closeButton = True
                else:
                    closeButton = False
                self.fileSelectShowBin(index, path, addr, prefix, closeButton=closeButton)
                index += 1
        self.boardCombobox.setCurrentText(self.param.board)
        self.burnPositionCombobox.setCurrentText(self.param.burnPosition)
        self.serailBaudrateCombobox.setCurrentIndex(self.param.baudRate)
        if self.param.slowMode:
            self.slowModeCombobox.setCurrentIndex(0)
        else:
            self.slowModeCombobox.setCurrentIndex(1)

    def closeEvent(self, event):
        try:
            self.programExitSaveParameters()
        finally:
            event.accept()

    def langChange(self):
        if self.param.language == translation.language_en:
            translation.setLanguage(translation.language_zh)
            lang = tr("Chinese language")
        else:
            translation.setLanguage(translation.language_en)
            lang = tr("English language")
        
        self.hint(tr("Hint"), tr("Language Changed to ") + lang + "\n"+ tr("Reboot to take effect"))
        self.frameWidget.style().unpolish(self.downloadButton)
        self.frameWidget.style().polish(self.downloadButton)
        self.frameWidget.update()

    def skinChange(self):
        if self.param.skin == 1: # light
            file = open(self.DataPath + '/assets/qss/style-dark.qss', "r")
            self.param.skin = 2
        else: # elif self.param.skin == 2: # dark
            file = open(self.DataPath + '/assets/qss/style.qss', "r")
            self.param.skin = 1
        self.app.setStyleSheet(file.read().replace("$DataPath", self.DataPath))

    def showAbout(self):
        QMessageBox.information(self, tr("About"),"<h1 style='color:#f75a5a';margin=10px;>"+parameters.appName+
                                '</h1><br><b style="color:#08c7a1;margin = 5px;">V'+str(helpAbout.versionMajor)+"."+
                                str(helpAbout.versionMinor)+"."+str(helpAbout.versionDev)+
                                "</b><br><br>"+helpAbout.date+"<br><br>"+helpAbout.strAbout())

    def autoUpdateDetect(self):
        auto = autoUpdate.AutoUpdate()
        if auto.detectNewVersion():
            auto.OpenBrowser()

    def openDevManagement(self):
        os.system('start devmgmt.msc')

    def updateProgress(self, fileTypeStr, current, total, speedStr):
        currBurnPos = self.burnPositionCombobox.currentText()
        if currBurnPos == tr("SRAM") or currBurnPos == tr_en("SRAM"):
            fileTypeStr = tr("ToSRAM")
        percent = current/float(total)*100
        hint = "<font color=%s>%s %s:</font>   <font color=%s> %.2f%%</font>   <font color=%s> %s</font>" %("#ff7575", tr("Downloading"), fileTypeStr, "#2985ff", percent, "#1aac2d", speedStr)
        self.progressHint.setText(hint)
        self.progressbar.setValue(percent)
    
    def updateProgressPrint(self, str):
        self.statusBarStauts.setText(str)

    def kflash_py_printCallback(self, *args, end = "\n"):
        msg = ""
        for i in args:
            msg += str(i)
        msg.replace("\n", " ")
        self.updateProgressPrintSignal.emit(msg)

    def progress(self, fileTypeStr, current, total, speedStr):
        self.updateProgressSignal.emit(fileTypeStr, current, total, speedStr)

    def download(self):
        if self.burning:
            self.terminateBurn()
            return
        tmpFile = ""
        fileType, filesInfo = self.getBurnFilesInfo()
        if not fileType or not filesInfo:
            self.errorSignal.emit(tr("Error"), tr("File path error"))
            return
        if fileType == "kfpkg":
            filename = filesInfo
        else:#generate kfpkg
            tmpFile = os.path.join(tempfile.gettempdir(), "kflash_gui_tmp.kfpkg")
            kfpkg = self.KFPKG()
            try:
                for path, addr, prefix in filesInfo:
                    kfpkg.addFile(addr, path, prefix)
                kfpkg.save(tmpFile)
            except Exception as e:
                os.remove(tmpFile)
                self.errorSignal.emit(tr("Error"), tr("Pack kfpkg fail")+":"+str(e))
                return
            filename = os.path.abspath(tmpFile)
        
        self.burning = True
        # if not self.checkFileName(filename):
        #     self.errorSignal.emit(tr("Error"), tr("FilePathError"))
        #     self.burning = False
        #     return
        color = False
        board = "dan"
        boardText = self.boardCombobox.currentText()
        if boardText == parameters.SipeedMaixGo:
            board = "goE"
        elif boardText == parameters.SipeedMaixGoD:
            board = "goD"
        elif boardText == parameters.SipeedMaixduino:
            board = "maixduino"
        elif boardText == parameters.SipeedMaixBit:
            board = "bit"
        elif boardText == parameters.SipeedMaixBitMic:
            board = "bit_mic"
        elif boardText == parameters.KendryteKd233:
            board = "kd233"
        elif boardText == parameters.kendryteTrainer:
            board = "trainer"
        elif boardText == parameters.Auto:
            board = None

        sram = False
        if self.burnPositionCombobox.currentText()==tr("SRAM") or \
            self.burnPositionCombobox.currentText()==tr_en("SRAM"):
            sram = True
        try:
            baud = int(self.serailBaudrateCombobox.currentText())
        except Exception:
            self.errorSignal.emit(tr("Error"), tr("BaudrateError"))
            self.burning = False
            return
        dev = ""
        try:
            dev  = self.serialPortCombobox.currentText().split()[0]
        except Exception:
            pass
        if dev=="":
            self.errorSignal.emit(tr("Error"), tr("PleaseSelectSerialPort"))
            self.burning = False
            return
        slow = self.slowModeCombobox.currentIndex()==0
        # hide setting widgets
        self.setFrameStrentch(1)
        self.settingWidget.hide()
        self.progressbar.setValue(0)
        self.progressbar.setGeometry(10, 0, self.downloadWidget.width()-25, 40)
        self.progressbarRootWidget.show()
        self.progressHint.show()
        self.downloadButton.setText(tr("Cancel"))
        self.downloadButton.setProperty("class", "redbutton")
        self.downloadButton.style().unpolish(self.downloadButton)
        self.downloadButton.style().polish(self.downloadButton)
        self.downloadButton.update()
        self.statusBarStauts.setText("<font color=%s>%s ...</font>" %("#1aac2d", tr("Downloading")))
        hint = "<font color=%s>%s</font>" %("#ff0d0d", tr("DownloadStart"))
        self.progressHint.setText(hint)
        # download
        self.burnThread = threading.Thread(target=self.flashBurnProcess, args=(dev, baud, board, sram, filename, self.progress, tmpFile!="", color, slow))
        self.burnThread.setDaemon(True)
        self.burnThread.start()

    def flashBurnProcess(self, dev, baud, board, sram, filename, callback, cleanFile, color, slow):
        success = True
        errMsg = ""
        try:
            if board:
                self.kflash.process(terminal=False, dev=dev, baudrate=baud, board=board, sram = sram, file=filename, callback=callback, noansi=not color, slow_mode=slow)
            else:
                self.kflash.process(terminal=False, dev=dev, baudrate=baud, sram = sram, file=filename, callback=callback, noansi=not color, slow_mode=slow)
        except Exception as e:
            errMsg = str(e)
            if str(e) != "Burn SRAM OK":
                success = False
        if cleanFile:
            os.remove(filename)
        if success:
            self.downloadResultSignal.emit(True, errMsg)
        else:
            self.downloadResultSignal.emit(False, errMsg)
            

    def downloadResult(self, success, msg):
        if success:
            self.hintSignal.emit(tr("Success"), tr("DownloadSuccess"))
            self.statusBarStauts.setText("<font color=%s>%s</font>" %("#1aac2d", tr("DownloadSuccess")))
        else:
            if msg == "Cancel":
                self.statusBarStauts.setText("<font color=%s>%s</font>" %("#ff1d1d", tr("DownloadCanceled")))
            else:
                msg = tr("ErrorSettingHint") + "\n\n"+msg
                self.errorSignal.emit(tr("Error"), msg)
                self.statusBarStauts.setText("<font color=%s>%s</font>" %("#ff1d1d", tr("DownloadFail")))
            self.progressHint.setText("")
        self.downloadButton.setText(tr("Download"))
        self.downloadButton.setProperty("class", "normalbutton")
        self.downloadButton.style().unpolish(self.downloadButton)
        self.downloadButton.style().polish(self.downloadButton)
        self.downloadButton.update()
        self.setFrameStrentch(0)
        self.progressbarRootWidget.hide()
        self.progressHint.hide()
        self.settingWidget.show()
        self.burning = False

    def terminateBurn(self):
        hint = "<font color=%s>%s</font>" %("#ff0d0d", tr("DownloadCanceling"))
        self.progressHint.setText(hint)
        self.kflash.kill()
Example #5
0
class Plugin(Plugin_Base):
    '''
        call sequence:
            set vars like hintSignal, hintSignal
            onInit
            onWidget
            onUiInitDone
                send
                onReceived
            getConfig
    '''
    # vars set by caller
    isConnected = lambda: False
    send = lambda x, y: None  # send(data_bytes=None, file_path=None, callback=lambda ok,msg:None)
    hintSignal = None  # hintSignal.emit(type(error, warning, info), title, msg)
    configGlobal = {}
    # other vars
    connParent = "dbg"  # parent id
    connChilds = []  # children ids
    id = "protocol"
    name = _("protocol")

    enabled = False  # user enabled this plugin
    active = False  # using this plugin

    showReceiveDataSignal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        if not self.id:
            raise ValueError(f"var id of Plugin {self} should be set")

    def onInit(self, config):
        '''
            init params, DO NOT take too long time in this func
        '''
        default = {
            "version":
            1,
            "sendAscii":
            True,
            "useCRLF":
            False,
            "sendEscape":
            True,
            "code":
            defaultProtocols.copy(),
            "currCode":
            "default",
            "customSendItems": [{
                "text": "hello",
                "remark": "hello",
                "icon": "fa5.hand-paper"
            }, {
                "text": "\\x01\\x03\\x03\\x03\\x03\\x01",
                "remark": "pre",
                "icon": "ei.arrow-left",
                "shortcut": [[16777234, "Left"]]
            }, {
                "text": "\\x01\\x04\\x04\\x04\\x04\\x01",
                "remark": "next",
                "icon": "ei.arrow-right",
                "shortcut": [[16777236, "Right"]]
            }, {
                "text": "\\x01\\x01\\x01\\x01\\x01\\x01",
                "remark": "ok",
                "icon": "fa.circle-o",
                "shortcut": [[16777220, "Return"]]
            }, {
                "text": "\\x01\\x02\\x02\\x02\\x02\\x01",
                "remark": "ret",
                "icon": "ei.return-key",
                "shortcut": [[16777216, "Esc"]]
            }]
        }
        self.config = config
        for k in default:
            if not k in self.config:
                self.config[k] = default[k]
        self.editingDefaults = False
        self.codeGlobals = {
            "unpack": unpack,
            "pack": pack,
            "crc": crc,
            "encoding": self.configGlobal["encoding"],
            "print": self.print
        }
        self.encodeMethod = lambda x: x
        self.decodeMethod = lambda x: x
        self.pressedKeys = []
        self.keyModeClickTime = 0

    def print(self, *args, **kw_args):
        end = "\n"
        start = "[MSG]: "
        if "end" in kw_args:
            end = kw_args["end"]
        if "start" in kw_args:
            start = kw_args["start"]
        string = start + " ".join(map(str, args)) + end
        self.showReceiveDataSignal.emit(string)

    class ModeButton(QPushButton):
        onFocusIn = pyqtSignal(QFocusEvent)
        onFocusOut = pyqtSignal(QFocusEvent)

        def __init__(self, text, eventFilter, parent=None) -> None:
            super().__init__(text, parent)
            self.installEventFilter(eventFilter)

        def focusInEvent(self, event):
            self.onFocusIn.emit(event)

        def focusOutEvent(self, event):
            self.onFocusOut.emit(event)

    def onWidgetMain(self, parent):
        self.mainWidget = QSplitter(Qt.Vertical)
        self.receiveWidget = TextEdit()
        font = QFont(
            'Menlo,Consolas,Bitstream Vera Sans Mono,Courier New,monospace, Microsoft YaHei',
            10)
        self.receiveWidget.setFont(font)
        self.receiveWidget.setLineWrapMode(TextEdit.NoWrap)
        self.clearBtn = QPushButton("")
        self.keyBtneventFilter = self.ModeButtonEventFilter(
            self.onModeBtnKeyPressEvent, self.onModeBtnKeyReleaseEvent)
        self.keyModeBtn = self.ModeButton(_("Key mode"),
                                          self.keyBtneventFilter)
        layoutClearMode = QHBoxLayout()
        layoutClearMode.addWidget(self.clearBtn)
        layoutClearMode.addWidget(self.keyModeBtn)
        clearModeWidget = QWidget()
        clearModeWidget.setLayout(layoutClearMode)
        utils_ui.setButtonIcon(self.clearBtn, "mdi6.broom")
        self.addButton = QPushButton("")
        utils_ui.setButtonIcon(self.addButton, "fa.plus")
        self.customSendScroll = QScrollArea()
        self.customSendScroll.setMinimumHeight(
            parameters.customSendItemHeight + 20)
        self.customSendScroll.setWidgetResizable(True)
        self.customSendScroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.customSendScroll.setHorizontalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)
        cutomSendItemsWraper = QWidget()
        self.customSendScroll.setWidget(cutomSendItemsWraper)
        #   wrapper widget
        cutomSendItemsWraper0 = QWidget()
        cutomSendItemsWraper0.setProperty("class", "scrollbar2")
        layout0 = QVBoxLayout()
        layout0.setContentsMargins(0, 8, 0, 0)
        cutomSendItemsWraper0.setLayout(layout0)
        layout0.addWidget(self.customSendScroll)
        customSendItemsLayoutWrapper = QVBoxLayout()
        customSendItemsLayoutWrapper.setContentsMargins(0, 0, 0, 0)
        cutomSendItemsWraper.setLayout(customSendItemsLayoutWrapper)
        # items container
        self.customItems = QWidget()
        self.customSendItemsLayout = QVBoxLayout()
        self.customSendItemsLayout.setContentsMargins(0, 0, 0, 0)
        self.customItems.setLayout(self.customSendItemsLayout)

        customSendItemsLayoutWrapper.addWidget(self.customItems)
        customSendItemsLayoutWrapper.addWidget(self.addButton)
        customSendItemsLayoutWrapper.addStretch(0)

        self.mainWidget.addWidget(self.receiveWidget)
        self.mainWidget.addWidget(clearModeWidget)
        self.mainWidget.addWidget(cutomSendItemsWraper0)
        self.mainWidget.setStretchFactor(0, 2)
        self.mainWidget.setStretchFactor(1, 1)
        self.mainWidget.setStretchFactor(2, 11)
        # event
        self.addButton.clicked.connect(lambda: self.insertSendItem())

        def clearReceived():
            self.receiveWidget.clear()
            self.statusBar.clear()

        self.clearBtn.clicked.connect(clearReceived)

        def keyModeOn(event):
            self.keyModeBtn.setProperty("class", "deleteBtn")
            utils_ui.updateStyle(self.mainWidget, self.keyModeBtn)
            self.keyModeClickTime = time.time()
            # show all shortcut
            widgets = self.customItems.findChildren(QPushButton, "editRemark")
            for i, w in enumerate(widgets):
                shortcut = "+".join(
                    (name for v, name in self.config["customSendItems"][i]
                     ["shortcut"]))
                w.setText(shortcut)
                utils_ui.updateStyle(self.mainWidget, w)

        def keyModeOff(event):
            self.keyModeBtn.setProperty("class", "")
            utils_ui.updateStyle(self.mainWidget, self.keyModeBtn)
            self.keyModeClickTime = 0
            # remove all preesed keys even them not release actually, to avoid window swith by ALT+TAB bug
            self.pressedKeys = []
            # hide all shortcut
            widgets = self.customItems.findChildren(QPushButton, "editRemark")
            for w in widgets:
                w.setText("")

        def keyModeTuggle():
            if self.keyModeBtn.property("class") == "deleteBtn":
                if time.time() - self.keyModeClickTime < 0.2:
                    return
                else:
                    self.keyModeBtn.clearFocus()

        self.keyModeBtn.onFocusIn.connect(keyModeOn)
        self.keyModeBtn.onFocusOut.connect(keyModeOff)
        self.keyModeBtn.clicked.connect(keyModeTuggle)
        return self.mainWidget

    def onWidgetSettings(self, parent):
        root = QWidget()
        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(0, 0, 0, 0)
        root.setLayout(rootLayout)
        setingGroup = QGroupBox(_("En-decoding settings"))
        layout = QGridLayout()
        setingGroup.setLayout(layout)
        self.codeItems = ComboBox()
        self.codeItemCustomStr = _("Custom, input name")
        self.codeItemLoadDefaultsStr = _("Load defaults")
        self.codeItems.setEditable(True)
        self.codeWidget = PlainTextEdit()
        self.saveCodeBtn = QPushButton(_("Save"))
        self.saveCodeBtn.setEnabled(False)
        self.deleteCodeBtn = QPushButton(_("Delete"))
        btnLayout = QHBoxLayout()
        btnLayout.addWidget(self.saveCodeBtn)
        btnLayout.addWidget(self.deleteCodeBtn)
        layout.addWidget(QLabel(_("Defaults")), 0, 0, 1, 1)
        layout.addWidget(self.codeItems, 0, 1, 1, 1)
        layout.addWidget(QLabel(_("Code")), 1, 0, 1, 1)
        layout.addWidget(self.codeWidget, 1, 1, 1, 1)
        layout.addLayout(btnLayout, 2, 1, 1, 1)
        serialSendSettingsLayout = QGridLayout()
        sendGroup = QGroupBox(_("Send settings"))
        sendGroup.setLayout(serialSendSettingsLayout)
        self.sendSettingsAscii = QRadioButton(_("ASCII"))
        self.sendSettingsHex = QRadioButton(_("HEX"))
        self.sendSettingsAscii.setToolTip(
            _("Get send data as visible format, select encoding method at top right corner"
              ))
        self.sendSettingsHex.setToolTip(
            _("Get send data as hex format, e.g. hex '31 32 33' equal to ascii '123'"
              ))
        self.sendSettingsAscii.setChecked(True)
        self.sendSettingsCRLF = QCheckBox(_("<CRLF>"))
        self.sendSettingsCRLF.setToolTip(
            _("Select to send \\r\\n instead of \\n"))
        self.sendSettingsCRLF.setChecked(False)
        self.sendSettingsEscape = QCheckBox(_("Escape"))
        self.sendSettingsEscape.setToolTip(
            _("Enable escape characters support like \\t \\r \\n \\x01 \\001"))
        serialSendSettingsLayout.addWidget(self.sendSettingsAscii, 0, 0, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsHex, 0, 1, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsCRLF, 1, 0, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsEscape, 1, 1, 1, 1)

        rootLayout.addWidget(sendGroup)
        rootLayout.addWidget(setingGroup)
        # event
        self.sendSettingsAscii.clicked.connect(lambda: self.bindVar(
            self.sendSettingsAscii, self.config, "sendAscii", bool))
        self.sendSettingsHex.clicked.connect(lambda: self.bindVar(
            self.sendSettingsHex, self.config, "sendAscii", bool, invert=True))
        self.sendSettingsCRLF.clicked.connect(lambda: self.bindVar(
            self.sendSettingsCRLF, self.config, "useCRLF", bool))
        self.sendSettingsEscape.clicked.connect(lambda: self.bindVar(
            self.sendSettingsEscape, self.config, "sendEscape", bool))
        self.saveCodeBtn.clicked.connect(self.saveCode)
        self.deleteCodeBtn.clicked.connect(self.deleteCode)
        self.codeWidget.onSave = self.saveCode
        return root

    def onWidgetStatusBar(self, parent):
        self.statusBar = statusBar(rxTxCount=True)
        return self.statusBar

    def onUiInitDone(self):
        '''
            UI init done, you can update your widget here
            this method runs in UI thread, do not block too long
        '''
        newItems = []
        for item in self.config["customSendItems"]:
            item = self.insertSendItem(item, load=True)
            newItems.append(item)
        self.config["customSendItems"] = newItems
        self.sendSettingsAscii.setChecked(self.config["sendAscii"])
        self.sendSettingsHex.setChecked(not self.config["sendAscii"])
        self.sendSettingsCRLF.setChecked(self.config["useCRLF"])
        self.sendSettingsEscape.setChecked(self.config["sendEscape"])
        self.showReceiveDataSignal.connect(self.showReceivedData)
        # init decoder and encoder
        for k in self.config["code"]:
            self.codeItems.addItem(k)
        self.codeItems.addItem(self.codeItemCustomStr)
        self.codeItems.addItem(self.codeItemLoadDefaultsStr)
        name = self.config["currCode"]
        idx = self.codeItems.findText(self.config["currCode"])
        if idx < 0:
            idx = 0
            name = "default"
        self.codeItems.setCurrentIndex(idx)
        self.selectCode(name)
        self.codeItems.currentIndexChanged.connect(
            self.onCodeItemChanged
        )  # add here to avoid self.selectCode trigger
        self.codeWidget.textChanged.connect(self.onCodeChanged)

    class ModeButtonEventFilter(QObject):
        def __init__(self, keyPressCb, keyReleaseCb) -> None:
            super().__init__()
            self.keyPressCb = keyPressCb
            self.keyReleaseCb = keyReleaseCb

        def eventFilter(self, obj, evt):
            if evt.type() == QEvent.KeyPress:
                # prevent default key events
                self.keyPressCb(evt)
                return True
            elif evt.type() == QEvent.KeyRelease:
                self.keyReleaseCb(evt)
                return True
            return False

    def onModeBtnKeyPressEvent(self, event):
        # send by shortcut
        key = event.key()
        self.pressedKeys.append(key)
        for item in self.config["customSendItems"]:
            if not "shortcut" in item:
                continue
            shortcut = item["shortcut"]
            if len(shortcut) == len(self.pressedKeys):
                same = True
                for i in range(len(shortcut)):
                    if shortcut[i][0] != self.pressedKeys[i]:
                        same = False
                        break
                if same:
                    self.sendCustomItem(item)

    def onModeBtnKeyReleaseEvent(self, event):
        key = event.key()
        if key in self.pressedKeys:
            self.pressedKeys.remove(key)

    def onKeyPressEvent(self, event):
        pass

    def onKeyReleaseEvent(self, event):
        pass

    def insertSendItem(self, item=None, load=False):
        # itemsNum = self.customSendItemsLayout.count() + 1
        # height = parameters.customSendItemHeight * (itemsNum + 1) + 20
        # topHeight = self.receiveWidget.height() + 100
        # if height + topHeight > self.funcParent.height():
        #     height = self.funcParent.height() - topHeight
        # if height < 0:
        #     height = self.funcParent.height() // 3
        # self.customSendScroll.setMinimumHeight(height)
        if not item:
            item = {"text": "", "remark": None, "icon": None}
        if type(item) == str:
            item = {"text": item, "remark": None}
        text = item["text"]
        remark = item["remark"]
        itemWidget = QWidget()
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        itemWidget.setLayout(layout)
        cmd = QLineEdit(text)
        if remark:
            send = QPushButton(remark)
        else:
            send = QPushButton("")
        if (not "icon" in item) or not item["icon"]:
            item["icon"] = "fa.send"
        if not "shortcut" in item:
            item["shortcut"] = []
        utils_ui.setButtonIcon(send, item["icon"])
        editRemark = QPushButton("")
        editRemark.setObjectName("editRemark")
        utils_ui.setButtonIcon(editRemark, "ei.pencil")
        editRemark.setProperty("class", "remark")
        cmd.setToolTip(text)
        send.setToolTip(text)
        cmd.textChanged.connect(lambda: self.onCustomItemChange(
            self.customSendItemsLayout.indexOf(itemWidget), cmd, send))
        send.setProperty("class", "smallBtn")

        def sendCustomData(idx):
            self.sendCustomItem(self.config["customSendItems"][idx])

        send.clicked.connect(lambda: sendCustomData(
            self.customSendItemsLayout.indexOf(itemWidget)))
        delete = QPushButton("")
        utils_ui.setButtonIcon(delete, "fa.close")
        delete.setProperty("class", "deleteBtn")
        layout.addWidget(cmd)
        layout.addWidget(send)
        layout.addWidget(editRemark)
        layout.addWidget(delete)
        delete.clicked.connect(lambda: self.deleteSendItem(
            self.customSendItemsLayout.indexOf(itemWidget), itemWidget,
            [send, editRemark, delete]))

        def changeRemark(idx, obj):
            if not "icon" in self.config["customSendItems"][idx]:
                self.config["customSendItems"][idx]["icon"] = None
            shortcut = []
            if "shortcut" in self.config["customSendItems"][idx]:
                shortcut = self.config["customSendItems"][idx]["shortcut"]
            ok, remark, icon, shortcut = EditRemarDialog(
                obj.text(), self.config["customSendItems"][idx]["icon"],
                shortcut).exec()
            if ok:
                obj.setText(remark)
                if icon:
                    utils_ui.setButtonIcon(obj, icon)
                else:
                    obj.setIcon(QIcon())
                self.config["customSendItems"][idx]["remark"] = remark
                self.config["customSendItems"][idx]["icon"] = icon
                self.config["customSendItems"][idx]["shortcut"] = shortcut

        editRemark.clicked.connect(lambda: changeRemark(
            self.customSendItemsLayout.indexOf(itemWidget), send))
        self.customSendItemsLayout.addWidget(itemWidget)
        if not load:
            self.config["customSendItems"].append(item)
        return item

    def deleteSendItem(self, idx, item, iconItems=[]):
        for obj in iconItems:
            utils_ui.clearButtonIcon(obj)
        item.setParent(None)
        self.config["customSendItems"].pop(idx)
        # itemsNum = self.customSendItemsLayout.count()
        # height = parameters.customSendItemHeight * (itemsNum + 1) + 20
        # topHeight = self.receiveWidget.height() + 100
        # if height + topHeight > self.funcParent.height():
        #     height = self.funcParent.height() - topHeight
        # self.customSendScroll.setMinimumHeight(height)

    def showReceivedData(self, text: str):
        curScrollValue = self.receiveWidget.verticalScrollBar().value()
        self.receiveWidget.moveCursor(QTextCursor.End)
        endScrollValue = self.receiveWidget.verticalScrollBar().value()
        self.receiveWidget.insertPlainText(text)
        if curScrollValue < endScrollValue:
            self.receiveWidget.verticalScrollBar().setValue(curScrollValue)
        else:
            self.receiveWidget.moveCursor(QTextCursor.End)

    def onReceived(self, data: bytes):
        self.statusBar.addRx(len(data))
        try:
            data = self.decodeMethod(data)
        except Exception as e:
            self.hintSignal.emit("error", _("Error"),
                                 _("Run decode error") + " " + str(e))
            return
        if not data:
            return
        for plugin in self.connChilds:
            plugin.onReceived(data)
        if type(data) != str:
            data = self.decodeReceivedData(data, self.configGlobal["encoding"],
                                           not self.config["sendAscii"],
                                           self.config["sendEscape"])
        self.showReceiveDataSignal.emit(data + "\n")

    def sendData(self, data_bytes=None):
        try:
            data_bytes = self.encodeMethod(data_bytes)
        except Exception as e:
            self.hintSignal.emit("error", _("Error"),
                                 _("Run encode error") + " " + str(e))
            return
        if data_bytes:
            self.send(data_bytes, callback=self.onSent)

    def onSent(self, ok, msg, length, path):
        if ok:
            self.statusBar.addTx(length)
        else:
            self.hintSignal.emit("error", _("Error"),
                                 _("Send data failed!") + " " + msg)

    def sendCustomItem(self, item):
        text = item["text"]
        dateBytes = self.parseSendData(text, self.configGlobal["encoding"],
                                       self.config["useCRLF"],
                                       not self.config["sendAscii"],
                                       self.config["sendEscape"])
        if dateBytes:
            self.sendData(data_bytes=dateBytes)

    def onCustomItemChange(self, idx, edit, send):
        text = edit.text()
        edit.setToolTip(text)
        send.setToolTip(text)
        self.config["customSendItems"][idx].update({
            "text": text,
            "remark": send.text()
        })

    def onCodeItemChanged(self):
        if self.editingDefaults:
            return
        self.editingDefaults = True
        if self.codeItems.currentText() == self.codeItemCustomStr:
            self.codeItems.clearEditText()
            self.editingDefaults = False
            return
        if self.codeItems.currentText() == self.codeItemLoadDefaultsStr:
            for name in defaultProtocols:
                idx = self.codeItems.findText(name)
                if idx >= 0:
                    self.codeItems.removeItem(idx)
                self.codeItems.insertItem(self.codeItems.count() - 2, name)
                self.config["code"][name] = defaultProtocols[name]
            self.codeItems.setCurrentIndex(0)
            self.selectCode(self.codeItems.currentText())
            self.editingDefaults = False
            return
        # update code from defaults
        self.selectCode(self.codeItems.currentText())
        self.editingDefaults = False

    def selectCode(self, name):
        if name in [self.codeItemCustomStr, self.codeItemLoadDefaultsStr
                    ] or not name or not name in self.config["code"]:
            print(f"name {name} invalid")
            return
        self.config["currCode"] = name
        self.codeWidget.clear()
        self.codeWidget.insertPlainText(self.config["code"][name])
        ok, e, d = self.getEnDecodeMethod(self.codeWidget.toPlainText())
        if ok:
            self.encodeMethod = e
            self.decodeMethod = d
        self.saveCodeBtn.setText(_("Save"))
        self.saveCodeBtn.setEnabled(False)

    def getEnDecodeMethod(self, code):
        func = lambda x: x
        try:
            exec(code, self.codeGlobals)
            if (not "decode"
                    in self.codeGlobals) or not "encode" in self.codeGlobals:
                raise ValueError(
                    _("decode and encode method should be in code"))
            return True, self.codeGlobals["encode"], self.codeGlobals["decode"]
        except Exception as e:
            msg = _("Method error") + "\n" + str(e)
            self.hintSignal.emit("error", _("Error"), msg)
        return False, func, func

    def onCodeChanged(self):
        changed = True
        name = self.codeItems.currentText()
        if name in self.config["code"]:
            codeSaved = self.config["code"][name]
            code = self.codeWidget.toPlainText()
            if code == codeSaved:
                changed = False
        if changed:
            self.saveCodeBtn.setText(_("Save") + " *")
            self.saveCodeBtn.setEnabled(True)
        else:
            self.saveCodeBtn.setText(_("Save"))
            self.saveCodeBtn.setEnabled(False)

    def saveCode(self):
        self.editingDefaults = True
        name = self.codeItems.currentText()
        if name in [self.codeItemCustomStr, self.codeItemLoadDefaultsStr
                    ] or not name:
            self.hintSignal.emit("warning", _("Warning"),
                                 _("Please input code profile name first"))
            self.editingDefaults = False
            return
        idx = self.codeItems.findText(name)
        if idx < 0:
            self.codeItems.insertItem(self.codeItems.count() - 2, name)
        self.editingDefaults = False
        code = self.codeWidget.toPlainText()
        ok, e, d = self.getEnDecodeMethod(code)
        if ok:
            self.encodeMethod = e
            self.decodeMethod = d
            self.config["code"][name] = code
            self.saveCodeBtn.setText(_("Save"))
            self.saveCodeBtn.setEnabled(False)

    def deleteCode(self):
        self.editingDefaults = True
        name = self.codeItems.currentText()
        itemsConfig = [self.codeItemCustomStr, self.codeItemLoadDefaultsStr]
        # QMessageBox.infomation()
        if name in itemsConfig or not name:
            self.hintSignal.emit(
                "warning", _("Warning"),
                _("Please select a code profile name first to delete"))
            self.editingDefaults = False
            return
        idx = self.codeItems.findText(name)
        if idx < 0:
            self.editingDefaults = False
            return
        self.codeItems.removeItem(idx)
        self.config["code"].pop(name)
        name = list(self.config["code"].keys())
        if len(name) > 0:
            name = name[0]
            self.codeItems.setCurrentText(name)
            self.selectCode(name)
        self.editingDefaults = False