示例#1
0
def gui_it(click_func, style="qdarkstyle", **argvs) -> None:
    """
    Parameters
    ----------
    click_func
    `new_thread` is used for qt-based func, like matplotlib
    """
    global _gstyle
    _gstyle = GStyle(style)
    # Need to ensure plugins work on systems w. no Qt5 installed:
    # os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = "."     # Or rather: 'resource_path(".")' ???
    # app_path = os.path.abspath(__file__)
    app_path = resource_path(".")
    app_plugin_path = os.path.join(app_path, "plugins")
    os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = app_path
    # QtWidgets.QApplication.addLibraryPath(os.path.join(pyqt, "plugins"))
    app = QtWidgets.QApplication(sys.argv)
    # app_path = app.applicationDirPath()      # Won't work! Points to local 'python.exe' ... :-(
    app.addLibraryPath(app_path)
    app.addLibraryPath(app_plugin_path)
    print(f"Using '{app_plugin_path}" ' as plugin PATH ...')
    print(app.libraryPaths())  # For DEBUG only!
    print(f"Running application '{app_path}' ...")
    app.setStyleSheet(_gstyle.stylesheet)

    # set the default value for argvs
    argvs["run_exit"] = argvs.get("run_exit", False)
    argvs["new_thread"] = argvs.get("new_thread", False)

    ex = App(click_func, **argvs)
    sys.exit(app.exec_())
def vv_fram_erase(cleanup=True, verbose=True, debug=False):
    """
    Erase FRAM on irrigation-sensor target (VV).
    Note that erase-application START-address is NOT equal to RAM-startaddr!
    Instead, the 'ResetISR' symbol is located 212 bytes ABOVE the vector table, at addr=0x1FFFE0D4.
    """
    FRAM_ERASE_JLINK_CMD_FILE = "FRAM_erase.tmp.jlink"
    FRAM_ERASE_APP_SREC = resource_path("VV_FRAM_eraser.srec")      # TODO: must have a separate, K32L-specific application(=SREC) in order to erase FRAM on 'AB'-type!!
    FRAM_ERASE_APP_START_ADDR = 0x1FFFE0D4                          # NOTE: location of '.init' symbol read from .MAP-file --> app loaded in SRAM!
    #
    with open(FRAM_ERASE_JLINK_CMD_FILE, 'w') as fp:
        fp.write("halt\n")
        fp.write("r\n")
        fp.write(f"loadfile {FRAM_ERASE_APP_SREC}\n")
        fp.write(f"setpc {hex(FRAM_ERASE_APP_START_ADDR)}\n")
        fp.write("g\n")
        fp.write("sleep 6000\n")   # Must ensure we sleep at least 5sec to allow erase-app to run to finish!
        fp.write("q\n")
    # Need to sleep at least 5sec to allow FRAM-erase process to complete.
    # TODO: check when erase-app has finished blanking FRAM!
    #  (but, tricky without serial port connection ...)
    # TODO: also determine end result of FRAM-erase (PASS or FAIL)!
    cmd_status, jlink_output = run_jlink_cmd_file(FRAM_ERASE_JLINK_CMD_FILE)
    # Remove file if specified:
    if cleanup:
        try:
            os.remove(FRAM_ERASE_JLINK_CMD_FILE)
        except OSError:
            pass
    #
    return cmd_status, jlink_output
def run_jlink_cmd_file(cmd_file_name, verbose=True):
    SUBPROC_RETVAL_STATUS_SUCCESS = 0
    status = False
    #
    cmd_with_args = []
    cmd_with_args.append(resource_path(JLINK_EXE_FILE))
    cmd_with_args.extend(JLINK_TARGET_OPTIONS)
    cmd_with_args.append(cmd_file_name)
    #
    print("Running: " + str(cmd_with_args))
    try:
        # if sys.plaform == 'win32':
        if os.name != 'posix':
            startup_info = subprocess.STARTUPINFO()
            startup_info.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
            startup_info.wShowWindow = subprocess.SW_HIDE
            #
            p1 = subprocess.Popen(cmd_with_args,
                                  shell=False,
                                  stdin=subprocess.DEVNULL,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE,
                                  startupinfo=startup_info)
        else:
            p1 = subprocess.Popen(cmd_with_args,
                                  shell=False,
                                  stdin=subprocess.DEVNULL,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
        # Run the command
        output = p1.communicate(timeout=30)[0]
    except subprocess.TimeoutExpired:
        print("ERROR: timeout from running J-Link!")
        return status, None

    lines = output.splitlines()
    lines_out = []
    for line in lines:
        line_str = line.decode('latin1', 'ignore')
        lines_out.append(line_str)
        if verbose:
            print(line_str)
        # Check for J-Link NOT connected, or connection problems:
        if line_str.startswith("Cannot connect to target") or line_str.startswith("Connecting to J-Link via USB...FAILED"):
            return status, lines_out
        # Check for WRITE-errors:
        if line_str.startswith("Could not write"):
            return status, lines_out
        # Check for 'Error'/'ERROR' in output:
        if line_str.find('Error') > 0 or line_str.find('ERROR') > 0:
            return status, lines_out
        # Check for 'Error'/'ERROR' in output:
        if line_str.find('Error') > 0 or line_str.find('ERROR') > 0:
            return status, lines_out
    # If 'normal' output - or NO output at all - the return value is used to decide 'status':
    status = (p1.returncode == SUBPROC_RETVAL_STATUS_SUCCESS)
    #
    return status, lines_out
示例#4
0
 def generate_cmd_button(self,
                         label,
                         cmd_slot,
                         tooltip: str = "",
                         icon_name: str = ""):
     button = QtWidgets.QPushButton(label)
     button.setToolTip(tooltip)
     if icon_name != "":
         if icon_name.startswith('SP_'):
             button.setIcon(button.style().standardIcon(
                 getattr(QtWidgets.QStyle, icon_name)))
         else:
             try:
                 button.setIcon(QtGui.QIcon(resource_path(icon_name)))
             except Exception:
                 pass
     button.clicked.connect(self.clean_sysargv)
     button.clicked.connect(self.add_sysargv)
     button.clicked.connect(cmd_slot)
     return button
示例#5
0
def run_jlink_cmd_file(cmd_file_name, verbose=True):
    SUBPROC_RETVAL_STATUS_SUCCESS = 0
    status = False
    #
    cmd_with_args = []
    cmd_with_args.append(resource_path(JLINK_EXE_FILE))
    cmd_with_args.extend(JLINK_TARGET_OPTIONS)
    cmd_with_args.append(cmd_file_name)
    #
    print("Running: " + str(cmd_with_args))
    try:
        startup_info = subprocess.STARTUPINFO()
        startup_info.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
        startup_info.wShowWindow = subprocess.SW_HIDE
        #
        p1 = subprocess.Popen(cmd_with_args,
                              shell=False,
                              stdin=subprocess.DEVNULL,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE,
                              startupinfo=startup_info)
        # Run the command
        output = p1.communicate(timeout=30)[0]
    except subprocess.TimeoutExpired:
        print("ERROR: timeout from running J-Link!")
        return status

    lines = output.splitlines()
    lines_out = []
    for line in lines:
        line_str = line.decode('latin1', 'ignore')
        lines_out.append(line_str)
        if verbose:
            print(line_str)

    status = (p1.returncode == SUBPROC_RETVAL_STATUS_SUCCESS)
    #
    return status, lines_out
        print("================================")
        #
        if total_status:
            print("PASS: successful programming.")
        else:
            print("FAIL: programming error!!")
        print("================================")
        print("")
    #
    print("Completed FW-programming.")
    #
    return total_status


# ***************** MAIN ************************

if __name__ == "__main__":
    prog_func = run_irrigation_sensor_programming
    prog_func.__setattr__("name", f"Irrigation Sensor Programming Tool ver.{VER_MAJOR}.{VER_MINOR}.{VER_SUBMINOR}")
    quick.gui_it(prog_func,
           run_exit=False,
           new_thread=False,
           style="qdarkstyle",
           output="gui",
           width=650,
           height=750,
           left=100,
           top=100,
           app_icon=resource_path("7sense-7-hvit.png"))