Initial commit: ch55xtool

This commit is contained in:
eddyem
2020-11-16 01:00:51 +03:00
parent 2e60721244
commit d6137006fd
22 changed files with 5049 additions and 0 deletions

4
CH55xtool/59-ch55x.rules Normal file
View File

@@ -0,0 +1,4 @@
# ch552 bootloader
SUBSYSTEMS=="usb", ATTRS{idVendor}=="4348", ATTRS{idProduct}=="55e0", MODE:="0666", SYMLINK+="ch55x_%n"

167
CH55xtool/CMakeLists.txt Normal file
View File

@@ -0,0 +1,167 @@
cmake_minimum_required(VERSION 2.8)
set(PROJ ch55tool)
set(MINOR_VERSION "1")
set(MID_VERSION "0")
set(MAJOR_VERSION "0")
set(VERSION "${MAJOR_VERSION}.${MID_VERSION}.${MINOR_VERSION}")
enable_language(C)
message("VER: ${VERSION}")
# default flags
set(CFLAGS -O2 -Wextra -Wall -Werror -W -std=gnu99)
set(CMAKE_COLOR_MAKEFILE ON)
# here is one of two variants: all .c in directory or .c files in list
aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR} SOURCES)
#list(REMOVE_ITEM SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/<file to remove>)
#set(SOURCES list_of_c_files)
# we can change file list
#if(NOT DEFINED something)
# set(SOURCES ${SOURCES} one_more_list)
# add_definitions(-DSOME_DEFS)
#endif()
# cmake -DEBUG=1 -> debugging
if(DEFINED EBUG)
add_definitions(-DEBUG)
endif()
# directory should contain dir locale/ru for gettext translations
set(LCPATH ${CMAKE_SOURCE_DIR}/locale/ru)
if(NOT DEFINED LOCALEDIR)
if(DEFINED DEBUG)
set(LOCALEDIR ${CMAKE_CURRENT_SOURCE_DIR}/locale)
else()
set(LOCALEDIR ${CMAKE_INSTALL_PREFIX}/share/locale)
endif()
endif()
###### pkgconfig ######
# pkg-config modules (for pkg-check-modules)
set(MODULES usefull_macros libusb-1.0)
# additional modules on condition
#if(DEFINED SOMETHING)
# set(MODULES ${MODULES} more_modules>=version)
# add_definitions(-DSOMEDEFS)
#endif()
# find packages:
find_package(PkgConfig REQUIRED)
# non-required
#find_package(<pkg1>)
pkg_check_modules(${PROJ} REQUIRED ${MODULES})
# external modules like OpenMP:
#include(FindOpenMP)
#if(OPENMP_FOUND)
# set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
# set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
#endif()
# append data from find_package:
#list(APPEND ${PROJ}_INCLUDE_DIRS ${<pkg1>_INCLUDE_DIR} ${<pkg2>_INCLUDE_DIR})
#list(APPEND ${PROJ}_LIBRARIES ${<pkg1>_LIBRARY} ${<pkg2>_LIBRARY})
#list(APPEND ${${PROJ}_LIBRARY_DIRS} ${<pkg1>_LIBRARY_DIRS})
###### additional flags ######
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -lfftw3_threads")
# conditional check:
#if(NOT DEFINED NO_GSL)
# pkg_check_modules(GSL gsl)
#endif()
#if(NOT DEFINED GSL_VERSION)
# message("GSL not found, some mathematics functions wouldn't be avialable")
#else()
# add_definitions(-DGSL_FOUND)
#endif()
project(${PROJ})
# change wrong behaviour with install prefix
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT AND CMAKE_INSTALL_PREFIX MATCHES "/usr/local")
message("Change default install path to /usr")
set(CMAKE_INSTALL_PREFIX "/usr")
endif()
message("Install dir prefix: ${CMAKE_INSTALL_PREFIX}")
# gettext files
set(PO_FILE ${LCPATH}/messages.po)
set(MO_FILE ${LCPATH}/LC_MESSAGES/${PROJ}.mo)
set(RU_FILE ${LCPATH}/ru.po)
# exe file
add_executable(${PROJ} ${SOURCES})
# another exe, depending on some other files
#add_executable(test_client client.c usefull_macros.c parceargs.c)
# -I
include_directories(${${PROJ}_INCLUDE_DIRS})
# -L
link_directories(${${PROJ}_LIBRARY_DIRS})
# -D
add_definitions(${CFLAGS} -DLOCALEDIR=\"${LOCALEDIR}\"
-DPACKAGE_VERSION=\"${VERSION}\" -DGETTEXT_PACKAGE=\"${PROJ}\"
-DMINOR_VERSION=\"${MINOR_VERSION}\" -DMID_VERSION=\"${MID_VERSION}\"
-DMAJOR_VERSION=\"${MAJOR_VESION}\")
###### pthreads ######
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
set_property(TARGET ${PROJ} PROPERTY COMPILE_OPTIONS "-pthread")
set_property(TARGET ${PROJ} PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
list(APPEND ${PROJ}_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}")
endif()
# target libraries
target_link_libraries(${PROJ} ${${PROJ}_LIBRARIES})
# Installation of the program
INSTALL(FILES ${CMAKE_SOURCE_DIR}/59-ch55x.rules DESTINATION /etc/udev/rules.d/)
INSTALL(TARGETS ${PROJ} DESTINATION "bin")
#PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
INSTALL(FILES ${MO_FILE} DESTINATION "share/locale/ru/LC_MESSAGES")
#PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ)
# Script to be executed at installation time (kind of post-intallation script) to
# change the right accesses on the installed files
#INSTALL(SCRIPT inst.cmake)
###### gettext ######
find_package(Gettext REQUIRED)
find_program(GETTEXT_XGETTEXT_EXECUTABLE xgettext)
if(NOT GETTEXT_XGETTEXT_EXECUTABLE OR NOT GETTEXT_MSGFMT_EXECUTABLE)
message(FATAL_ERROR "xgettext not found")
endif()
file(MAKE_DIRECTORY ${LCPATH})
file(MAKE_DIRECTORY ${LCPATH}/LC_MESSAGES)
add_custom_command(
OUTPUT ${PO_FILE}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMAND ${GETTEXT_XGETTEXT_EXECUTABLE} --from-code=utf-8 ${SOURCES} -c -k_ -kN_ -o ${PO_FILE}
COMMAND sed -i 's/charset=.*\\\\n/charset=koi8-r\\\\n/' ${PO_FILE}
COMMAND enconv ${PO_FILE}
DEPENDS ${SOURCES}
)
# we need this to prewent ru.po from deleting by make clean
add_custom_command(
OUTPUT ${MO_FILE}
COMMAND ${GETTEXT_MSGFMT_EXECUTABLE} ${RU_FILE} -o ${MO_FILE}
DEPENDS ru_file_updated
)
add_custom_command(
OUTPUT ru_file_updated
COMMAND [ -f ${RU_FILE} ] && ${GETTEXT_MSGMERGE_EXECUTABLE} -Uis ${RU_FILE} ${PO_FILE} || cp ${PO_FILE} ${RU_FILE}
COMMAND ${CMAKE_COMMAND} -E touch ru_file_updated
#BYPRODUCTS ${RU_FILE}
DEPENDS ${PO_FILE}
)
add_custom_target(MO_FILE ALL DEPENDS ${MO_FILE})

15
CH55xtool/Readme.md Normal file
View File

@@ -0,0 +1,15 @@
CH55xtool
=========
Tool for CH55x flashing [from here](https://github.com/MarsTechHAN/ch552tool), rewritten in C.
```
Usage: ch55tool [args]
Where args are:
-P, --pidfile=arg pidfile (default: /tmp/testcmdlnopts.pid)
-b, --binname=arg name of binary file to flash
-d, --dontrestart don't reset MCU after writing
-h, --help show this help
```

82
CH55xtool/cmdlnopts.c Normal file
View File

@@ -0,0 +1,82 @@
/*
* This file is part of the CH55tool project.
* Copyright 2020 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <math.h>
#include "cmdlnopts.h"
#include "usefull_macros.h"
/*
* here are global parameters initialisation
*/
static int help;
static glob_pars G;
// default PID filename:
#define DEFAULT_PIDFILE "/tmp/testcmdlnopts.pid"
// DEFAULTS
// default global parameters
static glob_pars const Gdefault = {
.pidfile = DEFAULT_PIDFILE,
};
/*
* Define command line options by filling structure:
* name has_arg flag val type argptr help
*/
static myoption cmdlnopts[] = {
// common options
{"help", NO_ARGS, NULL, 'h', arg_int, APTR(&help), _("show this help")},
{"pidfile", NEED_ARG, NULL, 'P', arg_string, APTR(&G.pidfile), _("pidfile (default: " DEFAULT_PIDFILE ")")},
{"binname", NEED_ARG, NULL, 'b', arg_string, APTR(&G.binname), _("name of binary file to flash")},
{"dontrestart",NO_ARGS, NULL, 'd', arg_int, APTR(&G.dontrestart),_("don't reset MCU after writing")},
end_option
};
/**
* Parse command line options and return dynamically allocated structure
* to global parameters
* @param argc - copy of argc from main
* @param argv - copy of argv from main
* @return allocated structure with global parameters
*/
glob_pars *parse_args(int argc, char **argv){
int i;
void *ptr;
ptr = memcpy(&G, &Gdefault, sizeof(G)); assert(ptr);
size_t hlen = 1024;
char helpstring[1024], *hptr = helpstring;
snprintf(hptr, hlen, "Usage: %%s [args]\n\n\tWhere args are:\n");
// format of help: "Usage: progname [args]\n"
change_helpstring(helpstring);
// parse arguments
parseargs(&argc, &argv, cmdlnopts);
if(help) showhelp(-1, cmdlnopts);
if(argc > 0){
G.rest_pars_num = argc;
G.rest_pars = MALLOC(char *, argc);
for (i = 0; i < argc; i++)
G.rest_pars[i] = strdup(argv[i]);
}
return &G;
}

38
CH55xtool/cmdlnopts.h Normal file
View File

@@ -0,0 +1,38 @@
/*
* This file is part of the CH55tool project.
* Copyright 2020 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef CMDLNOPTS_H__
#define CMDLNOPTS_H__
/*
* here are some typedef's for global data
*/
typedef struct{
char *pidfile; // name of PID file
char *binname; // name of binary file
int dontrestart; // don't restart after writing
int rest_pars_num; // number of rest parameters
char** rest_pars; // the rest parameters: array of char*
} glob_pars;
glob_pars *parse_args(int argc, char **argv);
#endif // CMDLNOPTS_H__

Binary file not shown.

View File

@@ -0,0 +1,110 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-11-16 00:54+0300\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=koi8-r\n"
"Content-Transfer-Encoding: 8bit\n"
#. common options
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/cmdlnopts.c:48
msgid "show this help"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/cmdlnopts.c:49
msgid "pidfile (default: "
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/cmdlnopts.c:50
msgid "name of binary file to flash"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/cmdlnopts.c:51
msgid "don't reset MCU after writing"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:47
#, c-format
msgid "Another copy of this process found, pid=%d. Exit."
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:55
#, c-format
msgid "%d extra options:\n"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:71
msgid "Chip not found"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:74
msgid "Bad chip version"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:75
#, c-format
msgid "Found %s, version %s; flash size %d\n"
msgstr ""
#. just check chip
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:77
msgid "Can't erase chip"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:78
#, c-format
msgid "Try to write %s\n"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:79
msgid "Can't write flash"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:80
msgid "Verify data\n"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:81
msgid "Verification of flash failed"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:82
msgid "Can't fix writing"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:84
msgid "Reset MCU\n"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/usb.c:66
msgid "No devices found"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/usb.c:135
#, c-format
msgid "Version %s not supported\n"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/usb.c:149
msgid "Wrong getver()?"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/usb.c:150
msgid "Wrong detect_chip()?"
msgstr ""
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/usb.c:152
#, c-format
msgid "Can't open %s"
msgstr ""

109
CH55xtool/locale/ru/ru.po Normal file
View File

@@ -0,0 +1,109 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr "Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-11-16 00:54+0300\n"
"PO-Revision-Date: 2020-11-16 00:50+0300\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: ru\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=koi8-r\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3.1\n"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:55
#, c-format
msgid "%d extra options:\n"
msgstr "%d ÌÉÛÎÉÈ ÏÐÃÉÊ:\n"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:47
#, c-format
msgid "Another copy of this process found, pid=%d. Exit."
msgstr "îÁÊÄÅÎÁ ÄÒÕÇÁÑ ËÏÐÉÑ ÜÔÏÇÏ ÐÒÏÃÅÓÓÁ, pid=%d. ÷ÙÈÏÄ."
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:74
msgid "Bad chip version"
msgstr "îÅÐÒÁ×ÉÌØÎÁÑ ×ÅÒÓÉÑ ÞÉÐÁ"
#. just check chip
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:77
msgid "Can't erase chip"
msgstr "îÅ ÍÏÇÕ ÏÞÉÓÔÉÔØ ÞÉÐ"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:82
msgid "Can't fix writing"
msgstr "îÅ ÍÏÇÕ ÚÁ×ÅÒÛÉÔØ ÚÁÐÉÓØ"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/usb.c:152
#, c-format
msgid "Can't open %s"
msgstr "îÅ ÍÏÇÕ ÏÔËÒÙÔØ %s"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:79
msgid "Can't write flash"
msgstr "îÅ ÍÏÇÕ ÚÁÐÉÓÁÔØ ÆÌÅÛ"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:71
msgid "Chip not found"
msgstr "þÉÐ ÎÅ ÎÁÊÄÅÎ"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:75
#, c-format
msgid "Found %s, version %s; flash size %d\n"
msgstr "îÁÊÄÅÎ %s, ×ÅÒÓÉÑ %s; ÒÁÚÍÅÒ ÆÌÅÛÁ %d\n"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/usb.c:66
msgid "No devices found"
msgstr "õÓÔÒÏÊÓÔ×Á ÎÅ ÏÂÎÁÒÕÖÅÎÙ"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:84
msgid "Reset MCU\n"
msgstr "ðÅÒÅÚÁÐÕÓË íë\n"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:78
#, c-format
msgid "Try to write %s\n"
msgstr "ðÙÔÁÀÓØ ÚÁÐÉÓÁÔØ %s\n"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:81
msgid "Verification of flash failed"
msgstr "ðÒÏ×ÅÒËÁ ÐÒÏ×ÁÌÉÌÁÓØ"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/main.c:80
msgid "Verify data\n"
msgstr "ðÒÏ×ÅÒËÁ ÄÁÎÙÈ\n"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/usb.c:135
#, c-format
msgid "Version %s not supported\n"
msgstr "÷ÅÒÓÉÑ %s ÎÅ ÐÏÄÄÅÒÖÉ×ÁÅÔÓÑ\n"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/usb.c:150
msgid "Wrong detect_chip()?"
msgstr "îÅÐÒÁ×ÉÌØÎÙÊ detect_chip()?"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/usb.c:149
msgid "Wrong getver()?"
msgstr "îÅÐÒÁ×ÉÌØÎÙÊ getver()?"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/cmdlnopts.c:51
msgid "don't reset MCU after writing"
msgstr "ÎÅ ÐÅÒÅÚÁÐÕÓËÁÔØ íë ÐÏÓÌÅ ÐÒÏÛÉ×ËÉ"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/cmdlnopts.c:50
msgid "name of binary file to flash"
msgstr "ÎÁÚ×ÁÎÉÅ ÂÉÎÁÒÎÉËÁ ÄÌÑ ÐÒÏÛÉ×ËÉ"
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/cmdlnopts.c:49
msgid "pidfile (default: "
msgstr "pid-ÆÁÊÌ (ÐÏ ÕÍÏÌÞÁÎÉÀ: "
#. common options
#: /Big/Data/00__Electronics/CH551..CH554/ch552tool-master/CH55xtool/cmdlnopts.c:48
msgid "show this help"
msgstr "ÏÔÏÂÒÁÚÉÔØ ÜÔÕ ÓÐÒÁ×ËÕ"

90
CH55xtool/main.c Normal file
View File

@@ -0,0 +1,90 @@
/*
* This file is part of the CH55tool project.
* Copyright 2020 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cmdlnopts.h"
#include "usb.h"
#include <signal.h> // signal
#include <stdio.h> // printf
#include <stdlib.h> // exit, free
#include <string.h> // strdup
#include <sys/types.h> // pid_t
#include <unistd.h> // sleep
#include <usefull_macros.h>
static glob_pars *GP = NULL; // for GP->pidfile need in `signals`
/**
* We REDEFINE the default WEAK function of signal processing
*/
void signals(int sig){
if(sig){
signal(sig, SIG_IGN);
DBG("Get signal %d, quit.\n", sig);
}
if(GP->pidfile) // remove unnesessary PID file
unlink(GP->pidfile);
restore_console();
exit(sig);
}
void iffound_default(pid_t pid){
ERRX(_("Another copy of this process found, pid=%d. Exit."), pid);
}
int main(int argc, char *argv[]){
initial_setup();
char *self = strdup(argv[0]);
GP = parse_args(argc, argv);
if(GP->rest_pars_num){
printf(_("%d extra options:\n"), GP->rest_pars_num);
for(int i = 0; i < GP->rest_pars_num; ++i)
printf("%s\n", GP->rest_pars[i]);
return 1;
}
check4running(self, GP->pidfile);
free(self);
signal(SIGTERM, signals); // kill (-15) - quit
signal(SIGHUP, SIG_IGN); // hup - ignore
signal(SIGINT, signals); // ctrl+C - quit
signal(SIGQUIT, signals); // ctrl+\ - quit
signal(SIGTSTP, SIG_IGN); // ignore ctrl+Z
setup_con();
const ch55descr *descr = detect_chip();
if(!descr){
ERRX(_("Chip not found"));
}
char *ver = getver();
if(!ver) ERRX(_("Bad chip version"));
green(_("Found %s, version %s; flash size %d\n"), descr->devname, ver, descr->flash_size);
if(!GP->binname) signals(0); // just check chip
if(erasechip()) ERRX(_("Can't erase chip"));
green(_("Try to write %s\n"), GP->binname);
if(writeflash(GP->binname)) ERRX(_("Can't write flash"));
green(_("Verify data\n"));
if(verifyflash(GP->binname)) ERRX(_("Verification of flash failed"));
if(endflash()) ERRX(_("Can't fix writing"));
if(!GP->dontrestart){
green(_("Reset MCU\n"));
restart();
}
// clean everything
signals(0);
return 0;
}

195
CH55xtool/usb.c Normal file
View File

@@ -0,0 +1,195 @@
/*
* This file is part of the CH55tool project.
* Copyright 2020 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <libusb.h>
#include <stdio.h>
#include <string.h>
#include <usefull_macros.h>
#include "usb.h"
#define DETECT_CHIP_LEN (6)
#define GETVER_LEN (30)
#define SENDKEYLEN (6)
#define ERASELEN (6)
#define WRITELEN (6)
#define WRITEPACKETLEN (56)
#define WRITEVERIFYSZ (64)
#define FIXLEN (6)
static uint8_t DETECT_CHIP_CMD_V2[] = "\xA1\x12\x00\x52\x11MCU ISP & WCH.CN";
static uint8_t READ_CFG_CMD_V2[] = {0xa7, 0x02, 0x00, 0x1f, 0x00};
static uint8_t SEND_KEY_CMD_V230[48] = {0xa3, 0x30, 0x00};
static uint8_t SEND_KEY_CMD_V240[56] = {0xa3, 0x38, 0x00};
static uint8_t ERASE_CHIP_CMD_V2[] = {0xa4, 0x01, 0x00, 0x08};
static uint8_t WRITE_CMD_V2[64] = {0xa5, 0x00};
static uint8_t VERIFY_CMD_V2[64] = {0xa6, 0x00};
static uint8_t END_FLASH_CMD_V2[] = {0xa2, 0x01, 0x00, 0x00};
static uint8_t RESET_RUN_CMD_V2[] = {0xa2, 0x01, 0x00, 0x01};
static const ch55descr devlist[] = {
{"CH551", 10240, 0x51},
{"CH552", 16384, 0x52},
{"CH553", 10240, 0x53},
{"CH554", 14336, 0x54},
{"CH559", 61440, 0x59},
{NULL, 0, 0}
};
static uint8_t buf[64];
uint8_t *getusbbuf(){
return buf;
}
static libusb_device_handle *devh = NULL;
int usbcmd(const uint8_t *data, int olen, int ilen){
FNAME();
static libusb_context *ctx = NULL;
int inum, onum;
if(!olen) return 0;
if(!devh){
if(libusb_init(&ctx)) ERR("libusb_init()");
devh = libusb_open_device_with_vid_pid(ctx, CH55VID, CH55PID);
if(!devh) ERR(_("No devices found"));
if(libusb_claim_interface(devh, 0)) ERR("libusb_claim_interface()");
}
#ifdef EBUG
green("usbcmd() send:\n");
for(int i = 0; i < olen; ++i){
printf("0x%02X ", data[i]);
}
printf("\n");
#endif
int oret = libusb_bulk_transfer(devh, EPOUT, (unsigned char*)data, olen, &onum, USB_TIMEOUT);
int iret = libusb_bulk_transfer(devh, EPIN, buf, ilen, &inum, USB_TIMEOUT);
if(oret || iret || onum != olen || inum != ilen){
WARN("libusb_bulk_transfer()");
libusb_release_interface(devh, 0);
libusb_close(devh);
libusb_exit(NULL);
exit(3);
}
#ifdef EBUG
green("usbcmd() got:\n");
for(int i = 0; i < inum; ++i){
printf("0x%02X ", buf[i]);
}
printf("\n");
#endif
return inum;
}
static uint8_t chipid = 0;
const ch55descr *detect_chip(){
int got = usbcmd(DETECT_CHIP_CMD_V2, sizeof(DETECT_CHIP_CMD_V2)-1, DETECT_CHIP_LEN);
if(DETECT_CHIP_LEN != got) return NULL;
const ch55descr *ptr = devlist;
while(ptr->devname){
if(buf[4] == ptr->chipid){
chipid = ptr->chipid;
return ptr;
}
++ptr;
}
return NULL;
}
static int old = -1; // ==1 for V2.30, ==0 for V2.31 or V2.40
static uint8_t chk_sum = 0;
/**
* @brief getver - get version string
* @return version or NULL if failed
*/
char *getver(){
static char v[32];
if(GETVER_LEN != usbcmd(READ_CFG_CMD_V2, sizeof(READ_CFG_CMD_V2), GETVER_LEN)) return NULL;
snprintf(v, 32, "V%d.%d%d", buf[19], buf[20], buf[21]);
int s = buf[22] + buf[23] + buf[24] + buf[25];
chk_sum = s&0xff;
DBG("chk_sum=0x%02X", chk_sum);
if(strcmp(v, "V2.30") == 0){ // ver 2.30, sendkey
for(int i = 3; i < 48; ++i) SEND_KEY_CMD_V230[i] = chk_sum;
DBG("Write key");
if(SENDKEYLEN != usbcmd(SEND_KEY_CMD_V230, sizeof(SEND_KEY_CMD_V230), SENDKEYLEN)) return NULL;
if(buf[3]) return NULL;
old = 1;
}else if(strcmp(v, "V2.31") == 0 || strcmp(v, "V2.40") == 0){
if(SENDKEYLEN != usbcmd(SEND_KEY_CMD_V240, sizeof(SEND_KEY_CMD_V240), SENDKEYLEN)) return NULL;
if(buf[3]) return NULL;
old = 0;
}else{
WARNX(_("Version %s not supported\n"), v);
return NULL;
}
return v;
}
int erasechip(){
if(ERASELEN != usbcmd(ERASE_CHIP_CMD_V2, sizeof(ERASE_CHIP_CMD_V2), ERASELEN)) return 1;
if(buf[3]) return 2;
return 0;
}
static int writeverify(char *filename, uint8_t *cmd){
uint8_t packet[WRITEPACKETLEN];
if(old < 0) ERRX(_("Wrong getver()?"));
if(!chipid) ERRX(_("Wrong detect_chip()?"));
FILE *f = fopen(filename, "r");
if(!f) ERR(_("Can't open %s"), filename);
size_t n = 0, curr_addr = 0;
do{
memset(packet, 0, WRITEPACKETLEN);
if(!(n = fread(packet, 1, WRITEPACKETLEN, f))) break;
n = WRITEPACKETLEN;
for(size_t i = 0; i < n; i++){
if(i % 8 == 7) packet[i] = packet[i] ^ ((chk_sum + chipid) & 0xff);
else if(old == 0) packet[i] ^= chk_sum;
}
cmd[1] = (n + 5) & 0xff;
cmd[3] = curr_addr & 0xff;
cmd[4] = (curr_addr >> 8) & 0xff;
cmd[7] = 56;//n & 0xff;
curr_addr += n;
memcpy(&cmd[8], packet, n);
if(WRITELEN != usbcmd(cmd, n+8, WRITELEN)){
fclose(f);
return 1;
}
if(buf[4]) WARNX("buf[4]==0x%02X", buf[4]);
}while(n == WRITEPACKETLEN);
fclose(f);
return 0;
}
int writeflash(char *filename){
return writeverify(filename, WRITE_CMD_V2);
}
int verifyflash(char *filename){
return writeverify(filename, VERIFY_CMD_V2);
}
int endflash(){
if(FIXLEN != usbcmd(END_FLASH_CMD_V2, sizeof(END_FLASH_CMD_V2), FIXLEN) || buf[4]) return 1;
return 0;
}
void restart(){
int onum;
libusb_bulk_transfer(devh, EPOUT, (unsigned char*)RESET_RUN_CMD_V2, sizeof(RESET_RUN_CMD_V2), &onum, USB_TIMEOUT);
}

48
CH55xtool/usb.h Normal file
View File

@@ -0,0 +1,48 @@
/*
* This file is part of the CH55tool project.
* Copyright 2020 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef USB_H__
#define USB_H__
#include <stdint.h>
#include <stdlib.h>
#define CH55VID (0x4348)
#define CH55PID (0x55E0)
#define EPOUT (0x02)
#define EPIN (0x82)
#define USB_TIMEOUT (2000)
typedef struct{
char *devname; // device name
uint16_t flash_size; // flash size
uint8_t chipid; // chip ID
} ch55descr;
uint8_t *getusbbuf();
int usbcmd (const uint8_t *data, int olen, int ilen);
const ch55descr *detect_chip();
char *getver();
int erasechip();
int writeflash(char *filename);
int verifyflash(char *filename);
int endflash();
void restart();
#endif // USB_H__